@progmruansilva/omp-web 1.202608.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 (234) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +181 -0
  3. package/dist/cli.js +1015 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/client/assets/CodeViewer-Da66baHj.js +4 -0
  6. package/dist/client/assets/TerminalPanel-Bj9an79F.js +126 -0
  7. package/dist/client/assets/UnifiedDiffViewer-eK_kynTO.js +34 -0
  8. package/dist/client/assets/index-DytaeWNd.js +3070 -0
  9. package/dist/client/assets/vendor-editor-core-CL2gOCIg.js +12 -0
  10. package/dist/client/assets/vendor-editor-languages-zOM9I4iZ.js +26 -0
  11. package/dist/client/assets/vendor-editor-legacy-B4QLsWF8.js +1 -0
  12. package/dist/client/assets/vendor-terminal-DDGTF8rc.css +1 -0
  13. package/dist/client/assets/vendor-terminal-DjQ08hXu.js +16 -0
  14. package/dist/client/favicon-16x16.png +0 -0
  15. package/dist/client/favicon-180x180.png +0 -0
  16. package/dist/client/favicon-192x192.png +0 -0
  17. package/dist/client/favicon-32x32.png +0 -0
  18. package/dist/client/favicon-512x512.png +0 -0
  19. package/dist/client/favicon.ico +0 -0
  20. package/dist/client/favicon.png +0 -0
  21. package/dist/client/favicon.svg +11 -0
  22. package/dist/client/index.html +67 -0
  23. package/dist/client/manifest.webmanifest +36 -0
  24. package/dist/config.js +272 -0
  25. package/dist/config.js.map +1 -0
  26. package/dist/docker/ompWebDockerCommandPlan.js +211 -0
  27. package/dist/docker/ompWebDockerCommandPlan.js.map +1 -0
  28. package/dist/omp-web-plugins/info/omp-web-plugin.js +51 -0
  29. package/dist/omp-web-plugins/info/package.json +9 -0
  30. package/dist/omp-web-plugins/schedule-prompts/omp-web-plugin.js +43 -0
  31. package/dist/omp-web-plugins/schedule-prompts/package.json +9 -0
  32. package/dist/omp-web-plugins/schedule-prompts/schedulePromptsPanelElement.js +242 -0
  33. package/dist/omp-web-plugins/schedule-prompts/types.js +2 -0
  34. package/dist/omp-web-plugins/updates/omp-web-plugin.js +173 -0
  35. package/dist/omp-web-plugins/updates/package.json +9 -0
  36. package/dist/omp-web-plugins/updates/updatesLogic.js +97 -0
  37. package/dist/ompWebVersionReport.js +217 -0
  38. package/dist/ompWebVersionReport.js.map +1 -0
  39. package/dist/plugin-api/unstable.d.ts +22 -0
  40. package/dist/plugin-api.d.ts +197 -0
  41. package/dist/server/activity/workspaceActivityRoutes.js +4 -0
  42. package/dist/server/activity/workspaceActivityRoutes.js.map +1 -0
  43. package/dist/server/activity/workspaceActivityService.js +98 -0
  44. package/dist/server/activity/workspaceActivityService.js.map +1 -0
  45. package/dist/server/app.js +162 -0
  46. package/dist/server/app.js.map +1 -0
  47. package/dist/server/configRoutes.js +270 -0
  48. package/dist/server/configRoutes.js.map +1 -0
  49. package/dist/server/diagnostics/nodePtySpawnHelper.js +130 -0
  50. package/dist/server/diagnostics/nodePtySpawnHelper.js.map +1 -0
  51. package/dist/server/git/gitEnv.js +15 -0
  52. package/dist/server/git/gitEnv.js.map +1 -0
  53. package/dist/server/git/gitService.js +119 -0
  54. package/dist/server/git/gitService.js.map +1 -0
  55. package/dist/server/gitRoutes.js +23 -0
  56. package/dist/server/gitRoutes.js.map +1 -0
  57. package/dist/server/index.js +7 -0
  58. package/dist/server/index.js.map +1 -0
  59. package/dist/server/machines/machineClient.js +162 -0
  60. package/dist/server/machines/machineClient.js.map +1 -0
  61. package/dist/server/machines/machinePluginProxyRoutes.js +157 -0
  62. package/dist/server/machines/machinePluginProxyRoutes.js.map +1 -0
  63. package/dist/server/machines/machineProxyRoutes.js +127 -0
  64. package/dist/server/machines/machineProxyRoutes.js.map +1 -0
  65. package/dist/server/machines/machineRoutes.js +54 -0
  66. package/dist/server/machines/machineRoutes.js.map +1 -0
  67. package/dist/server/machines/machineService.js +230 -0
  68. package/dist/server/machines/machineService.js.map +1 -0
  69. package/dist/server/machines/machineStore.js +123 -0
  70. package/dist/server/machines/machineStore.js.map +1 -0
  71. package/dist/server/machines/proxyUtils.js +30 -0
  72. package/dist/server/machines/proxyUtils.js.map +1 -0
  73. package/dist/server/ompWebPluginService.js +279 -0
  74. package/dist/server/ompWebPluginService.js.map +1 -0
  75. package/dist/server/ompWebStatus.js +601 -0
  76. package/dist/server/ompWebStatus.js.map +1 -0
  77. package/dist/server/ompWebStatusCache.js +31 -0
  78. package/dist/server/ompWebStatusCache.js.map +1 -0
  79. package/dist/server/piPackageRoutes.js +82 -0
  80. package/dist/server/piPackageRoutes.js.map +1 -0
  81. package/dist/server/piPackageService.js +65 -0
  82. package/dist/server/piPackageService.js.map +1 -0
  83. package/dist/server/projects/directorySuggestions.js +37 -0
  84. package/dist/server/projects/directorySuggestions.js.map +1 -0
  85. package/dist/server/projects/projectService.js +31 -0
  86. package/dist/server/projects/projectService.js.map +1 -0
  87. package/dist/server/push/PushNotificationService.js +137 -0
  88. package/dist/server/push/PushNotificationService.js.map +1 -0
  89. package/dist/server/push/pushRoutes.js +55 -0
  90. package/dist/server/push/pushRoutes.js.map +1 -0
  91. package/dist/server/realtime/sessionEventHub.js +39 -0
  92. package/dist/server/realtime/sessionEventHub.js.map +1 -0
  93. package/dist/server/sessiond/sessionProxyRoutes.js +61 -0
  94. package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -0
  95. package/dist/server/sessiond.js +92 -0
  96. package/dist/server/sessiond.js.map +1 -0
  97. package/dist/server/sessions/attachmentService.js +112 -0
  98. package/dist/server/sessions/attachmentService.js.map +1 -0
  99. package/dist/server/sessions/authProviderOptions.js +52 -0
  100. package/dist/server/sessions/authProviderOptions.js.map +1 -0
  101. package/dist/server/sessions/authRoutes.js +59 -0
  102. package/dist/server/sessions/authRoutes.js.map +1 -0
  103. package/dist/server/sessions/authService.js +105 -0
  104. package/dist/server/sessions/authService.js.map +1 -0
  105. package/dist/server/sessions/builtinCommands.js +29 -0
  106. package/dist/server/sessions/builtinCommands.js.map +1 -0
  107. package/dist/server/sessions/editPreview.js +196 -0
  108. package/dist/server/sessions/editPreview.js.map +1 -0
  109. package/dist/server/sessions/messagePaging.js +41 -0
  110. package/dist/server/sessions/messagePaging.js.map +1 -0
  111. package/dist/server/sessions/oauthLoginFlowService.js +136 -0
  112. package/dist/server/sessions/oauthLoginFlowService.js.map +1 -0
  113. package/dist/server/sessions/piSessionManagerGateway.js +97 -0
  114. package/dist/server/sessions/piSessionManagerGateway.js.map +1 -0
  115. package/dist/server/sessions/piSessionService.js +2401 -0
  116. package/dist/server/sessions/piSessionService.js.map +1 -0
  117. package/dist/server/sessions/schedulePrompt/schedulePromptService.js +46 -0
  118. package/dist/server/sessions/schedulePrompt/schedulePromptService.js.map +1 -0
  119. package/dist/server/sessions/schedulePrompt/scheduler.js +315 -0
  120. package/dist/server/sessions/schedulePrompt/scheduler.js.map +1 -0
  121. package/dist/server/sessions/schedulePrompt/storage.js +118 -0
  122. package/dist/server/sessions/schedulePrompt/storage.js.map +1 -0
  123. package/dist/server/sessions/schedulePrompt/tool.js +252 -0
  124. package/dist/server/sessions/schedulePrompt/tool.js.map +1 -0
  125. package/dist/server/sessions/schedulePrompt/types.js +2 -0
  126. package/dist/server/sessions/schedulePrompt/types.js.map +1 -0
  127. package/dist/server/sessions/sessionArchiveStore.js +254 -0
  128. package/dist/server/sessions/sessionArchiveStore.js.map +1 -0
  129. package/dist/server/sessions/sessionArchiveTree.js +35 -0
  130. package/dist/server/sessions/sessionArchiveTree.js.map +1 -0
  131. package/dist/server/sessions/sessionCleanup.js +157 -0
  132. package/dist/server/sessions/sessionCleanup.js.map +1 -0
  133. package/dist/server/sessions/sessionCommandService.js +260 -0
  134. package/dist/server/sessions/sessionCommandService.js.map +1 -0
  135. package/dist/server/sessions/sessionNameGenerator.js +61 -0
  136. package/dist/server/sessions/sessionNameGenerator.js.map +1 -0
  137. package/dist/server/sessions/sessionRoutes.js +344 -0
  138. package/dist/server/sessions/sessionRoutes.js.map +1 -0
  139. package/dist/server/sessions/sessionRuntimeStore.js +2 -0
  140. package/dist/server/sessions/sessionRuntimeStore.js.map +1 -0
  141. package/dist/server/sessions/spawnSessionTool.js +41 -0
  142. package/dist/server/sessions/spawnSessionTool.js.map +1 -0
  143. package/dist/server/sessions/spawnSubsessionTool.js +203 -0
  144. package/dist/server/sessions/spawnSubsessionTool.js.map +1 -0
  145. package/dist/server/sessions/spawnTargetResolver.js +36 -0
  146. package/dist/server/sessions/spawnTargetResolver.js.map +1 -0
  147. package/dist/server/sessions/subsessionTranscript.js +233 -0
  148. package/dist/server/sessions/subsessionTranscript.js.map +1 -0
  149. package/dist/server/storage/projectStore.js +83 -0
  150. package/dist/server/storage/projectStore.js.map +1 -0
  151. package/dist/server/terminalProxyRoutes.js +140 -0
  152. package/dist/server/terminalProxyRoutes.js.map +1 -0
  153. package/dist/server/terminals/terminalRoutes.js +153 -0
  154. package/dist/server/terminals/terminalRoutes.js.map +1 -0
  155. package/dist/server/terminals/terminalService.js +320 -0
  156. package/dist/server/terminals/terminalService.js.map +1 -0
  157. package/dist/server/terminals/terminalSize.js +17 -0
  158. package/dist/server/terminals/terminalSize.js.map +1 -0
  159. package/dist/server/types.js +2 -0
  160. package/dist/server/types.js.map +1 -0
  161. package/dist/server/utils.js +8 -0
  162. package/dist/server/utils.js.map +1 -0
  163. package/dist/server/webSocketBridge.js +32 -0
  164. package/dist/server/webSocketBridge.js.map +1 -0
  165. package/dist/server/workingDirectory.js +44 -0
  166. package/dist/server/workingDirectory.js.map +1 -0
  167. package/dist/server/workspaceExplorerRoutes.js +109 -0
  168. package/dist/server/workspaceExplorerRoutes.js.map +1 -0
  169. package/dist/server/workspaces/effectivePathAccess.js +27 -0
  170. package/dist/server/workspaces/effectivePathAccess.js.map +1 -0
  171. package/dist/server/workspaces/fileContentService.js +181 -0
  172. package/dist/server/workspaces/fileContentService.js.map +1 -0
  173. package/dist/server/workspaces/fileSuggestions.js +512 -0
  174. package/dist/server/workspaces/fileSuggestions.js.map +1 -0
  175. package/dist/server/workspaces/fileTreeService.js +27 -0
  176. package/dist/server/workspaces/fileTreeService.js.map +1 -0
  177. package/dist/server/workspaces/gitWorktreeDiscovery.js +34 -0
  178. package/dist/server/workspaces/gitWorktreeDiscovery.js.map +1 -0
  179. package/dist/server/workspaces/imagePreviewService.js +40 -0
  180. package/dist/server/workspaces/imagePreviewService.js.map +1 -0
  181. package/dist/server/workspaces/pathAccessPolicy.js +87 -0
  182. package/dist/server/workspaces/pathAccessPolicy.js.map +1 -0
  183. package/dist/server/workspaces/pathSafety.js +54 -0
  184. package/dist/server/workspaces/pathSafety.js.map +1 -0
  185. package/dist/server/workspaces/projectOmpWebConfig.js +56 -0
  186. package/dist/server/workspaces/projectOmpWebConfig.js.map +1 -0
  187. package/dist/server/workspaces/workspaceContext.js +8 -0
  188. package/dist/server/workspaces/workspaceContext.js.map +1 -0
  189. package/dist/server/workspaces/workspaceDeletionRoutes.js +111 -0
  190. package/dist/server/workspaces/workspaceDeletionRoutes.js.map +1 -0
  191. package/dist/server/workspaces/workspaceService.js +39 -0
  192. package/dist/server/workspaces/workspaceService.js.map +1 -0
  193. package/dist/sessiond/config.js +9 -0
  194. package/dist/sessiond/config.js.map +1 -0
  195. package/dist/sessiond/sessionDaemonClient.js +65 -0
  196. package/dist/sessiond/sessionDaemonClient.js.map +1 -0
  197. package/dist/shared/activity.js +26 -0
  198. package/dist/shared/activity.js.map +1 -0
  199. package/dist/shared/apiTypes.d.ts +688 -0
  200. package/dist/shared/apiTypes.js +11 -0
  201. package/dist/shared/apiTypes.js.map +1 -0
  202. package/dist/shared/capabilities.js +52 -0
  203. package/dist/shared/capabilities.js.map +1 -0
  204. package/dist/shared/federatedRoutes.js +79 -0
  205. package/dist/shared/federatedRoutes.js.map +1 -0
  206. package/dist/shared/machinePluginIds.js +41 -0
  207. package/dist/shared/machinePluginIds.js.map +1 -0
  208. package/dist/shared/ompWebStatusParsing.js +100 -0
  209. package/dist/shared/ompWebStatusParsing.js.map +1 -0
  210. package/dist/shared/pluginIds.js +5 -0
  211. package/dist/shared/pluginIds.js.map +1 -0
  212. package/dist/shared/promptAttachments.js +90 -0
  213. package/dist/shared/promptAttachments.js.map +1 -0
  214. package/dist/shared/thinkingLevels.d.ts +19 -0
  215. package/dist/shared/thinkingLevels.js +24 -0
  216. package/dist/shared/thinkingLevels.js.map +1 -0
  217. package/dist/shared/utils.js +4 -0
  218. package/dist/shared/utils.js.map +1 -0
  219. package/dist/shared/workspaceDeletion.js +12 -0
  220. package/dist/shared/workspaceDeletion.js.map +1 -0
  221. package/dist/shared/workspaceFiles.js +3 -0
  222. package/dist/shared/workspaceFiles.js.map +1 -0
  223. package/docs/assets/favicon.svg +11 -0
  224. package/docs/assets/omp-web-banner.png +0 -0
  225. package/docs/assets/omp-web-desktop.png +0 -0
  226. package/docs/assets/omp-web-mobile.png +0 -0
  227. package/docs/assets/omp-web-tablet.png +0 -0
  228. package/docs/config.md +208 -0
  229. package/docs/plugins.md +916 -0
  230. package/extensions/omp-web.ts +133 -0
  231. package/install.sh +5 -0
  232. package/package.json +141 -0
  233. package/plugin-api/unstable.d.ts +1 -0
  234. package/plugin-api.d.ts +1 -0
@@ -0,0 +1,3070 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-Da66baHj.js","assets/vendor-editor-core-CL2gOCIg.js","assets/vendor-editor-languages-zOM9I4iZ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/UnifiedDiffViewer-eK_kynTO.js","assets/TerminalPanel-Bj9an79F.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as fo,v as dt,J as Ts,R as yc,S as Sc,G as xc,U as kc,V as $c,W as Pc,A as Cc,X as Rc,Y as Mc,Z as go,w as mo,_ as Ic}from"./vendor-editor-core-CL2gOCIg.js";import{m as Tc,d as Ac,i as Ec}from"./vendor-editor-languages-zOM9I4iZ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const Di=globalThis,$r=Di.ShadowRoot&&(Di.ShadyCSS===void 0||Di.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Pr=Symbol(),vo=new WeakMap;let Pa=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==Pr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o;const i=this.t;if($r&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=vo.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&vo.set(i,t))}return t}toString(){return this.cssText}};const Dc=e=>new Pa(typeof e=="string"?e:e+"",void 0,Pr),D=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+e[o+1],e[0]);return new Pa(i,e,Pr)},Wc=(e,t)=>{if($r)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=Di.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},bo=$r?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Dc(i)})(e):e;const{is:Lc,defineProperty:Oc,getOwnPropertyDescriptor:Fc,getOwnPropertyNames:_c,getOwnPropertySymbols:jc,getPrototypeOf:Uc}=Object,us=globalThis,wo=us.trustedTypes,Nc=wo?wo.emptyScript:"",Bc=us.reactiveElementPolyfillSupport,si=(e,t)=>e,Bi={toAttribute(e,t){switch(t){case Boolean:e=e?Nc:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=e!==null;break;case Number:i=e===null?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},Cr=(e,t)=>!Lc(e,t),yo={attribute:!0,type:String,converter:Bi,reflect:!1,useDefault:!1,hasChanged:Cr};Symbol.metadata??=Symbol("metadata"),us.litPropertyMetadata??=new WeakMap;let It=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=yo){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),r=this.getPropertyDescriptor(t,s,i);r!==void 0&&Oc(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=Fc(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:r,set(n){const a=r?.call(this);o?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??yo}static _$Ei(){if(this.hasOwnProperty(si("elementProperties")))return;const t=Uc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(si("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(si("properties"))){const i=this.properties,s=[..._c(i),...jc(i)];for(const r of s)this.createProperty(r,i[r])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,r]of i)this.elementProperties.set(s,r)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const r=this._$Eu(i,s);r!==void 0&&this._$Eh.set(r,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const r of s)i.unshift(bo(r))}else t!==void 0&&i.push(bo(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Wc(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),r=this.constructor._$Eu(t,s);if(r!==void 0&&s.reflect===!0){const o=(s.converter?.toAttribute!==void 0?s.converter:Bi).toAttribute(i,s.type);this._$Em=t,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(t,i){const s=this.constructor,r=s._$Eh.get(t);if(r!==void 0&&this._$Em!==r){const o=s.getPropertyOptions(r),n=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:Bi;this._$Em=r;const a=n.fromAttribute(i,o.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(t,i,s,r=!1,o){if(t!==void 0){const n=this.constructor;if(r===!1&&(o=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Cr)(o,i)||s.useDefault&&s.reflect&&o===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:r,wrapped:o},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),o!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),r===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};It.elementStyles=[],It.shadowRootOptions={mode:"open"},It[si("elementProperties")]=new Map,It[si("finalized")]=new Map,Bc?.({ReactiveElement:It}),(us.reactiveElementVersions??=[]).push("2.1.2");const Rr=globalThis,So=e=>e,zi=Rr.trustedTypes,xo=zi?zi.createPolicy("lit-html",{createHTML:e=>e}):void 0,Ca="$lit$",nt=`lit$${Math.random().toFixed(9).slice(2)}$`,Ra="?"+nt,zc=`<${Ra}>`,wt=document,ni=()=>wt.createComment(""),ai=e=>e===null||typeof e!="object"&&typeof e!="function",Mr=Array.isArray,qc=e=>Mr(e)||typeof e?.[Symbol.iterator]=="function",As=`[
3
+ \f\r]`,Nt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ko=/-->/g,$o=/>/g,pt=RegExp(`>|${As}(?:([^\\s"'>=/]+)(${As}*=${As}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Po=/'/g,Co=/"/g,Ma=/^(?:script|style|textarea|title)$/i,Ia=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=Ia(1),ye=Ia(2),at=Symbol.for("lit-noChange"),N=Symbol.for("lit-nothing"),Ro=new WeakMap,mt=wt.createTreeWalker(wt,129);function Ta(e,t){if(!Mr(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return xo!==void 0?xo.createHTML(t):t}const Hc=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=Nt;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,f=0;for(;f<c.length&&(n.lastIndex=f,u=n.exec(c),u!==null);)f=n.lastIndex,n===Nt?u[1]==="!--"?n=ko:u[1]!==void 0?n=$o:u[2]!==void 0?(Ma.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=pt):u[3]!==void 0&&(n=pt):n===pt?u[0]===">"?(n=r??Nt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?pt:u[3]==='"'?Co:Po):n===Co||n===Po?n=pt:n===ko||n===$o?n=Nt:(n=pt,r=void 0);const S=n===pt&&e[a+1].startsWith("/>")?" ":"";o+=n===Nt?c+zc:h>=0?(s.push(p),c.slice(0,h)+Ca+c.slice(h)+nt+S):c+nt+(h===-2?a:S)}return[Ta(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class li{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,c=this.parts,[p,u]=Hc(t,i);if(this.el=li.createElement(p,s),mt.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=mt.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(Ca)){const f=u[n++],S=r.getAttribute(h).split(nt),$=/([.?@])?(.*)/.exec(f);c.push({type:1,index:o,name:$[2],strings:S,ctor:$[1]==="."?Vc:$[1]==="?"?Gc:$[1]==="@"?Qc:fs}),r.removeAttribute(h)}else h.startsWith(nt)&&(c.push({type:6,index:o}),r.removeAttribute(h));if(Ma.test(r.tagName)){const h=r.textContent.split(nt),f=h.length-1;if(f>0){r.textContent=zi?zi.emptyScript:"";for(let S=0;S<f;S++)r.append(h[S],ni()),mt.nextNode(),c.push({type:2,index:++o});r.append(h[f],ni())}}}else if(r.nodeType===8)if(r.data===Ra)c.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(nt,h+1))!==-1;)c.push({type:7,index:o}),h+=nt.length-1}o++}}static createElement(t,i){const s=wt.createElement("template");return s.innerHTML=t,s}}function Dt(e,t,i=e,s){if(t===at)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=ai(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(e),r._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=r:i._$Cl=r),r!==void 0&&(t=Dt(e,r._$AS(e,t.values),r,s)),t}class Kc{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,r=(t?.creationScope??wt).importNode(i,!0);mt.currentNode=r;let o=mt.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new Ft(o,o.nextSibling,this,t):c.type===1?p=new c.ctor(o,c.name,c.strings,this,t):c.type===6&&(p=new Jc(o,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(o=mt.nextNode(),n++)}return mt.currentNode=wt,r}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class Ft{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=N,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=Dt(this,t,i),ai(t)?t===N||t==null||t===""?(this._$AH!==N&&this._$AR(),this._$AH=N):t!==this._$AH&&t!==at&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):qc(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==N&&ai(this._$AH)?this._$AA.nextSibling.data=t:this.T(wt.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=li.createElement(Ta(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Kc(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=Ro.get(t.strings);return i===void 0&&Ro.set(t.strings,i=new li(t)),i}k(t){Mr(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,r=0;for(const o of t)r===i.length?i.push(s=new Ft(this.O(ni()),this.O(ni()),this,this.options)):s=i[r],s._$AI(o),r++;r<i.length&&(this._$AR(s&&s._$AB.nextSibling,r),i.length=r)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=So(t).nextSibling;So(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let fs=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=N,this._$AN=void 0,this.element=t,this.name=i,this._$AM=r,this.options=o,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=N}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=Dt(this,t,i,0),n=!ai(t)||t!==this._$AH&&t!==at,n&&(this._$AH=t);else{const a=t;let c,p;for(t=o[0],c=0;c<o.length-1;c++)p=Dt(this,a[s+c],i,c),p===at&&(p=this._$AH[c]),n||=!ai(p)||p!==this._$AH[c],p===N?t=N:t!==N&&(t+=(p??"")+o[c+1]),this._$AH[c]=p}n&&!r&&this.j(t)}j(t){t===N?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}};class Vc extends fs{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===N?void 0:t}}let Gc=class extends fs{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==N)}},Qc=class extends fs{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=Dt(this,t,i,0)??N)===at)return;const s=this._$AH,r=t===N&&s!==N||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==N&&(s===N||r);r&&this.element.removeEventListener(this.name,this,s),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Jc=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){Dt(this,t)}};const Zc={I:Ft},Xc=Rr.litHtmlPolyfillSupport;Xc?.(li,Ft),(Rr.litHtmlVersions??=[]).push("3.3.3");const Yc=(e,t,i)=>{const s=i?.renderBefore??t;let r=s._$litPart$;if(r===void 0){const o=i?.renderBefore??null;s._$litPart$=r=new Ft(t.insertBefore(ni(),o),o,void 0,i??{})}return r._$AI(e),r};const Ir=globalThis;let I=class extends It{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Yc(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return at}};I._$litElement$=!0,I.finalized=!0,Ir.litElementHydrateSupport?.({LitElement:I});const ed=Ir.litElementPolyfillSupport;ed?.({LitElement:I});(Ir.litElementVersions??=[]).push("4.2.2");function B(e){return typeof e=="object"&&e!==null}function q(e){return e instanceof Error?e.message:String(e)}const E=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const td={attribute:!0,type:String,converter:Bi,reflect:!1,hasChanged:Cr},id=(e=td,t,i)=>{const{kind:s,metadata:r}=i;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?id(e,t,i):((s,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,s),n?Object.getOwnPropertyDescriptor(r,o):void 0})(e,t,i)}function v(e){return d({...e,state:!0,attribute:!1})}const sd=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function K(e,t){return(i,s,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return sd(i,s,{get(){return o(this)}})}}async function y(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&!s.has("content-type")&&s.set("content-type","application/json");const r=await fetch(e,{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(rd(n)??r.statusText)}const o=await r.json();return t(o)}function rd(e){if(B(e))return typeof e.error=="string"?e.error:void 0}const Ce={sessionsDeleteArchived:"sessions.deleteArchived",sessionsBulkMutations:"sessions.bulkMutations",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions",piPackagesManage:"piPackages.manage",selectedMachineSettings:"settings.selectedMachine"},od=Object.values(Ce),nd=new Set(od);function ad(e){return typeof e=="string"&&nd.has(e)}function Fe(e,t){return e?.capabilities?.includes(t)===!0}function ld(e){if(!(!Array.isArray(e)||!e.every(t=>typeof t=="string")))return e.filter(ad)}function b(e){if(!B(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function P(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function J(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function W(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function cd(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function Wt(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function dd(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=b(e);return{messages:cd(t.messages),start:J(t,"start"),total:J(t,"total")}}function pd(e){const t=b(e);return j(Aa)(t.machines)}function Aa(e){const t=b(e),i=fd(t,"kind"),s=P(t,"baseUrl"),r=Ea(t,"status"),o=P(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...r===void 0?{}:{status:r},...o===void 0?{}:{statusMessage:o}}}function hd(e){const t=b(e),i=Ea(t,"status"),s=P(t,"error");return{machineId:m(t,"machineId"),ok:W(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:qi(t.web)},...t.sessiond===void 0?{}:{sessiond:qi(t.sessiond)},...s===void 0?{}:{error:s}}}function ud(e){const t=b(e),i=P(t,"error");return{machineId:m(t,"machineId"),ok:W(t,"ok"),checkedAt:m(t,"checkedAt"),...w("packageName",P(t,"packageName")),...w("generatedAt",P(t,"generatedAt")),...t.components===void 0?{}:{components:Ua(t.components)},...t.capabilities===void 0?{}:{capabilities:Tr(t.capabilities)},...i===void 0?{}:{error:i}}}function fd(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function Ea(e,t){const i=P(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function Mo(e){const t=b(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function gd(e){const t=b(e),i=P(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:W(t,"isMain"),isGitRepo:W(t,"isGitRepo"),isGitWorktree:W(t,"isGitWorktree"),...w("effectiveConfig",md(t.effectiveConfig))}}function md(e){if(e!==void 0){if(!B(e)||Array.isArray(e))throw new Error("Invalid workspace effectiveConfig field");return{...w("uploads",Fa(e.uploads))}}}function or(e){const t=b(e),i=P(t,"name"),s=gs(t.persisted,"persisted"),r=P(t,"parentSessionPath"),o=P(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...s===void 0?{}:{persisted:s},...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:J(t,"messageCount"),firstMessage:m(t,"firstMessage"),...r===void 0?{}:{parentSessionPath:r},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function Bt(e){const t=b(e);return{sessionId:m(t,"sessionId"),...w("persisted",gs(t.persisted,"persisted")),isStreaming:W(t,"isStreaming"),isCompacting:W(t,"isCompacting"),isBashRunning:W(t,"isBashRunning"),pendingMessageCount:J(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(kd)(t.queuedMessages),...w("messageCount",Se(t,"messageCount")),tokens:$d(t.tokens),cost:J(t,"cost"),...Pd(t.model),..._d(t.contextUsage),...w("thinkingLevel",P(t,"thinkingLevel"))}}function Da(e){const t=b(e),i=t.skippedBusySessionIds===void 0?void 0:Wt(t.skippedBusySessionIds,"skippedBusySessionIds");return{generatedAt:m(t,"generatedAt"),thresholds:yd(t.thresholds),projects:j(Sd)(t.projects),totals:xd(t.totals),...i===void 0?{}:{skippedBusySessionIds:i}}}function vd(e){const t=b(e);return{...Da(t),archivedSessionIds:Wt(t.archivedSessionIds,"archivedSessionIds"),deletedSessionIds:Wt(t.deletedSessionIds,"deletedSessionIds")}}function bd(e){const t=b(e);if(t.archived!==!0)throw new Error("Expected bulk archived response");return{archived:!0,archivedSessionIds:Wt(t.archivedSessionIds,"archivedSessionIds"),failures:j(Wa)(t.failures),generatedAt:m(t,"generatedAt")}}function wd(e){const t=b(e);if(t.deleted!==!0)throw new Error("Expected bulk deleted response");return{deleted:!0,deletedSessionIds:Wt(t.deletedSessionIds,"deletedSessionIds"),failures:j(Wa)(t.failures),generatedAt:m(t,"generatedAt")}}function Wa(e){const t=b(e);return{sessionId:m(t,"sessionId"),error:m(t,"error")}}function yd(e){const t=b(e);return{...w("archiveIdleDays",Se(t,"archiveIdleDays")),...w("deleteArchivedDays",Se(t,"deleteArchivedDays"))}}function Sd(e){const t=b(e);return{cwd:m(t,"cwd"),archiveCount:J(t,"archiveCount"),deleteCount:J(t,"deleteCount")}}function xd(e){const t=b(e);return{archiveCount:J(t,"archiveCount"),deleteCount:J(t,"deleteCount")}}function kd(e){const t=b(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text")}}function $d(e){const t=b(e);return{input:J(t,"input"),output:J(t,"output"),cacheRead:J(t,"cacheRead"),cacheWrite:J(t,"cacheWrite"),total:J(t,"total")}}function La(e){const t=b(e);return{...w("provider",P(t,"provider")),...w("id",P(t,"id")),...w("name",P(t,"name")),...w("contextWindow",Se(t,"contextWindow")),...w("reasoning",t.reasoning)}}function Pd(e){return e===void 0?{}:{model:La(e)}}function Cd(e){const t=b(e);return{models:j(La)(t.models)}}function Rd(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function Md(e){const t=b(e);return{levels:j(Rd)(t.levels)}}function Id(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Td(e){if(e!=="stored"&&e!=="runtime"&&e!=="environment"&&e!=="fallback"&&e!=="models_json_key"&&e!=="models_json_command")throw new Error("Invalid auth status source");return e}function Ad(e){const t=b(e),i=t.source===void 0?void 0:Td(t.source);return{configured:W(t,"configured"),...w("source",i),...w("label",P(t,"label"))}}function Ed(e){const t=b(e);return{id:m(t,"id"),name:m(t,"name"),authType:Id(t.authType),status:Ad(t.status)}}function Dd(e){const t=b(e);return{providers:j(Ed)(t.providers)}}function yi(e){const t=b(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Wd(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...w("error",P(t,"error")),...w("auth",Ld(t.auth)),...w("prompt",Od(t.prompt)),...w("select",Fd(t.select))}}function Wd(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Ld(e){if(e===void 0)return;const t=b(e);return{url:m(t,"url"),...w("instructions",P(t,"instructions"))}}function Od(e){if(e===void 0)return;const t=b(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...w("placeholder",P(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Fd(e){if(e===void 0)return;const t=b(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:j(Ba)(t.options)}}function _d(e){if(e===void 0)return{};const t=b(e);return{contextUsage:{tokens:Oo(t,"tokens"),contextWindow:J(t,"contextWindow"),percent:Oo(t,"percent")}}}function jd(e){const t=b(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...w("description",P(t,"description"))}}function nr(e){const t=b(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Ud(e){const t=b(e);return{path:m(t,"path"),entries:j(Nd)(t.entries),scannedAt:m(t,"scannedAt"),truncated:W(t,"truncated")}}function Nd(e){const t=b(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...w("size",Se(t,"size")),...w("modifiedAt",P(t,"modifiedAt"))}}function Bd(e){const t=b(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...w("language",P(t,"language")),...w("mediaType",Hd(t.mediaType)),...w("mimeType",P(t,"mimeType")),encoding:i,size:J(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:W(t,"truncated"),binary:W(t,"binary")}}function Oa(e){const t=b(e);return{path:m(t,"path"),size:J(t,"size"),modifiedAt:m(t,"modifiedAt"),created:W(t,"created")}}function zd(e){const t=b(e);return{path:m(t,"path"),existed:W(t,"existed")}}function qd(e){const t=b(e);return{fromPath:m(t,"fromPath"),toPath:m(t,"toPath"),size:J(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Hd(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function Kd(e){const t=b(e);return{isGitRepo:W(t,"isGitRepo"),hash:m(t,"hash"),...w("branch",P(t,"branch")),...w("upstream",P(t,"upstream")),...w("ahead",Se(t,"ahead")),...w("behind",Se(t,"behind")),files:j(Vd)(t.files)}}function Vd(e){const t=b(e);return{path:m(t,"path"),...w("oldPath",P(t,"oldPath")),index:Io(t.index),workingTree:Io(t.workingTree)}}function Io(e){switch(e){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return e;default:throw new Error("Invalid git file state")}}function Gd(e){const t=b(e);return{...w("path",P(t,"path")),staged:W(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:W(t,"truncated")}}function Es(e){const t=b(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:W(t,"exited"),...w("exitCode",Se(t,"exitCode")),...w("commandRunId",P(t,"commandRunId"))}}function ri(e){const t=b(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:Qd(t.status),...w("exitCode",Se(t,"exitCode")),createdAt:m(t,"createdAt"),...w("startedAt",P(t,"startedAt")),...w("completedAt",P(t,"completedAt")),metadata:Jd(t.metadata,"metadata")}}function Qd(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Jd(e,t){const i=b(e);return Object.fromEntries(Object.entries(i).map(([s,r])=>{if(typeof r!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,r]}))}function Zd(e){const t=b(e);return{cwd:m(t,"cwd"),hasSessionActivity:W(t,"hasSessionActivity"),hasTerminalActivity:W(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Xd(e){const t=b(e);return{workspaces:j(Zd)(t.workspaces),generatedAt:m(t,"generatedAt")}}function To(e){const t=b(e);return{path:m(t,"path"),exists:W(t,"exists"),config:Ao(t.config),effectiveConfig:Ao(t.effectiveConfig),envOverrides:np(t.envOverrides)}}function Ao(e){const t=b(e);return{...w("host",P(t,"host")),...w("port",Se(t,"port")),...w("allowedHosts",Yd(t.allowedHosts)),...w("shortcuts",rp(t.shortcuts)),...w("plugins",op(t.plugins)),...w("pathAccess",ep(t.pathAccess)),...w("uploads",Fa(t.uploads)),...w("maxUploadBytes",Se(t,"maxUploadBytes")),...w("spawnSessions",Lo(t,"spawnSessions")),...w("subsessions",Lo(t,"subsessions"))}}function Yd(e){if(e!==void 0){if(e===!0)return!0;if(ip(e))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function ep(e){if(e===void 0)return;if(!B(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...w("allowedPaths",tp(t,"pathAccess.allowedPaths"))}}function tp(e,t){if(e!==void 0){if(sp(e))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function Fa(e){if(e!==void 0){if(!B(e)||Array.isArray(e))throw new Error("Invalid PI WEB uploads field");return{...w("defaultFolder",P(e,"defaultFolder"))}}}function ip(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function sp(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t!=="")}function rp(e){if(e!==void 0){if(!B(e)||Array.isArray(e))throw new Error("Invalid PI WEB shortcuts field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(i!==null&&(typeof i!="string"||i===""))throw new Error("Invalid PI WEB shortcut field");return[t,i]}))}}function op(e){if(e!==void 0){if(!B(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!B(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const r=i.settings;if(r!==void 0&&(!B(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function np(e){const t=b(e);return{host:W(t,"host"),port:W(t,"port"),allowedHosts:W(t,"allowedHosts"),spawnSessions:W(t,"spawnSessions"),subsessions:W(t,"subsessions")}}function ap(e){const t=b(e);return{packages:j(_a)(t.packages)}}function Ds(e){const t=b(e),i=P(t,"source"),s=t.scope===void 0?void 0:ja(t.scope),r=gs(t.removed,"removed");return{action:lp(t.action),...w("source",i),...w("scope",s),...w("removed",r),packages:j(_a)(t.packages)}}function _a(e){const t=b(e);return{source:m(t,"source"),scope:ja(t.scope),filtered:W(t,"filtered"),...w("installedPath",P(t,"installedPath"))}}function ja(e){if(e!=="user"&&e!=="project")throw new Error("Invalid Pi package scope");return e}function lp(e){if(e!=="install"&&e!=="remove"&&e!=="update")throw new Error("Invalid Pi package mutation action");return e}function cp(e){const t=b(e);return{plugins:j(dp)(t.plugins)}}function dp(e){const t=b(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:pp(t.scope),machineSpecific:gs(t.machineSpecific,"machineSpecific")??!1,enabled:W(t,"enabled")}}function pp(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function gs(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function hp(e){const t=b(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:fp(t.components),release:mp(t.release),commands:vp(t.commands),messages:j(bp)(t.messages)}}function up(e){const t=b(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Ua(t.components),capabilities:Tr(t.capabilities)}}function fp(e){const t=b(e);return{web:qi(t.web),sessiond:qi(t.sessiond)}}function Ua(e){const t=b(e);return{web:Eo(t.web),sessiond:Eo(t.sessiond)}}function Eo(e){const t=b(e);return{component:Na(t.component),label:m(t,"label"),...w("runtimeVersion",P(t,"runtimeVersion")),available:W(t,"available"),capabilities:Tr(t.capabilities),...w("error",P(t,"error"))}}function qi(e){const t=b(e);return{component:Na(t.component),label:m(t,"label"),...w("runtimeVersion",P(t,"runtimeVersion")),...w("installedVersion",P(t,"installedVersion")),stale:W(t,"stale"),available:W(t,"available"),...w("installation",gp(t.installation)),...w("error",P(t,"error"))}}function gp(e){if(e===void 0)return;const t=b(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="docker"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");const r=t.dockerMode;if(r!==void 0&&r!=="runtime"&&r!=="dev")throw new Error("Invalid PI WEB Docker mode");return{kind:i,...w("path",P(t,"path")),...w("source",P(t,"source")),...s===void 0?{}:{scope:s},...w("npmRoot",P(t,"npmRoot")),...r===void 0?{}:{dockerMode:r}}}function mp(e){const t=b(e);return{packageName:m(t,"packageName"),...w("latestVersion",P(t,"latestVersion")),updateAvailable:W(t,"updateAvailable"),...w("checkedAt",P(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...w("error",P(t,"error"))}}function vp(e){const t=b(e);return{...w("update",P(t,"update")),...w("restart",P(t,"restart")),...w("restartWeb",P(t,"restartWeb")),...w("restartSessiond",P(t,"restartSessiond")),...w("status",P(t,"status"))}}function bp(e){const t=b(e);return{id:m(t,"id"),severity:wp(t.severity),title:m(t,"title"),body:m(t,"body"),...w("command",P(t,"command"))}}function Na(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Tr(e){const t=ld(e);if(t===void 0)throw new Error("Invalid PI WEB capabilities");return t}function wp(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Do(e){const t=b(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:j(Ba)(t.options)};if(i==="done")return{type:i,...w("message",P(t,"message")),...yp(t.session),...w("promptDraft",P(t,"promptDraft"))};throw new Error("Invalid command result type")}function Ba(e){const t=b(e);return{value:m(t,"value"),label:m(t,"label"),...w("description",P(t,"description"))}}function yp(e){return e===void 0?{}:{session:or(e)}}function Si(e){if(b(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Sp(e){const t=b(e);return j(xp)(t.attachments)}function xp(e){const t=b(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:J(t,"size")}}function ar(e){if(b(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function kp(e){if(b(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function $p(e){if(b(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Wo(e){const t=b(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:Wt(t.sessionIds,"sessionIds"),s=Se(t,"archivedCount"),r=Se(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function Pp(e){if(b(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function Cp(e){if(b(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function Rp(e){if(b(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Mp(e){if(b(e).reloaded!==!0)throw new Error("Expected reloaded response");return{reloaded:!0}}function Lo(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function Se(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function Oo(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function w(e,t){return t===void 0?{}:{[e]:t}}function Ip(e){return typeof e=="string"?e:e.id}function Tp(e){return typeof e=="string"?void 0:e.cwd}function Ap(e,t,i,s){const r=new URLSearchParams;s?.path!==void 0&&r.set("path",s.path),s?.staged===!0&&r.set("staged","true");const o=r.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${o?`?${o}`:""}`}function Ep(e,t,i="local"){const s=new URLSearchParams,r=Tp(e);r!==void 0&&r!==""&&s.set("cwd",r),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const o=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(Ip(e))}/messages${o===""?"":`?${o}`}`}function Dp(e,t,i,s){const r=new URLSearchParams({path:i});return s?.createDirs===!1&&r.set("createDirs","false"),s?.overwrite===!1&&r.set("overwrite","false"),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`}function Wp(e,t,i,s){const r=new URLSearchParams;return r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`}const C=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function za(e){return typeof e=="string"?e:e.id}function Ar(e){return typeof e=="string"?void 0:e.cwd}function qa(e,t="local"){return`${C(t)}/sessions/${encodeURIComponent(za(e))}`}function ie(e,t,i="local"){return`${qa(e,i)}/${t}`}function xi(e,t,i="local"){return`${ie(e,t,i)}${Ha(e)}`}function Lp(e,t="local"){return`${qa(e,t)}${Ha(e)}`}function Ha(e){const t=Ar(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function oe(e,t={}){const i=Ar(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}function Fo(e){return JSON.stringify({sessions:e.map(Op)})}function Op(e){const t=za(e),i=Ar(e);return i===void 0||i===""?{id:t}:{id:t,cwd:i}}const Ka={ompWebStatus:(e="local")=>y(e==="local"?"/api/omp-web/status":`${C(e)}/omp-web/status`,hp),ompWebRuntime:()=>y("/api/omp-web/runtime",up)},Fp={machines:()=>y("/api/machines",pd),addMachine:e=>y("/api/machines",Aa,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>y(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>y(`/api/machines/${encodeURIComponent(e)}/health`,hd),runtime:e=>y(`/api/machines/${encodeURIComponent(e)}/runtime`,ud)};function _o(e){return e===void 0?"/api/config":`${C(e)}/config`}function _p(e){return e===void 0?"/api/plugins":`${C(e)}/plugins`}const ze={config:e=>y(_o(e),To),saveConfig:(e,t)=>y(_o(t),To,{method:"PUT",body:JSON.stringify({config:e})})},Zt={plugins:e=>y(_p(e),cp)};function ki(e="",t){const i=t===void 0?"/api/pi-packages":`${C(t)}/pi-packages`;return e===""?i:`${i}/${e}`}const Xt={packages:e=>y(ki("",e),ap),install:(e,t)=>{const i={source:e};return y(ki("install",t),Ds,{method:"POST",body:JSON.stringify(i)})},remove:(e,t,i)=>{const s=t===void 0?{source:e}:{source:e,scope:t};return y(ki("remove",i),Ds,{method:"POST",body:JSON.stringify(s)})},update:(e,t)=>{const i=e===void 0?void 0:{source:e};return y(ki("update",t),Ds,{method:"POST",...i===void 0?{}:{body:JSON.stringify(i)}})}},Va={workspaceActivity:(e="local")=>y(`${C(e)}/activity`,Xd)},jp={projects:(e="local")=>y(`${C(e)}/projects`,j(Mo)),addProject:(e,t,i,s="local")=>y(`${C(s)}/projects`,Mo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>y(`${C(t)}/projects/${encodeURIComponent(e)}`,ar,{method:"DELETE"}),projectDirectories:(e,t="local")=>y(`${C(t)}/project-directories?q=${encodeURIComponent(e)}`,j(nr))},Tt={workspaces:(e,t="local")=>y(`${C(t)}/projects/${e}/workspaces`,j(gd)),deleteWorkspace:(e,t,i="local")=>y(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ri,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>y(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Ud),workspaceFile:(e,t,i,s="local")=>y(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Bd),writeWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({path:i});r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!1&&n.set("overwrite","false");const a=s instanceof Uint8Array,c=a?new Uint8Array(s):new TextEncoder().encode(s);return y(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${n.toString()}`,Oa,{method:"PUT",body:c,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})},deleteWorkspaceFile:(e,t,i,s="local")=>{const r=new URLSearchParams({path:i});return y(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,zd,{method:"DELETE"})},moveWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({fromPath:i,toPath:s});return r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!0&&n.set("overwrite","true"),y(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${n.toString()}`,qd,{method:"POST"})}},lr={sessions:(e,t="local")=>y(`${C(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(or)),startSession:(e,t="local")=>y(`${C(t)}/sessions`,or,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>y(`${C(t)}/sessions/cleanup/preview`,Da,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>y(`${C(t)}/sessions/cleanup`,vd,{method:"POST",body:JSON.stringify(e)}),archiveMany:(e,t="local")=>y(`${C(t)}/sessions/bulk/archive`,bd,{method:"POST",body:Fo(e)}),deleteArchivedMany:(e,t="local")=>y(`${C(t)}/sessions/bulk/delete-archived`,wd,{method:"POST",body:Fo(e)}),messages:(e,t,i="local")=>y(Ep(e,t,i),dd),status:(e,t="local")=>y(xi(e,"status",t),Bt),models:(e,t="local")=>y(xi(e,"models",t),Cd),setModel:(e,t,i,s="local")=>y(ie(e,"model",s),Bt,{method:"POST",body:oe(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>y(ie(e,"model/cycle",i),Bt,{method:"POST",body:oe(e,{direction:t})}),thinkingLevels:(e,t="local")=>y(xi(e,"thinking-levels",t),Md),setThinkingLevel:(e,t,i="local")=>y(ie(e,"thinking-level",i),Bt,{method:"POST",body:oe(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>y(ie(e,"thinking-level/cycle",t),Bt,{method:"POST",body:oe(e)}),commands:(e,t="local")=>y(xi(e,"commands",t),j(jd)),prompt:(e,t,i,s="local",r)=>y(ie(e,"prompt",s),Si,{method:"POST",body:oe(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...r!==void 0&&r.length>0?{attachments:r}:{}})}),saveAttachments:(e,t,i="local",s)=>y(ie(e,"attachments",i),Sp,{method:"POST",body:oe(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>y(ie(e,"shell",i),Si,{method:"POST",body:oe(e,{text:t})}),runCommand:(e,t,i="local")=>y(ie(e,"commands/run",i),Do,{method:"POST",body:oe(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>y(ie(e,"commands/respond",s),Do,{method:"POST",body:oe(e,{requestId:t,value:i})}),abort:(e,t="local")=>y(ie(e,"abort",t),kp,{method:"POST",body:oe(e)}),stop:(e,t="local")=>y(ie(e,"stop",t),$p,{method:"POST",body:oe(e)}),archive:(e,t="local")=>y(ie(e,"archive",t),Wo,{method:"POST",body:oe(e)}),archiveWithDescendants:(e,t="local")=>y(ie(e,"archive-tree",t),Wo,{method:"POST",body:oe(e)}),restore:(e,t="local")=>y(ie(e,"restore",t),Pp,{method:"POST",body:oe(e)}),deleteArchived:(e,t="local")=>y(Lp(e,t),Cp,{method:"DELETE"}),detachParent:(e,t="local")=>y(ie(e,"detach-parent",t),Rp,{method:"POST",body:oe(e)}),reloadSession:(e,t="local")=>y(ie(e,"reload",t),Mp,{method:"POST",body:oe(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return y(`${C(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Dd)},saveApiKey:(e,t,i="local")=>y(`${C(i)}/auth/api-key`,Si,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>y(`${C(t)}/auth/logout`,Si,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>y(`${C(t)}/auth/oauth`,yi,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>y(`${C(t)}/auth/oauth/${encodeURIComponent(e)}`,yi),respondOAuthFlow:(e,t,i,s="local")=>y(`${C(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,yi,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>y(`${C(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,yi,{method:"POST"})},At={terminals:(e,t,i="local")=>y(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(Es)),startTerminal:(e,t,i,s="local")=>y(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Es,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>y(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ar,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>y(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,ar,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>y(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Es,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>y(`${C(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ri,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>y(`${C(t)}/terminal-command-runs${Np(e)}`,j(ri)),getCommandRun:(e,t="local")=>Up(e,t),cancelCommandRun:(e,t="local")=>y(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ri,{method:"POST"})};async function Up(e,t){const i=await fetch(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Bp(s)??i.statusText)}return ri(await i.json())}}function Np(e){if(e===void 0)return"";const t=new URLSearchParams;e.projectId!==void 0&&t.set("projectId",e.projectId),e.workspaceId!==void 0&&t.set("workspaceId",e.workspaceId),e.terminalId!==void 0&&t.set("terminalId",e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set("statuses",e.statuses.join(",")),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set("metadata",JSON.stringify(e.metadata));const i=t.toString();return i===""?"":`?${i}`}function Bp(e){if(!B(e))return;const t=e.error;return typeof t=="string"?t:void 0}const zp={files:(e,t,i={})=>{const s=new URLSearchParams({q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?y(`${C(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,j(nr)):(s.set("cwd",e),y(`${C(i.machineId)}/files?${s.toString()}`,j(nr)))}},qp={gitStatus:(e,t,i="local")=>y(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Kd),gitDiff:(e,t,i,s="local")=>y(Ap(s,e,t,i),Gd)},G={...Ka,...Fp,...ze,...Zt,...Xt,...Va,...jp,...Tt,...lr,...At,...zp,...qp};function Hp(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,r=typeof e=="string"?e:e.id;return new WebSocket(`${Dr()}${Er(t)}/sessions/${encodeURIComponent(r)}/events${s}`)}function z0(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Dr()}${Er(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function Kp(e="local"){return new WebSocket(`${Dr()}${Er(e)}/events`)}function Er(e){return`/api/machines/${encodeURIComponent(e)}`}function Dr(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const oi=".omp-web/uploads";class ms extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class Ga extends Error{constructor(t,i){super(eh(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function jo(e){return e?.uploads?.defaultFolder??oi}function Vp(e,t){return e?.uploads?.defaultFolder??t}function Wr(e,t){const i=Uo(e,"upload destination",{allowEmpty:!0}),s=Uo(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function Gp(e,t,i,s={}){const r=s.xhrFactory?.()??new XMLHttpRequest;let o=!1,n=!1;return{promise:new Promise((c,p)=>{const u=f=>{o||(o=!0,p(f))},h=f=>{o||(o=!0,c(f))};r.open("PUT",Dp(e,t,i.path,Zp(s)),!0),r.responseType="json",r.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),r.upload.onprogress=f=>{s.onProgress?.(Xp(f,i.file.size))},r.onload=()=>{if(r.status>=200&&r.status<300){try{s.onProgress?.({loaded:i.file.size,total:i.file.size,percent:1,lengthComputable:!0}),h(Oa(Qa(r)))}catch(f){u(f instanceof Error?f:new Error(String(f)))}return}u(new Error(sh(r)))},r.onerror=()=>{u(new Error("Workspace upload failed"))},r.onabort=()=>{u(new ms(n?void 0:"Workspace upload aborted"))},r.send(i.file)}),cancel:()=>{o||(n=!0,r.abort())}}}function Qp(e,t,i,s={}){const r=s.destinationFolder??oi,o=i.map((h,f)=>({index:f,name:h.name,path:Wr(r,h.name),loaded:0,total:h.size,percent:Lr(0,h.size),lengthComputable:!0,done:!1}));let n,a=0;const c={requested:!1},p=()=>{s.onProgress?.(Yp(o,a,o.every(h=>h.done)))};return{promise:(async()=>{const h=[],f=[];for(let S=0;S<i.length;S+=1){if(c.requested)throw new ms;a=S;const $=i[S],R=o[S];if(!($===void 0||R===void 0)){n=Gp(e,t,{path:R.path,file:$},{...Jp(s),onProgress:ee=>{R.total=ee.total,R.loaded=Math.min(ee.loaded,R.total),R.percent=ee.percent,R.lengthComputable=ee.lengthComputable,p()}});try{const ee=await n.promise;R.loaded=R.total,R.percent=1,R.lengthComputable=!0,R.done=!0,h.push(ee),p()}catch(ee){if(th(ee,c))throw ee;const st=q(ee);R.loaded=R.total,R.percent=1,R.lengthComputable=!0,R.done=!0,R.error=st,f.push({index:S,name:$.name,path:R.path,error:st}),p()}finally{n=void 0}}}if(f.length>0)throw new Ga(f,h);return h})(),cancel:()=>{c.requested=!0,n?.cancel()}}}function Jp(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Zp(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Xp(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:Lr(e.loaded,i),lengthComputable:e.lengthComputable}}function Yp(e,t,i){const s=e.reduce((o,n)=>o+n.total,0),r=e.reduce((o,n)=>o+n.loaded,0);return{currentFileIndex:t,files:e.map(o=>({...o})),loaded:r,total:s,percent:Lr(r,s),done:i}}function Lr(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function eh(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function th(e,t){return t.requested||e instanceof ms}function Uo(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(ih(s))throw new Error(`${t} must be workspace-relative`);const r=s.split(/[\\/]+/u).filter(o=>o!==""&&o!==".");if(r.length===0){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(r.some(o=>o===".."))throw new Error(`${t} must not contain path traversal`);return r.join("/")}function ih(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function Qa(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function sh(e){const t=rh(e);return B(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function rh(e){try{return Qa(e)}catch{return}}function Wi(){return{sessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function oh(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,ompWebStatus:void 0,error:""}}function lt(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Ja(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Za="local";function Ws(e,t){return`${e}:${t}`}function Yt(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??Za}class nh{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??Va}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,ah(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),r=g(s)===i,o=s.machineActivities[i]??(r?s.workspaceActivities:{}),n=lh(o,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...r?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function ah(e){const t={};for(const i of e.workspaces)Ja(i)&&(t[i.cwd]=i);return t}function lh(e,t){const i={...e};return Ja(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class ch{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??G,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=dh(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:g(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const r=s.providers.find(o=>o.id===t&&(i===void 0||o.authType===i));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({authDialog:{...t,saving:!1,error:String(r)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(r=>r.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(r=>r.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({error:String(r)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const r=t??i.inputValue??"",o={...i};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,r,g(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,g(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:g(this.getState())}),s=i.filter(o=>o.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const r=s[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,g(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const r=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",r=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,o=t.prompt?.requestId??t.select?.requestId,n=r!==void 0&&r===o,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,g(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function dh(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const r=i[2];return r===void 0||r===""?{command:s}:{command:s,providerId:r}}function hi(e){return e.replaceAll(":",".")}function ph(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[r,o]of t.entries()){if(!r.startsWith(i))continue;const n=r.slice(i.length),a=s[n];a===void 0?s[n]=o:Array.isArray(a)?a.push(o):s[n]=[a,o]}return s}function Ls(e,t){const i=ph(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function We(e,t,i,s){const r=new URL(window.location.href),o=`${e}--${t}`;if(r.searchParams.delete(o),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(i));hh(r,s)}function hh(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}function uh(e){const t=e.files.map((s,r)=>{const o=s.size;return{index:r,name:s.name,path:Wr(e.destinationFolder,s.name),size:s.size,loaded:0,total:o,percent:Bo(0,o),lengthComputable:!0,status:r===0?"uploading":"pending"}}),i=t.reduce((s,r)=>s+r.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:i,percent:Bo(0,i),status:"uploading",startedAt:e.startedAt}}function fh(e,t){const i=new Map(t.files.map(r=>[r.index,r])),s=e.files.map(r=>{const o=i.get(r.index);if(o===void 0)return r;const n={...r,path:o.path,loaded:o.loaded,total:o.total,percent:o.percent,lengthComputable:o.lengthComputable,status:o.error!==void 0?"error":o.done?"completed":t.currentFileIndex===r.index?"uploading":r.status};return o.error===void 0?delete n.error:n.error=o.error,n});return{...e,files:s,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function gh(e,t,i){const s=e.files.map((o,n)=>{const a=t[n];return{...o,...a===void 0?{}:{path:a.path,response:a},loaded:o.total,percent:1,lengthComputable:!0,status:"completed"}}),r=Or(s);return{...e,files:s,currentFileIndex:s.length===0?-1:s.length-1,...r,status:"completed",completedAt:i}}function mh(e,t,i){const s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:r.status==="uploading"||r.index===e.currentFileIndex?{...r,status:"error",error:t}:{...r,status:"cancelled",error:"Not uploaded because an earlier file failed."});return{...e,files:s,...Or(s),status:"error",error:t,completedAt:i}}function No(e,t){const i="Upload cancelled",s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:{...r,status:"cancelled",error:i});return{...e,files:s,...Or(s),status:"cancelled",error:i,completedAt:t}}function Or(e){const t=e.reduce((i,s)=>i+s.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Bo(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const zo=hi("core:workspace.files");class vh{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??G,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Qp,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=g(this.getState()),r=await this.api.workspaceTree(t.id,i.id,"",s),o={...this.getState().expandedDirs};await Promise.all(Object.keys(o).map(async n=>{o[n]=(await this.api.workspaceTree(t.id,i.id,n,s)).entries})),this.setState({fileTree:r.entries,expandedDirs:o,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:qo(this.getState().expandedDirs,t)});return}try{const r=await this.api.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),We(zo,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const r=await this.api.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==t)return;if(bh(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),We(zo,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}startWorkspaceUpload(t,i){const s=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(s===void 0||r===void 0){this.setState({error:"Select a workspace before uploading files."});return}if(t.length===0)return;const o=g(this.getState()),n=i.overwrite??!1,a=i.createDirs??!0;let c;try{c=uh({id:this.createUploadBatchId(),projectId:s.id,workspaceId:r.id,machineId:o,destinationFolder:i.destinationFolder,overwrite:n,createDirs:a,files:t,startedAt:this.now()})}catch(h){this.setState({error:String(h)});return}this.setUploadBatch(c);let p;try{p=this.uploadWorkspaceFiles(s.id,r.id,t,{destinationFolder:i.destinationFolder,machineId:o,overwrite:n,createDirs:a,onProgress:h=>{this.updateUploadProgress(c.id,h)}})}catch(h){return this.failUploadBatch(c.id,h),{batchId:c.id,done:Promise.resolve()}}this.uploadTasks.set(c.id,p);const u=p.promise.then(async h=>{await this.completeUploadBatch(c.id,h,i)}).catch(async h=>{await this.handleUploadFailure(c.id,h,i)}).finally(()=>{this.uploadTasks.delete(c.id)});return{batchId:c.id,done:u}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(No(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:qo(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(fh(s,i))}async completeUploadBatch(t,i,s){const r=this.getUploadBatch(t);if(r?.status!=="uploading"||(this.setUploadBatch(gh(r,i,this.now()),{error:""}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();const o=i[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}async handleUploadFailure(t,i,s){const r=this.failUploadBatch(t,i);if(!(i instanceof Ga)||i.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();const o=i.responses[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}failUploadBatch(t,i){const s=this.getUploadBatch(t);if(s?.status!=="uploading")return;if(wh(i)){const n=No(s,this.now());return this.setUploadBatch(n),n}const r=q(i),o=mh(s,r,this.now());return this.setUploadBatch(o,{error:r}),o}getUploadBatch(t){return this.getState().workspaceUploadBatches[t]}setUploadBatch(t,i={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[t.id]:t},...i})}isCurrentWorkspaceBatch(t){const i=this.getState();return i.selectedProject?.id===t.projectId&&i.selectedWorkspace?.id===t.workspaceId&&g(i)===t.machineId}}function bh(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function wh(e){return e instanceof ms}function qo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const Ho=hi("core:workspace.git");class yh{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await G.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(s.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),We(Ho,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),We(Ho,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[r,o]=await Promise.all([G.gitDiff(i.id,s.id,{path:t},g(this.getState())),G.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class Sh{constructor(t,i,s,r){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=r}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await G.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:Ko(this.getState().machineActivities,r),machineRuntimes:Ko(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Wi()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await G.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await G.deleteMachine(t.id);const r=this.getState().machines.filter(n=>n.id!==t.id),o=r.find(n=>n.id==="local")??r[0];return this.setState({machines:r,machineStatuses:Os(this.getState().machineStatuses,t.id),machineRuntimes:Os(this.getState().machineRuntimes,t.id),machineActivities:Os(this.getState().machineActivities,t.id)}),s&&o!==void 0?(i.selectFallback===!1||await this.selectMachine(o),o):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await G.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await G.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(o=>o.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const r=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await G.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(r=>G.health(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(r=>G.runtime(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function Os(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Ko(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class xh{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=g(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await G.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(o=>o.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([o])=>s.has(o)));this.setState({projects:i,workspacesByProjectId:r})}catch(i){g(this.getState())===t&&this.setState({error:String(i)})}finally{g(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await G.addProject(t.trim(),void 0,i,g(this.getState())),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await G.closeProject(t,g(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const cr="omp-web:cached-new-sessions:v1",kh="browserCachedNew",_t="local";function ui(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Vo(e,t=_t,i=ui()){if(e.messageCount!==0||e.archived===!0)return;const s=Fr(i).filter(r=>r.id!==e.id||r.machineId!==t);_r([dr(e,t),...s],i)}function dr(e,t=_t){return{...e,browserCachedNew:!0,machineId:t}}function Go(e,t=_t,i=ui()){const s=Fr(i).filter(r=>r.id!==e||r.machineId!==t);_r(s,i)}function Xa(e,t,i=_t,s=ui()){const r=new Set(t.map(c=>c.id)),o=Fr(s),n=o.filter(c=>c.machineId!==i||!r.has(c.id));return n.length!==o.length&&_r(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Hi(e){return e===void 0?!1:Ch(e)&&e.browserCachedNew===!0}function $h(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:_t},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Fr(e=ui()){try{const t=e?.getItem(cr);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Ph(s)):[]}catch{return[]}}function _r(e,t=ui()){try{e.length===0?t?.removeItem(cr):t?.setItem(cr,JSON.stringify(e))}catch{}}function Ph(e){if(!B(e))return[];const t=Pt(e,"id"),i=Pt(e,"path"),s=Pt(e,"cwd"),r=Pt(e,"created"),o=Pt(e,"modified"),n=Pt(e,"firstMessage"),a=Rh(e,"messageCount");if(t===void 0||i===void 0||s===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const c=Fs(e,"name"),p=Fs(e,"parentSessionPath"),u=Fs(e,"machineId")??_t;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function Ch(e){return kh in e}function Pt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Fs(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Rh(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Mh(e){return qh(e.flatMap(jr)).filter(t=>t.parts.length>0)}function qe(e,t){return{role:e,parts:[{type:"text",text:t}]}}function zt(e,t){const i=Oh(t);return i===void 0?e:{...e,meta:i}}function Ih(e,t,i){if(i==="")return e;const s=e.at(-1),r=s?.parts.at(-1);return s?.role===t&&r?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...r,text:r.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,qe(t,i)]}function Th(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function jr(e){if(Eh(e))return[e];if(_(e,"role")==="bashExecution")return[zt(jh(e),e)];const t=Uh(_(e,"role")),i=Nh(Me(e,"content"),e),s=t==="user"?Dh(i):void 0;if(s!==void 0)return s.map(p=>zt(p,e));const r=Lh(e);if(t==="tool")return[zt({role:t,parts:i,...r===void 0?{}:{source:r}},e)];const o=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&o.length>0&&o.every(p=>p.type==="skillRead")?"skill":t,a=o.length>0?[zt({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[],c=Ah(e);return c===void 0?a:[...a,zt(c,e)]}function Ah(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return qe("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Eh(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(Me(e,"parts"))}function Dh(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Wh(e[0].text);if(t!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:t.userMessage}]}]]}function Wh(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;const i=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...i===void 0||i===""?{}:{userMessage:i}}}function Lh(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Oh(e){const t=Fh(Me(e,"timestamp")),i=_h(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Fh(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function _h(e){if(_(e,"role")!=="assistant")return;const t=_(e,"provider"),i=_(e,"model"),s=_(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function jh(e){const t=_(e,"command")??"",i=Li(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=Me(e,"output");s!=null&&i.push("",Vi(s));const r=Me(e,"exitCode");r!=null&&i.push("",`exit ${Vi(r)}`),Li(e,"cancelled")===!0&&i.push("","cancelled"),Li(e,"truncated")===!0&&i.push("","output truncated");const o=_(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
+ `)}]}}function Uh(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function Nh(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=_(i,"type"),r=_(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=_(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=_(i,"name")??"tool",n=Me(i,"arguments"),a=_(i,"id"),c=o==="read"?zh(_(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:o,summary:fi(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const o=_(i,"data"),n=_(i,"mimeType");return o!==void 0&&o!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:o}]:[{type:"text",text:"[image]"}]}return Qo(i)}).map(i=>i.type==="text"&&_(t,"role")==="toolResult"?Bh(i.text,t):i):Qo(e)}function Bh(e,t){const i=_(t,"toolCallId"),s=Me(t,"content"),r=Me(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:_(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:Li(t,"isError")===!0}}function zh(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function qh(e){const t=[],i=new Map;for(const s of e){let r=[];const o={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{r.length!==0&&(t.push({role:s.role,parts:r,...o}),r=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=Hh(a),p=t.length;t.push({role:"tool",parts:[c],...o}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&Kh(t,c,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function Hh(e){return{type:"toolExecution",...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:"pending"}}function Kh(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=Ki(i.details)??r.preview,n={...r,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...o===void 0?{}:{preview:o}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function Ki(e){const t=Me(e,"preview");if(!B(t))return;const i=_(t,"diff"),s=_(t,"error"),r=Gh(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&r===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...r===void 0?{}:{firstChangedLine:r}}}function Qo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:fi(e)}]:[{type:"text",text:Vi(e)}]}function fi(e){if(!B(e))return Vi(e);const t=_(e,"command");if(t!==void 0)return t;const i=_(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${Vh(n)}`).join(" · ")}function Vh(e){return typeof e=="string"?e.length>80?`${e.slice(0,77)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?"":"s"}`:typeof e=="object"&&e!==null?"object":""}function Me(e,t){return B(e)?e[t]:void 0}function _(e,t){const i=Me(e,t);return typeof i=="string"?i:void 0}function Li(e,t){const i=Me(e,t);return typeof i=="boolean"?i:void 0}function Gh(e,t){const i=Me(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function Vi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Qh="omp-web:prompt-draft:";function Gi(e){return`${Qh}${e}`}function vs(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Ya(e,t=vs()){try{return t?.getItem(Gi(e))??""}catch{return""}}function Qi(e,t,i=vs()){try{t?i?.setItem(Gi(e),t):i?.removeItem(Gi(e))}catch{}}function Ji(e,t=vs()){try{t?.removeItem(Gi(e))}catch{}}function Jo(e,t,i=vs()){const s=Ya(e,i);s!==""&&(Qi(t,s,i),Ji(e,i))}function Jh(e,t){return qe("bash",`${t===!0?`excluded from context
6
+
7
+ `:""}$ ${e}`)}function Zh(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,qe("bash",t)];const r=Yh(s.text)?"":`
8
+
9
+ `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function Xh(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const r=[];return!s.text.includes(`
10
+
11
+ `)&&(t.output===void 0||t.output==="")&&r.push("(no output)"),t.isError===!0&&r.push(t.output??"Bash command failed"),t.exitCode!=null&&r.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&r.push("cancelled"),t.truncated===!0&&r.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&r.push(`full output: ${t.fullOutputPath}`),r.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
+
13
+ ${r.join(`
14
+ `)}`}]}]}function Yh(e){const t=e.lastIndexOf(`
15
+
16
+ `),i=e.lastIndexOf("$ ");return t>i}function eu(e,t){if(t.type==="message.append")return fu(e,t.message);if(t.type==="assistant.delta")return Ih(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Th(e,t.text);if(t.type==="tool.start")return ou(e,t);if(t.type==="tool.update")return tl(e,t.toolCallId,i=>nu(i,t));if(t.type==="tool.end")return el(e,t.toolCallId,t.toolName,fi(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,Jh(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Zh(e,t.chunk);if(t.type==="shell.end")return Xh(e,t);if(t.type==="command.output")return[...e,qe(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,qe("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:tu(e,t.message)}function tu(e,t){const i=au(t);if(i!==void 0)return el(e,i.toolCallId,i.toolName,fi(i.content),i.text,i.isError,i.content,i.details);const s=jr(t);if(s.length===0)return;const r=s.map(o=>o.role==="assistant"?su(o):o).filter(o=>o.parts.length>0);return r.length===0?e:r.reduce((o,n)=>iu(o,n),e)}function iu(e,t){const i=lu(e,t);if(i.length>0)return cu(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||uu(s,t)?[...e.slice(0,-1),t]:[...e,t]}function su(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function ru(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function ou(e,t){const i=t.toolName==="read"?ru(vt(t.args,"path")):void 0;if(i!==void 0)return gu(e,{role:"skill",parts:[{type:"skillRead",...i,...t.toolCallId===""?{}:{toolCallId:t.toolCallId}}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||fi(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function nu(e,t){const i=Ki(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function el(e,t,i,s,r,o,n,a){const c=tl(e,t,h=>{const f=Ki(a)??h.preview;return{...h,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...f===void 0?{}:{preview:f}}});if(c!==e)return c;const p=Ki(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function tl(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r===void 0)continue;const o=r.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(o<0)continue;const n=r.parts[o];if(n?.type!=="toolExecution")continue;const a={...r,parts:[...r.parts.slice(0,o),i(n),...r.parts.slice(o+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function au(e){if(vt(e,"role")!=="toolResult")return;const t=vt(e,"toolCallId"),i=Xi(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:vt(e,"toolName")??"tool",text:il(i),isError:bu(e,"isError")===!0,content:i,details:Xi(e,"details")}}function il(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(il).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=vt(e,"text")??vt(e,"content")??vt(e,"output");if(t!==void 0)return t}return""}function lu(e,t){const i=Zi(t);if(i.length===0)return[];const s=[];let r=i.length;const o=rl(e)+1;for(let n=e.length-1;n>=o;n--){const a=Zi(e[n]);if(a.length===0)continue;const c=r-a.length;if(!(c<0)&&hu(a,i.slice(c,r))&&(s.unshift(n),r=c,r===0))return s}return[]}function cu(e,t,i){const s=du(e,t,i),r=s[0];if(r===void 0)return e;const o=new Set(s),n=[];for(let a=0;a<e.length;a++){a===r&&n.push(i);const c=e[a];c!==void 0&&!o.has(a)&&n.push(c)}return n}function du(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const r=s-1;return pu(e[r])?[r,...t]:t}function pu(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function Zi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function hu(e,t){return e.length===t.length&&e.every((i,s)=>sl(i,t[s]))}function sl(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:Zo(e.path)===Zo(t.path)||e.name===t.name}function Zo(e){return e.replace(/\\/g,"/")}function uu(e,t){return Xo(e)===Xo(t)}function Xo(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
+
19
+ `)}function fu(e,t){const i=jr(t);return i.length===0?e:[...e,...i]}function gu(e,t){const i=e.at(-1);return mu(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function mu(e,t){const i=Zi(t);if(t.role!=="skill"||i.length===0)return!1;const s=rl(e)+1;return i.every(r=>vu(e,r,s))}function vu(e,t,i){for(let s=e.length-1;s>=i;s--)if(Zi(e[s]).some(r=>sl(r,t)))return!0;return!1}function rl(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function Xi(e,t){return B(e)?e[t]:void 0}function vt(e,t){const i=Xi(e,t);return typeof i=="string"?i:void 0}function bu(e,t){const i=Xi(e,t);return typeof i=="boolean"?i:void 0}const wu="omp-web:chat-history:v2:",yu=1800*1e3;function Su(e){try{const t=sessionStorage.getItem(Yi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Ru(i))return;if(Date.now()-i.savedAt>yu){sessionStorage.removeItem(Yi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function xu(e,t){try{sessionStorage.setItem(Yi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function ku(e){try{sessionStorage.removeItem(Yi(e))}catch{}}function $u(e,t){if(e===void 0||!pr(e))return t;if(!pr(t))return e;if(Pu(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),r=new Array(s-i);return Yo(r,i,e),Yo(r,i,t),Cu(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function Pu(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Cu(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Yo(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function Yi(e){return`${wu}${e}`}function Ru(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:r}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof r=="number"&&pr({messages:t,start:i,total:s})}function pr(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some(Mu)}function Mu(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&!("content"in e)&&typeof e.role=="string"&&Array.isArray(e.parts)}const Iu={read:Su,write:xu,remove:ku};class Tu{constructor(t=Iu){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return en(this.rawHistoryPage(t))}mergeHistory(t,i){const s=$u(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),en(s)}applyLiveEvent(t,i){return eu(t,i)}discard(t){this.rawHistoryPages.delete(t),this.cache.remove?.(t)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function en(e){const t=e?.start??0;return{messages:Mh(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function ol(e,t=e.length){const i=e.slice(0,t),s=Au(i,t);if(s!==void 0)return s;const r=Eu(i,t);if(r!==void 0)return r;const o=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
+ `))+1,n=i.slice(o);if(i.slice(0,o).endsWith("@ "))return{kind:"file",query:n,from:o-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&o===0)return{kind:"command",query:n.slice(1),from:o,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:o,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:o,to:t,fileScope:"tracked"}}function nl(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Au(e,t){const i=e.lastIndexOf('"');if(i===-1)return;const s=e.slice(0,i);if(s.endsWith("!@"))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"!@",quoted:!0};if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,fileScope:"tracked",quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"@ ",quoted:!0}}function Eu(e,t){const i=e.lastIndexOf(`
21
+ `)+1,s=e.slice(i),r=tn(s,"@ "),o=tn(s,"!@"),n=Math.max(r,o);if(n===-1)return;const a=n===o?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function tn(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Du(e[i-1]))return i;return-1}function Du(e){return e===" "||e===" "}function es(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Lu(e).startsWith("/")?{kind:"command"}:ol(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function sn(e){return es(e).kind==="shell"}function Wu(e,t){return e.kind!==t.kind?!1:e.kind==="shell"&&t.kind==="shell"?e.excludeFromContext===t.excludeFromContext:!0}function Lu(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
+ `))+1;return e.slice(t)}class Ou{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,r="local"){this.close(),this.machineId=r,this.session=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),ll(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.session===void 0||this.session.id===""||this.session.cwd===""||!this.shouldReconnect)return;const t=Hp(this.session,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await al(t);Fu(i)&&this.onEvent?.(i)}}class rn{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),ll(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Kp(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await al(t);ju(i)&&this.onEvent?.(i)}}function Fu(e){const t=Ur(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","session.created","pi.event"].includes(t)}function _u(e){const t=Ur(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function ju(e){const t=Ur(e);return _u(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Ur(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function al(e){try{return typeof e=="string"?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function ll(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function cl(e,t){if(e===void 0)return"unknown";const s=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return s===!0?"persisted":s===!1||Hi(e)?"transient":"unknown"}function He(e,t){return e!==void 0&&e.archived!==!0&&cl(e,t)==="persisted"}function ci(e,t){return e!==void 0&&e.archived!==!0&&cl(e,t)==="transient"}function gi(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class bs{constructor(t,i,s=gi()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[r,o]of Uu(t,i,s))this.values.set(r,o)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function Nr(e){return typeof e=="string"&&e!==""?e:void 0}function Uu(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!Nu(r))return[];const o=[];for(const n of r.entries){const a=n[0],c=t(n[1]);c!==void 0&&o.push([a,c])}return o}catch{return[]}}function Nu(e){return!B(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}class Bu{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}const zu="omp-web:session-selection:v1";class qu{constructor(t=gi()){this.sessionIdsByCwd=new bs(zu,Nr,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Hu(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Vu(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>r.archived!==!0):e.find(r=>r.archived!==!0)}function Ku(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Vu(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function Gu(e,t,i){return Oi(e,[t],i)}function Oi(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function Qu(e,t,i){return Fi(e,t,[i])}function Fi(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),r=e.find(o=>!s.has(o.id)&&o.archived!==!0);return r===void 0?{type:"clear"}:{type:"select",session:r}}const qt=100,on=4;class Ju{constructor(t,i,s,r=new Bu,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.socket=o.socket??new Ou,this.api=o.api??G,this.transcripts=o.transcripts??new Tu}applyGlobalEvent(t){t.type==="status.update"?this.queueStatusUpdate(t.status):t.type==="activity.update"?this.queueActivityUpdate(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();Ku(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(!t)return;const i=g(this.getState()),s=this.createPendingSessionStart(t,i);this.pendingSessionStarts.set(s.tempId,s),this.insertAndSelectPendingSession(s.session);try{const r=await this.api.startSession(t.path,i);await this.resolvePendingSessionStart(s.tempId,r)}catch(r){this.failPendingSessionStart(s.tempId,r)}}preferredSession(t,i,s){return Hu(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){if(ht(t)){this.selectClientPendingStartSession(t,i);return}this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates();const r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const u=await this.api.messages(t,{limit:qt},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(r,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:qt},g(this.getState())),this.api.status(t,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(r,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(c.isStreaming?t.id:void 0),status:c,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(c),this.refreshAvailableThinkingLevels();for(const u of n)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(Hi(t)&&lf(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i,{before:t.messagePageStart,limit:qt},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(r)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,r="inline"){const o=this.getState().selectedSession;if(!o||o.archived===!0)return;const n=t.trim(),a=s!==void 0&&s.length>0;if(ht(o)){!a&&n.startsWith("/")?this.enqueuePendingSessionSend(o,{type:"command",text:t}):!a&&sn(t)?this.enqueuePendingSessionSend(o,{type:"shell",text:t}):this.enqueuePendingSessionSend(o,{type:"prompt",text:t,streamingBehavior:i,attachments:s,delivery:r});return}if(!a&&n.startsWith("/"))return this.runCommand(t);if(!a&&sn(t))return this.runShell(t);await this.deliverPromptToSession(o,t,i,s,r,g(this.getState()),{markSending:a})}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:Je(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){if(ht(i)){this.enqueuePendingSessionSend(i,{type:"shell",text:t});return}await this.deliverShellToSession(i,t,g(this.getState()),{optimisticLine:!0})}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){if(ht(i)){this.enqueuePendingSessionSend(i,{type:"command",text:t});return}await this.deliverCommandToSession(i,t,g(this.getState()),{applyResult:!0})}}enqueuePendingSessionSend(t,i){const s=this.pendingSessionStarts.get(t.id);if(s===void 0||s.discarded){this.setState({error:"The backend session is not ready for queued sends. Copy your message before discarding this failed start."});return}const r={...i,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};s.queuedSends.push(r);const o=this.getState(),n=o.clientQueuedSessionMessages[t.id]??[],a=js(t.id,s.queuedSends.length);this.setState({clientQueuedSessionMessages:{...o.clientQueuedSessionMessages,[t.id]:[...n,Yu(r)]},sessionActivities:{...o.sessionActivities,[t.id]:a},activity:o.selectedSession?.id===t.id?a:o.activity,error:""})}async flushQueuedPendingSends(t,i,s){for(const r of s){if(!await this.deliverQueuedPendingSend(t,i,r))return;this.dropNextQueuedSessionMessage(t.id)}}async deliverQueuedPendingSend(t,i,s){return s.type==="prompt"?this.deliverPromptToSession(t,s.text,s.streamingBehavior,s.attachments,s.delivery,i,{markSending:!0}):s.type==="shell"?this.deliverShellToSession(t,s.text,i,{optimisticLine:!0}):this.deliverCommandToSession(t,s.text,i,{applyResult:!0})}async deliverPromptToSession(t,i,s,r,o,n,a){const c=r!==void 0&&r.length>0;a.markSending&&this.markSendingPrompt(t.id,!0);try{if(c&&o==="folder"){const u=(await this.api.saveAttachments(t,r,n)).map(f=>nl(f.path,!1)).join(" "),h=i===""?u:`${i}
23
+
24
+ ${u}`;await this.api.prompt(t,h,s,n)}else await this.api.prompt(t,i,s,n,r);return this.markCachedNewSessionPersisted(t),!0}catch(p){return this.setState({error:String(p)}),!1}finally{a.markSending&&this.markSendingPrompt(t.id,!1)}}async deliverShellToSession(t,i,s,r){r.optimisticLine&&this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("user",i)]});try{return await this.api.shell(t,i,s),this.markCachedNewSessionPersisted(t),!0}catch(o){return this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("system",String(o))]}),this.setState({error:String(o)}),!1}}async deliverCommandToSession(t,i,s,r){this.markSendingPrompt(t.id,!0);try{const o=await this.api.runCommand(t,i,s);return r.applyResult&&this.getState().selectedSession?.id===t.id?this.applyCommandResult(o):o.type==="select"&&this.setState({error:`Queued command “${i}” needs input; open the session and run it again.`}),this.markCachedNewSessionPersisted(t),!0}catch(o){return this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("system",String(o))]}),this.setState({error:String(o)}),!1}finally{this.markSendingPrompt(t.id,!1)}}dropNextQueuedSessionMessage(t){const i=this.getState(),s=i.clientQueuedSessionMessages[t]??[];if(s.length===0)return;const r=s.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?Je(i.clientQueuedSessionMessages,t):{...i.clientQueuedSessionMessages,[t]:r}})}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,g(this.getState())))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(!t)return;const i=this.statusForSession(t);if(ci(t,i)){await this.deleteCachedNewSession(t);return}if(He(t,i))try{await this.api.archive(t,g(this.getState()));const s=this.getState(),r=Gu(s.sessions,t.id,new Date().toISOString()),o=Qu(r,s.selectedSession?.id,t.id);this.setState({sessions:r}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(s){this.setState({error:String(s)})}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(t===void 0||!He(t,this.statusForSession(t))))try{const i=await this.api.archiveWithDescendants(t,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],r=this.getState(),o=Oi(r.sessions,s,new Date().toISOString()),n=Fi(o,r.selectedSession?.id,s);this.setState({sessions:o}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=ln(t).filter(s=>He(s,this.statusForSession(s)));if(i.length!==0)try{const s=g(this.getState()),{succeededIds:r,failures:o,generatedAt:n}=await this.archiveSessionBatch(i,s);if(r.length>0){const a=this.getState(),c=Oi(a.sessions,r,n??new Date().toISOString()),p=Fi(c,a.selectedSession?.id,r);this.setState({sessions:c}),p.type==="select"?await this.selectSession(p.session):p.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures("Archive",o)}catch(s){this.setState({error:`Archive failed: ${q(s)}`})}}async deleteArchivedSessions(t){const i=ln(t).filter(o=>o.archived===!0);if(i.length===0)return;const s=g(this.getState()),r=this.getState().machineRuntimes[s];if(r?.ok!==!0||!Fe(r,Ce.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Omp-Web runtime on this machine."});return}try{const{succeededIds:o,failures:n}=await this.deleteArchivedSessionBatch(i,s);if(o.length>0){const a=new Set(o),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionFailures("Delete",n)}catch(o){this.setState({error:`Delete failed: ${q(o)}`})}}async archiveSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&Fe(s,Ce.sessionsBulkMutations)){const o=await this.api.archiveMany(t,i);return{succeededIds:o.archivedSessionIds,failures:dn(o.failures),generatedAt:o.generatedAt}}const r=await hn(t,on,async o=>(await this.api.archive(o,i),o.id));return{succeededIds:cn(r),failures:pn(t,r)}}async deleteArchivedSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&Fe(s,Ce.sessionsBulkMutations)){const o=await this.api.deleteArchivedMany(t,i);return{succeededIds:o.deletedSessionIds,failures:dn(o.failures)}}const r=await hn(t,on,async o=>(await this.api.deleteArchived(o,i),o.id));return{succeededIds:cn(r),failures:pn(t,r)}}async applySessionCleanupResult(t,i=g(this.getState())){if(g(this.getState())!==i)return;const s=t.archivedSessionIds,r=t.deletedSessionIds;if(s.length>0||r.length>0){const o=this.getState(),n=new Set(r),a=[...s,...r],c=Oi(o.sessions,s,t.generatedAt).filter(u=>!n.has(u.id)),p=o.selectedSession!==void 0&&a.includes(o.selectedSession.id);if(this.setState({sessions:c,sessionStatuses:nn(o.sessionStatuses,a),sessionActivities:nn(o.sessionActivities,a),...p?{status:void 0,activity:void 0}:{}}),o.selectedSession!==void 0&&n.has(o.selectedSession.id)){const u=c.find(h=>h.archived!==!0)??c[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}else{const u=Fi(c,o.selectedSession?.id,s);u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(i)}async refreshCurrentWorkspaceSessions(t=g(this.getState())){const i=this.getState().selectedWorkspace;if(i!==void 0)try{const s=Xa(i.path,await this.api.sessions(i.path,t),t).filter(c=>!this.isSuppressedCreatedSession(c,t));if(g(this.getState())!==t||this.getState().selectedWorkspace?.id!==i.id)return;const r=this.mergePendingStartSessions(i.path,s,t),o=this.getState().selectedSession;if(this.setState({sessions:r}),o===void 0)return;const n=r.find(c=>c.id===o.id);if(n!==void 0){n!==o&&this.setState({selectedSession:n});return}const a=r.find(c=>c.archived!==!0)??r[0];a!==void 0?await this.selectSession(a):this.deselectSession({forgetRememberedSelection:!0})}catch(s){g(this.getState())===t&&this.getState().selectedWorkspace?.id===i.id&&this.setState({error:String(s)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(t===void 0||!ci(t,this.statusForSession(t)))return;const i=ht(t)?this.pendingSessionStarts.get(t.id):void 0;i!==void 0?(i.discarded=!0,i.queuedSends=[]):this.api.stop(t,g(this.getState())).catch(()=>{}),Go(t.id,g(this.getState())),Ji(this.sessionCacheKey(t.id));const s=this.getState(),r=s.sessions.filter(n=>n.id!==t.id);if(this.setState({sessions:r,sessionStatuses:Je(s.sessionStatuses,t.id),sessionActivities:_s(s.sessionActivities,t.id),sendingPrompts:Je(s.sendingPrompts,t.id),clientQueuedSessionMessages:Je(s.clientQueuedSessionMessages,t.id)}),this.getState().selectedSession?.id!==t.id)return;const o=r.find(n=>n.archived!==!0)??r[0];o!==void 0?await this.selectSession(o):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,g(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async reloadSession(t=this.getState().selectedSession){if(t===void 0||!He(t,this.statusForSession(t)))return;const i=g(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!Fe(s,Ce.sessionsReload)){this.setState({error:"Reloading sessions from disk requires an updated Omp-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(r){this.setState({error:String(r)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,g(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t,g(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,g(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(r){this.setState({error:String(r)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,g(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t,g(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t,g(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,g(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0||ht(i)))try{this.flushPendingUpdates();const[s,r]=await Promise.all([this.api.messages(i,{limit:qt},g(this.getState())),this.api.status(i,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...o,status:r,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(r.isStreaming?t:void 0)}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionFailures(t,i){i.length!==0&&this.setState({error:`${t} failed for ${String(i.length)} session${i.length===1?"":"s"}: ${i.join("; ")}`})}sessionCacheKey(t){return Yt(g(this.getState()),t)}statusForSession(t){if(t===void 0)return;const i=this.getState();return i.status?.sessionId===t.id&&i.selectedSession?.id===t.id?i.status:i.sessionStatuses[t.id]}workspaceSelectionKey(t){return`${g(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}createPendingSessionStart(t,i){const s=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,r=new Date().toISOString(),o={id:s,path:`omp-web://pending-session/${s}`,cwd:t.path,persisted:!1,name:"New session",created:r,modified:r,messageCount:0,firstMessage:"",clientPendingStart:!0,machineId:i};return{tempId:s,workspaceId:t.id,cwd:t.path,machineId:i,session:o,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(t){const i=this.getState();this.selectClientPendingStartSession(t,{activity:js(t.id),sessions:[t,...i.sessions.filter(s=>s.id!==t.id)]})}selectClientPendingStartSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)}),this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates();const s=this.getState(),r=this.pendingSessionStarts.get(t.id),o=i?.activity??s.sessionActivities[t.id]??(r!==void 0?js(t.id,r.queuedSends.length):void 0);this.setState({...i?.sessions===void 0?{}:{sessions:i.sessions},selectedSession:t,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:o,availableThinkingLevels:[],...o===void 0?{}:{sessionActivities:{...s.sessionActivities,[t.id]:o}},error:""}),i?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(t,i){const s=this.pendingSessionStarts.get(t);if(s===void 0)return;this.pendingSessionStarts.delete(t);const r=s.queuedSends.splice(0),o=this.takeSuppressedCreatedSessionsFor(s.cwd,s.machineId,i.id);if(s.discarded){Ji(Yt(s.machineId,t)),this.setState({clientQueuedSessionMessages:Je(this.getState().clientQueuedSessionMessages,t)}),this.applyReleasedCreatedSessions(o,s.machineId),this.api.stop(i,s.machineId).catch(()=>{});return}Vo(i,s.machineId),Jo(Yt(s.machineId,t),Yt(s.machineId,i.id));const n=dr(i,s.machineId);if(!this.isCurrentPendingStart(s)){this.setState({clientQueuedSessionMessages:Je(this.getState().clientQueuedSessionMessages,t)}),await this.flushQueuedPendingSends(n,s.machineId,r);return}const a=this.getState(),c=a.selectedSession?.id===t;this.setState({sessions:Zu(a.sessions,t,n),sessionActivities:_s(a.sessionActivities,t),sendingPrompts:an(a.sendingPrompts,t,n.id),clientQueuedSessionMessages:an(a.clientQueuedSessionMessages,t,n.id),...c?{selectedSession:n,status:a.sessionStatuses[n.id],activity:a.sessionActivities[n.id]}:{},error:""}),this.applyReleasedCreatedSessions(o,s.machineId),c&&(this.updateUrl({replace:!0}),await this.selectSession(n,{updateUrl:!1})),await this.flushQueuedPendingSends(n,s.machineId,r)}failPendingSessionStart(t,i){const s=this.pendingSessionStarts.get(t);if(s===void 0)return;this.pendingSessionStarts.delete(t);const r=this.takeSuppressedCreatedSessionsFor(s.cwd,s.machineId),o=this.isCurrentPendingStart(s);if(s.discarded||!o){o&&this.applyReleasedCreatedSessions(r,s.machineId);return}const n=this.getState(),a=q(i),c=Xu(t,a,s.queuedSends.length),p=n.sessions.some(u=>u.id===t);this.setState({sessions:p?n.sessions:[s.session,...n.sessions],sessionActivities:{...n.sessionActivities,[t]:c},activity:n.selectedSession?.id===t?c:n.activity,error:`Failed to start session: ${a}`}),this.applyReleasedCreatedSessions(r,s.machineId)}isCurrentPendingStart(t){const i=this.getState();return g(i)===t.machineId&&i.selectedWorkspace?.id===t.workspaceId}hasPendingStartFor(t,i){return Array.from(this.pendingSessionStarts.values()).some(s=>s.cwd===t&&s.machineId===i)}isSuppressedCreatedSession(t,i){const s=this.suppressedCreatedSessions.get(t.id);return s?.session.cwd===t.cwd&&s.machineId===i}takeSuppressedCreatedSessionsFor(t,i,s){if(s!==void 0&&this.suppressedCreatedSessions.delete(s),this.hasPendingStartFor(t,i))return[];const r=[];for(const[o,n]of this.suppressedCreatedSessions)n.session.cwd!==t||n.machineId!==i||(this.suppressedCreatedSessions.delete(o),r.push(n.session));return r}applyReleasedCreatedSessions(t,i){if(t.length===0||g(this.getState())!==i)return;const s=this.getState();if(s.selectedWorkspace===void 0)return;const r=new Set(s.sessions.map(n=>n.id)),o=t.filter(n=>n.cwd===s.selectedWorkspace?.path&&!r.has(n.id));o.length!==0&&this.setState({sessions:[...o.reverse(),...s.sessions]})}mergePendingStartSessions(t,i,s){const r=this.getState().sessions.filter(n=>ht(n)&&n.cwd===t&&n.machineId===s);if(r.length===0)return i;const o=new Set(r.map(n=>n.id));return[...r,...i.filter(n=>!o.has(n.id))]}async recreateCachedNewSession(t,i){try{const s=g(this.getState()),r=await this.api.startSession(t.cwd,s);Vo(r,s),Jo(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),Go(t.id,s);const o=dr(r,s);this.setState({sessions:[o,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(o,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Hi(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession($h(i))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,qe(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&Qi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,r=[t.session,...this.getState().sessions.filter(o=>o.id!==t.session?.id)];this.setState({sessions:r,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();if(i.selectedWorkspace?.path!==t.cwd||i.sessions.some(r=>r.id===t.id))return;const s=g(i);if(this.hasPendingStartFor(t.cwd,s)){this.suppressedCreatedSessions.set(t.id,{session:t,machineId:s});return}this.setState({sessions:[t,...i.sessions]})}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!lt(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...of(i,t.sessionId,t.messageCount),...s?{sessionActivities:_s(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),t.isStreaming||this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=o=>{if(o.id!==t)return o;const n={...o};return i===void 0||i===""?delete n.name:n.name=i,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:r===void 0?void 0:s(r)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(nf(t))return}if(t.type==="status.update"){this.queueStatusUpdate(t.status);return}if(t.type==="activity.update"){this.queueActivityUpdate(t.activity);return}if(af(t)){this.queueTranscriptEvent(t);return}this.flushPendingUpdates();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.schedulePendingFlush()}queueStatusUpdate(t){this.pendingStatusBySession.set(t.sessionId,t),this.schedulePendingFlush()}queueActivityUpdate(t){this.pendingActivityBySession.set(t.sessionId,t),this.schedulePendingFlush()}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}if(this.pendingActivityBySession.size>0){const t=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(const i of t)this.applyActivity(i)}if(this.pendingStatusBySession.size>0){const t=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(const i of t)this.applyStatus(i)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:qt},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function _s(e,t){return Je(e,t)}function Je(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function nn(e,t){if(t.length===0)return e;const i=new Set(t);return Object.fromEntries(Object.entries(e).filter(([s])=>!i.has(s)))}function an(e,t,i){if(t===i||!(t in e))return e;const s=e[t];return s===void 0?e:{...Je(e,t),[i]:s}}function Zu(e,t,i){const s=[];let r=!1;for(const o of e){if(o.id===t){r||(s.push(i),r=!0);continue}o.id!==i.id&&s.push(o)}return r?s:[i,...s]}function ht(e){return e!==void 0&&"clientPendingStart"in e&&e.clientPendingStart===!0}function js(e,t=0){return{sessionId:e,phase:"active",label:"Creating session",detail:t>0?`${String(t)} queued ${t===1?"message":"messages"} will send when the backend session is ready`:"Waiting for the backend session to be ready",at:new Date().toISOString()}}function Xu(e,t,i=0){const s=i>0?` · ${String(i)} queued ${i===1?"message":"messages"} kept below`:"";return{sessionId:e,phase:"error",label:"Session creation failed",detail:`${t}${s}`,at:new Date().toISOString()}}function Yu(e){return e.type==="prompt"?{kind:e.streamingBehavior==="steer"?"steer":"followUp",text:ef(e.text,e.attachments)}:{kind:"followUp",text:e.text}}function ef(e,t){const i=tf(t);return i===void 0?e:e.trim()===""?i:`${e}
25
+
26
+ ${i}`}function tf(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?.trim()).filter(n=>n!==void 0&&n!==""),i=e.length,s=`${String(i)} ${i===1?"attachment":"attachments"}`;if(t.length===0)return`[${s} queued]`;const r=t.slice(0,3).join(", "),o=t.length>3?`, +${String(t.length-3)} more`:"";return`[${s} queued: ${r}${o}]`}function ln(e){const t=new Set,i=[];for(const s of e)t.has(s.id)||(t.add(s.id),i.push(s));return i}function cn(e){return e.filter(sf).map(t=>t.value)}function dn(e){return e.map(t=>`${t.sessionId}: ${t.error}`)}function pn(e,t){return t.flatMap((i,s)=>rf(i)?[`${e[s]?.id??"unknown"}: ${q(i.reason)}`]:[])}async function hn(e,t,i){const s=e.map((c,p)=>({item:c,index:p})),r=[];let o=0;async function n(){for(;o<s.length;){const c=s[o];if(c===void 0)return;o+=1;try{r[c.index]={status:"fulfilled",value:await i(c.item)}}catch(p){r[c.index]={status:"rejected",reason:p}}}}const a=Math.min(Math.max(1,t),s.length);return await Promise.all(Array.from({length:a},()=>n())),r}function sf(e){return e.status==="fulfilled"}function rf(e){return e.status==="rejected"}function of(e,t,i){if(i===void 0)return{};const r=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,o=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...o!==e.selectedSession?{selectedSession:o}:{}}}function nf(e){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(e.type)}function af(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function lf(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class cf{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}const df="omp-web:workspace-selection:v1";class pf{constructor(t=gi()){this.workspaceIdsByProject=new bs(df,Nr,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function hf(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e[0]:e[0]}class uf{constructor(t,i,s,r,o=new cf,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??G}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Wi()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Ws(g(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=g(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Wi()});try{const r=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:r},isLoadingWorkspaces:!1});const o=hf(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Ws(s,t.id))});o?await this.selectWorkspace(o,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(r),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Ws(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...Wi()});try{const r=Xa(t.path,await this.api.sessions(t.path,s),s);if(g(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:r});const o=this.sessions.preferredSession(t.path,r,i?.sessionId);o?await this.sessions.selectSession(o,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(r)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(r=>r.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,g(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),r=this.getState();if(r.selectedProject?.id!==t||r.selectedWorkspace?.id!==i)return;const o=gf(s);o!==void 0?await this.selectWorkspace(o):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),r={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:r}):this.setState({workspacesByProjectId:r})}}function ff(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function gf(e){return e.find(t=>t.isMain)??e[0]}const mf="omp-web:machine-navigation:v1";class vf{constructor(t=gi()){this.snapshotsByMachine=new bs(mf,wf,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?gn(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,gn(t))}forget(t){this.snapshotsByMachine.delete(t)}}function bf(e){return{machineId:e,surface:{}}}function un(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Za,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function fn(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function gn(e){return{...e,surface:{...e.surface}}}function wf(e){if(!B(e))return;const t=Ze(e,"machineId");if(t===void 0)return;const i=dl(Ze(e,"tool")),s=Sf(Ze(e,"view"));return{machineId:t,projectId:Ze(e,"projectId"),workspaceId:Ze(e,"workspaceId"),sessionId:Ze(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:yf(e.surface)}}function yf(e){return B(e)?{selectedFilePath:Ze(e,"selectedFilePath"),selectedDiffPath:Ze(e,"selectedDiffPath"),selectedTerminalId:Ze(e,"selectedTerminalId")}:{}}function Sf(e){return e==="navigation"||e==="chat"?e:dl(e)}function dl(e){return xf(e)?e:void 0}function xf(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ze(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}const kf="omp-web:terminal-selection:v1";class $f{constructor(t=gi()){this.terminalIdsByCwd=new bs(kf,Nr,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function q0(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>!r.exited)??e[0]:e.find(r=>!r.exited)??e[0]}function H0(e){return e.find(t=>!t.exited)??e[0]}const pl=1200,Pf=["mod","alt","shift"];class Cf{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const r=ul(t);if(r===void 0)return!1;const o=Br(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,r],o))return!0;if(this.clearPending(),!di(r))return!1}else if(!di(r))return!1;return this.handleSequence([r],o)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(o=>Of(o.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(o=>zr(o.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},pl)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Br(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Rf(p,t,u);return h===void 0?[]:[h]}),r=new Map;for(const p of s)r.set(p.key,[...r.get(p.key)??[],p]);const o=new Map;for(const p of r.values()){const u=[...p].sort(hr)[0];u!==void 0&&o.set(u.key,u)}const n=[...o.values()].sort(Tf),a=new Map,c=new Map;for(const p of s){const u=o.get(p.key);if(u===void 0)continue;const h=Af(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,f=u===void 0||h?void 0:mn(u),S=h?[...a.get(p)??[]].sort(hr).map(mn):[];return{...p,active:h,shadows:S,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function Us(e){return fl(e,{requireFirstChordActivator:!0})}function hl(e){const t=fl(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function _i(e){return hl(e).map(t=>t.split("+").map(ml).join("+")).join(" ")}function ul(e){if(e.isComposing)return;const t=Wf(e.key);if(t===void 0)return;const i=[];return(e.metaKey||e.ctrlKey)&&i.push("mod"),e.altKey&&i.push("alt"),e.shiftKey&&i.push("shift"),i.push(t),i.join("+")}function di(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Rf(e,t,i){const s=Mf(e.id,t);if(s===null)return;const r=s??e.shortcut;if(r===void 0||r==="")return;const o=hl(r),n=o[0];if(!(n===void 0||!di(n)))return{action:e,shortcut:o.join(" "),source:s===void 0?"default":"custom",tokens:o,key:If(o),order:i}}function Mf(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function If(e){return e.join("\0")}function mn(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function hr(e,t){return vn(e.source)-vn(t.source)||bn(e.action.id,t.action.id)||bn(e.action.title,t.action.title)||e.order-t.order}function Tf(e,t){return e.tokens.length-t.tokens.length||hr(e,t)}function Af(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&zr(e.tokens,i.tokens))}function vn(e){switch(e){case"custom":return 0;case"default":return 1}}function bn(e,t){return e<t?-1:e>t?1:0}function fl(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"Enter a shortcut, choose None, or reset to the default."};const s=[],r=i.split(/\s+/u).filter(o=>o!=="");for(const[o,n]of r.entries()){const a=Ef(n);if(!a.ok)return a;if(o===0&&t.requireFirstChordActivator&&!di(a.token))return{ok:!1,message:"Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured."};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Ef(e){const t=e.split("+").filter(o=>o!=="");if(t.length===0)return{ok:!1,message:"Shortcut chords must include a key."};const i=new Set;let s;for(const o of t){const n=Df(o);if(n!==void 0){if(i.has(n))return{ok:!1,message:`Shortcut has duplicate ${ml(n)} modifiers.`};i.add(n);continue}const a=gl(o);if(a===void 0)return{ok:!1,message:`Unsupported shortcut key: ${o}`};if(s!==void 0)return{ok:!1,message:"Each shortcut chord can include only one non-modifier key."};s=a}return s===void 0?{ok:!1,message:"Shortcut chords must include a key."}:{ok:!0,token:[...Pf.filter(o=>i.has(o)),s].join("+")}}function Df(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function gl(e){const t=Lf(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function Wf(e){if(e===" ")return"space";const t=e.toLowerCase();return gl(t)}function Lf(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function ml(e){return e==="mod"?wn()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?wn()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Of(e,t){return e.length===t.length&&zr(e,t)}function zr(e,t){return t.every((i,s)=>e[s]===i)}function wn(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Ff={archiveIdleEnabled:!0,archiveIdleDays:"30",deleteArchivedEnabled:!1,deleteArchivedDays:"90"};function ei(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:"Enable at least one cleanup action."};const t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){const i=xn(e.archiveIdleDays,"Archive idle sessions after");if(typeof i=="string")return{ok:!1,error:i};t.archiveIdleDays=i}if(e.deleteArchivedEnabled){const i=xn(e.deleteArchivedDays,"Delete archived sessions after");if(typeof i=="string")return{ok:!1,error:i};t.deleteArchivedDays=i}return{ok:!0,request:t}}function Lt(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function yn(e){if(!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0)return!1;const t=ei(e.draft);return!t.ok||Lt(t.request)!==Lt(e.previewRequest)?!1:ji(e.preview)}function ji(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function vl(e,t){const i=e.projects.map(r=>r.cwd);if(t===void 0)return i;const s=new Set(t);return i.filter(r=>s.has(r))}function Sn(e,t){const i=new Set(vl(e,t)),s=e.projects.filter(r=>i.has(r.cwd));return{...e,projects:s,totals:s.reduce((r,o)=>({archiveCount:r.archiveCount+o.archiveCount,deleteCount:r.deleteCount+o.deleteCount}),{archiveCount:0,deleteCount:0})}}function _f(e,t){return t(jf(e))}function jf(e){const t=e.totals.archiveCount,i=e.totals.deleteCount,s=[];return t>0&&s.push(`archive ${String(t)} idle ${t===1?"session":"sessions"}`),i>0&&s.push(`permanently delete ${String(i)} archived ${i===1?"session":"sessions"}`),`Run cleanup and ${s.length===0?"run cleanup":s.join(" and ")}?
27
+
28
+ Permanent deletion only applies to archived sessions and cannot be undone.`}function Uf(e){return`Update and restart Omp-Web on ${e??"this machine"} to clean up sessions.`}function xn(e,t){const i=e.trim();if(i==="")return`${t} must be set.`;const s=Number(i);return!Number.isInteger(s)||s<0?`${t} must be a non-negative whole number of days.`:s}const qr="themes:classic",Nf="themes:omp-web-dark",Bf={themeId:Nf,auto:!0},bl="omp-web-app-theme",zf=["--pi-bg","--pi-surface","--pi-surface-hover","--pi-terminal-bg","--pi-terminal-text","--pi-border","--pi-border-muted","--pi-text","--pi-text-secondary","--pi-text-bright","--pi-muted","--pi-dim","--pi-accent","--pi-accent-border","--pi-selection-bg","--pi-success","--pi-success-border","--pi-success-bg","--pi-success-surface","--pi-success-ring","--pi-warning","--pi-warning-border","--pi-warning-surface","--pi-danger","--pi-purple","--pi-purple-border","--pi-purple-surface","--pi-overlay","--pi-shadow-soft","--pi-shadow","--pi-shadow-strong","--pi-bg-overlay-soft","--pi-bg-overlay","--pi-success-bg-overlay","--pi-terminal-selection"],qf=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Hf(){try{const e=window.localStorage.getItem(bl);return e===null?void 0:Jf(e)}catch{return}}function Kf(e){try{window.localStorage.setItem(bl,JSON.stringify(e))}catch{}}function Vf(e){const t=document.documentElement;t.dataset.ompWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of zf){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Gf(e){const t=Qf(e.themes,e.fallbackThemeId??qr),i=e.themes.find(n=>n.id===e.preference.themeId)??t;if(i===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};const s=wl(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const r=e.prefersLight?s.light:s.dark,o=e.themes.find(n=>n.id===r)??i;return{selectedTheme:i,activeTheme:o,selectedThemePair:s,fallbackTheme:t}}function Qf(e,t=qr){return e.find(i=>i.id===t)??e[0]}function wl(e,t){return e.find(i=>i.light===t||i.dark===t)}function Jf(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Zf(i)?i:void 0}catch{return}}function Zf(e){if(!Xf(e))return!1;const t=e.themeId,i=e.auto;return Yf(t)&&typeof i=="boolean"}function Xf(e){return typeof e=="object"&&e!==null}function Yf(e){return typeof e=="string"&&qf.test(e)}const eg="workspace.delete",tg="pi.operation",ig="target.workspaceId";function sg(e){return{...e===void 0?{}:{projectId:e},metadata:{[tg]:eg}}}function rg(e){const t={};for(const i of e){const s=ur(i);if(s===void 0)continue;const r=t[s];(r===void 0||i.createdAt.localeCompare(r.createdAt)>=0)&&(t[s]=i)}return t}function og(e){return Object.entries(e).filter(([,t])=>ts(t)).map(([t])=>t)}function yl(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&ts(i)}function ur(e){return e.metadata[ig]}function ts(e){return e.status==="queued"||e.status==="running"}function ng(){return[{id:"actions.show",title:"Show Actions",description:"Open the command palette",shortcut:"mod+k",group:"General",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"Focus Prompt",description:"Move keyboard focus to the message composer",shortcut:"mod+g c",group:"General",run:e=>{e.focusPrompt()}},{id:"machine.add",title:"Add Machine",description:"Register another PI WEB runtime reachable from this gateway",group:"Machine",run:e=>e.addMachine()},{id:"machine.refresh",title:"Refresh Selected Machine",description:"Check whether the selected PI WEB runtime is online",group:"Machine",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"Open Selected Machine PI WEB",description:"Open the selected remote PI WEB directly in a new tab",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"Remove Selected Machine",description:"Remove the selected remote machine from this gateway",group:"Machine",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"Add Project",group:"Project",run:e=>e.addProject()},{id:"auth.login",title:"Configure Provider Authentication",description:"Run /login without tying authentication to a session",group:"General",run:e=>e.configureAuth()},{id:"auth.logout",title:"Remove Provider Authentication",description:"Run /logout for stored pi credentials",group:"General",run:e=>e.logoutAuth()},{id:"theme.select",title:"Select Theme",description:"Choose the PI WEB color theme",group:"Preferences",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"Open Settings",description:"Manage PI WEB configuration and keyboard shortcuts",shortcut:"mod+,",group:"Preferences",run:e=>{e.ompWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"Full Page Reload",description:"Reload the PI WEB browser page",group:"General",run:e=>{e.reloadPage()}},{id:"view.chat",title:"Go to Chat",shortcut:"mod+1",group:"Navigation",run:e=>{e.focusPrompt()}},{id:"view.files",title:"Go to Files",shortcut:"mod+2",group:"Navigation",enabled:Ht,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"Go to Git",shortcut:"mod+3",group:"Navigation",enabled:kn,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"Go to Terminal",shortcut:"mod+4",group:"Navigation",enabled:Ht,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"Refresh Files",shortcut:"mod+shift+f",group:"Workspace",enabled:Ht,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"Refresh Git",shortcut:"mod+shift+g",group:"Workspace",enabled:kn,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"Refresh Current Panel",shortcut:"mod+shift+r",group:"Workspace",enabled:Ht,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"Delete Workspace",description:"Remove the selected Git worktree",group:"Workspace",enabled:ag,run:e=>e.deleteWorkspace()},{id:"session.start",title:"Start Session",shortcut:"mod+enter",group:"Session",enabled:Ht,run:e=>e.startSession()},{id:"session.archive",title:"Archive Session",description:"Archive the selected session",group:"Session",enabled:lg,run:e=>e.archiveSession()},{id:"session.reload",title:"Reload Session from Disk",description:"Close and re-open the selected session from its session file. Use /reload in the prompt for Pi runtime resources.",group:"Session",enabled:dg,disabledReason:Sl,run:e=>e.reloadSession()},{id:"session.delete",title:"Delete New Session",description:"Delete the selected transient new session",group:"Session",enabled:cg,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"Stop Active Work",shortcut:"mod+.",group:"Session",enabled:e=>e.state.selectedSession!==void 0&&lt(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function Ht(e){return e.state.selectedWorkspace!==void 0}function kn(e){return e.state.selectedWorkspace?.isGitRepo===!0}function ag(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!yl(e.state,t)}function lg(e){return He(e.state.selectedSession,e.state.status)}function cg(e){return ci(e.state.selectedSession,e.state.status)}function dg(e){return!He(e.state.selectedSession,e.state.status)||Sl(e)!==void 0?!1:!lt(e.state.status,e.state.activity)}function Sl(e){if(He(e.state.selectedSession,e.state.status)&&!lt(e.state.status,e.state.activity))return pg(e.state,Ce.sessionsReload,"reload sessions from disk")}function pg(e,t,i){const s=e.machineRuntimes[g(e)];if(!(s?.ok===!0&&Fe(s,t)))return`Update and restart Omp-Web on ${e.selectedMachine?.name??"this machine"} to ${i}.`}const hg="modulepreload",ug=function(e){return"/"+e},$n={},Hr=function(t,i,s){let r=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");r=c(i.map(p=>{if(p=ug(p),p in $n)return;$n[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":hg,u||(f.as="script"),f.crossOrigin="",f.href=p,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((S,$)=>{f.addEventListener("load",S),f.addEventListener("error",()=>$(new Error(`Unable to preload CSS for ${p}`)))})}))}function o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};function fg(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ti(e)}function ti(e){switch(e){case"navigation":return ye`
29
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
30
+ <circle cx="6" cy="7" r="1.5"></circle>
31
+ <path d="M10 7h8"></path>
32
+ <circle cx="6" cy="12" r="1.5"></circle>
33
+ <path d="M10 12h8"></path>
34
+ <circle cx="6" cy="17" r="1.5"></circle>
35
+ <path d="M10 17h8"></path>
36
+ </svg>
37
+ `;case"chat":return ye`
38
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
39
+ <path d="M7 5h10a3 3 0 0 1 3 3v5a3 3 0 0 1-3 3h-6l-5 4v-4H7a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3Z"></path>
40
+ <path d="M8 9h8"></path>
41
+ <path d="M8 13h5"></path>
42
+ </svg>
43
+ `;case"files":return ye`
44
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
45
+ <path d="M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"></path>
46
+ </svg>
47
+ `;case"git":return ye`
48
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
49
+ <circle cx="6" cy="6" r="2"></circle>
50
+ <circle cx="18" cy="6" r="2"></circle>
51
+ <circle cx="12" cy="18" r="2"></circle>
52
+ <path d="M8 6h6"></path>
53
+ <path d="M6 8v2a6 6 0 0 0 6 6"></path>
54
+ <path d="M18 8v2a6 6 0 0 1-6 6"></path>
55
+ </svg>
56
+ `;case"terminal":return ye`
57
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
58
+ <rect x="3" y="5" width="18" height="14" rx="2"></rect>
59
+ <path d="m7 10 3 3-3 3"></path>
60
+ <path d="M12 16h5"></path>
61
+ </svg>
62
+ `;case"tasks":return ye`
63
+ <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
64
+ <rect x="4" y="3" width="16" height="18" rx="2"></rect>
65
+ <path d="M9 10h6"></path>
66
+ <path d="M9 14h6"></path>
67
+ <path d="M9 18h4"></path>
68
+ <path d="M9 6h6"></path>
69
+ </svg>
70
+ `}}const gg=10*1024*1024,mg="10 MB",vg=D`
71
+ /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
72
+ :host { --pi-app-safe-area-bottom: 0px; position: fixed; top: 0; right: 0; left: 0; display: block; height: 100dvh; box-sizing: border-box; overflow: hidden; padding: env(safe-area-inset-top) env(safe-area-inset-right) var(--pi-app-safe-area-bottom) env(safe-area-inset-left); color: var(--pi-text); background: var(--pi-bg); font: 14px system-ui, sans-serif; }
73
+ :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
74
+ @media (display-mode: standalone), (display-mode: fullscreen), (display-mode: minimal-ui) {
75
+ :host { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
76
+ }
77
+ .shell { --navigation-panel-size: 340px; --workspace-panel-size: minmax(360px, 42vw); --navigation-panel-width: var(--navigation-panel-size); --workspace-panel-width: var(--workspace-panel-size); display: grid; grid-template-columns: var(--navigation-panel-width) 1px minmax(320px, 1fr) 1px var(--workspace-panel-width); height: 100%; min-height: 0; }
78
+ aside { grid-column: 1; display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
79
+ aside app-navigation-panel { flex: 1 1 auto; min-height: 0; }
80
+ header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
81
+ .header-actions { display: flex; align-items: center; gap: 8px; }
82
+ project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
83
+ session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
84
+ main { grid-column: 3; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
85
+ .context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: none; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
86
+ .context-bar::before, .context-bar::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
87
+ .context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
88
+ .context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
89
+ .context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
90
+ .context-bar-label { display: none; }
91
+ .context-items { flex: 1 1 auto; min-width: 0; display: flex; align-items: stretch; gap: 5px; margin: 0; padding: 0 8px; list-style: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scroll-padding-inline: 8px; scrollbar-width: thin; }
92
+ .context-bar.has-context-actions .context-items { padding-right: 52px; scroll-padding-inline: 8px 52px; }
93
+ .context-item { flex: 0 0 auto; min-width: 0; display: flex; }
94
+ .context-actions { position: absolute; top: 6px; right: 0; bottom: 6px; z-index: 3; display: flex; align-items: center; padding: 0 8px 0 0; pointer-events: none; }
95
+ .context-actions::after { content: ""; position: absolute; top: 0; right: 0; bottom: 0; z-index: 0; width: 26px; background: var(--pi-bg); pointer-events: none; }
96
+ .context-chip { flex: 0 0 auto; min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 8px; font: inherit; text-align: left; }
97
+ .context-chip:hover { background: var(--pi-surface-hover); }
98
+ .context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
99
+ .context-chip.empty { border-style: dashed; color: var(--pi-muted); }
100
+ .context-kind { display: none; }
101
+ .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
102
+ app-mobile-main-tabs { display: none; }
103
+ .mobile-tabs-frame { position: relative; display: none; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
104
+ .mobile-tabs-frame::before, .mobile-tabs-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
105
+ .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
106
+ .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
107
+ .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
108
+ .mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
109
+ .mobile-tabs button { flex: 0 0 auto; white-space: nowrap; }
110
+ .mobile-navigation-tab, .mobile-navigation-panel { display: none; }
111
+ .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
112
+ .tab-badge { display: inline-block; min-width: 14px; margin-left: 4px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
113
+ .navigation-panel-edge, .workspace-panel-edge { min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
114
+ .navigation-panel-edge { grid-column: 2; }
115
+ .workspace-panel-edge { grid-column: 4; }
116
+ .navigation-panel-edge-button, .workspace-panel-edge-button { position: relative; z-index: 1; box-sizing: border-box; display: grid; place-items: center; width: 18px; height: 48px; padding: 0; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-bg); color: var(--pi-muted); opacity: .75; cursor: pointer; }
117
+ .navigation-panel-edge-button:hover, .navigation-panel-edge-button:focus-visible, .workspace-panel-edge-button:hover, .workspace-panel-edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
118
+ .shell.navigation-panel-collapsed .navigation-panel-edge-button { transform: translateX(calc(50% - .5px)); }
119
+ .shell.workspace-panel-collapsed .workspace-panel-edge-button { transform: translateX(calc(-50% + .5px)); }
120
+ .navigation-panel-edge-icon, .workspace-panel-edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
121
+ workspace-panel { grid-column: 5; min-width: 0; min-height: 0; overflow: hidden; }
122
+ @media (min-width: 1181px) {
123
+ .shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
124
+ .shell.navigation-panel-collapsed > aside { display: none; }
125
+ .shell.workspace-panel-collapsed { --workspace-panel-width: 0px; }
126
+ .shell.workspace-panel-collapsed > workspace-panel { display: none; }
127
+ }
128
+ @media (max-width: 1180px) {
129
+ .shell { grid-template-columns: var(--navigation-panel-width) 1px minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
130
+ .shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
131
+ .shell.navigation-panel-collapsed > aside { display: none; }
132
+ aside { grid-row: 1 / 3; }
133
+ .navigation-panel-edge { grid-row: 1 / 3; }
134
+ main { grid-column: 3; grid-row: 1 / 3; }
135
+ app-mobile-main-tabs { display: block; flex: 0 0 auto; min-width: 0; }
136
+ .mobile-tabs-frame { display: flex; }
137
+ .shell.workspace-view main { grid-row: 1; min-height: auto; }
138
+ .shell.workspace-view > workspace-panel { grid-column: 3; grid-row: 2; display: flex; border-left: 0; }
139
+ .shell:not(.workspace-view) > workspace-panel { display: none; }
140
+ .workspace-panel-edge { display: none; }
141
+ main.workspace-view chat-view, main.workspace-view prompt-editor, main.workspace-view status-bar,
142
+ main.workspace-view .empty { display: none; }
143
+ main.workspace-view { overflow: hidden; }
144
+ }
145
+ @media (max-width: 760px) {
146
+ .shell { grid-template-columns: minmax(0, 1fr); }
147
+ aside, .navigation-panel-edge { display: none; }
148
+ main, .shell.workspace-view > workspace-panel { grid-column: 1; }
149
+ .context-bar { display: flex; }
150
+ .mobile-navigation-tab { display: block; }
151
+ main.navigation-view chat-view, main.navigation-view prompt-editor, main.navigation-view status-bar,
152
+ main.navigation-view .empty { display: none; }
153
+ main.navigation-view .mobile-navigation-panel { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
154
+ main.navigation-view .mobile-navigation-panel app-navigation-panel { flex: 1 1 auto; min-height: 0; }
155
+ main.navigation-view .mobile-navigation-panel project-list,
156
+ main.navigation-view .mobile-navigation-panel workspace-list,
157
+ main.navigation-view .mobile-navigation-panel session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
158
+ main.navigation-view .mobile-navigation-panel project-list[collapsed],
159
+ main.navigation-view .mobile-navigation-panel workspace-list[collapsed],
160
+ main.navigation-view .mobile-navigation-panel session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
161
+ }
162
+ status-bar { flex: 0 0 auto; }
163
+ chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
164
+ prompt-editor { flex: 0 0 auto; }
165
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
166
+ .empty { margin: auto; color: var(--pi-muted); }
167
+ .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
168
+ `,Kr=D`
169
+ :host { display: flex; flex-direction: column; min-height: 0; color: var(--pi-text); background: var(--pi-bg); font: 13px system-ui, sans-serif; container-type: inline-size; }
170
+ header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
171
+ .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
172
+ .workspace-header-scroll-frame::before, .workspace-header-scroll-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 18px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
173
+ .workspace-header-scroll-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
174
+ .workspace-header-scroll-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
175
+ .workspace-header-scroll-frame.can-scroll-left::before, .workspace-header-scroll-frame.can-scroll-right::after { opacity: 1; }
176
+ .workspace-header-strip { display: flex; justify-content: space-between; align-items: center; gap: 8px; min-width: 0; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
177
+ .tabs { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; }
178
+ .tabs button { flex: 0 0 auto; white-space: nowrap; }
179
+ .tabs button.icon-tab { min-width: 34px; }
180
+ button { display: inline-flex; align-items: center; gap: 5px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; cursor: pointer; }
181
+ button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
182
+ .tab-icon { flex: 0 0 auto; width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
183
+ .tab-custom-icon { flex: 0 0 auto; width: 16px; height: 16px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
184
+ .tab-custom-icon svg { width: 16px; height: 16px; pointer-events: none; }
185
+ .tab-label { min-width: 0; }
186
+ .tab-badge { flex: 0 0 auto; display: inline-block; min-width: 14px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
187
+ @container (max-width: 430px) {
188
+ .tabs button.icon-tab { justify-content: center; padding-inline: 7px; }
189
+ .tabs button.icon-tab .tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
190
+ }
191
+ .panel-content { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: auto; }
192
+ .empty-state { box-sizing: border-box; width: min(100%, 380px); margin: auto; padding: 24px; display: grid; gap: 8px; color: var(--pi-muted); text-align: center; }
193
+ .empty-state h2 { margin: 0; color: var(--pi-text); font-size: 15px; line-height: 1.3; }
194
+ .empty-state p { margin: 0; line-height: 1.45; }
195
+ small, .muted { color: var(--pi-muted); }
196
+ @media (max-width: 1180px) { header { display: none; } }
197
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
198
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
199
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
200
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
201
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
202
+ .toolbar { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); }
203
+ .toolbar button { margin-left: auto; }
204
+ .stale { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); padding: 1px 6px; font-size: 12px; }
205
+ .split { flex: 1 1 auto; min-height: 0; display: grid; grid-template-rows: minmax(160px, 34%) minmax(0, 1fr); }
206
+ .list { min-height: 0; overflow: auto; border-bottom: 1px solid var(--pi-border); padding: 6px; }
207
+ .row { display: grid; grid-template-columns: 18px minmax(0, 1fr); gap: 4px; width: 100%; border: 0; border-radius: 5px; background: transparent; text-align: left; padding: 4px 6px 4px calc(6px + var(--depth, 0) * 14px); }
208
+ .row:hover, .row.selected { background: var(--pi-selection-bg); }
209
+ .row span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
210
+ .summary { margin: 4px 6px 8px; color: var(--pi-muted); }
211
+ .viewer { min-height: 0; overflow: auto; display: flex; flex-direction: column; }
212
+ .diffs { flex: 1 1 auto; min-height: 0; overflow: auto; display: grid; grid-template-rows: minmax(120px, 1fr) minmax(120px, 1fr); }
213
+ .diffs.single { grid-template-rows: minmax(0, 1fr); }
214
+ .diff-section { min-height: 0; display: flex; flex-direction: column; border-bottom: 1px solid var(--pi-border); }
215
+ .diff-section:last-child { border-bottom: 0; }
216
+ .viewer-header { position: sticky; top: 0; display: flex; justify-content: space-between; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
217
+ .viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
218
+ code-viewer, unified-diff-viewer { flex: 1 1 auto; min-height: 0; }
219
+ .image-preview { flex: 1 1 auto; min-height: 0; box-sizing: border-box; display: flex; align-items: center; justify-content: center; overflow: auto; padding: 16px; }
220
+ .image-preview img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; border: 1px solid var(--pi-border-muted); border-radius: 8px; background-color: var(--pi-surface); background-image: linear-gradient(45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(-45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%), linear-gradient(-45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%); background-position: 0 0, 0 8px, 8px -8px, -8px 0; background-size: 16px 16px; box-shadow: 0 8px 24px var(--pi-shadow-soft); }
221
+ pre { margin: 0; padding: 10px; overflow: auto; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
222
+ p { margin: 10px; }
223
+ `,ws=D`
224
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
225
+ :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
226
+ section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
227
+ h2 { flex: 0 0 auto; display: flex; justify-content: space-between; align-items: center; gap: 8px; margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
228
+ .list-body { flex: 1 1 auto; min-height: 0; overflow: auto; }
229
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
230
+ section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
231
+ .subheading { margin-top: 14px; }
232
+ .section-toggle { display: flex; flex: 1 1 auto; min-width: 0; align-items: center; justify-content: space-between; gap: 8px; width: 100%; border: 0; background: transparent; color: inherit; padding: 0; font: inherit; text-align: left; text-transform: inherit; }
233
+ .section-toggle span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
234
+ .section-title { display: grid; gap: 2px; min-width: 0; }
235
+ .section-toggle .section-selected { display: block; color: var(--pi-text); font-size: 12px; font-weight: 600; line-height: 1.25; text-transform: none; }
236
+ .section-toggle .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
237
+ .section-toggle small { display: inline; color: inherit; font-size: inherit; }
238
+ .action-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 6px 0; cursor: pointer; }
239
+ .action-row:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; border-radius: 8px; }
240
+ .action-row.selected .action-main, .action-row.selected .action-menu-toggle { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
241
+ .action-row.archived .action-main { color: var(--pi-muted); }
242
+ .action-main { position: relative; box-sizing: border-box; min-width: 0; width: 100%; border: 1px solid var(--pi-border); border-top-right-radius: 0; border-bottom-right-radius: 0; border-top-left-radius: 8px; border-bottom-left-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 22px 7px calc(9px + var(--depth, 0) * 16px); text-align: left; }
243
+ .action-name { display: -webkit-box; max-height: 2.5em; overflow: hidden; overflow-wrap: anywhere; line-height: 1.25; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
244
+ .action-row:not(.selected):hover .action-main { background: var(--pi-surface-hover); }
245
+ .workspace-row .action-main { border-radius: 8px 0 0 8px; }
246
+ .workspace-primary { min-width: 0; display: flex; align-items: baseline; gap: 6px; }
247
+ .workspace-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
248
+ .workspace-status { flex: 0 0 auto; color: var(--pi-warning); font-size: 12px; }
249
+ .workspace-secondary { margin-top: 3px; }
250
+ .workspace-menu-panel { width: max-content; min-width: min(120px, calc(100vw - 16px)); padding: 8px; }
251
+ .workspace-menu-actions { margin: 0 0 8px; padding-bottom: 8px; border-bottom: 1px solid var(--pi-border-muted); }
252
+ .workspace-menu-actions button.danger { color: var(--pi-danger); }
253
+ .workspace-menu-actions button.danger:hover, .workspace-menu-actions button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
254
+ .workspace-menu-details { display: grid; gap: 6px; margin: 0; }
255
+ .workspace-detail-row { display: grid; grid-template-columns: minmax(58px, max-content) minmax(0, 1fr); gap: 8px; align-items: baseline; }
256
+ .workspace-detail-row dt { color: var(--pi-muted); font-size: 12px; white-space: normal; }
257
+ .workspace-detail-row dd { min-width: 0; margin: 0; overflow-wrap: anywhere; white-space: normal; }
258
+ .tree-marker { color: var(--pi-dim); margin-right: 5px; }
259
+ .badge { display: inline-block; margin-left: 5px; border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); padding: 0 5px; font-size: 11px; font-weight: 400; }
260
+ .action-activity { position: absolute; top: 5px; right: 6px; z-index: 1; display: grid; place-items: center; width: 10px; height: 10px; }
261
+ .action-activity .activity-indicator { margin: 0; vertical-align: 0; }
262
+ .activity-indicator { display: inline-block; width: 7px; height: 7px; margin-right: 6px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; vertical-align: 1px; }
263
+ .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
264
+ .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
265
+ /* Client-side sending (upload in flight); distinct from server activity, which propagates to workspace/machine rows. */
266
+ .activity-indicator.sending { border-radius: 50%; background: var(--pi-warning); }
267
+ .action-menu { position: relative; align-self: stretch; }
268
+ .action-menu-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0; }
269
+ .action-menu-toggle:hover { color: var(--pi-text); background: var(--pi-surface-hover); }
270
+ .action-menu-panel { position: fixed; z-index: 50; box-sizing: border-box; min-width: min(120px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); overflow-wrap: anywhere; }
271
+ .action-menu-panel button { display: block; width: 100%; text-align: left; white-space: normal; overflow-wrap: anywhere; border: 0; background: transparent; color: var(--pi-text); }
272
+ .action-menu-panel button:hover { background: var(--pi-selection-bg); }
273
+ button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
274
+ button:disabled { opacity: .5; cursor: not-allowed; }
275
+ small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
276
+ .workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
277
+ .workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
278
+ .workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
279
+ .workspace-label-link { color: var(--pi-accent); text-decoration: none; }
280
+ .workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
281
+ .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
282
+ .workspace-detail-row .workspace-label-base, .workspace-detail-row .workspace-label-item, .workspace-detail-row .workspace-label-render { overflow: visible; text-overflow: clip; overflow-wrap: anywhere; white-space: normal; }
283
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
284
+ `,bg=D`
285
+ :host { position: relative; z-index: 0; display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
286
+ .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
287
+ .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; max-width: 800px; margin: 0 auto; width: 100%; }
288
+ .scroll-marker { display: block; height: 0; overflow: hidden; pointer-events: none; }
289
+ .activity-dock { position: absolute; left: 16px; right: 16px; bottom: 12px; z-index: 20; display: flex; align-items: center; gap: 8px; min-width: 0; box-sizing: border-box; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-bg-overlay); color: var(--pi-muted); padding: 8px 12px; font-size: 13px; pointer-events: none; box-shadow: 0 8px 28px var(--pi-shadow); backdrop-filter: blur(6px); }
290
+ .activity-dock.active { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-bg-overlay); }
291
+ .activity-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
292
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
293
+ .activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
294
+ .msg { max-width: 100%; min-width: 0; box-sizing: border-box; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); overflow: visible; }
295
+ .msg.assistant { background: var(--pi-surface); }
296
+ .msg.user { border-color: var(--pi-accent-border); background: var(--pi-selection-bg); }
297
+ .msg.tool { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
298
+ .msg.tool-execution-shell { padding: 0; border: 0; background: transparent; color: var(--pi-text); }
299
+ .msg.system { color: var(--pi-danger); }
300
+ .msg.bash { border-color: var(--pi-success); background: var(--pi-success-bg); }
301
+ .msg.skill { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
302
+ .msg.event-group { padding: 0; border-color: var(--pi-border); background: var(--pi-bg); color: var(--pi-muted); }
303
+ .msg.event-group.live { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
304
+ .msg.event-group > summary { position: sticky; top: -26px; z-index: 5; display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 9px 9px 0 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); color: var(--pi-muted); }
305
+ .msg.event-group.live > summary { border-bottom-color: var(--pi-success-border); background: var(--pi-success-bg); color: var(--pi-success); }
306
+ .msg.event-group > summary .label { margin: 0; }
307
+ .group-body { padding: 0 12px 12px; }
308
+ .chat-image { display: block; max-width: 100%; max-height: 320px; margin: 8px 0 0; border: 1px solid var(--pi-border-muted); border-radius: 8px; object-fit: contain; }
309
+ .group-msg { max-width: 100%; min-width: 0; box-sizing: border-box; padding: 10px 0; border-top: 1px solid var(--pi-border-muted); color: var(--pi-text); overflow: visible; }
310
+ .group-msg.tool { color: var(--pi-warning); }
311
+ .group-msg.tool-execution-shell { color: var(--pi-text); }
312
+ .group-msg.system { color: var(--pi-danger); }
313
+ .group-msg.bash { color: var(--pi-success); }
314
+ .history-boundary { position: relative; z-index: 5; display: grid; gap: 3px; justify-items: center; margin: 0 0 14px; color: var(--pi-muted); font-size: 12px; text-align: center; }
315
+ .history-load-button { border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text-secondary); padding: 5px 12px; font: 12px system-ui, sans-serif; cursor: pointer; }
316
+ .history-load-button:hover, .history-load-button:focus { border-color: var(--pi-accent); color: var(--pi-text-bright); }
317
+ .history-load-button:disabled { cursor: default; opacity: .55; }
318
+ .queued-messages { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 8px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-warning-border); border-radius: 10px; background: var(--pi-warning-surface); color: var(--pi-text); overflow: hidden; }
319
+ .queued-header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
320
+ .queued-header strong { color: var(--pi-warning); }
321
+ .queued-header small { color: var(--pi-muted); }
322
+ .queued-message { display: grid; gap: 4px; padding-top: 8px; border-top: 1px solid var(--pi-border); }
323
+ .queued-message:first-of-type { padding-top: 0; border-top: 0; }
324
+ .queued-kind { color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
325
+ .session-activity { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 4px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); color: var(--pi-text); overflow: hidden; }
326
+ .session-activity.compacting { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
327
+ .session-activity.receiving { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
328
+ .session-activity strong { color: var(--pi-purple); }
329
+ .session-activity.receiving strong { color: var(--pi-success); }
330
+ .session-activity span, .session-activity small { color: var(--pi-muted); }
331
+ .history-boundary small { color: var(--pi-dim); }
332
+ .msg-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 22px; margin-bottom: 8px; }
333
+ .msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -12px -12px 8px; padding: 7px 10px 6px; border-radius: 9px 9px 0 0; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-surface); box-shadow: 0 8px 18px var(--pi-shadow-soft); }
334
+ .msg.user > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-accent-border) 35%, transparent); background: var(--pi-selection-bg); }
335
+ .msg.assistant > .msg-header .label { color: var(--pi-text-secondary); }
336
+ .msg.user > .msg-header .label { color: var(--pi-accent); }
337
+ .msg.tool > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-warning-border) 35%, transparent); background: var(--pi-warning-surface); }
338
+ .msg.bash > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-success) 35%, transparent); background: var(--pi-success-bg); }
339
+ .msg.skill > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-purple-border) 35%, transparent); background: var(--pi-purple-surface); }
340
+ .group-msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -10px 0 8px; padding: 7px 0 6px; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-bg); }
341
+ .msg-header-trailing { min-width: 0; display: inline-flex; align-items: baseline; justify-content: flex-end; gap: 8px; }
342
+ .msg-actions { display: inline-flex; gap: 6px; opacity: 0; transition: opacity .12s ease; }
343
+ .msg-action { display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
344
+ .msg-action:hover, .msg-action:focus { color: var(--pi-text); border-color: var(--pi-accent); }
345
+ .msg:hover > .msg-header .msg-actions, .msg:focus-within > .msg-header .msg-actions, .group-msg:hover > .msg-header .msg-actions, .group-msg:focus-within > .msg-header .msg-actions { opacity: 1; }
346
+ .label { display: block; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
347
+ .msg-header .label { margin: 0; }
348
+ .msg-meta { min-width: 0; opacity: .28; border: 0; background: transparent; color: var(--pi-dim); padding: 0; font: 11px system-ui, sans-serif; text-align: right; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: opacity .12s ease, max-width .12s ease; cursor: pointer; user-select: text; -webkit-user-select: text; }
349
+ .msg:hover > .msg-header .msg-meta, .msg:focus-within > .msg-header .msg-meta, .group-msg:hover > .msg-header .msg-meta, .group-msg:focus-within > .msg-header .msg-meta, .msg-meta:focus, .msg-meta.expanded { opacity: 1; }
350
+ .msg-meta:focus { outline: 1px solid var(--pi-border); outline-offset: 3px; border-radius: 4px; }
351
+ @media (hover: none) {
352
+ .msg-actions { opacity: 1; }
353
+ .msg-meta { opacity: .75; max-width: 26px; }
354
+ .msg-meta::before { content: "ⓘ"; font-size: 13px; }
355
+ .msg-meta:focus, .msg-meta.expanded { opacity: 1; max-width: 75%; }
356
+ .msg-meta:focus::before, .msg-meta.expanded::before { content: ""; }
357
+ }
358
+ formatted-text.part { display: block; }
359
+ formatted-text.part, .queued-message formatted-text { text-align: start; unicode-bidi: plaintext; }
360
+ .part { max-width: 100%; min-width: 0; box-sizing: border-box; overflow: visible; }
361
+ .part + .part { margin-top: 10px; }
362
+ .tool-line { color: var(--pi-warning); }
363
+ .summary { color: var(--pi-muted); margin-left: 6px; }
364
+ .part:is(details) { border-top: 1px solid var(--pi-border); padding-top: 8px; }
365
+ .part > formatted-text { display: block; max-width: 100%; min-width: 0; overflow: visible; }
366
+ .skill-invocation, .skill-read { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); padding: 8px 10px; }
367
+ .skill-invocation > summary, .skill-read > strong { color: var(--pi-purple); }
368
+ .skill-invocation > small, .skill-read > small { display: block; margin: 6px 0 0; color: var(--pi-muted); }
369
+ summary { cursor: pointer; color: var(--pi-muted); }
370
+ pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; direction: ltr; text-align: left; unicode-bidi: isolate; }
371
+ .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; direction: ltr; text-align: left; unicode-bidi: isolate; }
372
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
373
+ `,wg=D`
374
+ :host { display: block; }
375
+ .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; text-align: start; unicode-bidi: plaintext; }
376
+ p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
377
+ :is(p, ul, ol, pre, blockquote, table, .code-block-wrapper):last-child { margin-bottom: 0; }
378
+ ul, ol { padding-left: 22px; }
379
+ li + li { margin-top: 3px; }
380
+ code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-bg); padding: 1px 4px; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; direction: ltr; text-align: left; unicode-bidi: isolate; }
381
+ .code-block-wrapper { position: relative; }
382
+ .code-block-wrapper pre { margin: 0; padding-right: 40px; }
383
+ pre { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 10px; overflow-x: auto; overflow-y: hidden; direction: ltr; text-align: left; unicode-bidi: isolate; }
384
+ pre code { border: 0; padding: 0; background: transparent; }
385
+ .code-copy-button { position: absolute; top: 6px; right: 6px; z-index: 1; display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
386
+ .code-copy-button:hover, .code-copy-button:focus { color: var(--pi-text); border-color: var(--pi-accent); }
387
+ blockquote { border-left: 3px solid var(--pi-border); padding-left: 10px; color: var(--pi-muted); }
388
+ a { color: var(--pi-accent); }
389
+ h1, h2, h3, h4 { margin: 14px 0 8px; line-height: 1.2; }
390
+ h1:first-child, h2:first-child, h3:first-child, h4:first-child { margin-top: 0; }
391
+ h1 { font-size: 20px; }
392
+ h2 { font-size: 17px; }
393
+ h3 { font-size: 15px; }
394
+ h4 { font-size: 14px; }
395
+ table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
396
+ th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
397
+ th { background: var(--pi-surface); }
398
+ `,yg=D`
399
+ :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
400
+ .bar { display: flex; justify-content: flex-end; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
401
+ span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
402
+ .activity { display: inline-flex; align-items: center; gap: 6px; color: var(--pi-muted); }
403
+ .activity.active { color: var(--pi-success); }
404
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
405
+ .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
406
+ .muted { color: var(--pi-dim); }
407
+ @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
408
+ `,Sg=D`
409
+ :host { display: block; }
410
+ .menu { position: absolute; left: 0; right: 0; bottom: calc(100% + 6px); z-index: 10; max-height: 260px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 10px 30px var(--pi-shadow); }
411
+ button { display: grid; grid-template-columns: minmax(120px, 1fr) auto; gap: 4px 10px; width: 100%; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; cursor: pointer; }
412
+ button:last-child { border-bottom: 0; }
413
+ button.selected, button:hover { background: var(--pi-selection-bg); }
414
+ span { color: var(--pi-muted); font-size: 12px; }
415
+ small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
416
+ `,xl=D`
417
+ :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
418
+ .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
419
+ section { width: min(720px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
420
+ header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
421
+ .options { min-height: 0; overflow: auto; outline: none; }
422
+ button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
423
+ header button { font-size: 20px; color: var(--pi-muted); }
424
+ input { margin: 10px 12px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); font: var(--pi-control-font-size, 16px) var(--pi-control-font-family, system-ui, sans-serif); padding: 8px 10px; outline: none; }
425
+ input:focus { border-color: var(--pi-accent); }
426
+ .options button { display: block; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
427
+ .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
428
+ small { display: block; margin-top: 4px; color: var(--pi-muted); }
429
+ .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
430
+ `,xg=D`
431
+ :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
432
+ .backdrop { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); display: grid; align-items: start; justify-items: center; width: 100%; height: 100dvh; background: var(--pi-overlay); padding: var(--palette-top) 20px var(--palette-bottom); box-sizing: border-box; overflow: hidden; }
433
+ section { width: min(720px, 100%); max-height: min(640px, calc(100dvh - var(--palette-top) - var(--palette-bottom))); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
434
+ header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid var(--pi-border); }
435
+ input { min-width: 0; border: 0; outline: none; background: transparent; color: var(--pi-text); font: var(--pi-control-font-size, 16px) var(--pi-control-font-family, system-ui, sans-serif); padding: 8px; }
436
+ input::placeholder { color: var(--pi-dim); }
437
+ button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
438
+ header button { color: var(--pi-muted); font-size: 22px; padding: 2px 8px; }
439
+ .options { flex: 1 1 auto; min-height: 0; overflow: auto; }
440
+ .options button { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 3px 12px; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
441
+ .options button.selected, .options button:hover:not(:disabled) { background: var(--pi-selection-bg); }
442
+ .options button:disabled { cursor: not-allowed; opacity: .68; }
443
+ .options button.disabled.selected { background: color-mix(in srgb, var(--pi-selection-bg) 55%, transparent); }
444
+ .main { min-width: 0; }
445
+ strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
446
+ small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
447
+ .disabled-reason { color: var(--pi-warning); }
448
+ .group { grid-column: 1 / -1; font-size: 12px; }
449
+ kbd { align-self: center; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 2px 6px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
450
+ .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
451
+ `,kg=D`
452
+ :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
453
+ footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
454
+ footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
455
+ .editor-wrap { position: relative; min-width: 0; }
456
+ .actions { display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: nowrap; white-space: nowrap; }
457
+ .compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: var(--pi-muted); font-size: 12px; flex: 1 1 0; }
458
+ .compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
459
+ .select-model { max-width: min(42vw, 320px); }
460
+ .icon-button { flex: 0 0 auto; display: inline-grid; place-items: center; width: 36px; height: 36px; padding: 0; }
461
+ .icon-button .prompt-action-icon, .icon-button .prompt-thinking-gauge { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
462
+ .icon-button .prompt-action-icon-filled { fill: currentColor; stroke: none; }
463
+ .send-button:not(:disabled) { color: var(--pi-accent, var(--pi-text)); }
464
+ .stop-button:not(:disabled) { color: var(--pi-danger); }
465
+ .select-thinking .prompt-thinking-gauge .gauge-bar { fill: currentColor; stroke: none; opacity: .28; }
466
+ .select-thinking .prompt-thinking-gauge .gauge-bar-active { opacity: 1; }
467
+ .editor-attach { position: absolute; right: 8px; bottom: 8px; z-index: 2; width: 30px; height: 30px; }
468
+ .editor-attach .prompt-action-icon { width: 16px; height: 16px; }
469
+ textarea, .markdown-editor .cm-editor { box-sizing: border-box; width: 100%; min-height: 54px; max-height: 220px; resize: none; overflow: hidden; border-radius: 8px; border: 1px solid var(--pi-border); background: var(--pi-bg); color: var(--pi-text); font: var(--pi-control-font-size, 16px)/1.4 var(--pi-control-font-family, system-ui, sans-serif); }
470
+ textarea { overflow-y: auto; padding: 8px; }
471
+ .markdown-editor .cm-scroller { max-height: 220px; overflow-y: auto; font-family: var(--pi-control-font-family, system-ui, sans-serif); line-height: 1.4; }
472
+ .markdown-editor .cm-content { min-height: 38px; padding: 8px 44px 8px 8px; caret-color: var(--pi-text); text-align: start; unicode-bidi: plaintext; }
473
+ .markdown-editor .cm-line { padding: 0; unicode-bidi: plaintext; }
474
+ .markdown-editor .cm-placeholder { color: var(--pi-dim); }
475
+ .markdown-editor .cm-focused { outline: none; }
476
+ .shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: var(--pi-success); box-shadow: 0 0 0 1px var(--pi-success-ring); }
477
+ .mode-hint { position: absolute; right: 46px; bottom: 8px; max-width: calc(100% - 54px); border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 2px 8px; font-size: 12px; pointer-events: none; }
478
+ .attachments { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 8px; }
479
+ .attachment-chip { position: relative; width: 56px; height: 56px; border: 1px solid var(--pi-border); border-radius: 8px; overflow: hidden; background: var(--pi-bg); }
480
+ .attachment-chip img { width: 100%; height: 100%; object-fit: cover; display: block; }
481
+ .attachment-chip-file { display: grid; place-items: center; }
482
+ .attachment-file-preview { display: grid; place-items: center; width: 34px; height: 26px; border: 1px solid var(--pi-border-muted); border-radius: 4px; background: var(--pi-surface); color: var(--pi-muted); font: 700 10px/1 system-ui, sans-serif; letter-spacing: .03em; }
483
+ .attachment-file-name { position: absolute; right: 4px; bottom: 3px; left: 4px; overflow: hidden; color: var(--pi-muted); font-size: 10px; line-height: 1.2; text-align: center; text-overflow: ellipsis; white-space: nowrap; }
484
+ .attachment-remove { position: absolute; top: 1px; right: 1px; width: 18px; height: 18px; padding: 0; line-height: 16px; border-radius: 50%; border: 1px solid var(--pi-border); background: var(--pi-surface); color: var(--pi-text); font-size: 13px; cursor: pointer; }
485
+ .attachment-delivery select { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; font: var(--pi-control-font-size, 16px) var(--pi-control-font-family, system-ui, sans-serif); }
486
+ .attachment-error { flex-basis: 100%; color: var(--pi-danger); font-size: 12px; }
487
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
488
+ button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
489
+ @media (max-width: 640px) {
490
+ footer { gap: 8px; padding: 8px; }
491
+ .actions { gap: 6px; }
492
+ .compact-status { flex: 1 1 220px; gap: 4px; }
493
+ .select-model { max-width: min(58vw, 260px); }
494
+ button { padding: 6px 8px; }
495
+ }
496
+ @media (max-width: 430px) {
497
+ .compact-status { flex-basis: 170px; font-size: 11px; }
498
+ .select-model { max-width: 48vw; }
499
+ button { padding: 5px 7px; }
500
+ .icon-button { width: 34px; height: 34px; }
501
+ }
502
+ `;var $g=Object.defineProperty,Pg=Object.getOwnPropertyDescriptor,et=(e,t,i,s)=>{for(var r=s>1?void 0:s?Pg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$g(t,i,r),r};let _e=class extends I{constructor(){super(...arguments),this.destinationFolder="",this.overwrite=!1,this.createDirs=!0,this.formError="",this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,i=t?.files?Array.from(t.files):[];t!==void 0&&(t.value=""),i.length>0&&this.openUploadReview(i)},this.handleDragEnter=e=>{$i(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{$i(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect="copy"),this.dragActive=!0)},this.handleDragLeave=e=>{$i(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!$i(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;const t=e.dataTransfer?.files?Array.from(e.dataTransfer.files):[],i=this.context;t.length>0&&i!==void 0&&Ig(i,t)},this.handleDestinationInput=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??"",this.formError=""},this.handleCreateDirsChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key==="Escape"&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has("context"))return;const t=e.get("context");t!==void 0&&this.context!==void 0&&Pn(t)!==Pn(this.context)&&this.resetPendingUpload()}render(){const e=this.context;return e===void 0?l`<p class="muted">Files unavailable.</p>`:l`
503
+ <section
504
+ class=${this.dragActive?"files-panel dragging":"files-panel"}
505
+ @dragenter=${this.handleDragEnter}
506
+ @dragover=${this.handleDragOver}
507
+ @dragleave=${this.handleDragLeave}
508
+ @drop=${this.handleDrop}
509
+ >
510
+ <section class="toolbar">
511
+ <strong>Files</strong>
512
+ ${e.fileTreeStale?l`<span class="stale">stale</span>`:null}
513
+ <div class="toolbar-actions">
514
+ <button @click=${this.openFilePicker}>Upload</button>
515
+ <button @click=${e.onRefreshFiles}>Refresh</button>
516
+ </div>
517
+ <input id="workspace-upload-input" class="visually-hidden" type="file" multiple @change=${this.handleFileInputChange} />
518
+ </section>
519
+ ${this.renderUploadProgress(e)}
520
+ <section class="split">
521
+ <div class="list tree">
522
+ ${e.fileTree.length===0?l`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>this.renderTreeEntry(e,t,0))}
523
+ </div>
524
+ <div class="viewer">
525
+ ${this.renderFileViewer(e)}
526
+ </div>
527
+ </section>
528
+ <div class="drop-overlay" aria-hidden=${this.dragActive?"false":"true"}>
529
+ <div>
530
+ <strong>Drop files to upload</strong>
531
+ <span>Uploads immediately to the default folder.</span>
532
+ </div>
533
+ </div>
534
+ ${this.pendingUpload===void 0?null:this.renderUploadDialog(e,this.pendingUpload)}
535
+ </section>
536
+ `}renderTreeEntry(e,t,i){const s=e.expandedDirs[t.path],r=s!==void 0,o=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
537
+ <button class=${o?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{this.selectTreeEntry(e,t)}}>
538
+ <span>${t.type==="directory"?r?"▾":"▸":"·"}</span>
539
+ <span>${t.name}</span>
540
+ </button>
541
+ ${r?s.map(n=>this.renderTreeEntry(e,n,i+1)):null}
542
+ `}selectTreeEntry(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}renderFileViewer(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">Select a file.</p>`:e.state.error!==""&&t===void 0?l`
543
+ <div class="viewer-header"><strong>${e.selectedFilePath}</strong><small>Error</small></div>
544
+ <p class="muted dialog-error" style="margin: 16px;">${e.state.error}</p>
545
+ `:t===void 0?l`<p class="muted">Loading ${e.selectedFilePath}…</p>`:t.mediaType==="image"?this.renderImageViewer(e,t):t.binary?l`<p class="muted">Binary file: ${t.path} · ${Et(t.size)}</p>`:(Og(),l`
546
+ <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"text"}${t.truncated?" · truncated":""}</small></div>
547
+ <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
548
+ `)}renderImageViewer(e,t){const i=`${t.mimeType??"image"} · ${Et(t.size)}`;if(t.size>gg)return l`
549
+ <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
550
+ <p class="muted">Image too large to preview: ${Et(t.size)} · limit ${mg}</p>
551
+ `;const s=Wp(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
552
+ <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
553
+ <div class="image-preview">
554
+ <img src=${s} alt=${t.path} decoding="async" />
555
+ </div>
556
+ `}renderUploadProgress(e){const t=Cg(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:l`
557
+ <section class="upload-progress" aria-label="Workspace uploads">
558
+ <div class="upload-progress-header">
559
+ <strong>Uploads</strong>
560
+ <small>${Tg(t)}</small>
561
+ </div>
562
+ ${t.map(i=>this.renderUploadBatch(e,i))}
563
+ </section>
564
+ `}renderUploadBatch(e,t){return l`
565
+ <article class=${`upload-batch ${t.status}`}>
566
+ <div class="upload-batch-heading">
567
+ <div>
568
+ <strong>${Ag(t)}</strong>
569
+ <small>${t.destinationFolder===""?"workspace root":t.destinationFolder}</small>
570
+ </div>
571
+ <span>${Eg(t)}</span>
572
+ </div>
573
+ <progress max="1" .value=${Dg(t)}></progress>
574
+ <div class="upload-file-list">
575
+ ${t.files.map(i=>this.renderUploadFile(i))}
576
+ </div>
577
+ <div class="upload-actions">
578
+ ${t.status==="uploading"?l`<button @click=${()=>{e.onCancelWorkspaceUpload(t.id)}}>Cancel</button>`:l`<button @click=${()=>{e.onClearWorkspaceUpload(t.id)}}>Dismiss</button>`}
579
+ </div>
580
+ </article>
581
+ `}renderUploadFile(e){const t=Lg(e);return l`
582
+ <div class=${`upload-file ${e.status}`}>
583
+ <div class="upload-file-main">
584
+ <span>${e.name}</span>
585
+ <small>${t}</small>
586
+ </div>
587
+ <span class="upload-file-status">${Wg(e)}</span>
588
+ </div>
589
+ `}renderUploadDialog(e,t){const i=t.files.length;return l`
590
+ <div class="dialog-backdrop" @mousedown=${()=>{this.closeUploadDialog()}}>
591
+ <section class="upload-dialog" role="dialog" aria-modal="true" aria-label="Review file upload" @mousedown=${s=>{s.stopPropagation()}} @keydown=${this.handleDialogKeyDown}>
592
+ <header>
593
+ <div>
594
+ <span class="eyebrow">Upload</span>
595
+ <h2>Review ${i===1?"file":`${String(i)} files`}</h2>
596
+ </div>
597
+ <button class="close-button" title="Cancel upload" aria-label="Cancel upload" @click=${()=>{this.closeUploadDialog()}}>×</button>
598
+ </header>
599
+ <form @submit=${s=>{this.submitUploadReview(s,e,t)}}>
600
+ <label>
601
+ <span>Destination folder</span>
602
+ <input .value=${this.destinationFolder} placeholder=${e.workspaceUploadDefaultFolder} @input=${this.handleDestinationInput} />
603
+ <small>Workspace-relative. Leave empty to upload at the workspace root.</small>
604
+ </label>
605
+ <div class="dialog-options">
606
+ <label>
607
+ <input type="checkbox" .checked=${this.createDirs} @change=${this.handleCreateDirsChange} />
608
+ <span>Create parent folders</span>
609
+ </label>
610
+ <label>
611
+ <input type="checkbox" .checked=${this.overwrite} @change=${this.handleOverwriteChange} />
612
+ <span>Overwrite existing files</span>
613
+ </label>
614
+ </div>
615
+ <section class="review-files" aria-label="Files to upload">
616
+ <strong>${i===1?"File":"Files"}</strong>
617
+ ${t.files.map(s=>l`
618
+ <div class="review-file">
619
+ <span>${s.name}</span>
620
+ <small>${Et(s.size)}</small>
621
+ </div>
622
+ `)}
623
+ </section>
624
+ ${this.formError===""?null:l`<div class="dialog-error" role="alert">${this.formError}</div>`}
625
+ <footer>
626
+ <button type="button" @click=${()=>{this.closeUploadDialog()}}>Cancel</button>
627
+ <button type="submit">Upload</button>
628
+ </footer>
629
+ </form>
630
+ </section>
631
+ </div>
632
+ `}openUploadReview(e){const t=this.context,i=Mg(t?.workspaceUploadDefaultFolder??"");this.pendingUpload={files:e},this.destinationFolder=i.destinationFolder,this.overwrite=i.overwrite,this.createDirs=i.createDirs,this.formError=""}submitUploadReview(e,t,i){e.preventDefault();const s=Rg(i.files,this.destinationFolder);if(s!==void 0){this.formError=s;return}t.onStartWorkspaceUpload(i.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=""}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}};_e.styles=[Kr,D`
633
+ :host { flex: 1 1 auto; }
634
+ .files-panel { position: relative; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
635
+ .toolbar-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
636
+ .toolbar .toolbar-actions button { margin-left: 0; }
637
+ .visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
638
+ .drop-overlay { position: absolute; inset: 52px 10px 10px; z-index: 15; display: grid; place-items: center; border: 2px dashed var(--pi-accent); border-radius: 12px; background: color-mix(in srgb, var(--pi-bg-overlay) 90%, var(--pi-accent) 10%); color: var(--pi-text); opacity: 0; pointer-events: none; transition: opacity .12s ease; }
639
+ .files-panel.dragging .drop-overlay { opacity: 1; }
640
+ .drop-overlay div { display: grid; gap: 4px; justify-items: center; padding: 18px; border-radius: 10px; background: var(--pi-bg-overlay); box-shadow: 0 8px 24px var(--pi-shadow); }
641
+ .drop-overlay span { color: var(--pi-muted); }
642
+ .upload-progress { flex: 0 0 auto; display: grid; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); background: color-mix(in srgb, var(--pi-surface) 55%, transparent); }
643
+ .upload-progress-header, .upload-batch-heading, .upload-actions { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
644
+ .upload-batch { display: grid; gap: 6px; border: 1px solid var(--pi-border-muted); border-radius: 8px; background: var(--pi-bg); padding: 8px; }
645
+ .upload-batch.error { border-color: var(--pi-danger); }
646
+ .upload-batch.cancelled { border-color: var(--pi-warning-border); }
647
+ .upload-batch.completed { border-color: var(--pi-success-border); }
648
+ .upload-batch-heading > div { min-width: 0; display: grid; gap: 2px; }
649
+ .upload-batch-heading strong, .upload-batch-heading small { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
650
+ progress { width: 100%; accent-color: var(--pi-accent); }
651
+ .upload-file-list { display: grid; gap: 4px; max-height: 180px; overflow: auto; padding-right: 2px; }
652
+ .upload-file { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px; color: var(--pi-muted); }
653
+ .upload-file.completed .upload-file-status { color: var(--pi-success); }
654
+ .upload-file.error { color: var(--pi-danger); }
655
+ .upload-file.cancelled .upload-file-status { color: var(--pi-warning); }
656
+ .upload-file-main { min-width: 0; display: grid; gap: 1px; }
657
+ .upload-file-main span, .upload-file-main small { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
658
+ .upload-file-status { font-size: 12px; white-space: nowrap; }
659
+ .upload-actions { justify-content: end; }
660
+ .dialog-backdrop { position: fixed; inset: 0; z-index: 100; box-sizing: border-box; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); }
661
+ .upload-dialog { box-sizing: border-box; width: min(560px, 100%); max-height: min(720px, 100%); display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 18px 70px var(--pi-shadow-strong); }
662
+ .upload-dialog header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border-muted); }
663
+ .upload-dialog h2 { margin: 2px 0 0; font-size: 18px; line-height: 1.2; }
664
+ .eyebrow { color: var(--pi-muted); font-size: 11px; letter-spacing: .08em; text-transform: uppercase; }
665
+ .close-button { font-size: 20px; line-height: 1; padding: 4px 9px; }
666
+ form { min-height: 0; display: flex; flex-direction: column; gap: 12px; overflow: auto; padding: 16px; }
667
+ form > label { display: grid; gap: 6px; }
668
+ form > label > span, .review-files > strong { font-weight: 600; }
669
+ input[type="text"], form > label > input:not([type]) { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 8px 9px; font: var(--pi-control-font-size, 16px) var(--pi-control-font-family, system-ui, sans-serif); }
670
+ input:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 1px; }
671
+ .dialog-options { display: grid; gap: 8px; }
672
+ .dialog-options label { display: flex; align-items: center; gap: 8px; color: var(--pi-text); }
673
+ .review-files { display: grid; gap: 6px; min-height: 0; max-height: 180px; overflow: auto; border: 1px solid var(--pi-border-muted); border-radius: 8px; padding: 8px; }
674
+ .review-file { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: baseline; }
675
+ .review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
676
+ .dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; overflow-wrap: anywhere; }
677
+ footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
678
+ `];et([d({attribute:!1})],_e.prototype,"context",2);et([K("#workspace-upload-input")],_e.prototype,"uploadInput",2);et([v()],_e.prototype,"pendingUpload",2);et([v()],_e.prototype,"destinationFolder",2);et([v()],_e.prototype,"overwrite",2);et([v()],_e.prototype,"createDirs",2);et([v()],_e.prototype,"formError",2);et([v()],_e.prototype,"dragActive",2);_e=et([E("workspace-files-panel")],_e);function Cg(e,t){return Object.values(e).filter(i=>i.projectId===t.projectId&&i.workspaceId===t.workspaceId&&i.machineId===t.machineId).sort((i,s)=>s.startedAt.localeCompare(i.startedAt))}function Rg(e,t){if(e.length===0)return"Choose at least one file to upload.";for(const i of e)try{Wr(t,i.name)}catch(s){return s instanceof Error?s.message:String(s)}}function Mg(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Ig(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Pn(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function $i(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function Tg(e){const t=e.filter(i=>i.status==="uploading").length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function Ag(e){const t=e.files.length,i=t===1?"file":"files";switch(e.status){case"completed":return`Uploaded ${String(t)} ${i}`;case"error":return`Upload failed for ${String(t)} ${i}`;case"cancelled":return`Upload cancelled for ${String(t)} ${i}`;case"uploading":return`Uploading ${String(t)} ${i}`}}function Eg(e){switch(e.status){case"completed":return"Done";case"error":return"Failed";case"cancelled":return"Cancelled";case"uploading":return kl(e.percent)}}function Dg(e){return e.status==="uploading"?e.percent:1}function Wg(e){switch(e.status){case"pending":return"Pending";case"uploading":return kl(e.percent);case"completed":return"Done";case"error":return"Error";case"cancelled":return"Cancelled"}}function Lg(e){return e.error!==void 0?e.error:e.response!==void 0?`Wrote ${e.response.path}`:`${e.path} · ${Et(e.loaded)} / ${Et(e.total)}`}function kl(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Og(){Hr(()=>import("./CodeViewer-Da66baHj.js"),__vite__mapDeps([0,1,2,3]))}function Et(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${Ns(t)} KB`;const i=t/1024;return i<1024?`${Ns(i)} MB`:`${Ns(i/1024)} GB`}function Ns(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var Fg=Object.defineProperty,_g=Object.getOwnPropertyDescriptor,$l=(e,t,i,s)=>{for(var r=s>1?void 0:s?_g(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Fg(t,i,r),r};let is=class extends I{get executions(){if(!this.context)return[];const e=this.context.state.messages;if(e.length===0)return[];const t=[];for(const i of e)for(const s of i.parts)s.type==="toolExecution"&&(s.toolName==="task"||s.toolName==="todo")&&t.push(s);return t}render(){const e=this.executions;return e.length===0?l`
679
+ <section class="panel-content">
680
+ <div class="empty-state" role="status">
681
+ <h2>No tasks</h2>
682
+ <p>Task tool and todo tool calls will appear here when used in the current session.</p>
683
+ </div>
684
+ </section>
685
+ `:l`
686
+ <section class="panel-content">
687
+ <div class="task-list">
688
+ ${e.map(t=>t.toolName==="task"?this.renderTask(t):this.renderTodo(t))}
689
+ </div>
690
+ </section>
691
+ `}renderTask(e){const t=Ug(e.args),i=t?.length??0;return l`
692
+ <details class="task-card ${e.status}">
693
+ <summary class="task-header">
694
+ <span class="status-icon" aria-hidden="true">${jg(e.status)}</span>
695
+ <span class="tool-badge task-badge">subagent</span>
696
+ <span class="task-summary">${e.summary||"Task"}</span>
697
+ <span class="task-meta">
698
+ ${i>0?l`<span class="subagent-count">${i} agent${i===1?"":"s"}</span>`:""}
699
+ <span class="status-badge ${e.status}">${Cn(e.status)}</span>
700
+ </span>
701
+ </summary>
702
+ <div class="task-body">
703
+ ${this.renderTaskContext(e)}
704
+ ${t?.map(s=>this.renderSubagent(s))}
705
+ ${typeof e.resultText=="string"&&e.resultText.length>0?l`<pre class="task-result">${e.resultText}</pre>`:""}
706
+ </div>
707
+ </details>
708
+ `}renderTodo(e){const t=typeof e.args=="object"&&e.args!==null?e.args:{},i=typeof t.op=="string"?t.op:"",s=typeof t.task=="string"?t.task:"",r=typeof t.phase=="string"?t.phase:"",n=i!==""?{init:"Initialized",start:"Started",done:"Completed",append:"Added",drop:"Removed"}[i]??i:"";return l`
709
+ <details class="todo-card ${e.status}">
710
+ <summary class="task-header">
711
+ <span class="status-icon" aria-hidden="true">${i==="done"?"✓":i==="init"?"○":"◈"}</span>
712
+ <span class="tool-badge todo-badge">todo</span>
713
+ <span class="task-summary">${s||r||n||"Todo"}</span>
714
+ <span class="task-meta">
715
+ ${n?l`<span class="todo-op">${n}</span>`:""}
716
+ <span class="status-badge ${e.status}">${Cn(e.status)}</span>
717
+ </span>
718
+ </summary>
719
+ <div class="task-body">
720
+ ${r?l`<div class="todo-phase">Phase: ${r}</div>`:""}
721
+ ${s?l`<div class="todo-task">${s}</div>`:""}
722
+ ${typeof e.resultText=="string"&&e.resultText.length>0?l`<pre class="task-result">${e.resultText}</pre>`:""}
723
+ </div>
724
+ </details>
725
+ `}renderTaskContext(e){if(typeof e.args!="object"||e.args===null)return null;const i=e.args.context;return typeof i!="string"||i===""?null:l`
726
+ <details class="context-section">
727
+ <summary class="context-header">Context</summary>
728
+ <div class="context-body">${i}</div>
729
+ </details>
730
+ `}renderSubagent(e){const t=e.id??e.description??"Sub-agent";return l`
731
+ <div class="subagent">
732
+ <span class="subagent-icon">◈</span>
733
+ <div class="subagent-info">
734
+ <div class="subagent-label">${t}</div>
735
+ ${typeof e.assignment=="string"&&e.assignment.length>0?l`<div class="subagent-assignment">${e.assignment}</div>`:""}
736
+ </div>
737
+ </div>
738
+ `}};is.styles=[Kr,D`
739
+ .task - list { padding: 8px; display: grid; gap: 8px; }
740
+ .task - card, .todo - card { border: 1px solid var(--pi - border); border - radius: 8px; background: var(--pi - surface); }
741
+ .task - card[open], .todo - card[open] { border - color: var(--pi - accent); }
742
+ .task - card.error, .todo - card.error { border - color: var(--pi - danger - border); }
743
+ .task - card.success, .todo - card.success { border - color: var(--pi - success - border); }
744
+ .task - header { display: flex; align - items: center; gap: 6px; padding: 8px 10px; cursor: pointer; user - select: none; }
745
+ .task - header:: -webkit - details - marker { display: none; }
746
+ .status - icon { flex: 0 0 auto; width: 18px; text - align: center; font - size: 14px; }
747
+ .task - card.running.status - icon, .todo - card.running.status - icon { color: var(--pi - accent); }
748
+ .task - card.success.status - icon, .todo - card.success.status - icon { color: var(--pi - success); }
749
+ .task - card.error.status - icon, .todo - card.error.status - icon { color: var(--pi - danger); }
750
+ .tool - badge { font - size: 10px; padding: 1px 4px; border - radius: 3px; font - weight: 600; text - transform: uppercase; letter - spacing: 0.3px; flex: 0 0 auto; }
751
+ .task - badge { background: color - mix(in srgb, var(--pi - accent) 14 %, transparent); color: var(--pi - accent); }
752
+ .todo - badge { background: color - mix(in srgb, var(--pi - success) 14 %, transparent); color: var(--pi - success); }
753
+ .task - summary { flex: 1 1 auto; min - width: 0; overflow: hidden; text - overflow: ellipsis; white - space: nowrap; font - weight: 600; font - size: 13px; }
754
+ .task - meta { flex: 0 0 auto; display: flex; align - items: center; gap: 6px; }
755
+ .subagent - count { color: var(--pi - muted); font - size: 11px; white - space: nowrap; }
756
+ .todo - op { color: var(--pi - muted); font - size: 11px; white - space: nowrap; }
757
+ .status - badge { font - size: 11px; padding: 1px 5px; border - radius: 4px; white - space: nowrap; }
758
+ .status - badge.running { background: color - mix(in srgb, var(--pi - accent) 14 %, transparent); color: var(--pi - accent); }
759
+ .status - badge.success { background: color - mix(in srgb, var(--pi - success) 14 %, transparent); color: var(--pi - success); }
760
+ .status - badge.error { background: color - mix(in srgb, var(--pi - danger) 14 %, transparent); color: var(--pi - danger); }
761
+ .status - badge.pending { background: color - mix(in srgb, var(--pi - muted) 14 %, transparent); color: var(--pi - muted); }
762
+ .task - body { padding: 0 10px 10px; display: grid; gap: 6px; }
763
+ .context - section { border: 1px solid var(--pi - border - muted); border - radius: 5px; }
764
+ .context - header { padding: 5px 8px; cursor: pointer; user - select: none; font - size: 11px; font - weight: 600; color: var(--pi - muted); }
765
+ .context - header:: -webkit - details - marker { display: none; }
766
+ .context - body { padding: 0 8px 8px; color: var(--pi - muted); font - size: 12px; line - height: 1.4; white - space: pre - wrap; overflow - wrap: anywhere; max - height: 120px; overflow: auto; }
767
+ .todo - phase { font - size: 11px; color: var(--pi - muted); }
768
+ .todo - task { font - size: 12px; font - weight: 600; padding: 4px 0; }
769
+ .subagent { display: flex; gap: 6px; padding: 6px 8px; border: 1px solid var(--pi - border - muted); border - radius: 5px; background: var(--pi - bg); align - items: flex - start; }
770
+ .subagent - icon { flex: 0 0 auto; color: var(--pi - accent); font - size: 12px; margin - top: 1px; }
771
+ .subagent - info { flex: 1 1 auto; min - width: 0; }
772
+ .subagent - label { font - weight: 600; font - size: 12px; overflow: hidden; text - overflow: ellipsis; white - space: nowrap; }
773
+ .subagent - assignment { color: var(--pi - muted); font - size: 11px; margin - top: 2px; display: -webkit - box; -webkit - line - clamp: 3; -webkit - box - orient: vertical; overflow: hidden; }
774
+ .task - result { margin: 0; padding: 8px; background: var(--pi - bg); border: 1px solid var(--pi - border - muted); border - radius: 5px; font: 12px ui - monospace, SFMono - Regular, Menlo, Consolas, monospace; line - height: 1.4; white - space: pre - wrap; overflow - wrap: anywhere; max - height: 200px; overflow: auto; }
775
+ `];$l([d({attribute:!1})],is.prototype,"context",2);is=$l([E("workspace-tasks-panel")],is);function jg(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Cn(e){return e==="success"?"done":e==="error"?"failed":e==="running"?"running":"pending"}function Ug(e){if(typeof e!="object"||e===null)return;const i=e.tasks;if(Array.isArray(i))return i.map(s=>{if(typeof s!="object"||s===null)return{};const r=s;return{...typeof r.id=="string"?{id:r.id}:{},...typeof r.description=="string"?{description:r.description}:{},...typeof r.assignment=="string"?{assignment:r.assignment}:{}}})}function Ng(){return[{id:"workspace.files",title:"Files",icon:ti("files"),order:10,render:Bg},{id:"workspace.git",title:"Git",icon:ti("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:qg},{id:"workspace.terminal",title:"Terminal",icon:ti("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:zg},{id:"workspace.tasks",title:"Tasks",icon:ti("tasks"),order:35,render:Qg}]}function Bg(e){return l`<workspace-files-panel .context=${e}></workspace-files-panel>`}function zg(e){return Gg(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function qg(e){const t=e.gitStatus;return l`
776
+ <section class="toolbar">
777
+ <strong>Git</strong>
778
+ ${e.gitStale?l`<span class="stale">stale</span>`:null}
779
+ <button @click=${e.onRefreshGit}>Refresh</button>
780
+ </section>
781
+ <section class="split">
782
+ <div class="list">
783
+ ${t===void 0?l`<p class="muted">No status loaded.</p>`:t.isGitRepo?l`
784
+ <p class="summary">${Jg(t)}</p>
785
+ ${t.files.length===0?l`<p class="muted">No changes.</p>`:t.files.map(i=>l`
786
+ <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
787
+ <span>${Zg(i.index,i.workingTree)}</span>
788
+ <span>${i.path}</span>
789
+ </button>
790
+ `)}
791
+ `:l`<p class="muted">Not a git repository.</p>`}
792
+ </div>
793
+ <div class="viewer">
794
+ ${Hg(e)}
795
+ </div>
796
+ </section>
797
+ `}function Hg(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">Select a changed file.</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">Loading diff…</p>`;const s=[i,t].filter(r=>r.diff!=="");return s.length===0?l`<p class="muted">No staged or unstaged diff.</p>`:l`
798
+ <div class=${s.length===1?"diffs single":"diffs"}>
799
+ ${s.map(r=>Kg(r))}
800
+ </div>
801
+ `}function Kg(e){return Vg(),l`
802
+ <section class="diff-section">
803
+ <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"staged":"unstaged"}${e.truncated?" · truncated":""}</small></div>
804
+ <unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
805
+ </section>
806
+ `}function Vg(){Hr(()=>import("./UnifiedDiffViewer-eK_kynTO.js"),__vite__mapDeps([4,1,2]))}function Gg(){Hr(()=>import("./TerminalPanel-Bj9an79F.js"),__vite__mapDeps([5,6,7,1,2]))}function Qg(e){return l`<workspace-tasks-panel .context=${e}></workspace-tasks-panel>`}function Jg(e){const t=e.branch??"detached",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function Zg(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const Xg={apiVersion:1,name:"PI WEB Core",activate:()=>({contributions:{actions:ng(),workspacePanels:Ng()}})},Yg={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},em={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#5a47b0","--pi-selection-bg":"#1d2547","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},tm={"--pi-bg":"#f7f1e6","--pi-surface":"#fff9ee","--pi-surface-hover":"#f0e6d6","--pi-terminal-bg":"#15131b","--pi-terminal-text":"#fff9ee","--pi-border":"#c9bca8","--pi-border-muted":"#d8cdbc","--pi-text":"#15131b","--pi-text-secondary":"#15131b","--pi-text-bright":"#15131b","--pi-muted":"#5f586a","--pi-dim":"#766f7e","--pi-accent":"#6430d8","--pi-accent-border":"#6430d8","--pi-selection-bg":"#eadff8","--pi-success":"#008c82","--pi-success-border":"#008c82","--pi-success-bg":"#e1f4ef","--pi-success-surface":"#d7f0ec","--pi-success-ring":"#008c8255","--pi-warning":"#b05f00","--pi-warning-border":"#b05f00","--pi-warning-surface":"#fff2d2","--pi-danger":"#b51d49","--pi-purple":"#6430d8","--pi-purple-border":"#6430d8","--pi-purple-surface":"#eadff8","--pi-overlay":"#15131b66","--pi-shadow-soft":"#15131b22","--pi-shadow":"#15131b33","--pi-shadow-strong":"#15131b44","--pi-bg-overlay-soft":"#f7f1e6dd","--pi-bg-overlay":"#f7f1e6e6","--pi-success-bg-overlay":"#e1f4efee","--pi-terminal-selection":"#8d7b64"},im={apiVersion:1,name:"PI WEB Themes",activate:()=>({contributions:{themes:[{id:"omp-web-dark",name:"PI WEB Dark",description:"Dark PI WEB palette.",order:10,colorScheme:"dark",tokens:em},{id:"omp-web-light",name:"PI WEB Light",description:"Light PI WEB palette.",order:20,colorScheme:"light",tokens:tm},{id:"classic",name:"PI WEB Classic",description:"The original PI WEB dark palette.",order:30,colorScheme:"dark",tokens:Yg}],themePairs:[{id:"omp-web",name:"PI WEB",description:"Follow the system light/dark preference with PI WEB themes.",order:10,light:"omp-web-light",dark:"omp-web-dark"}]}})},sm=/^[a-z][a-z0-9.-]*$/u;function rm(e){return sm.test(e)}const om="machine.";function nm(e,t){if(e==="")throw new Error("Machine id is required");if(!rm(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${om}${am(e)}.${t}`}function am(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Rn(e="/omp-web-plugins/manifest.json",t={}){const i=await lm(e);if(i===void 0)return[];const s=[];for(const r of i.plugins)if(t.shouldLoadPlugin?.(r)!==!1)try{const o=new URL(r.module,new URL(e,window.location.href)).toString(),n=await import(o),a=pm(n,o);s.push({id:t.machineId===void 0?r.id:nm(t.machineId,r.id),plugin:a,machineSpecific:r.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:r.id}})}catch(o){console.warn(`Failed to load PI WEB plugin ${r.module}`,o)}return s}async function lm(e){const t=await fetch(e,{cache:"no-store"});if(t.status!==404){if(!t.ok)throw new Error(`Failed to load plugin manifest: ${t.statusText}`);return cm(await t.json())}}function cm(e){if(!B(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!B(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:dm(t.machineSpecific)}})}}function dm(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function pm(e,t){if(!B(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!hm(i))throw new Error(`Plugin module ${t} default export is not a OmpWebPlugin`);return i}function hm(e){return B(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}const Mn=/^[a-z][a-z0-9.-]*$/u,Pl=new WeakMap,Cl=new WeakMap;class um{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const r=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,r))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:ye}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),r&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&r&&vm(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=wm(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const r=fm(t,s.pluginId),o=s.enabled?.(r),n=o===!1?s.disabledReason?.(r):void 0,a={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(r)};return s.description!==void 0&&(a.description=s.description),s.shortcut!==void 0&&(a.shortcut=s.shortcut),s.group!==void 0&&(a.group=s.group),o!==void 0&&(a.enabled=o),n!==void 0&&n!==""&&(a.disabledReason=n),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,r){const o=this.qualify(t,i.id);return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(t,i,s,r){const o=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(a?.(Bs(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,r)?n(Bs(c,t)):void 0},render:c=>i.render(Bs(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,r){const o=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,r)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,r){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(r,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!Mn.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!Mn.test(t))throw new Error(`Invalid contribution id: ${t}`)}parseMachineSpecific(t,i){if(i===void 0)return!1;if(typeof i!="boolean")throw new Error(`Invalid plugin machineSpecific value for ${t}: ${bm(i)}`);return i}}function fm(e,t){return Pl.get(e)?.(t)??e}function Bs(e,t){return Cl.get(e)?.(t)??e}function gm(e,t){return Pl.set(e,t),e}function mm(e,t){return Cl.set(e,t),e}function vm(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function bm(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"||typeof e=="function"||e===null||e===void 0)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function wm(e){return e.state.selectedMachine?.id??"local"}const ym=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Sm(){return typeof window>"u"||!("matchMedia"in window)?[]:ym.map(e=>window.matchMedia(e))}function In(e,t=xm()){return e.some(i=>i.matches)||km(t)}function xm(){return typeof navigator>"u"?void 0:navigator}function km(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const $m=250;class Pm{constructor(t=Cm()){this.scheduler=t}repair(t){if(!t){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},$m)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function Cm(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>"u"?void 0:document.documentElement},get body(){return typeof document>"u"?void 0:document.body}}}const Rm="(max-width: 760px)";class Mm{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=In(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Im(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Sm(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Pm,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=In(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Im(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Rm)}const ss=["machines","projects","workspaces","sessions"];function Tm(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Vr(e,t){if(e!=="none")return e??Tm(t)}function Am(e,t){return t.isMobileLayout?Vr(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Em(e,t,i){return Vr(e,i.state)===t?"none":t}function Dm(e,t,i){return i?t:e}function Wm(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Fm(i)}function Lm(e){return ss[ss.indexOf(e)+1]}class Om{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Vr(this.expanded,this.getState())}isCollapsed(t){return Am(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Em(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Wm(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Dm(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Lm(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){_m(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Fm(e){const t=new Set(e);return ss.filter(i=>t.has(i))}function _m(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class jm{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",Rl(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Rl(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const fr="omp-web:panel-sizes:v1",Um={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Nm{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Gr(),this.panelSizes=Hm(this.storage)}hostConnected(){}constraints(t){return mi(t)}panelWidth(t,i){return Re(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const r=Re(t,i);this.storedPanelWidth(t)!==r&&(this.panelSizes=Gm(this.panelSizes,t,r),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Qm(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Km(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${An(Re("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${An(Re("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function mi(e){return Um[e]}function Bm(e,t,i){return e==="navigation"?i-t:t-i}function zm(e,t,i,s,r=mi(e)){return Re(e,t+Bm(e,i,s),r)}function qm(e,t,i,s={}){const r=s.constraints??mi(e);if(i==="Home")return r.minWidth;if(i==="End")return r.maxWidth;const o=s.largeStep===!0?r.largeKeyboardStep:r.keyboardStep,n=Jm(e,i,o);if(n!==void 0)return Re(e,t+n,r)}function Re(e,t,i=mi(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Hm(e=Gr()){try{const t=e?.getItem(fr);if(t==null||t==="")return{};const i=JSON.parse(t);return Vm(i)}catch{return{}}}function Km(e,t=Gr()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(fr);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=Re("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=Re("workspace",e.workspacePanelWidth)),t.setItem(fr,JSON.stringify(i))}catch{}}function Vm(e){if(!B(e)||e.version!==1)return{};const t={},i=Tn(e.navigationPanelWidth),s=Tn(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=Re("navigation",i)),s!==void 0&&(t.workspacePanelWidth=Re("workspace",s)),t}function Tn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Gm(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Qm(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Jm(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function An(e){return`${String(Math.round(e))}px`}function Gr(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function En(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:Zm(e.get("tool")),view:Xm(e.get("view"))}}function zs(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Zm(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Ml(e)?e:void 0}function Xm(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Ml(e)?e:void 0}function Ml(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Dn(){return Ym(new URLSearchParams(window.location.search).get("settings"))}function qs(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&window.history.pushState({},"",i)}function Ym(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="packages"||e==="pi-packages")return"packages";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function ev(e,t){return t===void 0?e:e.map(i=>iv(i,t))}function tv(e,t){const i=new Set(Br(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return ev(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?Il(s):s)}function iv(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Il(e):{...e,shortcut:i}}function Il(e){const t={...e};return delete t.shortcut,t}function sv(e,t){const i=t.api??At,s=t.pollIntervalMs??1e3,r=t.setTimeout??ov(),o=t.clearTimeout??nv();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:rv(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function rv(e,t,i,s,r){return Wn(e)?Promise.resolve(e):new Promise((o,n)=>{let a,c=!1;const p=f=>{c||(c=!0,a!==void 0&&r(a),o(f))},u=f=>{c||(c=!0,a!==void 0&&r(a),n(f instanceof Error?f:new Error(String(f))))},h=()=>{t.getCommandRun(e.id).then(f=>{if(f!==void 0&&Wn(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function Wn(e){return e.status==="succeeded"||e.status==="failed"}function ov(){return(e,t)=>globalThis.setTimeout(e,t)}function nv(){return e=>{globalThis.clearTimeout(e)}}function av(e,t){return t[e.path]}function lv(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function cv(e,t,i){return Al(dv(e,t,i))}function Tl(e){return Al(Object.values(e??{}))}function Al(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function dv(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}const Pi=0,pv=120;function vi(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?El():hv(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),c=Math.max(0,s.top),p=Math.min(o,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Pi,f=i.top-c-Pi;return[...h<pv&&f>h?[`bottom: ${Ct(o-i.top+Pi)};`,`max-height: ${Ct(Math.max(0,f))};`]:[`top: ${Ct(i.bottom+Pi)};`,`max-height: ${Ct(Math.max(0,h))};`],`right: ${Ct(Math.max(0,r-u))};`,`max-width: ${Ct(Math.max(0,u-n))};`].join(" ")}function hv(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():El()}function El(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Ct(e){return`${String(Math.round(e))}px`}function Dl(e,t="Active"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function ys(e,t="Active"){const i=Dl(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const uv=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Wl(e){return e.composedPath().some(t=>fv(t,uv))}function fv(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function Ss(e,t){Wl(e)||t()}function xs(e,t){return Wl(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?ut(e,()=>{Ln(e.currentTarget,-1)}):e.key==="ArrowDown"?ut(e,()=>{Ln(e.currentTarget,1)}):e.key==="Home"?ut(e,()=>{On(e.currentTarget,0)}):e.key==="End"?ut(e,()=>{On(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?ut(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?ut(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?ut(e,t.cancel):!1}function ks(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function ut(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Ln(e,t){const i=Ol(e),s=Fl(e);if(s===void 0||i.length===0)return;const r=i.indexOf(s);r<0||Ll(i,r+t)}function On(e,t){const i=Ol(e);i.length!==0&&Ll(i,t<0?i.length-1:t)}function Ll(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Ol(e){const t=Fl(e)?.getRootNode();return t===void 0||!gv(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function gv(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Fl(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}var mv=Object.defineProperty,vv=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var r=s>1?void 0:s?vv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&mv(t,i,r),r};let ae=class extends I{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,ks(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
807
+ <section>
808
+ <h2>${this.renderHeading()}</h2>
809
+ ${this.collapsed?null:l`
810
+ <div class="list-body">
811
+ ${this.machines.map(e=>this.renderMachine(e))}
812
+ </div>
813
+ `}
814
+ </section>
815
+ `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"online":t==="offline"?"offline":t==="error"?"error":"unknown",s=_l(e)&&this.onRemove!==void 0;return l`
816
+ <div
817
+ class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
818
+ tabindex="0"
819
+ title=${e.baseUrl??e.name}
820
+ @click=${r=>{Ss(r,()=>this.onSelect?.(e))}}
821
+ @keydown=${r=>{this.handleMachineKeydown(r,e)}}
822
+ >
823
+ <div class="action-main">
824
+ <span class="action-name machine-primary"><span class="machine-primary-label">${e.name}</span></span><small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${i}</small>
825
+ ${this.renderActivity(e)}
826
+ </div>
827
+ ${s?this.renderMachineMenu(e):null}
828
+ </div>
829
+ `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=Tl(this.activities[e.id]);return ys(i,i==="terminal"?"Machine terminal active":"Machine active")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=bv(e.id);return l`
830
+ <div class="action-menu">
831
+ <button
832
+ class="action-menu-toggle"
833
+ title="Machine actions"
834
+ aria-label=${`Actions for ${e.name}`}
835
+ aria-expanded=${String(t)}
836
+ aria-controls=${i}
837
+ @click=${s=>{s.stopPropagation(),this.toggleMenu(e.id,s.currentTarget)}}
838
+ >⋯</button>
839
+ ${t?l`
840
+ <div class="action-menu-panel machine-menu-panel" id=${i} style=${this.menuStyle} @click=${s=>{s.stopPropagation()}}>
841
+ <button class="danger" title=${`Remove ${e.name}`} @click=${()=>{this.removeMachine(e)}}>Remove</button>
842
+ </div>
843
+ `:null}
844
+ </div>
845
+ `}renderHeading(){if(!this.collapsible)return"Machines";const e=this.selected?.name??"No machine selected",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Machines</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=vi(t,{constrainTo:"viewport"}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}xs(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};ae.styles=[ws,D`
846
+ .machine-row.no-actions .action-main { border-radius: 8px; }
847
+ .machine-primary { display: flex; align-items: baseline; gap: 6px; }
848
+ .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
849
+ .machine-menu-panel button.danger { color: var(--pi-danger); }
850
+ .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
851
+ `];be([d({attribute:!1})],ae.prototype,"machines",2);be([d({attribute:!1})],ae.prototype,"selected",2);be([d({attribute:!1})],ae.prototype,"statuses",2);be([d({attribute:!1})],ae.prototype,"activities",2);be([d({type:Boolean,reflect:!0})],ae.prototype,"collapsible",2);be([d({type:Boolean,reflect:!0})],ae.prototype,"collapsed",2);be([d({attribute:!1})],ae.prototype,"onSelect",2);be([d({attribute:!1})],ae.prototype,"onRemove",2);be([d({attribute:!1})],ae.prototype,"onToggleCollapsed",2);be([d({attribute:!1})],ae.prototype,"onFocusNextSection",2);be([d({attribute:!1})],ae.prototype,"onCancelKeyboardNavigation",2);be([v()],ae.prototype,"openMenuMachineId",2);be([v()],ae.prototype,"menuStyle",2);ae=be([E("machine-list")],ae);function _l(e){return e.kind==="remote"}function bv(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var wv=Object.defineProperty,yv=Object.getOwnPropertyDescriptor,fe=(e,t,i,s)=>{for(var r=s>1?void 0:s?yv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&wv(t,i,r),r};let se=class extends I{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,ks(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
852
+ <section>
853
+ <h2>${this.renderHeading()}</h2>
854
+ ${this.collapsed?null:l`
855
+ <div class="list-body">
856
+ ${this.projects.map(e=>l`
857
+ <div
858
+ class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
859
+ tabindex="0"
860
+ title=${e.path}
861
+ @click=${t=>{Ss(t,()=>this.onSelect?.(e))}}
862
+ @keydown=${t=>{this.handleProjectKeydown(t,e)}}
863
+ >
864
+ <div class="action-main">
865
+ <span class="action-name">${e.name}</span><small>${e.path}</small>
866
+ ${this.renderActivity(e)}
867
+ </div>
868
+ <div class="action-menu">
869
+ <button class="action-menu-toggle" title="Project actions" aria-label=${`Actions for ${e.name}`} @click=${t=>{t.stopPropagation(),this.toggleMenu(e.id,t.currentTarget)}}>⋯</button>
870
+ ${this.openMenuProjectId===e.id?l`
871
+ <div class="action-menu-panel" style=${this.menuStyle}>
872
+ <button title="Close project" @click=${()=>{this.close(e)}}>Close</button>
873
+ </div>
874
+ `:null}
875
+ </div>
876
+ </div>
877
+ `)}
878
+ </div>
879
+ `}
880
+ </section>
881
+ `}handleProjectKeydown(e,t){xs(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"Projects";const e=this.selected?.name??"No project selected",t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Projects</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=cv(e,this.workspacesByProjectId[e.id]??[],this.activities);return ys(t,t==="terminal"?"Project terminal active":"Project active")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=vi(t,{constrainTo:"viewport"}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?
882
+
883
+ This only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}};se.styles=ws;fe([d({attribute:!1})],se.prototype,"projects",2);fe([d({attribute:!1})],se.prototype,"selected",2);fe([d({attribute:!1})],se.prototype,"activities",2);fe([d({attribute:!1})],se.prototype,"workspacesByProjectId",2);fe([d({type:Boolean,reflect:!0})],se.prototype,"collapsible",2);fe([d({type:Boolean,reflect:!0})],se.prototype,"collapsed",2);fe([d({attribute:!1})],se.prototype,"onSelect",2);fe([d({attribute:!1})],se.prototype,"onClose",2);fe([d({attribute:!1})],se.prototype,"onToggleCollapsed",2);fe([d({attribute:!1})],se.prototype,"onFocusPreviousSection",2);fe([d({attribute:!1})],se.prototype,"onFocusNextSection",2);fe([d({attribute:!1})],se.prototype,"onCancelKeyboardNavigation",2);fe([v()],se.prototype,"openMenuProjectId",2);fe([v()],se.prototype,"menuStyle",2);se=fe([E("project-list")],se);function Fn(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Sv(t)}`)}function Sv(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&xv(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${i??void 0}>${e.text}</a>`}return l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function xv(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var kv=Object.defineProperty,$v=Object.getOwnPropertyDescriptor,ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?$v(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&kv(t,i,r),r};let Z=class extends I{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,ks(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
884
+ <section>
885
+ <h2>${this.renderHeading()}</h2>
886
+ ${this.collapsed?null:l`
887
+ <div class="list-body">
888
+ ${this.workspaces.map(e=>{const t=Pv(e),i=this.workspaceLabelItems(e);return l`
889
+ <div
890
+ class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
891
+ tabindex="0"
892
+ title=${t}
893
+ @click=${s=>{Ss(s,()=>this.onSelect?.(e))}}
894
+ @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
895
+ >
896
+ <div class="action-main">
897
+ ${this.renderWorkspaceMain(t,i,e)}
898
+ </div>
899
+ ${this.renderWorkspaceMenu(t,i,e)}
900
+ </div>
901
+ `})}
902
+ </div>
903
+ `}
904
+ </section>
905
+ `}renderHeading(){if(!this.collapsible)return"Workspaces";const e=this.selected===void 0?"No workspace selected":`${this.selected.label}${this.selected.isMain?" · main":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Workspaces</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=lv(av(e,this.activities));return ys(t,t==="terminal"?"Workspace terminal active":"Workspace active")}renderWorkspaceMain(e,t,i){return l`
906
+ <span class="workspace-primary">
907
+ <span class="workspace-primary-label">${e}</span>
908
+ ${this.isDeleting(i)?l`<span class="workspace-status">Deleting…</span>`:null}
909
+ </span>
910
+ ${t.length===0?null:l`
911
+ <small class="workspace-secondary">
912
+ <span class="workspace-label">${Fn(t)}</span>
913
+ </small>
914
+ `}
915
+ ${this.renderActivity(i)}
916
+ `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,r=Rv(i.id);return l`
917
+ <div class="action-menu">
918
+ <button
919
+ class="action-menu-toggle"
920
+ title="Workspace actions and details"
921
+ aria-label=${`Actions and details for ${e}`}
922
+ aria-expanded=${String(s)}
923
+ aria-controls=${r}
924
+ @click=${o=>{o.stopPropagation(),this.toggleMenu(i.id,o.currentTarget)}}
925
+ >⋯</button>
926
+ ${s?l`
927
+ <div class="action-menu-panel workspace-menu-panel" id=${r} style=${this.menuStyle} @click=${o=>{o.stopPropagation()}}>
928
+ ${this.renderWorkspaceActions(i)}
929
+ ${this.renderWorkspaceDetails(e,t,i)}
930
+ </div>
931
+ `:null}
932
+ </div>
933
+ `}renderWorkspaceActions(e){if(!Cv(e))return;const t=this.isDeleting(e);return l`
934
+ <div class="workspace-menu-actions">
935
+ <button class="danger" title=${t?"Workspace deletion in progress":"Delete workspace"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"Deleting…":"Delete workspace"}</button>
936
+ </div>
937
+ `}renderWorkspaceDetails(e,t,i){return l`
938
+ <dl class="workspace-menu-details">
939
+ <div class="workspace-detail-row">
940
+ <dt>${i.branch===void 0?"Workspace":"Branch"}</dt>
941
+ <dd>${e}</dd>
942
+ </div>
943
+ <div class="workspace-detail-row">
944
+ <dt>Path</dt>
945
+ <dd title=${i.path}>${i.path}</dd>
946
+ </div>
947
+ ${t.length===0?null:l`
948
+ <div class="workspace-detail-row">
949
+ <dt>Details</dt>
950
+ <dd><span class="workspace-label">${Fn(t)}</span></dd>
951
+ </div>
952
+ `}
953
+ </dl>
954
+ `}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=vi(t,{constrainTo:"viewport"}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}xs(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};Z.styles=ws;ce([d({attribute:!1})],Z.prototype,"workspaces",2);ce([d({attribute:!1})],Z.prototype,"selected",2);ce([d({type:Boolean,reflect:!0})],Z.prototype,"collapsible",2);ce([d({type:Boolean,reflect:!0})],Z.prototype,"collapsed",2);ce([d({attribute:!1})],Z.prototype,"workspaceLabelItems",2);ce([d({attribute:!1})],Z.prototype,"activities",2);ce([d({attribute:!1})],Z.prototype,"deletingWorkspaceIds",2);ce([d({attribute:!1})],Z.prototype,"onSelect",2);ce([d({attribute:!1})],Z.prototype,"onDelete",2);ce([d({attribute:!1})],Z.prototype,"onToggleCollapsed",2);ce([d({attribute:!1})],Z.prototype,"onFocusPreviousSection",2);ce([d({attribute:!1})],Z.prototype,"onFocusNextSection",2);ce([d({attribute:!1})],Z.prototype,"onCancelKeyboardNavigation",2);ce([v()],Z.prototype,"openMenuWorkspaceId",2);ce([v()],Z.prototype,"menuStyle",2);Z=ce([E("workspace-list")],Z);function Pv(e){return`${e.branch??e.label}${e.isMain?" · main":""}`}function Cv(e){return e.isGitWorktree&&!e.isMain}function Rv(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}function jl(e){return e.slice(-8)}var Mv=Object.defineProperty,Iv=Object.getOwnPropertyDescriptor,T=(e,t,i,s)=>{for(var r=s>1?void 0:s?Iv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Mv(t,i,r),r};function Kt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:jl(e.id)}let M=class extends I{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.startingCount=0,this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.archivedDeleteUnavailableMessage="Update and restart Omp-Web on this machine to delete archived sessions.",this.cleanupUnavailableMessage="Update and restart Omp-Web on this machine to clean up sessions.",this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&(this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,ks(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Ev(this.sessions),t=new Set(e.map(o=>o.session.id)),i=e.map(o=>o.session).filter(o=>Vt(o)==="current"),s=Ul(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),r=Tv(this.sessions);return l`
955
+ <section>
956
+ ${this.renderHeading(e.length+s.length,i)}
957
+ ${this.collapsed?null:l`
958
+ <div class="list-body">
959
+ ${this.renderCurrentSelectionToolbar(i)}
960
+ ${this.startingCount>0?this.renderStartingSession():null}
961
+ ${e.map(o=>this.renderSession(o,r.get(o.session.id)??0,"current"))}
962
+ ${s.length>0?l`
963
+ ${this.renderArchivedHeading(s.map(o=>o.session))}
964
+ ${this.archivedExpanded?l`
965
+ ${this.renderArchivedSelectionToolbar(s.map(o=>o.session))}
966
+ ${s.map(o=>this.renderSession(o,r.get(o.session.id)??0,"archived"))}
967
+ `:null}
968
+ `:null}
969
+ </div>
970
+ `}
971
+ </section>
972
+ `}renderHeading(e,t){if(!this.collapsible)return l`
973
+ <h2>
974
+ Sessions
975
+ ${this.renderCurrentSelectionButton(t)}
976
+ ${this.renderCleanupButton()}
977
+ ${this.renderStartButton()}
978
+ </h2>
979
+ `;const i=this.selected===void 0?"No session selected":Kt(this.selected),s=this.selected?.path??i;return l`
980
+ <h2>
981
+ <button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} Sessions</span>${this.collapsed?l`<small class="section-selected" dir="auto" title=${s}>${i}</small>`:null}</span></button>
982
+ ${this.renderCurrentSelectionButton(t)}
983
+ <small class="section-count">${e}</small>
984
+ ${this.renderCleanupButton()}
985
+ ${this.renderStartButton()}
986
+ </h2>
987
+ `}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;const t=this.selectionScopes.has("current");return l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"Close current session selection":"Select current sessions"} aria-label=${t?"Close current session selection":"Select current sessions"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${i=>{i.stopPropagation(),this.toggleSelection("current",e)}}>☑</button>`}renderCleanupButton(){return l`<button class="cleanup-entry" title=${this.canCleanup?"Preview session cleanup":this.cleanupUnavailableMessage} @click=${e=>{e.stopPropagation(),this.onCleanup?.()}}>Clean up</button>`}renderStartButton(){const e=this.startingCount>0?"Start another session":"Start a new session";return l`<button class="start-session-button" title=${e} aria-label=${e} ?disabled=${!this.canStart} @click=${t=>{t.stopPropagation(),this.onStart?.()}}>+</button>`}renderStartingSession(){const e=this.startingCount!==1;return l`
988
+ <div class="pending-session-row starting-session" role="status" aria-live="polite">
989
+ <div class="action-main">
990
+ <span class="action-name"><span class="activity-indicator sending" aria-hidden="true"></span>${e?`Starting ${String(this.startingCount)} sessions…`:"Starting session…"}</span>
991
+ <small>Waiting for ${e?"new sessions":"the new session"} to be created</small>
992
+ </div>
993
+ </div>
994
+ `}renderArchivedHeading(e){const t=this.selectionScopes.has("archived");return l`
995
+ <h2 class="subheading">
996
+ <button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} Archived</span></button>
997
+ ${this.archivedExpanded?l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"Close archived session selection":"Select archived sessions"} aria-label=${t?"Close archived session selection":"Select archived sessions"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${()=>{this.toggleSelection("archived",e)}}>☑</button>`:null}
998
+ <small class="section-count">${e.length}</small>
999
+ </h2>
1000
+ `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(o=>He(o,this.statuses[o.id])),s=e.length>0&&e.every(o=>this.selectedSessionIds.has(o.id)),r=e.filter(o=>this.selectedSessionIds.has(o.id)).length;return l`
1001
+ <div class="bulk-row selecting">
1002
+ <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!s)}}>${s?"Clear visible":"Select visible"}</button>
1003
+ <small>${t.length} selected${r!==t.length?l` · ${r} visible`:null}</small>
1004
+ <button ?disabled=${i.length===0} @click=${()=>{this.archiveSelectedCurrent()}}>Archive selected</button>
1005
+ <button @click=${()=>{this.clearSelection("current")}}>Clear</button>
1006
+ <button @click=${()=>{this.closeSelection("current")}}>Done</button>
1007
+ </div>
1008
+ `}renderArchivedSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("archived"))return null;const t=this.selectedSessions("archived"),i=e.length>0&&e.every(r=>this.selectedSessionIds.has(r.id)),s=e.filter(r=>this.selectedSessionIds.has(r.id)).length;return l`
1009
+ <div class="bulk-row selecting">
1010
+ <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!i)}}>${i?"Clear visible":"Select visible"}</button>
1011
+ <small>${t.length} selected${s!==t.length?l` · ${s} visible`:null}</small>
1012
+ <button class="danger" title=${this.canDeleteArchived?"Permanently delete selected archived sessions":this.archivedDeleteUnavailableMessage} ?disabled=${t.length===0||!this.canDeleteArchived} @click=${()=>{this.confirmDeleteSelectedArchived()}}>Delete selected</button>
1013
+ <button @click=${()=>{this.clearSelection("archived")}}>Clear</button>
1014
+ <button @click=${()=>{this.closeSelection("archived")}}>Done</button>
1015
+ ${this.canDeleteArchived?null:l`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
1016
+ </div>
1017
+ `}renderSession(e,t,i){const{session:s}=e,r=Math.min(e.depth,2),o=Vt(s)===i,n=this.selectionScopes.has(i),a=n&&o,c=a&&this.selectedSessionIds.has(s.id),p=this.statuses[s.id],u=this.activities[s.id],h=He(s,p),f=ci(s,p),S=h&&this.canReload;return l`
1018
+ <div
1019
+ class="action-row ${this.selected?.id===s.id?"selected":""} ${c?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
1020
+ style=${`--depth:${String(r)}`}
1021
+ tabindex="0"
1022
+ title=${s.path}
1023
+ @click=${$=>{Ss($,()=>{this.activateSessionRow(s,i)})}}
1024
+ @keydown=${$=>{this.handleSessionKeydown($,s,i)}}
1025
+ >
1026
+ <div class="action-main ${n?"selecting":""}">
1027
+ ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${Kt(s)}`} .checked=${c} @click=${$=>{$.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
1028
+ <span class="action-name" dir="auto">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Kt(s)}${e.depth>2?l` <span class="badge">depth ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">parent unavailable</span>`:null}</span><small>${this.renderSessionMetaPrefix(s,p,u)}${String(s.messageCount)} messages</small>
1029
+ ${this.renderActivity(s)}
1030
+ </div>
1031
+ <div class="action-menu">
1032
+ <button class="action-menu-toggle" title="Session actions" @click=${$=>{$.stopPropagation(),this.toggleMenu(s.id,$.currentTarget)}}>⋯</button>
1033
+ ${this.openMenuSessionId===s.id?l`
1034
+ <div class="action-menu-panel" style=${this.menuStyle}>
1035
+ ${s.archived===!0?l`
1036
+ <button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(s)}}>Restore</button>
1037
+ <button class="danger" title=${this.canDeleteArchived?"Permanently delete archived session":this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.openMenuSessionId=void 0,this.confirmDeleteArchived(s)}}>Delete archived session</button>
1038
+ `:f?l`<button title="Delete transient new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(s)}}>Delete</button>`:l`
1039
+ ${h?l`
1040
+ <button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(s)}}>Archive</button>
1041
+ ${t>0?l`<button title="Archive this session and its descendants" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(s,t)}}>Archive with descendants (${t})</button>`:null}
1042
+ `:null}
1043
+ ${s.parentSessionPath!==void 0?l`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(s)}}>Detach from parent</button>`:null}
1044
+ ${S?l`<button title=${lt(this.statuses[s.id],this.activities[s.id])?"Stop current session activity before reloading from disk":"Reload session from disk without refreshing Pi runtime resources"} ?disabled=${lt(this.statuses[s.id],this.activities[s.id])} @click=${()=>{this.openMenuSessionId=void 0,this.onReload?.(s)}}>Reload from disk</button>`:null}
1045
+ `}
1046
+ </div>
1047
+ `:null}
1048
+ </div>
1049
+ </div>
1050
+ `}handleSessionKeydown(e,t,i){xs(e,{activate:()=>{this.activateSessionRow(t,i)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&Vt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){const i=t===1?"descendant session":"descendant sessions";confirm(`Archive “${Kt(e)}” and ${String(t)} ${i}?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`Permanently delete archived session “${Kt(e)}”? This cannot be undone.`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");if(e.length===0)return;const t=e.length===1?"archived session":"archived sessions";confirm(`Permanently delete ${String(e.length)} selected ${t}? This cannot be undone.`)&&(this.selectedSessionIds=Hs(this.selectedSessionIds,e.map(i=>i.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>He(t,this.statuses[t.id]));this.selectedSessionIds=Hs(this.selectedSessionIds,e.map(t=>t.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);const i=t.length===1?t[0]:void 0;i!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,i.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){const t=this.sessions.filter(i=>Vt(i)===e).map(i=>i.id);this.selectedSessionIds=Hs(this.selectedSessionIds,t)}toggleSelected(e){const t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){const i=new Set(this.selectedSessionIds);for(const s of e)t?i.add(s.id):i.delete(s.id);this.selectedSessionIds=i}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&Vt(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=vi(t,{constrainTo:"viewport"}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e,t,i){return ci(e,t)?i?.phase==="active"?"creating · ":i?.phase==="error"?"error · ":"new · ":e.archived===!0?"read-only · ":""}renderActivity(e){const t=Av(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return ys(t,t==="sending"?"Sending message":"Session active")}};M.styles=[ws,D`
1051
+ h2 { min-height: 30px; }
1052
+ h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
1053
+ .bulk-select-entry { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; width: 30px; height: 30px; padding: 0; font-size: 13px; line-height: 1; text-transform: none; }
1054
+ .start-session-button { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; min-width: 30px; height: 30px; padding: 0 9px; }
1055
+ .cleanup-entry { flex: 0 0 auto; padding: 5px 7px; font-size: 12px; text-transform: none; }
1056
+ .bulk-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 0 0 6px; }
1057
+ .bulk-row button { padding: 5px 7px; font-size: 12px; }
1058
+ .bulk-row small { display: inline; min-width: 0; color: var(--pi-muted); }
1059
+ .action-name, .section-selected { text-align: start; unicode-bidi: plaintext; }
1060
+ .bulk-row .capability-hint { flex: 1 0 100%; color: var(--pi-warning); }
1061
+ .bulk-row.selecting { padding: 6px; border: 1px solid var(--pi-border-muted); border-radius: 8px; background: color-mix(in srgb, var(--pi-surface) 65%, transparent); }
1062
+ button.danger, .action-menu-panel button.danger { color: var(--pi-danger); }
1063
+ button.danger:hover, .action-menu-panel button.danger:hover { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
1064
+ .action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
1065
+ .pending-session-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr); margin: 6px 0; cursor: default; }
1066
+ .pending-session-row.starting-session .action-main { border-radius: 8px; border-style: dashed; color: var(--pi-muted); }
1067
+ .pending-session-row.starting-session .action-name { display: flex; align-items: center; gap: 6px; max-height: none; -webkit-line-clamp: 1; }
1068
+ .pending-session-row.starting-session .activity-indicator { flex: 0 0 auto; margin: 0; }
1069
+ .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
1070
+ .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
1071
+ `];T([d({attribute:!1})],M.prototype,"sessions",2);T([d({attribute:!1})],M.prototype,"statuses",2);T([d({attribute:!1})],M.prototype,"activities",2);T([d({attribute:!1})],M.prototype,"sending",2);T([d({attribute:!1})],M.prototype,"selected",2);T([d({type:Number})],M.prototype,"startingCount",2);T([d({type:Boolean})],M.prototype,"canStart",2);T([d({type:Boolean})],M.prototype,"canDeleteArchived",2);T([d({type:Boolean})],M.prototype,"canReload",2);T([d({type:Boolean})],M.prototype,"canCleanup",2);T([d({type:String})],M.prototype,"archivedDeleteUnavailableMessage",2);T([d({type:String})],M.prototype,"cleanupUnavailableMessage",2);T([d({type:Boolean,reflect:!0})],M.prototype,"collapsible",2);T([d({type:Boolean,reflect:!0})],M.prototype,"collapsed",2);T([d({attribute:!1})],M.prototype,"onSelect",2);T([d({attribute:!1})],M.prototype,"onStart",2);T([d({attribute:!1})],M.prototype,"onToggleCollapsed",2);T([d({attribute:!1})],M.prototype,"onArchivedCollapsed",2);T([d({attribute:!1})],M.prototype,"onFocusPreviousSection",2);T([d({attribute:!1})],M.prototype,"onFocusNextSection",2);T([d({attribute:!1})],M.prototype,"onCancelKeyboardNavigation",2);T([d({attribute:!1})],M.prototype,"onArchive",2);T([d({attribute:!1})],M.prototype,"onArchiveWithDescendants",2);T([d({attribute:!1})],M.prototype,"onArchiveMany",2);T([d({attribute:!1})],M.prototype,"onRestore",2);T([d({attribute:!1})],M.prototype,"onDelete",2);T([d({attribute:!1})],M.prototype,"onDeleteArchived",2);T([d({attribute:!1})],M.prototype,"onDeleteArchivedMany",2);T([d({attribute:!1})],M.prototype,"onDetachParent",2);T([d({attribute:!1})],M.prototype,"onReload",2);T([d({attribute:!1})],M.prototype,"onCleanup",2);T([v()],M.prototype,"openMenuSessionId",2);T([v()],M.prototype,"menuStyle",2);T([v()],M.prototype,"archivedExpanded",2);T([v()],M.prototype,"selectionScopes",2);T([v()],M.prototype,"selectedSessionIds",2);M=T([E("session-list")],M);function Vt(e){return e.archived===!0?"archived":"current"}function Hs(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Tv(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const r=t.get(s.parentSessionPath)??[];r.push(s),t.set(s.parentSessionPath,r)}const i=(s,r)=>{if(r.has(s.path))return 0;const o=new Set(r);o.add(s.path);let n=0;for(const a of t.get(s.path)??[])o.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,o));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Av(e,t,i,s){if(!(Hi(e)||e.archived===!0))return s?"sending":lt(t,i)?"session":void 0}function Ev(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let r=s.parentSessionPath;const o=new Set([s.path]);for(;r!==void 0&&!o.has(r);){o.add(r);const n=t.get(r);if(n===void 0)break;i.add(n.id),r=n.parentSessionPath}}return Ul(e.filter(s=>i.has(s.id)))}function Ul(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const r=[],o=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;r.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])o(h,a+1,u)};for(const n of s)o(n,0,new Set);return r}var Dv=Object.defineProperty,Wv=Object.getOwnPropertyDescriptor,ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?Wv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Dv(t,i,r),r};let re=class extends I{constructor(){super(...arguments),this.canCleanup=!0,this.unavailableMessage="Update and restart Omp-Web on this machine to clean up sessions.",this.loading=!1,this.running=!1,this.error="",this.draft={...Ff},this.formError=""}willUpdate(e){e.has("preview")&&(this.selectedProjectCwds=this.preview?.projects.map(t=>t.cwd))}render(){const e=ei(this.draft),t=this.selectedPreview(),i=yn({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),s=i?"Run cleanup":t!==void 0&&!ji(t)?"Select at least one project to run cleanup":"Preview cleanup before running it";return l`
1072
+ <div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
1073
+ <section role="dialog" aria-modal="true" aria-label="Clean up sessions" @mousedown=${r=>{r.stopPropagation()}} @keydown=${r=>{this.handleKeyDown(r)}}>
1074
+ <header>
1075
+ <div>
1076
+ <span class="eyebrow">Sessions</span>
1077
+ <h1>Clean up sessions</h1>
1078
+ </div>
1079
+ <button class="close-button" title="Close cleanup" aria-label="Close cleanup" @click=${()=>{this.onClose?.()}}>×</button>
1080
+ </header>
1081
+ <div class="body">
1082
+ <p class="intro">Preview manual cleanup for this machine before archiving idle sessions or permanently deleting old archived sessions.</p>
1083
+ ${this.canCleanup?this.renderForm(e.ok?"":e.error):this.renderUnavailable()}
1084
+ ${this.renderMessage()}
1085
+ ${this.preview===void 0?null:this.renderPreview(this.preview)}
1086
+ ${this.result===void 0?null:this.renderResult(this.result)}
1087
+ </div>
1088
+ <footer>
1089
+ <button @click=${()=>{this.onClose?.()}}>${this.result===void 0?"Cancel":"Close"}</button>
1090
+ <button ?disabled=${!this.canCleanup||this.loading||this.running} @click=${()=>{this.previewCleanup()}}>${this.loading?"Previewing…":"Preview"}</button>
1091
+ <button class="danger" ?disabled=${!i} title=${s} @click=${()=>{this.runCleanup()}}>${this.running?"Running…":"Run cleanup"}</button>
1092
+ </footer>
1093
+ </section>
1094
+ </div>
1095
+ `}renderForm(e){const t=this.loading||this.running,i=ei(this.draft),s=this.preview!==void 0&&i.ok&&Lt(i.request)!==Lt(this.previewRequest)&&ji(this.preview);return l`
1096
+ <fieldset ?disabled=${t}>
1097
+ <label class="toggle-row">
1098
+ <input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${r=>{this.updateDraft({archiveIdleEnabled:Ks(r)})}}>
1099
+ <span>Archive non-archived sessions idle for more than</span>
1100
+ <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${r=>{this.updateDraft({archiveIdleDays:_n(r)})}}>
1101
+ <span>days</span>
1102
+ </label>
1103
+ <label class="toggle-row delete-row">
1104
+ <input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${r=>{this.updateDraft({deleteArchivedEnabled:Ks(r)})}}>
1105
+ <span>Delete archived sessions archived for more than</span>
1106
+ <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${r=>{this.updateDraft({deleteArchivedDays:_n(r)})}}>
1107
+ <span>days</span>
1108
+ </label>
1109
+ </fieldset>
1110
+ <p class="warning"><strong>Deletion is permanent.</strong> Cleanup only deletes sessions that are already archived.</p>
1111
+ ${e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}
1112
+ ${s?l`<div class="hint" role="status">Thresholds changed. Preview again before running cleanup.</div>`:null}
1113
+ `}renderUnavailable(){return l`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){const e=this.formError||this.error;return e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){const t=this.selectedProjectCwdsForPreview(),i=new Set(t),s=Sn(e,t);return l`
1114
+ <section class="preview" aria-label="Cleanup preview">
1115
+ <h2>Preview</h2>
1116
+ ${e.projects.length===0?l`<p class="empty">No sessions match these thresholds.</p>`:l`
1117
+ ${this.renderSelectionControls(e,t)}
1118
+ <div class="table-scroll" tabindex="0" aria-label="Cleanup projects table">
1119
+ <table>
1120
+ <thead>
1121
+ <tr><th>Clean up</th><th>Project/workspace path</th><th>Archive</th><th>Delete archived</th></tr>
1122
+ </thead>
1123
+ <tbody>
1124
+ ${e.projects.map(r=>this.renderProjectRow(r,i.has(r.cwd)))}
1125
+ </tbody>
1126
+ <tfoot>
1127
+ <tr><th colspan="2">Selected totals</th><td>${s.totals.archiveCount}</td><td>${s.totals.deleteCount}</td></tr>
1128
+ </tfoot>
1129
+ </table>
1130
+ </div>
1131
+ `}
1132
+ ${e.skippedBusySessionIds===void 0||e.skippedBusySessionIds.length===0?null:l`<p class="hint">${e.skippedBusySessionIds.length} busy ${e.skippedBusySessionIds.length===1?"session was":"sessions were"} skipped.</p>`}
1133
+ </section>
1134
+ `}renderSelectionControls(e,t){const i=this.loading||this.running;return l`
1135
+ <div class="selection-controls" role="group" aria-label="Project selection">
1136
+ <span>${t.length} of ${e.projects.length} projects selected</span>
1137
+ <button ?disabled=${i||t.length===e.projects.length} @click=${()=>{this.selectAllProjects()}}>Select all</button>
1138
+ <button ?disabled=${i||t.length===0} @click=${()=>{this.deselectAllProjects()}}>Deselect all</button>
1139
+ </div>
1140
+ ${t.length===0?l`<p class="hint" role="status">Select at least one project to run cleanup.</p>`:null}
1141
+ `}renderProjectRow(e,t){return l`
1142
+ <tr class=${t?"":"unselected"}>
1143
+ <td class="select-cell"><input type="checkbox" aria-label=${`Clean up ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${i=>{this.setProjectSelected(e.cwd,Ks(i))}}></td>
1144
+ <th title=${e.cwd} dir="auto">${e.cwd}</th>
1145
+ <td>${e.archiveCount}</td>
1146
+ <td>${e.deleteCount}</td>
1147
+ </tr>
1148
+ `}renderResult(e){return l`
1149
+ <section class="result" aria-label="Cleanup result">
1150
+ <h2>Cleanup complete</h2>
1151
+ <p>Archived ${e.archivedSessionIds.length} ${e.archivedSessionIds.length===1?"session":"sessions"}; permanently deleted ${e.deletedSessionIds.length} archived ${e.deletedSessionIds.length===1?"session":"sessions"}.</p>
1152
+ </section>
1153
+ `}updateDraft(e){this.draft={...this.draft,...e},this.formError=""}selectedPreview(){return this.preview===void 0?void 0:Sn(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:vl(this.preview,this.selectedProjectCwds)}selectAllProjects(){this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd)??[],this.formError=""}deselectAllProjects(){this.selectedProjectCwds=[],this.formError=""}setProjectSelected(e,t){const i=this.preview;if(i===void 0)return;const s=new Set(this.selectedProjectCwdsForPreview());t?s.add(e):s.delete(e),this.selectedProjectCwds=i.projects.map(r=>r.cwd).filter(r=>s.has(r)),this.formError=""}previewCleanup(){const e=ei(this.draft);if(!e.ok){this.formError=e.error;return}this.formError="",this.onPreview?.(e.request)}runCleanup(){const e=ei(this.draft);if(!e.ok){this.formError=e.error;return}const t=this.selectedPreview(),i=this.selectedProjectCwdsForPreview();if(!yn({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest})){this.formError=t!==void 0&&!ji(t)?"Select at least one project to run cleanup.":"Preview cleanup before running it.";return}t===void 0||!_f(t,s=>confirm(s))||(this.formError="",this.onRun?.({...e.request,projectCwds:i}))}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};re.styles=D`
1154
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1155
+ .backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
1156
+ section[role="dialog"] { width: min(760px, 100%); max-height: min(760px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr) auto; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
1157
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
1158
+ footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1159
+ .body { min-height: 0; overflow: auto; display: grid; gap: 14px; padding: 16px; }
1160
+ .eyebrow { display: block; color: var(--pi-muted); font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
1161
+ h1, h2, p { margin: 0; }
1162
+ h1 { font-size: 20px; line-height: 1.2; }
1163
+ h2 { font-size: 15px; }
1164
+ .intro, .hint, .empty { color: var(--pi-muted); }
1165
+ fieldset { margin: 0; padding: 0; border: 0; display: grid; gap: 10px; }
1166
+ .toggle-row { display: grid; grid-template-columns: auto minmax(0, max-content) 88px auto; align-items: center; gap: 8px; color: var(--pi-text); }
1167
+ input[type="checkbox"] { width: 16px; height: 16px; accent-color: var(--pi-accent); }
1168
+ input.days { box-sizing: border-box; width: 88px; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 8px 9px; font: var(--pi-control-font-size, 16px) var(--pi-control-font-family, system-ui, sans-serif); }
1169
+ input.days:disabled { opacity: .55; }
1170
+ .warning, .unavailable, .dialog-error, .result { border: 1px solid var(--pi-border); border-radius: 10px; padding: 10px 12px; }
1171
+ .warning { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-text); }
1172
+ .unavailable { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
1173
+ .dialog-error { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); color: var(--pi-danger); }
1174
+ .result { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
1175
+ .preview { display: grid; gap: 10px; min-width: 0; }
1176
+ .selection-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
1177
+ .selection-controls span { color: var(--pi-muted); }
1178
+ .selection-controls button { padding: 5px 7px; font-size: 12px; }
1179
+ .table-scroll { max-width: 100%; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; -webkit-overflow-scrolling: touch; border: 1px solid var(--pi-border); border-radius: 10px; }
1180
+ table { width: 100%; min-width: 620px; border-collapse: collapse; }
1181
+ th, td { border-bottom: 1px solid var(--pi-border-muted); padding: 8px 10px; text-align: right; }
1182
+ thead th:first-child, td.select-cell { width: 72px; text-align: center; }
1183
+ th:nth-child(2), td:nth-child(2) { text-align: left; }
1184
+ tbody tr.unselected { opacity: .58; }
1185
+ tbody th { max-width: 380px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-weight: 500; }
1186
+ tfoot th, tfoot td { border-bottom: 0; font-weight: 700; }
1187
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; font: inherit; cursor: pointer; }
1188
+ button:disabled { opacity: .5; cursor: not-allowed; }
1189
+ button.danger { color: var(--pi-danger); }
1190
+ button.danger:not(:disabled):hover { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
1191
+ .close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
1192
+ .close-button:hover, .close-button:focus { color: var(--pi-text); background: var(--pi-surface-hover); }
1193
+
1194
+ @media (max-width: 680px) {
1195
+ .backdrop { padding: 0; place-items: stretch; }
1196
+ section[role="dialog"] { width: 100%; height: 100dvh; max-height: none; border: 0; border-radius: 0; }
1197
+ .toggle-row { grid-template-columns: auto minmax(0, 1fr); }
1198
+ .toggle-row input.days { grid-column: 2; }
1199
+ .toggle-row span:last-child { grid-column: 2; }
1200
+ table { min-width: 560px; }
1201
+ thead th:first-child, td.select-cell { width: 58px; }
1202
+ }
1203
+ `;ge([d({type:Boolean})],re.prototype,"canCleanup",2);ge([d({type:String})],re.prototype,"unavailableMessage",2);ge([d({attribute:!1})],re.prototype,"preview",2);ge([d({attribute:!1})],re.prototype,"previewRequest",2);ge([d({attribute:!1})],re.prototype,"result",2);ge([d({type:Boolean})],re.prototype,"loading",2);ge([d({type:Boolean})],re.prototype,"running",2);ge([d({type:String})],re.prototype,"error",2);ge([d({attribute:!1})],re.prototype,"onPreview",2);ge([d({attribute:!1})],re.prototype,"onRun",2);ge([d({attribute:!1})],re.prototype,"onClose",2);ge([v()],re.prototype,"draft",2);ge([v()],re.prototype,"formError",2);ge([v()],re.prototype,"selectedProjectCwds",2);re=ge([E("session-cleanup-dialog")],re);function Ks(e){return e.target instanceof HTMLInputElement?e.target.checked:!1}function _n(e){return e.target instanceof HTMLInputElement?e.target.value:""}const Qr={CHILD:2,ELEMENT:6},Jr=e=>(...t)=>({_$litDirective$:e,values:t});let Zr=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,i,s){this._$Ct=t,this._$AM=i,this._$Ci=s}_$AS(t,i){return this.update(t,i)}update(t,i){return this.render(...i)}};const{I:Lv}=Zc,jn=e=>e,Un=()=>document.createComment(""),Gt=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(Un(),r),n=s.insertBefore(Un(),r);i=new Lv(o,n,e,e.options)}else{const o=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(o!==r||a){let c=i._$AA;for(;c!==o;){const p=jn(c).nextSibling;jn(s).insertBefore(c,r),c=p}}}return i},ft=(e,t,i=e)=>(e._$AI(t,i),e),Ov={},Fv=(e,t=Ov)=>e._$AH=t,_v=e=>e._$AH,Vs=e=>{e._$AR(),e._$AA.remove()};const Nn=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},jv=Jr(class extends Zr{constructor(e){if(super(e),e.type!==Qr.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const r=[],o=[];let n=0;for(const a of e)r[n]=s?s(a,n):n,o[n]=i(a,n),n++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const r=_v(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],c=[];let p,u,h=0,f=r.length-1,S=0,$=o.length-1;for(;h<=f&&S<=$;)if(r[h]===null)h++;else if(r[f]===null)f--;else if(a[h]===n[S])c[S]=ft(r[h],o[S]),h++,S++;else if(a[f]===n[$])c[$]=ft(r[f],o[$]),f--,$--;else if(a[h]===n[$])c[$]=ft(r[h],o[$]),Gt(e,c[$+1],r[h]),h++,$--;else if(a[f]===n[S])c[S]=ft(r[f],o[S]),Gt(e,r[h],r[f]),f--,S++;else if(p===void 0&&(p=Nn(n,S,$),u=Nn(a,h,f)),p.has(a[h]))if(p.has(a[f])){const R=u.get(n[S]),ee=R!==void 0?r[R]:null;if(ee===null){const st=Gt(e,r[h]);ft(st,o[S]),c[S]=st}else c[S]=ft(ee,o[S]),Gt(e,r[h],ee),r[R]=null;S++}else Vs(r[f]),f--;else Vs(r[h]),h++;for(;S<=$;){const R=Gt(e,c[$+1]);ft(R,o[S]),c[S++]=R}for(;h<=f;){const R=r[h++];R!==null&&Vs(R)}return this.ut=n,Fv(e,c),at}}),Uv="omp-web:chat-groups:",Nv={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Bn(e));return t===null||t===""?void 0:zv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Bn(e),JSON.stringify(t))}catch{}}};class Bv{constructor(t=Nv){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const r=this.isOpen(t,s),o=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(o.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?o.add(t):o.delete(t)),(s?!n.has(t):o.has(t))===r&&zn(o,this.openGroupKeys)&&zn(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=o,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function Bn(e){return`${Uv}${e}`}function zv(e){if(Array.isArray(e))return{open:Gs(e),closedDefaultOpen:[]};if(B(e))return{open:Array.isArray(e.open)?Gs(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Gs(e.closedDefaultOpen):[]}}function Gs(e){return e.filter(t=>typeof t=="string")}function zn(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function qv(e,t=0){const i=[];let s=[],r=0;const o=(a,c)=>{s.length||(r=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(S=>qn(a,S)),u=a.parts.filter(S=>!qn(a,S)),h=t+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({role:a.role,parts:u,...f},h),p.length){n();const S=p.every($=>$.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:S,parts:p,...f},index:h})}}),n(),i}function Hv(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} history compaction ${e.length===1?"summary":"summaries"}`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} branch ${e.length===1?"summary":"summaries"}`;const t=e.reduce((s,r)=>(s[r.role]=(s[r.role]??0)+1,s),{}),i=Object.entries(t).map(([s,r])=>`${String(r)} ${s}`).join(" · ");return`${String(e.length)} ${e.length===1?"event":"events"}${i!==""?` · ${i}`:""}`}function qn(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const Kv=30;function Vv(e,t){const i=Qv(Xv(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Gv(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Jv(s,t.markerOffset);return}e.scrollTop=Zv(e.scrollHeight,t.distanceFromBottom)}function Qv(e){let t,i=Number.NEGATIVE_INFINITY,s,r=Number.POSITIVE_INFINITY;for(const o of e)o.offset<=0&&o.offset>=i?(t=o,i=o.offset):o.offset>0&&o.offset<r&&(s=o,r=o.offset);return t??s}function Jv(e,t){return e-t}function Zv(e,t){return Math.max(0,e-t)}function Xv(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const r=s.dataset.markerId;return r===void 0?[]:[{id:r,offset:s.getBoundingClientRect().top-i}]})}const Yv=600,eb=1;function tb(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:ib(e)||sb(e)}function ib(e){return e.scrollTop<(e.topThreshold??Math.max(Yv,e.clientHeight))}function sb(e){return e.scrollHeight<=e.clientHeight+eb}const rb="omp-web:chat-scroll:",ob=180,nb=48,ab=2,lb={getItem(e){return typeof localStorage>"u"?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>"u"||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>"u"||localStorage.removeItem(e)}},cb={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class db{constructor(t=lb,i=cb){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=ob){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=ab){if(t===""||i===void 0||!Js(i))return"skipped";try{if(Bl(i,r)){const a={mode:"bottom"};return this.storage.setItem(Qs(t),JSON.stringify(a)),"saved"}const o=ub(i,s);if(o===void 0)return"skipped";const n=hb(i,o);return this.storage.setItem(Qs(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,r){const o=this.readPosition(t);return o===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(o,i,s,r)}restoreExplicitPosition(t,i,s,r){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!Js(i))return{status:"skipped"};const o=fb(s,t.anchorId);if(o===void 0)return r?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=o.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(Qs(t));if(i===null||i==="")return;const s=JSON.parse(i);return pb(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!Js(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function Qs(e){return`${rb}${e}`}function pb(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function Js(e){return e.clientHeight>0&&e.scrollHeight>0}function Nl(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Bl(e,t=nb){return Nl(e)<t}function hb(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:Xr(t)??"",offset:t.getBoundingClientRect().top-i}}function ub(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(Xr(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function Hn(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function fb(e,t){return e.find(i=>Xr(i)===t)}function Xr(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var gb=Object.defineProperty,mb=Object.getOwnPropertyDescriptor,Yr=(e,t,i,s)=>{for(var r=s>1?void 0:s?mb(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&gb(t,i,r),r};let pi=class extends I{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Kn(this.positionPercent),t=Kn(this.loadedPercent),i=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return l`
1204
+ <div
1205
+ class="meter"
1206
+ style=${`--position:${e.toFixed(2)}%;`}
1207
+ role="meter"
1208
+ aria-label=${i}
1209
+ aria-valuemin="0"
1210
+ aria-valuemax="100"
1211
+ aria-valuenow=${String(Math.round(e))}
1212
+ title=${i}
1213
+ >
1214
+ <div class="track" aria-hidden="true">
1215
+ <div class="progress"></div>
1216
+ <div class="marker"></div>
1217
+ </div>
1218
+ </div>
1219
+ `}};pi.styles=D`
1220
+ :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
1221
+ :host(:hover), :host(:focus-within) { opacity: .92; }
1222
+ .meter { height: 100%; }
1223
+ .track { position: relative; height: 4px; margin-top: 4px; border-radius: 999px; background: color-mix(in srgb, var(--pi-border-muted) 34%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--pi-bg) 55%, transparent); }
1224
+ .progress { position: absolute; left: 0; width: var(--position); top: 0; bottom: 0; border-radius: 999px; background: color-mix(in srgb, var(--pi-accent) 42%, var(--pi-border-muted)); }
1225
+ .marker { position: absolute; left: var(--position); top: 50%; width: 10px; height: 10px; border: 2px solid var(--pi-bg); border-radius: 50%; background: var(--pi-accent); box-shadow: 0 2px 8px var(--pi-shadow); transform: translate(-50%, -50%); }
1226
+ `;Yr([d({type:Number})],pi.prototype,"positionPercent",2);Yr([d({type:Number})],pi.prototype,"loadedPercent",2);pi=Yr([E("conversation-meter")],pi);function Kn(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class gr extends Zr{constructor(t){if(super(t),this.it=N,t.type!==Qr.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===N||t==null)return this._t=void 0,this.it=t;if(t===at)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}gr.directiveName="unsafeHTML",gr.resultType=1;const vb=Jr(gr);function eo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var xt=eo();function zl(e){xt=e}var gt={exec:()=>null};function Rt(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),r=t[s];return r||(r=e(s),t[s]=r),r}}function A(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(ne.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var bb=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),ne={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Rt(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Rt(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Rt(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Rt(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Rt(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Rt(e=>new RegExp(`^ {0,${e}}>`))},wb=/^(?:[ \t]*(?:\n|$))+/,yb=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Sb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,bi=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,xb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,to=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ql=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Hl=A(ql).replace(/bull/g,to).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),kb=A(ql).replace(/bull/g,to).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),io=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,$b=/^[^\n]+/,so=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Pb=A(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",so).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Cb=A(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,to).getRegex(),$s="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ro=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Rb=A("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",ro).replace("tag",$s).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Kl=e=>A(io).replace("hr",bi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~~~)[^\\n]*\\n").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",$s).getRegex(),Mb=Kl(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ib=Kl(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Tb=A(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ib).getRegex(),oo={blockquote:Tb,code:yb,def:Pb,fences:Sb,heading:xb,hr:bi,html:Rb,lheading:Hl,list:Cb,newline:wb,paragraph:Mb,table:gt,text:$b},Vn=A("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",bi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~~~)[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",$s).getRegex(),Ab={...oo,lheading:kb,table:Vn,paragraph:A(io).replace("hr",bi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Vn).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~~~)[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",$s).getRegex()},Eb={...oo,html:A(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ro).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:gt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:A(io).replace("hr",bi).replace("heading",` *#{1,6} *[^
1227
+ ]`).replace("lheading",Hl).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Db=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Wb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Vl=/^( {2,}|\\)\n(?!\s*$)/,Lb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,jt=/[\p{P}\p{S}]/u,Ps=/[\s\p{P}\p{S}]/u,no=/[^\s\p{P}\p{S}]/u,Ob=A(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ps).getRegex(),Gl=/(?!~)[\p{P}\p{S}]/u,Fb=/(?!~)[\s\p{P}\p{S}]/u,_b=/(?:[^\s\p{P}\p{S}]|~)/u,jb=A(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",bb?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ql=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ub=A(Ql,"u").replace(/punct/g,jt).getRegex(),Nb=A(Ql,"u").replace(/punct/g,Gl).getRegex(),Jl="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Bb=A(Jl,"gu").replace(/notPunctSpace/g,no).replace(/punctSpace/g,Ps).replace(/punct/g,jt).getRegex(),zb=A(Jl,"gu").replace(/notPunctSpace/g,_b).replace(/punctSpace/g,Fb).replace(/punct/g,Gl).getRegex(),qb=A("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,no).replace(/punctSpace/g,Ps).replace(/punct/g,jt).getRegex(),Hb=A(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,jt).getRegex(),Kb="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Vb=A(Kb,"gu").replace(/notPunctSpace/g,no).replace(/punctSpace/g,Ps).replace(/punct/g,jt).getRegex(),Gb=A(/\\(punct)/,"gu").replace(/punct/g,jt).getRegex(),Qb=A(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Jb=A(ro).replace("(?:-->|$)","-->").getRegex(),Zb=A("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Jb).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),rs=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Xb=A(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",rs).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Zl=A(/^!?\[(label)\]\[(ref)\]/).replace("label",rs).replace("ref",so).getRegex(),Xl=A(/^!?\[(ref)\](?:\[\])?/).replace("ref",so).getRegex(),Yb=A("reflink|nolink(?!\\()","g").replace("reflink",Zl).replace("nolink",Xl).getRegex(),Gn=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ao={_backpedal:gt,anyPunctuation:Gb,autolink:Qb,blockSkip:jb,br:Vl,code:Wb,del:gt,delLDelim:gt,delRDelim:gt,emStrongLDelim:Ub,emStrongRDelimAst:Bb,emStrongRDelimUnd:qb,escape:Db,link:Xb,nolink:Xl,punctuation:Ob,reflink:Zl,reflinkSearch:Yb,tag:Zb,text:Lb,url:gt},ew={...ao,link:A(/^!?\[(label)\]\((.*?)\)/).replace("label",rs).getRegex(),reflink:A(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",rs).getRegex()},mr={...ao,emStrongRDelimAst:zb,emStrongLDelim:Nb,delLDelim:Hb,delRDelim:Vb,url:A(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Gn).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:A(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Gn).getRegex()},tw={...mr,br:A(Vl).replace("{2,}","*").getRegex(),text:A(mr.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ci={normal:oo,gfm:Ab,pedantic:Eb},Qt={normal:ao,gfm:mr,breaks:tw,pedantic:ew},iw={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Qn=e=>iw[e];function Be(e,t){if(t){if(ne.escapeTest.test(e))return e.replace(ne.escapeReplace,Qn)}else if(ne.escapeTestNoEncode.test(e))return e.replace(ne.escapeReplaceNoEncode,Qn);return e}function Jn(e){try{e=encodeURI(e).replace(ne.percentDecode,"%")}catch{return null}return e}function Zn(e,t){let i=e.replace(ne.findPipe,(o,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(ne.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;r<s.length;r++)s[r]=s[r].trim().replace(ne.slashPipe,"|");return s}function rt(e,t,i){let s=e.length;if(s===0)return"";let r=0;for(;r<s&&e.charAt(s-r-1)===t;)r++;return e.slice(0,s-r)}function Xn(e){let t=e.split(`
1228
+ `),i=t.length-1;for(;i>=0&&ne.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
1229
+ `)}function sw(e,t){if(e.indexOf(t[1])===-1)return-1;let i=0;for(let s=0;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]===t[0])i++;else if(e[s]===t[1]&&(i--,i<0))return s;return i>0?-2:-1}function rw(e,t=0){let i=t,s="";for(let r of e)if(r===" "){let o=4-i%4;s+=" ".repeat(o),i+=o}else s+=r,i++;return s}function Yn(e,t,i,s,r){let o=t.href,n=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function ow(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
1230
+ `).map(o=>{let n=o.match(i.other.beginningSpace);if(n===null)return o;let[a]=n;return a.length>=r.length?o.slice(r.length):o}).join(`
1231
+ `)}var os=class{options;rules;lexer;constructor(e){this.options=e||xt}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Xn(t[0]),s=i.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],s=ow(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let s=rt(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:rt(t[0],`
1232
+ `),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:rt(t[0],`
1233
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=rt(t[0],`
1234
+ `).split(`
1235
+ `),s="",r="",o=[];for(;i.length>0;){let n=!1,a=[],c;for(c=0;c<i.length;c++)if(this.rules.other.blockquoteStart.test(i[c]))a.push(i[c]),n=!0;else if(!n)a.push(i[c]);else break;i=i.slice(c);let p=a.join(`
1236
+ `),u=p.replace(this.rules.other.blockquoteSetextReplace,`
1237
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
1238
+ ${p}`:p,r=r?`${r}
1239
+ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=h,i.length===0)break;let f=o.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let S=f,$=S.raw+`
1240
+ `+i.join(`
1241
+ `),R=this.blockquote($);o[o.length-1]=R,s=s.substring(0,s.length-S.raw.length)+R.raw,r=r.substring(0,r.length-S.text.length)+R.text;break}else if(f?.type==="list"){let S=f,$=S.raw+`
1242
+ `+i.join(`
1243
+ `),R=this.list($);o[o.length-1]=R,s=s.substring(0,s.length-f.raw.length)+R.raw,r=r.substring(0,r.length-S.raw.length)+R.raw,i=$.substring(o.at(-1).raw.length).split(`
1244
+ `);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,r={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let o=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=rw(t[2].split(`
1245
+ `,1)[0],t[1].length),f=e.split(`
1246
+ `,1)[0],S=!h.trim(),$=0;if(this.options.pedantic?($=2,u=h.trimStart()):S?$=t[1].length+1:($=h.search(this.rules.other.nonSpaceChar),$=$>4?1:$,u=h.slice($),$+=t[1].length),S&&this.rules.other.blankLine.test(f)&&(p+=f+`
1247
+ `,e=e.substring(f.length+1),c=!0),!c){let R=this.rules.other.nextBulletRegex($),ee=this.rules.other.hrRegex($),st=this.rules.other.fencesBeginRegex($),uo=this.rules.other.headingBeginRegex($),bc=this.rules.other.htmlBeginRegex($),wc=this.rules.other.blockquoteBeginRegex($);for(;e;){let Is=e.split(`
1248
+ `,1)[0],Ut;if(f=Is,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),Ut=f):Ut=f.replace(this.rules.other.tabCharGlobal," "),st.test(f)||uo.test(f)||bc.test(f)||wc.test(f)||R.test(f)||ee.test(f))break;if(Ut.search(this.rules.other.nonSpaceChar)>=$||!f.trim())u+=`
1249
+ `+Ut.slice($);else{if(S||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||st.test(h)||uo.test(h)||ee.test(h))break;u+=`
1250
+ `+f}S=!f.trim(),p+=Is+`
1251
+ `,e=e.substring(Is.length+1),h=Ut.slice($)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=p}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let c of r.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,r.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!r.loose){let u=c.tokens.filter(f=>f.type==="space"),h=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));r.loose=h}}if(r.loose)for(let c of r.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Xn(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:rt(t[0],`
1252
+ `),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Zn(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
1253
+ `):[],o={type:"table",raw:rt(t[0],`
1254
+ `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?o.align.push("right"):this.rules.other.tableAlignCenter.test(n)?o.align.push("center"):this.rules.other.tableAlignLeft.test(n)?o.align.push("left"):o.align.push(null);for(let n=0;n<i.length;n++)o.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:o.align[n]});for(let n of r)o.rows.push(Zn(n,o.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:rt(t[0],`
1255
+ `),depth:t[2].charAt(0)==="="?1:2,text:i,tokens:this.lexer.inline(i)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let i=t[1].charAt(t[1].length-1)===`
1256
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let o=rt(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=sw(t[2],"()");if(o===-2)return;if(o>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(s);o&&(s=o[1],r=o[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),Yn(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[s.toLowerCase()];if(!r){let o=i[0].charAt(0);return{type:"text",raw:o,text:o}}return Yn(i,r,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+r);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(n=[...o].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&r%3&&!((r+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,r+s.index+u+n);if(Math.min(r,n)%2){let S=h.slice(1,-1);return{type:"em",raw:h,text:S,tokens:this.lexer.inlineTokens(S)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),r=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&r&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(n=[...o].length,n!==r))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,r+s.index+p+n),h=u.slice(r,-r);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},Le=class vr{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||xt,this.options.tokenizer=this.options.tokenizer||new os,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let i={other:ne,block:Ci.normal,inline:Qt.normal};this.options.pedantic?(i.block=Ci.pedantic,i.inline=Qt.pedantic):this.options.gfm&&(i.block=Ci.gfm,this.options.breaks?i.inline=Qt.breaks:i.inline=Qt.gfm),this.tokenizer.rules=i}static get rules(){return{block:Ci,inline:Qt}}static lex(t,i){return new vr(i).lex(t)}static lexInline(t,i){return new vr(i).inlineTokens(t)}lex(t){t=t.replace(ne.carriageReturn,`
1257
+ `),this.blockTokens(t,this.tokens);for(let i=0;i<this.inlineQueue.length;i++){let s=this.inlineQueue[i];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,i=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(ne.tabCharGlobal," ").replace(ne.spaceLine,""));let r=1/0;for(;t;){if(t.length<r)r=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let a=i.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
1258
+ `:i.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
1259
+ `)?"":`
1260
+ `)+o.raw,a.text+=`
1261
+ `+o.text,this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
1262
+ `)?"":`
1263
+ `)+o.raw,a.text+=`
1264
+ `+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},i.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),i.push(o);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,c=t.slice(1),p;this.options.extensions.startBlock.forEach(u=>{p=u.call({lexer:this},c),typeof p=="number"&&p>=0&&(a=Math.min(a,p))}),a<1/0&&a>=0&&(n=t.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
1265
+ `)?"":`
1266
+ `)+o.raw,a.text+=`
1267
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o),s=n.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
1268
+ `)?"":`
1269
+ `)+o.raw,a.text+=`
1270
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t;if(this.tokens.links){let a=Object.keys(this.tokens.links);a.length>0&&(s=s.replace(this.tokenizer.rules.inline.reflinkSearch,c=>a.includes(c.slice(c.lastIndexOf("[")+1,-1))?"["+"a".repeat(c.length-2)+"]":c))}s=s.replace(this.tokenizer.rules.inline.anyPunctuation,"++"),s=s.replace(this.tokenizer.rules.inline.blockSkip,(a,c,p)=>{let u=p?p.length:0;return a.slice(0,u)+"["+"a".repeat(a.length-u-2)+"]"}),s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let r=!1,o="",n=1/0;for(;t;){if(t.length<n)n=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}r||(o=""),r=!1;let a;if(this.options.extensions?.inline?.some(p=>(a=p.call({lexer:this},t,i))?(t=t.substring(a.raw.length),i.push(a),!0):!1))continue;if(a=this.tokenizer.escape(t)){t=t.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.tag(t)){t=t.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.link(t)){t=t.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(a.raw.length);let p=i.at(-1);a.type==="text"&&p?.type==="text"?(p.raw+=a.raw,p.text+=a.text):i.push(a);continue}if(a=this.tokenizer.emStrong(t,s,o)){t=t.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.codespan(t)){t=t.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.br(t)){t=t.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.del(t,s,o)){t=t.substring(a.raw.length),i.push(a);continue}if(a=this.tokenizer.autolink(t)){t=t.substring(a.raw.length),i.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(t))){t=t.substring(a.raw.length),i.push(a);continue}let c=t;if(this.options.extensions?.startInline){let p=1/0,u=t.slice(1),h;this.options.extensions.startInline.forEach(f=>{h=f.call({lexer:this},u),typeof h=="number"&&h>=0&&(p=Math.min(p,h))}),p<1/0&&p>=0&&(c=t.substring(0,p+1))}if(a=this.tokenizer.inlineText(c)){t=t.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(o=a.raw.slice(-1)),r=!0;let p=i.at(-1);p?.type==="text"?(p.raw+=a.raw,p.text+=a.text):i.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},ns=class{options;parser;constructor(e){this.options=e||xt}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(ne.notSpaceStart)?.[0],r=e.replace(ne.endingNewline,"")+`
1271
+ `;return s?'<pre><code class="language-'+Be(s)+'">'+(i?r:Be(r,!0))+`</code></pre>
1272
+ `:"<pre><code>"+(i?r:Be(r,!0))+`</code></pre>
1273
+ `}blockquote({tokens:e}){return`<blockquote>
1274
+ ${this.parser.parse(e)}</blockquote>
1275
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
1276
+ `}hr(e){return`<hr>
1277
+ `}list(e){let t=e.ordered,i=e.start,s="";for(let n=0;n<e.items.length;n++){let a=e.items[n];s+=this.listitem(a)}let r=t?"ol":"ul",o=t&&i!==1?' start="'+i+'"':"";return"<"+r+o+`>
1278
+ `+s+"</"+r+`>
1279
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
1280
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
1281
+ `}table(e){let t="",i="";for(let r=0;r<e.header.length;r++)i+=this.tablecell(e.header[r]);t+=this.tablerow({text:i});let s="";for(let r=0;r<e.rows.length;r++){let o=e.rows[r];i="";for(let n=0;n<o.length;n++)i+=this.tablecell(o[n]);s+=this.tablerow({text:i})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
1282
+ <thead>
1283
+ `+t+`</thead>
1284
+ `+s+`</table>
1285
+ `}tablerow({text:e}){return`<tr>
1286
+ ${e}</tr>
1287
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
1288
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Be(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),r=Jn(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+Be(t)+'"'),o+=">"+s+"</a>",o}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let r=Jn(e);if(r===null)return Be(i);e=r;let o=`<img src="${e}" alt="${Be(i)}"`;return t&&(o+=` title="${Be(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Be(e.text)}},lo=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Oe=class br{options;renderer;textRenderer;constructor(t){this.options=t||xt,this.options.renderer=this.options.renderer||new ns,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new lo}static parse(t,i){return new br(i).parse(t)}static parseInline(t,i){return new br(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let r=t[s];if(this.options.extensions?.renderers?.[r.type]){let n=r,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let o=r;switch(o.type){case"space":{i+=this.renderer.space(o);break}case"hr":{i+=this.renderer.hr(o);break}case"heading":{i+=this.renderer.heading(o);break}case"code":{i+=this.renderer.code(o);break}case"table":{i+=this.renderer.table(o);break}case"blockquote":{i+=this.renderer.blockquote(o);break}case"list":{i+=this.renderer.list(o);break}case"checkbox":{i+=this.renderer.checkbox(o);break}case"html":{i+=this.renderer.html(o);break}case"def":{i+=this.renderer.def(o);break}case"paragraph":{i+=this.renderer.paragraph(o);break}case"text":{i+=this.renderer.text(o);break}default:{let n='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let r=0;r<t.length;r++){let o=t[r];if(this.options.extensions?.renderers?.[o.type]){let a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){s+=a||"";continue}}let n=o;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},ii=class{options;block;constructor(e){this.options=e||xt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Le.lex:Le.lexInline}provideParser(e=this.block){return e?Oe.parse:Oe.parseInline}},nw=class{defaults=eo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Oe;Renderer=ns;TextRenderer=lo;Lexer=Le;Tokenizer=os;Hooks=ii;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let r=s;for(let o of r.header)i=i.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let n of o)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let r=s;i=i.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let n=r[o].flat(1/0);i=i.concat(this.walkTokens(n,t))}):r.tokens&&(i=i.concat(this.walkTokens(r.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...n){let a=r.renderer.apply(this,n);return a===!1&&(a=o.apply(this,n)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),i.renderer){let r=this.defaults.renderer||new ns(this.defaults);for(let o in i.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let n=o,a=i.renderer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new os(this.defaults);for(let o in i.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let n=o,a=i.tokenizer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new ii;for(let o in i.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let n=o,a=i.hooks[n],c=r[n];ii.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&ii.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return c.call(r,h)})();let u=a.call(r,p);return c.call(r,u)}:r[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,p);return h===!1&&(h=await c.apply(r,p)),h})();let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.hooks=r}if(i.walkTokens){let r=this.defaults.walkTokens,o=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(o.call(this,n)),r&&(a=a.concat(r.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Le.lex(e,t??this.defaults)}parser(e,t){return Oe.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},r={...this.defaults,...s},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let n=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?Le.lex:Le.lexInline)(n,r),c=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(c,r.walkTokens));let p=await(r.hooks?await r.hooks.provideParser(e):e?Oe.parse:Oe.parseInline)(c,r);return r.hooks?await r.hooks.postprocess(p):p})().catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let n=(r.hooks?r.hooks.provideLexer(e):e?Le.lex:Le.lexInline)(t,r);r.hooks&&(n=r.hooks.processAllTokens(n)),r.walkTokens&&this.walkTokens(n,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?Oe.parse:Oe.parseInline)(n,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(n){return o(n)}}}onError(e,t){return i=>{if(i.message+=`
1289
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Be(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},yt=new nw;function O(e,t){return yt.parse(e,t)}O.options=O.setOptions=function(e){return yt.setOptions(e),O.defaults=yt.defaults,zl(O.defaults),O};O.getDefaults=eo;O.defaults=xt;O.use=function(...e){return yt.use(...e),O.defaults=yt.defaults,zl(O.defaults),O};O.walkTokens=function(e,t){return yt.walkTokens(e,t)};O.parseInline=yt.parseInline;O.Parser=Oe;O.parser=Oe.parse;O.Renderer=ns;O.TextRenderer=lo;O.Lexer=Le;O.lexer=Le.lex;O.Tokenizer=os;O.Hooks=ii;O.parse=O;O.options;O.setOptions;O.use;O.walkTokens;O.parseInline;Oe.parse;Le.lex;const Yl=new O.Renderer;Yl.html=({text:e})=>cw(e);const aw=300,Jt=new Map;function lw(e){const t=Jt.get(e);if(t!==void 0)return t;const i=O.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Yl}),s=dw(i);if(Jt.set(e,s),Jt.size>aw){const r=Jt.keys().next().value;r!==void 0&&Jt.delete(r)}return s}function cw(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function dw(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const r=s.name.toLowerCase();r.startsWith("on")&&i.removeAttribute(s.name),(r==="href"||r==="src")&&!pw(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function pw(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var hw=Object.defineProperty,uw=Object.getOwnPropertyDescriptor,ec=(e,t,i,s)=>{for(var r=s>1?void 0:s?uw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&hw(t,i,r),r};let as=class extends I{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)}}render(){return l`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${vb(lw(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains("code-block-wrapper")===!0||!(e.querySelector("code")instanceof HTMLElement))return;const i=document.createElement("div");i.className="code-block-wrapper";const s=document.createElement("button");s.type="button",s.className="code-copy-button",s.title="Copy code block",s.setAttribute("aria-label","Copy code block");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⧉",s.append(r),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await fw(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"Copied code block":t==="failed"?"Failed to copy code block":"Copy code block";e.title=s,e.setAttribute("aria-label",s)}};as.styles=wg;ec([d()],as.prototype,"text",2);as=ec([E("formatted-text")],as);async function fw(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var gw=Object.defineProperty,mw=Object.getOwnPropertyDescriptor,wi=(e,t,i,s)=>{for(var r=s>1?void 0:s?mw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&gw(t,i,r),r};const ea=180;let St=class extends I{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=bw(e.args),i=ww(e.details),s=e.preview,r=i??s?.diff,o=r===void 0?void 0:yw(r),n=i!==void 0&&s?.diff!==void 0&&i!==s.diff,a=e.status==="error"?e.resultText:s?.error,c=r===void 0?e.resultText:void 0,p=vw(e,t);return l`
1290
+ <section class=${`tool-card ${e.status}`}>
1291
+ <div class="tool-header">
1292
+ <div class="tool-title">
1293
+ <span class="status-icon" aria-hidden="true">${xw(e.status)}</span>
1294
+ <strong>${e.toolName}</strong>
1295
+ ${this.renderHeaderTarget(p)}
1296
+ </div>
1297
+ <div class="tool-meta">
1298
+ ${ta(e)===void 0?null:l`<span>${ta(e)}</span>`}
1299
+ ${o===void 0?null:l`<span class="diff-stats"><b class="added">+${o.added}</b><span>/</span><b class="removed">-${o.removed}</b></span>`}
1300
+ <span class="status-label">${kw(e.status)}</span>
1301
+ </div>
1302
+ </div>
1303
+
1304
+ ${n?l`<p class="notice">Applied diff differs from the preview.</p>`:null}
1305
+ ${a===void 0||a===""?null:l`<pre class="error-text">${a}</pre>`}
1306
+ ${r===void 0?this.renderTextBody(c,e.status==="error",p):this.renderDiffBody(r,i===void 0?"Preview diff":"Applied diff",p)}
1307
+ </section>
1308
+ `}renderHeaderTarget(e){if(e===void 0)return null;const t=e.label==="File"?"path":"summary";return l`<span class=${t} title=${e.text} aria-label=${`${e.label}: ${e.text}`}>${e.text}</span>`}renderExpandedTarget(e){return e===void 0?null:l`
1309
+ <div class="detail-target">
1310
+ <span class="detail-label">${e.label}</span>
1311
+ <pre class="detail-target-value">${e.text}</pre>
1312
+ </div>
1313
+ `}renderTextBody(e,t,i){return(e===void 0||e==="")&&i===void 0?null:l`
1314
+ <details class="text-body" ?open=${t}>
1315
+ <summary>Details</summary>
1316
+ ${this.renderExpandedTarget(i)}
1317
+ ${e===void 0||e===""?null:l`
1318
+ <div class="detail-result">
1319
+ <span class="detail-label">Result</span>
1320
+ <pre>${e}</pre>
1321
+ </div>
1322
+ `}
1323
+ </details>
1324
+ `}renderDiffBody(e,t,i){const s=e.split(`
1325
+ `),r=!this.showFullDiff&&s.length>ea,o=r?s.slice(0,ea):s;return l`
1326
+ <details class="diff-details" ?open=${this.diffOpen} @toggle=${n=>{this.onDiffToggle(n)}}>
1327
+ <summary>
1328
+ <span>${t}</span>
1329
+ <small>${String(s.length)} ${s.length===1?"line":"lines"}</small>
1330
+ </summary>
1331
+ ${this.renderExpandedTarget(i)}
1332
+ <div class="diff-toolbar">
1333
+ <span>${r?`Showing ${String(o.length)} of ${String(s.length)} lines`:"Full diff"}</span>
1334
+ <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"Copied":"Copy diff"}</button>
1335
+ </div>
1336
+ <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(n=>l`<span class=${Sw(n)}>${n}</span>`)}</code></pre>
1337
+ ${r?l`
1338
+ <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
1339
+ Show all ${String(s.length)} diff lines
1340
+ </button>
1341
+ `:null}
1342
+ </details>
1343
+ `}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){try{await navigator.clipboard.writeText(e),this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}catch{this.copied=!1}}};St.styles=D`
1344
+ :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
1345
+ .tool-card { display: grid; gap: 8px; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 9px; color: var(--pi-text); }
1346
+ .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
1347
+ .tool-card.success { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
1348
+ .tool-card.error { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); }
1349
+ .tool-header { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; min-width: 0; }
1350
+ .tool-title { flex: 1 1 auto; display: inline-flex; align-items: baseline; gap: 7px; min-width: 0; }
1351
+ .status-icon { flex: 0 0 auto; color: var(--pi-muted); }
1352
+ strong { flex: 0 0 auto; color: var(--pi-text); }
1353
+ .path, .summary { display: block; flex: 1 1 auto; min-width: 0; max-width: 100%; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; white-space: pre; color: var(--pi-accent); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; direction: ltr; text-align: left; unicode-bidi: isolate; }
1354
+ .summary { color: var(--pi-muted); font-family: inherit; }
1355
+ .tool-meta { flex: 0 0 auto; display: inline-flex; align-items: baseline; gap: 8px; color: var(--pi-muted); font-size: 12px; }
1356
+ .diff-stats { display: inline-flex; gap: 3px; }
1357
+ .added, .diff .added { color: var(--pi-success); }
1358
+ .removed, .diff .removed { color: var(--pi-danger); }
1359
+ .status-label { text-transform: uppercase; letter-spacing: .04em; color: var(--pi-muted); }
1360
+ .notice { margin: 0; color: var(--pi-warning); }
1361
+ .muted { margin: 0; color: var(--pi-muted); }
1362
+ .error-text { margin: 0; border: 1px solid var(--pi-danger); border-radius: 7px; background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); color: var(--pi-danger); padding: 8px; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1363
+ .text-body { border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
1364
+ .detail-target, .detail-result { display: grid; gap: 4px; margin-top: 8px; min-width: 0; }
1365
+ .detail-label { color: var(--pi-muted); font-size: 12px; text-transform: uppercase; letter-spacing: .04em; }
1366
+ .text-body pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--pi-text); }
1367
+ .detail-result pre { box-sizing: border-box; max-width: 100%; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; border: 1px solid var(--pi-border-muted); border-radius: 7px; background: var(--pi-bg); padding: 8px; white-space: pre; overflow-wrap: normal; direction: ltr; text-align: left; unicode-bidi: isolate; }
1368
+ .detail-target-value { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--pi-accent); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; direction: ltr; text-align: left; unicode-bidi: isolate; }
1369
+ .diff-details { min-width: 0; max-width: 100%; border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
1370
+ .diff-details > summary { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; min-width: 0; color: var(--pi-muted); cursor: pointer; }
1371
+ .diff-details > summary span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1372
+ .diff-details > summary small { flex: 0 0 auto; color: var(--pi-dim); }
1373
+ .diff-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-width: 0; margin-top: 8px; color: var(--pi-muted); font-size: 12px; }
1374
+ .diff-toolbar span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1375
+ button { border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-text); padding: 3px 7px; font: 12px system-ui, sans-serif; cursor: pointer; }
1376
+ button:hover, button:focus { border-color: var(--pi-accent); }
1377
+ .diff { box-sizing: border-box; width: 100%; max-width: 100%; min-width: 0; margin: 0; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; border: 1px solid var(--pi-border-muted); border-radius: 7px; background: var(--pi-bg); padding: 8px 0; color: var(--pi-muted); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
1378
+ .diff-content { display: block; width: max-content; min-width: 100%; }
1379
+ .diff span { display: block; min-height: 1.45em; padding: 0 8px; white-space: pre; }
1380
+ .diff .context { color: var(--pi-muted); }
1381
+ .diff .hunk { color: var(--pi-accent); }
1382
+ .diff .file { color: var(--pi-dim); }
1383
+ .diff .meta { color: var(--pi-dim); }
1384
+ .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
1385
+ .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
1386
+ .show-more { justify-self: start; }
1387
+ `;wi([d({attribute:!1})],St.prototype,"execution",2);wi([v()],St.prototype,"showFullDiff",2);wi([v()],St.prototype,"copied",2);wi([v()],St.prototype,"diffOpen",2);St=wi([E("tool-execution-view")],St);function vw(e,t){if(t!==void 0&&t!=="")return{label:"File",text:t};const i=ls(e.args,"command");if(i!==void 0&&i!=="")return{label:"Command",text:i};if(e.summary!=="")return{label:"Input",text:e.summary}}function bw(e){return ls(e,"path")??ls(e,"file_path")}function ta(e){if(e.toolName!=="edit")return;const t=Ui(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?"":"s"}`;if(typeof Ui(e.args,"oldText")=="string"&&typeof Ui(e.args,"newText")=="string")return"1 edit"}function ww(e){return ls(e,"diff")}function yw(e){let t=0,i=0;for(const s of e.split(`
1388
+ `))tc(s)?t++:ic(s)&&i++;return{added:t,removed:i}}function Sw(e){return tc(e)?"added":ic(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function tc(e){return e.startsWith("+")&&!e.startsWith("+++")}function ic(e){return e.startsWith("-")&&!e.startsWith("---")}function xw(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function kw(e){return e==="success"?"done":e==="error"?"failed":e==="running"?"running":"pending"}function Ui(e,t){return B(e)?e[t]:void 0}function ls(e,t){const i=Ui(e,t);return typeof i=="string"?i:void 0}var $w=Object.defineProperty,Pw=Object.getOwnPropertyDescriptor,V=(e,t,i,s)=>{for(var r=s>1?void 0:s?Pw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$w(t,i,r),r};const Cw=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Rw=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),Zs=["You opened this chat while the assistant was already replying. The complete answer will appear shortly.","We joined mid-sentence. Holding the curtain until the full reply is ready.","The assistant started before this tab arrived. We’ll show the full answer when it lands.","Catching the reply in one piece — no spoilers, no half-answers.","The tokens are still assembling themselves. Full answer incoming.","We arrived fashionably late to this response. The complete version will appear soon."];function ia(){return Zs[Math.floor(Math.random()*Zs.length)]??Zs[0]}function sa(e){return Ni(e,0,100)}function Ni(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}function Mw(e,t){return[e.length===0?void 0:{heading:"Queued until session starts",detail:"Will send once the backend session is ready",messages:e},t.length===0?void 0:{heading:"Queued messages",detail:`${String(t.length)} pending · Stop clears the queue`,messages:t}].filter(i=>i!==void 0)}let H=class extends I{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.clientQueuedMessages=[],this.pinnedToBottom=!0,this.disclosures=new Bv,this.scrollController=new db,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),e.has("sessionId")&&this.restoreScrollPosition(),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
1389
+ <div class="chat-wrap">
1390
+ ${this.renderConversationRail()}
1391
+ <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
1392
+ ${this.renderHistoryBoundary()}
1393
+ ${jv(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupRenderKey(t.startIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
1394
+ ${this.renderQueuedMessages()}
1395
+ ${this.renderSessionActivity()}
1396
+ </div>
1397
+ ${this.renderActivityDock()}
1398
+ </div>
1399
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=qv(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
1400
+ <div class="activity-dock active" aria-live="polite">
1401
+ <span class="dot"></span>
1402
+ <span class="activity-text">Sending your message…</span>
1403
+ </div>
1404
+ `;const e=this.activityState();if(e===void 0)return null;const t=e!=="idle"||this.activity?.phase==="active";return l`
1405
+ <div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
1406
+ <span class="dot"></span>
1407
+ <span class="activity-text">${this.activityText(e)}</span>
1408
+ </div>
1409
+ `}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return l`${Mw(this.clientQueuedMessages,e).map(t=>this.renderQueuedMessageList(t))}`}renderQueuedMessageList(e){return l`
1410
+ <aside class="queued-messages" aria-live="polite">
1411
+ <div class="queued-header">
1412
+ <strong>${e.heading}</strong>
1413
+ <small>${e.detail}</small>
1414
+ </div>
1415
+ ${e.messages.map((t,i)=>l`
1416
+ <div class="queued-message">
1417
+ <span class="queued-kind">${t.kind==="steer"?"Steer":"Follow-up"} ${String(i+1)}</span>
1418
+ <formatted-text .text=${t.text}></formatted-text>
1419
+ </div>
1420
+ `)}
1421
+ </aside>
1422
+ `}renderSessionActivity(){return this.isReceivingPartialStream?l`
1423
+ <aside class="session-activity receiving" aria-live="polite">
1424
+ <strong>Catching up…</strong>
1425
+ <span>${this.currentPartialStreamNoticeBody()}</span>
1426
+ </aside>
1427
+ `:this.isCompacting?l`
1428
+ <aside class="session-activity compacting" aria-live="polite">
1429
+ <strong>Compacting history…</strong>
1430
+ <span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
1431
+ ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?"message":"messages"}</small>`:null}
1432
+ </aside>
1433
+ `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?ia():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=ia(),this.partialStreamNoticeBody}activityState(){const e=this.status;return e===void 0?this.activity?.label:e.isCompacting?"compacting":e.isBashRunning?"bash":e.isStreaming?"running":e.pendingMessageCount>0?"queued":"idle"}activityText(e){const t=this.activity;return t===void 0||e!=="idle"&&t.phase==="idle"?e:t.detail!==void 0&&t.detail!==""?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?sa(this.messages.length/e*100):100;return l`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=Ni(this.currentConversationIndex??t,0,e-1);return sa(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?l`
1434
+ <div class="history-boundary">
1435
+ <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
1436
+ <span>Scroll up to load earlier messages</span>
1437
+ ${e}
1438
+ </div>
1439
+ `:this.messages.length?l`<div class="history-boundary"><span>Beginning of session</span>${e}</div>`:null}historyRangeLabel(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.messageStart+1,t=this.loadedRawMessageEnd(),i=Math.max(this.messageTotal,t);return l`<small>Showing messages ${e}–${t} of ${i}</small>`}loadedRawMessageEnd(){return Math.max(this.messageEnd,this.messageStart+this.messages.length)}renderMessage(e,t){const i=this.isToolExecutionOnlyMessage(e);return l`
1440
+ ${this.renderScrollMarker(this.messageScrollMarkerId(t))}
1441
+ <article class=${i?"msg tool-execution-shell":`msg ${e.role}`} data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
1442
+ ${i?null:this.renderMessageHeader(e,String(t))}
1443
+ ${e.parts.map(s=>this.renderPart(s,e))}
1444
+ </article>
1445
+ `}isToolExecutionOnlyMessage(e){return e.role==="tool"&&e.parts.length>0&&e.parts.every(t=>t.type==="toolExecution")}renderMessageGroup(e,t,i,s){const r=this.groupDisclosureKey(t,i,s),o=this.disclosures.isOpen(r,s);return l`
1446
+ ${this.renderScrollMarker(this.groupScrollMarkerId(i))}
1447
+ <details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${o} @toggle=${n=>{this.onGroupToggle(r,n,s)}}>
1448
+ <summary>
1449
+ <b class="label">${s?"live events":"events"}</b>
1450
+ <span>${Hv(e)}</span>
1451
+ </summary>
1452
+ <div class="group-body">
1453
+ ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
1454
+ <section class=${c?"group-msg tool-execution-shell":`group-msg ${n.role}`} data-index=${t+a} data-scroll-anchor-id=${this.eventAnchorKey(t+a)}>
1455
+ ${c?null:this.renderMessageHeader(n,`${String(t)}:${String(a)}`)}
1456
+ ${n.parts.map(p=>this.renderPart(p,n))}
1457
+ </section>
1458
+ `})}
1459
+ </div>
1460
+ </details>
1461
+ `}renderScrollMarker(e){return l`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t){const i=this.messageMetaLabel(e),s=this.expandedMetaKey===t;return l`
1462
+ <div class="msg-header">
1463
+ <b class="label">${e.role}</b>
1464
+ <div class="msg-header-trailing">
1465
+ ${this.renderMessageActions(e,t)}
1466
+ <span class=${s?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${i.full} aria-label=${i.full} aria-expanded=${String(s)} @click=${()=>{this.expandedMetaKey=s?void 0:t}} @keydown=${r=>{this.onMetaKeydown(r,t,s)}}>${i.short}</span>
1467
+ </div>
1468
+ </div>
1469
+ `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
1470
+ <div class="msg-actions" aria-label="Message actions">
1471
+ <button type="button" class="msg-action" title=${i?"Copied":"Copy message"} aria-label=${`${i?"Copied":"Copy"} ${e.role} message`} @click=${s=>{this.copyMessage(e,t,s)}}>
1472
+ <span aria-hidden="true">${i?"✓":"⧉"}</span>
1473
+ </button>
1474
+ </div>
1475
+ `}onMetaKeydown(e,t,i){e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),this.expandedMetaKey=i?void 0:t)}isCopyableMessage(e){return(e.role==="user"||e.role==="assistant")&&this.messageCopyText(e)!==""}messageCopyText(e){const t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;const i=e.parts.filter(s=>s.type==="text").map(s=>s.text.trim()).filter(s=>s!=="").join(`
1476
+
1477
+ `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"no info",full:"No Pi message metadata available"};return this.messageMetaCache.set(e,c),c}const r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(c=>c!==void 0&&c!==""),n=[r?.full,s===void 0?void 0:`Model: ${s}`].filter(c=>c!==void 0&&c!==""),a={short:o.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:Cw.format(t),full:Rw.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="thinking"?l`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
1478
+ <details class="part skill-invocation">
1479
+ <summary><b>[skill]</b> ${e.name}</summary>
1480
+ <small>${e.location}</small>
1481
+ <formatted-text .text=${e.content}></formatted-text>
1482
+ </details>
1483
+ `:e.type==="skillRead"?l`
1484
+ <div class="part skill-read">
1485
+ <strong>Loaded ${e.name}</strong>
1486
+ <small>read ${e.path}</small>
1487
+ </div>
1488
+ `:e.type==="image"?l`<img class="part chat-image" src=${`data:${e.mimeType};base64,${e.data}`} alt="attached image" loading="lazy" />`:e.type==="toolCall"?l`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type==="toolExecution"?l`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type==="toolResult"?l`
1489
+ <details class="part" ?open=${e.isError}>
1490
+ <summary>${e.isError?"✖":"✓"} ${e.toolName} result</summary>
1491
+ <formatted-text .text=${e.text}></formatted-text>
1492
+ </details>
1493
+ `:null}onGroupToggle(e,t,i){const s=t.currentTarget;s instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,s.open,i)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){const t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){const e=this.chat;if(!e)return;const t=this.didChatHeightChange(),i=this.pinnedToBottom,s=e.scrollTop<this.lastScrollTop;if(t&&i){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:s?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){const e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){const t=e.get("messageStart");return typeof t=="number"&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;const e=this.chat;e&&tb({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){const e=this.chat;return e?Bl(e):!0}isAtBottom(){const e=this.chat;return e?Nl(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;const e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){const e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){const e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const i=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,i)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!=="missing"){this.updatePinnedToBottomAfterRestore(t.status),(t.status==="restored"||t.status==="bottom")&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;const i=this.chat;i===void 0||!this.hasMore||this.loadingMore||(i.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore&&!this.isReceivingPartialStream}updatePinnedToBottomAfterRestore(e){e==="bottom"?this.pinnedToBottom=!0:e==="restored"&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){const e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){const e=this.chat;if(e)return Vv(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const r=this.chat;if(!(!r||t!==this.prependRestoreToken)){if(Gv(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<Kv){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=Ni(i,0,Math.max(0,e-1));return}this.currentConversationIndex=Ni(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(e===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return Hn(e,t)??Hn(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};H.styles=bg;V([d({attribute:!1})],H.prototype,"messages",2);V([d()],H.prototype,"sessionId",2);V([d({type:Number})],H.prototype,"messageStart",2);V([d({type:Number})],H.prototype,"messageEnd",2);V([d({type:Number})],H.prototype,"messageTotal",2);V([d({type:Boolean})],H.prototype,"hasMore",2);V([d({type:Boolean})],H.prototype,"loadingMore",2);V([d({type:Boolean})],H.prototype,"isReceivingPartialStream",2);V([d({type:Boolean})],H.prototype,"isSendingPrompt",2);V([d({type:Boolean})],H.prototype,"isCompacting",2);V([d({type:Number})],H.prototype,"pendingMessageCount",2);V([d({attribute:!1})],H.prototype,"clientQueuedMessages",2);V([d({attribute:!1})],H.prototype,"status",2);V([d({attribute:!1})],H.prototype,"activity",2);V([d({attribute:!1})],H.prototype,"onLoadMore",2);V([K(".chat")],H.prototype,"chat",2);V([v()],H.prototype,"pinnedToBottom",2);V([v()],H.prototype,"expandedMetaKey",2);V([v()],H.prototype,"copiedMessageKey",2);V([v()],H.prototype,"currentConversationIndex",2);V([v()],H.prototype,"loadMoreRequested",2);H=V([E("chat-view")],H);const Iw=["image/jpeg","image/png","image/gif","image/webp"],Tw=new Set(Iw);function co(e){return typeof e=="string"&&Tw.has(e)}function Aw(e){switch(e){case"image/jpeg":return"jpg";case"image/png":return"png";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}const Ew="application/octet-stream",Dw="Failed to read an attachment.";async function Ww(e,t){const i=[];let s;for(const r of e)try{const o=await t(r);i.push(Ow(r,o))}catch{s=Dw}return{attachments:i,...s===void 0?{}:{error:s}}}function wr(e){return e.kind==="image"&&co(e.mimeType)}function yr(e){return e.every(t=>wr(t))}function Lw(e,t){return yr(t)?e:"folder"}function Ow(e,t){return co(e.type)?{kind:"image",name:ra(e),mimeType:e.type,data:t,size:e.size}:{kind:"file",name:ra(e),mimeType:Fw(e),data:t,size:e.size}}function Fw(e){const t=e.type.trim();return t===""?Ew:t}function ra(e){return e.name!==""?e.name:co(e.type)?`pasted-image.${Aw(e.type)}`:"pasted-file.bin"}const sc="omp-web:attachment-delivery";function rc(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function _w(e=rc()){try{return e?.getItem(sc)==="folder"?"folder":"inline"}catch{return"inline"}}function jw(e,t=rc()){try{t?.setItem(sc,e)}catch{}}const Uw="(pointer: coarse), (max-width: 760px)",oc="omp-web.promptEnterPreference";function Cs(){return typeof window<"u"&&"matchMedia"in window?window.matchMedia(Uw):void 0}function Nw(e){return e==="send"||e==="newline"?e:"auto"}function Rs(e=nc()){if(e===void 0)return"auto";try{return Nw(e.getItem(oc))}catch{return"auto"}}function Bw(e,t=nc()){if(t!==void 0)try{t.setItem(oc,e)}catch{}}function zw(e=Cs(),t=Rs()){return t==="send"?!0:t==="newline"?!1:e?.matches!==!0}function qw(e,t,i=Cs()){return e?i?.matches===!0?t:!0:!1}function Hw(e,t=Cs(),i=Rs()){const s=zw(t,i);return e?!s:s}function nc(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function Kw(){return ye`
1494
+ <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1495
+ <path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
1496
+ </svg>
1497
+ `}function ac(){return ye`
1498
+ <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1499
+ <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
1500
+ <path d="M21 3 11.5 12.5"></path>
1501
+ </svg>
1502
+ `}function Vw(){return ye`
1503
+ <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1504
+ <path d="M4 7h11"></path>
1505
+ <path d="M4 12h7"></path>
1506
+ <path d="M4 17h7"></path>
1507
+ <path d="m15 14 5 3-5 3z"></path>
1508
+ </svg>
1509
+ `}function Gw(){return ac()}function Qw(){return ye`
1510
+ <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1511
+ <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
1512
+ </svg>
1513
+ `}function Jw(e){const t=Math.max(e.total,1),i=t>1?1.2:0,s=3,n=(21-s-i*(t-1))/t,a=Array.from({length:t},(c,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,f=20-h,S=p<e.filled;return ye`<rect class=${S?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${f} width=${n} height=${h} rx="1"></rect>`});return ye`
1514
+ <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1515
+ ${a}
1516
+ </svg>
1517
+ `}const Zw=["off","minimal","low","medium","high","xhigh"];function Sr(e){return e===void 0||e===""?"off":e}function Xw(e,t){const i=t.length>=2?t:Zw,s=i.length-1,r=Sr(e),o=i.indexOf(r),n=o<=0?0:Math.min(o,s);return{total:s,filled:n}}class Yw extends Zr{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===Qr.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const r="element"in t?t.element:void 0;requestAnimationFrame(()=>{r instanceof HTMLElement&&r.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const po=Jr(Yw);var ey=Object.defineProperty,ty=Object.getOwnPropertyDescriptor,Ms=(e,t,i,s)=>{for(var r=s>1?void 0:s?ty(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ey(t,i,r),r};let Ot=class extends I{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1518
+ <div class="menu">
1519
+ ${this.items.map((e,t)=>l`
1520
+ <button class=${t===this.selectedIndex?"selected":""} ${po(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1521
+ <strong>${e.insertText}</strong>
1522
+ <span>${e.detail}</span>
1523
+ ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1524
+ </button>
1525
+ `)}
1526
+ </div>
1527
+ `:null}};Ot.styles=Sg;Ms([d({attribute:!1})],Ot.prototype,"items",2);Ms([d({type:Number})],Ot.prototype,"selectedIndex",2);Ms([d({attribute:!1})],Ot.prototype,"onPick",2);Ot=Ms([E("autocomplete-menu")],Ot);var iy=Object.defineProperty,sy=Object.getOwnPropertyDescriptor,z=(e,t,i,s)=>{for(var r=s>1?void 0:s?sy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&iy(t,i,r),r};let U=class extends I{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.currentInputMode={kind:"normal"},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=_w(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new fo,this.readOnlyCompartment=new fo,this.mobilePromptEnterMedia=Cs(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=Ri(i,t);s!==void 0&&Qi(s,this.draft);const r=Ri(this.machineId,this.sessionId);this.draft=r!==void 0?Ya(r):"",this.currentInputMode=es(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has("status")&&e.size===1?!ry(e.get("status"),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=this.currentInputMode.kind==="shell"?this.currentInputMode:void 0,t=e!==void 0,i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
1528
+ <footer class=${t?"shell-mode":""} @paste=${r=>{this.handlePaste(r)}} @dragover=${r=>{this.handleDragOver(r)}} @drop=${r=>{this.handleDrop(r)}}>
1529
+ <div class="editor-wrap">
1530
+ <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="Message pi" aria-disabled=${this.disabled?"true":"false"}></div>
1531
+ <input class="attachment-input" type="file" multiple hidden @change=${r=>{this.handleFileInput(r)}} />
1532
+ <button class="editor-attach icon-button" ?disabled=${s} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${Kw()}</button>
1533
+ ${t?l`<div class="mode-hint">Shell command${e.excludeFromContext?" · excluded from context":""}</div>`:null}
1534
+ ${this.isCompacting&&!t?l`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
1535
+ ${this.renderAttachments()}
1536
+ <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${r=>{this.pick(r)}}></autocomplete-menu>
1537
+ </div>
1538
+ <div class="actions">
1539
+ ${this.renderCompactStatus()}
1540
+ <button class="icon-button send-button" ?disabled=${s} title=${i?"Queue until the current activity finishes":"Send message"} aria-label=${i?"Queue message":"Send message"} @click=${()=>{this.send("followUp")}}>${i?Vw():ac()}</button>
1541
+ ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send("steer")}}>${Gw()}</button>`:null}
1542
+ <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"Stop current work and clear queued messages":"Nothing running"} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${Qw()}</button>
1543
+ </div>
1544
+ </footer>
1545
+ `}focusInput(){this.editor?.focus()}get view(){return this.editor}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"no model",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return l`
1546
+ <div class="compact-status" aria-label="Session status">
1547
+ <button class="select-model" title="Select model" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1548
+ <button class="select-thinking icon-button" title=${`Thinking level: ${Sr(e.thinkingLevel)}`} aria-label=${`Thinking level: ${Sr(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${Jw(Xw(e.thinkingLevel,this.availableThinkingLevels))}</button>
1549
+ </div>
1550
+ `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;const e=yr(this.attachments),t=this.effectiveAttachmentDelivery();return l`
1551
+ <div class="attachments" aria-label="Pending attachments">
1552
+ ${this.attachments.map(i=>l`
1553
+ <div class=${`attachment-chip ${wr(i)?"attachment-chip-image":"attachment-chip-file"}`} title=${i.name}>
1554
+ ${this.renderAttachmentPreview(i)}
1555
+ <button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${i.name}`} @click=${()=>{this.removeAttachment(i.id)}}>×</button>
1556
+ </div>
1557
+ `)}
1558
+ ${this.attachments.length>0?l`
1559
+ <label class="attachment-delivery" title=${e?"How attachments are delivered to the agent":"General files are saved and mentioned from the workspace"}>
1560
+ <select .value=${t} @change=${i=>{this.changeDelivery(i)}}>
1561
+ <option value="inline" ?disabled=${!e}>Attach to message${e?"":" (images only)"}</option>
1562
+ <option value="folder">Save to .omp-web/attachments</option>
1563
+ </select>
1564
+ </label>
1565
+ `:null}
1566
+ ${this.attachmentError!==void 0?l`<div class="attachment-error">${this.attachmentError}</div>`:null}
1567
+ </div>
1568
+ `}renderAttachmentPreview(e){return wr(e)?l`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:l`
1569
+ <div class="attachment-file-preview" aria-hidden="true">${cy(e.name)}</div>
1570
+ <span class="attachment-file-name">${e.name}</span>
1571
+ `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;const t=e.target.value==="folder"?"folder":"inline";if(t==="inline"&&!yr(this.attachments)){e.target.value="folder";return}this.attachmentDelivery=t,jw(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=oa(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&ay(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){const t=oa(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;const t=Array.from(e.target.files);e.target.value="",await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;const{attachments:t,error:i}=await Ww(e,dy);t.length>0&&(this.attachments=[...this.attachments,...t.map(s=>({id:`attachment-${String(++this.attachmentSeq)}`,...s}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>ly(e))}effectiveAttachmentDelivery(){return Lw(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new dt({parent:this.editorHost,state:Ts.create({doc:this.draft,extensions:[yc(),Tc(),Sc(),xc.of(" "),kc($c,{fallback:!0}),dt.lineWrapping,dt.contentAttributes.of(e=>uy(e.state.sliceDoc(0,e.state.selection.main.head))),dt.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),Pc("Message pi... Use / for commands, @ for tracked files, @ space for all files"),this.editableCompartment.of(dt.editable.of(!this.disabled)),this.readOnlyCompartment.of(Ts.readOnly.of(this.disabled)),dt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Cc.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>go.shift?.(e)??!1},{key:"Backspace",run:e=>Ac(e)},...Rc,...Mc])]})}))}syncEditorDoc(){const e=this.editor;if(!e)return;const t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:mo.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(dt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(Ts.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Ri(this.machineId,this.sessionId);t!==void 0&&Qi(t,this.draft);const i=es(this.draft);Wu(i,this.currentInputMode)||(this.currentInputMode=i),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await G.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(oy);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await G.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(ny);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=nl(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:r,detail:s.kind,...s.path.endsWith("/")&&r.endsWith('"')?{cursorOffset:r.length-1}:{}}})}}currentTrigger(){return ol(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key==="Shift")return this.explicitShiftKeyActive=!0,!1;if(e.key!=="Enter")return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;const i=qw(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,i)}handleEditorKeyUp(e){return e.key==="Shift"&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return Hw(t,this.mobilePromptEnterMedia,Rs())?(this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0):Ec(e)||Ic(e)}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):go.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,r=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:r,insert:`${e.insertText}${i}`},selection:mo.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,r=i.length>0?this.currentAttachments():void 0,o=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,s,r,r===void 0?void 0:o)}resetComposer(){this.draft="",this.currentInputMode={kind:"normal"};const e=Ri(this.machineId,this.sessionId);e!==void 0&&Ji(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}};U.styles=kg;z([d({type:Boolean})],U.prototype,"disabled",2);z([d()],U.prototype,"sessionId",2);z([d()],U.prototype,"cwd",2);z([d()],U.prototype,"machineId",2);z([d()],U.prototype,"projectId",2);z([d()],U.prototype,"workspaceId",2);z([d({type:Boolean})],U.prototype,"workspaceScopedFileSuggestions",2);z([d({type:Boolean})],U.prototype,"canSteer",2);z([d({type:Boolean})],U.prototype,"isCompacting",2);z([d({type:Boolean})],U.prototype,"canStop",2);z([d({attribute:!1})],U.prototype,"status",2);z([d({type:Boolean})],U.prototype,"sending",2);z([d({attribute:!1})],U.prototype,"onSend",2);z([d({attribute:!1})],U.prototype,"onStop",2);z([d({attribute:!1})],U.prototype,"onSelectModel",2);z([d({attribute:!1})],U.prototype,"onSelectThinking",2);z([d({attribute:!1})],U.prototype,"availableThinkingLevels",2);z([K(".markdown-editor")],U.prototype,"editorHost",2);z([K(".attachment-input")],U.prototype,"attachmentInput",2);z([v()],U.prototype,"currentInputMode",2);z([v()],U.prototype,"completions",2);z([v()],U.prototype,"selectedIndex",2);z([v()],U.prototype,"attachments",2);z([v()],U.prototype,"attachmentDelivery",2);z([v()],U.prototype,"attachmentError",2);U=z([E("prompt-editor")],U);function ry(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function Ri(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return Yt(e,t)}function oy(){return[]}function ny(){return[]}function oa(e){return e===null?[]:Array.from(e.files)}function ay(e){const t=Array.from(e.items);return t.length>0?t.some(i=>i.kind==="file"):Array.from(e.types).includes("Files")}function ly(e){return e.kind==="image"?{kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}:{kind:"file",mimeType:e.mimeType,data:e.data,name:e.name}}function cy(e){const t=e.trim(),i=t.lastIndexOf(".");return i>=0&&i<t.length-1?t.slice(i+1,i+5).toUpperCase():"FILE"}function dy(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("Failed to read file"))},s.onload=()=>{const r=s.result;if(typeof r!="string"){i(new Error("Unexpected file reader result"));return}const o=r.indexOf(",");t(o===-1?r:r.slice(o+1))},s.readAsDataURL(e)})}const py={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true",dir:"auto"},hy={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",dir:"auto"};function uy(e){return es(e).kind==="normal"?py:hy}function Mi(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:"0"}function fy(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var gy=Object.defineProperty,my=Object.getOwnPropertyDescriptor,lc=(e,t,i,s)=>{for(var r=s>1?void 0:s?my(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&gy(t,i,r),r};let cs=class extends I{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">No session status yet</div>`;const t=e.contextUsage,i=t?t.percent==null?`context ${Mi(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Mi(t.contextWindow)}`:"context unknown",s=e.tokens;return l`
1572
+ <div class="bar">
1573
+ <span>↑${Mi(s.input)}</span>
1574
+ <span>↓${Mi(s.output)}</span>
1575
+ <span class="context">${i}</span>
1576
+ <span>${fy(e.cost)}</span>
1577
+ ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} queued</span>`:null}
1578
+ </div>
1579
+ `}};cs.styles=yg;lc([d({attribute:!1})],cs.prototype,"status",2);cs=lc([E("status-bar")],cs);var vy=Object.defineProperty,by=Object.getOwnPropertyDescriptor,tt=(e,t,i,s)=>{for(var r=s>1?void 0:s?by(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&vy(t,i,r),r};let je=class extends I{constructor(){super(...arguments),this.title="Select",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1580
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1581
+ <section @mousedown=${t=>{t.stopPropagation()}}>
1582
+ <header>
1583
+ <strong>${this.title}</strong>
1584
+ <button @click=${()=>this.onCancel?.()}>×</button>
1585
+ </header>
1586
+ ${this.searchable?l`<input placeholder="Search" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1587
+ <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1588
+ ${e.map((t,i)=>l`
1589
+ <button class=${i===this.selectedIndex?"selected":""} ${po(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1590
+ <span>${t.label}</span>
1591
+ ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1592
+ </button>
1593
+ `)}
1594
+ ${e.length===0?l`<div class="empty">No matching options</div>`:null}
1595
+ </div>
1596
+ </section>
1597
+ </div>
1598
+ `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};je.styles=xl;tt([d()],je.prototype,"title",2);tt([d({type:Boolean})],je.prototype,"searchable",2);tt([d({attribute:!1})],je.prototype,"options",2);tt([d({attribute:!1})],je.prototype,"selectedValue",2);tt([d({attribute:!1})],je.prototype,"onPick",2);tt([d({attribute:!1})],je.prototype,"onCancel",2);tt([v()],je.prototype,"selectedIndex",2);tt([v()],je.prototype,"query",2);je=tt([E("command-picker")],je);var wy=Object.defineProperty,yy=Object.getOwnPropertyDescriptor,kt=(e,t,i,s)=>{for(var r=s>1?void 0:s?yy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&wy(t,i,r),r};let Xe=class extends I{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1599
+ <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1600
+ <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1601
+ <header>
1602
+ <input
1603
+ .value=${this.queryText}
1604
+ placeholder="Search actions..."
1605
+ @input=${t=>{t.target instanceof HTMLInputElement&&(this.queryText=t.target.value,this.selectedIndex=0)}}
1606
+ >
1607
+ <button title="Close" @click=${()=>this.onCancel?.()}>×</button>
1608
+ </header>
1609
+ <div class="options">
1610
+ ${e.length===0?l`<div class="empty">No actions found.</div>`:e.map((t,i)=>l`
1611
+ <button class=${`${i===this.selectedIndex?"selected":""} ${t.enabled===!1?"disabled":""}`} ?disabled=${t.enabled===!1} title=${t.disabledReason??t.title} ${po(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1612
+ <span class="main">
1613
+ <strong>${t.title}</strong>
1614
+ ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1615
+ ${t.enabled===!1&&t.disabledReason!==void 0?l`<small class="disabled-reason">${t.disabledReason}</small>`:null}
1616
+ </span>
1617
+ ${t.shortcut!==void 0?l`<kbd>${_i(t.shortcut)}</kbd>`:null}
1618
+ ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1619
+ </button>
1620
+ `)}
1621
+ </div>
1622
+ </section>
1623
+ </div>
1624
+ `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return Sy(this.actions,this.queryText)}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){e.enabled!==!1&&this.onRun?.(e)}};Xe.styles=xg;kt([d({attribute:!1})],Xe.prototype,"actions",2);kt([d({attribute:!1})],Xe.prototype,"onRun",2);kt([d({attribute:!1})],Xe.prototype,"onCancel",2);kt([K("input")],Xe.prototype,"input",2);kt([v()],Xe.prototype,"queryText",2);kt([v()],Xe.prototype,"selectedIndex",2);Xe=kt([E("action-palette")],Xe);function Sy(e,t){const i=t.trim().toLowerCase();return e.filter(s=>s.enabled!==!1||s.disabledReason!==void 0).filter(s=>i===""?!0:[s.title,s.description??"",s.disabledReason??"",s.group??"",s.shortcut??""].join(" ").toLowerCase().includes(i))}var xy=Object.defineProperty,ky=Object.getOwnPropertyDescriptor,Ee=(e,t,i,s)=>{for(var r=s>1?void 0:s?ky(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&xy(t,i,r),r};let me=class extends I{render(){const e=this.state;return e===void 0?null:l`
1625
+ <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1626
+ <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1627
+ <header>
1628
+ <strong>${this.dialogTitle(e)}</strong>
1629
+ <button title="Close" @click=${()=>{this.cancel()}}>×</button>
1630
+ </header>
1631
+ ${this.renderBody(e)}
1632
+ </section>
1633
+ </div>
1634
+ `}updated(){this.focusInputIfNeeded()}dialogTitle(e){switch(e.step){case"method":return"Configure provider authentication";case"providers":return e.authType===void 0?"Select provider authentication":e.authType==="oauth"?"Select subscription provider":"Select API key provider";case"apiKey":return`API key for ${e.provider.name}`;case"oauth":return`Login to ${e.flow.providerName}`;case"logout":return"Remove stored provider authentication"}}renderBody(e){switch(e.step){case"method":return l`
1635
+ <div class="options">
1636
+ <button @click=${()=>{this.onChooseMethod?.("oauth")}}><span>Use a subscription</span><small>ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot</small></button>
1637
+ <button @click=${()=>{this.onChooseMethod?.("api_key")}}><span>Use an API key</span><small>Store an API key in pi auth.json</small></button>
1638
+ </div>
1639
+ `;case"providers":return l`<div class="options">${e.providers.length===0?l`<div class="empty">No providers available.</div>`:e.providers.map(t=>this.renderProviderButton(t))}</div>`;case"apiKey":return l`
1640
+ <div class="form">
1641
+ <p>Enter the API key for <strong>${e.provider.name}</strong>. It will be stored by pi in <code>auth.json</code>.</p>
1642
+ <input type="password" autocomplete="off" placeholder="API key" .value=${e.value} @input=${t=>{t.target instanceof HTMLInputElement&&this.onApiKeyInput?.(t.target.value)}}>
1643
+ ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1644
+ <div class="actions"><button @click=${()=>{this.cancel()}}>Cancel</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?"Saving…":"Save API key"}</button></div>
1645
+ </div>
1646
+ `;case"oauth":return this.renderOAuth(e);case"logout":return l`<div class="options">${e.providers.length===0?l`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(t=>l`
1647
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${na(t.authType)}</small></button>
1648
+ `)}</div>`}}renderProviderButton(e){return l`
1649
+ <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1650
+ <span>${e.name}${e.status.source!==void 0?l` <em>${Py(e)}</em>`:null}</span>
1651
+ <small>${e.id} · ${na(e.authType)}</small>
1652
+ </button>
1653
+ `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1654
+ <div class="form">
1655
+ ${t.auth!==void 0?l`
1656
+ <p>Open this authorization link:</p>
1657
+ <p><a href=${t.auth.url} target="_blank" rel="noreferrer">${t.auth.url}</a></p>
1658
+ ${t.auth.instructions!==void 0?l`<p class="warning">${t.auth.instructions}</p>`:null}
1659
+ `:l`<p>Starting login flow…</p>`}
1660
+ ${t.progress.length>0?l`<ul class="progress">${t.progress.map(r=>l`<li>${r}</li>`)}</ul>`:null}
1661
+ ${i!==void 0?l`
1662
+ <label>${i.message}</label>
1663
+ <input .value=${e.inputValue??""} placeholder=${i.placeholder??""} @input=${r=>{r.target instanceof HTMLInputElement&&this.onOAuthInput?.(r.target.value)}}>
1664
+ <div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button><button class="primary" ?disabled=${e.responding===!0} @click=${()=>{this.onOAuthRespond?.()}}>Submit</button></div>
1665
+ `:null}
1666
+ ${s!==void 0?l`
1667
+ <p>${s.message}</p>
1668
+ <div class="inline-options">${s.options.map(r=>l`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
1669
+ `:null}
1670
+ ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1671
+ ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??t.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
1672
+ ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
1673
+ </div>
1674
+ `}focusInputIfNeeded(){const e=$y(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key!=="Enter")return;const t=this.state;t?.step==="apiKey"?(e.preventDefault(),this.onSaveApiKey?.()):t?.step==="oauth"&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};me.styles=[xl,D`
1675
+ .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1676
+ .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1677
+ .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
1678
+ .form code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-surface); padding: 1px 4px; }
1679
+ label { color: var(--pi-muted); }
1680
+ .actions { display: flex; justify-content: flex-end; gap: 8px; }
1681
+ .actions button, .inline-options button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; }
1682
+ .actions button.primary { border-color: var(--pi-success-border); background: var(--pi-success-surface); color: var(--pi-success); }
1683
+ .actions button:disabled { opacity: .6; cursor: wait; }
1684
+ .warning { color: var(--pi-warning); }
1685
+ .error-text { color: var(--pi-danger); }
1686
+ .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1687
+ .inline-options { display: grid; gap: 8px; }
1688
+ em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1689
+ `];Ee([d({attribute:!1})],me.prototype,"state",2);Ee([d({attribute:!1})],me.prototype,"onChooseMethod",2);Ee([d({attribute:!1})],me.prototype,"onSelectProvider",2);Ee([d({attribute:!1})],me.prototype,"onApiKeyInput",2);Ee([d({attribute:!1})],me.prototype,"onSaveApiKey",2);Ee([d({attribute:!1})],me.prototype,"onLogoutProvider",2);Ee([d({attribute:!1})],me.prototype,"onOAuthInput",2);Ee([d({attribute:!1})],me.prototype,"onOAuthRespond",2);Ee([d({attribute:!1})],me.prototype,"onOAuthCancel",2);Ee([d({attribute:!1})],me.prototype,"onCancel",2);Ee([K("input")],me.prototype,"input",2);me=Ee([E("auth-dialog")],me);function na(e){return e==="oauth"?"subscription":"API key"}function $y(e){if(e?.step==="apiKey")return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step==="oauth"&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function Py(e){if(e.status.source===void 0)return"";switch(e.status.source){case"stored":return"✓ configured";case"environment":return`✓ env${e.status.label===void 0?"":`: ${e.status.label}`}`;case"runtime":return"✓ runtime";case"fallback":return"✓ custom key";case"models_json_key":return"✓ models.json key";case"models_json_command":return"✓ models.json command";default:return""}}var Cy=Object.defineProperty,Ry=Object.getOwnPropertyDescriptor,Ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ry(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Cy(t,i,r),r};let Ie=class extends I{constructor(){super(...arguments),this.machineId="local",this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const e=++this.requestId;this.loading=!0;try{const t=await G.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return l`
1690
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
1691
+ <section @click=${e=>{e.stopPropagation()}}>
1692
+ <header>
1693
+ <strong>Add project</strong>
1694
+ <button @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
1695
+ </header>
1696
+ <div class="body">
1697
+ <label>
1698
+ Project folder
1699
+ <input .value=${this.path} @input=${e=>{this.onPathInput(e)}} @keydown=${e=>{this.onKeyDown(e)}} placeholder="/path/to/project or ~/code/project" autofocus />
1700
+ </label>
1701
+ <div class="suggestions">
1702
+ ${this.loading?l`<div class="hint">Loading folders…</div>`:null}
1703
+ ${this.suggestions.map((e,t)=>l`
1704
+ <button class=${t===this.selected?"selected":""} @click=${()=>{this.pick(e)}}>
1705
+ ${e.path}
1706
+ </button>
1707
+ `)}
1708
+ ${!this.loading&&this.suggestions.length===0?l`<div class="hint">No matching folders. Enter a new path to create it.</div>`:null}
1709
+ </div>
1710
+ <label class="check">
1711
+ <input type="checkbox" .checked=${this.createMissing} @change=${e=>{this.onCreateMissingChange(e)}} />
1712
+ Create the folder if it does not exist
1713
+ </label>
1714
+ </div>
1715
+ <footer>
1716
+ <button @click=${()=>{this.onCancel?.()}}>Cancel</button>
1717
+ <button class="primary" ?disabled=${this.path.trim()===""} @click=${()=>{this.submit()}}>Add project</button>
1718
+ </footer>
1719
+ </section>
1720
+ </div>
1721
+ `}};Ie.styles=D`
1722
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1723
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1724
+ section { width: min(720px, calc(100vw - 40px)); max-height: min(700px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
1725
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1726
+ footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1727
+ .body { display: grid; gap: 12px; padding: 12px; min-height: 0; }
1728
+ label { display: grid; gap: 6px; color: var(--pi-muted); }
1729
+ input[type="text"], input:not([type]) { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: var(--pi-control-font-size, 16px) var(--pi-control-monospace-font-family, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); }
1730
+ .check { display: flex; grid-template-columns: auto 1fr; align-items: center; color: var(--pi-text); }
1731
+ .suggestions { min-height: 90px; max-height: 320px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); }
1732
+ .suggestions button { display: block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1733
+ .suggestions button.selected, .suggestions button:hover { background: var(--pi-selection-bg); }
1734
+ .hint { padding: 12px; color: var(--pi-muted); }
1735
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1736
+ header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1737
+ .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1738
+ button:disabled { opacity: .5; cursor: not-allowed; }
1739
+ `;Ve([d({attribute:!1})],Ie.prototype,"onSubmit",2);Ve([d({attribute:!1})],Ie.prototype,"onCancel",2);Ve([d()],Ie.prototype,"machineId",2);Ve([v()],Ie.prototype,"path",2);Ve([v()],Ie.prototype,"createMissing",2);Ve([v()],Ie.prototype,"suggestions",2);Ve([v()],Ie.prototype,"selected",2);Ve([v()],Ie.prototype,"loading",2);Ve([K("input")],Ie.prototype,"pathInput",2);Ie=Ve([E("project-dialog")],Ie);var My=Object.defineProperty,Iy=Object.getOwnPropertyDescriptor,Ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?Iy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&My(t,i,r),r};let Te=class extends I{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=Ty(t);(!this.nameEdited||this.name.trim()===""||this.name===this.previousSuggestedName)&&(this.name=i),this.previousSuggestedName=i,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.onCancel?.();return}e.key==="Enter"&&e.target instanceof HTMLInputElement&&e.target.name==="baseUrl"&&Xs(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){const e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){const e=this.url.trim(),t=this.name.trim();if(e===""||t===""||Xs(e)!==void 0)return;const i=this.token.trim();return{name:t,baseUrl:e,...i===""?{}:{token:i}}}render(){const e=this.url.trim()!=="",t=e?Xs(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1740
+ <div class="backdrop" @click=${()=>this.onCancel?.()}>
1741
+ <section @click=${s=>{s.stopPropagation()}}>
1742
+ <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
1743
+ <header>
1744
+ <strong>Add machine</strong>
1745
+ <button type="button" @click=${()=>{this.onCancel?.()}} aria-label="Close">×</button>
1746
+ </header>
1747
+ <div class="body">
1748
+ ${this.error===""?null:l`<div class="dialog-error" role="alert">${this.error}</div>`}
1749
+ <label>
1750
+ Remote PI WEB URL
1751
+ <input name="baseUrl" type="url" .value=${this.url} @input=${s=>{this.handleUrlInput(s)}} placeholder="http://dev-box.local:8504" autocomplete="url" inputmode="url" autofocus />
1752
+ </label>
1753
+ <small class=${t===void 0?"hint":"field-error"}>${t??"Enter the reachable base URL first, including http:// or https://."}</small>
1754
+ ${e?l`
1755
+ <label>
1756
+ Machine name
1757
+ <input name="name" type="text" .value=${this.name} @input=${s=>{this.handleNameInput(s)}} placeholder=${this.previousSuggestedName||"Dev Box"} autocomplete="off" />
1758
+ </label>
1759
+ <small class="hint">Suggested from the URL. Edit it to use a friendlier sidebar label.</small>
1760
+ <label>
1761
+ Bearer token <span class="optional">optional</span>
1762
+ <input name="token" type="password" .value=${this.token} @input=${s=>{this.handleTokenInput(s)}} placeholder="Leave blank if the remote machine does not require one" autocomplete="off" />
1763
+ </label>
1764
+ <small class="hint">Paste only the token value; PI WEB sends it as an Authorization: Bearer header.</small>
1765
+ `:l`<p class="hint intro">After you enter a URL, PI WEB will suggest a machine name and let you add an optional bearer token.</p>`}
1766
+ </div>
1767
+ <footer>
1768
+ <button type="button" @click=${()=>{this.onCancel?.()}}>Cancel</button>
1769
+ <button class="primary" type="submit" ?disabled=${!i}>${this.submitting?"Adding…":"Add machine"}</button>
1770
+ </footer>
1771
+ </form>
1772
+ </section>
1773
+ </div>
1774
+ `}};Te.styles=D`
1775
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1776
+ .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1777
+ section { width: min(560px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
1778
+ form { display: flex; flex-direction: column; max-height: inherit; min-height: 0; }
1779
+ header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
1780
+ footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
1781
+ .body { display: grid; gap: 8px; padding: 12px; min-height: 0; overflow: auto; }
1782
+ label { display: grid; gap: 6px; color: var(--pi-muted); }
1783
+ input { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: var(--pi-control-font-size, 16px) var(--pi-control-monospace-font-family, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); }
1784
+ input:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 1px; }
1785
+ .hint { color: var(--pi-muted); }
1786
+ .intro { margin: 4px 0 0; line-height: 1.4; }
1787
+ .optional { color: var(--pi-muted); font-weight: 400; }
1788
+ .field-error { color: var(--pi-danger); }
1789
+ .dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; }
1790
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1791
+ header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1792
+ .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1793
+ button:disabled { opacity: .5; cursor: not-allowed; }
1794
+ `;Ge([d({attribute:!1})],Te.prototype,"onSubmit",2);Ge([d({attribute:!1})],Te.prototype,"onCancel",2);Ge([d()],Te.prototype,"error",2);Ge([v()],Te.prototype,"url",2);Ge([v()],Te.prototype,"name",2);Ge([v()],Te.prototype,"token",2);Ge([v()],Te.prototype,"submitting",2);Ge([K("input[name='baseUrl']")],Te.prototype,"urlInput",2);Ge([K("input[name='name']")],Te.prototype,"nameInput",2);Te=Ge([E("machine-dialog")],Te);function Ty(e){const t=e.trim();if(t==="")return"";const i=aa(t)??aa(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Ay(t)}function Xs(e){const t=e.trim();if(t==="")return"Remote PI WEB URL is required.";let i;try{i=new URL(t)}catch{return"Enter a valid URL including http:// or https://."}if(i.protocol!=="http:"&&i.protocol!=="https:")return"Use an http:// or https:// URL.";if(i.username!==""||i.password!=="")return"Do not include credentials in the machine URL.";if(i.search!==""||i.hash!=="")return"Do not include a query string or fragment."}function aa(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Ay(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}var Ey=Object.defineProperty,Dy=Object.getOwnPropertyDescriptor,ct=(e,t,i,s)=>{for(var r=s>1?void 0:s?Dy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ey(t,i,r),r};const Wy={availability:"error",error:"error",success:"success",security:"warning",warning:"warning",info:"info"};function Ly(e){return e.tone??Wy[e.type]}let Ke=class extends I{constructor(){super(...arguments),this.heading="",this.description="",this.actionLabel="",this.actionTitle="",this.actionDisabled=!1,this.notices=[]}render(){return l`
1795
+ <section class="panel" aria-label=${this.heading||"Settings panel"}>
1796
+ <header class="section-heading">
1797
+ <div class="heading-copy">
1798
+ ${this.heading===""?N:l`<h2>${this.heading}</h2>`}
1799
+ <div class="description"><slot name="description">${this.description}</slot></div>
1800
+ </div>
1801
+ <div class="heading-actions"><slot name="actions">${this.renderDefaultAction()}</slot></div>
1802
+ </header>
1803
+ ${this.renderNoticeStack()}
1804
+ <div class="content"><slot></slot></div>
1805
+ </section>
1806
+ `}renderDefaultAction(){return this.actionLabel===""?N:l`
1807
+ <button
1808
+ class="secondary"
1809
+ title=${this.actionTitle||this.actionLabel}
1810
+ ?disabled=${this.actionDisabled}
1811
+ @click=${()=>{this.onAction?.()}}
1812
+ >${this.actionLabel}</button>
1813
+ `}renderNoticeStack(){return this.notices.length===0?N:l`
1814
+ <div class="notice-stack" aria-label="Settings notices">
1815
+ ${this.notices.map(e=>this.renderNotice(e))}
1816
+ </div>
1817
+ `}renderNotice(e){const t=Ly(e),i=e.role??Oy(t),s=e.title;return l`
1818
+ <article class=${`notice ${t}`} role=${i}>
1819
+ ${s===void 0||s===""?N:l`<strong class="notice-title">${s}</strong>`}
1820
+ <div class="notice-content">${e.content}</div>
1821
+ </article>
1822
+ `}};Ke.styles=D`
1823
+ :host { display: block; }
1824
+ .panel { display: block; }
1825
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1826
+ .heading-copy { display: grid; gap: 6px; min-width: 0; }
1827
+ .heading-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; }
1828
+ h2 { margin: 0; font-size: 17px; line-height: 1.25; }
1829
+ .description { color: var(--pi-muted); line-height: 1.45; }
1830
+ .description ::slotted(*) { margin: 0; }
1831
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; font: inherit; cursor: pointer; }
1832
+ button:disabled { opacity: .55; cursor: not-allowed; }
1833
+ .secondary { flex: 0 0 auto; }
1834
+ .notice-stack { display: grid; gap: 12px; margin-bottom: 14px; }
1835
+ .notice { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; line-height: 1.45; }
1836
+ .notice.error { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1837
+ .notice.success { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1838
+ .notice.warning { border-color: var(--pi-warning-border); color: var(--pi-text); background: var(--pi-warning-surface); }
1839
+ .notice.info { color: var(--pi-muted); }
1840
+ .notice-title { display: block; margin-bottom: 4px; color: inherit; }
1841
+ .notice-content { min-width: 0; }
1842
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1843
+ .content { display: grid; gap: 14px; min-width: 0; }
1844
+ .content ::slotted(*) { min-width: 0; }
1845
+
1846
+ @media (max-width: 760px) {
1847
+ .section-heading { display: grid; gap: 12px; }
1848
+ .heading-actions { justify-self: start; }
1849
+ }
1850
+ `;ct([d()],Ke.prototype,"heading",2);ct([d({attribute:!1})],Ke.prototype,"description",2);ct([d()],Ke.prototype,"actionLabel",2);ct([d()],Ke.prototype,"actionTitle",2);ct([d({type:Boolean})],Ke.prototype,"actionDisabled",2);ct([d({attribute:!1})],Ke.prototype,"notices",2);ct([d({attribute:!1})],Ke.prototype,"onAction",2);Ke=ct([E("settings-panel-frame")],Ke);function Oy(e){switch(e){case"error":return"alert";case"success":return"status";case"warning":case"info":return"note"}}function Fy(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function _y(){return{allowedPathsText:"",uploadDefaultFolder:""}}function jy(e){return{host:e.host??"",port:e.port===void 0?"":String(e.port),allowedHostsMode:e.allowedHosts===!0?"all":"list",allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
1851
+ `):""}}function Uy(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
1852
+ `)??"",uploadDefaultFolder:e.uploads?.defaultFolder??""}}function Ny(e,t={}){const i=zy(t),s=e.host.trim(),r=e.port.trim();if(s!==""&&(i.host=s),r!==""){const o=Number(r);if(!Number.isInteger(o)||o<1||o>65535)throw new Error("Port must be an integer from 1 to 65535.");i.port=o}return i.allowedHosts=e.allowedHostsMode==="all"?!0:qy(e.allowedHostsText),i}function By(e){const t=Hy(e.allowedPathsText),i=Ky(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:i===""?{}:{defaultFolder:i}}}function zy(e){return{...e.shortcuts===void 0?{}:{shortcuts:e.shortcuts},...e.plugins===void 0?{}:{plugins:e.plugins},...e.pathAccess===void 0?{}:{pathAccess:e.pathAccess},...e.uploads===void 0?{}:{uploads:e.uploads},...e.maxUploadBytes===void 0?{}:{maxUploadBytes:e.maxUploadBytes},...e.spawnSessions===void 0?{}:{spawnSessions:e.spawnSessions},...e.subsessions===void 0?{}:{subsessions:e.subsessions}}}function qy(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function Hy(e){const t=e.split(`
1853
+ `).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!Vy(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function Ky(e){const t=e.trim();if(t==="")return"";if(Gy(t))throw new Error("Upload default folder must be workspace-relative.");const i=t.split(/[\\/]+/u).filter(s=>s!==""&&s!==".");if(i.length===0)return"";if(i.some(s=>s===".."))throw new Error("Upload default folder must not contain path traversal.");return i.join("/")}function Vy(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}function Gy(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}var Qy=Object.defineProperty,Jy=Object.getOwnPropertyDescriptor,Y=(e,t,i,s)=>{for(var r=s>1?void 0:s?Jy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Qy(t,i,r),r};function Zy(e){return l`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}let Q=class extends I{constructor(){super(...arguments),this.loading=!1,this.machineLoading=!1,this.saving=!1,this.error="",this.machineError="",this.savedMessage="",this.targetLabel="selected machine",this.gatewayDraft=Fy(),this.machineDraft=_y(),this.gatewayLocalError="",this.machineLocalError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.gatewayDraft=jy(this.configResponse.config),this.gatewayLocalError=""),e.has("machineConfigResponse")&&this.machineConfigResponse!==void 0&&(this.machineDraft=Uy(this.machineConfigResponse.config),this.machineLocalError="")}render(){return l`
1854
+ <settings-panel-frame
1855
+ heading="General configuration"
1856
+ .description=${Zy(this.targetLabel)}
1857
+ actionLabel="Reload"
1858
+ .actionDisabled=${this.loading||this.machineLoading}
1859
+ .notices=${this.panelNotices()}
1860
+ .onAction=${()=>{this.reloadAll()}}
1861
+ >
1862
+ <div class="settings-sections">
1863
+ ${this.renderGatewayServerSettings()}
1864
+ ${this.renderSelectedMachineAccessSettings()}
1865
+ </div>
1866
+ </settings-panel-frame>
1867
+ `}renderGatewayServerSettings(){const e=this.configResponse;return l`
1868
+ <section class="settings-card" aria-label="Gateway server settings">
1869
+ <div class="card-heading">
1870
+ <h3>Gateway server</h3>
1871
+ <p>Host, port, and allowed hosts are saved in the gateway config. Address changes require the web service to restart before the running server binds to the new address.</p>
1872
+ </div>
1873
+ ${e===void 0&&this.loading?l`<div class="loading-card">Loading gateway configuration…</div>`:l`
1874
+ <div class="config-path-card">
1875
+ <span>Gateway config file</span>
1876
+ <code>${e?.path??"Unknown"}</code>
1877
+ <small>${e?.exists===!0?"Existing file":"This file will be created on save"}</small>
1878
+ </div>
1879
+ <form class="config-form" @submit=${t=>{this.saveGatewayConfig(t)}}>
1880
+ <label class="field">
1881
+ <span class="field-heading">
1882
+ <span>Host</span>
1883
+ ${this.renderOverrideBadge("host")}
1884
+ </span>
1885
+ <input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateGatewayDraft({host:Ys(t)})}}>
1886
+ <small>Address the web server should bind to. Leave empty to use PI WEB's default.</small>
1887
+ </label>
1888
+
1889
+ <label class="field">
1890
+ <span class="field-heading">
1891
+ <span>Port</span>
1892
+ ${this.renderOverrideBadge("port")}
1893
+ </span>
1894
+ <input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateGatewayDraft({port:Ys(t)})}}>
1895
+ <small>TCP port from 1 to 65535. Leave empty to use PI WEB's default.</small>
1896
+ </label>
1897
+
1898
+ <div class="field">
1899
+ <span class="field-heading">
1900
+ <span>Allowed hosts</span>
1901
+ ${this.renderOverrideBadge("allowedHosts")}
1902
+ </span>
1903
+ <select .value=${this.gatewayDraft.allowedHostsMode} @change=${t=>{this.updateGatewayDraft({allowedHostsMode:eS(t)==="all"?"all":"list"})}}>
1904
+ <option value="list">Only listed hosts</option>
1905
+ <option value="all">Allow every host</option>
1906
+ </select>
1907
+ <textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode==="all"} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${t=>{this.updateGatewayDraft({allowedHostsText:la(t)})}}></textarea>
1908
+ <small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
1909
+ </div>
1910
+
1911
+ ${this.renderGatewayEffectiveConfig()}
1912
+
1913
+ <footer class="form-actions">
1914
+ <button class="primary" ?disabled=${this.loading||this.saving}>${this.saving?"Saving…":"Save gateway server config"}</button>
1915
+ </footer>
1916
+ </form>
1917
+ `}
1918
+ </section>
1919
+ `}renderSelectedMachineAccessSettings(){const e=this.machineConfigResponse;return l`
1920
+ <section class="settings-card" aria-label="Selected machine file access and upload settings">
1921
+ <div class="card-heading">
1922
+ <h3>Selected machine file access and uploads</h3>
1923
+ <p>External filesystem roots and upload defaults are saved on ${this.targetLabel}.</p>
1924
+ </div>
1925
+ ${this.renderMachineMessages()}
1926
+ ${e===void 0?l`<div class="loading-card">${this.machineLoading?"Loading selected-machine file access config…":"Selected-machine file access config is unavailable. Reload before saving file/upload settings."}</div>`:l`
1927
+ <div class="config-path-card">
1928
+ <span>Selected machine config file</span>
1929
+ <code>${e.path}</code>
1930
+ <small>${e.exists?"Existing file":"This file will be created on save"}</small>
1931
+ </div>
1932
+ <form class="config-form" @submit=${t=>{this.saveMachineAccessConfig(t)}}>
1933
+ <label class="field">
1934
+ <span class="field-heading">
1935
+ <span>External filesystem roots</span>
1936
+ </span>
1937
+ <textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${t=>{this.updateMachineDraft({allowedPathsText:la(t)})}}></textarea>
1938
+ <small>Allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace on ${this.targetLabel}. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
1939
+ </label>
1940
+
1941
+ <label class="field">
1942
+ <span class="field-heading">
1943
+ <span>Default upload folder</span>
1944
+ </span>
1945
+ <input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${oi} autocomplete="off" spellcheck="false" @input=${t=>{this.updateMachineDraft({uploadDefaultFolder:Ys(t)})}}>
1946
+ <small>Workspace-relative folder for manual file uploads on ${this.targetLabel}. Leave empty to use PI WEB's default <code>${oi}</code>.</small>
1947
+ </label>
1948
+
1949
+ ${this.renderMachineEffectiveConfig()}
1950
+
1951
+ <footer class="form-actions">
1952
+ <button class="primary" ?disabled=${this.machineLoading||this.saving}>${this.saving?"Saving…":"Save file/upload config"}</button>
1953
+ </footer>
1954
+ </form>
1955
+ `}
1956
+ </section>
1957
+ `}panelNotices(){const e=[],t=this.gatewayLocalError||this.error;return t!==""&&e.push({type:"error",title:"Gateway server",content:t}),this.savedMessage!==""&&e.push({type:"success",content:this.savedMessage}),e}renderMachineMessages(){const e=this.machineLocalError||this.machineError;return e===""?null:l`<div class="message error-message">${e}</div>`}renderOverrideBadge(e){return this.configResponse?.envOverrides[e]!==!0?null:l`<span class="override-badge">environment override</span>`}renderGatewayEffectiveConfig(){const e=this.configResponse?.effectiveConfig??{};return l`
1958
+ <section class="effective-card" aria-label="Effective gateway configuration summary">
1959
+ <h3>Effective gateway settings after environment overrides</h3>
1960
+ <dl>
1961
+ <div><dt>Host</dt><dd>${e.host??l`<span class="muted">127.0.0.1 default</span>`}</dd></div>
1962
+ <div><dt>Port</dt><dd>${e.port??l`<span class="muted">8504 default</span>`}</dd></div>
1963
+ <div><dt>Allowed hosts</dt><dd>${Xy(e.allowedHosts)}</dd></div>
1964
+ </dl>
1965
+ </section>
1966
+ `}renderMachineEffectiveConfig(){const e=this.machineConfigResponse?.effectiveConfig??{};return l`
1967
+ <section class="effective-card" aria-label="Effective selected machine file access and upload summary">
1968
+ <h3>Effective selected-machine settings</h3>
1969
+ <dl>
1970
+ <div><dt>External roots</dt><dd>${Yy(e.pathAccess?.allowedPaths)}</dd></div>
1971
+ <div><dt>Upload folder</dt><dd>${e.uploads?.defaultFolder??l`<span class="muted">${oi} default</span>`}</dd></div>
1972
+ </dl>
1973
+ </section>
1974
+ `}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError="";try{await this.onSave?.(Ny(this.gatewayDraft,this.configResponse?.config??{}))}catch(t){this.gatewayLocalError=q(t)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError="";try{await this.onSaveMachineConfig?.(By(this.machineDraft))}catch(t){this.machineLocalError=q(t)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=""}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=""}};Q.styles=D`
1975
+ :host { display: block; }
1976
+ .card-heading { display: grid; gap: 6px; min-width: 0; }
1977
+ h3, p { margin: 0; }
1978
+ h3 { font-size: 13px; line-height: 1.3; }
1979
+ p { color: var(--pi-muted); line-height: 1.45; }
1980
+ button, input, select, textarea { font: inherit; }
1981
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1982
+ button:disabled { opacity: .55; cursor: not-allowed; }
1983
+ .settings-sections { display: grid; gap: 14px; }
1984
+ .settings-card, .message, .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1985
+ .settings-card { display: grid; gap: 14px; }
1986
+ .message { margin-bottom: 12px; }
1987
+ .settings-card .message { margin-bottom: 0; }
1988
+ .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1989
+ .loading-card { color: var(--pi-muted); }
1990
+ .config-path-card { display: grid; gap: 5px; }
1991
+ .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1992
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1993
+ .config-path-card small, .field small { color: var(--pi-muted); }
1994
+ .config-form { display: grid; gap: 14px; }
1995
+ .field { display: grid; gap: 7px; }
1996
+ .field-heading { display: flex; align-items: center; gap: 8px; }
1997
+ input, select, textarea { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px 10px; outline: none; font: var(--pi-control-font-size, 16px) var(--pi-control-font-family, system-ui, sans-serif); }
1998
+ input:focus, select:focus, textarea:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1999
+ textarea { resize: vertical; min-height: 94px; font-family: var(--pi-control-monospace-font-family, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); }
2000
+ textarea:disabled { opacity: .55; }
2001
+ .override-badge { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); background: var(--pi-warning-surface); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: none; }
2002
+ .effective-card { display: grid; gap: 10px; }
2003
+ .effective-card dl { display: grid; gap: 8px; margin: 0; }
2004
+ .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
2005
+ dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
2006
+ .muted { color: var(--pi-muted); }
2007
+ .form-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
2008
+ .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
2009
+
2010
+ @media (max-width: 760px) {
2011
+ .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
2012
+ }
2013
+ `;Y([d({attribute:!1})],Q.prototype,"configResponse",2);Y([d({attribute:!1})],Q.prototype,"machineConfigResponse",2);Y([d({type:Boolean})],Q.prototype,"loading",2);Y([d({type:Boolean})],Q.prototype,"machineLoading",2);Y([d({type:Boolean})],Q.prototype,"saving",2);Y([d()],Q.prototype,"error",2);Y([d()],Q.prototype,"machineError",2);Y([d()],Q.prototype,"savedMessage",2);Y([d()],Q.prototype,"targetLabel",2);Y([d({attribute:!1})],Q.prototype,"onReload",2);Y([d({attribute:!1})],Q.prototype,"onReloadMachine",2);Y([d({attribute:!1})],Q.prototype,"onSave",2);Y([d({attribute:!1})],Q.prototype,"onSaveMachineConfig",2);Y([v()],Q.prototype,"gatewayDraft",2);Y([v()],Q.prototype,"machineDraft",2);Y([v()],Q.prototype,"gatewayLocalError",2);Y([v()],Q.prototype,"machineLocalError",2);Q=Y([E("settings-general-panel")],Q);function Xy(e){return e===!0?"Any host":Array.isArray(e)?e.length===0?l`<span class="muted">None listed</span>`:e.join(", "):l`<span class="muted">Unset</span>`}function Yy(e){return e===void 0||e.length===0?l`<span class="muted">External paths denied</span>`:e.join(", ")}function Ys(e){return e.target instanceof HTMLInputElement?e.target.value:""}function eS(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function la(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function tS(e){return{spawnSessions:e}}function iS(e){return{subsessions:e}}function sS(e,t){return{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:{...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions}}}var rS=Object.defineProperty,oS=Object.getOwnPropertyDescriptor,it=(e,t,i,s)=>{for(var r=s>1?void 0:s?oS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&rS(t,i,r),r};let Ue=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.targetLabel="local (local gateway)"}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,r=e?.effectiveConfig.subsessions===!0&&i;return l`
2014
+ <settings-panel-frame
2015
+ heading="Session daemon"
2016
+ .description=${nS(this.targetLabel)}
2017
+ actionLabel="Reload"
2018
+ .actionDisabled=${this.loading}
2019
+ .notices=${this.panelNotices(e)}
2020
+ .onAction=${this.onReload}
2021
+ >
2022
+ ${e===void 0?this.renderUnavailableConfigState():l`
2023
+ <div class="config-path-card">
2024
+ <span>Config file</span>
2025
+ <code>${e.path}</code>
2026
+ </div>
2027
+ <div class="field">
2028
+ <span class="field-heading">
2029
+ <span>Allow agents to start sessions</span>
2030
+ ${t?l`<span class="override-badge">environment override</span>`:null}
2031
+ </span>
2032
+ <label class="toggle">
2033
+ <input
2034
+ type="checkbox"
2035
+ .checked=${i}
2036
+ ?disabled=${this.loading||this.saving||t}
2037
+ @change=${o=>{this.toggleSpawnSessions(o)}}
2038
+ >
2039
+ <span>Enable the <code>spawn_session</code> tool</span>
2040
+ </label>
2041
+ <small>When enabled, LLMs can start new sessions, constrained to a workspace (any worktree) of the same registered project so every spawned session stays visible here. On by default.</small>
2042
+ </div>
2043
+ <div class="field">
2044
+ <span class="field-heading">
2045
+ <span>Allow agents to start tracked subsessions</span>
2046
+ <span class="beta-badge">beta</span>
2047
+ ${s?l`<span class="override-badge">environment override</span>`:null}
2048
+ </span>
2049
+ <label class="toggle">
2050
+ <input
2051
+ type="checkbox"
2052
+ .checked=${r}
2053
+ ?disabled=${this.loading||this.saving||s||!i}
2054
+ @change=${o=>{this.toggleSubsessions(o)}}
2055
+ >
2056
+ <span>Enable the <code>spawn_subsession</code> tools</span>
2057
+ </label>
2058
+ <small>Beta: agents can start child sessions they stay attached to (<code>spawn_subsession</code>, <code>list_subsessions</code>, <code>check_subsession</code>, <code>read_subsession</code>) and are notified when a child finishes. Requires "Allow agents to start sessions". Off by default.</small>
2059
+ </div>
2060
+ <section class="effective-card" aria-label="Effective configuration summary">
2061
+ <h3>Effective after environment overrides</h3>
2062
+ <dl>
2063
+ <div><dt>Spawn sessions</dt><dd>${i?"Enabled":l`<span class="muted">Disabled</span>`}</dd></div>
2064
+ <div><dt>Subsessions</dt><dd>${r?"Enabled":l`<span class="muted">Disabled</span>`}</dd></div>
2065
+ </dl>
2066
+ </section>
2067
+ `}
2068
+ </settings-panel-frame>
2069
+ `}panelNotices(e){const t=[];return this.error!==""&&t.push({type:"error",content:this.error}),this.savedMessage!==""&&t.push({type:"success",content:this.savedMessage}),e!==void 0&&t.push({type:"warning",title:`Restart required on ${this.targetLabel}`,content:l`run <code>omp-web restart</code> on that machine (or restart its session daemon service) after changing these settings.`}),t}renderUnavailableConfigState(){return l`<div class="loading-card">${this.loading?"Loading configuration…":"Configuration is unavailable. Reload to try again."}</div>`}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(tS(t))}async toggleSubsessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(iS(t))}};Ue.styles=D`
2070
+ :host { display: block; }
2071
+ h3 { margin: 0; font-size: 13px; line-height: 1.3; }
2072
+ button, input { font: inherit; }
2073
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2074
+ button:disabled { opacity: .55; cursor: not-allowed; }
2075
+ .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
2076
+ .loading-card { color: var(--pi-muted); }
2077
+ .config-path-card { display: grid; gap: 5px; }
2078
+ .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
2079
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
2080
+ .field { display: grid; gap: 7px; }
2081
+ .field small { color: var(--pi-muted); line-height: 1.45; }
2082
+ .field-heading { display: flex; align-items: center; gap: 8px; }
2083
+ .toggle { display: flex; align-items: center; gap: 9px; cursor: pointer; }
2084
+ .toggle input { width: 16px; height: 16px; }
2085
+ .toggle input:disabled { cursor: not-allowed; }
2086
+ .override-badge { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); background: var(--pi-warning-surface); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: none; }
2087
+ .beta-badge { border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); background: var(--pi-bg); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; }
2088
+ .effective-card { display: grid; gap: 10px; }
2089
+ .effective-card dl { display: grid; gap: 8px; margin: 0; }
2090
+ .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
2091
+ dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
2092
+ .muted { color: var(--pi-muted); }
2093
+
2094
+ @media (max-width: 760px) {
2095
+ .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
2096
+ }
2097
+ `;it([d({attribute:!1})],Ue.prototype,"configResponse",2);it([d({type:Boolean})],Ue.prototype,"loading",2);it([d({type:Boolean})],Ue.prototype,"saving",2);it([d()],Ue.prototype,"error",2);it([d()],Ue.prototype,"savedMessage",2);it([d()],Ue.prototype,"targetLabel",2);it([d({attribute:!1})],Ue.prototype,"onReload",2);it([d({attribute:!1})],Ue.prototype,"onSave",2);Ue=it([E("settings-sessiond-panel")],Ue);function nS(e){return`These settings affect the long-lived session runtime on ${e}. Changes are saved immediately but only take effect after the session daemon on that machine restarts.`}function xr(e){return e!==void 0?{id:e.id,name:e.name,kind:e.kind}:{id:"local",name:"local",kind:"local"}}function te(e){return e.kind==="local"?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function ca(e,t){return e.kind==="local"?{state:"supported"}:t?.ok!==!0?{state:"unknown"}:Fe(t,Ce.selectedMachineSettings)?{state:"supported"}:{state:"unsupported",message:cc(e)}}function da(e){return`${e.state}:${e.message??""}`}function Mt(e){return e?.state==="unsupported"}function cc(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEB on that machine, then try again.`}function ot(e,t){const i=e.trim();return t.kind!=="remote"?i:aS(i)?cc(t):i==="Remote machine timeout"?`Timed out while contacting ${t.name} for selected-machine settings. The operation may still be running remotely; reload before retrying.`:i==="Remote machine unavailable"?`Could not reach ${t.name} for selected-machine settings. Check the machine connection and try again.`:i}function aS(e){return e==="Not Found"||/route\s+(GET|PUT):?\/api\/(config|plugins)\b.*not found/iu.test(e)||/cannot\s+(GET|PUT)\s+.*\/api\/(config|plugins)\b/iu.test(e)}function dc(e){return xr(e)}function bt(e){return e.kind==="local"?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function pa(e,t){return e.kind==="local"?{state:"supported"}:t?.ok!==!0?{state:"unknown"}:Fe(t,Ce.piPackagesManage)?{state:"supported"}:{state:"unsupported",message:pc(e)}}function ha(e){return`${e.state}:${e.message??""}`}function ho(e){return e?.state==="unsupported"}function pc(e){return`Pi package management is not available on ${e.name}. Update and restart Omp-Web on that machine, then try again.`}function lS(e){return e.kind==="local"}function hc(e){return e.trim()}function cS(e){if(hc(e)==="")return"Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path."}function dS(e){return e.scope==="project"?"Project scope":"User scope"}function pS(e){return e.filtered?"Filtered by current Pi package settings":"Available in this PI WEB process"}function hS(e){return e.installedPath??"Installed path not reported by Pi"}function uc(e){return e.scope==="user"}function uS(e){if(!uc(e))return"Project-scope Pi packages are listed for visibility, but PI WEB only updates user-scope Pi packages safely from this view."}function fS(e){return e.length>0&&e.every(uc)}function gS(e){if(e.length===0)return"No Pi packages are configured yet.";if(!fS(e))return"Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually."}function Ii(e,t,i){return e?.kind!==t?!1:i===void 0||e.source===i}function mS(e,t=dc(void 0)){const i=e==="install"?"installed":e==="remove"?"removed":"updated",s=t.kind==="local"?"":` on ${t.name}`,r=t.kind==="local"?"each idle PI WEB session":`each idle PI WEB session on ${t.name}`,o=t.kind==="local"?"PI WEB browser plugin changes":`PI WEB browser plugin changes served by ${t.name}`;return`Pi package ${i}${s}. Type /reload in ${r} to rediscover Pi runtime resources: extensions, skills, prompt templates, themes, and context/system prompt files. Reload the browser page separately for ${o}.`}function fc(e,t){const i=e.trim();return t.kind!=="remote"?i:vS(i)?pc(t):i==="Remote machine timeout"?`Timed out while contacting ${t.name} for Pi package management. The package operation may still be running remotely; reload the package list before retrying.`:i==="Remote machine unavailable"?`Could not reach ${t.name} for Pi package management. Check the machine connection and try again.`:i}function vS(e){return e==="Not Found"||/route\s+(GET|POST):?\/api\/pi-packages\b.*not found/iu.test(e)||/cannot\s+(GET|POST)\s+.*\/api\/pi-packages\b/iu.test(e)}var bS=Object.defineProperty,wS=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var r=s>1?void 0:s?wS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&bS(t,i,r),r};let le=class extends I{constructor(){super(...arguments),this.loading=!1,this.error="",this.operationMessage="",this.installSource="",this.validationMessage=""}render(){const e=this.packagesResponse?.packages??[],t=this.packageTarget,i=bt(t),s=this.packageManagementUnavailable,r=this.packagesResponse!==void 0&&!s;return l`
2098
+ <settings-panel-frame
2099
+ heading="Pi packages"
2100
+ .description=${yS(i)}
2101
+ actionLabel="Reload"
2102
+ actionTitle=${s?this.packageManagementUnavailableMessage(i):`Reload Pi packages from ${i}`}
2103
+ .actionDisabled=${this.loading||this.isOperating||s}
2104
+ .notices=${this.panelNotices(i,r)}
2105
+ .onAction=${this.onReload}
2106
+ >
2107
+ ${this.renderPanelContent(e,t,i)}
2108
+ </settings-panel-frame>
2109
+ `}panelNotices(e,t){const i=[];return this.packageManagementUnavailable?i.push({type:"availability",content:this.packageManagementUnavailableMessage(e)}):this.error!==""&&i.push({type:"error",content:this.error}),this.operationMessage!==""&&i.push({type:"success",content:this.operationMessage}),t&&i.push({type:"security",content:l`<strong>Trusted code warning:</strong> Pi packages and PI WEB plugins can run with your user permissions. Install packages and enable plugins only from sources you trust.`}),i}renderPanelContent(e,t,i){return this.packageManagementUnavailable?null:this.packagesResponse===void 0?l`<div class="loading-card">${this.loading?`Loading Pi packages from ${i}…`:`Pi package list unavailable for ${i}. Use Reload to try again.`}</div>`:l`
2110
+ ${this.renderInstallForm(i)}
2111
+ ${this.renderPackageList(e,t)}
2112
+ `}renderInstallForm(e){return l`
2113
+ <form class="install-card" @submit=${t=>{this.installPackage(t)}}>
2114
+ <label for="package-source">Pi package source</label>
2115
+ <div class="install-row">
2116
+ <input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package, git URL, or local path" @input=${t=>{this.updateInstallSource(t)}}>
2117
+ <button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${Ii(this.operation,"install")?"Installing…":"Install"}</button>
2118
+ </div>
2119
+ ${this.validationMessage===""?null:l`<div class="field-error">${this.validationMessage}</div>`}
2120
+ <small>Installs run on ${e} and use Pi's default package location, equivalent to <code>pi install &lt;source&gt;</code>. PI WEB does not ask you to choose an install location.</small>
2121
+ </form>
2122
+ `}renderPackageList(e,t){const i=bt(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(i):gS(e),o=r!==void 0&&e.length>0;return l`
2123
+ <section class="package-section" aria-label="Configured Pi packages">
2124
+ <div class="package-toolbar">
2125
+ <div>
2126
+ <h3>Configured Pi packages</h3>
2127
+ <p>This list comes from Pi's package manager settings on ${i}.</p>
2128
+ </div>
2129
+ <button class="secondary" title=${r??"Update all user-scope Pi packages"} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
2130
+ ${Ii(this.operation,"update-all")?"Updating…":"Update all"}
2131
+ </button>
2132
+ </div>
2133
+ ${o?l`<div class="action-note">${r}</div>`:null}
2134
+ ${this.loading&&e.length>0?l`<div class="action-note">Refreshing Pi packages from ${i}…</div>`:null}
2135
+ ${this.renderPackageListContent(e,i)}
2136
+ </section>
2137
+ `}renderPackageListContent(e,t){return this.loading&&e.length===0?l`<div class="loading-card">Loading Pi packages from ${t}…</div>`:e.length===0?l`<div class="loading-card">No Pi packages configured in Pi settings on ${t} yet.</div>`:l`
2138
+ <div class="package-list">
2139
+ ${e.map(i=>this.renderPackage(i))}
2140
+ </div>
2141
+ `}renderPackage(e){const t=bt(this.packageTarget),i=this.packageManagementUnavailable,s=i?this.packageManagementUnavailableMessage(t):uS(e),r=i?this.packageManagementUnavailableMessage(t):"Remove this Pi package",o=Ii(this.operation,"update",e.source),n=Ii(this.operation,"remove",e.source);return l`
2142
+ <article class=${`package-card${e.filtered?" filtered":""}`}>
2143
+ <div class="package-main">
2144
+ <strong>${e.source}</strong>
2145
+ <small>${dS(e)} · ${pS(e)}</small>
2146
+ <small>Installed path: <code>${hS(e)}</code></small>
2147
+ ${s===void 0?null:l`<small class="action-note">${s}</small>`}
2148
+ </div>
2149
+ <div class="package-actions">
2150
+ <button class="secondary" title=${s??"Update this Pi package"} ?disabled=${this.isOperating||s!==void 0} @click=${()=>{this.updatePackage(e.source)}}>${o?"Updating…":"Update"}</button>
2151
+ <button class="danger" title=${r} ?disabled=${this.isOperating||i} @click=${()=>{this.removePackage(e)}}>${n?"Removing…":"Remove"}</button>
2152
+ </div>
2153
+ </article>
2154
+ `}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:"",this.validationMessage=""}async installPackage(e){e.preventDefault();const t=cS(this.installSource);if(t!==void 0){this.validationMessage=t;return}const i=hc(this.installSource);try{await this.onInstallPackage?.(i),this.installSource="",this.validationMessage=""}catch{}}async removePackage(e){try{await this.onRemovePackage?.(e.source,e.scope)}catch{}}async updatePackage(e){try{await this.onUpdatePackage?.(e)}catch{}}get packageTarget(){return this.targetMachine??dc(void 0)}get packageManagementUnavailable(){return ho(this.managementSupport)}packageManagementUnavailableMessage(e){return this.managementSupport?.message??`Pi package management is not available on ${e}.`}get isOperating(){return this.operation!==void 0}};le.styles=D`
2155
+ :host { display: block; }
2156
+ .package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
2157
+ .package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
2158
+ h3, p { margin: 0; }
2159
+ h3 { font-size: 15px; line-height: 1.25; }
2160
+ p, small { color: var(--pi-muted); line-height: 1.45; }
2161
+ button, input { font: inherit; }
2162
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2163
+ button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
2164
+ input { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 8px 9px; }
2165
+ label { font-weight: 700; }
2166
+ .secondary { flex: 0 0 auto; }
2167
+ .danger { border-color: color-mix(in srgb, var(--pi-danger) 55%, var(--pi-border)); color: var(--pi-danger); }
2168
+ .loading-card, .install-card, .package-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
2169
+ .field-error { color: var(--pi-danger); font-size: 12px; }
2170
+ .install-card { display: grid; gap: 8px; }
2171
+ .install-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: center; }
2172
+ .package-section { display: block; }
2173
+ .loading-card, .action-note { color: var(--pi-muted); }
2174
+ .action-note { margin-bottom: 10px; font-size: 12px; }
2175
+ .package-list { display: grid; gap: 10px; }
2176
+ .package-card { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center; }
2177
+ .package-card.filtered { opacity: .82; }
2178
+ .package-main strong, .package-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2179
+ .package-actions { display: flex; align-items: center; gap: 8px; }
2180
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
2181
+
2182
+ @media (max-width: 760px) {
2183
+ .package-toolbar { display: grid; gap: 12px; }
2184
+ .package-toolbar .secondary { justify-self: start; }
2185
+ .install-row, .package-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
2186
+ .package-actions { justify-self: start; flex-wrap: wrap; }
2187
+ .package-main strong, .package-main small { white-space: normal; }
2188
+ }
2189
+ `;we([d({attribute:!1})],le.prototype,"packagesResponse",2);we([d({type:Boolean})],le.prototype,"loading",2);we([d({attribute:!1})],le.prototype,"operation",2);we([d({attribute:!1})],le.prototype,"targetMachine",2);we([d({attribute:!1})],le.prototype,"managementSupport",2);we([d()],le.prototype,"error",2);we([d()],le.prototype,"operationMessage",2);we([d({attribute:!1})],le.prototype,"onReload",2);we([d({attribute:!1})],le.prototype,"onInstallPackage",2);we([d({attribute:!1})],le.prototype,"onRemovePackage",2);we([d({attribute:!1})],le.prototype,"onUpdatePackage",2);we([v()],le.prototype,"installSource",2);we([v()],le.prototype,"validationMessage",2);le=we([E("settings-packages-panel")],le);function yS(e){return l`Managing Pi packages on <strong>${e}</strong>. Install, remove, and update packages managed by Pi on the selected machine. Pi packages can provide extensions, skills, prompt templates, themes, context/system prompt files, and PI WEB browser plugins.`}var SS=Object.defineProperty,xS=Object.getOwnPropertyDescriptor,Qe=(e,t,i,s)=>{for(var r=s>1?void 0:s?xS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&SS(t,i,r),r};let Ae=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.targetLabel="local (local gateway)"}render(){const e=this.pluginsResponse?.plugins??[],t=this.pluginsResponse!==void 0;return l`
2190
+ <settings-panel-frame
2191
+ heading="PI WEB plugins"
2192
+ .description=${kS(this.targetLabel)}
2193
+ actionLabel="Reload"
2194
+ actionTitle=${`Reload PI WEB plugins from ${this.targetLabel}`}
2195
+ .actionDisabled=${this.loading}
2196
+ .notices=${this.panelNotices(e.length>0)}
2197
+ .onAction=${this.onReload}
2198
+ >
2199
+ ${this.renderPanelContent(e,t)}
2200
+ </settings-panel-frame>
2201
+ `}panelNotices(e){const t=[];return this.error!==""&&t.push({type:"error",content:this.error}),this.shouldShowConfigUnavailableNotice(e)&&t.push({type:"availability",content:"Configuration is unavailable. Reload to try again before changing plugin enablement."}),this.savedMessage!==""&&t.push({type:"success",content:`${this.savedMessage} Reload the browser tab to apply plugin changes.`}),e&&t.push({type:"security",content:l`<strong>Trusted code warning:</strong> PI WEB plugins and Pi packages can run with your user permissions. Enable plugins only from sources you trust.`}),t}shouldShowConfigUnavailableNotice(e){return e&&this.configResponse===void 0&&!this.loading&&this.error===""}renderPanelContent(e,t){return t?e.length===0?l`<div class="loading-card">No PI WEB browser plugins discovered on ${this.targetLabel}.</div>`:l`
2202
+ <div class="plugin-note">Config key on ${this.targetLabel}: <code>plugins</code>. Plugins are enabled unless their entry sets <code>enabled</code> to <code>false</code>.</div>
2203
+ <div class="plugin-list">
2204
+ ${e.map(i=>this.renderPlugin(i))}
2205
+ </div>
2206
+ `:l`<div class="loading-card">${this.loading?"Loading PI WEB plugins…":`PI WEB plugin list unavailable for ${this.targetLabel}. Use Reload to try again.`}</div>`}renderPlugin(e){const t=this.configResponse?.config.plugins?.[e.id],i=t?.enabled===!1?"Config disabled":t?.enabled===!0?"Config enabled":"Default enabled";return l`
2207
+ <article class=${`plugin-card${e.enabled?"":" disabled"}`}>
2208
+ <div class="plugin-main">
2209
+ <strong>${e.id}</strong>
2210
+ <small>${e.source} · ${e.scope}${e.machineSpecific?" · machine-specific":""}</small>
2211
+ <small>${i}</small>
2212
+ </div>
2213
+ <label class="toggle">
2214
+ <input type="checkbox" .checked=${e.enabled} ?disabled=${this.saving||this.configResponse===void 0} @change=${s=>{this.togglePlugin(e,s)}}>
2215
+ <span>${e.enabled?"Enabled":"Disabled"}</span>
2216
+ </label>
2217
+ </article>
2218
+ `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Ae.styles=D`
2219
+ :host { display: block; }
2220
+ input { font: inherit; }
2221
+ input:disabled { opacity: .55; cursor: not-allowed; }
2222
+ .loading-card, .plugin-note, .plugin-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
2223
+ .loading-card, .plugin-note { color: var(--pi-muted); }
2224
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
2225
+ .plugin-list { display: grid; gap: 10px; }
2226
+ .plugin-card { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center; }
2227
+ .plugin-card.disabled { opacity: .75; }
2228
+ .plugin-main { min-width: 0; display: grid; gap: 3px; }
2229
+ .plugin-main strong, .plugin-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2230
+ .plugin-main small { color: var(--pi-muted); }
2231
+ .toggle { display: inline-flex; align-items: center; gap: 7px; white-space: nowrap; }
2232
+ .toggle input { width: 18px; height: 18px; accent-color: var(--pi-accent); }
2233
+
2234
+ @media (max-width: 760px) {
2235
+ .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
2236
+ .toggle { justify-self: start; }
2237
+ }
2238
+ `;Qe([d({attribute:!1})],Ae.prototype,"pluginsResponse",2);Qe([d({attribute:!1})],Ae.prototype,"configResponse",2);Qe([d({type:Boolean})],Ae.prototype,"loading",2);Qe([d({type:Boolean})],Ae.prototype,"saving",2);Qe([d()],Ae.prototype,"error",2);Qe([d()],Ae.prototype,"savedMessage",2);Qe([d()],Ae.prototype,"targetLabel",2);Qe([d({attribute:!1})],Ae.prototype,"onReload",2);Qe([d({attribute:!1})],Ae.prototype,"onTogglePlugin",2);Ae=Qe([E("settings-plugins-panel")],Ae);function kS(e){return l`Enable or disable discovered PI WEB browser plugins on <strong>${e}</strong>. This is separate from installing Pi packages. Reload the browser tab to apply plugin runtime changes.`}var $S=Object.defineProperty,PS=Object.getOwnPropertyDescriptor,ke=(e,t,i,s)=>{for(var r=s>1?void 0:s?PS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$S(t,i,r),r};const ua={capture:!0},CS=[{value:"auto",label:"Auto/default",description:"Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line."},{value:"send",label:"Enter sends message",description:"Enter sends the chat message; Shift+Enter adds a new line when supported."},{value:"newline",label:"Enter inserts new line",description:"Enter adds a line break; Shift+Enter sends the chat message when supported."}];function RS(){return l`Edit app shortcuts by action. Type a shortcut such as <code>mod+k</code> or <code>mod+g p</code>, record one from the keyboard, disable it with None, or reset it to the default. When shortcuts conflict, custom shortcuts win before defaults; ties are resolved by action id, and shorter shortcuts shadow longer sequences with the same prefix.`}let pe=class extends I{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.promptEnterPreference=Rs(),this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=ul(e);if(i===void 0){this.localError="Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.";return}if(t.tokens.length===0&&!di(i)){this.localError="Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.";return}const s=[...t.tokens,i];this.localError="",this.drafts={[t.actionId]:s.join(" ")},this.recording={actionId:t.actionId,tokens:s},this.armRecordingTimer()}}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.drafts={},this.localError="",this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){const e=AS(this.actions),t=this.shortcutResolutions();return l`
2239
+ <settings-panel-frame
2240
+ heading="Keyboard shortcuts"
2241
+ .description=${RS()}
2242
+ actionLabel="Reload"
2243
+ .actionDisabled=${this.loading}
2244
+ .notices=${this.panelNotices()}
2245
+ .onAction=${this.onReload}
2246
+ >
2247
+ ${this.renderPromptEnterPreferenceCard()}
2248
+ ${this.configResponse===void 0&&this.loading?l`<div class="loading-card">Loading shortcuts…</div>`:l`
2249
+ <div class="config-path-card">
2250
+ <span>Config file</span>
2251
+ <code>${this.configResponse?.path??"Unknown"}</code>
2252
+ <small>Shortcut overrides are saved under <code>shortcuts</code>. A value of <code>null</code> disables the action shortcut.</small>
2253
+ </div>
2254
+ ${e.length===0?l`<div class="loading-card">No actions registered.</div>`:e.map(i=>l`
2255
+ <section class="shortcut-group">
2256
+ <h3>${i.name}</h3>
2257
+ <div class="shortcut-list">
2258
+ ${i.actions.map(s=>this.renderShortcutRow(s,t.get(s.id)))}
2259
+ </div>
2260
+ </section>
2261
+ `)}
2262
+ `}
2263
+ </settings-panel-frame>
2264
+ `}panelNotices(){const e=[],t=this.localError||this.error;return t!==""&&e.push({type:"error",content:t}),this.savedMessage!==""&&e.push({type:"success",content:this.savedMessage}),e}renderPromptEnterPreferenceCard(){return l`
2265
+ <section class="prompt-enter-card" aria-labelledby="prompt-enter-preference-title">
2266
+ <div class="prompt-enter-copy">
2267
+ <span class="card-eyebrow">Chat composer</span>
2268
+ <h3 id="prompt-enter-preference-title">Enter key behavior</h3>
2269
+ <p>Choose what Enter does in this browser. Shift+Enter does the opposite when supported; automatic touch-keyboard capitalization is ignored to avoid accidental sends.</p>
2270
+ </div>
2271
+ <div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
2272
+ ${CS.map(e=>l`
2273
+ <label class="prompt-enter-option">
2274
+ <input
2275
+ type="radio"
2276
+ name="prompt-enter-preference"
2277
+ .value=${e.value}
2278
+ .checked=${this.promptEnterPreference===e.value}
2279
+ @change=${()=>{this.updatePromptEnterPreference(e.value)}}
2280
+ >
2281
+ <span>
2282
+ <strong>${e.label}</strong>
2283
+ <small>${e.description}</small>
2284
+ </span>
2285
+ </label>
2286
+ `)}
2287
+ </div>
2288
+ </section>
2289
+ `}updatePromptEnterPreference(e){this.promptEnterPreference=e,Bw(e)}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=ds(e.id,i),r=LS(e,i),o=this.shortcutInputText(e),n=o.trim()===""?void 0:Us(o),a=n?.ok===!0?n.shortcut:WS(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&o.trim()!==""?"custom":r,h=this.recordingHint(e.id),f=TS(t);return l`
2290
+ <article class=${MS(t)}>
2291
+ <div class="shortcut-main">
2292
+ <strong>${e.title}</strong>
2293
+ ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
2294
+ <small class="shortcut-id">${e.id}</small>
2295
+ <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${_i(e.shortcut)}</kbd>`:"No default shortcut"}</small>
2296
+ </div>
2297
+ <div class="shortcut-editor">
2298
+ <div class="shortcut-status">
2299
+ ${a!==void 0&&a!==""?l`<kbd>${_i(a)}</kbd>`:l`<span class="unassigned">${r==="disabled"?"Disabled":"Unassigned"}</span>`}
2300
+ <small class=${u}>${OS(u)}${p?" · Unsaved":""}</small>
2301
+ ${f===void 0?null:l`<small class=${IS(t)}>${f}</small>`}
2302
+ </div>
2303
+ <label class="shortcut-input-label">
2304
+ <span>Shortcut</span>
2305
+ <input
2306
+ class="shortcut-input"
2307
+ data-action-id=${e.id}
2308
+ .value=${o}
2309
+ placeholder=${e.shortcut??"mod+k"}
2310
+ autocomplete="off"
2311
+ autocapitalize="off"
2312
+ spellcheck="false"
2313
+ ?disabled=${this.saving}
2314
+ @input=${S=>{this.updateDraft(e.id,FS(S))}}
2315
+ >
2316
+ </label>
2317
+ ${h!==""?l`<small class="recording-hint">${h}</small>`:null}
2318
+ <div class="shortcut-actions">
2319
+ <button class="primary" ?disabled=${this.loading||this.saving||!p||o.trim()===""} @click=${()=>{this.saveShortcut(e)}}>Save</button>
2320
+ <button ?disabled=${this.loading||this.saving} @click=${()=>{this.toggleRecording(e.id)}}>${this.recording?.actionId===e.id?"Cancel recording":"Record"}</button>
2321
+ <button ?disabled=${this.loading||this.saving||s===null} @click=${()=>{this.setShortcutNone(e.id)}}>None</button>
2322
+ <button ?disabled=${this.loading||this.saving||!c} @click=${()=>{this.resetShortcut(e.id)}}>Reset</button>
2323
+ </div>
2324
+ </div>
2325
+ </article>
2326
+ `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=ds(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${_i(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=Us(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},r=t===void 0?DS(s,e):{...s,[e]:t};Object.keys(r).length===0?delete i.shortcuts:i.shortcuts=r,await this.onSave?.(i)}shortcutResolutions(){return new Map(Br(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const r=Us(s);r.ok&&(e[t]=r.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},pl)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||(window.addEventListener("keydown",this.onRecordKeyDown,ua),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,ua),this.recordingListenerActive=!1)}};pe.styles=D`
2327
+ :host { display: block; }
2328
+ h3, p { margin: 0; }
2329
+ h3 { font-size: 13px; line-height: 1.3; }
2330
+ p { color: var(--pi-muted); line-height: 1.45; }
2331
+ button, input { font: inherit; }
2332
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2333
+ button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
2334
+ .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
2335
+ .loading-card, .config-path-card, .prompt-enter-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
2336
+ .loading-card, .config-path-card { color: var(--pi-muted); }
2337
+ .config-path-card { display: grid; gap: 5px; }
2338
+ .config-path-card span, .card-eyebrow { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
2339
+ .prompt-enter-card { display: grid; grid-template-columns: minmax(0, .85fr) minmax(260px, 1fr); gap: 12px; align-items: start; }
2340
+ .prompt-enter-copy { display: grid; gap: 5px; min-width: 0; }
2341
+ .prompt-enter-copy p, .prompt-enter-option small { font-size: 12px; }
2342
+ .prompt-enter-options { display: grid; gap: 7px; }
2343
+ .prompt-enter-option { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 8px; align-items: start; color: var(--pi-text); }
2344
+ .prompt-enter-option input { box-sizing: border-box; width: 14px; min-width: 14px; height: 14px; margin: 3px 0 0; padding: 0; border: 0; background: transparent; accent-color: var(--pi-accent); font-family: inherit; }
2345
+ .prompt-enter-option input:focus { border-color: transparent; box-shadow: none; outline: 2px solid var(--pi-accent-border); outline-offset: 2px; }
2346
+ .prompt-enter-option span { display: grid; gap: 2px; }
2347
+ .prompt-enter-option small { color: var(--pi-muted); line-height: 1.35; }
2348
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
2349
+ .shortcut-group { margin: 0; }
2350
+ .shortcut-group h3 { margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
2351
+ .shortcut-list { border: 1px solid var(--pi-border); border-radius: 10px; overflow: hidden; }
2352
+ .shortcut-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(360px, 48%); gap: 14px; align-items: start; padding: 12px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-surface); }
2353
+ .shortcut-row.shadowed { background: color-mix(in srgb, var(--pi-warning) 5%, var(--pi-surface)); }
2354
+ .shortcut-row.shadowing { background: color-mix(in srgb, var(--pi-accent) 5%, var(--pi-surface)); }
2355
+ .shortcut-row:last-child { border-bottom: 0; }
2356
+ .shortcut-main { min-width: 0; display: grid; gap: 4px; }
2357
+ .shortcut-main strong, .shortcut-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2358
+ .shortcut-main small { color: var(--pi-muted); }
2359
+ .shortcut-id { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
2360
+ .shortcut-editor { min-width: 0; display: grid; gap: 8px; }
2361
+ .shortcut-status { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
2362
+ .shortcut-status small { color: var(--pi-muted); font-size: 11px; }
2363
+ .shortcut-status small.custom { color: var(--pi-accent); }
2364
+ .shortcut-status small.disabled { color: var(--pi-warning); }
2365
+ .shortcut-status small.conflict { border: 1px solid currentColor; border-radius: 999px; padding: 2px 7px; }
2366
+ .shortcut-status small.conflict.shadowing { color: var(--pi-accent); }
2367
+ .shortcut-status small.conflict.shadowed { color: var(--pi-warning); }
2368
+ .shortcut-input-label { min-width: 0; display: grid; gap: 5px; }
2369
+ .shortcut-input-label span { color: var(--pi-muted); font-size: 11px; font-weight: 700; text-transform: uppercase; }
2370
+ input { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 8px 9px; outline: none; font: var(--pi-control-font-size, 16px) var(--pi-control-monospace-font-family, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); }
2371
+ input:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
2372
+ .shortcut-actions { display: flex; justify-content: flex-end; gap: 7px; flex-wrap: wrap; }
2373
+ kbd { border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-bg); color: var(--pi-text-secondary); padding: 3px 7px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
2374
+ .unassigned { color: var(--pi-muted); font-size: 12px; }
2375
+ .recording-hint { color: var(--pi-accent); font-size: 12px; }
2376
+
2377
+ @media (max-width: 760px) {
2378
+ .prompt-enter-card { grid-template-columns: minmax(0, 1fr); }
2379
+ .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
2380
+ .shortcut-status, .shortcut-actions { justify-content: flex-start; }
2381
+ }
2382
+ `;ke([d({attribute:!1})],pe.prototype,"actions",2);ke([d({attribute:!1})],pe.prototype,"configResponse",2);ke([d({type:Boolean})],pe.prototype,"loading",2);ke([d({type:Boolean})],pe.prototype,"saving",2);ke([d()],pe.prototype,"error",2);ke([d()],pe.prototype,"savedMessage",2);ke([d({attribute:!1})],pe.prototype,"onReload",2);ke([d({attribute:!1})],pe.prototype,"onSave",2);ke([v()],pe.prototype,"drafts",2);ke([v()],pe.prototype,"localError",2);ke([v()],pe.prototype,"promptEnterPreference",2);ke([v()],pe.prototype,"recording",2);pe=ke([E("settings-shortcuts-panel")],pe);function MS(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function IS(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function TS(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(r=>r.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function AS(e){const t=new Map;for(const i of[...e].sort(ES)){const s=i.group??"Other";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function ES(e,t){return(e.group??"Other").localeCompare(t.group??"Other")||e.title.localeCompare(t.title)}function ds(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function DS(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function WS(e,t){const i=ds(e.id,t);if(i!==null)return i??e.shortcut}function LS(e,t){const i=ds(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function OS(e){switch(e){case"default":return"Default";case"custom":return"Custom";case"disabled":return"Disabled";case"unassigned":return"No default"}}function FS(e){return e.target instanceof HTMLInputElement?e.target.value:""}async function _S(e){const[t,i]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),s={error:""},r=[];return t.status==="fulfilled"?s.config=t.value:r.push(`config: ${q(t.reason)}`),i.status==="fulfilled"?s.plugins=i.value:r.push(`PI WEB plugins: ${q(i.reason)}`),r.length>0&&(s.error=`Failed to load settings: ${r.join("; ")}`),s}async function jS(e,t,i){if(ho(i))return{error:i.message??`Pi package management is not available on ${bt(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:""}}catch(s){return{error:`Failed to load Pi packages from ${bt(e)}: ${fc(q(s),e)}`}}}function US(e,t){return{...e,config:fa(e.config,t.config),effectiveConfig:fa(e.effectiveConfig,t.effectiveConfig)}}function fa(e,t){return{...e,...t.pathAccess===void 0?{}:{pathAccess:t.pathAccess},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes}}}function NS(e,t,i){const s=e.plugins??{},r=s[t]??{};return{plugins:{...s,[t]:{...r,enabled:i}}}}function BS(e,t){return{...e,config:ga(e.config,t.config),effectiveConfig:ga(e.effectiveConfig,t.effectiveConfig)}}function ga(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var zS=Object.defineProperty,qS=Object.getOwnPropertyDescriptor,F=(e,t,i,s)=>{for(var r=s>1?void 0:s?qS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&zS(t,i,r),r};let L=class extends I{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error="",this.accessError="",this.sessiondError="",this.pluginError="",this.packageError="",this.savedMessage="",this.packageMessage="",this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.loadSessiondConfigForTarget(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){const t=this.settingsTarget();if(e.has("machine")&&xr(e.get("machine")).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t);return}e.has("machineRuntime")&&(this.selectedMachineSettingsSupportNeedsReload(e.get("machineRuntime"),t)&&(this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t)),this.packageManagementSupportNeedsReload(e.get("machineRuntime"),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return l`
2383
+ <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
2384
+ <section class="settings-shell" role="dialog" aria-modal="true" aria-label="OMP Web settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
2385
+ <header class="settings-header">
2386
+ <div>
2387
+ <span class="eyebrow">Settings</span>
2388
+ <h1>OMP Web</h1>
2389
+ </div>
2390
+ <button class="close-button" title="Close settings" aria-label="Close settings" @click=${()=>this.onClose?.()}>×</button>
2391
+ </header>
2392
+ <div class="settings-body">
2393
+ <nav class="settings-nav" aria-label="Settings sections">
2394
+ ${this.renderNavButton("general","General","Gateway + selected machine")}
2395
+ ${this.renderNavButton("sessiond","Session daemon","Selected machine")}
2396
+ ${this.renderNavButton("packages","Pi packages","Selected machine")}
2397
+ ${this.renderNavButton("plugins","PI WEB plugins","Selected machine")}
2398
+ ${this.renderNavButton("shortcuts","Keyboard","Gateway shortcuts")}
2399
+ </nav>
2400
+ <main class="settings-content">
2401
+ ${this.renderActiveSection()}
2402
+ </main>
2403
+ </div>
2404
+ </section>
2405
+ </div>
2406
+ `}renderActiveSection(){return this.section==="sessiond"?l`
2407
+ <settings-sessiond-panel
2408
+ .configResponse=${this.sessiondConfigResponse}
2409
+ .loading=${this.sessiondLoading}
2410
+ .saving=${this.saving}
2411
+ .error=${this.sessiondError}
2412
+ .savedMessage=${this.savedMessage}
2413
+ .targetLabel=${te(this.settingsTarget())}
2414
+ .onReload=${()=>this.loadSessiondConfigForTarget()}
2415
+ .onSave=${e=>this.saveSessiondConfig(e)}
2416
+ ></settings-sessiond-panel>
2417
+ `:this.section==="shortcuts"?l`
2418
+ <settings-shortcuts-panel
2419
+ .actions=${this.actions}
2420
+ .configResponse=${this.configResponse}
2421
+ .loading=${this.loading}
2422
+ .saving=${this.saving}
2423
+ .error=${this.error}
2424
+ .savedMessage=${this.savedMessage}
2425
+ .onReload=${()=>this.loadConfig()}
2426
+ .onSave=${e=>this.saveConfig(e)}
2427
+ ></settings-shortcuts-panel>
2428
+ `:this.section==="packages"?l`
2429
+ <settings-packages-panel
2430
+ .packagesResponse=${this.packagesResponse}
2431
+ .targetMachine=${this.packageTarget()}
2432
+ .managementSupport=${this.packageManagementSupport()}
2433
+ .loading=${this.packageLoading}
2434
+ .operation=${this.packageOperation}
2435
+ .error=${this.packageError}
2436
+ .operationMessage=${this.packageMessage}
2437
+ .onReload=${()=>this.loadPackagesForTarget()}
2438
+ .onInstallPackage=${e=>this.installPiPackage(e)}
2439
+ .onRemovePackage=${(e,t)=>this.removePiPackage(e,t)}
2440
+ .onUpdatePackage=${e=>this.updatePiPackage(e)}
2441
+ ></settings-packages-panel>
2442
+ `:this.section==="plugins"?l`
2443
+ <settings-plugins-panel
2444
+ .configResponse=${this.selectedPluginConfigResponse}
2445
+ .pluginsResponse=${this.selectedPluginsResponse}
2446
+ .loading=${this.pluginLoading}
2447
+ .saving=${this.saving}
2448
+ .error=${this.pluginError}
2449
+ .savedMessage=${this.savedMessage}
2450
+ .targetLabel=${te(this.settingsTarget())}
2451
+ .onReload=${()=>this.loadPluginsForTarget()}
2452
+ .onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
2453
+ ></settings-plugins-panel>
2454
+ `:l`
2455
+ <settings-general-panel
2456
+ .configResponse=${this.configResponse}
2457
+ .machineConfigResponse=${this.accessConfigResponse}
2458
+ .loading=${this.loading}
2459
+ .machineLoading=${this.accessLoading}
2460
+ .saving=${this.saving}
2461
+ .error=${this.error}
2462
+ .machineError=${this.accessError}
2463
+ .savedMessage=${this.savedMessage}
2464
+ .targetLabel=${te(this.settingsTarget())}
2465
+ .onReload=${()=>this.loadConfig()}
2466
+ .onReloadMachine=${()=>this.loadAccessConfigForTarget()}
2467
+ .onSave=${e=>this.saveConfig(e)}
2468
+ .onSaveMachineConfig=${e=>this.saveMachineAccessConfig(e)}
2469
+ ></settings-general-panel>
2470
+ `}renderNavButton(e,t,i){const s=this.section===e;return l`
2471
+ <button class=${s?"selected":""} aria-current=${s?"page":"false"} @click=${()=>{this.navigate(e)}}>
2472
+ <strong>${t}</strong>
2473
+ <small>${i}</small>
2474
+ </button>
2475
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){const e=++this.loadRequestSeq;this.loading=!0,this.error="";try{const t=await _S({loadConfig:()=>ze.config(),loadPlugins:()=>Zt.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){const t=++this.accessLoadRequestSeq,i=this.selectedMachineSettingsSupport(e);if(Mt(i)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=i.message??`Selected-machine settings are not available on ${te(e)}.`;return}this.accessLoading=!0,this.accessError="";try{const s=await ze.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=s}catch(s){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${te(e)}: ${ot(q(s),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async loadSessiondConfigForTarget(e=this.settingsTarget()){const t=++this.sessiondLoadRequestSeq,i=this.selectedMachineSettingsSupport(e);if(Mt(i)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=i.message??`Selected-machine settings are not available on ${te(e)}.`;return}this.sessiondLoading=!0,this.sessiondError="";try{const s=await ze.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=s}catch(s){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${te(e)}: ${ot(q(s),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){const t=++this.pluginLoadRequestSeq,i=this.selectedMachineSettingsSupport(e);if(Mt(i)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=i.message??`Selected-machine settings are not available on ${te(e)}.`;return}this.pluginLoading=!0,this.pluginError="";try{const[s,r]=await Promise.allSettled([ze.config(e.id),Zt.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;const o=[];s.status==="fulfilled"?this.selectedPluginConfigResponse=s.value:o.push(`config: ${ot(q(s.reason),e)}`),r.status==="fulfilled"?this.selectedPluginsResponse=r.value:o.push(`PI WEB plugins: ${ot(q(r.reason),e)}`),this.pluginError=o.length===0?"":`Failed to load PI WEB plugin settings from ${te(e)}: ${o.join("; ")}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){const t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError="",this.packageMessage="";try{const i=await jS(e,s=>Xt.packages(s),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=i.packagesResponse,this.packageError=i.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;const i=this.settingsTarget(),s=this.selectedMachineSettingsSupport(i);if(Mt(s)){this.pluginError=s.message??`Selected-machine settings are not available on ${te(i)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${te(i)}. Reload before changing plugin enablement.`;return}const r=NS(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError="",this.savedMessage="";try{const o=await ze.saveConfig(r,i.id);if(!this.isCurrentSettingsTarget(i))return;this.selectedPluginConfigResponse=o,i.kind==="local"&&this.configResponse!==void 0&&(this.configResponse=BS(this.configResponse,o),this.onConfigSaved?.(this.configResponse.effectiveConfig));const n=await this.refreshPluginsForTarget(i);if(!this.isCurrentSettingsTarget(i))return;n!==void 0&&(this.pluginError=n),this.showSavedMessage()}catch(o){this.isCurrentSettingsTarget(i)&&(this.pluginError=`Failed to save PI WEB plugin config on ${te(i)}: ${ot(q(o),i)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await ze.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(t){this.error=`Failed to save config: ${q(t)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;const t=this.settingsTarget(),i=this.selectedMachineSettingsSupport(t);if(Mt(i)){this.accessError=i.message??`Selected-machine settings are not available on ${te(t)}.`;return}this.saving=!0,this.accessError="",this.savedMessage="";try{const s=await ze.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=s,t.kind==="local"&&this.configResponse!==void 0&&(this.configResponse=US(this.configResponse,s),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(s){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${te(t)}: ${ot(q(s),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;const t=this.settingsTarget(),i=this.selectedMachineSettingsSupport(t);if(Mt(i)){this.sessiondError=i.message??`Selected-machine settings are not available on ${te(t)}.`;return}this.saving=!0,this.sessiondError="",this.savedMessage="";try{const s=await ze.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=s,t.kind==="local"&&this.configResponse!==void 0&&(this.configResponse=sS(this.configResponse,s)),this.showSavedMessage()}catch(s){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${te(t)}: ${ot(q(s),t)}`)}finally{this.saving=!1}}async installPiPackage(e){const t=this.packageTarget();await this.runPiPackageMutation({kind:"install",source:e},"install Pi package",t,()=>Xt.install(e,t.id))}async removePiPackage(e,t){const i=this.packageTarget();await this.runPiPackageMutation({kind:"remove",source:e},"remove Pi package",i,()=>Xt.remove(e,t,i.id))}async updatePiPackage(e){const t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:"update-all"}:{kind:"update",source:e},"update Pi packages",t,()=>Xt.update(e,t.id))}async runPiPackageMutation(e,t,i,s){const r=this.packageManagementSupport(i);if(ho(r))throw this.packageError=r.message??`Pi package management is not available on ${bt(i)}.`,new Error(this.packageError);if(this.saving)throw new Error("A settings operation is already running.");const o=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError="",this.packageMessage="";try{const n=await s();if(!this.isCurrentPackageMutation(o,i))return;this.packagesResponse={packages:n.packages};const a=lS(i)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(o,i))return;a!==void 0&&(this.packageError=a),this.packageMessage=mS(n.action,i)}catch(n){throw this.isCurrentPackageMutation(o,i)&&(this.packageError=`Failed to ${t} on ${bt(i)}: ${fc(q(n),i)}`),n}finally{this.packageMutationSeq===o&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Zt.plugins();return}catch(e){return`Failed to refresh gateway PI WEB plugins: ${q(e)}`}}async refreshPluginsForTarget(e){try{const t=await Zt.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEB plugins from ${te(e)}: ${ot(q(t),e)}`}}settingsTarget(){return xr(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return ca(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){const i=ca(t,e),s=this.selectedMachineSettingsSupport(t);return da(i)!==da(s)}packageManagementSupport(e=this.packageTarget()){return pa(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){const i=pa(t,e),s=this.packageManagementSupport(t);return ha(i)===ha(s)?!1:i.state==="unsupported"||s.state==="unsupported"}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError="",this.accessConfigResponse=void 0,this.savedMessage=""}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError="",this.sessiondConfigResponse=void 0,this.savedMessage=""}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError="",this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=""}resetPackageStateForTargetChange(){const e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage="",this.packageError="",this.packagesResponse=void 0,e&&(this.saving=!1)}showSavedMessage(){this.savedMessage="Config saved.",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="Config saved."&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};L.styles=D`
2476
+ :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
2477
+ .backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
2478
+ .settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
2479
+ .settings-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
2480
+ .eyebrow { display: block; color: var(--pi-muted); font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
2481
+ h1 { margin: 0; font-size: 20px; line-height: 1.2; }
2482
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; font: inherit; cursor: pointer; }
2483
+ .close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
2484
+ .close-button:hover, .close-button:focus { color: var(--pi-text); background: var(--pi-surface-hover); }
2485
+ .settings-body { min-height: 0; display: grid; grid-template-columns: 220px minmax(0, 1fr); }
2486
+ .settings-nav { min-height: 0; padding: 10px; border-right: 1px solid var(--pi-border); background: var(--pi-surface); overflow: auto; }
2487
+ .settings-nav button { display: grid; gap: 2px; width: 100%; margin: 0 0 6px; text-align: left; border-color: transparent; background: transparent; }
2488
+ .settings-nav button:hover, .settings-nav button:focus { background: var(--pi-surface-hover); }
2489
+ .settings-nav button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
2490
+ .settings-nav small { color: var(--pi-muted); }
2491
+ .settings-content { min-width: 0; min-height: 0; overflow: auto; padding: 18px; }
2492
+
2493
+ @media (max-width: 760px) {
2494
+ .backdrop { padding: 0; place-items: stretch; }
2495
+ .settings-shell { width: 100%; height: 100dvh; max-height: none; min-height: 0; border: 0; border-radius: 0; }
2496
+ .settings-header { padding: max(12px, env(safe-area-inset-top)) 12px 12px; }
2497
+ .settings-body { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
2498
+ .settings-nav { display: flex; gap: 8px; padding: 8px; border-right: 0; border-bottom: 1px solid var(--pi-border); overflow-x: auto; overflow-y: hidden; }
2499
+ .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
2500
+ .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
2501
+ }
2502
+ `;F([d({attribute:!1})],L.prototype,"section",2);F([d({attribute:!1})],L.prototype,"actions",2);F([d({attribute:!1})],L.prototype,"machine",2);F([d({attribute:!1})],L.prototype,"machineRuntime",2);F([d({attribute:!1})],L.prototype,"onNavigate",2);F([d({attribute:!1})],L.prototype,"onClose",2);F([d({attribute:!1})],L.prototype,"onConfigSaved",2);F([v()],L.prototype,"configResponse",2);F([v()],L.prototype,"accessConfigResponse",2);F([v()],L.prototype,"sessiondConfigResponse",2);F([v()],L.prototype,"pluginsResponse",2);F([v()],L.prototype,"selectedPluginConfigResponse",2);F([v()],L.prototype,"selectedPluginsResponse",2);F([v()],L.prototype,"packagesResponse",2);F([v()],L.prototype,"loading",2);F([v()],L.prototype,"accessLoading",2);F([v()],L.prototype,"sessiondLoading",2);F([v()],L.prototype,"pluginLoading",2);F([v()],L.prototype,"packageLoading",2);F([v()],L.prototype,"saving",2);F([v()],L.prototype,"packageOperation",2);F([v()],L.prototype,"error",2);F([v()],L.prototype,"accessError",2);F([v()],L.prototype,"sessiondError",2);F([v()],L.prototype,"pluginError",2);F([v()],L.prototype,"packageError",2);F([v()],L.prototype,"savedMessage",2);F([v()],L.prototype,"packageMessage",2);L=F([E("settings-dialog")],L);var HS=Object.defineProperty,KS=Object.getOwnPropertyDescriptor,Ne=(e,t,i,s)=>{for(var r=s>1?void 0:s?KS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&HS(t,i,r),r};let xe=class extends I{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"Select a workspace",body:"Choose a workspace to inspect files, Git, or terminals."});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"Workspace tools unavailable",body:"Try selecting the workspace again."});const i=this.panels,s=i.find(r=>r.id===this.tool)??i[0];return l`
2503
+ ${this.hideToolTabs?null:l`
2504
+ <header>
2505
+ <div class=${this.workspaceHeaderFrameClass()}>
2506
+ <div class="workspace-header-strip" @scroll=${this.onWorkspaceHeaderScroll}>
2507
+ <div class="tabs">
2508
+ ${i.map(r=>{const o=s?.id===r.id,n=r.badge?.(t),a=this.panelTabAriaLabel(r,n);return l`
2509
+ <button class=${this.panelTabClass(r,o)} title=${a} aria-label=${a} aria-pressed=${String(o)} @click=${()=>{this.onSelectTool(r.id)}}>
2510
+ ${this.renderPanelTabContent(r,n)}
2511
+ </button>
2512
+ `})}
2513
+ </div>
2514
+ </div>
2515
+ </div>
2516
+ </header>
2517
+ `}
2518
+ ${s===void 0?this.renderEmptyState({title:"No workspace tools available",body:"No tools are available for this workspace."}):l`
2519
+ <div class="panel-content">
2520
+ ${s.render(t)}
2521
+ </div>
2522
+ `}
2523
+ `}panelTabClass(e,t){return[...e.icon===void 0?[]:["icon-tab"],...t?["selected"]:[]].join(" ")}panelTabAriaLabel(e,t){if(typeof t!="string"&&typeof t!="number")return e.title;const i=String(t).trim();return i===""?e.title:`${e.title}, ${i}`}renderPanelTabContent(e,t){return l`
2524
+ ${e.icon===void 0?null:l`<span class="tab-custom-icon" aria-hidden="true">${e.icon}</span>`}
2525
+ <span class="tab-label">${e.title}</span>
2526
+ ${this.isEmptyBadge(t)?null:l`<span class="tab-badge">${t}</span>`}
2527
+ `}isEmptyBadge(e){return e===void 0||e===""}renderEmptyState(e){return l`
2528
+ <section class="empty-state" role="status">
2529
+ <h2>${e.title}</h2>
2530
+ ${e.body===void 0?null:l`<p>${e.body}</p>`}
2531
+ </section>
2532
+ `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){const e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};xe.styles=Kr;Ne([d({attribute:!1})],xe.prototype,"workspace",2);Ne([d({attribute:!1})],xe.prototype,"panelContext",2);Ne([d({attribute:!1})],xe.prototype,"emptyState",2);Ne([d()],xe.prototype,"tool",2);Ne([d({attribute:!1})],xe.prototype,"panels",2);Ne([d({type:Boolean})],xe.prototype,"hideToolTabs",2);Ne([d({attribute:!1})],xe.prototype,"onSelectTool",2);Ne([K(".workspace-header-strip")],xe.prototype,"workspaceHeaderStrip",2);Ne([v()],xe.prototype,"workspaceHeaderCanScrollLeft",2);Ne([v()],xe.prototype,"workspaceHeaderCanScrollRight",2);xe=Ne([E("workspace-panel")],xe);var VS=Object.defineProperty,GS=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var r=s>1?void 0:s?GS(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&VS(t,i,r),r};let ve=class extends I{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=QS(this.machines),t=JS(this.machine),i=XS(this.project),s=e0(this.workspace),r=i0(this.session);return l`
2533
+ <nav class=${this.contextBarClass()} aria-label="Current location">
2534
+ <span class="context-bar-label">Location</span>
2535
+ <ol class="context-items" @scroll=${this.onContextScroll}>
2536
+ ${e?l`
2537
+ <li class="context-item">
2538
+ <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${ZS(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.("machines")}}>
2539
+ <span class="context-kind">Machine</span>
2540
+ <span class="context-value">${t}</span>
2541
+ </button>
2542
+ </li>
2543
+ `:null}
2544
+ <li class="context-item">
2545
+ <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${YS(this.project)} aria-label=${`Project: ${i}. Open project selection.`} @click=${()=>{this.onOpenSection?.("projects")}}>
2546
+ <span class="context-kind">Project</span>
2547
+ <span class="context-value">${i}</span>
2548
+ </button>
2549
+ </li>
2550
+ <li class="context-item">
2551
+ <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${t0(this.workspace)} aria-label=${`Workspace: ${s}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
2552
+ <span class="context-kind">Workspace</span>
2553
+ <span class="context-value">${s}</span>
2554
+ </button>
2555
+ </li>
2556
+ <li class="context-item">
2557
+ <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${s0(this.session)} aria-label=${`Session: ${r}. Open session selection.`} @click=${()=>{this.onOpenSection?.("sessions")}}>
2558
+ <span class="context-kind">Session</span>
2559
+ <span class="context-value">${r}</span>
2560
+ </button>
2561
+ </li>
2562
+ </ol>
2563
+ ${this.hasContextActions()?l`<div class="context-actions">${this.renderActionsButton()}${this.refreshControl}</div>`:null}
2564
+ </nav>
2565
+ `}renderActionsButton(){return this.onShowActions===void 0?null:l`
2566
+ <button type="button" class="context-action-button" title="Show Actions" aria-label="Show Actions" @click=${e=>{e.stopPropagation(),this.onShowActions?.()}}>
2567
+ <svg class="context-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2568
+ <path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
2569
+ </svg>
2570
+ </button>
2571
+ `}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};ve.styles=D`
2572
+ /* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
2573
+ :host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
2574
+ .context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: flex; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
2575
+ .context-bar::before, .context-bar::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
2576
+ .context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
2577
+ .context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
2578
+ .context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
2579
+ .context-bar-label { display: none; }
2580
+ .context-items { flex: 1 1 auto; min-width: 0; display: flex; align-items: stretch; gap: 5px; margin: 0; padding: 0 8px; list-style: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scroll-padding-inline: 8px; scrollbar-width: thin; }
2581
+ .context-bar.has-context-actions .context-items { padding-right: 58px; scroll-padding-inline: 8px 58px; }
2582
+ .context-bar.has-context-actions-double .context-items { padding-right: 102px; scroll-padding-inline: 8px 102px; }
2583
+ .context-item { flex: 0 0 auto; min-width: 0; display: flex; }
2584
+ .context-actions { position: absolute; top: 6px; right: 0; bottom: 6px; z-index: 3; display: flex; align-items: center; gap: 6px; padding: 0 8px; background: var(--pi-bg); pointer-events: none; }
2585
+ .context-actions::before { content: ""; position: absolute; top: 0; bottom: 0; left: -24px; z-index: 0; width: 24px; background: linear-gradient(90deg, transparent, var(--pi-bg)); pointer-events: none; }
2586
+ app-refresh-control, .context-action-button { position: relative; z-index: 1; pointer-events: auto; }
2587
+ .context-action-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 0; line-height: 1; }
2588
+ .context-action-button:hover, .context-action-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
2589
+ .context-action-icon { width: 18px; height: 18px; fill: currentColor; pointer-events: none; }
2590
+ .context-chip { flex: 0 0 auto; min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 8px; font: inherit; text-align: left; }
2591
+ .context-chip:hover { background: var(--pi-surface-hover); }
2592
+ .context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
2593
+ .context-chip.empty { border-style: dashed; color: var(--pi-muted); }
2594
+ .context-kind { display: none; }
2595
+ .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
2596
+ button { cursor: pointer; }
2597
+ `;De([d({attribute:!1})],ve.prototype,"machines",2);De([d({attribute:!1})],ve.prototype,"machine",2);De([d({attribute:!1})],ve.prototype,"project",2);De([d({attribute:!1})],ve.prototype,"workspace",2);De([d({attribute:!1})],ve.prototype,"session",2);De([d({attribute:!1})],ve.prototype,"refreshControl",2);De([d({attribute:!1})],ve.prototype,"onOpenSection",2);De([d({attribute:!1})],ve.prototype,"onShowActions",2);De([K(".context-items")],ve.prototype,"contextItems",2);De([v()],ve.prototype,"canScrollLeft",2);De([v()],ve.prototype,"canScrollRight",2);ve=De([E("app-context-bar")],ve);function QS(e){return e.length>1}function JS(e){return e===void 0?"No machine":`${e.name}${e.kind==="remote"?" · remote":""}`}function ZS(e){return e===void 0?"No machine selected":e.baseUrl??e.name}function XS(e){return e?.name??"No project"}function YS(e){return e===void 0?"No project selected":`${e.name} — ${e.path}`}function e0(e){return e===void 0?"No workspace":`${e.label}${e.isMain?" · main":""} · ${e.path}`}function t0(e){return e===void 0?"No workspace selected":`${e.label}${e.isMain?" · main":""} — ${e.path}`}function i0(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e===void 0?"No session":jl(e.id)}function s0(e){return e===void 0?"No session selected":e.path}var r0=Object.defineProperty,o0=Object.getOwnPropertyDescriptor,$t=(e,t,i,s)=>{for(var r=s>1?void 0:s?o0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&r0(t,i,r),r};let Ye=class extends I{constructor(){super(...arguments),this.tabs=[],this.selectedView="chat",this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){const e=this.fallbackLabels();return l`
2598
+ <div class=${this.frameClass()}>
2599
+ <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
2600
+ ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
2601
+ <button class=${this.tabClass(t)} title=${t.label} aria-label=${this.tabAriaLabel(t)} aria-pressed=${String(i)} @click=${()=>{this.onSelect?.(t.id)}}>
2602
+ ${this.renderTabMark(t,e)}
2603
+ <span class="tab-label">${t.label}</span>
2604
+ ${this.isEmptyBadge(t.badge)?null:l`<span class="tab-badge">${t.badge}</span>`}
2605
+ </button>
2606
+ `})}
2607
+ </div>
2608
+ </div>
2609
+ `}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:fg(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const r=this.initialsLabel(s.label);t.set(r,(t.get(r)??0)+1)}const i=new Map;for(const s of e){const r=this.initialsLabel(s.label);i.set(s.id,(t.get(r)??0)>1?this.fullFallbackLabel(s.label):r)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};Ye.styles=D`
2610
+ :host { flex: 0 0 auto; min-width: 0; }
2611
+ .mobile-tabs-frame { position: relative; display: flex; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
2612
+ .mobile-tabs-frame::before, .mobile-tabs-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
2613
+ .mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
2614
+ .mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
2615
+ .mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
2616
+ .mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
2617
+ .mobile-tabs button { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
2618
+ .mobile-tabs .navigation-tab { display: none; }
2619
+ .mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
2620
+ .tab-icon { flex: 0 0 auto; width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2621
+ .tab-custom-icon { flex: 0 0 auto; width: 18px; height: 18px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
2622
+ .tab-custom-icon svg { width: 18px; height: 18px; pointer-events: none; }
2623
+ .tab-fallback { display: none; font-weight: 650; letter-spacing: .01em; pointer-events: none; }
2624
+ .tab-label { min-width: 0; }
2625
+ .tab-badge { flex: 0 0 auto; display: inline-block; min-width: 14px; margin-left: 0; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
2626
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2627
+ @media (max-width: 760px) {
2628
+ .mobile-tabs { gap: 4px; padding: 6px 8px; }
2629
+ .mobile-tabs button { min-width: 40px; height: 36px; justify-content: center; gap: 4px; padding: 0 8px; }
2630
+ .mobile-tabs .navigation-tab { display: inline-flex; }
2631
+ .tab-fallback { display: inline-block; }
2632
+ .tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
2633
+ .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
2634
+ }
2635
+ `;$t([d({attribute:!1})],Ye.prototype,"tabs",2);$t([d({attribute:!1})],Ye.prototype,"selectedView",2);$t([d({attribute:!1})],Ye.prototype,"onSelect",2);$t([K(".mobile-tabs")],Ye.prototype,"mobileTabs",2);$t([v()],Ye.prototype,"canScrollLeft",2);$t([v()],Ye.prototype,"canScrollRight",2);Ye=$t([E("app-mobile-main-tabs")],Ye);var n0=Object.defineProperty,a0=Object.getOwnPropertyDescriptor,$e=(e,t,i,s)=>{for(var r=s>1?void 0:s?a0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&n0(t,i,r),r};let he=class extends I{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=er(e,this.statuses),i=e.name;return l`
2636
+ <div class="machine-switcher">
2637
+ <button
2638
+ type="button"
2639
+ class="machine-switcher-button"
2640
+ title=${va(e)}
2641
+ aria-label=${`Machine: ${i}. Switch machine.`}
2642
+ aria-expanded=${String(this.open)}
2643
+ @click=${s=>{this.toggleMenu(s.currentTarget)}}
2644
+ @keydown=${s=>{this.handleSwitcherButtonKeydown(s)}}
2645
+ >
2646
+ ${this.renderActivity(e)}
2647
+ <span class="machine-switcher-text">
2648
+ <span class="machine-switcher-kicker">Machine</span>
2649
+ <span class="machine-switcher-label">${i}</span>
2650
+ </span>
2651
+ <span class=${`machine-status ${t}`}>${ma(t)}</span>
2652
+ <span class="machine-chevron" aria-hidden="true">▾</span>
2653
+ </button>
2654
+ ${this.open?l`
2655
+ <div class="machine-switcher-menu" style=${this.menuStyle} @click=${s=>{s.stopPropagation()}}>
2656
+ ${this.machines.map(s=>this.renderMachineOption(s))}
2657
+ </div>
2658
+ `:null}
2659
+ </div>
2660
+ `}renderMachineOption(e){const t=this.selected?.id===e.id,i=er(e,this.statuses),s=_l(e)&&this.onRemove!==void 0,r=this.openActionsMachineId===e.id;return l`
2661
+ <div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
2662
+ <button
2663
+ type="button"
2664
+ class="machine-option-main"
2665
+ title=${va(e)}
2666
+ data-machine-id=${e.id}
2667
+ @click=${()=>{this.select(e)}}
2668
+ @keydown=${o=>{this.handleMachineOptionKeydown(o)}}
2669
+ >
2670
+ <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
2671
+ <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${ma(i)}</small>
2672
+ </button>
2673
+ ${s?l`
2674
+ <div class="machine-option-actions">
2675
+ <button
2676
+ type="button"
2677
+ class="machine-option-actions-toggle"
2678
+ title="Machine actions"
2679
+ aria-label=${`Actions for ${e.name}`}
2680
+ aria-expanded=${String(r)}
2681
+ @click=${o=>{o.stopPropagation(),this.toggleActionsMenu(e.id,o.currentTarget)}}
2682
+ >⋯</button>
2683
+ ${r?l`
2684
+ <div class="machine-option-actions-panel" style=${this.actionMenuStyle} @click=${o=>{o.stopPropagation()}}>
2685
+ <button class="danger" title=${`Remove ${e.name}`} @click=${()=>{this.removeMachine(e)}}>Remove</button>
2686
+ </div>
2687
+ `:null}
2688
+ </div>
2689
+ `:null}
2690
+ </div>
2691
+ `}renderActivity(e){const t=er(e,this.statuses);if(t==="offline"||t==="error")return;const i=Tl(this.activities[e.id]);return Dl(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}switcherButton(){return this.renderRoot.querySelector(".machine-switcher-button")}handleSwitcherButtonKeydown(e){if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key==="Escape"&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key==="ArrowUp"){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key==="ArrowDown"){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key==="Home"){this.focusIndexedMachineOption(0,e);return}if(e.key==="End"){this.focusIndexedMachineOption(-1,e);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key==="ArrowLeft"||e.key==="Escape")&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=ba(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){const e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=ba(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const r=s.indexOf(e);r<0||this.focusMachineOptionAt(r+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=vi(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};he.styles=D`
2692
+ :host { min-width: 0; display: block; }
2693
+ .machine-switcher { min-width: 0; }
2694
+ .machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
2695
+ .machine-switcher-button:hover, .machine-switcher-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
2696
+ .machine-switcher-text { flex: 1 1 auto; min-width: 0; display: grid; gap: 1px; }
2697
+ .machine-switcher-kicker { color: var(--pi-muted); font-size: 10px; line-height: 1; text-transform: uppercase; letter-spacing: .02em; }
2698
+ .machine-switcher-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 600; line-height: 1.2; }
2699
+ .machine-status { flex: 0 0 auto; color: var(--pi-muted); font-size: 11px; }
2700
+ .machine-status.online { color: var(--pi-success); }
2701
+ .machine-status.offline, .machine-status.error { color: var(--pi-danger); }
2702
+ .machine-chevron { flex: 0 0 auto; color: var(--pi-muted); font-size: 11px; }
2703
+ .activity-indicator { flex: 0 0 auto; display: inline-block; width: 7px; height: 7px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; }
2704
+ .activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
2705
+ .activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
2706
+ .activity-indicator.sending { border-radius: 50%; background: var(--pi-warning); }
2707
+ .machine-switcher-menu { position: fixed; z-index: 10000; box-sizing: border-box; min-width: min(280px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); }
2708
+ .machine-option { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px; align-items: stretch; margin: 2px 0; }
2709
+ .machine-option.no-actions { grid-template-columns: minmax(0, 1fr); }
2710
+ .machine-option-main, .machine-option-actions-toggle, .machine-option-actions-panel button { border: 0; border-radius: 7px; background: transparent; color: var(--pi-text); cursor: pointer; }
2711
+ .machine-option-main { min-width: 0; display: grid; gap: 2px; padding: 7px 8px; text-align: left; }
2712
+ .machine-option-name { min-width: 0; display: flex; align-items: baseline; gap: 6px; }
2713
+ .machine-option-name span:last-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2714
+ .machine-option-main small { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-muted); }
2715
+ .machine-option-actions { position: relative; align-self: stretch; }
2716
+ .machine-option-actions-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); }
2717
+ .machine-option-actions-panel { position: fixed; z-index: 10001; box-sizing: border-box; min-width: min(120px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); }
2718
+ .machine-option-actions-panel button { display: block; width: 100%; padding: 7px 9px; text-align: left; white-space: nowrap; }
2719
+ .machine-option-actions-panel button.danger { color: var(--pi-danger); }
2720
+ .machine-option-main:hover, .machine-option-main:focus-visible, .machine-option-actions-toggle:hover, .machine-option-actions-toggle:focus-visible, .machine-option.selected .machine-option-main { background: var(--pi-selection-bg); }
2721
+ .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
2722
+ .machine-option-actions-panel button.danger:hover, .machine-option-actions-panel button.danger:focus-visible { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
2723
+ @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
2724
+ `;$e([d({attribute:!1})],he.prototype,"machines",2);$e([d({attribute:!1})],he.prototype,"selected",2);$e([d({attribute:!1})],he.prototype,"statuses",2);$e([d({attribute:!1})],he.prototype,"activities",2);$e([d({attribute:!1})],he.prototype,"onSelect",2);$e([d({attribute:!1})],he.prototype,"onRemove",2);$e([d({attribute:!1})],he.prototype,"onFocusNextSection",2);$e([d({attribute:!1})],he.prototype,"onCancelKeyboardNavigation",2);$e([v()],he.prototype,"open",2);$e([v()],he.prototype,"menuStyle",2);$e([v()],he.prototype,"openActionsMachineId",2);$e([v()],he.prototype,"actionMenuStyle",2);he=$e([E("machine-switcher")],he);function er(e,t){return t[e.id]?.status??e.status??"unknown"}function ma(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function va(e){return e.baseUrl??e.name}function ba(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),r=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),o=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${Ti(t.bottom)};`,`left: ${Ti(r)};`,`width: ${Ti(s)};`,`max-height: ${Ti(o)};`].join(" ")}function Ti(e){return`${String(Math.round(e))}px`}var l0=Object.defineProperty,c0=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var r=s>1?void 0:s?c0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&l0(t,i,r),r};let x=class extends I{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Omp-Web on this machine to delete archived sessions.",this.cleanupUnavailableMessage="Update and restart Omp-Web on this machine to clean up sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
2725
+ <header>
2726
+ <strong>OMP Web</strong>
2727
+ ${ps(this.machines)?l`
2728
+ <machine-switcher
2729
+ .machines=${this.machines}
2730
+ .selected=${this.selectedMachine}
2731
+ .statuses=${this.machineStatuses}
2732
+ .activities=${this.machineActivities}
2733
+ .onSelect=${e=>this.onSelectMachine?.(e)}
2734
+ .onRemove=${e=>this.onRemoveMachine?.(e)}
2735
+ .onFocusNextSection=${()=>{this.focusNextFrom("machines")}}
2736
+ .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2737
+ ></machine-switcher>
2738
+ `:null}
2739
+ <div class="header-actions">
2740
+ ${this.refreshControl}
2741
+ <button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
2742
+ </div>
2743
+ </header>
2744
+ ${this.compact&&ps(this.machines)?l`
2745
+ <machine-list
2746
+ .machines=${this.machines}
2747
+ .selected=${this.selectedMachine}
2748
+ .statuses=${this.machineStatuses}
2749
+ .activities=${this.machineActivities}
2750
+ .collapsible=${this.collapsible}
2751
+ .collapsed=${this.machinesCollapsed}
2752
+ .onToggleCollapsed=${()=>{this.onToggleMachines?.()}}
2753
+ .onSelect=${e=>this.onSelectMachine?.(e)}
2754
+ .onRemove=${e=>this.onRemoveMachine?.(e)}
2755
+ .onFocusNextSection=${()=>{this.focusNextFrom("machines")}}
2756
+ .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2757
+ ></machine-list>
2758
+ `:null}
2759
+ <project-list
2760
+ .projects=${this.projects}
2761
+ .selected=${this.selectedProject}
2762
+ .activities=${this.workspaceActivities}
2763
+ .workspacesByProjectId=${this.workspacesByProjectId}
2764
+ .collapsible=${this.collapsible}
2765
+ .collapsed=${this.projectsCollapsed}
2766
+ .onToggleCollapsed=${()=>{this.onToggleProjects?.()}}
2767
+ .onSelect=${e=>this.onSelectProject?.(e)}
2768
+ .onClose=${e=>this.onCloseProject?.(e)}
2769
+ .onFocusPreviousSection=${()=>{this.focusPreviousFrom("projects")}}
2770
+ .onFocusNextSection=${()=>{this.focusNextFrom("projects")}}
2771
+ .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2772
+ ></project-list>
2773
+ <workspace-list
2774
+ .workspaces=${this.workspaces}
2775
+ .selected=${this.selectedWorkspace}
2776
+ .activities=${this.workspaceActivities}
2777
+ .deletingWorkspaceIds=${this.deletingWorkspaceIds}
2778
+ .collapsible=${this.collapsible}
2779
+ .collapsed=${this.workspacesCollapsed}
2780
+ .workspaceLabelItems=${this.workspaceLabelItems}
2781
+ .onToggleCollapsed=${()=>{this.onToggleWorkspaces?.()}}
2782
+ .onSelect=${e=>this.onSelectWorkspace?.(e)}
2783
+ .onDelete=${e=>this.onDeleteWorkspace?.(e)}
2784
+ .onFocusPreviousSection=${()=>{this.focusPreviousFrom("workspaces")}}
2785
+ .onFocusNextSection=${()=>{this.focusNextFrom("workspaces")}}
2786
+ .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2787
+ ></workspace-list>
2788
+ <session-list
2789
+ .sessions=${this.sessions}
2790
+ .statuses=${this.sessionStatuses}
2791
+ .activities=${this.sessionActivities}
2792
+ .sending=${this.sendingPrompts}
2793
+ .selected=${this.selectedSession}
2794
+ .startingCount=${this.startingSessionCount}
2795
+ .canStart=${this.canStartSession}
2796
+ .canDeleteArchived=${this.canDeleteArchivedSessions}
2797
+ .canReload=${this.canReloadSessions}
2798
+ .canCleanup=${this.canCleanupSessions}
2799
+ .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage}
2800
+ .cleanupUnavailableMessage=${this.cleanupUnavailableMessage}
2801
+ .collapsible=${this.collapsible}
2802
+ .collapsed=${this.sessionsCollapsed}
2803
+ .onToggleCollapsed=${()=>{this.onToggleSessions?.()}}
2804
+ .onArchivedCollapsed=${()=>this.onArchivedCollapsed?.()}
2805
+ .onStart=${()=>this.onStartSession?.()}
2806
+ .onSelect=${e=>this.onSelectSession?.(e)}
2807
+ .onArchive=${e=>this.onArchiveSession?.(e)}
2808
+ .onArchiveWithDescendants=${e=>this.onArchiveSessionWithDescendants?.(e)}
2809
+ .onArchiveMany=${e=>this.onArchiveSessions?.(e)}
2810
+ .onRestore=${e=>this.onRestoreSession?.(e)}
2811
+ .onDelete=${e=>this.onDeleteCachedNewSession?.(e)}
2812
+ .onDeleteArchived=${e=>this.onDeleteArchivedSession?.(e)}
2813
+ .onDeleteArchivedMany=${e=>this.onDeleteArchivedSessions?.(e)}
2814
+ .onDetachParent=${e=>this.onDetachParentSession?.(e)}
2815
+ .onReload=${e=>this.onReloadSession?.(e)}
2816
+ .onCleanup=${()=>this.onCleanupSessions?.()}
2817
+ .onFocusPreviousSection=${()=>{this.focusPreviousFrom("sessions")}}
2818
+ .onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
2819
+ .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2820
+ ></session-list>
2821
+ `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=d0(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(p0(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=D`
2822
+ :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
2823
+ :host([compact]) { flex: 1 1 auto; }
2824
+ header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
2825
+ header strong { flex: 0 0 auto; }
2826
+ machine-switcher { flex: 1 1 auto; min-width: 0; }
2827
+ :host([compact]) header { display: none; }
2828
+ .header-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; }
2829
+ machine-list, project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
2830
+ session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
2831
+ machine-list[collapsed],
2832
+ project-list[collapsed],
2833
+ workspace-list[collapsed],
2834
+ session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
2835
+ :host([compact]) machine-list,
2836
+ :host([compact]) project-list,
2837
+ :host([compact]) workspace-list,
2838
+ :host([compact]) session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
2839
+ :host([compact]) machine-list[collapsed],
2840
+ :host([compact]) project-list[collapsed],
2841
+ :host([compact]) workspace-list[collapsed],
2842
+ :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
2843
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2844
+ `;k([d({attribute:!1})],x.prototype,"machines",2);k([d({attribute:!1})],x.prototype,"selectedMachine",2);k([d({attribute:!1})],x.prototype,"machineStatuses",2);k([d({attribute:!1})],x.prototype,"machineActivities",2);k([d({attribute:!1})],x.prototype,"projects",2);k([d({attribute:!1})],x.prototype,"selectedProject",2);k([d({attribute:!1})],x.prototype,"workspaces",2);k([d({attribute:!1})],x.prototype,"selectedWorkspace",2);k([d({attribute:!1})],x.prototype,"sessions",2);k([d({attribute:!1})],x.prototype,"selectedSession",2);k([d({attribute:!1})],x.prototype,"workspaceActivities",2);k([d({attribute:!1})],x.prototype,"sessionActivities",2);k([d({attribute:!1})],x.prototype,"sessionStatuses",2);k([d({attribute:!1})],x.prototype,"sendingPrompts",2);k([d({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],x.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([d({type:Boolean})],x.prototype,"machinesCollapsed",2);k([d({type:Boolean})],x.prototype,"projectsCollapsed",2);k([d({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([d({type:Number})],x.prototype,"startingSessionCount",2);k([d({type:Boolean})],x.prototype,"canStartSession",2);k([d({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],x.prototype,"canReloadSessions",2);k([d({type:Boolean})],x.prototype,"canCleanupSessions",2);k([d({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([d({type:String})],x.prototype,"cleanupUnavailableMessage",2);k([d({attribute:!1})],x.prototype,"onShowActions",2);k([d({attribute:!1})],x.prototype,"onToggleMachines",2);k([d({attribute:!1})],x.prototype,"onToggleProjects",2);k([d({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],x.prototype,"onToggleSessions",2);k([d({attribute:!1})],x.prototype,"onSelectProject",2);k([d({attribute:!1})],x.prototype,"onCloseProject",2);k([d({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],x.prototype,"onStartSession",2);k([d({attribute:!1})],x.prototype,"onSelectSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],x.prototype,"onArchiveSessions",2);k([d({attribute:!1})],x.prototype,"onRestoreSession",2);k([d({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],x.prototype,"onDetachParentSession",2);k([d({attribute:!1})],x.prototype,"onReloadSession",2);k([d({attribute:!1})],x.prototype,"onCleanupSessions",2);k([d({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],x.prototype,"onSelectMachine",2);k([d({attribute:!1})],x.prototype,"onRemoveMachine",2);k([d({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([K("machine-list")],x.prototype,"machineList",2);k([K("machine-switcher")],x.prototype,"machineSwitcher",2);k([K("project-list")],x.prototype,"projectList",2);k([K("workspace-list")],x.prototype,"workspaceList",2);k([K("session-list")],x.prototype,"sessionList",2);x=k([E("app-navigation-panel")],x);function ps(e){return e.length>1}function d0(e,t){const i=gc(t);return i[i.indexOf(e)-1]}function p0(e,t){const i=gc(t);return i[i.indexOf(e)+1]??"chat"}function gc(e){return ss.filter(t=>t!=="machines"||ps(e))}var h0=Object.defineProperty,u0=Object.getOwnPropertyDescriptor,de=(e,t,i,s)=>{for(var r=s>1?void 0:s?u0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&h0(t,i,r),r};const f0=new Set(["ArrowLeft","ArrowRight","Home","End"]),g0=420,m0=4;let X=class extends I{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="Resize panel",this.expandLabel="Expand panel",this.collapseLabel="Collapse panel",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
2845
+ ${this.renderResizeHandle()}
2846
+ <button
2847
+ type="button"
2848
+ class="edge-button"
2849
+ title=${e}
2850
+ aria-label=${e}
2851
+ aria-controls=${this.controls}
2852
+ aria-expanded=${String(!this.collapsed)}
2853
+ @click=${()=>{this.onToggle?.()}}
2854
+ >${this.renderIcon()}</button>
2855
+ `}renderResizeHandle(){if(!this.resizable)return N;const e=this.resizeConstraints();return l`
2856
+ <div
2857
+ class="resize-handle"
2858
+ role="separator"
2859
+ tabindex="0"
2860
+ aria-label=${this.resizeLabel}
2861
+ title=${`${this.resizeLabel}. Double-click or double-tap to reset.`}
2862
+ aria-controls=${this.controls}
2863
+ aria-orientation="vertical"
2864
+ aria-valuemin=${String(e.minWidth)}
2865
+ aria-valuemax=${String(e.maxWidth)}
2866
+ aria-valuenow=${this.resizeAriaValueNow()}
2867
+ @pointerdown=${t=>{this.onResizePointerDown(t)}}
2868
+ @pointermove=${t=>{this.onResizePointerMove(t)}}
2869
+ @pointerup=${t=>{this.onResizePointerUp(t)}}
2870
+ @pointercancel=${t=>{this.onResizePointerCancel(t)}}
2871
+ @dblclick=${t=>{this.onResizeDoubleClick(t)}}
2872
+ @keydown=${t=>{this.onResizeKeyDown(t)}}
2873
+ ></div>
2874
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?N:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=m0)&&(t.moved=!0,this.commitPanelWidth(zm(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!f0.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=qm(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});i!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(i),this.onResizeEnd?.())}registerTapForReset(){const e=Date.now();if(e-this.lastTapAt<=g0){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return Re(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(Re(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=mi(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};X.styles=D`
2875
+ :host { position: relative; min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
2876
+ :host([side="navigation"]) { grid-column: 2; }
2877
+ :host([side="workspace"]) { grid-column: 4; }
2878
+ .resize-handle { position: absolute; inset: 0 -6px; z-index: 0; cursor: col-resize; touch-action: none; outline: none; }
2879
+ .resize-handle::after { content: ""; position: absolute; top: 0; bottom: 0; left: 50%; width: 1px; transform: translateX(-50%); background: transparent; transition: width .12s ease, background .12s ease, opacity .12s ease; }
2880
+ .resize-handle:hover::after, .resize-handle:focus-visible::after, :host([resizing]) .resize-handle::after { width: 3px; background: var(--pi-accent); opacity: .72; }
2881
+ .edge-button { position: relative; z-index: 1; box-sizing: border-box; display: grid; place-items: center; width: 18px; height: 48px; padding: 0; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-bg); color: var(--pi-muted); opacity: .75; cursor: pointer; }
2882
+ .edge-button:hover, .edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
2883
+ :host([side="navigation"][collapsed]) .edge-button { transform: translateX(calc(50% - .5px)); }
2884
+ :host([side="workspace"][collapsed]) .edge-button { transform: translateX(calc(-50% + .5px)); }
2885
+ .edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2886
+ @media (max-width: 1180px) {
2887
+ :host([side="navigation"]) { grid-row: 1 / 3; }
2888
+ :host([side="workspace"]) { display: none; }
2889
+ }
2890
+ @media (max-width: 760px) {
2891
+ :host([side="navigation"]) { display: none; }
2892
+ }
2893
+ `;de([d({reflect:!0})],X.prototype,"side",2);de([d({type:Boolean,reflect:!0})],X.prototype,"collapsed",2);de([d({type:Boolean})],X.prototype,"resizable",2);de([d({type:Number})],X.prototype,"panelWidth",2);de([d({type:Number})],X.prototype,"minWidth",2);de([d({type:Number})],X.prototype,"maxWidth",2);de([d()],X.prototype,"controls",2);de([d()],X.prototype,"resizeLabel",2);de([d()],X.prototype,"expandLabel",2);de([d()],X.prototype,"collapseLabel",2);de([d({attribute:!1})],X.prototype,"onToggle",2);de([d({attribute:!1})],X.prototype,"onResizeStart",2);de([d({attribute:!1})],X.prototype,"onResize",2);de([d({attribute:!1})],X.prototype,"onResizeEnd",2);de([d({attribute:!1})],X.prototype,"onReset",2);X=de([E("app-panel-edge-control")],X);var v0=Object.defineProperty,b0=Object.getOwnPropertyDescriptor,mc=(e,t,i,s)=>{for(var r=s>1?void 0:s?b0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&v0(t,i,r),r};let hs=class extends I{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="Full page reload";return l`
2894
+ <button
2895
+ class="app-refresh-button"
2896
+ title=${e}
2897
+ aria-label=${e}
2898
+ @click=${this.onReloadClick}
2899
+ >${this.renderRefreshIcon()}</button>
2900
+ `}renderRefreshIcon(){return l`
2901
+ <svg class="app-refresh-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
2902
+ <path d="M20 6v5h-5"></path>
2903
+ <path d="M4 18v-5h5"></path>
2904
+ <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
2905
+ <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
2906
+ </svg>
2907
+ `}};hs.styles=D`
2908
+ :host { position: relative; z-index: 1; display: flex; align-items: center; pointer-events: auto; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
2909
+ :host, :host * { -webkit-user-select: none; user-select: none; }
2910
+ .app-refresh-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 0; line-height: 1; cursor: pointer; touch-action: manipulation; -webkit-touch-callout: none; }
2911
+ .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2912
+ `;mc([d({attribute:!1})],hs.prototype,"onReload",2);hs=mc([E("app-refresh-control")],hs);var w0=Object.defineProperty,y0=Object.getOwnPropertyDescriptor,Pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?y0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&w0(t,i,r),r};const S0=900*1e3,x0=750,kr=[1e3,3e3,8e3,15e3,3e4],wa={capture:!0},tr="auto:on",ya="auto:off",Ai="theme:",ir=hi("core:workspace.files"),sr=hi("core:workspace.git"),Ei=hi("core:workspace.terminal"),k0=320,$0=2,P0="(min-width: 1181px)";let ue=class extends I{constructor(){super(...arguments),this.state=oh(),this.sessions=new Ju(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new qu),this.activity=new nh(()=>this.state,e=>{this.setState(e)}),this.auth=new ch(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new uf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new pf),this.projects=new xh(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Sh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new vh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new yh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Cf,this.realtime=new rn,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new vf,this.terminalSelection=new $f,this.appShell=new Mm(this),this.panelCollapse=new jm(this),this.panelResize=new Nm(this),this.navigationSections=new Om(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=C0(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Hf()??Bf,this.activeThemeId=qr,this.isRefreshingApp=!1,this.settingsSection=Dn(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=jo(void 0),this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.scheduleOmpWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.scheduleOmpWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,wa),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.ompWebStatusTimer=window.setInterval(()=>{this.scheduleOmpWebStatusRefresh()},S0),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.scheduleOmpWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,wa),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.ompWebStatusTimer!==void 0&&window.clearInterval(this.ompWebStatusTimer),this.ompWebStatusTimer=void 0,this.clearScheduledOmpWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!I0(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),R0(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=En();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=this.state.machineStatuses[t.machineId??"local"];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}scheduleOmpWebStatusRefresh(e=x0){this.clearScheduledOmpWebStatusRefresh(),this.ompWebStatusDeferredTimer=window.setTimeout(()=>{this.ompWebStatusDeferredTimer=void 0,this.refreshOmpWebStatus()},e)}clearScheduledOmpWebStatusRefresh(){this.ompWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.ompWebStatusDeferredTimer),this.ompWebStatusDeferredTimer=void 0)}async refreshOmpWebStatus(){const e=g(this.state);try{const t=await Ka.ompWebStatus(e);g(this.state)===e&&this.setState({ompWebStatus:t})}catch(t){g(this.state)===e&&this.setState({ompWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=g(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[g(this.state)]:this.state.machines.filter(t=>vc(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await ze.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=jo(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.scheduleOmpWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(En(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=g(this.state),o=e.projectId===void 0||e.projectId===""?ka():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),g(this.state)!==r&&this.scheduleOmpWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?ka():{selectedFilePath:Ls(ir,"file"),selectedDiffPath:Ls(sr,"diff"),selectedTerminalId:Ls(Ei,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){zs(e,{replace:!0}),We(ir,"file",void 0,{replace:!0}),We(sr,"diff",void 0,{replace:!0}),We(Ei,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=A0(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==""){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=kr.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",o=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${o===void 0?"":` ${o}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(r=>r.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await rr(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),zs({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView==="navigation"?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(un(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(un(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){zs(fn(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){We(ir,"file",e.selectedFilePath,{replace:!0}),We(sr,"diff",e.selectedDiffPath,{replace:!0}),We(Ei,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??bf(e.id);if(await this.restoreRouteFor(fn(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=g(this.state)){const i=$a(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=sv(e,{api:{runTerminalCommand:(o,n)=>At.runTerminalCommand(o,n,t),listCommandRuns:o=>At.listCommandRuns(o,t),getCommandRun:o=>At.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}async openRuntimeTerminal(e,t,i){if((g(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),g(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){We(Ei,"terminal",e,t)}terminalWorkspaceKey(e){return`${g(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,qs(e)}closeSettings(){this.settingsSection=void 0,qs(void 0)}navigateSettings(e){this.settingsSection=e,qs(e)}restoreSettingsRoute(){this.settingsSection=Dn()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},g(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new rn;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=g(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>M0(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):T0(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=g(this.state);try{const i=await At.terminals(e.projectId,e.id,t);if(g(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=xa(e),s=xa(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({ompWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
2913
+ <workspace-panel
2914
+ id="workspace-panel"
2915
+ .workspace=${e}
2916
+ .panelContext=${t}
2917
+ .emptyState=${i}
2918
+ .tool=${this.state.workspaceTool}
2919
+ .panels=${this.visibleWorkspacePanels()}
2920
+ .onSelectTool=${s=>{this.openWorkspaceTool(s)}}
2921
+ ></workspace-panel>
2922
+ `}renderNavigationPanelEdgeControl(){const e=this.resizablePanelConstraints("navigation");return l`
2923
+ <app-panel-edge-control
2924
+ side="navigation"
2925
+ controls="navigation-panel"
2926
+ resizeLabel="Resize navigation panel"
2927
+ expandLabel="Expand navigation panel"
2928
+ collapseLabel="Collapse navigation panel"
2929
+ .collapsed=${this.panelCollapse.navigationPanelCollapsed}
2930
+ .resizable=${!this.appShell.isMobileNavigationLayout}
2931
+ .panelWidth=${this.panelResize.panelWidth("navigation")}
2932
+ .minWidth=${e.minWidth}
2933
+ .maxWidth=${e.maxWidth}
2934
+ .onToggle=${()=>{this.panelCollapse.toggleNavigationPanel()}}
2935
+ .onResizeStart=${()=>this.startPanelResize("navigation")}
2936
+ .onResize=${t=>{this.panelResize.resizePanel("navigation",t,{persist:!1})}}
2937
+ .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2938
+ .onReset=${()=>{this.resetResizablePanel("navigation")}}
2939
+ ></app-panel-edge-control>
2940
+ `}renderWorkspacePanelEdgeControl(){const e=this.resizablePanelConstraints("workspace");return l`
2941
+ <app-panel-edge-control
2942
+ side="workspace"
2943
+ controls="workspace-panel"
2944
+ resizeLabel="Resize workspace panel"
2945
+ expandLabel="Expand workspace panel"
2946
+ collapseLabel="Collapse workspace panel"
2947
+ .collapsed=${this.panelCollapse.workspacePanelCollapsed}
2948
+ .resizable=${!this.appShell.isMobileNavigationLayout}
2949
+ .panelWidth=${this.panelResize.panelWidth("workspace")}
2950
+ .minWidth=${e.minWidth}
2951
+ .maxWidth=${e.maxWidth}
2952
+ .onToggle=${()=>{this.panelCollapse.toggleWorkspacePanel()}}
2953
+ .onResizeStart=${()=>this.startPanelResize("workspace")}
2954
+ .onResize=${t=>{this.panelResize.resizePanel("workspace",t,{persist:!1})}}
2955
+ .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2956
+ .onReset=${()=>{this.resetResizablePanel("workspace")}}
2957
+ ></app-panel-edge-control>
2958
+ `}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),r=Math.floor(i-s-$0-k0);return Math.max(t.minWidth,Math.min(t.maxWidth,r))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(P0).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Fe(e,Ce.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Fe(e,Ce.sessionsReload)}canCleanupSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Fe(e,Ce.sessionsCleanup)}supportsWorkspaceFileSuggestions(e=g(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&Fe(t,Ce.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`Update and restart Omp-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return Uf(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[g(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:""}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}const t=g(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:"",preview:void 0,previewRequest:void 0,result:void 0};try{const i=await lr.cleanupPreview(e,t);if(g(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:i,previewRequest:e,result:void 0,loading:!1,error:""}}catch(i){g(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${q(i)}`})}}async runSessionCleanup(e){const t=this.sessionCleanupDialog;if(t?.preview===void 0||Lt(t.previewRequest)!==Lt(e)){this.sessionCleanupDialog={...t??{},error:"Preview cleanup before running it."};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}const i=g(this.state);this.sessionCleanupDialog={...t,running:!0,error:""};try{const s=await lr.cleanup(e,i);if(g(this.state)!==i)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:s,previewRequest:e,result:s,running:!1,error:""},await this.sessions.applySessionCleanupResult(s,i)}catch(s){g(this.state)===i&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${q(s)}`})}}renderNavigationPanel(){return l`
2959
+ <app-navigation-panel
2960
+ .machines=${this.state.machines}
2961
+ .selectedMachine=${this.state.selectedMachine}
2962
+ .machineStatuses=${this.state.machineStatuses}
2963
+ .machineActivities=${this.state.machineActivities}
2964
+ .machinesCollapsed=${this.navigationSections.isCollapsed("machines")}
2965
+ .onToggleMachines=${()=>{this.navigationSections.toggle("machines")}}
2966
+ .onSelectMachine=${e=>this.selectNavigationItem("machines","projects",()=>this.selectMachineWithMemory(e))}
2967
+ .onRemoveMachine=${e=>{this.removeMachine(e)}}
2968
+ .projects=${this.state.projects}
2969
+ .selectedProject=${this.state.selectedProject}
2970
+ .workspaceActivities=${this.state.workspaceActivities}
2971
+ .workspacesByProjectId=${this.state.workspacesByProjectId}
2972
+ .workspaces=${this.state.workspaces}
2973
+ .selectedWorkspace=${this.state.selectedWorkspace}
2974
+ .deletingWorkspaceIds=${og(this.state.workspaceDeletionRuns)}
2975
+ .sessions=${this.state.sessions}
2976
+ .sessionStatuses=${this.state.sessionStatuses}
2977
+ .sessionActivities=${this.state.sessionActivities}
2978
+ .sendingPrompts=${this.state.sendingPrompts}
2979
+ .selectedSession=${this.state.selectedSession}
2980
+ .startingSessionCount=${this.state.startingSessionCount}
2981
+ .canStartSession=${!!this.state.selectedWorkspace}
2982
+ .canDeleteArchivedSessions=${this.canDeleteArchivedSessions()}
2983
+ .canReloadSessions=${this.canReloadSessions()}
2984
+ .canCleanupSessions=${this.canCleanupSessions()}
2985
+ .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage()}
2986
+ .cleanupUnavailableMessage=${this.sessionCleanupUnavailableMessage()}
2987
+ .collapsible=${!0}
2988
+ .compact=${this.appShell.isMobileNavigationLayout}
2989
+ .projectsCollapsed=${this.navigationSections.isCollapsed("projects")}
2990
+ .workspacesCollapsed=${this.navigationSections.isCollapsed("workspaces")}
2991
+ .sessionsCollapsed=${this.navigationSections.isCollapsed("sessions")}
2992
+ .workspaceLabelItems=${e=>this.workspaceLabelItems(e)}
2993
+ .refreshControl=${this.appShell.shouldShowAppRefreshInHeader()?this.renderAppRefresh():void 0}
2994
+ .onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
2995
+ .onToggleProjects=${()=>{this.navigationSections.toggle("projects")}}
2996
+ .onToggleWorkspaces=${()=>{this.navigationSections.toggle("workspaces")}}
2997
+ .onToggleSessions=${()=>{this.navigationSections.toggle("sessions")}}
2998
+ .onSelectProject=${e=>this.selectNavigationItem("projects","workspaces",()=>this.workspaces.selectProject(e))}
2999
+ .onCloseProject=${e=>this.projects.closeProject(e.id)}
3000
+ .onSelectWorkspace=${e=>this.selectNavigationItem("workspaces","sessions",()=>this.workspaces.selectWorkspace(e))}
3001
+ .onDeleteWorkspace=${e=>{this.deleteWorkspace(e)}}
3002
+ .onArchivedCollapsed=${()=>{this.sessions.clearSelectionAfterArchivedCollapse()}}
3003
+ .onStartSession=${()=>this.startSessionFromNavigation()}
3004
+ .onSelectSession=${e=>this.selectNavigationItem("sessions","chat",()=>this.sessions.selectSession(e))}
3005
+ .onArchiveSession=${e=>this.sessions.archiveSession(e)}
3006
+ .onArchiveSessionWithDescendants=${e=>this.sessions.archiveSessionWithDescendants(e)}
3007
+ .onArchiveSessions=${e=>this.sessions.archiveSessions(e)}
3008
+ .onRestoreSession=${e=>this.selectNavigationItem("sessions","chat",()=>this.sessions.restoreSession(e))}
3009
+ .onDeleteCachedNewSession=${e=>this.sessions.deleteCachedNewSession(e)}
3010
+ .onDeleteArchivedSession=${e=>this.sessions.deleteArchivedSessions([e])}
3011
+ .onDeleteArchivedSessions=${e=>this.sessions.deleteArchivedSessions(e)}
3012
+ .onDetachParentSession=${e=>this.sessions.detachParent(e)}
3013
+ .onReloadSession=${e=>this.sessions.reloadSession(e)}
3014
+ .onCleanupSessions=${()=>{this.openSessionCleanupDialog()}}
3015
+ .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
3016
+ .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
3017
+ ></app-navigation-panel>
3018
+ `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,r=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},r),r()&&await this.focusNavigationTarget(t)}async startSessionFromNavigation(){const e=++this.navigationSelectionSeq,t=()=>e===this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection("sessions"),await this.startSessionAndOpenChat(t)}async startSessionAndOpenChat(e=()=>!0){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!ps(this.state.machines)){await this.focusNavigationSection("projects");return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView("navigation"),this.navigationSections.expand(e),await this.updateComplete,await rr(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await rr(),this.promptEditor?.focusInput()}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;if(e===void 0)return[];const t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(i=>i.visible?.(t)??!0)}workspacePanelEmptyState(){const e=this.state.selectedProject;return this.state.isLoadingProjects?{title:"Loading projects…",body:"Looking for projects you have added to PI WEB."}:e===void 0?this.state.projects.length===0?{title:"No projects yet",body:"Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace."}:{title:"Select a project",body:"Choose a project from the sidebar, then select a workspace to inspect files, Git, or terminals."}:this.state.isLoadingWorkspaces?{title:"Loading workspaces…",body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:"No workspaces found",body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:"Select a workspace",body:`Choose a workspace in ${e.name} to inspect files, Git, or terminals.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"Loading projects…":this.state.selectedWorkspace!==void 0?"Select or start a session.":this.state.selectedProject!==void 0?"Select a workspace to start a session.":this.state.projects.length===0?"Add a project to start a session.":"Select a project and workspace to start a session."}mobilePanelBadge(e){const t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case"core:workspace.files":return"files";case"core:workspace.git":return"git";case"core:workspace.terminal":return"terminal";case"core:workspace.tasks":return"tasks";default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){const t=Sa(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>Tt.workspaceFile(e.projectId,e.id,i,t),writeFile:async(i,s,r)=>{const o=await Tt.writeWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o},deleteFile:async i=>{const s=await Tt.deleteWorkspaceFile(e.projectId,e.id,i,t);return this.files.refreshFiles(),s},moveFile:async(i,s,r)=>{const o=await Tt.moveWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=Sa(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return mm({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),prompt:this.createPromptEditor(),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),ompWebUnstable:{terminalCommandRuns:o},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Vp(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:n=>{this.files.expandDir(n)},onSelectFile:n=>{this.files.selectFile(n)},onStartWorkspaceUpload:(n,a)=>this.files.startWorkspaceUpload(n,a),onCancelWorkspaceUpload:n=>{this.files.cancelWorkspaceUpload(n)},onClearWorkspaceUpload:n=>{this.files.clearWorkspaceUpload(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return tv(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:"app.sessions.cleanup",title:"Clean Up Sessions",description:"Preview and manually clean up idle or archived sessions on the selected machine",group:"Sessions",...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"Reset Navigation Panel Size",description:"Restore the navigation panel to its default width",group:"View",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"Reset Workspace Panel Size",description:"Restore the workspace panel to its default width",group:"View",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"Reset Panel Sizes",description:"Restore all side panels to their default widths",group:"View",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"Focus Machines",description:"Move keyboard focus to the machine selector",shortcut:"mod+g m",group:"Navigation",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"Focus Projects",description:"Move keyboard focus to the projects list",shortcut:"mod+g p",group:"Navigation",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"Focus Workspaces",description:"Move keyboard focus to the workspaces list",shortcut:"mod+g w",group:"Navigation",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"Focus Sessions",description:"Move keyboard focus to the sessions list",shortcut:"mod+g s",group:"Navigation",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>Rn())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>Rn(`/api/machines/${encodeURIComponent(e.id)}/omp-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(r){console.warn(`Failed to register PI WEB plugin ${s.id}`,r)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPromptEditor(){return{insertText:e=>{const t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();const i=t.state.selection.main;t.dispatch({changes:{from:i.from,to:i.to,insert:e},selection:{anchor:i.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??"",getSelection:()=>{const e=this.promptEditor?.view;if(!e)return null;const t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){const e=t=>gm({state:this.state,prompt:this.createPromptEditor(),ompWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!ff(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(yl(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
3019
+
3020
+ This will run git worktree remove and delete:
3021
+ ${e.path}
3022
+
3023
+ The Git branch will not be deleted.`))return;const s=g(this.state);try{const r=await Tt.deleteWorkspace(e.projectId,e.id,s);if(g(this.state)!==s)return;this.recordWorkspaceDeletionRun(r,s);const o=await this.workspaceForCommandRun(r);if(g(this.state)!==s)return;o!==void 0&&this.openRuntimeTerminal(s,o,{terminalId:r.terminalId})}catch(r){g(this.state)===s&&this.setState({error:`Failed to start workspace deletion: ${q(r)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(g(this.state)!==t)return;const i=ur(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=g(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{const i=await this.terminalCommandRunsForOrigin("core",e).listCommandRuns(sg(t.id));if(g(this.state)!==e)return;const s=rg(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))ts(r)||await this.handleCompletedWorkspaceDeletionRun(r,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(ts);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=g(this.state)){if(g(this.state)!==t)return;const i=$a(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=ur(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),g(this.state)!==t)return;this.setState({workspaceDeletionRuns:E0(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"Workspace deletion failed. See terminal output."}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:""})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.scheduleOmpWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`Remove ${e.name}?
3024
+
3025
+ This only removes it from this PI WEB gateway.`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const e=this.state.selectedMachine;e?.kind!=="remote"||e.baseUrl===void 0||window.open(e.baseUrl,"_blank","noopener,noreferrer")}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${i}`})})}async openModelDialog(){const e=await this.sessions.listModels(),t=this.state.status?.model?.provider,i=this.state.status?.model?.id;this.setState({modelDialog:{title:"Select Model",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const r=s.provider??"",o=s.id??"",n=r===t&&o===i;return{value:`${r}/${o}`,label:`${o}${n?" ✓ current":""}`,description:r}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?ya:tr;this.setState({themeDialog:{title:"Select Theme",selectedValue:i===void 0?s:`${Ai}${i}`,options:[{value:s,label:`Auto ${this.themePreference.auto?"✓ on":"off"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${Ai}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===tr||e===ya){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===tr},this.applyPreferredTheme(!0);return}if(!e.startsWith(Ai))return;const t=e.slice(Ai.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,Vf(t),e&&Kf(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Gf({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return wl(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?"Follow the system light/dark preference when the selected theme has a pair.":e.selectedThemePair===void 0?"On, but the selected theme has no light/dark pair, so it will stay selected.":`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?"light":"dark"} preference.`}themeOptionLabel(e,t){const i=[...e.id===t?["selected"]:[],...e.id===this.activeThemeId&&e.id!==t?["active"]:[]];return i.length===0?e.name:`${e.name} ✓ ${i.join(" · ")}`}themeOptionDescription(e){const t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push("auto pair"),e.description!==void 0&&t.push(e.description),t.join(" · ")}async openThinkingDialog(){const e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??"off";this.setState({thinkingDialog:{title:"Select Thinking Level",selectedValue:t,options:e.map(i=>{const s=D0(i);return{value:i,label:`${i}${i===t?" ✓ current":""}`,...s===void 0?{}:{description:s}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==""&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,i,s){!(i!==void 0&&i.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,i,s)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
3026
+ <app-context-bar
3027
+ .machines=${this.state.machines}
3028
+ .machine=${this.state.selectedMachine}
3029
+ .project=${this.state.selectedProject}
3030
+ .workspace=${this.state.selectedWorkspace}
3031
+ .session=${this.state.selectedSession}
3032
+ .refreshControl=${this.appShell.shouldShowAppRefreshInContextBar()?this.renderAppRefresh():void 0}
3033
+ .onOpenSection=${e=>{this.openNavigationSection(e)}}
3034
+ .onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
3035
+ ></app-context-bar>
3036
+ `:null}renderMobileMainTabs(){return l`
3037
+ <app-mobile-main-tabs
3038
+ .tabs=${this.mobileMainTabs()}
3039
+ .selectedView=${this.state.mainView}
3040
+ .onSelect=${e=>{this.selectMainView(e)}}
3041
+ ></app-mobile-main-tabs>
3042
+ `}mobileMainTabs(){return[{id:"navigation",label:"Sessions",icon:"navigation",className:"navigation-tab"},{id:"chat",label:"Chat",icon:"chat"},...this.visibleWorkspacePanels().map(e=>{const t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return l`<app-refresh-control .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){const e=this.state;return l`
3043
+ <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
3044
+ <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
3045
+ ${this.renderNavigationPanelEdgeControl()}
3046
+ <main class=${Rl(e.mainView)}>
3047
+ ${this.renderContextBar()}
3048
+ ${this.renderMobileMainTabs()}
3049
+ ${e.error?l`<div class="error">${e.error}</div>`:null}
3050
+ <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
3051
+ ${e.selectedSession?l`
3052
+ <chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isSendingPrompt=${e.sendingPrompts[e.selectedSession.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[e.selectedSession.id]??[]} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
3053
+ <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${g(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .availableThinkingLevels=${e.availableThinkingLevels} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${this.handleSendPrompt} .onStop=${this.handleStopActiveWork} .onSelectModel=${this.handleSelectModel} .onSelectThinking=${this.handleSelectThinking}></prompt-editor>
3054
+ <status-bar .status=${e.status}></status-bar>
3055
+ ${e.commandDialog!==void 0?l`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??"",t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`:null}
3056
+ ${e.modelDialog!==void 0?l`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${t=>{this.pickModel(t)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`:null}
3057
+ ${e.thinkingDialog!==void 0?l`<command-picker title=${e.thinkingDialog.title} .options=${e.thinkingDialog.options} .selectedValue=${e.thinkingDialog.selectedValue} .onPick=${t=>{this.pickThinking(t)}} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`:null}
3058
+ ${e.authDialog!==void 0?l`<auth-dialog .state=${e.authDialog} .onChooseMethod=${t=>{this.auth.chooseLoginMethod(t)}} .onSelectProvider=${(t,i)=>{this.auth.selectLoginProvider(t,i)}} .onApiKeyInput=${t=>{this.auth.updateApiKey(t)}} .onSaveApiKey=${()=>{this.auth.saveApiKey()}} .onLogoutProvider=${t=>{this.auth.logoutProvider(t)}} .onOAuthInput=${t=>{this.auth.updateOAuthInput(t)}} .onOAuthRespond=${t=>{this.auth.respondOAuth(t)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`:null}
3059
+ `:l`<div class="empty">${this.sessionEmptyMessage()}</div>`}
3060
+ </main>
3061
+ ${this.renderWorkspacePanelEdgeControl()}
3062
+ ${this.renderWorkspacePanel()}
3063
+ ${e.actionPaletteOpen?l`<action-palette .actions=${this.getActions()} .onRun=${t=>{this.setState({actionPaletteOpen:!1}),this.runAction(t)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
3064
+ ${e.projectDialogOpen?l`<project-dialog .machineId=${g(e)} .onSubmit=${(t,i)=>this.projects.addProject(t,i)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
3065
+ ${e.machineDialogOpen?l`<machine-dialog .error=${e.error} .onSubmit=${t=>this.submitMachineDialog(t)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
3066
+ ${this.sessionCleanupDialog!==void 0?l`<session-cleanup-dialog .canCleanup=${this.canCleanupSessions()} .unavailableMessage=${this.sessionCleanupUnavailableMessage()} .preview=${this.sessionCleanupDialog.preview} .previewRequest=${this.sessionCleanupDialog.previewRequest} .result=${this.sessionCleanupDialog.result} .loading=${this.sessionCleanupDialog.loading===!0} .running=${this.sessionCleanupDialog.running===!0} .error=${this.sessionCleanupDialog.error??""} .onPreview=${t=>{this.previewSessionCleanup(t)}} .onRun=${t=>{this.runSessionCleanup(t)}} .onClose=${()=>{this.closeSessionCleanupDialog()}}></session-cleanup-dialog>`:null}
3067
+ ${e.themeDialog!==void 0?l`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${t=>{this.pickTheme(t)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
3068
+ ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
3069
+ </div>
3070
+ `}};ue.styles=vg;Pe([v()],ue.prototype,"state",2);Pe([K("chat-view")],ue.prototype,"chatView",2);Pe([K("prompt-editor")],ue.prototype,"promptEditor",2);Pe([K("app-navigation-panel")],ue.prototype,"navigationPanel",2);Pe([K("#navigation-panel")],ue.prototype,"navigationPanelFrame",2);Pe([K("#workspace-panel")],ue.prototype,"workspacePanelFrame",2);Pe([v()],ue.prototype,"activeThemeId",2);Pe([v()],ue.prototype,"isRefreshingApp",2);Pe([v()],ue.prototype,"sessionCleanupDialog",2);Pe([v()],ue.prototype,"settingsSection",2);Pe([v()],ue.prototype,"shortcutConfig",2);Pe([v()],ue.prototype,"workspaceUploadDefaultFolder",2);ue=Pe([E("omp-web-app")],ue);function C0(){const e=new um;return e.register({id:"core",plugin:Xg}),e.register({id:"themes",plugin:im}),e}function Sa(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function R0(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function M0(e,t){return vc(e,t)}function vc(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function I0(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function xa(e){return lt(e.status,e.activity)}function T0(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function ka(){return{}}function $a(e,t){return JSON.stringify([e,t])}function A0(e){const t=Math.min(e,kr.length-1);return kr[t]??3e4}function E0(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function rr(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function D0(e){switch(e){case"off":return"No reasoning";case"minimal":return"Very brief reasoning (~1k tokens)";case"low":return"Light reasoning (~2k tokens)";case"medium":return"Moderate reasoning (~8k tokens)";case"high":return"Deep reasoning (~16k tokens)";case"xhigh":return"Maximum reasoning (~32k tokens)";default:return}}export{D as a,l as b,At as c,H0 as d,z0 as e,B as f,K as g,I as i,d as n,v as r,q0 as s,E as t};