@kabmo-labs/kabmo 0.56.0 → 0.57.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 (122) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +2 -2
  3. package/dist/client/static/js/{Body-jfy4bhk2.js → Body-k96gtstv.js} +1 -1
  4. package/dist/client/static/js/{CsvGrid-4c5t668z.js → CsvGrid-t84xmbk9.js} +1 -1
  5. package/dist/client/static/js/{DocxView-3x7whtvq.js → DocxView-4jda3szm.js} +1 -1
  6. package/dist/client/static/js/{DrawioView-tbkc5dfz.js → DrawioView-9qvvtnvt.js} +1 -1
  7. package/dist/client/static/js/{HtmlPreview-egxkayya.js → HtmlPreview-4pba1ys5.js} +1 -1
  8. package/dist/client/static/js/{ImageView-swhzvw2p.js → ImageView-0gf5xdsv.js} +1 -1
  9. package/dist/client/static/js/{LayoutWrapper-sangsrt5.js → LayoutWrapper-pwbq5syv.js} +1 -1
  10. package/dist/client/static/js/MergeDiffView-m4jkr786.js +1 -0
  11. package/dist/client/static/js/{Modal-1fj8kvme.js → Modal-yjszc3vy.js} +12 -12
  12. package/dist/client/static/js/{PdfView-0k2egsbz.js → PdfView-sny55sne.js} +1 -1
  13. package/dist/client/static/js/{SessionsView-t547rqeb.js → SessionsView-q3800n83.js} +1 -1
  14. package/dist/client/static/js/{SheetView-anb3gavm.js → SheetView-ezqak2b4.js} +1 -1
  15. package/dist/client/static/js/{SvgPreview-e2wrj2hj.js → SvgPreview-q1cvdf4s.js} +1 -1
  16. package/dist/client/static/js/{abnfDiagram-O67JEVCF-0rs86b68.js → abnfDiagram-O67JEVCF-ftm2qwa3.js} +1 -1
  17. package/dist/client/static/js/{architectureDiagram-NJMV4G6O-0k3zzxz1.js → architectureDiagram-NJMV4G6O-j8kqfzmf.js} +1 -1
  18. package/dist/client/static/js/{blockDiagram-BEXU5L5S-t1n1fx96.js → blockDiagram-BEXU5L5S-m3zpsp9h.js} +3 -3
  19. package/dist/client/static/js/{c4Diagram-YGBWAQC7-93b7eds9.js → c4Diagram-YGBWAQC7-myshvbrx.js} +2 -2
  20. package/dist/client/static/js/{classDiagram-v2-NBCMYWYE-bnf85z0f.js → classDiagram-v2-NBCMYWYE-s0cwmsj4.js} +1 -1
  21. package/dist/client/static/js/{cose-bilkent-JH36ORCC-e290161f.js → cose-bilkent-JH36ORCC-t5t02sfr.js} +1 -1
  22. package/dist/client/static/js/{cynefinDiagram-VND7K2PF-s13ra9ag.js → cynefinDiagram-VND7K2PF-6yxd72sh.js} +1 -1
  23. package/dist/client/static/js/{dagre-6A5THRUB-83wshh5e.js → dagre-6A5THRUB-vft5103m.js} +1 -1
  24. package/dist/client/static/js/{diagram-22UHCM2B-ywh4wqna.js → diagram-22UHCM2B-yy2jfvxt.js} +1 -1
  25. package/dist/client/static/js/{diagram-3UASUU5V-cb53z698.js → diagram-3UASUU5V-1xqhzq20.js} +1 -1
  26. package/dist/client/static/js/{diagram-ATOU4E4O-btf55c44.js → diagram-ATOU4E4O-f11cxgvm.js} +1 -1
  27. package/dist/client/static/js/{diagram-CDSNMT55-p6tbbm1n.js → diagram-CDSNMT55-gqmkfcp7.js} +3 -3
  28. package/dist/client/static/js/{diagram-MLGK6HIB-6kzssf4y.js → diagram-MLGK6HIB-1fg7304a.js} +1 -1
  29. package/dist/client/static/js/{diagram-MPIPVDR6-4v0yncvv.js → diagram-MPIPVDR6-mem80369.js} +1 -1
  30. package/dist/client/static/js/{dockerfile-r422htmd.js → dockerfile-jarjwxp9.js} +1 -1
  31. package/dist/client/static/js/{ebnfDiagram-ZINNZB2B-mw1gh30z.js → ebnfDiagram-ZINNZB2B-4rcbvfrj.js} +1 -1
  32. package/dist/client/static/js/{elk-276RUBZZ-1pe786ap.js → elk-276RUBZZ-ykd0stxz.js} +1 -1
  33. package/dist/client/static/js/{erDiagram-OPXOYQCR-x7rk70q6.js → erDiagram-OPXOYQCR-b2th9bk4.js} +1 -1
  34. package/dist/client/static/js/flowDiagram-KWPJA3E3-f3bdtc1z.js +1 -0
  35. package/dist/client/static/js/{ganttDiagram-FUAMR5RP-j3m5km4p.js → ganttDiagram-FUAMR5RP-64p5r7cx.js} +2 -2
  36. package/dist/client/static/js/{gitGraphDiagram-X574FWY7-fd1kebdy.js → gitGraphDiagram-X574FWY7-z3yc333r.js} +1 -1
  37. package/dist/client/static/js/{index-004x0a3p.js → index-1mm7kyjd.js} +1 -1
  38. package/dist/client/static/js/{index-4dzvjfkd.js → index-2gf593e3.js} +1 -1
  39. package/dist/client/static/js/{index-4jg10xtp.js → index-3w18s59k.js} +1 -1
  40. package/dist/client/static/js/{index-tcp5cp53.js → index-3x3nhs8n.js} +1 -1
  41. package/dist/client/static/js/{index-j1prebvy.js → index-5m0se6fk.js} +1 -1
  42. package/dist/client/static/js/{index-kbk0vmex.js → index-6m5n8b6w.js} +1 -1
  43. package/dist/client/static/js/{index-bnamrpm6.js → index-77wznmg5.js} +1 -1
  44. package/dist/client/static/js/{index-cbbwq25c.js → index-bwwgtesb.js} +1 -1
  45. package/dist/client/static/js/{index-zkef5q39.js → index-c2vc6znd.js} +1 -1
  46. package/dist/client/static/js/{index-4acka5fn.js → index-dxx49b9m.js} +1 -1
  47. package/dist/client/static/js/{index-bxhszdcz.js → index-ebnd5hnr.js} +1 -1
  48. package/dist/client/static/js/{index-g84dwmvr.js → index-ep353yxd.js} +1 -1
  49. package/dist/client/static/js/{index-s6nv35dv.js → index-ewtv8gg7.js} +1 -1
  50. package/dist/client/static/js/{index-jtyzeynv.js → index-g71wn1pr.js} +1 -1
  51. package/dist/client/static/js/{index-473wm10a.js → index-gr07t5c4.js} +1 -1
  52. package/dist/client/static/js/{index-drsy400d.js → index-h4qmywn5.js} +1 -1
  53. package/dist/client/static/js/{index-s4v3vcsn.js → index-hmjb96kb.js} +1 -1
  54. package/dist/client/static/js/{index-q4t5j3x7.js → index-jd2h5tvh.js} +1 -1
  55. package/dist/client/static/js/{index-0mhxw0a1.js → index-k57bandz.js} +1 -1
  56. package/dist/client/static/js/{index-dfha2z56.js → index-k6wms0kx.js} +1 -1
  57. package/dist/client/static/js/{index-7tsdw8wt.js → index-k9v6477a.js} +1 -1
  58. package/dist/client/static/js/{index-4fpyzg5e.js → index-kbaffwp1.js} +20 -20
  59. package/dist/client/static/js/{index-3k45gspr.js → index-mdmtxh1c.js} +1 -1
  60. package/dist/client/static/js/{index-hgsjynb0.js → index-mv83hpva.js} +1 -1
  61. package/dist/client/static/js/{index-qdabc51h.js → index-n71ffk62.js} +2 -2
  62. package/dist/client/static/js/{index-qrwjxqdh.js → index-nr5gwny1.js} +176 -176
  63. package/dist/client/static/js/{index-rm5b3kn8.js → index-q9gbwqbe.js} +3 -3
  64. package/dist/client/static/js/{index-4nyajpeg.js → index-rqpbva78.js} +1 -1
  65. package/dist/client/static/js/{index-q178zgxp.js → index-sw370sk7.js} +1 -1
  66. package/dist/client/static/js/{index-8e66p2a7.js → index-t415df0c.js} +1 -1
  67. package/dist/client/static/js/index-taz2nfym.css +1 -0
  68. package/dist/client/static/js/{index-22frp78d.js → index-w659dhe5.js} +1 -1
  69. package/dist/client/static/js/{index-29b1ysz6.js → index-wgcgshdh.js} +1 -1
  70. package/dist/client/static/js/{index-72v57e07.js → index-x6945djv.js} +1 -1
  71. package/dist/client/static/js/{index-satnfvaz.js → index-y5mf2w81.js} +1 -1
  72. package/dist/client/static/js/{index-jbaceghb.js → index-y69cbdvd.js} +1 -1
  73. package/dist/client/static/js/{index-3hrvhyym.js → index-y6qtx68e.js} +1 -1
  74. package/dist/client/static/js/{index-5fxm2tpg.js → index-yktwxghr.js} +1 -1
  75. package/dist/client/static/js/{index-8n4qwd64.js → index-zj65csnm.js} +2 -2
  76. package/dist/client/static/js/{infoDiagram-VRGFBTTK-1m0br602.js → infoDiagram-VRGFBTTK-59xq3n1b.js} +2 -2
  77. package/dist/client/static/js/{ishikawaDiagram-OU5B5YK6-zryzhpq6.js → ishikawaDiagram-OU5B5YK6-v18q4qt7.js} +2 -2
  78. package/dist/client/static/js/{journeyDiagram-ZHPQQLJL-6apqr7h4.js → journeyDiagram-ZHPQQLJL-etazj0p8.js} +2 -2
  79. package/dist/client/static/js/{kanban-definition-PNTS6WVX-am385c1e.js → kanban-definition-PNTS6WVX-ph15e5p2.js} +1 -1
  80. package/dist/client/static/js/{mermaid.core-k937exrm.js → mermaid.core-7ygd161b.js} +2 -2
  81. package/dist/client/static/js/{mindmap-definition-NLK3R4M7-hx8qq866.js → mindmap-definition-NLK3R4M7-j5xsftrf.js} +1 -1
  82. package/dist/client/static/js/one-dark-pro-4s2rr12v.js +1 -0
  83. package/dist/client/static/js/one-light-3bkk59ww.js +1 -0
  84. package/dist/client/static/js/{pegDiagram-GJSIUBJH-1hasj2h7.js → pegDiagram-GJSIUBJH-09nvb70v.js} +1 -1
  85. package/dist/client/static/js/{pieDiagram-5QR66LMP-x5nwff8r.js → pieDiagram-5QR66LMP-6ymh1960.js} +2 -2
  86. package/dist/client/static/js/{quadrantDiagram-O4NWA36T-gmrcr5jb.js → quadrantDiagram-O4NWA36T-hk61avw2.js} +2 -2
  87. package/dist/client/static/js/{railroadDiagram-XR7U4H2S-rdznfhfb.js → railroadDiagram-XR7U4H2S-3jvqrfnb.js} +1 -1
  88. package/dist/client/static/js/{requirementDiagram-PLB6GJNP-v9wb3ppf.js → requirementDiagram-PLB6GJNP-zthfj48k.js} +1 -1
  89. package/dist/client/static/js/{rust-9cgnbbcs.js → rust-q7n7q6dy.js} +1 -1
  90. package/dist/client/static/js/{sankeyDiagram-IPEJSGJF-3p4ddd2h.js → sankeyDiagram-IPEJSGJF-nh5d6xte.js} +1 -1
  91. package/dist/client/static/js/{sequenceDiagram-PO4LG4MO-wfcqxjfq.js → sequenceDiagram-PO4LG4MO-crej9b40.js} +4 -4
  92. package/dist/client/static/js/{sizeCapture-INFHLROL-g02k0k8x.js → sizeCapture-INFHLROL-nvvxw58j.js} +1 -1
  93. package/dist/client/static/js/{stateDiagram-v2-GCMORJYK-7k449yvg.js → stateDiagram-v2-GCMORJYK-e6tztjnj.js} +1 -1
  94. package/dist/client/static/js/{swimlanes-2SLR337P-zkf2bgm8.js → swimlanes-2SLR337P-xhdqjqmf.js} +1 -1
  95. package/dist/client/static/js/{swimlanesDiagram-TC7HE7FX-yex8g4fx.js → swimlanesDiagram-TC7HE7FX-hbwg3m3k.js} +1 -1
  96. package/dist/client/static/js/{timeline-definition-EJHVYXUP-qsfpjr1c.js → timeline-definition-EJHVYXUP-9cve31zc.js} +1 -1
  97. package/dist/client/static/js/{usecaseDiagram-POWQR4AR-b2vprhsr.js → usecaseDiagram-POWQR4AR-asycstwe.js} +1 -1
  98. package/dist/client/static/js/{vennDiagram-UO4OBE2U-x0ffeg2t.js → vennDiagram-UO4OBE2U-gbzk6era.js} +4 -4
  99. package/dist/client/static/js/{wardleyDiagram-VNRHLVJA-hsnhaf4f.js → wardleyDiagram-VNRHLVJA-1swwfszr.js} +2 -2
  100. package/dist/client/static/js/{xychartDiagram-PMCCYNJV-90f9aadp.js → xychartDiagram-PMCCYNJV-v7qkwv0b.js} +3 -3
  101. package/package.json +3 -3
  102. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/FormAsk.tsx +25 -62
  103. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/FormDialog.test.tsx +40 -0
  104. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/FormDialog.tsx +41 -2
  105. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/QuestionList.tsx +117 -0
  106. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/SwipeDeck.tsx +220 -0
  107. package/src/client/data/settings/omp-schema.json +59 -7
  108. package/src/client/hooks/chat/timeline/ask-frames-form.test.ts +29 -0
  109. package/src/shared/lib/chat/ask-form/data.ts +25 -6
  110. package/src/shared/lib/chat/ask-form/deck.ts +80 -0
  111. package/src/shared/lib/chat/ask-form/fields.ts +26 -1
  112. package/src/shared/lib/chat/ask-form/index.ts +18 -310
  113. package/src/shared/lib/chat/ask-form/types.ts +14 -2
  114. package/src/shared/lib/chat/ask-form/walker.ts +350 -0
  115. package/src/shared/lib/chat/ask-form.test.ts +41 -0
  116. package/src/shared/lib/omp/config/schema-releases-19-4.test.ts +47 -0
  117. package/src/shared/lib/omp/config/schema-releases.test.ts +4 -2
  118. package/dist/client/static/js/MergeDiffView-bv00y63x.js +0 -1
  119. package/dist/client/static/js/flowDiagram-KWPJA3E3-kfwaac44.js +0 -1
  120. package/dist/client/static/js/index-gedsa0z7.css +0 -1
  121. package/dist/client/static/js/one-dark-pro-phxqe9mx.js +0 -1
  122. package/dist/client/static/js/one-light-vhwh499y.js +0 -1
@@ -65,7 +65,7 @@
65
65
  by `scripts/build-client.ts`. A page that ships an external font must
66
66
  name it somewhere; this one did not. -->
67
67
  <!--app-head-->
68
- <link rel="stylesheet" crossorigin href="./static/js/index-gedsa0z7.css"><script type="module" crossorigin src="./static/js/index-qrwjxqdh.js"></script></head>
68
+ <link rel="stylesheet" crossorigin href="./static/js/index-taz2nfym.css"><script type="module" crossorigin src="./static/js/index-nr5gwny1.js"></script></head>
69
69
  <body>
70
70
  <div id="app"></div>
71
71
  <!--app-bootstrap-->
@@ -663,7 +663,7 @@ return u.substring(s,qi)
663
663
  `:`c.headers={}
664
664
  for(const [k,v] of c.request.headers.entries())c.headers[k]=v
665
665
  `},listen(e){return(t,n)=>{if(typeof Bun>"u")throw Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(e.compile(),typeof t=="string"){if(!zx(t))throw Error("Port must be a numeric value");t=parseInt(t)}let r=(s,{withAsync:a=!1}={})=>{let c={},l=[];if(e.event.request?.length||e.event.trace?.length||e.extender.higherOrderFunctions.length)return a?Promise.resolve(c):c;for(let[u,d]of Object.entries(s))if(u=encodeURI(u),Jx){if(!d)continue;for(let[p,m]of Object.entries(d))if(!(!m||!(p in lH))){if(m instanceof Promise){a&&(c[u]||(c[u]={}),l.push(m.then((h)=>{h instanceof Response&&(c[u][p]=h),rb(h)&&(c[u][p]=h)})));continue}!(m instanceof Response)&&!rb(m)||(c[u]||(c[u]={}),c[u][p]=m)}}else{if(!d)continue;if(d instanceof Promise){a&&(c[u]||(c[u]={}),l.push(d.then((p)=>{p instanceof Response&&(c[u]=p)})));continue}if(!(d instanceof Response))continue;c[u]=d}return a?Promise.all(l).then(()=>c):c},o=aH(Ok(Ok(r(e.router.response),sH(e)),e.config.serve?.routes)),i=typeof t=="object"?{development:!qa,reusePort:!0,idleTimeout:30,...e.config.serve||{},...t||{},routes:o,websocket:{...e.config.websocket||{},...ZC||{},...t.websocket||{}},fetch:e.fetch}:{development:!qa,reusePort:!0,idleTimeout:30,...e.config.serve||{},routes:o,websocket:{...e.config.websocket||{},...ZC||{}},port:t,fetch:e.fetch};if(e.server=Bun.serve(i),e.event.start)for(let s=0;s<e.event.start.length;s++)e.event.start[s].fn(e);n&&n(e.server),process.on("beforeExit",async()=>{if(e.server&&(await e.server.stop?.(),e.server=null,e.event.stop))for(let s=0;s<e.event.stop.length;s++)e.event.stop[s].fn(e)}),e.promisedModules.then(async()=>{e.config.aot,e.compile();let s=aH(Ok(Ok(await r(e.router.response,{withAsync:!0}),sH(e)),e.config.serve?.routes));e.server?.reload({...i,fetch:e.fetch,routes:s}),Bun?.gc(!1)})}},async stop(e,t){if(e.server){if(await e.server.stop(t),e.server=null,e.event.stop?.length)for(let n=0;n<e.event.stop.length;n++)e.event.stop[n].fn(e)}else console.log("Elysia isn't running. Call `app.listen` to start the server.",Error().stack)},ws(e,t,n){let{parse:r,body:o,response:i,...s}=n,a=Qt(o,{modules:e.definitions.typebox,models:e.definitions.type,normalize:e.config.normalize}),c=a?a.provider==="standard"?(u)=>a.schema["~standard"].validate(u).issues:(u)=>a.Check(u)===!1:void 0,l=Qt(i,{modules:e.definitions.typebox,models:e.definitions.type,normalize:e.config.normalize});e.route("WS",t,async(u)=>{let d=u.server??e.server,{set:p,path:m,qi:h,headers:g,query:y,params:b}=u;if(u.validator=l,n.upgrade)if(typeof n.upgrade=="function"){let x=n.upgrade(u);x instanceof Promise&&await x}else n.upgrade&&Object.assign(p.headers,n.upgrade);if(p.cookie&&Je(p.cookie)){let x=zy(p.cookie);x&&(p.headers["set-cookie"]=x)}p.headers["set-cookie"]&&Array.isArray(p.headers["set-cookie"])&&(p.headers=HC(new Headers(p.headers),p.headers["set-cookie"]));let S=iH(l),P=oH(r),E;if(typeof n.beforeHandle=="function"){let x=n.beforeHandle(u);x instanceof Promise&&await x}let T=[...n.error?Array.isArray(n.error)?n.error:[n.error]:[],...(e.event.error??[]).map((x)=>typeof x=="function"?x:x.fn)].filter((x)=>x),I=T.length>0,v=I?async(x,R)=>{for(let C of T){let A=C(Object.assign(u,{error:R}));if(A instanceof Promise&&(A=await A),await S(x,A),A)break}}:()=>{};if(!d?.upgrade(u.request,{headers:Je(p.headers)?p.headers:void 0,data:{...u,get id(){return E||(E=Ka())},validator:l,ping(x,R){n.ping?.(x,R)},pong(x,R){n.pong?.(x,R)},open:async(x)=>{try{await S(x,n.open?.(new af(x,u)))}catch(R){v(x,R)}},message:async(x,R)=>{let C=await P(x,R);if(c&&c(C)){let A=new me("message",a,C);return I?v(x,A):void x.send(A.message)}try{await S(x,n.message?.(new af(x,u,C),C))}catch(A){v(x,A)}},drain:async(x)=>{try{await S(x,n.drain?.(new af(x,u)))}catch(R){v(x,R)}},close:async(x,R,C)=>{try{await S(x,n.close?.(new af(x,u),R,C))}catch(A){v(x,A)}}}}))return Hs(400,"Expected a websocket connection")},{...s,websocket:n})}};var Nk=No?Bun.env:typeof process<"u"&&process?.env?process.env:{};var fH=/^(.+)\[(\d+)\]$/,dH=new Set(["__proto__","constructor","prototype"]),pH=(e)=>{if(dH.has(e))return!0;let t=e.match(fH);return t?dH.has(t[1]):!1},mH=(e)=>{let t=e.match(fH);return t?{name:t[1],index:parseInt(t[2],10)}:null},aMe=(e)=>{if(!(typeof e!="string"||e.charCodeAt(0)!==123))try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return}},eM=(e,t,n)=>{let r=t.split("."),o=r.pop();if(pH(o)||r.some(pH))return;let i=e;for(let a of r){let c=mH(a);if(c){Array.isArray(i[c.name])||(i[c.name]=[]);let l=i[c.name][c.index],u=typeof File<"u"&&l instanceof File;(!l||typeof l!="object"||Array.isArray(l)||u)&&(i[c.name][c.index]=aMe(l)??{}),i=i[c.name][c.index]}else(!i[a]||typeof i[a]!="object")&&(i[a]={}),i=i[a]}let s=mH(o);s?(Array.isArray(i[s.name])||(i[s.name]=[]),i[s.name][s.index]=n):i[o]=n},tM=(e)=>{if(e.length===1){let o=e[0];if(typeof o=="string"&&(o.charCodeAt(0)===123||o.charCodeAt(0)===91))try{let i=JSON.parse(o);if(i&&typeof i=="object")return i}catch{}return e[0]}let t=e.find((o)=>typeof o=="string");if(!t||typeof File>"u")return e;let n=e.filter((o)=>o instanceof File);if(!n.length||t.charCodeAt(0)!==123)return e;let r;try{r=JSON.parse(t)}catch{return e}return typeof r!="object"||r===null?e:(!("file"in r)&&n.length===1?r.file=n[0]:!("files"in r)&&n.length>1&&(r.files=n),r)},nM=(e,t)=>{let n=e.schema;if(!n)return;n.$defs?.[n.$ref]&&(n=n.$defs[n.$ref]);let r=Gs(n);if(r)for(let[o,i]of Object.entries(r))t[o]??=i.default};async function Sd(e,t,n){let r=await t.Validate(n);if(r.issues)throw new me(e,t,n,!1,r.issues);return r.value}var rM=(e)=>{let{mapResponse:t,mapEarlyResponse:n}=e["~adapter"].handler,r=e.setHeaders;return async(o)=>{let i=o.url,s=i.indexOf("/",11),a=i.indexOf("?",s+1),c=a===-1?i.substring(s):i.substring(s,a),l={cookie:{},status:200,headers:r?{...r}:{}},u=Object.assign({},e.singleton.decorator,{set:l,store:e.singleton.store,request:o,path:c,qi:a,error:Hs,status:Hs,redirect:nd}),d;try{if(e.event.request)for(let R=0;R<e.event.request.length;R++){let C=e.event.request[R].fn,A=C(u);if(A instanceof Promise&&(A=await A),A=n(A,l),A)return u.response=A}let p=o.method==="GET"&&o.headers.get("upgrade")?.toLowerCase()==="websocket"?"WS":o.method,m=e.router.dynamic.find(o.method,c)??e.router.dynamic.find(p,c)??e.router.dynamic.find("ALL",c);if(!m)throw u.query=a===-1?{}:nl(i.substring(a+1)),new qm;let{handle:h,validator:g,content:y,route:b}=m.store;if(d=m.store.hooks,d.config?.mount)return await d.config.mount(o);let S;if(o.method!=="GET"&&o.method!=="HEAD")if(y)switch(y){case"application/json":S=await o.json();break;case"text/plain":S=await o.text();break;case"application/x-www-form-urlencoded":S=nl(await o.text());break;case"application/octet-stream":S=await o.arrayBuffer();break;case"multipart/form-data":{S={};let R=await o.formData(),C=new Map;R.forEach((A,N)=>{let O=C.get(N);O?O.push(A):C.set(N,[A])});for(let[A,N]of C){if(S[A])continue;let O=tM(N);A.includes(".")||A.includes("[")?eM(S,A,O):S[A]=O}break}}else{let R;if(o.body&&(R=o.headers.get("content-type")),R){let C=R.indexOf(";");if(C!==-1&&(R=R.slice(0,C)),u.contentType=R,d.parse)for(let A=0;A<d.parse.length;A++){let N=d.parse[A].fn;if(typeof N=="string")switch(N){case"json":case"application/json":S=await o.json();break;case"text":case"text/plain":S=await o.text();break;case"urlencoded":case"application/x-www-form-urlencoded":S=nl(await o.text());break;case"arrayBuffer":case"application/octet-stream":S=await o.arrayBuffer();break;case"formdata":case"multipart/form-data":{S={};let O=await o.formData(),H=new Map;O.forEach((_,te)=>{let J=H.get(te);J?J.push(_):H.set(te,[_])});for(let[_,te]of H){if(S[_])continue;let J=tM(te);_.includes(".")||_.includes("[")?eM(S,_,J):S[_]=J}break}default:{let O=e["~parser"][N];if(O){let H=O(u,R);if(H instanceof Promise&&(H=await H),H){S=H;break}}break}}else{let O=N(u,R);if(O instanceof Promise&&(O=await O),O){S=O;break}}}if(delete u.contentType,S===void 0)switch(R){case"application/json":S=await o.json();break;case"text/plain":S=await o.text();break;case"application/x-www-form-urlencoded":S=nl(await o.text());break;case"application/octet-stream":S=await o.arrayBuffer();break;case"multipart/form-data":{S={};let A=await o.formData(),N=new Map;A.forEach((O,H)=>{let _=N.get(H);_?_.push(O):N.set(H,[O])});for(let[O,H]of N){if(S[O])continue;let _=tM(H);O.includes(".")||O.includes("[")?eM(S,O,_):S[O]=_}break}}}}u.route=b,u.body=S,u.params=m?.params||void 0,u.query=a===-1?{}:nl(i.substring(a+1)),u.headers={};for(let[R,C]of o.headers.entries())u.headers[R]=C;let P={domain:e.config.cookie?.domain??g?.cookie?.config.domain,expires:e.config.cookie?.expires??g?.cookie?.config.expires,httpOnly:e.config.cookie?.httpOnly??g?.cookie?.config.httpOnly,maxAge:e.config.cookie?.maxAge??g?.cookie?.config.maxAge,path:e.config.cookie?.path??g?.cookie?.config.path,priority:e.config.cookie?.priority??g?.cookie?.config.priority,partitioned:e.config.cookie?.partitioned??g?.cookie?.config.partitioned,sameSite:e.config.cookie?.sameSite??g?.cookie?.config.sameSite,secure:e.config.cookie?.secure??g?.cookie?.config.secure,secrets:e.config.cookie?.secrets??g?.cookie?.config.secrets,sign:e.config.cookie?.sign??g?.cookie?.config.sign},E=o.headers.get("cookie");u.cookie=await wk(u.set,E,P);let T=g?.createHeaders?.();T&&nM(T,u.headers);let I=g?.createParams?.();I&&nM(I,u.params);let v=g?.createQuery?.();if(v&&nM(v,u.query),d.transform)for(let R=0;R<d.transform.length;R++){let C=d.transform[R],A=C.fn(u);if(A instanceof Promise&&(A=await A),A instanceof Yt){let N=n(A,u.set);if(N)return u.response=N}C.subType==="derive"&&Object.assign(u,A)}if(g){if(T){let C=structuredClone(u.headers);for(let[A,N]of o.headers)C[A]=N;if(T.provider==="standard")u.headers=await Sd("header",T,C);else if(g.headers.Check(C)===!1)throw new me("header",g.headers,C)}else g.headers?.Decode&&(u.headers=g.headers.Decode(u.headers));if(I?.provider==="standard")u.params=await Sd("params",I,u.params);else{if(I?.Check(u.params)===!1)throw new me("params",g.params,u.params);g.params?.Decode&&(u.params=g.params.Decode(u.params))}if(g.query?.schema){let C=g.query.schema;C.$defs?.[C.$ref]&&(C=C.$defs[C.$ref]);let A=Gs(C);if(A)for(let N of Object.keys(A)){let O=A[N];(O.type==="array"||O.items?.type==="string")&&typeof u.query[N]=="string"&&u.query[N]&&(u.query[N]=u.query[N].split(","))}}if(v?.provider==="standard")u.query=await Sd("query",v,u.query);else{if(v?.Check(u.query)===!1)throw new me("query",g.query,u.query);g.query?.Decode&&(u.query=g.query.Decode(u.query))}if(g.createCookie?.()){let C={};for(let[A,N]of Object.entries(u.cookie))C[A]=N.value;if(g.cookie.provider==="standard"){C=await Sd("cookie",g.cookie,C);for(let A of Object.keys(C))u.cookie[A].value=C[A]}else{if(g.cookie.Check(C)===!1)throw new me("cookie",g.cookie,C);g.cookie?.Decode&&(C=g.cookie.Decode(C))}}let R=g.createBody?.();if(R?.provider==="standard")u.body=await Sd("body",R,S);else{if(R?.Check(S)===!1)throw new me("body",g.body,S);if(g.body?.Decode){let C=g.body.Decode(S);C instanceof Promise&&(C=await C),u.body=C?.value??C}}}if(d.beforeHandle)for(let R=0;R<d.beforeHandle.length;R++){let C=d.beforeHandle[R],A=C.fn(u);if(A instanceof Promise&&(A=await A),A instanceof Yt){let N=n(A,u.set);if(N)return u.response=N}if(C.subType==="resolve"){Object.assign(u,A);continue}if(A!==void 0){if(u.response=A,d.afterHandle)for(let O=0;O<d.afterHandle.length;O++){let H=d.afterHandle[O].fn(u);H instanceof Promise&&(H=await H),H&&(A=H)}let N=n(A,u.set);if(N)return u.response=N}}let x=typeof h=="function"?h(u):h;if(x instanceof Promise&&(x=await x),d.afterHandle?.length){u.response=x;for(let R=0;R<d.afterHandle.length;R++){let C=d.afterHandle[R].fn(u);C instanceof Promise&&(C=await C);let A=C instanceof Yt,N=A?C.code:l.status?typeof l.status=="string"?js[l.status]:l.status:200;A&&(l.status=N,C=C.response);let O=g?.createResponse?.()?.[N];if(O?.provider==="standard")C=await Sd("response",O,C);else if(O?.Check(C)===!1)if(O?.Clean)try{let _=O.Clean(C);if(O?.Check(_)===!1)throw new me("response",O,C);C=_}catch(_){throw _ instanceof me?_:new me("response",O,C)}else throw new me("response",O,C);if(O?.Encode&&(u.response=C=O.Encode(C)),O?.Clean)try{u.response=C=O.Clean(C)}catch{}let H=n(C,u.set);if(H!==void 0)return u.response=H}}else{let R=x instanceof Yt,C=R?x.code:l.status?typeof l.status=="string"?js[l.status]:l.status:200;R&&(l.status=C,x=x.response);let A=g?.createResponse?.()?.[C];if(A?.provider==="standard")x=await Sd("response",A,x);else if(A?.Check(x)===!1)if(A?.Clean)try{let N=A.Clean(x);if(A?.Check(N)===!1)throw new me("response",A,x);x=N}catch(N){throw N instanceof me?N:new me("response",A,x)}else throw new me("response",A,x);if(A?.Encode&&(x=A.Encode(x)),A?.Clean)try{x=A.Clean(x)}catch{}}if(u.set.cookie&&P?.sign){let R=P.secrets?typeof P.secrets=="string"?P.secrets:P.secrets[0]:void 0;if(P.sign===!0){if(R)for(let[C,A]of Object.entries(u.set.cookie))u.set.cookie[C].value=await Km(A.value,R)}else{let C=Gs(g?.cookie?.schema);if(R)for(let A of P.sign)!C||!(A in C)||u.set.cookie[A]?.value&&(u.set.cookie[A].value=await Km(u.set.cookie[A].value,R))}}return t(u.response=x,u.set)}catch(p){let m=p instanceof Zu&&p.error?p.error:p;return e.handleError(u,m)}finally{let p=d?d.afterResponse:e.event.afterResponse;p&&(qx?setImmediate(async()=>{for(let m of p)await m.fn(u)}):Promise.resolve().then(async()=>{for(let m of p)await m.fn(u)}))}}},gH=(e)=>{let{mapResponse:t}=e["~adapter"].handler;return async(n,r)=>{let o=Object.assign(n,{error:r,code:r.code});if(o.set=n.set,typeof r?.toResponse=="function"&&!(r instanceof me)&&!(r instanceof Zu))try{let i=r.toResponse();typeof i?.then=="function"&&(i=await i),i instanceof Response&&(n.set.status=i.status),n.response=i}catch{}if(!n.response&&e.event.error)for(let i=0;i<e.event.error.length;i++){let s=e.event.error[i].fn(o);if(s instanceof Promise&&(s=await s),s!=null)return n.response=t(s,n.set)}if(n.response){if(e.event.mapResponse)for(let i=0;i<e.event.mapResponse.length;i++){let s=e.event.mapResponse[i].fn(o);s instanceof Promise&&(s=await s),s!=null&&(n.response=s)}return t(n.response,n.set)}return n.set.status=r.status??500,t(typeof r.cause=="string"?r.cause:r.message,n.set)}};var hH;hH=Symbol.dispose;var cMe=class e{constructor(t={}){this.server=null,this.dependencies={},this["~Prefix"]="",this["~Singleton"]=null,this["~Definitions"]=null,this["~Metadata"]=null,this["~Ephemeral"]=null,this["~Volatile"]=null,this["~Routes"]=null,this.singleton={decorator:{},store:{},derive:{},resolve:{}},this.definitions={typebox:X.Module({}),type:{},error:{}},this.extender={macro:{},higherOrderFunctions:[]},this.validator={global:null,scoped:null,local:null,getCandidate(){return!this.global&&!this.scoped&&!this.local?{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0}:$m($m(this.global,this.scoped),this.local)}},this.standaloneValidator={global:null,scoped:null,local:null},this.event={},this.router={"~http":void 0,get http(){return this["~http"]||(this["~http"]=new Du({lazy:!0,onParam:oM.default})),this["~http"]},"~dynamic":void 0,get dynamic(){return this["~dynamic"]||(this["~dynamic"]=new Du({onParam:oM.default})),this["~dynamic"]},static:{},response:{},history:[]},this.routeTree={},this.inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1,path:!1,route:!1,url:!1},this["~parser"]={},this.handle=async(n)=>this.fetch(n),this.handleError=async(n,r)=>(this.handleError=this.config.aot?QC(this):gH(this))(n,r),this.listen=(n,r)=>(this["~adapter"].listen(this)(n,r),this),this.stop=async(n)=>(await this["~adapter"].stop?.(this,n),this),this[hH]=()=>{this.server&&this.stop()},t.tags&&(t.detail?t.detail.tags=t.tags:t.detail={tags:t.tags}),this.config={aot:Nk.ELYSIA_AOT!=="false",nativeStaticResponse:!0,encodeSchema:!0,normalize:!0,...t,prefix:t.prefix?t.prefix.charCodeAt(0)===47?t.prefix:`/${t.prefix}`:void 0,cookie:{path:"/",...t?.cookie},experimental:t?.experimental??{},seed:t?.seed===void 0?"":t?.seed},this["~adapter"]=t.adapter??(typeof Bun<"u"?uH:Yy),t?.analytic&&(t?.name||t?.seed!==void 0)&&(this.telemetry={stack:Error().stack})}get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}getGlobalDefinitions(){return this.definitions}getServer(){return this.server}getParent(){return null}get promisedModules(){return this._promisedModules||(this._promisedModules=new cC(console.error,()=>{})),this._promisedModules}env(t,n=Nk){if(Qt(t,{modules:this.definitions.typebox,dynamic:!0,additionalProperties:!0,coerce:!0,sanitize:()=>this.config.sanitize}).Check(n)===!1){let r=new me("env",t,n);throw Error(r.all.map((o)=>o.summary).join(`
666
- `))}return this}wrap(t){return this.extender.higherOrderFunctions.push({checksum:Wa(JSON.stringify({name:this.config.name,seed:this.config.seed,content:t.toString()})),fn:t}),this}get models(){let t={};for(let n of Object.keys(this.definitions.type))t[n]=Qt(this.definitions.typebox.Import(n),{models:this.definitions.type});return t.modules=this.definitions.typebox,t}add(t,n,r,o,i){let s=i?.skipPrefix??!1,a=i?.allowMeta??!1;o??={},this.applyMacro(o);let c=[];if(o.standaloneValidator&&(c=c.concat(o.standaloneValidator)),this.standaloneValidator.local&&(c=c.concat(this.standaloneValidator.local)),this.standaloneValidator.scoped&&(c=c.concat(this.standaloneValidator.scoped)),this.standaloneValidator.global&&(c=c.concat(this.standaloneValidator.global)),n!==""&&n.charCodeAt(0)!==47&&(n="/"+n),this.config.prefix&&!s&&(n=this.config.prefix+n),o?.type)switch(o.type){case"text":o.type="text/plain";break;case"json":o.type="application/json";break;case"formdata":o.type="multipart/form-data";break;case"urlencoded":o.type="application/x-www-form-urlencoded";break;case"arrayBuffer":o.type="application/octet-stream";break;default:break}let l=this.validator.getCandidate(),u={body:o?.body??l?.body,headers:o?.headers??l?.headers,params:o?.params??l?.params,query:o?.query??l?.query,cookie:o?.cookie??l?.cookie,response:o?.response??l?.response},d=this.config.precompile===!0||typeof this.config.precompile=="object"&&this.config.precompile.compose===!0,p=()=>{let A=this.definitions.type,N=!this.config.aot,O=this.config.normalize,H=this.definitions.typebox,_=()=>this.config.sanitize,te=()=>{if(u.cookie||c.find((J)=>J.cookie))return Z9({modules:H,validator:u.cookie,defaultConfig:this.config.cookie,normalize:O,config:u.cookie?.config??{},dynamic:N,models:A,validators:c.map((J)=>J.cookie),sanitize:_})};return d?{body:Qt(u.body,{modules:H,dynamic:N,models:A,normalize:O,additionalCoerce:(()=>{let J=JC(u.body,A,H);return J&&F in J&&($n("File",J)||$n("Files",J))?zC():Zy()})(),validators:c.map((J)=>J.body),sanitize:_}),headers:Qt(u.headers,{modules:H,dynamic:N,models:A,additionalProperties:!0,coerce:!0,additionalCoerce:bd(),validators:c.map((J)=>J.headers),sanitize:_}),params:Qt(u.params,{modules:H,dynamic:N,models:A,coerce:!0,additionalCoerce:bd(),validators:c.map((J)=>J.params),sanitize:_}),query:Qt(u.query,{modules:H,dynamic:N,models:A,normalize:O,coerce:!0,additionalCoerce:VC(),validators:c.map((J)=>J.query),sanitize:_}),cookie:te(),response:Rk(u.response,{modules:H,dynamic:N,models:A,normalize:O,validators:c.map((J)=>J.response),sanitize:_})}:{createBody(){return this.body?this.body:this.body=Qt(u.body,{modules:H,dynamic:N,models:A,normalize:O,additionalCoerce:(()=>{let J=JC(u.body,A,H);return J&&F in J&&($n("File",J)||$n("Files",J))?zC():Zy()})(),validators:c.map((J)=>J.body),sanitize:_})},createHeaders(){return this.headers?this.headers:this.headers=Qt(u.headers,{modules:H,dynamic:N,models:A,normalize:O,additionalProperties:!O,coerce:!0,additionalCoerce:bd(),validators:c.map((J)=>J.headers),sanitize:_})},createParams(){return this.params?this.params:this.params=Qt(u.params,{modules:H,dynamic:N,models:A,normalize:O,coerce:!0,additionalCoerce:bd(),validators:c.map((J)=>J.params),sanitize:_})},createQuery(){return this.query?this.query:this.query=Qt(u.query,{modules:H,dynamic:N,models:A,normalize:O,coerce:!0,additionalCoerce:VC(),validators:c.map((J)=>J.query),sanitize:_})},createCookie(){return this.cookie?this.cookie:this.cookie=te()},createResponse(){return this.response?this.response:this.response=Rk(u.response,{modules:H,dynamic:N,models:A,normalize:O,validators:c.map((J)=>J.response),sanitize:_})}}};(l.body||l.cookie||l.headers||l.params||l.query||l.response)&&(o=Bs(o,l)),o.tags&&(o.detail?o.detail.tags=o.tags:o.detail={tags:o.tags}),Je(this.config.detail)&&(o.detail=wn(Object.assign({},this.config.detail),o.detail));let m=Je(this.event)?Bs(this.event,lC(o)):{...X7(lC(o))};if(c.length&&Object.assign(m,{standaloneValidator:c}),this.config.aot===!1){let A=p();this.router.dynamic.add(t,n,{validator:A,hooks:m,content:o?.type,handle:r,route:n});let N=od(n,{dynamic:!0});if(n!==N&&this.router.dynamic.add(t,N,{validator:A,hooks:m,content:o?.type,handle:r,route:n}),!this.config.strictPath){let O=rd(n);this.router.dynamic.add(t,O,{validator:A,hooks:m,content:o?.type,handle:r,route:n});let H=od(O);O!==H&&this.router.dynamic.add(t,O,{validator:A,hooks:m,content:o?.type,handle:r,route:n})}this.router.history.push({method:t,path:n,composed:null,handler:r,compile:void 0,hooks:m});return}let h=this["~adapter"].handler,g=typeof r!="function"?()=>{let A=h.createNativeStaticHandler?.(r,m,{headers:Object.assign({},this.setHeaders)});return A instanceof Promise?A.then((N)=>{if(N)return N}):A?.()}:void 0,y=this.config.nativeStaticResponse===!0,b=(A)=>{!y||!g||(Jx?this.router.response[A]?this.router.response[A][t]=g():this.router.response[A]={[t]:g()}:this.router.response[A]=g())};b(n);let S,P=()=>{if(S)return S;let A=tH({app:this,path:n,method:t,hooks:m,validator:p(),handler:typeof r!="function"&&typeof h.createStaticHandler!="function"?()=>r:r,allowMeta:a,inference:this.inference});return this.router.history[T]&&(S=this.router.history[T].composed=A),A},E;if(`${t}_${n}`in this.routeTree)for(let A=0;A<this.router.history.length;A++){let N=this.router.history[A];if(N.path===n&&N.method===t){E=A;break}}else this.routeTree[`${t}_${n}`]=this.router.history.length;let T=E??this.router.history.length,I=this.router.history,v=d?P():(A)=>S?S(A):(I[T].composed=P())(A);E!==void 0?this.router.history[E]=Object.assign({method:t,path:n,composed:v,compile:P,handler:r,hooks:m},c.length?{standaloneValidators:c}:void 0,o.webSocket?{websocket:o.websocket}:void 0):this.router.history.push(Object.assign({method:t,path:n,composed:v,compile:P,handler:r,hooks:m},o.webSocket?{websocket:o.websocket}:void 0));let x={handler:d?I[T].composed:void 0,compile(){return this.handler=P()}},R=this.router.static,C=n.indexOf(":")===-1&&n.indexOf("*")===-1;if(t==="WS"){if(C){n in R?R[n][t]=T:R[n]={[t]:T};return}this.router.http.add("WS",n,x),this.config.strictPath||this.router.http.add("WS",rd(n),x);let A=od(n,{dynamic:!0});n!==A&&this.router.http.add("WS",A,x);return}if(C)n in R?R[n][t]=T:R[n]={[t]:T},this.config.strictPath||b(rd(n));else{if(this.router.http.add(t,n,x),!this.config.strictPath){let N=rd(n);b(N),this.router.http.add(t,N,x)}let A=od(n,{dynamic:!0});n!==A&&(this.router.http.add(t,A,x),b(A))}}headers(t){return t?(this.setHeaders||(this.setHeaders={}),this.setHeaders=wn(this.setHeaders,t),this):this}onStart(t){return this.on("start",t),this}onRequest(t){return this.on("request",t),this}onParse(t,n){return n?this.on(t,"parse",n):typeof t=="string"?this.on("parse",this["~parser"][t]):this.on("parse",t)}parser(t,n){return this["~parser"][t]=n,this}onTransform(t,n){return n?this.on(t,"transform",n):this.on("transform",t)}resolve(t,n){n||(n=t,t={as:"local"});let r={subType:"resolve",fn:n};return this.onBeforeHandle(t,r)}mapResolve(t,n){n||(n=t,t={as:"local"});let r={subType:"mapResolve",fn:n};return this.onBeforeHandle(t,r)}onBeforeHandle(t,n){return n?this.on(t,"beforeHandle",n):this.on("beforeHandle",t)}onAfterHandle(t,n){return n?this.on(t,"afterHandle",n):this.on("afterHandle",t)}mapResponse(t,n){return n?this.on(t,"mapResponse",n):this.on("mapResponse",t)}onAfterResponse(t,n){return n?this.on(t,"afterResponse",n):this.on("afterResponse",t)}trace(t,n){n||(n=t,t={as:"local"}),Array.isArray(n)||(n=[n]);for(let r of n)this.on(t,"trace",V9(r));return this}error(t,n){switch(typeof t){case"string":return n.prototype[id]=t,this.definitions.error[t]=n,this;case"function":return this.definitions.error=t(this.definitions.error),this}for(let[r,o]of Object.entries(t))o.prototype[id]=r,this.definitions.error[r]=o;return this}onError(t,n){return n?this.on(t,"error",n):this.on("error",t)}onStop(t){return this.on("stop",t),this}on(t,n,r){let o;switch(typeof t){case"string":o=t,r=n;break;case"object":o=n,!Array.isArray(n)&&typeof n=="object"&&(r=n);break}Array.isArray(r)?r=bn(r):typeof r=="function"?r=[{fn:r}]:r=[r];let i=r;for(let s of i)s.scope=typeof t=="string"?"local":t?.as??"local",(o==="resolve"||o==="derive")&&(s.subType=o);o!=="trace"&&(this.inference=fd({[o]:i.map((s)=>s.fn)},this.inference,this.config.sucrose));for(let s of i){let a=Q7(s,"global",{skipIfHasType:!0});switch((this.config.name||this.config.seed)&&(a.checksum=Wa(this.config.name+JSON.stringify(this.config.seed))),o){case"start":this.event.start??=[],this.event.start.push(a);break;case"request":this.event.request??=[],this.event.request.push(a);break;case"parse":this.event.parse??=[],this.event.parse.push(a);break;case"transform":this.event.transform??=[],this.event.transform.push(a);break;case"derive":this.event.transform??=[],this.event.transform.push(bn(a,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(a);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(bn(a,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(a);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(a);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(a);break;case"trace":this.event.trace??=[],this.event.trace.push(a);break;case"error":this.event.error??=[],this.event.error.push(a);break;case"stop":this.event.stop??=[],this.event.stop.push(a);break}}return this}as(t){return Ga(this.event.parse,t),Ga(this.event.transform,t),Ga(this.event.beforeHandle,t),Ga(this.event.afterHandle,t),Ga(this.event.mapResponse,t),Ga(this.event.afterResponse,t),Ga(this.event.trace,t),Ga(this.event.error,t),t==="scoped"?(this.validator.scoped=$m(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null&&(this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null)):t==="global"&&(this.validator.global=$m(this.validator.global,$m(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null&&(this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null),this.standaloneValidator.scoped!==null&&(this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null)),this}group(t,n,r){let o=new e({...this.config,prefix:""});o.singleton={...this.singleton},o.definitions={...this.definitions},o.getServer=()=>this.getServer(),o.inference=_x(this.inference),o.extender={...this.extender},o["~parser"]=this["~parser"],o.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let i=typeof n=="object",s=(i?r:n)(o);return this.singleton=wn(this.singleton,o.singleton),this.definitions=wn(this.definitions,o.definitions),s.event.request?.length&&(this.event.request=[...this.event.request||[],...s.event.request||[]]),s.event.mapResponse?.length&&(this.event.mapResponse=[...this.event.mapResponse||[],...s.event.mapResponse||[]]),this.model(s.definitions.type),Object.values(o.router.history).forEach(({method:a,path:c,handler:l,hooks:u})=>{if(c=(i?"":this.config.prefix??"")+t+c,i){let{body:d,headers:p,query:m,params:h,cookie:g,response:y,...b}=n,S=u;this.applyMacro(b);let P=d||p||m||h||g||y;this.add(a,c,l,Bs(b,{...S||{},error:S.error?Array.isArray(S.error)?[...S.error??[],...s.event.error??[]]:[S.error,...s.event.error??[]]:s.event.error,standaloneValidator:b.standaloneValidator||S.standaloneValidator||P?[...b.standaloneValidator??[],...S.standaloneValidator??[],...P?[{body:d,headers:p,query:m,params:h,cookie:g,response:y}]:[]]:void 0}),void 0)}else this.add(a,c,l,Bs(u,{error:s.event.error}),{skipPrefix:!0})}),this}guard(t,n){if(!n){if(typeof t=="object"){this.applyMacro(t),t.detail&&(this.config.detail?this.config.detail=wn(Object.assign({},this.config.detail),t.detail):this.config.detail=t.detail),t.tags&&(this.config.detail?this.config.detail.tags=t.tags:this.config.detail={tags:t.tags});let i=t.as??"local";if(t.schema==="standalone"){this.standaloneValidator[i]||(this.standaloneValidator[i]=[]);let s=t?.response?typeof t.response=="string"||F in t.response||"~standard"in t.response?{200:t.response}:t?.response:void 0;this.standaloneValidator[i].push({body:t.body,headers:t.headers,params:t.params,query:t.query,response:s,cookie:t.cookie})}else this.validator[i]={body:t.body??this.validator[i]?.body,headers:t.headers??this.validator[i]?.headers,params:t.params??this.validator[i]?.params,query:t.query??this.validator[i]?.query,response:t.response??this.validator[i]?.response,cookie:t.cookie??this.validator[i]?.cookie};return t.parse&&this.on({as:i},"parse",t.parse),t.transform&&this.on({as:i},"transform",t.transform),t.derive&&this.on({as:i},"derive",t.derive),t.beforeHandle&&this.on({as:i},"beforeHandle",t.beforeHandle),t.resolve&&this.on({as:i},"resolve",t.resolve),t.afterHandle&&this.on({as:i},"afterHandle",t.afterHandle),t.mapResponse&&this.on({as:i},"mapResponse",t.mapResponse),t.afterResponse&&this.on({as:i},"afterResponse",t.afterResponse),t.error&&this.on({as:i},"error",t.error),this}return this.guard({},t)}let r=new e({...this.config,prefix:""});r.singleton={...this.singleton},r.definitions={...this.definitions},r.inference=_x(this.inference),r.extender={...this.extender},r.getServer=()=>this.getServer();let o=n(r);if(this.singleton=wn(this.singleton,r.singleton),this.definitions=wn(this.definitions,r.definitions),o.getServer=()=>this.server,o.event.request?.length&&(this.event.request=[...this.event.request||[],...o.event.request||[]]),o.event.mapResponse?.length&&(this.event.mapResponse=[...this.event.mapResponse||[],...o.event.mapResponse||[]]),this.model(o.definitions.type),Object.values(r.router.history).forEach(({method:i,path:s,handler:a,hooks:c})=>{let{body:l,headers:u,query:d,params:p,cookie:m,response:h,...g}=t,y=l||u||d||p||m||h;this.add(i,s,a,Bs(g,{...c||{},error:c.error?Array.isArray(c.error)?[...c.error??[],...o.event.error??[]]:[c.error,...o.event.error??[]]:o.event.error,standaloneValidator:y?[...c.standaloneValidator??[],{body:l,headers:u,query:d,params:p,cookie:m,response:h}]:c.standaloneValidator}))}),r.promisedModules.size>0){let i=r.router.history.length;for(let s of r.promisedModules.promises)this.promisedModules.add(s.then(()=>{let{body:a,headers:c,query:l,params:u,cookie:d,response:p,...m}=t,h=a||c||l||u||d||p,g=i;i=r.router.history.length;for(let y=g;y<r.router.history.length;y++){let{method:b,path:S,handler:P,hooks:E}=r.router.history[y];this.add(b,S,P,Bs(m,{...E||{},error:E.error?Array.isArray(E.error)?[...E.error??[],...o.event.error??[]]:[E.error,...o.event.error??[]]:o.event.error,standaloneValidator:h?[...E.standaloneValidator??[],{body:a,headers:c,query:l,params:u,cookie:d,response:p}]:E.standaloneValidator}))}}))}return this}use(t){if(!t)return this;if(Array.isArray(t)){let n=this;for(let r of t)n=n.use(r);return n}return t instanceof Promise?(this.promisedModules.add(t.then((n)=>{if(typeof n=="function")return n(this);if(n instanceof e)return this._use(n).compile();if(n.constructor?.name==="Elysia")return this._use(n).compile();if(typeof n.default=="function")return n.default(this);if(n.default instanceof e)return this._use(n.default);if(n.constructor?.name==="Elysia")return this._use(n.default);if(n.constructor?.name==="_Elysia")return this._use(n.default);try{return this._use(n.default)}catch(r){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),r}}).then((n)=>(n&&typeof n.compile=="function"&&n.compile(),n))),this):this._use(t)}propagatePromiseModules(t){if(t.promisedModules.size<=0)return this;for(let n of t.promisedModules.promises)this.promisedModules.add(n.then((r)=>{if(!r)return;let o=this._use(r);return o instanceof Promise?o.then((i)=>{i?i.compile():r.compile()}):r.compile()}));return this}_use(t){if(typeof t=="function"){let o=t(this);return o instanceof Promise?(this.promisedModules.add(o.then((i)=>{if(i instanceof e){i.getServer=()=>this.getServer(),i.getGlobalRoutes=()=>this.getGlobalRoutes(),i.getGlobalDefinitions=()=>this.getGlobalDefinitions(),i.model(this.definitions.type),i.error(this.definitions.error);for(let{method:s,path:a,handler:c,hooks:l}of Object.values(i.router.history))this.add(s,a,c,l,void 0);return i===this?void 0:(this.propagatePromiseModules(i),i)}return typeof i=="function"?i(this):typeof i.default=="function"?i.default(this):this._use(i)}).then((i)=>(i&&typeof i.compile=="function"&&i.compile(),i))),this):o}this.propagatePromiseModules(t);let n=t.config.name,r=t.config.seed;if(t.getParent=()=>this,t.getServer=()=>this.getServer(),t.getGlobalRoutes=()=>this.getGlobalRoutes(),t.getGlobalDefinitions=()=>this.getGlobalDefinitions(),t.standaloneValidator?.scoped&&(this.standaloneValidator.local?this.standaloneValidator.local=this.standaloneValidator.local.concat(t.standaloneValidator.scoped):this.standaloneValidator.local=t.standaloneValidator.scoped),t.standaloneValidator?.global&&(this.standaloneValidator.global?this.standaloneValidator.global=this.standaloneValidator.global.concat(t.standaloneValidator.global):this.standaloneValidator.global=t.standaloneValidator.global),Je(t["~parser"])&&(this["~parser"]={...t["~parser"],...this["~parser"]}),t.setHeaders&&this.headers(t.setHeaders),n){n in this.dependencies||(this.dependencies[n]=[]);let o=r!==void 0?Wa(n+JSON.stringify(r)):0;this.dependencies[n].some(({checksum:i})=>o===i)||(this.extender.macro={...this.extender.macro,...t.extender.macro},this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(t.extender.higherOrderFunctions))}else Je(t.extender.macro)&&(this.extender.macro={...this.extender.macro,...t.extender.macro}),t.extender.higherOrderFunctions.length&&(this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(t.extender.higherOrderFunctions));if(t.extender.higherOrderFunctions.length){pC(this.extender.higherOrderFunctions);let o=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let s=this.extender.higherOrderFunctions[i];s.checksum&&(o.includes(s.checksum)&&(this.extender.higherOrderFunctions.splice(i,1),i--),o.push(s.checksum))}o.length=0}this.inference=hk(this.inference,t.inference),Je(t.singleton.decorator)&&this.decorate(t.singleton.decorator),Je(t.singleton.store)&&this.state(t.singleton.store),Je(t.definitions.type)&&this.model(t.definitions.type),Je(t.definitions.error)&&this.error(t.definitions.error),Je(t.extender.macro)&&(this.extender.macro={...this.extender.macro,...t.extender.macro});for(let{method:o,path:i,handler:s,hooks:a}of Object.values(t.router.history))this.add(o,i,s,a);if(n){n in this.dependencies||(this.dependencies[n]=[]);let o=r!==void 0?Wa(n+JSON.stringify(r)):0;if(this.dependencies[n].some(({checksum:i})=>o===i))return this;this.dependencies[n].push(this.config?.analytic?{name:t.config.name,seed:t.config.seed,checksum:o,dependencies:t.dependencies,stack:t.telemetry?.stack,routes:t.router.history,decorators:t.singleton,store:t.singleton.store,error:t.definitions.error,derive:t.event.transform?.filter((i)=>i?.subType==="derive").map((i)=>({fn:i.toString(),stack:Error().stack??""})),resolve:t.event.transform?.filter((i)=>i?.subType==="resolve").map((i)=>({fn:i.toString(),stack:Error().stack??""}))}:{name:t.config.name,seed:t.config.seed,checksum:o,dependencies:t.dependencies}),Je(t.event)&&(this.event=iC(this.event,sC(t.event),o))}else Je(t.event)&&(this.event=iC(this.event,sC(t.event)));return t.validator.global&&(this.validator.global=Bs(this.validator.global,{...t.validator.global})),t.validator.scoped&&(this.validator.local=Bs(this.validator.local,{...t.validator.scoped})),this}macro(t,n){if(typeof t=="string"&&!n)throw Error("Macro function is required");return typeof t=="string"?this.extender.macro[t]=n:this.extender.macro={...this.extender.macro,...t},this}applyMacro(t,n=t,{iteration:r=0,applied:o={}}={}){if(r>=16)return;let i=this.extender.macro;for(let[s,a]of Object.entries(n)){if(!(s in i))continue;let c=typeof i[s]=="function"?i[s](a):i[s];if(!c||typeof i[s]=="object"&&a===!1)return;let l=Wa(s+JSON.stringify(c.seed??a));if(!(l in o)){o[l]=!0;for(let[u,d]of Object.entries(c))if(u!=="seed"){if(u in tj){Z7(t,u,d),delete t[s];continue}if(u==="introspect"){d?.(t),delete t[s];continue}if(u==="detail"){t.detail||(t.detail={}),t.detail=wn(t.detail,d,{mergeArray:!0}),delete t[s];continue}if(u in i){this.applyMacro(t,{[u]:d},{applied:o,iteration:r+1}),delete t[s];continue}switch((u==="derive"||u==="resolve")&&typeof d=="function"&&(d={fn:d,subType:u}),typeof t[u]){case"function":t[u]=[t[u],d];break;case"object":Array.isArray(t[u])?t[u].push(d):t[u]=[t[u],d];break;case"undefined":t[u]=d;break}delete t[s]}}}}mount(t,n,r){if(t instanceof e||typeof t=="function"||t.length===0||t==="/"){let a=typeof t=="function"?t:t instanceof e?t.compile().fetch:n instanceof e?n.compile().fetch:typeof n=="function"?n:(()=>{throw Error("Invalid handler")})(),c=({request:l,path:u})=>a(new Request(Gx(l.url,u),l));return this.route("ALL","/*",c,{parse:"none",...r,detail:{...r?.detail,hide:!0},config:{mount:a}}),this}let o=n instanceof e?n.compile().fetch:typeof n=="function"?n:(()=>{throw Error("Invalid handler")})(),i=(typeof t=="string"&&this.config.prefix?this.config.prefix+t:t).length-(t.endsWith("*")?1:0),s=({request:a,path:c})=>o(new Request(Gx(a.url,c.slice(i)||"/"),a));return this.route("ALL",t,s,{parse:"none",...r,detail:{...r?.detail,hide:!0},config:{mount:o}}),this.route("ALL",t+(t.endsWith("/")?"*":"/*"),s,{parse:"none",...r,detail:{...r?.detail,hide:!0},config:{mount:o}}),this}get(t,n,r){return this.add("GET",t,n,r),this}post(t,n,r){return this.add("POST",t,n,r),this}put(t,n,r){return this.add("PUT",t,n,r),this}patch(t,n,r){return this.add("PATCH",t,n,r),this}delete(t,n,r){return this.add("DELETE",t,n,r),this}options(t,n,r){return this.add("OPTIONS",t,n,r),this}all(t,n,r){return this.add("ALL",t,n,r),this}head(t,n,r){return this.add("HEAD",t,n,r),this}connect(t,n,r){return this.add("CONNECT",t,n,r),this}route(t,n,r,o){return this.add(t.toUpperCase(),n,r,o,o?.config),this}ws(t,n){return this["~adapter"].ws?this["~adapter"].ws(this,t,n):console.warn("Current adapter doesn't support WebSocket"),this}state(t,n,r){n===void 0?(r=t,t={as:"append"},n=""):r===void 0&&(typeof t=="string"?(r=n,n=t,t={as:"append"}):typeof t=="object"&&(r=n,n=""));let{as:o}=t;if(typeof n!="string")return this;switch(typeof r){case"object":return!r||!Je(r)?this:n?((n in this.singleton.store)?this.singleton.store[n]=wn(this.singleton.store[n],r,{override:o==="override"}):this.singleton.store[n]=r,this):r===null?this:(this.singleton.store=wn(this.singleton.store,r,{override:o==="override"}),this);case"function":return n?(o==="override"||!(n in this.singleton.store))&&(this.singleton.store[n]=r):this.singleton.store=r(this.singleton.store),this;default:return(o==="override"||!(n in this.singleton.store))&&(this.singleton.store[n]=r),this}}decorate(t,n,r){n===void 0?(r=t,t={as:"append"},n=""):r===void 0&&(typeof t=="string"?(r=n,n=t,t={as:"append"}):typeof t=="object"&&(r=n,n=""));let{as:o}=t;if(typeof n!="string")return this;switch(typeof r){case"object":return n?((n in this.singleton.decorator)?this.singleton.decorator[n]=wn(this.singleton.decorator[n],r,{override:o==="override"}):this.singleton.decorator[n]=r,this):r===null?this:(this.singleton.decorator=wn(this.singleton.decorator,r,{override:o==="override"}),this);case"function":return n?(o==="override"||!(n in this.singleton.decorator))&&(this.singleton.decorator[n]=r):this.singleton.decorator=r(this.singleton.decorator),this;default:return(o==="override"||!(n in this.singleton.decorator))&&(this.singleton.decorator[n]=r),this}}derive(t,n){n||(n=t,t={as:"local"});let r={subType:"derive",fn:n};return this.onTransform(t,r)}model(t,n){let r=(o)=>{let i={};for(let s in o)"~standard"in o[s]||(i[s]=o[s]);return i};switch(typeof t){case"object":let o={},i=Object.entries(t);if(!i.length)return this;for(let[c,l]of i)c in this.definitions.type||("~standard"in l?this.definitions.type[c]=l:(o[c]=this.definitions.type[c]=l,o[c].$id??=`#/components/schemas/${c}`));return this.definitions.typebox=X.Module({...this.definitions.typebox.$defs,...o}),this;case"function":let s=t(this.definitions.type);return this.definitions.type=s,this.definitions.typebox=X.Module(r(s)),this;case"string":if(!n)break;if(this.definitions.type[t]=n,"~standard"in n)return this;let a={...n,id:n.$id??`#/components/schemas/${t}`};return this.definitions.typebox=X.Module({...this.definitions.typebox.$defs,...a}),this}return n?(this.definitions.type[t]=n,("~standard"in n)?this:(this.definitions.typebox=X.Module({...this.definitions.typebox.$defs,[t]:n}),this)):this}Ref(t){return X.Ref(t)}mapDerive(t,n){n||(n=t,t={as:"local"});let r={subType:"mapDerive",fn:n};return this.onTransform(t,r)}affix(t,n,r){if(r==="")return this;let o=["_","-"," "],i=(l)=>l[0].toUpperCase()+l.slice(1),s=t==="prefix"?(l,u)=>o.includes(l.at(-1)??"")?l+u:l+i(u):o.includes(r.at(-1)??"")?(l,u)=>u+l:(l,u)=>u+i(l),a=(l)=>{let u={};switch(l){case"decorator":for(let d in this.singleton.decorator)u[s(r,d)]=this.singleton.decorator[d];this.singleton.decorator=u;break;case"state":for(let d in this.singleton.store)u[s(r,d)]=this.singleton.store[d];this.singleton.store=u;break;case"model":for(let d in this.definitions.type)u[s(r,d)]=this.definitions.type[d];this.definitions.type=u;break;case"error":for(let d in this.definitions.error)u[s(r,d)]=this.definitions.error[d];this.definitions.error=u;break}},c=Array.isArray(n)?n:[n];for(let l of c.some((u)=>u==="all")?["decorator","state","model","error"]:c)a(l);return this}prefix(t,n){return this.affix("prefix",t,n)}suffix(t,n){return this.affix("suffix",t,n)}compile(){return this["~adapter"].beforeCompile?.(this),this["~adapter"].isWebStandard?(this._handle=this.config.aot?Ck(this):rM(this),Object.defineProperty(this,"fetch",{value:this._handle,configurable:!0,writable:!0}),typeof this.server?.reload=="function"&&this.server.reload({...this.server||{},fetch:this.fetch}),this):(typeof this.server?.reload=="function"&&this.server.reload(this.server||{}),this._handle=Ck(this),this)}get fetch(){let t=this.config.aot?Ck(this):rM(this);return Object.defineProperty(this,"fetch",{value:t,configurable:!0,writable:!0}),t}get modules(){return this.promisedModules}},pi=cMe;var cf={name:"@kabmo-labs/kabmo",version:"0.56.0",description:"Web console and diagnostic workbench for AI coding agents: Elysia + Preact on Bun.",license:"MIT",author:"Wijanarko Putra Rajeb <wijanarko.rajeb@gmail.com>",type:"module",engines:{bun:">=1.4.0"},publishConfig:{access:"public"},bin:{kabmo:"./src/cli/kabmo.js"},repository:{type:"git",url:"git+https://github.com/kabmo-labs/kabmo.git"},homepage:"https://github.com/kabmo-labs/kabmo#readme",bugs:{url:"https://github.com/kabmo-labs/kabmo/issues"},keywords:["kabmo","coding-agent","agent","console","elysia","preact","bun"],files:["src","extensions","index.html","bunfig.toml","public","tsconfig.json","marketplace","dist/client"],scripts:{dev:"bun run --hot src/server/index.ts --kabmo-server","dev:lan":"HOST=0.0.0.0 bun run --hot src/server/index.ts --kabmo-server",build:"bun run scripts/build-client.ts","editor:themes":"bun run scripts/editor-themes.mjs","icons:tints":"bun run scripts/icon-tints.mjs","icons:tints:check":"bun run scripts/icon-tints.mjs --check","tray:icons":"bun run scripts/tray-icon.mjs","tray:icons:check":"bun run scripts/tray-icon.mjs --check","editor:themes:check":"bun run scripts/editor-themes.mjs --check","omp:schema":"bun run scripts/omp-schema.mjs","omp:schema:check":"bun run scripts/omp-schema.mjs --check",start:"NODE_ENV=production bun run src/server/index.ts --kabmo-server",typecheck:"tsc",clean:"rm -rf dist",lint:"tsc --noEmit","check:fast":"bun check --no-script",test:"bun test","test:e2e":"playwright test --config tests/e2e/playwright.config.ts","readme:media":"bun run scripts/readme-media.ts","shell:wordmark":"bun run scripts/shell-wordmark.mjs","shell:docs":"bun run scripts/shell-document-types.mjs --write","shell:docs:check":"bun run scripts/shell-document-types.mjs --check","typecheck:e2e":"tsc --noEmit -p tests/e2e","typecheck:consumer":"tsc --noEmit -p tsconfig.consumer.json","publish:plugins":"bash .github/scripts/publish-plugin-packages.sh packages/kabmo-sdk packages/kabmo-ui"},dependencies:{"@codemirror/autocomplete":"6.20.4","@codemirror/commands":"6.11.1","@codemirror/language":"6.13.1","@codemirror/legacy-modes":"^6.5.5","@codemirror/lint":"^6.9.7","@codemirror/merge":"6.12.3","@codemirror/search":"6.7.2","@codemirror/state":"6.7.6","@codemirror/view":"6.43.15","@dskripchenko/drawio":"^0.1.0","@fontsource/fira-code":"^5.3.0","@shikijs/langs":"^4.4.3","@shikijs/themes":"^4.4.3","@tailwindcss/postcss":"^4.1.14",dompurify:"^3.4.15",elysia:"^1.4.30","ghostty-web":"0.4.0-next.21.g640db46","jsonc-parser":"^3.3.1",katex:"^0.18.7","lucide-preact":"^1.47.0",mammoth:"^1.13.0",marked:"^18.0.11","marked-linkify-it":"^4.0.2",mermaid:"^12.0.0",postcss:"^8.5.16",preact:"^10.29.8","qrcode-generator":"^2.0.4",remend:"^1.3.1",ripgrep:"^0.3.1","sherpa-onnx-node":"^2.0.2",shiki:"^4.4.3","smol-toml":"^1.9.1",tailwindcss:"^4.1.14",xlsx:"https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",yaml:"^2.9.1","@kabmo-labs/kabmo-acp":"workspace:*","@kabmo-labs/kabmo-app-contracts":"workspace:*","@kabmo-labs/kabmo-auth":"workspace:*","@kabmo-labs/kabmo-bytes":"workspace:*","@kabmo-labs/kabmo-chat":"workspace:*","@kabmo-labs/kabmo-db":"workspace:*","@kabmo-labs/kabmo-format":"workspace:*","@kabmo-labs/kabmo-fs":"workspace:*","@kabmo-labs/kabmo-git":"workspace:*","@kabmo-labs/kabmo-guards":"workspace:*","@kabmo-labs/kabmo-harness":"workspace:*","@kabmo-labs/kabmo-http":"workspace:*","@kabmo-labs/kabmo-idle-reaper":"workspace:*","@kabmo-labs/kabmo-live-sessions":"workspace:*","@kabmo-labs/kabmo-mcp-contracts":"workspace:*","@kabmo-labs/kabmo-model-contracts":"workspace:*","@kabmo-labs/kabmo-omp":"workspace:*","@kabmo-labs/kabmo-paths":"workspace:*","@kabmo-labs/kabmo-platform":"workspace:*","@kabmo-labs/kabmo-process":"workspace:*","@kabmo-labs/kabmo-provider-contracts":"workspace:*","@kabmo-labs/kabmo-realtime-signals":"workspace:*","@kabmo-labs/kabmo-refresh-cadence":"workspace:*","@kabmo-labs/kabmo-rpc-lines":"workspace:*","@kabmo-labs/kabmo-runtime-flags":"workspace:*","@kabmo-labs/kabmo-sdk":"workspace:*","@kabmo-labs/kabmo-session":"workspace:*","@kabmo-labs/kabmo-settings":"workspace:*","@kabmo-labs/kabmo-ui":"workspace:*","@kabmo-labs/kabmo-workspace":"workspace:*","@kabmo-labs/kabmo-worktree":"workspace:*"},devDependencies:{"@playwright/test":"^1.64.0","@semantic-release/changelog":"^7.0.0","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/git":"^11.0.1","@semantic-release/github":"^12.0.10","@semantic-release/npm":"^13.2.0","@semantic-release/release-notes-generator":"^14.1.1","@types/bun":"1.4.4","@types/node":"^22.14.0","@types/qrcode-generator":"^0.0.16","bun-types":"1.4.4","conventional-changelog-conventionalcommits":"^9.3.1","happy-dom":"^20.14.5",jsqr:"^1.4.0","semantic-release":"^25.0.9",typescript:"~5.8.2"},overrides:{katex:"^0.18.7"},workspaces:["packages/*"],"$comment-workspaces":"Only `packages/*` are Bun workspaces. The native shells live in `apps/` and the sound and QR inputs in `assets/`; they have no package.json, so they are never installed, published or typechecked as libraries."};function Lk(e,t,n){let r=e.headers.get("if-none-match");if(r!==null){if(!t)return!1;let i=t.trim().replace(/^W\//,"");return r.split(",").some((s)=>s.trim().replace(/^W\//,"")===i)}let o=e.headers.get("if-modified-since");if(o&&n!==null){let i=Date.parse(o);if(!Number.isNaN(i))return Math.floor(n/1000)*1000<=i}return!1}import{brotliCompressSync as uMe,constants as dMe}from"zlib";function Fo(e){if(e.buffer instanceof ArrayBuffer)return e;return new Uint8Array(e)}var iM=1024,yH=/^(text\/|application\/(json|javascript|xml|wasm|svg))/,pMe=["zstd","br","gzip"];function bH(e){return yH.test(e)}function sM(e){if(!e)return null;for(let t of pMe)if(e.includes(t))return t;return null}function aM(e,t){if(t==="zstd")return Fo(Bun.zstdCompressSync(e,{level:3}));if(t==="br")return Fo(uMe(e,{params:{[dMe.BROTLI_PARAM_QUALITY]:4}}));return Fo(Bun.gzipSync(e,{level:6}))}async function qs(e,t){if(!t)return e;let n=e.headers.get("content-type")??"";if(n.includes("text/event-stream"))return e;if(!yH.test(n))return e;if(e.status===204||e.status===304)return e;let r=sM(t);if(!r)return e;let o=Fo(new Uint8Array(await e.arrayBuffer()));if(o.byteLength<iM)return mMe(e,o);let i=aM(o,r),s=new Headers(e.headers);return s.set("content-encoding",r),s.set("content-length",String(i.byteLength)),s.append("vary","accept-encoding"),new Response(i,{status:e.status,headers:s})}function mMe(e,t){return new Response(t,{status:e.status,headers:e.headers})}var Qa=Bun.env.NODE_ENV!=="production",SH="/_bun/",xH=["/_bun/client/","/_bun/asset/"],cM="/_dev-assets/",wH="no-cache";function kH(e){let t=e;for(let n of xH)t=t.replaceAll(n,cM+n.slice(SH.length));return t}function lM(e){if(!e.startsWith(cM))return null;let t=SH+e.slice(cM.length);return xH.some((n)=>t.startsWith(n))?t:null}async function vH(e,t,n,r={}){let o=lM(t);if(!o)return null;let i=await fetch(new URL(o,n),r),s=i.headers.get("content-type")??"";if(!i.ok||s.startsWith("text/html"))return new Response(`No dev asset at ${o}
666
+ `))}return this}wrap(t){return this.extender.higherOrderFunctions.push({checksum:Wa(JSON.stringify({name:this.config.name,seed:this.config.seed,content:t.toString()})),fn:t}),this}get models(){let t={};for(let n of Object.keys(this.definitions.type))t[n]=Qt(this.definitions.typebox.Import(n),{models:this.definitions.type});return t.modules=this.definitions.typebox,t}add(t,n,r,o,i){let s=i?.skipPrefix??!1,a=i?.allowMeta??!1;o??={},this.applyMacro(o);let c=[];if(o.standaloneValidator&&(c=c.concat(o.standaloneValidator)),this.standaloneValidator.local&&(c=c.concat(this.standaloneValidator.local)),this.standaloneValidator.scoped&&(c=c.concat(this.standaloneValidator.scoped)),this.standaloneValidator.global&&(c=c.concat(this.standaloneValidator.global)),n!==""&&n.charCodeAt(0)!==47&&(n="/"+n),this.config.prefix&&!s&&(n=this.config.prefix+n),o?.type)switch(o.type){case"text":o.type="text/plain";break;case"json":o.type="application/json";break;case"formdata":o.type="multipart/form-data";break;case"urlencoded":o.type="application/x-www-form-urlencoded";break;case"arrayBuffer":o.type="application/octet-stream";break;default:break}let l=this.validator.getCandidate(),u={body:o?.body??l?.body,headers:o?.headers??l?.headers,params:o?.params??l?.params,query:o?.query??l?.query,cookie:o?.cookie??l?.cookie,response:o?.response??l?.response},d=this.config.precompile===!0||typeof this.config.precompile=="object"&&this.config.precompile.compose===!0,p=()=>{let A=this.definitions.type,N=!this.config.aot,O=this.config.normalize,H=this.definitions.typebox,_=()=>this.config.sanitize,te=()=>{if(u.cookie||c.find((J)=>J.cookie))return Z9({modules:H,validator:u.cookie,defaultConfig:this.config.cookie,normalize:O,config:u.cookie?.config??{},dynamic:N,models:A,validators:c.map((J)=>J.cookie),sanitize:_})};return d?{body:Qt(u.body,{modules:H,dynamic:N,models:A,normalize:O,additionalCoerce:(()=>{let J=JC(u.body,A,H);return J&&F in J&&($n("File",J)||$n("Files",J))?zC():Zy()})(),validators:c.map((J)=>J.body),sanitize:_}),headers:Qt(u.headers,{modules:H,dynamic:N,models:A,additionalProperties:!0,coerce:!0,additionalCoerce:bd(),validators:c.map((J)=>J.headers),sanitize:_}),params:Qt(u.params,{modules:H,dynamic:N,models:A,coerce:!0,additionalCoerce:bd(),validators:c.map((J)=>J.params),sanitize:_}),query:Qt(u.query,{modules:H,dynamic:N,models:A,normalize:O,coerce:!0,additionalCoerce:VC(),validators:c.map((J)=>J.query),sanitize:_}),cookie:te(),response:Rk(u.response,{modules:H,dynamic:N,models:A,normalize:O,validators:c.map((J)=>J.response),sanitize:_})}:{createBody(){return this.body?this.body:this.body=Qt(u.body,{modules:H,dynamic:N,models:A,normalize:O,additionalCoerce:(()=>{let J=JC(u.body,A,H);return J&&F in J&&($n("File",J)||$n("Files",J))?zC():Zy()})(),validators:c.map((J)=>J.body),sanitize:_})},createHeaders(){return this.headers?this.headers:this.headers=Qt(u.headers,{modules:H,dynamic:N,models:A,normalize:O,additionalProperties:!O,coerce:!0,additionalCoerce:bd(),validators:c.map((J)=>J.headers),sanitize:_})},createParams(){return this.params?this.params:this.params=Qt(u.params,{modules:H,dynamic:N,models:A,normalize:O,coerce:!0,additionalCoerce:bd(),validators:c.map((J)=>J.params),sanitize:_})},createQuery(){return this.query?this.query:this.query=Qt(u.query,{modules:H,dynamic:N,models:A,normalize:O,coerce:!0,additionalCoerce:VC(),validators:c.map((J)=>J.query),sanitize:_})},createCookie(){return this.cookie?this.cookie:this.cookie=te()},createResponse(){return this.response?this.response:this.response=Rk(u.response,{modules:H,dynamic:N,models:A,normalize:O,validators:c.map((J)=>J.response),sanitize:_})}}};(l.body||l.cookie||l.headers||l.params||l.query||l.response)&&(o=Bs(o,l)),o.tags&&(o.detail?o.detail.tags=o.tags:o.detail={tags:o.tags}),Je(this.config.detail)&&(o.detail=wn(Object.assign({},this.config.detail),o.detail));let m=Je(this.event)?Bs(this.event,lC(o)):{...X7(lC(o))};if(c.length&&Object.assign(m,{standaloneValidator:c}),this.config.aot===!1){let A=p();this.router.dynamic.add(t,n,{validator:A,hooks:m,content:o?.type,handle:r,route:n});let N=od(n,{dynamic:!0});if(n!==N&&this.router.dynamic.add(t,N,{validator:A,hooks:m,content:o?.type,handle:r,route:n}),!this.config.strictPath){let O=rd(n);this.router.dynamic.add(t,O,{validator:A,hooks:m,content:o?.type,handle:r,route:n});let H=od(O);O!==H&&this.router.dynamic.add(t,O,{validator:A,hooks:m,content:o?.type,handle:r,route:n})}this.router.history.push({method:t,path:n,composed:null,handler:r,compile:void 0,hooks:m});return}let h=this["~adapter"].handler,g=typeof r!="function"?()=>{let A=h.createNativeStaticHandler?.(r,m,{headers:Object.assign({},this.setHeaders)});return A instanceof Promise?A.then((N)=>{if(N)return N}):A?.()}:void 0,y=this.config.nativeStaticResponse===!0,b=(A)=>{!y||!g||(Jx?this.router.response[A]?this.router.response[A][t]=g():this.router.response[A]={[t]:g()}:this.router.response[A]=g())};b(n);let S,P=()=>{if(S)return S;let A=tH({app:this,path:n,method:t,hooks:m,validator:p(),handler:typeof r!="function"&&typeof h.createStaticHandler!="function"?()=>r:r,allowMeta:a,inference:this.inference});return this.router.history[T]&&(S=this.router.history[T].composed=A),A},E;if(`${t}_${n}`in this.routeTree)for(let A=0;A<this.router.history.length;A++){let N=this.router.history[A];if(N.path===n&&N.method===t){E=A;break}}else this.routeTree[`${t}_${n}`]=this.router.history.length;let T=E??this.router.history.length,I=this.router.history,v=d?P():(A)=>S?S(A):(I[T].composed=P())(A);E!==void 0?this.router.history[E]=Object.assign({method:t,path:n,composed:v,compile:P,handler:r,hooks:m},c.length?{standaloneValidators:c}:void 0,o.webSocket?{websocket:o.websocket}:void 0):this.router.history.push(Object.assign({method:t,path:n,composed:v,compile:P,handler:r,hooks:m},o.webSocket?{websocket:o.websocket}:void 0));let x={handler:d?I[T].composed:void 0,compile(){return this.handler=P()}},R=this.router.static,C=n.indexOf(":")===-1&&n.indexOf("*")===-1;if(t==="WS"){if(C){n in R?R[n][t]=T:R[n]={[t]:T};return}this.router.http.add("WS",n,x),this.config.strictPath||this.router.http.add("WS",rd(n),x);let A=od(n,{dynamic:!0});n!==A&&this.router.http.add("WS",A,x);return}if(C)n in R?R[n][t]=T:R[n]={[t]:T},this.config.strictPath||b(rd(n));else{if(this.router.http.add(t,n,x),!this.config.strictPath){let N=rd(n);b(N),this.router.http.add(t,N,x)}let A=od(n,{dynamic:!0});n!==A&&(this.router.http.add(t,A,x),b(A))}}headers(t){return t?(this.setHeaders||(this.setHeaders={}),this.setHeaders=wn(this.setHeaders,t),this):this}onStart(t){return this.on("start",t),this}onRequest(t){return this.on("request",t),this}onParse(t,n){return n?this.on(t,"parse",n):typeof t=="string"?this.on("parse",this["~parser"][t]):this.on("parse",t)}parser(t,n){return this["~parser"][t]=n,this}onTransform(t,n){return n?this.on(t,"transform",n):this.on("transform",t)}resolve(t,n){n||(n=t,t={as:"local"});let r={subType:"resolve",fn:n};return this.onBeforeHandle(t,r)}mapResolve(t,n){n||(n=t,t={as:"local"});let r={subType:"mapResolve",fn:n};return this.onBeforeHandle(t,r)}onBeforeHandle(t,n){return n?this.on(t,"beforeHandle",n):this.on("beforeHandle",t)}onAfterHandle(t,n){return n?this.on(t,"afterHandle",n):this.on("afterHandle",t)}mapResponse(t,n){return n?this.on(t,"mapResponse",n):this.on("mapResponse",t)}onAfterResponse(t,n){return n?this.on(t,"afterResponse",n):this.on("afterResponse",t)}trace(t,n){n||(n=t,t={as:"local"}),Array.isArray(n)||(n=[n]);for(let r of n)this.on(t,"trace",V9(r));return this}error(t,n){switch(typeof t){case"string":return n.prototype[id]=t,this.definitions.error[t]=n,this;case"function":return this.definitions.error=t(this.definitions.error),this}for(let[r,o]of Object.entries(t))o.prototype[id]=r,this.definitions.error[r]=o;return this}onError(t,n){return n?this.on(t,"error",n):this.on("error",t)}onStop(t){return this.on("stop",t),this}on(t,n,r){let o;switch(typeof t){case"string":o=t,r=n;break;case"object":o=n,!Array.isArray(n)&&typeof n=="object"&&(r=n);break}Array.isArray(r)?r=bn(r):typeof r=="function"?r=[{fn:r}]:r=[r];let i=r;for(let s of i)s.scope=typeof t=="string"?"local":t?.as??"local",(o==="resolve"||o==="derive")&&(s.subType=o);o!=="trace"&&(this.inference=fd({[o]:i.map((s)=>s.fn)},this.inference,this.config.sucrose));for(let s of i){let a=Q7(s,"global",{skipIfHasType:!0});switch((this.config.name||this.config.seed)&&(a.checksum=Wa(this.config.name+JSON.stringify(this.config.seed))),o){case"start":this.event.start??=[],this.event.start.push(a);break;case"request":this.event.request??=[],this.event.request.push(a);break;case"parse":this.event.parse??=[],this.event.parse.push(a);break;case"transform":this.event.transform??=[],this.event.transform.push(a);break;case"derive":this.event.transform??=[],this.event.transform.push(bn(a,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(a);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(bn(a,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(a);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(a);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(a);break;case"trace":this.event.trace??=[],this.event.trace.push(a);break;case"error":this.event.error??=[],this.event.error.push(a);break;case"stop":this.event.stop??=[],this.event.stop.push(a);break}}return this}as(t){return Ga(this.event.parse,t),Ga(this.event.transform,t),Ga(this.event.beforeHandle,t),Ga(this.event.afterHandle,t),Ga(this.event.mapResponse,t),Ga(this.event.afterResponse,t),Ga(this.event.trace,t),Ga(this.event.error,t),t==="scoped"?(this.validator.scoped=$m(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null&&(this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null)):t==="global"&&(this.validator.global=$m(this.validator.global,$m(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null&&(this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null),this.standaloneValidator.scoped!==null&&(this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null)),this}group(t,n,r){let o=new e({...this.config,prefix:""});o.singleton={...this.singleton},o.definitions={...this.definitions},o.getServer=()=>this.getServer(),o.inference=_x(this.inference),o.extender={...this.extender},o["~parser"]=this["~parser"],o.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let i=typeof n=="object",s=(i?r:n)(o);return this.singleton=wn(this.singleton,o.singleton),this.definitions=wn(this.definitions,o.definitions),s.event.request?.length&&(this.event.request=[...this.event.request||[],...s.event.request||[]]),s.event.mapResponse?.length&&(this.event.mapResponse=[...this.event.mapResponse||[],...s.event.mapResponse||[]]),this.model(s.definitions.type),Object.values(o.router.history).forEach(({method:a,path:c,handler:l,hooks:u})=>{if(c=(i?"":this.config.prefix??"")+t+c,i){let{body:d,headers:p,query:m,params:h,cookie:g,response:y,...b}=n,S=u;this.applyMacro(b);let P=d||p||m||h||g||y;this.add(a,c,l,Bs(b,{...S||{},error:S.error?Array.isArray(S.error)?[...S.error??[],...s.event.error??[]]:[S.error,...s.event.error??[]]:s.event.error,standaloneValidator:b.standaloneValidator||S.standaloneValidator||P?[...b.standaloneValidator??[],...S.standaloneValidator??[],...P?[{body:d,headers:p,query:m,params:h,cookie:g,response:y}]:[]]:void 0}),void 0)}else this.add(a,c,l,Bs(u,{error:s.event.error}),{skipPrefix:!0})}),this}guard(t,n){if(!n){if(typeof t=="object"){this.applyMacro(t),t.detail&&(this.config.detail?this.config.detail=wn(Object.assign({},this.config.detail),t.detail):this.config.detail=t.detail),t.tags&&(this.config.detail?this.config.detail.tags=t.tags:this.config.detail={tags:t.tags});let i=t.as??"local";if(t.schema==="standalone"){this.standaloneValidator[i]||(this.standaloneValidator[i]=[]);let s=t?.response?typeof t.response=="string"||F in t.response||"~standard"in t.response?{200:t.response}:t?.response:void 0;this.standaloneValidator[i].push({body:t.body,headers:t.headers,params:t.params,query:t.query,response:s,cookie:t.cookie})}else this.validator[i]={body:t.body??this.validator[i]?.body,headers:t.headers??this.validator[i]?.headers,params:t.params??this.validator[i]?.params,query:t.query??this.validator[i]?.query,response:t.response??this.validator[i]?.response,cookie:t.cookie??this.validator[i]?.cookie};return t.parse&&this.on({as:i},"parse",t.parse),t.transform&&this.on({as:i},"transform",t.transform),t.derive&&this.on({as:i},"derive",t.derive),t.beforeHandle&&this.on({as:i},"beforeHandle",t.beforeHandle),t.resolve&&this.on({as:i},"resolve",t.resolve),t.afterHandle&&this.on({as:i},"afterHandle",t.afterHandle),t.mapResponse&&this.on({as:i},"mapResponse",t.mapResponse),t.afterResponse&&this.on({as:i},"afterResponse",t.afterResponse),t.error&&this.on({as:i},"error",t.error),this}return this.guard({},t)}let r=new e({...this.config,prefix:""});r.singleton={...this.singleton},r.definitions={...this.definitions},r.inference=_x(this.inference),r.extender={...this.extender},r.getServer=()=>this.getServer();let o=n(r);if(this.singleton=wn(this.singleton,r.singleton),this.definitions=wn(this.definitions,r.definitions),o.getServer=()=>this.server,o.event.request?.length&&(this.event.request=[...this.event.request||[],...o.event.request||[]]),o.event.mapResponse?.length&&(this.event.mapResponse=[...this.event.mapResponse||[],...o.event.mapResponse||[]]),this.model(o.definitions.type),Object.values(r.router.history).forEach(({method:i,path:s,handler:a,hooks:c})=>{let{body:l,headers:u,query:d,params:p,cookie:m,response:h,...g}=t,y=l||u||d||p||m||h;this.add(i,s,a,Bs(g,{...c||{},error:c.error?Array.isArray(c.error)?[...c.error??[],...o.event.error??[]]:[c.error,...o.event.error??[]]:o.event.error,standaloneValidator:y?[...c.standaloneValidator??[],{body:l,headers:u,query:d,params:p,cookie:m,response:h}]:c.standaloneValidator}))}),r.promisedModules.size>0){let i=r.router.history.length;for(let s of r.promisedModules.promises)this.promisedModules.add(s.then(()=>{let{body:a,headers:c,query:l,params:u,cookie:d,response:p,...m}=t,h=a||c||l||u||d||p,g=i;i=r.router.history.length;for(let y=g;y<r.router.history.length;y++){let{method:b,path:S,handler:P,hooks:E}=r.router.history[y];this.add(b,S,P,Bs(m,{...E||{},error:E.error?Array.isArray(E.error)?[...E.error??[],...o.event.error??[]]:[E.error,...o.event.error??[]]:o.event.error,standaloneValidator:h?[...E.standaloneValidator??[],{body:a,headers:c,query:l,params:u,cookie:d,response:p}]:E.standaloneValidator}))}}))}return this}use(t){if(!t)return this;if(Array.isArray(t)){let n=this;for(let r of t)n=n.use(r);return n}return t instanceof Promise?(this.promisedModules.add(t.then((n)=>{if(typeof n=="function")return n(this);if(n instanceof e)return this._use(n).compile();if(n.constructor?.name==="Elysia")return this._use(n).compile();if(typeof n.default=="function")return n.default(this);if(n.default instanceof e)return this._use(n.default);if(n.constructor?.name==="Elysia")return this._use(n.default);if(n.constructor?.name==="_Elysia")return this._use(n.default);try{return this._use(n.default)}catch(r){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),r}}).then((n)=>(n&&typeof n.compile=="function"&&n.compile(),n))),this):this._use(t)}propagatePromiseModules(t){if(t.promisedModules.size<=0)return this;for(let n of t.promisedModules.promises)this.promisedModules.add(n.then((r)=>{if(!r)return;let o=this._use(r);return o instanceof Promise?o.then((i)=>{i?i.compile():r.compile()}):r.compile()}));return this}_use(t){if(typeof t=="function"){let o=t(this);return o instanceof Promise?(this.promisedModules.add(o.then((i)=>{if(i instanceof e){i.getServer=()=>this.getServer(),i.getGlobalRoutes=()=>this.getGlobalRoutes(),i.getGlobalDefinitions=()=>this.getGlobalDefinitions(),i.model(this.definitions.type),i.error(this.definitions.error);for(let{method:s,path:a,handler:c,hooks:l}of Object.values(i.router.history))this.add(s,a,c,l,void 0);return i===this?void 0:(this.propagatePromiseModules(i),i)}return typeof i=="function"?i(this):typeof i.default=="function"?i.default(this):this._use(i)}).then((i)=>(i&&typeof i.compile=="function"&&i.compile(),i))),this):o}this.propagatePromiseModules(t);let n=t.config.name,r=t.config.seed;if(t.getParent=()=>this,t.getServer=()=>this.getServer(),t.getGlobalRoutes=()=>this.getGlobalRoutes(),t.getGlobalDefinitions=()=>this.getGlobalDefinitions(),t.standaloneValidator?.scoped&&(this.standaloneValidator.local?this.standaloneValidator.local=this.standaloneValidator.local.concat(t.standaloneValidator.scoped):this.standaloneValidator.local=t.standaloneValidator.scoped),t.standaloneValidator?.global&&(this.standaloneValidator.global?this.standaloneValidator.global=this.standaloneValidator.global.concat(t.standaloneValidator.global):this.standaloneValidator.global=t.standaloneValidator.global),Je(t["~parser"])&&(this["~parser"]={...t["~parser"],...this["~parser"]}),t.setHeaders&&this.headers(t.setHeaders),n){n in this.dependencies||(this.dependencies[n]=[]);let o=r!==void 0?Wa(n+JSON.stringify(r)):0;this.dependencies[n].some(({checksum:i})=>o===i)||(this.extender.macro={...this.extender.macro,...t.extender.macro},this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(t.extender.higherOrderFunctions))}else Je(t.extender.macro)&&(this.extender.macro={...this.extender.macro,...t.extender.macro}),t.extender.higherOrderFunctions.length&&(this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(t.extender.higherOrderFunctions));if(t.extender.higherOrderFunctions.length){pC(this.extender.higherOrderFunctions);let o=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let s=this.extender.higherOrderFunctions[i];s.checksum&&(o.includes(s.checksum)&&(this.extender.higherOrderFunctions.splice(i,1),i--),o.push(s.checksum))}o.length=0}this.inference=hk(this.inference,t.inference),Je(t.singleton.decorator)&&this.decorate(t.singleton.decorator),Je(t.singleton.store)&&this.state(t.singleton.store),Je(t.definitions.type)&&this.model(t.definitions.type),Je(t.definitions.error)&&this.error(t.definitions.error),Je(t.extender.macro)&&(this.extender.macro={...this.extender.macro,...t.extender.macro});for(let{method:o,path:i,handler:s,hooks:a}of Object.values(t.router.history))this.add(o,i,s,a);if(n){n in this.dependencies||(this.dependencies[n]=[]);let o=r!==void 0?Wa(n+JSON.stringify(r)):0;if(this.dependencies[n].some(({checksum:i})=>o===i))return this;this.dependencies[n].push(this.config?.analytic?{name:t.config.name,seed:t.config.seed,checksum:o,dependencies:t.dependencies,stack:t.telemetry?.stack,routes:t.router.history,decorators:t.singleton,store:t.singleton.store,error:t.definitions.error,derive:t.event.transform?.filter((i)=>i?.subType==="derive").map((i)=>({fn:i.toString(),stack:Error().stack??""})),resolve:t.event.transform?.filter((i)=>i?.subType==="resolve").map((i)=>({fn:i.toString(),stack:Error().stack??""}))}:{name:t.config.name,seed:t.config.seed,checksum:o,dependencies:t.dependencies}),Je(t.event)&&(this.event=iC(this.event,sC(t.event),o))}else Je(t.event)&&(this.event=iC(this.event,sC(t.event)));return t.validator.global&&(this.validator.global=Bs(this.validator.global,{...t.validator.global})),t.validator.scoped&&(this.validator.local=Bs(this.validator.local,{...t.validator.scoped})),this}macro(t,n){if(typeof t=="string"&&!n)throw Error("Macro function is required");return typeof t=="string"?this.extender.macro[t]=n:this.extender.macro={...this.extender.macro,...t},this}applyMacro(t,n=t,{iteration:r=0,applied:o={}}={}){if(r>=16)return;let i=this.extender.macro;for(let[s,a]of Object.entries(n)){if(!(s in i))continue;let c=typeof i[s]=="function"?i[s](a):i[s];if(!c||typeof i[s]=="object"&&a===!1)return;let l=Wa(s+JSON.stringify(c.seed??a));if(!(l in o)){o[l]=!0;for(let[u,d]of Object.entries(c))if(u!=="seed"){if(u in tj){Z7(t,u,d),delete t[s];continue}if(u==="introspect"){d?.(t),delete t[s];continue}if(u==="detail"){t.detail||(t.detail={}),t.detail=wn(t.detail,d,{mergeArray:!0}),delete t[s];continue}if(u in i){this.applyMacro(t,{[u]:d},{applied:o,iteration:r+1}),delete t[s];continue}switch((u==="derive"||u==="resolve")&&typeof d=="function"&&(d={fn:d,subType:u}),typeof t[u]){case"function":t[u]=[t[u],d];break;case"object":Array.isArray(t[u])?t[u].push(d):t[u]=[t[u],d];break;case"undefined":t[u]=d;break}delete t[s]}}}}mount(t,n,r){if(t instanceof e||typeof t=="function"||t.length===0||t==="/"){let a=typeof t=="function"?t:t instanceof e?t.compile().fetch:n instanceof e?n.compile().fetch:typeof n=="function"?n:(()=>{throw Error("Invalid handler")})(),c=({request:l,path:u})=>a(new Request(Gx(l.url,u),l));return this.route("ALL","/*",c,{parse:"none",...r,detail:{...r?.detail,hide:!0},config:{mount:a}}),this}let o=n instanceof e?n.compile().fetch:typeof n=="function"?n:(()=>{throw Error("Invalid handler")})(),i=(typeof t=="string"&&this.config.prefix?this.config.prefix+t:t).length-(t.endsWith("*")?1:0),s=({request:a,path:c})=>o(new Request(Gx(a.url,c.slice(i)||"/"),a));return this.route("ALL",t,s,{parse:"none",...r,detail:{...r?.detail,hide:!0},config:{mount:o}}),this.route("ALL",t+(t.endsWith("/")?"*":"/*"),s,{parse:"none",...r,detail:{...r?.detail,hide:!0},config:{mount:o}}),this}get(t,n,r){return this.add("GET",t,n,r),this}post(t,n,r){return this.add("POST",t,n,r),this}put(t,n,r){return this.add("PUT",t,n,r),this}patch(t,n,r){return this.add("PATCH",t,n,r),this}delete(t,n,r){return this.add("DELETE",t,n,r),this}options(t,n,r){return this.add("OPTIONS",t,n,r),this}all(t,n,r){return this.add("ALL",t,n,r),this}head(t,n,r){return this.add("HEAD",t,n,r),this}connect(t,n,r){return this.add("CONNECT",t,n,r),this}route(t,n,r,o){return this.add(t.toUpperCase(),n,r,o,o?.config),this}ws(t,n){return this["~adapter"].ws?this["~adapter"].ws(this,t,n):console.warn("Current adapter doesn't support WebSocket"),this}state(t,n,r){n===void 0?(r=t,t={as:"append"},n=""):r===void 0&&(typeof t=="string"?(r=n,n=t,t={as:"append"}):typeof t=="object"&&(r=n,n=""));let{as:o}=t;if(typeof n!="string")return this;switch(typeof r){case"object":return!r||!Je(r)?this:n?((n in this.singleton.store)?this.singleton.store[n]=wn(this.singleton.store[n],r,{override:o==="override"}):this.singleton.store[n]=r,this):r===null?this:(this.singleton.store=wn(this.singleton.store,r,{override:o==="override"}),this);case"function":return n?(o==="override"||!(n in this.singleton.store))&&(this.singleton.store[n]=r):this.singleton.store=r(this.singleton.store),this;default:return(o==="override"||!(n in this.singleton.store))&&(this.singleton.store[n]=r),this}}decorate(t,n,r){n===void 0?(r=t,t={as:"append"},n=""):r===void 0&&(typeof t=="string"?(r=n,n=t,t={as:"append"}):typeof t=="object"&&(r=n,n=""));let{as:o}=t;if(typeof n!="string")return this;switch(typeof r){case"object":return n?((n in this.singleton.decorator)?this.singleton.decorator[n]=wn(this.singleton.decorator[n],r,{override:o==="override"}):this.singleton.decorator[n]=r,this):r===null?this:(this.singleton.decorator=wn(this.singleton.decorator,r,{override:o==="override"}),this);case"function":return n?(o==="override"||!(n in this.singleton.decorator))&&(this.singleton.decorator[n]=r):this.singleton.decorator=r(this.singleton.decorator),this;default:return(o==="override"||!(n in this.singleton.decorator))&&(this.singleton.decorator[n]=r),this}}derive(t,n){n||(n=t,t={as:"local"});let r={subType:"derive",fn:n};return this.onTransform(t,r)}model(t,n){let r=(o)=>{let i={};for(let s in o)"~standard"in o[s]||(i[s]=o[s]);return i};switch(typeof t){case"object":let o={},i=Object.entries(t);if(!i.length)return this;for(let[c,l]of i)c in this.definitions.type||("~standard"in l?this.definitions.type[c]=l:(o[c]=this.definitions.type[c]=l,o[c].$id??=`#/components/schemas/${c}`));return this.definitions.typebox=X.Module({...this.definitions.typebox.$defs,...o}),this;case"function":let s=t(this.definitions.type);return this.definitions.type=s,this.definitions.typebox=X.Module(r(s)),this;case"string":if(!n)break;if(this.definitions.type[t]=n,"~standard"in n)return this;let a={...n,id:n.$id??`#/components/schemas/${t}`};return this.definitions.typebox=X.Module({...this.definitions.typebox.$defs,...a}),this}return n?(this.definitions.type[t]=n,("~standard"in n)?this:(this.definitions.typebox=X.Module({...this.definitions.typebox.$defs,[t]:n}),this)):this}Ref(t){return X.Ref(t)}mapDerive(t,n){n||(n=t,t={as:"local"});let r={subType:"mapDerive",fn:n};return this.onTransform(t,r)}affix(t,n,r){if(r==="")return this;let o=["_","-"," "],i=(l)=>l[0].toUpperCase()+l.slice(1),s=t==="prefix"?(l,u)=>o.includes(l.at(-1)??"")?l+u:l+i(u):o.includes(r.at(-1)??"")?(l,u)=>u+l:(l,u)=>u+i(l),a=(l)=>{let u={};switch(l){case"decorator":for(let d in this.singleton.decorator)u[s(r,d)]=this.singleton.decorator[d];this.singleton.decorator=u;break;case"state":for(let d in this.singleton.store)u[s(r,d)]=this.singleton.store[d];this.singleton.store=u;break;case"model":for(let d in this.definitions.type)u[s(r,d)]=this.definitions.type[d];this.definitions.type=u;break;case"error":for(let d in this.definitions.error)u[s(r,d)]=this.definitions.error[d];this.definitions.error=u;break}},c=Array.isArray(n)?n:[n];for(let l of c.some((u)=>u==="all")?["decorator","state","model","error"]:c)a(l);return this}prefix(t,n){return this.affix("prefix",t,n)}suffix(t,n){return this.affix("suffix",t,n)}compile(){return this["~adapter"].beforeCompile?.(this),this["~adapter"].isWebStandard?(this._handle=this.config.aot?Ck(this):rM(this),Object.defineProperty(this,"fetch",{value:this._handle,configurable:!0,writable:!0}),typeof this.server?.reload=="function"&&this.server.reload({...this.server||{},fetch:this.fetch}),this):(typeof this.server?.reload=="function"&&this.server.reload(this.server||{}),this._handle=Ck(this),this)}get fetch(){let t=this.config.aot?Ck(this):rM(this);return Object.defineProperty(this,"fetch",{value:t,configurable:!0,writable:!0}),t}get modules(){return this.promisedModules}},pi=cMe;var cf={name:"@kabmo-labs/kabmo",version:"0.57.0",description:"Web console and diagnostic workbench for AI coding agents: Elysia + Preact on Bun.",license:"MIT",author:"Wijanarko Putra Rajeb <wijanarko.rajeb@gmail.com>",type:"module",engines:{bun:">=1.4.0"},publishConfig:{access:"public"},bin:{kabmo:"./src/cli/kabmo.js"},repository:{type:"git",url:"git+https://github.com/kabmo-labs/kabmo.git"},homepage:"https://github.com/kabmo-labs/kabmo#readme",bugs:{url:"https://github.com/kabmo-labs/kabmo/issues"},keywords:["kabmo","coding-agent","agent","console","elysia","preact","bun"],files:["src","extensions","index.html","bunfig.toml","public","tsconfig.json","marketplace","dist/client"],scripts:{dev:"bun run --hot src/server/index.ts --kabmo-server","dev:lan":"HOST=0.0.0.0 bun run --hot src/server/index.ts --kabmo-server",build:"bun run scripts/build-client.ts","editor:themes":"bun run scripts/editor-themes.mjs","icons:tints":"bun run scripts/icon-tints.mjs","icons:tints:check":"bun run scripts/icon-tints.mjs --check","tray:icons":"bun run scripts/tray-icon.mjs","tray:icons:check":"bun run scripts/tray-icon.mjs --check","editor:themes:check":"bun run scripts/editor-themes.mjs --check","omp:schema":"bun run scripts/omp-schema.mjs","omp:schema:check":"bun run scripts/omp-schema.mjs --check",start:"NODE_ENV=production bun run src/server/index.ts --kabmo-server",typecheck:"tsc",clean:"rm -rf dist",lint:"tsc --noEmit","check:fast":"bun check --no-script",test:"bun test","test:e2e":"playwright test --config tests/e2e/playwright.config.ts","readme:media":"bun run scripts/readme-media.ts","shell:wordmark":"bun run scripts/shell-wordmark.mjs","shell:docs":"bun run scripts/shell-document-types.mjs --write","shell:docs:check":"bun run scripts/shell-document-types.mjs --check","typecheck:e2e":"tsc --noEmit -p tests/e2e","typecheck:consumer":"tsc --noEmit -p tsconfig.consumer.json","publish:plugins":"bash .github/scripts/publish-plugin-packages.sh packages/kabmo-sdk packages/kabmo-ui"},dependencies:{"@codemirror/autocomplete":"6.20.4","@codemirror/commands":"6.11.1","@codemirror/language":"6.13.1","@codemirror/legacy-modes":"^6.5.5","@codemirror/lint":"^6.9.7","@codemirror/merge":"6.12.3","@codemirror/search":"6.7.2","@codemirror/state":"6.7.6","@codemirror/view":"6.43.15","@dskripchenko/drawio":"^0.1.0","@fontsource/fira-code":"^5.3.0","@shikijs/langs":"^4.4.3","@shikijs/themes":"^4.4.3","@tailwindcss/postcss":"^4.1.14",dompurify:"^3.4.15",elysia:"^1.4.30","ghostty-web":"0.4.0-next.21.g640db46","jsonc-parser":"^3.3.1",katex:"^0.18.7","lucide-preact":"^1.47.0",mammoth:"^1.13.0",marked:"^18.0.11","marked-linkify-it":"^4.0.2",mermaid:"^12.0.0",postcss:"^8.5.16",preact:"^10.29.8","qrcode-generator":"^2.0.4",remend:"^1.3.1",ripgrep:"^0.3.1","sherpa-onnx-node":"^2.0.2",shiki:"^4.4.3","smol-toml":"^1.9.1",tailwindcss:"^4.1.14",xlsx:"https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",yaml:"^2.9.1","@kabmo-labs/kabmo-acp":"workspace:*","@kabmo-labs/kabmo-app-contracts":"workspace:*","@kabmo-labs/kabmo-auth":"workspace:*","@kabmo-labs/kabmo-bytes":"workspace:*","@kabmo-labs/kabmo-chat":"workspace:*","@kabmo-labs/kabmo-db":"workspace:*","@kabmo-labs/kabmo-format":"workspace:*","@kabmo-labs/kabmo-fs":"workspace:*","@kabmo-labs/kabmo-git":"workspace:*","@kabmo-labs/kabmo-guards":"workspace:*","@kabmo-labs/kabmo-harness":"workspace:*","@kabmo-labs/kabmo-http":"workspace:*","@kabmo-labs/kabmo-idle-reaper":"workspace:*","@kabmo-labs/kabmo-live-sessions":"workspace:*","@kabmo-labs/kabmo-mcp-contracts":"workspace:*","@kabmo-labs/kabmo-model-contracts":"workspace:*","@kabmo-labs/kabmo-omp":"workspace:*","@kabmo-labs/kabmo-paths":"workspace:*","@kabmo-labs/kabmo-platform":"workspace:*","@kabmo-labs/kabmo-process":"workspace:*","@kabmo-labs/kabmo-provider-contracts":"workspace:*","@kabmo-labs/kabmo-realtime-signals":"workspace:*","@kabmo-labs/kabmo-refresh-cadence":"workspace:*","@kabmo-labs/kabmo-rpc-lines":"workspace:*","@kabmo-labs/kabmo-runtime-flags":"workspace:*","@kabmo-labs/kabmo-sdk":"workspace:*","@kabmo-labs/kabmo-session":"workspace:*","@kabmo-labs/kabmo-settings":"workspace:*","@kabmo-labs/kabmo-ui":"workspace:*","@kabmo-labs/kabmo-workspace":"workspace:*","@kabmo-labs/kabmo-worktree":"workspace:*"},devDependencies:{"@playwright/test":"^1.64.0","@semantic-release/changelog":"^7.0.0","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/git":"^11.0.1","@semantic-release/github":"^12.0.10","@semantic-release/npm":"^13.2.0","@semantic-release/release-notes-generator":"^14.1.1","@types/bun":"1.4.4","@types/node":"^22.14.0","@types/qrcode-generator":"^0.0.16","bun-types":"1.4.4","conventional-changelog-conventionalcommits":"^9.3.1","happy-dom":"^20.14.5",jsqr:"^1.4.0","semantic-release":"^25.0.9",typescript:"~5.8.2"},overrides:{katex:"^0.18.7"},workspaces:["packages/*"],"$comment-workspaces":"Only `packages/*` are Bun workspaces. The native shells live in `apps/` and the sound and QR inputs in `assets/`; they have no package.json, so they are never installed, published or typechecked as libraries."};function Lk(e,t,n){let r=e.headers.get("if-none-match");if(r!==null){if(!t)return!1;let i=t.trim().replace(/^W\//,"");return r.split(",").some((s)=>s.trim().replace(/^W\//,"")===i)}let o=e.headers.get("if-modified-since");if(o&&n!==null){let i=Date.parse(o);if(!Number.isNaN(i))return Math.floor(n/1000)*1000<=i}return!1}import{brotliCompressSync as uMe,constants as dMe}from"zlib";function Fo(e){if(e.buffer instanceof ArrayBuffer)return e;return new Uint8Array(e)}var iM=1024,yH=/^(text\/|application\/(json|javascript|xml|wasm|svg))/,pMe=["zstd","br","gzip"];function bH(e){return yH.test(e)}function sM(e){if(!e)return null;for(let t of pMe)if(e.includes(t))return t;return null}function aM(e,t){if(t==="zstd")return Fo(Bun.zstdCompressSync(e,{level:3}));if(t==="br")return Fo(uMe(e,{params:{[dMe.BROTLI_PARAM_QUALITY]:4}}));return Fo(Bun.gzipSync(e,{level:6}))}async function qs(e,t){if(!t)return e;let n=e.headers.get("content-type")??"";if(n.includes("text/event-stream"))return e;if(!yH.test(n))return e;if(e.status===204||e.status===304)return e;let r=sM(t);if(!r)return e;let o=Fo(new Uint8Array(await e.arrayBuffer()));if(o.byteLength<iM)return mMe(e,o);let i=aM(o,r),s=new Headers(e.headers);return s.set("content-encoding",r),s.set("content-length",String(i.byteLength)),s.append("vary","accept-encoding"),new Response(i,{status:e.status,headers:s})}function mMe(e,t){return new Response(t,{status:e.status,headers:e.headers})}var Qa=Bun.env.NODE_ENV!=="production",SH="/_bun/",xH=["/_bun/client/","/_bun/asset/"],cM="/_dev-assets/",wH="no-cache";function kH(e){let t=e;for(let n of xH)t=t.replaceAll(n,cM+n.slice(SH.length));return t}function lM(e){if(!e.startsWith(cM))return null;let t=SH+e.slice(cM.length);return xH.some((n)=>t.startsWith(n))?t:null}async function vH(e,t,n,r={}){let o=lM(t);if(!o)return null;let i=await fetch(new URL(o,n),r),s=i.headers.get("content-type")??"";if(!i.ok||s.startsWith("text/html"))return new Response(`No dev asset at ${o}
667
667
  `,{status:404,headers:{"content-type":"text/plain; charset=utf-8"}});let a=new Uint8Array(await i.arrayBuffer()),c=`"${Bun.hash(a).toString(16)}"`;if(Lk(e,c,null))return new Response(null,{status:304,headers:{etag:c,"cache-control":wH}});return qs(new Response(a,{headers:{"content-type":s||"application/octet-stream","cache-control":wH,etag:c}}),e.headers.get("accept-encoding"))}var uM=Qa?(await import("@/../index.html")).default:null;function f(e,t={}){let n=new Headers(t.headers);if(!n.has("content-type"))n.set("content-type","application/json; charset=utf-8");return new Response(JSON.stringify(e),{status:t.status??200,headers:n})}var ee={"cache-control":"no-store"};function z(e,t,n={}){let r=[];if(e.loader)r.push({method:"GET",path:t,handler:e.loader});else if(e.action)r.push({method:"GET",path:t,handler:K});if(e.action)for(let o of n.mutating??["POST","PUT","PATCH","DELETE"])r.push({method:o,path:t,handler:e.action});return r}var K=()=>Vs();function Vs(){return new Response(JSON.stringify({error:"Method not allowed"}),{status:405,headers:{"content-type":"application/json; charset=utf-8"}})}async function $t(e){try{return{ok:!0,body:await e.json()}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}}function Pn(e,t){let n=e[t];return n?n:null}function Uo(e,t=500){return f({error:e instanceof Error?e.message:String(e)},{status:t})}async function fMe(e){if(e instanceof Response)return e;if(e instanceof ReadableStream)return new Response(e,{headers:{"content-type":"text/event-stream","cache-control":"no-cache"}});return new Response(JSON.stringify(e??null),{status:200,headers:{"content-type":"application/json; charset=utf-8"}})}function gMe(e){return async({request:t,params:n})=>{try{let r=await fMe(await e({request:t,params:n}));return await qs(r,t.headers.get("accept-encoding"))}catch(r){let o=r instanceof Error?r.message:String(r);return new Response(JSON.stringify({error:o}),{status:500,headers:{"content-type":"application/json; charset=utf-8"}})}}}function AH(e,t){let n=e;for(let{method:r,path:o,handler:i}of t){let s=gMe(i);if(r==="GET")n=n.get(o,s);else if(r==="POST")n=n.post(o,s);else if(r==="PUT")n=n.put(o,s);else if(r==="PATCH")n=n.patch(o,s);else n=n.delete(o,s)}return n}function ht(e,t,n){return[{method:"GET",path:t,handler:n??K},...["POST","PUT","PATCH","DELETE"].map((r)=>({method:r,path:t,handler:e}))]}import{existsSync as dM,realpathSync as hMe}from"fs";import{homedir as TH,tmpdir as sCt}from"os";import*as pn from"path";var EH="omp",yMe=".omp";function RH(){return Bun.env.PI_CONFIG_DIR||yMe}function Bo(){return pn.join(TH(),RH())}function pe(){let e=Bun.env.PI_CODING_AGENT_DIR;if(e)return pn.resolve(e);return pn.join(Bo(),"agent")}function IH(){let e=Bun.env.PI_CODING_AGENT_DIR;if(e)return pn.resolve(e)===pn.join(Bo(),"agent");return!0}function bMe(){if(process.platform!=="linux"&&process.platform!=="darwin")return;if(!IH())return;let e=Bun.env.XDG_DATA_HOME;if(!e)return;try{let t=pn.join(e,EH);return dM(t)?t:void 0}catch{return}}function wMe(e){let t=bMe();return pn.join(t??pe(),e)}function jo(){return wMe("sessions")}function PH(){return pn.join(pe(),"projects.json")}function CH(){if(process.platform!=="linux"&&process.platform!=="darwin")return Bo();if(!IH())return Bo();let e=Bun.env.XDG_DATA_HOME;if(!e)return Bo();try{let t=pn.join(e,EH);return dM(t)?t:Bo()}catch{return Bo()}}function MH(){return pn.join(CH(),"plugins")}function pM(){return pn.join(CH(),"marketplaces.json")}function OH(e){let t=TH(),n=RH(),r=pn.resolve(e);for(let o of[n,".git"]){let i=r;while(i!==t){if(dM(pn.join(i,o)))return pn.join(i,n,"plugins");let s=pn.dirname(i);if(s===i)break;i=s}}return pn.join(r,n,"plugins")}function xd(e){try{return hMe.native(e)}catch{return e}}async function Z(e){try{return await Bun.file(e).stat(),!0}catch{return!1}}function Ho(e){let t=xd(e);return t.replace(/\/+$/,"")||t}import fM from"fs";import*as Dk from"path";function w(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function xn(e){let t=[];for(let n of e.split(`
668
668
  `)){let r=n.trim();if(!r)continue;try{t.push(JSON.parse(r))}catch{}}return t}function NH(e){let t=e.endsWith("\\")?e.slice(0,-1):e;try{return JSON.parse(`"${t}"`)}catch{return t.replace(/\\n/g,`
669
669
  `).replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}}function Cn(e,t,n=0){let r=e.indexOf(`"${t}"`,n);if(r===-1)return;let o=e.indexOf(":",r+t.length+2);if(o===-1)return;let i=o+1;while(i<e.length){let c=e.charCodeAt(i);if(c!==32&&c!==9&&c!==10&&c!==13)break;i++}if(e.charCodeAt(i)!==34)return;let s=i+1,a=!1;for(let c=s;c<e.length;c++){let l=e.charCodeAt(c);if(a){a=!1;continue}if(l===92){a=!0;continue}if(l===34)return NH(e.slice(s,c))}return NH(e.slice(s))}function DH(e){let t=0,n=0;while(n<e.length){let r=e.indexOf('"type"',n);if(r===-1)break;let o=e.indexOf(":",r+6);if(o===-1)break;if(Cn(e,"type",r)==="message")t++;n=o+1}return t}function LH(e){if(e===void 0)return;return e.trim()?e:null}function SMe(e,t){if(e?.type!=="session"||typeof e.id!=="string")return;return{id:e.id,cwd:typeof e.cwd==="string"?e.cwd:void 0,title:t===null?void 0:t??(typeof e.title==="string"?e.title:void 0),parentSession:typeof e.parentSession==="string"?e.parentSession:void 0,timestamp:typeof e.timestamp==="string"?e.timestamp:void 0}}function xMe(e,t){if(Cn(e,"type")!=="session")return;let n=Cn(e,"id");if(!n)return;return{id:n,cwd:Cn(e,"cwd"),title:t===null?void 0:t??Cn(e,"title"),parentSession:Cn(e,"parentSession"),timestamp:Cn(e,"timestamp")}}function FH(e,t){let n=t[0],r=LH(n?.type==="title"&&typeof n.title==="string"?n.title:void 0),o=SMe(t[n?.type==="title"?1:0],r);if(o)return o;let i,s=!0;for(let a of e.split(/\r?\n/)){let c=a.trim();if(!c)continue;if(s&&Cn(c,"type")==="title"){i=LH(Cn(c,"title")),s=!1;continue}return xMe(c,i)}return}var mM=4096,kMe=16384,UH=1048576;async function BH(e,t){let n=Bun.file(e),r=await n.stat(),o=Math.min(t,r.size);return{text:o>0?await n.slice(0,o).text():"",size:r.size,mtime:new Date(r.mtimeMs),mtimeMs:r.mtimeMs}}var vMe={session_exit:!0};function AMe(e){let t,n,r,o=!1;try{let a=JSON.parse(e);if(w(a))o=!0,t=a.type,n=a.customType,r=a.timestamp}catch{}if(!o)r=Cn(e,"timestamp"),t=Cn(e,"type"),n=Cn(e,"customType");let i;if(typeof r==="number"&&Number.isFinite(r))i=new Date(r);else if(typeof r==="string"){let a=new Date(r);if(!Number.isNaN(a.getTime()))i=a}if(!i)return;let s=t==="custom"&&typeof n==="string"&&vMe[n]===!0;return{at:i,lifecycle:s}}async function jH(e,t,n){if(t<=0)return;let r=kMe;for(;;){let o=Math.max(0,t-r),i;if(t<=mM)i=n;else if(o===0)try{i=await Bun.file(e).text()}catch{return}else try{i=await Bun.file(e).slice(o-1).text()}catch{return}let s=i.split(`
@@ -1787,7 +1787,7 @@ ${$L.close}`}var fre=2000,gre=4000,hre=`
1787
1787
  send_at = excluded.send_at,
1788
1788
  updated_at = excluded.updated_at`,[crypto.randomUUID(),n,gE,l,i,o,o]),clearTimeout(KL().get(n)),KL().set(n,setTimeout(()=>{KL().delete(n),yre(n).catch((u)=>{console.error(`[sessions] could not deliver child outcomes to ${n}:`,u instanceof Error?u.message:u)})},fre))}async function $Ve(e){let t=await k(),n=await t.get("SELECT * FROM session_notices WHERE parent_session_id = ? AND coalesce_key = ?",[e,gE]);if(!n)return null;if((await t.run("DELETE FROM session_notices WHERE parent_session_id = ? AND coalesce_key = ?",[e,gE])).changes===0)return null;let o=JSON.parse(n.state);if(o.length===0)return null;let i=mre(o);return await MA(e,{text:i}),i}async function yre(e){if(await $Ve(e)===null)return;let n=await mE(e);if(!n){console.error(`[sessions] child outcomes for ${e} are queued but the session could not be resumed`);return}await w1(n)}async function bre(){let t=await(await k()).all("SELECT DISTINCT parent_session_id FROM session_notices");for(let n of t)await yre(n.parent_session_id).catch((r)=>{console.error(`[sessions] could not deliver a stranded child outcome to ${n.parent_session_id}:`,r instanceof Error?r.message:r)})}_Q(Ep);function wre(e,t){if(e.runAborted)return!0;return Array.isArray(t)&&t.some((n)=>{if(!n||typeof n!=="object"||Array.isArray(n))return!1;return n.stopReason==="aborted"})}function GL(e){if(e.role!=="assistant")return null;if(!e0(e))return null;let t=Js(e),n=t?.message?.trim();if(n){let o=t?.status;if(o===void 0||n.startsWith(String(o)))return n;return`${o} ${n}`}let r=t?.stopReason;return r?`The turn ended with ${r}.`:"The turn ended with an error."}function KVe(e){if(!Array.isArray(e))return null;for(let t of e){if(!t||typeof t!=="object"||Array.isArray(t))continue;let n=GL(t);if(n)return n}return null}function GVe(e,t){return e.retryFinalError??e.runFailure??KVe(t)??(e.retrySagaOpen?"The run ended while omp was still retrying a provider error.":null)}async function qVe(e,t,n,r){if(!e)return;if((await oK())[e]!=="stream")return;if(wre(t,n)){await Kn(e,"abort");return}await Kn(e,"finish",void 0,r)}function Sre(e,t){if(e.type!=="response"||e.success!==!1||e.command!=="prompt"||!t)return Promise.resolve();let n=typeof e.error==="string"?e.error:"Prompt failed";if(Bk.test(n))return Promise.resolve();return Ep({sessionId:t,status:"failed",failure:n}).catch((r)=>{console.error("[sessions] could not record a refused prompt:",r)})}function qL(e,t,n){if(!e.sessionId||e.runOutcomeReported)return Promise.resolve();return e.runOutcomeReported=!0,Ep({sessionId:e.sessionId,status:t,failure:n}).catch((r)=>{console.error("[sessions] could not record a child outcome:",r)})}function xre(e,t){let n=wre(e,t),r=n?null:GVe(e,t);if(e.sessionId)qVe(e.sessionId,e,t,r);let o=Promise.resolve();if(e.sessionId&&!e.runOutcomeReported)e.runOutcomeReported=!0,o=Ep({sessionId:e.sessionId,status:n?"interrupted":r?"failed":"completed",output:n?null:bp(t),...r?{failure:r}:{}}).catch((i)=>{console.error("[sessions] could not record a child outcome:",i)});if(!n)Rb(e,"settle"),zQ({host:e,messages:t}),CN(e);if(Y0(),Y("workspace-dirty"),e.sessionId)Y("session-data-dirty",e.sessionId);return yp(),o}function kre(e,t){if(t.type==="auto_retry_start")return e.retrySagaOpen=!0,e.retryFinalError=null,!0;if(t.type==="auto_retry_end")return e.retrySagaOpen=!1,e.retryFinalError=t.success===!1&&typeof t.finalError==="string"&&t.finalError.trim()?t.finalError.trim():null,!0;return!1}var VVe=IM;function vre(e){for(let t of VVe){if(!e.startsWith(t))continue;let n=e.slice(t.length).trim();try{let r=JSON.parse(n);if(r&&typeof r==="object"&&!Array.isArray(r))return{marker:t,payload:r}}catch{}return null}return null}function Are(e){let t=e.goal;if(!t||typeof t!=="object"||Array.isArray(t))return null;let n=t;if(typeof n.id!=="string"||typeof n.objective!=="string")return null;return n}function Tre(e){return e.enabled===!0}function Ere(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let t=e,n=Number(t.turn),r=Number(t.maxTurns);if(!Number.isInteger(n)||n<1)return null;if(!Number.isInteger(r)||r<1)return null;let o=typeof t.stopped==="string"?Vk.find((i)=>i===t.stopped):void 0;return o?{turn:n,maxTurns:r,stopped:o}:{turn:n,maxTurns:r}}function zVe(e,t){let n=t.message;if(n?.role==="assistant"&&n.stopReason==="aborted")e.runAborted=!0;if(n?.role==="assistant")e.runFailure=GL(n);if(n?.role==="user")Rb(e,"opening");else if(n?.role==="custom"&&n.customType===il)Rb(e,"opening")}function _Ve(e){if(Y("workspace-dirty"),Y("sidebar-activity"),e.sessionId)Y("session-data-dirty",e.sessionId)}function JVe(e,t){if(t.agentInvoked===!1&&(e.promptRunning||e.streaming))return!0;if(e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,SK(t,e))Ld(e.sessionId);return!1}function Rre(e,t){let n={suppressForward:!1};switch(t.type){case"agent_start":if(e.promptRunning=!0,e.streaming=!0,e.runAborted=!1,e.runFailure=null,e.runOutcomeReported=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,e.continuationGraceUntil=0,e.autoTitleRequested=!1,Ot(),e.sessionId)Kn(e.sessionId,"stream",e.runModel);e.syncRunModel();break;case"turn_start":if(e.sessionId)Kn(e.sessionId,"stream",e.runModel);break;case"message_start":if(e.sessionId)Kn(e.sessionId,"stream",e.runModel);break;case"message_end":zVe(e,t);break;case"tool_execution_end":_Ve(e);break;case"agent_end":if(t.isTerminal!==!1)e.streaming=!1,e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,e.continuationGraceUntil=0,Ot(),xre(e,t.messages);else e.continuationGraceUntil=Date.now()+YH;break;case"prompt_result":n.suppressForward=JVe(e,t);break;case"auto_compaction_start":case"manual_compaction_start":e.compacting=!0;break;case"auto_compaction_end":case"manual_compaction_end":e.compacting=!1,Ot();break;case"command_output":n.suppressForward=n2(e);break;case"auto_retry_start":case"auto_retry_end":kre(e,t);break;case"model_changed":e.syncRunModel();break;case"session_info_update":Ot(),yp();break;case"goal_updated":e.modeMirror.observe(t);break;case"extension_ui_request":{let r=t;if(r.method==="notify"){let o=vre(typeof r.message==="string"?r.message:"");if(o)e.modeMirror.observeMarker(o)}e.trackUiDialog(t);break}case"subagent_lifecycle":case"subagent_progress":case"subagent_event":e.observeSubagent(t,Date.now());break;case"response":{if(t.success===!1&&t.command==="prompt")e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,e.emit({type:"prompt_error",errorMessage:t.error??"Prompt failed"}),n.suppressForward=!0;break}}return n}function hE(e,t){e.streaming=t.isStreaming,e.compacting=t.isCompacting,e.adoptSessionIdentity(t);let n=!e.awaitingAgentStart||Date.now()>=e.awaitingAgentStartDeadline,r=e.promptDispatchPendingCount>0||e.awaitingAgentStart&&!n;if(t.isStreaming===!1&&t.isCompacting===!1&&!r&&Date.now()>=e.continuationGraceUntil)e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0;return{sessionId:t.sessionId,sessionFile:t.sessionFile??"",sessionName:t.sessionName,isStreaming:t.isStreaming,isPromptRunning:e.promptRunning,isBashRunning:e.bashRunning,isCompacting:t.isCompacting,autoCompactionEnabled:t.autoCompactionEnabled,autoRetryEnabled:t.autoRetryEnabled,interruptMode:t.interruptMode,steeringMode:t.steeringMode,followUpMode:t.followUpMode,model:t.model?{id:t.model.id,provider:t.model.provider,name:t.model.name,reasoning:t.model.reasoning,thinking:t.model.thinking?{efforts:t.model.thinking.efforts}:void 0}:void 0,messageCount:t.messageCount,queuedMessageCount:t.queuedMessageCount,contextUsage:t.contextUsage??null,systemPrompt:t.systemPrompt?.join(`
1789
1789
 
1790
- `)??"",thinkingLevel:t.thinkingLevel??"off",fastModeEnabled:t.fastModeEnabled??t.fastMode??e.fastModeEnabled,fastModeActive:t.fastModeActive,tokensPerSecond:t.tokensPerSecond??null,todoPhases:t.todoPhases??[]}}var YVe={btw:!0,plan:!0,goal:!0},XVe={settings:!0,setup:!0,providers:!0,"plan-review":!0,vibe:!0,"guided-goal":!0,loop:!0,queue:!0,collab:!0,join:!0,leave:!0,copy:!0,open:!0,local:!0,hotkeys:!0,extensions:!0,status:!0,agents:!0,git:!0,hub:!0,subagents:!0,branch:!0,rewind:!0,fork:!0,tree:!0,login:!0,logout:!0,new:!0,clear:!0,delete:!0,resume:!0,btw:!0,tan:!0,omfg:!0,cleanse:!0,debug:!0,exit:!0,restart:!0,skills:!0,live:!0,record:!0,pause:!0,quit:!0,q:!0};function Ire(e){let t=e.trimStart();if(!t.startsWith("/"))return null;let n=t.slice(1),r=n.search(/[\s:]/),o=r===-1?n:n.slice(0,r);return o?o.toLowerCase():null}function Pre(e){let t=Ire(e);if(t===null)return!1;if(YVe[t]===!0)return!1;return XVe[t]===!0}function Cre(e){return`\`/${Ire(e)??e.trim()}\` is available in the omp terminal only \u2014 it has no effect over the RPC bridge, so it was not sent.`}async function VL(e){if(e.isBusy())throw new Or(eW,"session_busy");throw await e.destroyAndWait(),new Or("The OMP session stopped responding and was reset.","session_unresponsive")}function zL(e){if(e.getPendingUiDialogs().length>0)throw new Or(ZH,"session_blocked_on_dialog")}function _L(e,t,n){if(typeof t!=="string"||!Pre(t))return!1;if(e.emit({type:"command_output",text:Cre(t)}),!n)e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,e.emit({type:"prompt_result",agentInvoked:!1}),Cg(e);return!0}async function Mre(e,t){if(e.restarting)throw new Or(QH,"session_restarting");if(!e.isAlive())throw Error("Session is no longer running");e.idle.reset();let n=t.type;if(sW.has(n)){let r=jk(t.images);if(r)throw Error(r)}switch(n){case"prompt":{if(e.bashRunning)throw Error("Cannot send a prompt while a shell command is running");if(_L(e,t.message,Boolean(t.streamingBehavior)))return null;await r2(e);let r=t.streamingBehavior,o=typeof t.message==="string"&&t.message.trimStart().startsWith("/"),i=!r&&!e.isRunning()&&Boolean(e.sessionId),s=i&&!o,a=()=>{if(s&&!e.streaming)Ld(e.sessionId)};if(!r&&!o){if(e.promptRunning=!0,e.promptDispatchPendingCount+=1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,e.continuationGraceUntil=0,s)Kn(e.sessionId,"stream",e.runModel)}try{let c=vd(t.images),l=await e.proc.sendCommand({type:"prompt",message:t.message,...c?{images:c}:{},...r?{streamingBehavior:r}:{}},Hk(t.images));if(l?.agentInvoked===!1&&!r){if(i)e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,a(),e.emit({type:"prompt_result",agentInvoked:!1}),Cg(e)}else if(!r&&l?.agentInvoked!==!1&&s)e.awaitingAgentStart=!0,e.awaitingAgentStartDeadline=Date.now()+XH,e.armAgentStartWatchdog?.()}catch(c){if(e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,a(),c instanceof ec)await VL(e);if(c instanceof ll&&Bk.test(c.message))throw e.streaming=!0,e.runSettle?.arm(),new Or(tW,"agent_busy");throw c}finally{if(!r&&!o)e.promptDispatchPendingCount=Math.max(0,e.promptDispatchPendingCount-1)}return null}case"abort":if(zL(e),await e.proc.sendCommand({type:"abort"}),e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,e.continuationGraceUntil=0,e.sessionId)Kn(e.sessionId,"abort");return null;case"force_reset":return await e.destroyAndWait(),null;case"get_state":try{let r=await e.proc.sendCommand({type:"get_state"},er);return hE(e,r)}catch(r){if(r instanceof ec)await VL(e);throw r}case"set_model":{let{provider:r,modelId:o}=t,i=await e.proc.sendCommand({type:"set_model",provider:r,modelId:o});return e.runModel={provider:i.provider,modelId:i.id},{id:i.id,provider:i.provider}}case"set_fast_mode":{let r=t.enabled===!0,o=await e.proc.sendCommand({type:"set_fast_mode",enabled:r});return e.fastModeEnabled=o?.enabled??r,{enabled:e.fastModeEnabled,active:o?.active??!1}}case"compact":try{e.compacting=!0;try{return await e.proc.sendCommand({type:"compact",...t.customInstructions?{customInstructions:t.customInstructions}:{}})}finally{e.compacting=!1}}finally{Ot()}case"abort_compaction":return await e.proc.sendCommand({type:"abort"}),null;case"set_session_name":{let r=t.name?.trim();if(!r)throw Error("Session name cannot be empty");return await e.proc.sendCommand({type:"set_session_name",name:r}),Ot(),null}case"get_commands":return await e.proc.sendCommand({type:"get_available_commands"});case"bash":{if(e.isRunning())throw Error("Cannot run a shell command while the session is busy");e.bashRunning=!0;try{return await e.proc.sendCommand({type:"bash",command:t.command})}finally{e.bashRunning=!1,Ot()}}case"extension_ui_response":{let{id:r,...o}=t;if(!r)throw Error("extension_ui_response requires an id");return e.proc.sendFrame({type:"extension_ui_response",id:r,...o}),e.resolvePendingUiDialog(r),null}case"steer":case"follow_up":{if(!e.isRunning())throw new Or("The session is idle \u2014 start a prompt first.","session_idle");if(_L(e,t.message,!0))return null;return await e.proc.sendCommand({type:n,message:t.message,...vd(t.images)?{images:vd(t.images)}:{}},SM),null}default:{if(nW.has(n)){if(n==="abort_and_prompt")return zL(e),await e.proc.sendCommand(t,SM)??null;let r=await e.proc.sendCommand(t);if(n==="set_thinking_level")Ot();return r??null}throw Error(`Unsupported command: ${n}`)}}}var Ore={completed:!0,failed:!0,aborted:!0};class JL{constructor(){this.lastSeen=new Map;this.keyByIndex=new Map}observe(e,t){if(e.type==="subagent_lifecycle"){let n=NK(e.payload);if(!n)return;if(Ore[n.status]===!0)this.forget(n.id);else this.mark(n.id,n.index>=0?n.index:void 0,t);return}if(e.type==="subagent_progress"){let n=LK(e.payload);if(!n)return;let r=n.index!==void 0&&n.index>=0?n.index:void 0,o=n.id??(r!==void 0?this.keyByIndex.get(r)??`idx:${r}`:void 0);if(o===void 0)return;if(n.status!==void 0&&Ore[n.status]===!0)this.forget(o);else this.mark(o,r,t);return}if(e.type==="subagent_event")for(let n of this.lastSeen.keys())this.lastSeen.set(n,t)}liveCount(e,t){for(let[n,r]of this.lastSeen)if(e-r>t)this.forget(n);return this.lastSeen.size}clear(){this.lastSeen.clear(),this.keyByIndex.clear()}mark(e,t,n){if(this.lastSeen.set(e,n),t===void 0)return;if(e!==`idx:${t}`)this.lastSeen.delete(`idx:${t}`);this.keyByIndex.set(t,e)}forget(e){this.lastSeen.delete(e);for(let[t,n]of this.keyByIndex)if(n===e)this.keyByIndex.delete(t)}}var Nre=new Set(["active","budget-limited"]);class YL{constructor(){this.goalEnabled=!1;this.goalRecord=null;this.goalContinuation=null;this.goalMaxTurns=null}observe(e){let{state:t,goal:n}=e,r=t?.goal?.status??n?.status;this.goalStatus=X0(r)?r:void 0,this.goalEnabled=t?.enabled===!0&&this.goalStatus!==void 0&&Nre.has(this.goalStatus)}observeMarker(e){if(qk(e.marker,"planStateMarker")){this.planEnabled=e.payload.enabled===!0;return}if(!qk(e.marker,"goalStateMarker"))return;let t=Are(e.payload);if(this.goalRecord=t,this.goalStatus=t&&X0(t.status)?t.status:void 0,this.goalEnabled=Tre(e.payload)&&this.goalStatus!==void 0&&Nre.has(this.goalStatus),"continuation"in e.payload)this.goalContinuation=e.payload.continuation===null?null:Ere(e.payload.continuation);let n=e.payload.maxTurns;if(typeof n==="number"&&Number.isInteger(n)&&n>0)this.goalMaxTurns=n}}class XL{#e;#t;#n;constructor(e,t){this.#e=null;this.#t=e,this.#n=t}arm(){if(this.stop(),!this.#t.awaitingAgentStart||!this.#t.sessionId)return;let e=Math.max(0,this.#t.awaitingAgentStartDeadline-Date.now());this.#e=setTimeout(()=>{if(this.#e=null,!this.#t.awaitingAgentStart||this.#t.streaming)return;this.#n()},e),this.#e.unref?.()}settleIfDone(){if(this.#e===null)return;if(!this.#t.awaitingAgentStart||this.#t.streaming)this.stop()}stop(){if(this.#e)clearTimeout(this.#e);this.#e=null}}var QVe=30000,ZVe=5000;class QL{#e;#t;#n;#r;#c;#i;#o;#a;constructor(e,t={}){this.#t=Date.now();this.#n=0;this.#r=!1;this.#c=null;this.#i=e,this.#o=t.silenceMs??QVe,this.#a=t.retrySlackMs??ZVe}noteFrame(e){if(this.#t=Date.now(),e.type==="auto_retry_start"){let t=typeof e.delayMs==="number"&&Number.isFinite(e.delayMs)?e.delayMs:0;this.#n=this.#t+Math.max(0,t)+this.#a}else if(e.type==="agent_start"||e.type==="agent_end")this.#n=0;this.#s()}async whenSettled(){await this.#c?.catch(()=>!1)}stop(){clearTimeout(this.#e),this.#e=void 0,this.#n=0}arm(){this.#s()}async reconcile(e){let t=this.#i;if(this.#r||!t.isAlive()||t.restarting||!t.sessionId)return!1;if(!t.isRunning()){if(t.subagents&&t.subagents.liveCount(Date.now(),Fk)>0)await this.#l();return this.stop(),!1}if(t.getPendingUiDialogs().length>0)return this.#s(),!1;if(Date.now()-this.#t<this.#o||Date.now()<this.#n)return this.#s(),!1;this.#r=!0;try{let n=await t.proc.sendCommand({type:"get_state"},er);if(n?.isSettled!==!0)return this.#s(),!1;if(t.bashRunning)return this.#s(),!1;return await this.#u(n),!0}catch{return this.#s(),!1}finally{this.#r=!1}}async#l(){if(this.#r)return;let e=this.#i.subagents;if(!e)return;this.#r=!0;try{if((await this.#i.proc.sendCommand({type:"get_state"},er))?.isSettled===!0)e.clear()}catch{}finally{this.#r=!1}}async#u(e){let t=this.#i,n=t.sessionId;if(hE(t,e),t.streaming=!1,t.promptRunning=!1,t.awaitingAgentStart=!1,t.awaitingAgentStartDeadline=0,t.continuationGraceUntil=0,this.stop(),n)Kn(n,"finish");t.emit({type:"agent_end",isTerminal:!0,messages:[]}),await qL(t,"interrupted","The run stopped reporting progress; open the session to read its output.")}#s(){if(clearTimeout(this.#e),this.#e=void 0,!this.#i.isRunning())return;let e=Math.max(this.#o,this.#n-Date.now()),t=setTimeout(()=>{this.#e=void 0,this.#c=this.reconcile("idle")},e);t.unref?.(),this.#e=t}}function Lre(e,t){if(!e.isAlive()||e.restarting)return Promise.resolve();let n=t.trim().split(`
1790
+ `)??"",thinkingLevel:t.thinkingLevel??"off",fastModeEnabled:t.fastModeEnabled??t.fastMode??e.fastModeEnabled,fastModeActive:t.fastModeActive,tokensPerSecond:t.tokensPerSecond??null,todoPhases:t.todoPhases??[]}}var YVe={btw:!0,plan:!0,goal:!0},XVe={settings:!0,setup:!0,providers:!0,"plan-review":!0,vibe:!0,"guided-goal":!0,loop:!0,queue:!0,collab:!0,join:!0,leave:!0,copy:!0,open:!0,local:!0,hotkeys:!0,extensions:!0,status:!0,agents:!0,git:!0,hub:!0,subagents:!0,branch:!0,rewind:!0,fork:!0,tree:!0,login:!0,logout:!0,new:!0,clear:!0,delete:!0,resume:!0,btw:!0,tan:!0,omfg:!0,cleanse:!0,debug:!0,exit:!0,restart:!0,schedule:!0,skills:!0,live:!0,record:!0,pause:!0,quit:!0,q:!0};function Ire(e){let t=e.trimStart();if(!t.startsWith("/"))return null;let n=t.slice(1),r=n.search(/[\s:]/),o=r===-1?n:n.slice(0,r);return o?o.toLowerCase():null}function Pre(e){let t=Ire(e);if(t===null)return!1;if(YVe[t]===!0)return!1;return XVe[t]===!0}function Cre(e){return`\`/${Ire(e)??e.trim()}\` is available in the omp terminal only \u2014 it has no effect over the RPC bridge, so it was not sent.`}async function VL(e){if(e.isBusy())throw new Or(eW,"session_busy");throw await e.destroyAndWait(),new Or("The OMP session stopped responding and was reset.","session_unresponsive")}function zL(e){if(e.getPendingUiDialogs().length>0)throw new Or(ZH,"session_blocked_on_dialog")}function _L(e,t,n){if(typeof t!=="string"||!Pre(t))return!1;if(e.emit({type:"command_output",text:Cre(t)}),!n)e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,e.emit({type:"prompt_result",agentInvoked:!1}),Cg(e);return!0}async function Mre(e,t){if(e.restarting)throw new Or(QH,"session_restarting");if(!e.isAlive())throw Error("Session is no longer running");e.idle.reset();let n=t.type;if(sW.has(n)){let r=jk(t.images);if(r)throw Error(r)}switch(n){case"prompt":{if(e.bashRunning)throw Error("Cannot send a prompt while a shell command is running");if(_L(e,t.message,Boolean(t.streamingBehavior)))return null;await r2(e);let r=t.streamingBehavior,o=typeof t.message==="string"&&t.message.trimStart().startsWith("/"),i=!r&&!e.isRunning()&&Boolean(e.sessionId),s=i&&!o,a=()=>{if(s&&!e.streaming)Ld(e.sessionId)};if(!r&&!o){if(e.promptRunning=!0,e.promptDispatchPendingCount+=1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,e.continuationGraceUntil=0,s)Kn(e.sessionId,"stream",e.runModel)}try{let c=vd(t.images),l=await e.proc.sendCommand({type:"prompt",message:t.message,...c?{images:c}:{},...r?{streamingBehavior:r}:{}},Hk(t.images));if(l?.agentInvoked===!1&&!r){if(i)e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,a(),e.emit({type:"prompt_result",agentInvoked:!1}),Cg(e)}else if(!r&&l?.agentInvoked!==!1&&s)e.awaitingAgentStart=!0,e.awaitingAgentStartDeadline=Date.now()+XH,e.armAgentStartWatchdog?.()}catch(c){if(e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,a(),c instanceof ec)await VL(e);if(c instanceof ll&&Bk.test(c.message))throw e.streaming=!0,e.runSettle?.arm(),new Or(tW,"agent_busy");throw c}finally{if(!r&&!o)e.promptDispatchPendingCount=Math.max(0,e.promptDispatchPendingCount-1)}return null}case"abort":if(zL(e),await e.proc.sendCommand({type:"abort"}),e.promptRunning=!1,e.awaitingAgentStart=!1,e.awaitingAgentStartDeadline=0,e.continuationGraceUntil=0,e.sessionId)Kn(e.sessionId,"abort");return null;case"force_reset":return await e.destroyAndWait(),null;case"get_state":try{let r=await e.proc.sendCommand({type:"get_state"},er);return hE(e,r)}catch(r){if(r instanceof ec)await VL(e);throw r}case"set_model":{let{provider:r,modelId:o}=t,i=await e.proc.sendCommand({type:"set_model",provider:r,modelId:o});return e.runModel={provider:i.provider,modelId:i.id},{id:i.id,provider:i.provider}}case"set_fast_mode":{let r=t.enabled===!0,o=await e.proc.sendCommand({type:"set_fast_mode",enabled:r});return e.fastModeEnabled=o?.enabled??r,{enabled:e.fastModeEnabled,active:o?.active??!1}}case"compact":try{e.compacting=!0;try{return await e.proc.sendCommand({type:"compact",...t.customInstructions?{customInstructions:t.customInstructions}:{}})}finally{e.compacting=!1}}finally{Ot()}case"abort_compaction":return await e.proc.sendCommand({type:"abort"}),null;case"set_session_name":{let r=t.name?.trim();if(!r)throw Error("Session name cannot be empty");return await e.proc.sendCommand({type:"set_session_name",name:r}),Ot(),null}case"get_commands":return await e.proc.sendCommand({type:"get_available_commands"});case"bash":{if(e.isRunning())throw Error("Cannot run a shell command while the session is busy");e.bashRunning=!0;try{return await e.proc.sendCommand({type:"bash",command:t.command})}finally{e.bashRunning=!1,Ot()}}case"extension_ui_response":{let{id:r,...o}=t;if(!r)throw Error("extension_ui_response requires an id");return e.proc.sendFrame({type:"extension_ui_response",id:r,...o}),e.resolvePendingUiDialog(r),null}case"steer":case"follow_up":{if(!e.isRunning())throw new Or("The session is idle \u2014 start a prompt first.","session_idle");if(_L(e,t.message,!0))return null;return await e.proc.sendCommand({type:n,message:t.message,...vd(t.images)?{images:vd(t.images)}:{}},SM),null}default:{if(nW.has(n)){if(n==="abort_and_prompt")return zL(e),await e.proc.sendCommand(t,SM)??null;let r=await e.proc.sendCommand(t);if(n==="set_thinking_level")Ot();return r??null}throw Error(`Unsupported command: ${n}`)}}}var Ore={completed:!0,failed:!0,aborted:!0};class JL{constructor(){this.lastSeen=new Map;this.keyByIndex=new Map}observe(e,t){if(e.type==="subagent_lifecycle"){let n=NK(e.payload);if(!n)return;if(Ore[n.status]===!0)this.forget(n.id);else this.mark(n.id,n.index>=0?n.index:void 0,t);return}if(e.type==="subagent_progress"){let n=LK(e.payload);if(!n)return;let r=n.index!==void 0&&n.index>=0?n.index:void 0,o=n.id??(r!==void 0?this.keyByIndex.get(r)??`idx:${r}`:void 0);if(o===void 0)return;if(n.status!==void 0&&Ore[n.status]===!0)this.forget(o);else this.mark(o,r,t);return}if(e.type==="subagent_event")for(let n of this.lastSeen.keys())this.lastSeen.set(n,t)}liveCount(e,t){for(let[n,r]of this.lastSeen)if(e-r>t)this.forget(n);return this.lastSeen.size}clear(){this.lastSeen.clear(),this.keyByIndex.clear()}mark(e,t,n){if(this.lastSeen.set(e,n),t===void 0)return;if(e!==`idx:${t}`)this.lastSeen.delete(`idx:${t}`);this.keyByIndex.set(t,e)}forget(e){this.lastSeen.delete(e);for(let[t,n]of this.keyByIndex)if(n===e)this.keyByIndex.delete(t)}}var Nre=new Set(["active","budget-limited"]);class YL{constructor(){this.goalEnabled=!1;this.goalRecord=null;this.goalContinuation=null;this.goalMaxTurns=null}observe(e){let{state:t,goal:n}=e,r=t?.goal?.status??n?.status;this.goalStatus=X0(r)?r:void 0,this.goalEnabled=t?.enabled===!0&&this.goalStatus!==void 0&&Nre.has(this.goalStatus)}observeMarker(e){if(qk(e.marker,"planStateMarker")){this.planEnabled=e.payload.enabled===!0;return}if(!qk(e.marker,"goalStateMarker"))return;let t=Are(e.payload);if(this.goalRecord=t,this.goalStatus=t&&X0(t.status)?t.status:void 0,this.goalEnabled=Tre(e.payload)&&this.goalStatus!==void 0&&Nre.has(this.goalStatus),"continuation"in e.payload)this.goalContinuation=e.payload.continuation===null?null:Ere(e.payload.continuation);let n=e.payload.maxTurns;if(typeof n==="number"&&Number.isInteger(n)&&n>0)this.goalMaxTurns=n}}class XL{#e;#t;#n;constructor(e,t){this.#e=null;this.#t=e,this.#n=t}arm(){if(this.stop(),!this.#t.awaitingAgentStart||!this.#t.sessionId)return;let e=Math.max(0,this.#t.awaitingAgentStartDeadline-Date.now());this.#e=setTimeout(()=>{if(this.#e=null,!this.#t.awaitingAgentStart||this.#t.streaming)return;this.#n()},e),this.#e.unref?.()}settleIfDone(){if(this.#e===null)return;if(!this.#t.awaitingAgentStart||this.#t.streaming)this.stop()}stop(){if(this.#e)clearTimeout(this.#e);this.#e=null}}var QVe=30000,ZVe=5000;class QL{#e;#t;#n;#r;#c;#i;#o;#a;constructor(e,t={}){this.#t=Date.now();this.#n=0;this.#r=!1;this.#c=null;this.#i=e,this.#o=t.silenceMs??QVe,this.#a=t.retrySlackMs??ZVe}noteFrame(e){if(this.#t=Date.now(),e.type==="auto_retry_start"){let t=typeof e.delayMs==="number"&&Number.isFinite(e.delayMs)?e.delayMs:0;this.#n=this.#t+Math.max(0,t)+this.#a}else if(e.type==="agent_start"||e.type==="agent_end")this.#n=0;this.#s()}async whenSettled(){await this.#c?.catch(()=>!1)}stop(){clearTimeout(this.#e),this.#e=void 0,this.#n=0}arm(){this.#s()}async reconcile(e){let t=this.#i;if(this.#r||!t.isAlive()||t.restarting||!t.sessionId)return!1;if(!t.isRunning()){if(t.subagents&&t.subagents.liveCount(Date.now(),Fk)>0)await this.#l();return this.stop(),!1}if(t.getPendingUiDialogs().length>0)return this.#s(),!1;if(Date.now()-this.#t<this.#o||Date.now()<this.#n)return this.#s(),!1;this.#r=!0;try{let n=await t.proc.sendCommand({type:"get_state"},er);if(n?.isSettled!==!0)return this.#s(),!1;if(t.bashRunning)return this.#s(),!1;return await this.#u(n),!0}catch{return this.#s(),!1}finally{this.#r=!1}}async#l(){if(this.#r)return;let e=this.#i.subagents;if(!e)return;this.#r=!0;try{if((await this.#i.proc.sendCommand({type:"get_state"},er))?.isSettled===!0)e.clear()}catch{}finally{this.#r=!1}}async#u(e){let t=this.#i,n=t.sessionId;if(hE(t,e),t.streaming=!1,t.promptRunning=!1,t.awaitingAgentStart=!1,t.awaitingAgentStartDeadline=0,t.continuationGraceUntil=0,this.stop(),n)Kn(n,"finish");t.emit({type:"agent_end",isTerminal:!0,messages:[]}),await qL(t,"interrupted","The run stopped reporting progress; open the session to read its output.")}#s(){if(clearTimeout(this.#e),this.#e=void 0,!this.#i.isRunning())return;let e=Math.max(this.#o,this.#n-Date.now()),t=setTimeout(()=>{this.#e=void 0,this.#c=this.reconcile("idle")},e);t.unref?.(),this.#e=t}}function Lre(e,t){if(!e.isAlive()||e.restarting)return Promise.resolve();let n=t.trim().split(`
1791
1791
  `).pop()??"",r=Promise.resolve();if(e.emit({type:"notice",level:"error",message:`The omp process for this session exited unexpectedly${n?`: ${n}`:"."}`}),e.streaming||e.promptRunning){if(e.emit({type:"agent_end",isTerminal:!0,messages:[]}),r=qL(e,"failed",`The omp process for this session exited unexpectedly${n?`: ${n}`:"."}`),e.sessionId)Kn(e.sessionId,"finish",void 0,`The omp process for this session exited unexpectedly${n?`: ${n}`:"."}`)}return e.destroy(),r}class ZL{constructor(){this.#e=[];this.#t=[]}#e;#t;emit(e){for(let t of this.#t)try{t(e)}catch{}gV(e);for(let t of this.#e)try{t(e)}catch{}}on(e){return this.#e.push(e),()=>{let t=this.#e.indexOf(e);if(t!==-1)this.#e.splice(t,1)}}onRaw(e){return this.#t.push(e),()=>{let t=this.#t.indexOf(e);if(t!==-1)this.#t.splice(t,1)}}}function Dre(e){e.proc.sendCommand({type:"get_state"},er).then((t)=>{if(!t.model)return;let n={provider:t.model.provider,modelId:t.model.id};if(e.runModel=n,e.sessionId)Tv(e.sessionId,n)}).catch(()=>{})}async function Fre(e){if(!e.isAlive())return!1;return e.idle.reset(),(await e.proc.sendCommand({type:"prompt",message:"/reload-plugins"},lf))?.agentInvoked!==!0}var Ure={finish:"notifyOnFinish",ask:"notifyOnAsk",error:"notifyOnError"};var Bre={desktop:"notifyDesktopEnabled",mobile:"notifyMobileEnabled"};var eze=200,tze=604800000;function nze(e){return{id:e.id,kind:e.kind==="error"||e.kind==="ask"?e.kind:"finish",sessionId:e.session_id,title:e.title,body:e.body,at:e.created_at,...typeof e.duration_ms==="number"&&e.duration_ms>0?{durationMs:e.duration_ms}:{}}}async function jre(e){let t=await k(),n=Date.now(),r=e.durationMs??null,o=await t.run(`INSERT INTO notification_events (kind, session_id, title, body, duration_ms, created_at)
1792
1792
  VALUES (?, ?, ?, ?, ?, ?)`,[e.kind,e.sessionId,e.title,e.body,r,n]);return await rze(),{id:o.lastID,...e,at:n}}async function Hre(e){return(await(await k()).all(`SELECT id, kind, session_id, title, body, created_at, duration_ms
1793
1793
  FROM notification_events WHERE id > ? ORDER BY id ASC`,[e])).map(nze)}async function Wre(){return(await(await k()).get("SELECT MAX(id) AS id FROM notification_events"))?.id??0}async function rze(){try{let e=await k();await e.run("DELETE FROM notification_events WHERE created_at < ?",[Date.now()-tze]),await e.run(`DELETE FROM notification_events
@@ -1,3 +1,3 @@
1
- import{d,n,o,i,u,a,e,s,B,p,dn,I,f,ae,Xe,fe,Nt,et,tn,S,U,Cr,wi,cr,X,ys,El,Bl}from"./index-qrwjxqdh.js";import{Oe,oe,Mt,D,ye}from"./index-e4yj4kbe.js";import{Zs}from"./index-kbk0vmex.js";import"./index-0mhxw0a1.js";import{ht,Ru,Lu,Mu,Ps,Fi,cp}from"./index-473wm10a.js";import{uu,Xd,ep,du,pr,Rs,pu,mu,fu,gu,Au,Ri,hu,$l,bu}from"./index-qdabc51h.js";import{EA,Ls,ku,Xo,zl,Su}from"./index-j1prebvy.js";import{Wa,Ka,ai}from"./index-drsy400d.js";var $e={name:"git-commit-vertical",size:24,node:[["path",{d:"M12 3v6",key:"1holv5"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M12 15v6",key:"a9ows0"}]]},me=s($e);var _e={name:"maximize",size:24,node:[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]},te=s(_e);var Ue={name:"minimize",size:24,node:[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]]},ne=s(Ue);var Ke={name:"save-all",size:24,node:[["path",{d:"M10 2v3a1 1 0 0 0 1 1h5",key:"1xspal"}],["path",{d:"M18 18v-6a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6",key:"1ra60u"}],["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"M8 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9.172a2 2 0 0 1 1.414.586l2.828 2.828A2 2 0 0 1 22 6.828V16a2 2 0 0 1-2.01 2z",key:"1yve0x"}]]},re=s(Ke);function de(t){if(t.byteViewer)return[];return[{id:"save",pinned:!0,actions:[{label:"Save file",icon:re,onSelect:t.onSave,disabled:t.saveDisabled}],children:t.saveButton},{id:"save-as",actions:[{label:"Save as…",icon:re,onSelect:t.onSaveAs}],children:e("button",{type:"button",onClick:t.onSaveAs,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:"Save the buffer to a new file","aria-label":"Save as",children:e(re,{size:14})})}]}function ue(t){if(!t.hasReview)return[];let r=t.isReviewing?"Exit review mode":"Review this document";return[{id:"review",actions:[{label:r,icon:tn,onSelect:t.onToggleReview,active:t.isReviewing}],children:e(Rs,{label:r,pressed:t.isReviewing,title:t.isReviewing?"Review mode is on — click a block to judge it":"Review: click blocks to mark them good or needing work",onClick:t.onToggleReview,children:e(tn,{size:14})})}]}function pe(t){if(!t.hasPreview)return[];return[{id:"preview",actions:[{label:t.previewLabel,icon:t.isPreview?Nt:et,onSelect:t.onTogglePreview,active:t.isPreview}],children:e(Rs,{label:t.previewLabel,pressed:t.isPreview,onClick:t.onTogglePreview,children:t.isPreview?e(Nt,{size:14}):e(et,{size:14})})}]}function be(t){let r=[];if(r.push(...de(t),...ue(t),...pe(t)),!t.byteViewer)r.push({id:"find",actions:[{label:t.findLabel,icon:U,onSelect:t.onToggleFind,active:t.findOpen}],children:e(Rs,{label:t.findLabel,pressed:t.findOpen,title:`${t.findLabel} (Ctrl+F)`,onClick:t.onToggleFind,children:e(U,{size:14})})}),r.push({id:"wrap",actions:[{label:t.wordWrapLabel,icon:dn,onSelect:t.onToggleWordWrap,active:t.wordWrap}],children:e(Rs,{label:t.wordWrapLabel,pressed:t.wordWrap,onClick:t.onToggleWordWrap,children:e(dn,{size:14})})}),r.push({id:"blame",actions:[{label:t.blameInline?"Hide line blame":"Show line blame",icon:me,onSelect:t.onToggleBlameInline,active:t.blameInline}],children:e(Rs,{label:t.blameInline?"Hide line blame":"Show line blame",pressed:t.blameInline,title:"Who last changed each block, from git (hover a line for the commit)",onClick:t.onToggleBlameInline,children:e(me,{size:14})})}),r.push({id:"zoom",actions:[{label:"Decrease font size",icon:Ka,onSelect:t.onZoomOut},{label:"Increase font size",icon:Wa,onSelect:t.onZoomIn}],children:e(d,{children:[e("button",{type:"button",onClick:t.onZoomOut,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:"Decrease font size","aria-label":"Decrease font size",children:e(Ka,{size:14})}),e("button",{type:"button",onClick:t.onZoomIn,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:"Increase font size","aria-label":"Increase font size",children:e(Wa,{size:14})})]})}),r.push({id:"reload",actions:[{label:"Reload from disk",icon:S,onSelect:t.onReload,disabled:!t.canReload}],children:e("button",{type:"button",onClick:t.onReload,disabled:!t.canReload||t.refreshing,"aria-busy":t.refreshing,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:!t.canReload?"Nothing to reload — this tab has no file on disk":t.reloadDiscardsEdits?"Discard my changes and reload from disk":"Reload from disk","aria-label":"Reload from disk",children:e(S,{size:14,className:t.refreshing?"animate-spin":void 0})})});return r.push({id:"copy",actions:[{label:t.copyLabel,icon:ae,onSelect:t.onCopy},{label:"Download file",icon:fe,onSelect:t.onDownload}],children:e(d,{children:[e("button",{type:"button",onClick:t.onCopy,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:t.copyLabel,"aria-label":t.copyLabel,children:t.copied?e(ae,{size:14,className:"text-success"}):e(ae,{size:14})}),e("button",{type:"button",onClick:t.onDownload,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:"Download file","aria-label":"Download file",children:e(fe,{size:14})})]})}),r.push({id:"view-modes",pinned:!0,actions:t.viewModeActions,children:t.viewModeButtons}),r.push({id:"maximize",pinned:!0,actions:[{label:t.maximizeLabel,icon:t.isMaximized?ne:te,onSelect:t.onToggleMaximize,active:t.isMaximized}],children:t.maximizeButton}),r}function he({path:t,saveStatus:r,wordWrap:l,hasPreview:m,isPreview:c,hasReview:b,isReviewing:w,copied:k,byteViewer:y=!1,saveDisabled:h=!1,unsupported:x=!1,handleMissing:T=!1,readOnly:M=!1,isMaximized:g=!1,findOpen:v=!1,onToggleFind:C,onSave:P,onTogglePreview:N,onToggleReview:R,onToggleWordWrap:V,onZoomIn:_,onZoomOut:E,onCopy:O,onDownload:H,onReload:F,canReload:A,refreshing:z=!1,reloadDiscardsEdits:Z,onSaveAs:W,onToggleMaximize:K}){let Q=h?M?"Read-only — this file was opened from the phone, not from a workspace":T?"Cannot save — reopen the file from the system to restore write access":x?"Nothing to save — this file cannot be opened as a document":"Nothing to save — this file could not be read":r==="needs-permission"?"Click Save to allow writing this file":r==="saving"?"Saving…":r==="error"?"Save failed — the file on disk was not changed":"Save file (Ctrl+S)",se=e("button",{type:"button",onClick:P,disabled:h||r==="saving",className:`${pr} hover:bg-ink/5`,title:Q,"aria-label":Q,children:r==="saving"?e(ht,{size:14,className:"text-warning animate-pulse"}):r==="saved"?e(f,{size:14,className:"text-success"}):r==="error"?e(B,{size:14,className:"text-error"}):r==="needs-permission"?e(ht,{size:14,className:"text-warning"}):e(ht,{size:14,className:"hover:text-ink"})}),q=g?"Exit full screen":"Full screen",j=e("button",{type:"button",onClick:K,className:`${pr} hover:bg-ink/5 hover:text-ink ${g?"text-ink":""}`,title:q,"aria-label":q,"aria-pressed":g,children:g?e(ne,{size:14}):e(te,{size:14})}),ee=cp(),G=Xd(),Y=be({byteViewer:y,hasPreview:m,isPreview:c,wordWrap:l,hasReview:b,isReviewing:w,blameInline:ee.inline,findOpen:v,copied:k,isMaximized:g,saveDisabled:h,canReload:A,refreshing:z,reloadDiscardsEdits:Z,saveButton:se,maximizeButton:j,viewModeButtons:e(ep,{size:14}),viewModeActions:G,previewLabel:c?"Show source":"Show preview",findLabel:"Find and replace",wordWrapLabel:l?"Word wrap on":"Word wrap off",copyLabel:k?"Copied":y?"Copy image":"Copy content",maximizeLabel:q,onTogglePreview:N,onToggleReview:R,onToggleFind:C,onToggleWordWrap:V,onToggleBlameInline:()=>{let ce={...Fi(),inline:!ee.inline};Cr({editorBlameInline:ce.inline}),window.dispatchEvent(new CustomEvent(Ps,{detail:ce}))},onZoomIn:_,onZoomOut:E,onCopy:O,onDownload:H,onReload:F,onSaveAs:W,onToggleMaximize:K,onSave:P});return e("div",{className:`@container ${wi.desktop} flex items-center justify-between gap-2 px-3 border-b border-ink/10 bg-paper flex-shrink-0`,children:[e("div",{className:"hidden @[420px]:flex items-center space-x-2 text-xs font-mono text-ink/40 min-w-0",children:e("span",{className:"truncate max-w-[300px]",title:t,children:t})}),e(ai,{clusters:Y,className:"text-ink/40 ml-auto"})]})}function ge({content:t,file:r,zoomLevel:l,reviewActive:m,onExitReview:c,scrollRef:b,onScroll:w}){return e("div",{ref:b,onScroll:w,"data-testid":"editor-scroller",className:"flex-1 overflow-auto bg-paper flex",children:e("div",{className:"p-6 max-w-4xl mx-auto font-sans flex-1",style:{fontSize:`${l}px`},children:e(pu,{content:t,file:r,active:m,onExit:c})})})}function Ze(t,r){return r?`Spaces: ${t}`:"Tabs"}function ve({caret:t,eol:r,onSetEol:l,indentWidth:m,insertSpaces:c,language:b,byteViewer:w,viewerKind:k,lineCount:y,conflicts:h=0}){return e("footer",{className:"flex bg-canvas border-t border-ink/10 px-3 items-center justify-between text-[10px] text-ink/50 flex-shrink-0 font-mono h-6","data-editor-status-bar":"",children:[e("div",{className:"flex items-center gap-3 min-w-0",children:w?e("span",{className:"uppercase",children:Xo[k]}):e(d,{children:[e("span",{className:"tabular-nums",children:t?`Ln ${t.line}, Col ${t.column}`:"Ln —, Col —"}),e("span",{children:Ze(m,c)}),e("button",{type:"button",onClick:()=>l(r==="lf"?"crlf":"lf"),className:"uppercase hover:text-ink transition-colors cursor-pointer",title:`Line endings: ${r.toUpperCase()} — click to switch`,"aria-label":`Line endings ${r.toUpperCase()}, switch`,children:r}),e("span",{children:[y," lines"]})]})}),e("div",{className:"flex items-center gap-3 min-w-0",children:[h>0&&e("span",{className:"text-error font-semibold tabular-nums",title:`${h} unresolved conflict${h===1?"":"s"} — markers are highlighted in the file`,children:["⚠ ",h," conflict",h===1?"":"s"]}),e("span",{className:"uppercase text-ink/40",children:b})]})]})}function Ge(t){if(t===0)return 0;return Math.max(-1,Math.min(1,-Math.sign(t)))}function qe(t,r,l=El,m=Bl){return Math.max(l,Math.min(m,t+r))}function je(t,r){let l=t instanceof HTMLElement?t:null;while(l&&l!==r){let m=getComputedStyle(l);if(/(auto|scroll)/.test(m.overflowY)&&l.scrollHeight>l.clientHeight)return!0;l=l.parentElement}return!1}function xe(t,r){o(()=>{if(!t)return;let l=t.closest("[data-code-surface]"),m=l instanceof HTMLElement?l:t,c=(b)=>{if(!b.ctrlKey&&!b.metaKey)return;if(b.preventDefault(),je(b.target,m))return;let w=Ge(b.deltaY);if(w===0)return;r((k)=>qe(k,w))};return t.addEventListener("wheel",c,{passive:!1}),()=>t.removeEventListener("wheel",c)},[t,r])}function we(t,r){let l=t.trim();if(!/^\d+$/.test(l))return null;let m=Number(l);if(m<1)return null;return Math.min(m,Math.max(r,1))}function ke({lineCount:t,onGo:r,onClose:l}){let[m,c]=n(""),b=i(null);o(()=>{b.current?.focus(),b.current?.select()},[]);let w=()=>{let h=we(m,t);if(h===null)return;r(h)},k=(h)=>{if(h.key==="Enter"){h.preventDefault(),w();return}if(h.key==="Escape")h.preventDefault(),l()},y=we(m,t);return e(X,{onClose:l,maxWidthClass:"max-w-xs",header:e("span",{className:"text-sm font-semibold text-ink",children:"Go to line"}),children:e("div",{className:"px-4 py-3 space-y-2",children:[e("div",{className:"flex items-center gap-2",children:[e("input",{ref:b,value:m,onInput:(h)=>c(h.target.value),onKeyDown:k,inputMode:"numeric",placeholder:"1","aria-label":"Line number",className:"flex-1 bg-paper border border-ink/20 rounded px-2 py-1 text-xs font-mono text-ink outline-none focus:border-ink/40"}),e("span",{className:"text-[10px] font-mono text-ink/40",children:["/ ",t]}),e("button",{type:"button",onClick:w,disabled:y===null,className:"flex items-center gap-1 px-2 py-1 rounded bg-ink text-paper text-xs disabled:opacity-40 disabled:cursor-default cursor-pointer",children:[e(Xe,{size:12}),"Go"]})]}),m&&y!==null&&String(y)!==m.trim()?e("div",{className:"text-[10px] text-ink/50 font-mono",children:["line ",y," (the last line)"]}):null,m&&y===null?e("div",{className:"text-[10px] text-error font-mono",children:"Enter a line number"}):null]})})}var Ee={status:"idle",payload:null,message:null};function Se(t){if(!t?.path)return"";return`${t.root??""}\x00${t.repo??""}\x00${t.path}`}function Te(t,r={}){let l=r.enabled!==!1&&Boolean(t?.path)&&t?.deviceFile!==!0,m=r.dirty===!0,c=Se(t),[b,w]=n({key:"",value:Ee}),k=i(t);k.current=t;let y=i(c);y.current=c;let h=i(l);h.current=l;let x=i(m);x.current=m;let T=i(b);T.current=b;let M=i(0),g=i(""),v=i(new Map),C=i(new Set),P=a(async()=>{let E=k.current;if(!E?.path)return;let O=Se(E),H=++M.current;g.current=O,w((A)=>({key:O,value:{status:"loading",payload:A.key===O?A.value.payload:null,message:null}}));let F=new URLSearchParams({blame:"1",file:E.path,repo:E.repo||"."});if(E.root)F.set("root",E.root);try{let A=await fetch(`/api/fs/git?${F.toString()}`),z=await A.json().catch(()=>null);if(H!==M.current)return;if(!A.ok||!z){w({key:O,value:{status:"error",payload:null,message:z?.error??`Blame request failed (HTTP ${A.status})`}});return}w({key:O,value:z.available?{status:"ready",payload:z,message:null}:{status:"unavailable",payload:z,message:z.message??null}})}catch(A){if(H!==M.current)return;w({key:O,value:{status:"error",payload:null,message:A instanceof Error?A.message:"Blame failed"}})}finally{if(g.current===O)g.current=""}},[]),N=a(async(E)=>{let O=v.current.get(E);if(O)return O;let H=k.current;if(!H?.path)return{entries:[],truncated:!1};let F=new URLSearchParams({blameHistory:"1",file:H.path,line:String(E),repo:H.repo||"."});if(H.root)F.set("root",H.root);try{let z=await(await fetch(`/api/fs/git?${F.toString()}`)).json().catch(()=>null),Z={entries:Array.isArray(z?.entries)?z.entries:[],truncated:z?.truncated===!0};return v.current.set(E,Z),Z}catch{return{entries:[],truncated:!1}}},[]),R=i(null);if(!R.current)R.current={ensure:()=>{if(!h.current||x.current)return;let E=T.current;if(E.key===y.current&&E.value.status!=="idle")return;if(g.current===y.current)return;P()},reload:()=>{v.current.clear(),P()},history:N,snapshot:()=>{let E=T.current;return E.key===y.current?E.value:Ee},stale:()=>x.current,subscribe:(E)=>(C.current.add(E),()=>{C.current.delete(E)})};o(()=>{if(!l||m||!c)return;v.current.clear(),P()},[l,m,c,P]);let V=i(m);return o(()=>{if(V.current===m)return;V.current=m;for(let E of C.current)E()},[m]),o(()=>{for(let E of C.current)E()},[b]),R.current}var Ye="0".repeat(40);function ie(t){return t===Ye}function J(t,r=Date.now()){let l=Math.max(0,Math.floor(r/1000)-t);if(l<60)return"just now";let m=Math.floor(l/60);if(m<60)return`${m}m ago`;let c=Math.floor(m/60);if(c<24)return`${c}h ago`;let b=Math.floor(c/24);if(b<30)return`${b}d ago`;let w=Math.floor(b/30);if(w<12)return`${w}mo ago`;return`${Math.floor(b/365)}y ago`}function Ce(t,r){switch(t){case"not-repo":return"This folder is not a git repository.";case"no-commit":return"This repository has no commits yet.";case"untracked":return"This file has never been committed, so it has no history.";case"too-large":return r??"This file is too large to blame.";case"empty":return"This file is empty.";default:return r??"git could not read this file."}}var Le="fixed z-50 w-[min(340px,92vw)] rounded-xl border border-ink/20 bg-paper p-3 shadow-xl font-sans text-xs text-ink",Be="flex items-baseline justify-between gap-2",Re="truncate text-xs font-semibold text-ink",Je="shrink-0 font-mono text-[10px] text-ink/40",Qe="mt-1 line-clamp-2 text-[11px] leading-snug text-ink/80",tt="mt-2 border-t border-ink/10 pt-2",ot="flex items-center gap-2 font-mono text-[10px] text-ink/40",Me="mt-1 text-[10px] leading-snug text-ink/50",nt="mt-2 flex w-full items-center gap-1.5 text-left text-[10px] text-ink/50 hover:text-ink cursor-pointer",rt="mt-1.5 space-y-1 border-t border-ink/10 pt-1.5",le="flex items-center gap-1.5 font-mono text-[10px]";function L(t,r,l){let m=document.createElement(t);if(m.className=r,l!==void 0)m.textContent=l;return m}function it(t){return new Date(t*1000).toLocaleDateString(void 0,{day:"numeric",month:"short",year:"numeric"})}function at(t){let r=t.payload;if(t.status==="error")return{title:"Blame failed",body:t.message??"git could not read this file."};if(t.status==="unavailable")return{title:r?.reason==="untracked"?"Not tracked":"No history",body:Ce(r?.reason??"error",t.message??void 0)};if(!r)return null;if(t.stale)return{title:"Not committed yet",body:"This line changed in the editor. Save the file to see its blame."};if(t.line>r.lines)return{title:"Not committed yet",body:`Line ${t.line} is past the end of the file at HEAD (${r.lines} lines).`};let l=r.runs.length>0?Ne(r,t.line):null;if(!l)return{title:"Not committed yet",body:`git has no attribution for line ${t.line}.`};if(ie(l.sha))return{title:"Not committed yet",body:"This line differs from the last commit."};return null}function Ne(t,r){for(let l of t.runs)if(r>=l.from&&r<=l.to)return t.commits[l.sha]??null;return null}function lt(t,r){t.replaceChildren(),t.className=Le;let l=at(r);if(l){let h=L("div",Be);if(h.append(L("span",Re,l.title)),r.status==="error"&&r.message){let x=L("button","shrink-0 cursor-pointer text-[10px] text-ink/50 hover:text-ink","Try again");x.type="button",x.setAttribute("aria-label","Read the blame again"),h.append(x)}t.append(h,L("p",Me,l.body));return}let m=r.payload;if(!m){t.append(L("p",Me,"Reading blame…"));return}let c=Ne(m,r.line),b=L("div",Be);if(b.append(L("span",Re,c.author.trim()||"Unknown"),L("span",Je,J(c.time))),t.append(b),c.summary)t.append(L("p",Qe,c.summary));let w=L("div",`${ot} ${tt}`);if(w.append(L("code","truncate",c.sha.slice(0,7)),L("span","",it(c.time))),c.mail){let h=L("span","truncate",c.mail);h.title=c.mail,w.append(h)}t.append(w);let k=L("button",nt);if(k.type="button",k.setAttribute("aria-expanded",r.historyOpen?"true":"false"),k.textContent=`${r.historyOpen?"▾":"▸"} Line history`,t.append(k),!r.historyOpen)return;let y=L("ol",rt);if(r.historyLoading)y.append(L("li",`${le} text-ink/40`,"Reading history…"));else if(!r.history||r.history.entries.length===0)y.append(L("li",`${le} text-ink/40`,"No commits touched this line."));else{let h=r.history.entries;if(h.forEach((x,T)=>{let M=L("li",le),g=T===h.length-1?"new":"edit";M.append(L("span","text-ink/40",T===0?"●":"○"),L("code","text-ink/60",x.sha.slice(0,7)),L("span","truncate text-ink/80",x.author.trim()||"Unknown"),L("span","ml-auto shrink-0 text-ink/40",J(x.time)),L("span","shrink-0 rounded bg-ink/5 px-1 text-[8.5px] uppercase tracking-wider text-ink/45",g)),y.append(M)}),r.history.truncated)y.append(L("li",`${le} text-ink/40`,"Older commits are not shown."))}t.append(y)}function Pe(t,r,l){let m=L("div",Le);m.setAttribute("role","dialog"),m.setAttribute("aria-label","Line blame"),m.addEventListener("mousedown",(x)=>x.stopPropagation());let c=null,b=!1,w=!1,k=()=>{let x=r.snapshot();return{line:t,status:x.status,payload:x.payload,message:x.message,stale:r.stale(),history:c,historyOpen:b,historyLoading:w}},y=()=>{lt(m,k());let x=m.querySelector('[aria-label="Read the blame again"]');if(x)x.addEventListener("click",(T)=>{T.stopPropagation(),l()});m.querySelector("button[aria-expanded]")?.addEventListener("click",(T)=>{if(T.stopPropagation(),b=!b,y(),!b||c||w)return;w=!0,y(),r.history(t).then((M)=>{c=M,w=!1,y()})})};y();let h=r.subscribe(y);return{element:m,place(x){let T=m.ownerDocument.defaultView,M=T?.innerWidth??1024,g=T?.innerHeight??768,v=m.offsetWidth||340,C=m.offsetHeight||120,P=8,N=Math.max(8,Math.min(x.left,M-v-8)),R=x.bottom+6,V=x.top-C-6,_=R+C>g-8&&V>8?V:R;m.style.left=`${N}px`,m.style.top=`${Math.max(8,_)}px`},destroy(){h(),m.remove()}}}function De(t){return ye.define((r)=>{let l=null,m=0,c,b=()=>{clearTimeout(c),c=void 0,l?.destroy(),l=null,m=0},w=(g,v)=>{let C=g.getBoundingClientRect();if(C.width>0)return{left:C.left,top:C.top,bottom:C.bottom};let P=r.state.doc.line(Math.min(v,r.state.doc.lines)),N=null;try{N=r.coordsAtPos(P.from)}catch{N=null}if(N)return N;let R=r.scrollDOM.getBoundingClientRect();return{left:R.left,top:R.top+24,bottom:R.top+24}},k=(g,v)=>{if(m===g&&l)return;b(),m=g,l=Pe(g,t,()=>{t.reload(),b()}),document.body.append(l.element),l.place(v)},y=(g)=>{let v=g.target,C=v?.closest?.(".cm-blame-label");if(C){let R=Number(C.dataset.blameLine);return Number.isInteger(R)&&R>0?{line:R,anchor:C}:null}let P=v?.closest?.(".cm-lineNumbers .cm-gutterElement");if(!P)return null;let N=Number((P.textContent??"").trim());return Number.isInteger(N)&&N>0?{line:N,anchor:P}:null},h=(g)=>{let v=y(g);if(!v)return;k(v.line,w(v.anchor,v.line))},x=(g)=>{let v=y(g);if(v){g.preventDefault(),k(v.line,w(v.anchor,v.line));return}if(l&&!l.element.contains(g.target))b()},T=(g)=>{if(g.key==="Escape"&&l)b(),g.stopPropagation()},M=(g)=>{if(!l)return;let v=g.relatedTarget;if(v&&(l.element.contains(v)||r.scrollDOM.contains(v)))return;c=setTimeout(b,200)};return r.scrollDOM.addEventListener("mouseover",h),r.scrollDOM.addEventListener("mouseleave",M),r.scrollDOM.addEventListener("mousedown",x),document.addEventListener("mousedown",x),document.addEventListener("keydown",T,!0),{update(g){if(g.docChanged&&l)b()},destroy(){b(),r.scrollDOM.removeEventListener("mouseover",h),r.scrollDOM.removeEventListener("mouseleave",M),r.scrollDOM.removeEventListener("mousedown",x),document.removeEventListener("mousedown",x),document.removeEventListener("keydown",T,!0)}}})}var Ae=40,ze=oe.define();function st(t){return Oe.define({create:()=>({payload:t.snapshot().payload,stale:!1}),update(r,l){let m=r;for(let c of l.effects){if(!c.is(ze))continue;m=c.value.payload!==r.payload?{payload:c.value.payload,stale:!1}:{payload:r.payload,stale:r.stale}}if(l.docChanged&&!m.stale)m={payload:m.payload,stale:!0};return m}})}function mt(t,r,l){let m=t.commits[r];if(!m||ie(r))return null;let c=m.author.trim()||"Unknown";return l?c:`${c} · ${J(m.time)}`}class He extends Mt{constructor(t,r,l){super();this.line=t;this.text=r;this.title=l}eq(t){return t.line===this.line&&t.text===this.text&&t.title===this.title}toDOM(){let t=document.createElement("span");return t.className="cm-blame-label",t.dataset.blameLine=String(this.line),t.title=this.title,t.textContent=this.text,t}}function Ie(t,r,l){let{payload:m,stale:c}=t;if(!m?.available||c)return D.none;let b=Math.min(m.lines,r.state.doc.lines);if(b<1)return D.none;let w=r.state.doc.lineAt(Math.max(0,Math.min(r.viewport.from,r.state.doc.length))).number,k=r.state.doc.lineAt(Math.max(0,Math.min(r.viewport.to,r.state.doc.length))).number,y=Math.max(1,w-Ae),h=Math.min(b,k+Ae),x=[];for(let T of m.runs){let M=Math.max(T.from,y);if(M>T.to||M>h)continue;let g=mt(m,T.sha,l);if(!g)continue;let v=m.commits[T.sha],C=r.state.doc.line(M);x.push({from:C.to,deco:D.widget({widget:new He(C.number,g,v.summary||v.sha),side:1})})}return D.set(x.map((T)=>T.deco.range(T.from)),!0)}function ct(t,r){return ye.fromClass(class{constructor(l){this.view=l;this.decorations=Ie(l.state.field(t),l,r)}update(l){if(l.startState.field(t)===l.state.field(t)&&!l.docChanged&&!l.viewportChanged)return;this.decorations=Ie(l.state.field(t),l.view,r)}},{decorations:(l)=>l.decorations})}function dt(t){return ye.define((r)=>{let l=!0,m=()=>{if(!l)return;let b=t.snapshot();r.dispatch({effects:ze.of({payload:b.payload,stale:!1})})},c=t.subscribe(m);return{destroy(){l=!1,c()}}})}function Ve({controller:t,inline:r=!0,compact:l=!1}){let m=st(t);return[m,dt(t),r?ct(m,l):[],De(t)]}function Fe({activeFile:t,editor:r,find:l,surfaceRef:m,goToLineRequest:c,rootPath:b=null,repoPath:w=null,onRunCommand:k,wordWrap:y,zoomLevel:h,setZoomLevel:x,editorFontFamily:T,editorTheme:M,viewerKind:g,isPreview:v,reviewActive:C,onToggleReview:P,revealActive:N}){let R=g==="markdown",V=Lu(),_=Mu(),E=cp(),O=Te({name:t.name,path:t.path,root:t.root??b??void 0,repo:t.repo??w??"."},{enabled:E.enabled,dirty:r.isDirty}),H=u(()=>E.enabled?Ve({controller:O,inline:E.inline}):null,[E.enabled,E.inline,O]),[F,A]=n(null),z=u(()=>mu(r.content),[r.content]),[Z,W]=n(!1);o(()=>{if(c>0)W(!0)},[c]);let[K,Q]=n(null),[se,q]=n(null);xe(K,x);let j=Zs({tabKey:String(t.id),surface:R&&v?"rendered":"code",ready:r.loaded,element:R&&v?void 0:K}),ee=a((G)=>{j.ref(G),q(G)},[j.ref]);return Au({path:t.path,scroller:se,preview:R&&v}),e("div",{className:"relative flex-1 min-h-0 flex flex-col",children:[l.open?e(gu,{find:l}):null,Z?e(ke,{lineCount:r.content?r.content.split(`
1
+ import{d,n,o,i,u,a,e,s,B,p,dn,I,f,ae,Xe,fe,Nt,et,tn,S,U,Cr,wi,cr,X,ys,El,Bl}from"./index-nr5gwny1.js";import{Oe,oe,Mt,D,ye}from"./index-e4yj4kbe.js";import{Zs}from"./index-6m5n8b6w.js";import"./index-k57bandz.js";import{ht,Ru,Lu,Mu,Ps,Fi,cp}from"./index-gr07t5c4.js";import{uu,Xd,ep,du,pr,Rs,pu,mu,fu,gu,Au,Ri,hu,$l,bu}from"./index-n71ffk62.js";import{EA,Ls,ku,Xo,zl,Su}from"./index-5m0se6fk.js";import{Wa,Ka,ai}from"./index-h4qmywn5.js";var $e={name:"git-commit-vertical",size:24,node:[["path",{d:"M12 3v6",key:"1holv5"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M12 15v6",key:"a9ows0"}]]},me=s($e);var _e={name:"maximize",size:24,node:[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]},te=s(_e);var Ue={name:"minimize",size:24,node:[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]]},ne=s(Ue);var Ke={name:"save-all",size:24,node:[["path",{d:"M10 2v3a1 1 0 0 0 1 1h5",key:"1xspal"}],["path",{d:"M18 18v-6a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6",key:"1ra60u"}],["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"M8 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9.172a2 2 0 0 1 1.414.586l2.828 2.828A2 2 0 0 1 22 6.828V16a2 2 0 0 1-2.01 2z",key:"1yve0x"}]]},re=s(Ke);function de(t){if(t.byteViewer)return[];return[{id:"save",pinned:!0,actions:[{label:"Save file",icon:re,onSelect:t.onSave,disabled:t.saveDisabled}],children:t.saveButton},{id:"save-as",actions:[{label:"Save as…",icon:re,onSelect:t.onSaveAs}],children:e("button",{type:"button",onClick:t.onSaveAs,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:"Save the buffer to a new file","aria-label":"Save as",children:e(re,{size:14})})}]}function ue(t){if(!t.hasReview)return[];let r=t.isReviewing?"Exit review mode":"Review this document";return[{id:"review",actions:[{label:r,icon:tn,onSelect:t.onToggleReview,active:t.isReviewing}],children:e(Rs,{label:r,pressed:t.isReviewing,title:t.isReviewing?"Review mode is on — click a block to judge it":"Review: click blocks to mark them good or needing work",onClick:t.onToggleReview,children:e(tn,{size:14})})}]}function pe(t){if(!t.hasPreview)return[];return[{id:"preview",actions:[{label:t.previewLabel,icon:t.isPreview?Nt:et,onSelect:t.onTogglePreview,active:t.isPreview}],children:e(Rs,{label:t.previewLabel,pressed:t.isPreview,onClick:t.onTogglePreview,children:t.isPreview?e(Nt,{size:14}):e(et,{size:14})})}]}function be(t){let r=[];if(r.push(...de(t),...ue(t),...pe(t)),!t.byteViewer)r.push({id:"find",actions:[{label:t.findLabel,icon:U,onSelect:t.onToggleFind,active:t.findOpen}],children:e(Rs,{label:t.findLabel,pressed:t.findOpen,title:`${t.findLabel} (Ctrl+F)`,onClick:t.onToggleFind,children:e(U,{size:14})})}),r.push({id:"wrap",actions:[{label:t.wordWrapLabel,icon:dn,onSelect:t.onToggleWordWrap,active:t.wordWrap}],children:e(Rs,{label:t.wordWrapLabel,pressed:t.wordWrap,onClick:t.onToggleWordWrap,children:e(dn,{size:14})})}),r.push({id:"blame",actions:[{label:t.blameInline?"Hide line blame":"Show line blame",icon:me,onSelect:t.onToggleBlameInline,active:t.blameInline}],children:e(Rs,{label:t.blameInline?"Hide line blame":"Show line blame",pressed:t.blameInline,title:"Who last changed each block, from git (hover a line for the commit)",onClick:t.onToggleBlameInline,children:e(me,{size:14})})}),r.push({id:"zoom",actions:[{label:"Decrease font size",icon:Ka,onSelect:t.onZoomOut},{label:"Increase font size",icon:Wa,onSelect:t.onZoomIn}],children:e(d,{children:[e("button",{type:"button",onClick:t.onZoomOut,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:"Decrease font size","aria-label":"Decrease font size",children:e(Ka,{size:14})}),e("button",{type:"button",onClick:t.onZoomIn,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:"Increase font size","aria-label":"Increase font size",children:e(Wa,{size:14})})]})}),r.push({id:"reload",actions:[{label:"Reload from disk",icon:S,onSelect:t.onReload,disabled:!t.canReload}],children:e("button",{type:"button",onClick:t.onReload,disabled:!t.canReload||t.refreshing,"aria-busy":t.refreshing,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:!t.canReload?"Nothing to reload — this tab has no file on disk":t.reloadDiscardsEdits?"Discard my changes and reload from disk":"Reload from disk","aria-label":"Reload from disk",children:e(S,{size:14,className:t.refreshing?"animate-spin":void 0})})});return r.push({id:"copy",actions:[{label:t.copyLabel,icon:ae,onSelect:t.onCopy},{label:"Download file",icon:fe,onSelect:t.onDownload}],children:e(d,{children:[e("button",{type:"button",onClick:t.onCopy,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:t.copyLabel,"aria-label":t.copyLabel,children:t.copied?e(ae,{size:14,className:"text-success"}):e(ae,{size:14})}),e("button",{type:"button",onClick:t.onDownload,className:`${pr} hover:bg-ink/5 hover:text-ink`,title:"Download file","aria-label":"Download file",children:e(fe,{size:14})})]})}),r.push({id:"view-modes",pinned:!0,actions:t.viewModeActions,children:t.viewModeButtons}),r.push({id:"maximize",pinned:!0,actions:[{label:t.maximizeLabel,icon:t.isMaximized?ne:te,onSelect:t.onToggleMaximize,active:t.isMaximized}],children:t.maximizeButton}),r}function he({path:t,saveStatus:r,wordWrap:l,hasPreview:m,isPreview:c,hasReview:b,isReviewing:w,copied:k,byteViewer:y=!1,saveDisabled:h=!1,unsupported:x=!1,handleMissing:T=!1,readOnly:M=!1,isMaximized:g=!1,findOpen:v=!1,onToggleFind:C,onSave:P,onTogglePreview:N,onToggleReview:R,onToggleWordWrap:V,onZoomIn:_,onZoomOut:E,onCopy:O,onDownload:H,onReload:F,canReload:A,refreshing:z=!1,reloadDiscardsEdits:Z,onSaveAs:W,onToggleMaximize:K}){let Q=h?M?"Read-only — this file was opened from the phone, not from a workspace":T?"Cannot save — reopen the file from the system to restore write access":x?"Nothing to save — this file cannot be opened as a document":"Nothing to save — this file could not be read":r==="needs-permission"?"Click Save to allow writing this file":r==="saving"?"Saving…":r==="error"?"Save failed — the file on disk was not changed":"Save file (Ctrl+S)",se=e("button",{type:"button",onClick:P,disabled:h||r==="saving",className:`${pr} hover:bg-ink/5`,title:Q,"aria-label":Q,children:r==="saving"?e(ht,{size:14,className:"text-warning animate-pulse"}):r==="saved"?e(f,{size:14,className:"text-success"}):r==="error"?e(B,{size:14,className:"text-error"}):r==="needs-permission"?e(ht,{size:14,className:"text-warning"}):e(ht,{size:14,className:"hover:text-ink"})}),q=g?"Exit full screen":"Full screen",j=e("button",{type:"button",onClick:K,className:`${pr} hover:bg-ink/5 hover:text-ink ${g?"text-ink":""}`,title:q,"aria-label":q,"aria-pressed":g,children:g?e(ne,{size:14}):e(te,{size:14})}),ee=cp(),G=Xd(),Y=be({byteViewer:y,hasPreview:m,isPreview:c,wordWrap:l,hasReview:b,isReviewing:w,blameInline:ee.inline,findOpen:v,copied:k,isMaximized:g,saveDisabled:h,canReload:A,refreshing:z,reloadDiscardsEdits:Z,saveButton:se,maximizeButton:j,viewModeButtons:e(ep,{size:14}),viewModeActions:G,previewLabel:c?"Show source":"Show preview",findLabel:"Find and replace",wordWrapLabel:l?"Word wrap on":"Word wrap off",copyLabel:k?"Copied":y?"Copy image":"Copy content",maximizeLabel:q,onTogglePreview:N,onToggleReview:R,onToggleFind:C,onToggleWordWrap:V,onToggleBlameInline:()=>{let ce={...Fi(),inline:!ee.inline};Cr({editorBlameInline:ce.inline}),window.dispatchEvent(new CustomEvent(Ps,{detail:ce}))},onZoomIn:_,onZoomOut:E,onCopy:O,onDownload:H,onReload:F,onSaveAs:W,onToggleMaximize:K,onSave:P});return e("div",{className:`@container ${wi.desktop} flex items-center justify-between gap-2 px-3 border-b border-ink/10 bg-paper flex-shrink-0`,children:[e("div",{className:"hidden @[420px]:flex items-center space-x-2 text-xs font-mono text-ink/40 min-w-0",children:e("span",{className:"truncate max-w-[300px]",title:t,children:t})}),e(ai,{clusters:Y,className:"text-ink/40 ml-auto"})]})}function ge({content:t,file:r,zoomLevel:l,reviewActive:m,onExitReview:c,scrollRef:b,onScroll:w}){return e("div",{ref:b,onScroll:w,"data-testid":"editor-scroller",className:"flex-1 overflow-auto bg-paper flex",children:e("div",{className:"p-6 max-w-4xl mx-auto font-sans flex-1",style:{fontSize:`${l}px`},children:e(pu,{content:t,file:r,active:m,onExit:c})})})}function Ze(t,r){return r?`Spaces: ${t}`:"Tabs"}function ve({caret:t,eol:r,onSetEol:l,indentWidth:m,insertSpaces:c,language:b,byteViewer:w,viewerKind:k,lineCount:y,conflicts:h=0}){return e("footer",{className:"flex bg-canvas border-t border-ink/10 px-3 items-center justify-between text-[10px] text-ink/50 flex-shrink-0 font-mono h-6","data-editor-status-bar":"",children:[e("div",{className:"flex items-center gap-3 min-w-0",children:w?e("span",{className:"uppercase",children:Xo[k]}):e(d,{children:[e("span",{className:"tabular-nums",children:t?`Ln ${t.line}, Col ${t.column}`:"Ln —, Col —"}),e("span",{children:Ze(m,c)}),e("button",{type:"button",onClick:()=>l(r==="lf"?"crlf":"lf"),className:"uppercase hover:text-ink transition-colors cursor-pointer",title:`Line endings: ${r.toUpperCase()} — click to switch`,"aria-label":`Line endings ${r.toUpperCase()}, switch`,children:r}),e("span",{children:[y," lines"]})]})}),e("div",{className:"flex items-center gap-3 min-w-0",children:[h>0&&e("span",{className:"text-error font-semibold tabular-nums",title:`${h} unresolved conflict${h===1?"":"s"} — markers are highlighted in the file`,children:["⚠ ",h," conflict",h===1?"":"s"]}),e("span",{className:"uppercase text-ink/40",children:b})]})]})}function Ge(t){if(t===0)return 0;return Math.max(-1,Math.min(1,-Math.sign(t)))}function qe(t,r,l=El,m=Bl){return Math.max(l,Math.min(m,t+r))}function je(t,r){let l=t instanceof HTMLElement?t:null;while(l&&l!==r){let m=getComputedStyle(l);if(/(auto|scroll)/.test(m.overflowY)&&l.scrollHeight>l.clientHeight)return!0;l=l.parentElement}return!1}function xe(t,r){o(()=>{if(!t)return;let l=t.closest("[data-code-surface]"),m=l instanceof HTMLElement?l:t,c=(b)=>{if(!b.ctrlKey&&!b.metaKey)return;if(b.preventDefault(),je(b.target,m))return;let w=Ge(b.deltaY);if(w===0)return;r((k)=>qe(k,w))};return t.addEventListener("wheel",c,{passive:!1}),()=>t.removeEventListener("wheel",c)},[t,r])}function we(t,r){let l=t.trim();if(!/^\d+$/.test(l))return null;let m=Number(l);if(m<1)return null;return Math.min(m,Math.max(r,1))}function ke({lineCount:t,onGo:r,onClose:l}){let[m,c]=n(""),b=i(null);o(()=>{b.current?.focus(),b.current?.select()},[]);let w=()=>{let h=we(m,t);if(h===null)return;r(h)},k=(h)=>{if(h.key==="Enter"){h.preventDefault(),w();return}if(h.key==="Escape")h.preventDefault(),l()},y=we(m,t);return e(X,{onClose:l,maxWidthClass:"max-w-xs",header:e("span",{className:"text-sm font-semibold text-ink",children:"Go to line"}),children:e("div",{className:"px-4 py-3 space-y-2",children:[e("div",{className:"flex items-center gap-2",children:[e("input",{ref:b,value:m,onInput:(h)=>c(h.target.value),onKeyDown:k,inputMode:"numeric",placeholder:"1","aria-label":"Line number",className:"flex-1 bg-paper border border-ink/20 rounded px-2 py-1 text-xs font-mono text-ink outline-none focus:border-ink/40"}),e("span",{className:"text-[10px] font-mono text-ink/40",children:["/ ",t]}),e("button",{type:"button",onClick:w,disabled:y===null,className:"flex items-center gap-1 px-2 py-1 rounded bg-ink text-paper text-xs disabled:opacity-40 disabled:cursor-default cursor-pointer",children:[e(Xe,{size:12}),"Go"]})]}),m&&y!==null&&String(y)!==m.trim()?e("div",{className:"text-[10px] text-ink/50 font-mono",children:["line ",y," (the last line)"]}):null,m&&y===null?e("div",{className:"text-[10px] text-error font-mono",children:"Enter a line number"}):null]})})}var Ee={status:"idle",payload:null,message:null};function Se(t){if(!t?.path)return"";return`${t.root??""}\x00${t.repo??""}\x00${t.path}`}function Te(t,r={}){let l=r.enabled!==!1&&Boolean(t?.path)&&t?.deviceFile!==!0,m=r.dirty===!0,c=Se(t),[b,w]=n({key:"",value:Ee}),k=i(t);k.current=t;let y=i(c);y.current=c;let h=i(l);h.current=l;let x=i(m);x.current=m;let T=i(b);T.current=b;let M=i(0),g=i(""),v=i(new Map),C=i(new Set),P=a(async()=>{let E=k.current;if(!E?.path)return;let O=Se(E),H=++M.current;g.current=O,w((A)=>({key:O,value:{status:"loading",payload:A.key===O?A.value.payload:null,message:null}}));let F=new URLSearchParams({blame:"1",file:E.path,repo:E.repo||"."});if(E.root)F.set("root",E.root);try{let A=await fetch(`/api/fs/git?${F.toString()}`),z=await A.json().catch(()=>null);if(H!==M.current)return;if(!A.ok||!z){w({key:O,value:{status:"error",payload:null,message:z?.error??`Blame request failed (HTTP ${A.status})`}});return}w({key:O,value:z.available?{status:"ready",payload:z,message:null}:{status:"unavailable",payload:z,message:z.message??null}})}catch(A){if(H!==M.current)return;w({key:O,value:{status:"error",payload:null,message:A instanceof Error?A.message:"Blame failed"}})}finally{if(g.current===O)g.current=""}},[]),N=a(async(E)=>{let O=v.current.get(E);if(O)return O;let H=k.current;if(!H?.path)return{entries:[],truncated:!1};let F=new URLSearchParams({blameHistory:"1",file:H.path,line:String(E),repo:H.repo||"."});if(H.root)F.set("root",H.root);try{let z=await(await fetch(`/api/fs/git?${F.toString()}`)).json().catch(()=>null),Z={entries:Array.isArray(z?.entries)?z.entries:[],truncated:z?.truncated===!0};return v.current.set(E,Z),Z}catch{return{entries:[],truncated:!1}}},[]),R=i(null);if(!R.current)R.current={ensure:()=>{if(!h.current||x.current)return;let E=T.current;if(E.key===y.current&&E.value.status!=="idle")return;if(g.current===y.current)return;P()},reload:()=>{v.current.clear(),P()},history:N,snapshot:()=>{let E=T.current;return E.key===y.current?E.value:Ee},stale:()=>x.current,subscribe:(E)=>(C.current.add(E),()=>{C.current.delete(E)})};o(()=>{if(!l||m||!c)return;v.current.clear(),P()},[l,m,c,P]);let V=i(m);return o(()=>{if(V.current===m)return;V.current=m;for(let E of C.current)E()},[m]),o(()=>{for(let E of C.current)E()},[b]),R.current}var Ye="0".repeat(40);function ie(t){return t===Ye}function J(t,r=Date.now()){let l=Math.max(0,Math.floor(r/1000)-t);if(l<60)return"just now";let m=Math.floor(l/60);if(m<60)return`${m}m ago`;let c=Math.floor(m/60);if(c<24)return`${c}h ago`;let b=Math.floor(c/24);if(b<30)return`${b}d ago`;let w=Math.floor(b/30);if(w<12)return`${w}mo ago`;return`${Math.floor(b/365)}y ago`}function Ce(t,r){switch(t){case"not-repo":return"This folder is not a git repository.";case"no-commit":return"This repository has no commits yet.";case"untracked":return"This file has never been committed, so it has no history.";case"too-large":return r??"This file is too large to blame.";case"empty":return"This file is empty.";default:return r??"git could not read this file."}}var Le="fixed z-50 w-[min(340px,92vw)] rounded-xl border border-ink/20 bg-paper p-3 shadow-xl font-sans text-xs text-ink",Be="flex items-baseline justify-between gap-2",Re="truncate text-xs font-semibold text-ink",Je="shrink-0 font-mono text-[10px] text-ink/40",Qe="mt-1 line-clamp-2 text-[11px] leading-snug text-ink/80",tt="mt-2 border-t border-ink/10 pt-2",ot="flex items-center gap-2 font-mono text-[10px] text-ink/40",Me="mt-1 text-[10px] leading-snug text-ink/50",nt="mt-2 flex w-full items-center gap-1.5 text-left text-[10px] text-ink/50 hover:text-ink cursor-pointer",rt="mt-1.5 space-y-1 border-t border-ink/10 pt-1.5",le="flex items-center gap-1.5 font-mono text-[10px]";function L(t,r,l){let m=document.createElement(t);if(m.className=r,l!==void 0)m.textContent=l;return m}function it(t){return new Date(t*1000).toLocaleDateString(void 0,{day:"numeric",month:"short",year:"numeric"})}function at(t){let r=t.payload;if(t.status==="error")return{title:"Blame failed",body:t.message??"git could not read this file."};if(t.status==="unavailable")return{title:r?.reason==="untracked"?"Not tracked":"No history",body:Ce(r?.reason??"error",t.message??void 0)};if(!r)return null;if(t.stale)return{title:"Not committed yet",body:"This line changed in the editor. Save the file to see its blame."};if(t.line>r.lines)return{title:"Not committed yet",body:`Line ${t.line} is past the end of the file at HEAD (${r.lines} lines).`};let l=r.runs.length>0?Ne(r,t.line):null;if(!l)return{title:"Not committed yet",body:`git has no attribution for line ${t.line}.`};if(ie(l.sha))return{title:"Not committed yet",body:"This line differs from the last commit."};return null}function Ne(t,r){for(let l of t.runs)if(r>=l.from&&r<=l.to)return t.commits[l.sha]??null;return null}function lt(t,r){t.replaceChildren(),t.className=Le;let l=at(r);if(l){let h=L("div",Be);if(h.append(L("span",Re,l.title)),r.status==="error"&&r.message){let x=L("button","shrink-0 cursor-pointer text-[10px] text-ink/50 hover:text-ink","Try again");x.type="button",x.setAttribute("aria-label","Read the blame again"),h.append(x)}t.append(h,L("p",Me,l.body));return}let m=r.payload;if(!m){t.append(L("p",Me,"Reading blame…"));return}let c=Ne(m,r.line),b=L("div",Be);if(b.append(L("span",Re,c.author.trim()||"Unknown"),L("span",Je,J(c.time))),t.append(b),c.summary)t.append(L("p",Qe,c.summary));let w=L("div",`${ot} ${tt}`);if(w.append(L("code","truncate",c.sha.slice(0,7)),L("span","",it(c.time))),c.mail){let h=L("span","truncate",c.mail);h.title=c.mail,w.append(h)}t.append(w);let k=L("button",nt);if(k.type="button",k.setAttribute("aria-expanded",r.historyOpen?"true":"false"),k.textContent=`${r.historyOpen?"▾":"▸"} Line history`,t.append(k),!r.historyOpen)return;let y=L("ol",rt);if(r.historyLoading)y.append(L("li",`${le} text-ink/40`,"Reading history…"));else if(!r.history||r.history.entries.length===0)y.append(L("li",`${le} text-ink/40`,"No commits touched this line."));else{let h=r.history.entries;if(h.forEach((x,T)=>{let M=L("li",le),g=T===h.length-1?"new":"edit";M.append(L("span","text-ink/40",T===0?"●":"○"),L("code","text-ink/60",x.sha.slice(0,7)),L("span","truncate text-ink/80",x.author.trim()||"Unknown"),L("span","ml-auto shrink-0 text-ink/40",J(x.time)),L("span","shrink-0 rounded bg-ink/5 px-1 text-[8.5px] uppercase tracking-wider text-ink/45",g)),y.append(M)}),r.history.truncated)y.append(L("li",`${le} text-ink/40`,"Older commits are not shown."))}t.append(y)}function Pe(t,r,l){let m=L("div",Le);m.setAttribute("role","dialog"),m.setAttribute("aria-label","Line blame"),m.addEventListener("mousedown",(x)=>x.stopPropagation());let c=null,b=!1,w=!1,k=()=>{let x=r.snapshot();return{line:t,status:x.status,payload:x.payload,message:x.message,stale:r.stale(),history:c,historyOpen:b,historyLoading:w}},y=()=>{lt(m,k());let x=m.querySelector('[aria-label="Read the blame again"]');if(x)x.addEventListener("click",(T)=>{T.stopPropagation(),l()});m.querySelector("button[aria-expanded]")?.addEventListener("click",(T)=>{if(T.stopPropagation(),b=!b,y(),!b||c||w)return;w=!0,y(),r.history(t).then((M)=>{c=M,w=!1,y()})})};y();let h=r.subscribe(y);return{element:m,place(x){let T=m.ownerDocument.defaultView,M=T?.innerWidth??1024,g=T?.innerHeight??768,v=m.offsetWidth||340,C=m.offsetHeight||120,P=8,N=Math.max(8,Math.min(x.left,M-v-8)),R=x.bottom+6,V=x.top-C-6,_=R+C>g-8&&V>8?V:R;m.style.left=`${N}px`,m.style.top=`${Math.max(8,_)}px`},destroy(){h(),m.remove()}}}function De(t){return ye.define((r)=>{let l=null,m=0,c,b=()=>{clearTimeout(c),c=void 0,l?.destroy(),l=null,m=0},w=(g,v)=>{let C=g.getBoundingClientRect();if(C.width>0)return{left:C.left,top:C.top,bottom:C.bottom};let P=r.state.doc.line(Math.min(v,r.state.doc.lines)),N=null;try{N=r.coordsAtPos(P.from)}catch{N=null}if(N)return N;let R=r.scrollDOM.getBoundingClientRect();return{left:R.left,top:R.top+24,bottom:R.top+24}},k=(g,v)=>{if(m===g&&l)return;b(),m=g,l=Pe(g,t,()=>{t.reload(),b()}),document.body.append(l.element),l.place(v)},y=(g)=>{let v=g.target,C=v?.closest?.(".cm-blame-label");if(C){let R=Number(C.dataset.blameLine);return Number.isInteger(R)&&R>0?{line:R,anchor:C}:null}let P=v?.closest?.(".cm-lineNumbers .cm-gutterElement");if(!P)return null;let N=Number((P.textContent??"").trim());return Number.isInteger(N)&&N>0?{line:N,anchor:P}:null},h=(g)=>{let v=y(g);if(!v)return;k(v.line,w(v.anchor,v.line))},x=(g)=>{let v=y(g);if(v){g.preventDefault(),k(v.line,w(v.anchor,v.line));return}if(l&&!l.element.contains(g.target))b()},T=(g)=>{if(g.key==="Escape"&&l)b(),g.stopPropagation()},M=(g)=>{if(!l)return;let v=g.relatedTarget;if(v&&(l.element.contains(v)||r.scrollDOM.contains(v)))return;c=setTimeout(b,200)};return r.scrollDOM.addEventListener("mouseover",h),r.scrollDOM.addEventListener("mouseleave",M),r.scrollDOM.addEventListener("mousedown",x),document.addEventListener("mousedown",x),document.addEventListener("keydown",T,!0),{update(g){if(g.docChanged&&l)b()},destroy(){b(),r.scrollDOM.removeEventListener("mouseover",h),r.scrollDOM.removeEventListener("mouseleave",M),r.scrollDOM.removeEventListener("mousedown",x),document.removeEventListener("mousedown",x),document.removeEventListener("keydown",T,!0)}}})}var Ae=40,ze=oe.define();function st(t){return Oe.define({create:()=>({payload:t.snapshot().payload,stale:!1}),update(r,l){let m=r;for(let c of l.effects){if(!c.is(ze))continue;m=c.value.payload!==r.payload?{payload:c.value.payload,stale:!1}:{payload:r.payload,stale:r.stale}}if(l.docChanged&&!m.stale)m={payload:m.payload,stale:!0};return m}})}function mt(t,r,l){let m=t.commits[r];if(!m||ie(r))return null;let c=m.author.trim()||"Unknown";return l?c:`${c} · ${J(m.time)}`}class He extends Mt{constructor(t,r,l){super();this.line=t;this.text=r;this.title=l}eq(t){return t.line===this.line&&t.text===this.text&&t.title===this.title}toDOM(){let t=document.createElement("span");return t.className="cm-blame-label",t.dataset.blameLine=String(this.line),t.title=this.title,t.textContent=this.text,t}}function Ie(t,r,l){let{payload:m,stale:c}=t;if(!m?.available||c)return D.none;let b=Math.min(m.lines,r.state.doc.lines);if(b<1)return D.none;let w=r.state.doc.lineAt(Math.max(0,Math.min(r.viewport.from,r.state.doc.length))).number,k=r.state.doc.lineAt(Math.max(0,Math.min(r.viewport.to,r.state.doc.length))).number,y=Math.max(1,w-Ae),h=Math.min(b,k+Ae),x=[];for(let T of m.runs){let M=Math.max(T.from,y);if(M>T.to||M>h)continue;let g=mt(m,T.sha,l);if(!g)continue;let v=m.commits[T.sha],C=r.state.doc.line(M);x.push({from:C.to,deco:D.widget({widget:new He(C.number,g,v.summary||v.sha),side:1})})}return D.set(x.map((T)=>T.deco.range(T.from)),!0)}function ct(t,r){return ye.fromClass(class{constructor(l){this.view=l;this.decorations=Ie(l.state.field(t),l,r)}update(l){if(l.startState.field(t)===l.state.field(t)&&!l.docChanged&&!l.viewportChanged)return;this.decorations=Ie(l.state.field(t),l.view,r)}},{decorations:(l)=>l.decorations})}function dt(t){return ye.define((r)=>{let l=!0,m=()=>{if(!l)return;let b=t.snapshot();r.dispatch({effects:ze.of({payload:b.payload,stale:!1})})},c=t.subscribe(m);return{destroy(){l=!1,c()}}})}function Ve({controller:t,inline:r=!0,compact:l=!1}){let m=st(t);return[m,dt(t),r?ct(m,l):[],De(t)]}function Fe({activeFile:t,editor:r,find:l,surfaceRef:m,goToLineRequest:c,rootPath:b=null,repoPath:w=null,onRunCommand:k,wordWrap:y,zoomLevel:h,setZoomLevel:x,editorFontFamily:T,editorTheme:M,viewerKind:g,isPreview:v,reviewActive:C,onToggleReview:P,revealActive:N}){let R=g==="markdown",V=Lu(),_=Mu(),E=cp(),O=Te({name:t.name,path:t.path,root:t.root??b??void 0,repo:t.repo??w??"."},{enabled:E.enabled,dirty:r.isDirty}),H=u(()=>E.enabled?Ve({controller:O,inline:E.inline}):null,[E.enabled,E.inline,O]),[F,A]=n(null),z=u(()=>mu(r.content),[r.content]),[Z,W]=n(!1);o(()=>{if(c>0)W(!0)},[c]);let[K,Q]=n(null),[se,q]=n(null);xe(K,x);let j=Zs({tabKey:String(t.id),surface:R&&v?"rendered":"code",ready:r.loaded,element:R&&v?void 0:K}),ee=a((G)=>{j.ref(G),q(G)},[j.ref]);return Au({path:t.path,scroller:se,preview:R&&v}),e("div",{className:"relative flex-1 min-h-0 flex flex-col",children:[l.open?e(gu,{find:l}):null,Z?e(ke,{lineCount:r.content?r.content.split(`
2
2
  `).length:1,onGo:(G)=>{W(!1);let Y=cr(r.content,G-1);m.current?.select(Y,Y,!0),m.current?.revealOffset(Y)},onClose:()=>W(!1)}):null,R&&v?e(ge,{content:r.content,file:{name:t.name,path:t.path,root:t.root,repo:t.repo},zoomLevel:h,reviewActive:C,onExitReview:P,scrollRef:ee,onScroll:j.onScroll}):e(fu,{ref:m,value:r.content,onValueChange:r.onChange,language:r.language,wordWrap:y,documentKey:String(t.id),marks:l.open||N?l.matches:void 0,currentMark:l.currentIndex,onCommand:k,onScroller:Q,onCaret:A,scrollTestId:"editor-scroller",className:"flex-1 min-h-0 text-ink select-text",blame:H,themeVars:M.vars,themes:M.themes,indentUnitText:Ru(V),typing:_,padding:16,placeholder:"This file is empty",style:{fontFamily:T,fontSize:`${h}px`,lineHeight:ys}}),!R||!v?e(ve,{caret:F,eol:r.eol,onSetEol:r.setEol,indentWidth:V.width,insertSpaces:V.insertSpaces,language:r.language,byteViewer:r.isBinaryViewer,viewerKind:g,lineCount:r.content?r.content.split(`
3
3
  `).length:0,conflicts:z}):null]})}function We({activeFile:t,editor:r,find:l,surfaceRef:m,pluginFileView:c,wordWrap:b,setWordWrap:w,viewerKind:k,isPreview:y,isReviewing:h,onToggleReview:x,isMaximized:T,setIsMaximized:M,zoomLevel:g,setZoomLevel:v,goToLineRequest:C,onSaveAs:P,rootPath:N=null,repoPath:R=null,runCommand:V,editorFontFamily:_,editorTheme:E,togglePreview:O,revealActive:H,missing:F}){let A=Ls[k]===!0,z=ku[k]===!0,Z=a(async(W)=>{let K=await bu(t,W,{interactive:!0,baseMtimeMs:r.baseMtimeMs});if(K.status==="written")return{ok:!0};if(K.status==="conflict")return{ok:!1,error:"This file changed on disk since it was opened."};if(K.status==="needs-permission")return{ok:!1,error:"Click Save again to grant write access."};return{ok:!1,error:K.error}},[t,r.baseMtimeMs]);return e(d,{children:[e(he,{path:t.path,saveStatus:r.saveStatus,wordWrap:b,hasPreview:z,isPreview:y,hasReview:k==="markdown"&&y,isReviewing:h,copied:r.copied,byteViewer:A,saveDisabled:Boolean(r.loadError)||r.handleMissing||r.deviceBacked,unsupported:Boolean(r.unsupported),handleMissing:r.handleMissing,readOnly:r.deviceBacked,isMaximized:T,findOpen:l.open,onToggleFind:()=>l.open?l.close():l.openFind(),onSave:r.saveNow,onTogglePreview:O,onToggleReview:x,onToggleWordWrap:()=>w(!b),onZoomIn:()=>v((W)=>Math.min(Bl,W+1)),onZoomOut:()=>v((W)=>Math.max(El,W-1)),onCopy:r.copy,onDownload:r.download,onReload:r.reloadFromDisk,onSaveAs:P,canReload:zl(t)&&!r.loadError&&!r.unsupported,refreshing:r.isReading,reloadDiscardsEdits:r.isDirty,onToggleMaximize:()=>M(!T)}),F&&e("div",{className:"flex items-start gap-2 px-3 py-2 border-b border-error/30 bg-error/10 text-error",children:[e(I,{size:14,className:"shrink-0 mt-0.5"}),e("div",{className:"min-w-0",children:[e("div",{className:"text-[11.5px] font-sans",children:"This file was deleted from disk."}),e("div",{className:"text-[11px] font-sans text-error/80",children:"The buffer is still here. Saving recreates the file — autosave is off until then."})]})]}),r.conflict&&e(Su,{diskMtimeMs:r.conflict.diskMtimeMs,fileName:t.name,onReload:r.resolveConflictByReload,onKeepMine:r.resolveConflictByKeepingMine}),r.handleMissing&&e("div",{className:"flex items-start gap-2 px-3 py-2 border-b border-warning/30 bg-warning/10 text-warning",children:[e(I,{size:14,className:"shrink-0 mt-0.5"}),e("div",{className:"min-w-0",children:[e("div",{className:"text-[11.5px] font-sans",children:"This file was opened by the system, not from a workspace."}),e("div",{className:"text-[11px] font-sans text-warning/80",children:"Its write permission ended with the last page load. Reopen the file from the OS to edit it again."})]})]}),r.deviceBacked&&e("div",{className:"flex items-start gap-2 px-3 py-2 border-b border-ink/20 bg-ink/5 text-ink/70",children:[e(I,{size:14,className:"shrink-0 mt-0.5"}),e("div",{className:"min-w-0",children:[e("div",{className:"text-[11.5px] font-sans",children:r.deviceMissing?"The bytes for this file did not survive the reload.":"Opened from this device, so it is read-only here."}),e("div",{className:"text-[11px] font-sans text-ink/50",children:r.deviceMissing?"A phone's file lives only on the phone, so it cannot be re-read. Open it again from the app that shared it.":"The console cannot reach a file on your phone. Copy it into a workspace to edit it."})]})]}),r.isImage&&r.imageUrl?e(Ri,{src:r.imageUrl,name:t.name,className:"flex-1 min-h-0"}):r.isImage?e($l,{kind:"image",path:t.path,name:t.name,source:r.byteSource,content:r.content,revision:r.revision}):r.isLoading?e("div",{className:"flex-1 flex items-center justify-center gap-2 text-ink/40 text-xs font-mono",children:[e(p,{size:14,className:"animate-spin"}),e("span",{children:"Loading file content…"})]}):r.unsupported?e("div",{className:"flex-1 flex flex-col items-center justify-center gap-2 px-6 text-center",children:[e(uu,{size:20,className:"text-ink/40"}),e("span",{className:"text-xs text-ink/70 font-sans",children:[t.name," cannot be opened here"]}),e("span",{className:"text-[11px] text-ink/50 font-sans max-w-[42ch]",children:r.unsupported})]}):r.loadError?e("div",{className:"flex-1 flex flex-col items-center justify-center gap-2 px-6 text-center",children:[e(I,{size:20,className:"text-error"}),e("span",{className:"text-xs text-error font-sans",children:["Could not read ",t.name]}),e("span",{className:"text-[11px] text-ink/50 font-mono break-all",children:r.loadError})]}):c&&!r.isImage?e(EA,{view:c}):hu(k)&&(A||y)?e($l,{kind:k,path:t.path,name:t.name,source:r.byteSource,content:r.content,root:t.root??N,repo:t.repo??R,revision:r.revision,onContentChange:r.onChange,onSaveBytes:r.deviceBacked?void 0:Z,onDirtyChange:r.setBinaryDirty}):e(Fe,{activeFile:t,editor:r,find:l,surfaceRef:m,goToLineRequest:C,rootPath:N,repoPath:R,onRunCommand:V,wordWrap:b,zoomLevel:g,setZoomLevel:v,editorFontFamily:_,editorTheme:E,isPreview:y,reviewActive:h,onToggleReview:x,viewerKind:k,revealActive:H})]})}function en({activeFile:t,editor:r,find:l,surfaceRef:m,pluginFileView:c,wordWrap:b,setWordWrap:w,viewerKind:k,isPreview:y,isReviewing:h,onToggleReview:x,isMaximized:T,setIsMaximized:M,zoomLevel:g,setZoomLevel:v,goToLineRequest:C,onSaveAs:P,rootPath:N=null,repoPath:R=null,runCommand:V,editorFontFamily:_,editorTheme:E,togglePreview:O,revealActive:H,missing:F,onConvertDiffToEditor:A,onFileSaved:z}){if(!t)return e("div",{className:"flex-1 flex items-center justify-center text-ink/40",children:e("p",{className:"font-mono text-sm",children:"Select a tab to view content"})});if(t.isDiff)return e(du,{filePath:t.path,status:t.diffStatus||"M",isStaged:Boolean(t.diffStaged),root:t.root,repo:t.repo||".",journalDiff:t.journalDiff,readOnly:t.diffSource==="journal",onOpenInEditor:()=>A(t.id),onFileSaved:z,className:"flex-1",tabKey:String(t.id)});return e(We,{activeFile:t,editor:r,find:l,surfaceRef:m,pluginFileView:c,wordWrap:b,setWordWrap:w,viewerKind:k,isPreview:y,isReviewing:h,onToggleReview:x,isMaximized:T,setIsMaximized:M,zoomLevel:g,setZoomLevel:v,goToLineRequest:C,onSaveAs:P,rootPath:N,repoPath:R,runCommand:V,editorFontFamily:_,editorTheme:E,togglePreview:O,revealActive:H,missing:F})}export{en as EditorBody};
@@ -1,2 +1,2 @@
1
- import{u,e}from"./index-qrwjxqdh.js";import{yu,xA,cg,vu}from"./index-jtyzeynv.js";function w({content:d,path:l,onChange:s}){let r=u(()=>xA(d,l),[d,l]),o=s!==void 0&&!r.truncated,a=d.endsWith(`
1
+ import{u,e}from"./index-nr5gwny1.js";import{yu,xA,cg,vu}from"./index-g71wn1pr.js";function w({content:d,path:l,onChange:s}){let r=u(()=>xA(d,l),[d,l]),o=s!==void 0&&!r.truncated,a=d.endsWith(`
2
2
  `),c=o?(i,n,t)=>{s(cg(r.header,vu(r.rows,i,n,t),r.delimiter,a))}:void 0,h=o?(i,n)=>{let t=r.header.slice();while(t.length<=i)t.push("");t[i]=n,s(cg(t,r.rows,r.delimiter,a))}:void 0;return e(yu,{header:r.header,rows:r.rows,truncated:r.truncated,readOnlyNote:r.truncated?"This file is too large to edit in the grid — use Show source.":o?"Paste is not supported — double-click a cell to edit it.":"This grid is read-only — use Show source to edit the cells.",onEditCell:c,onEditHeader:h})}export{w as CsvGrid};