@kabmo-labs/kabmo 0.56.0 → 0.57.1

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 (129) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +3 -3
  3. package/dist/client/static/js/{Body-jfy4bhk2.js → Body-p6zwk0nx.js} +1 -1
  4. package/dist/client/static/js/{CsvGrid-4c5t668z.js → CsvGrid-563qmmmr.js} +1 -1
  5. package/dist/client/static/js/{DocxView-3x7whtvq.js → DocxView-5j69q3s0.js} +1 -1
  6. package/dist/client/static/js/{DrawioView-tbkc5dfz.js → DrawioView-gd6k3hvn.js} +1 -1
  7. package/dist/client/static/js/{HtmlPreview-egxkayya.js → HtmlPreview-6gnktzzp.js} +1 -1
  8. package/dist/client/static/js/{ImageView-swhzvw2p.js → ImageView-fkfq3fwv.js} +1 -1
  9. package/dist/client/static/js/{LayoutWrapper-sangsrt5.js → LayoutWrapper-mdb1qm26.js} +1 -1
  10. package/dist/client/static/js/MergeDiffView-7kpjxcg9.js +1 -0
  11. package/dist/client/static/js/{Modal-1fj8kvme.js → Modal-0p9cr2tn.js} +12 -12
  12. package/dist/client/static/js/{PdfView-0k2egsbz.js → PdfView-n1zq27td.js} +1 -1
  13. package/dist/client/static/js/{SessionsView-t547rqeb.js → SessionsView-gptt0rq8.js} +1 -1
  14. package/dist/client/static/js/{SheetView-anb3gavm.js → SheetView-nes7j86v.js} +1 -1
  15. package/dist/client/static/js/{SvgPreview-e2wrj2hj.js → SvgPreview-vv0qzkt7.js} +1 -1
  16. package/dist/client/static/js/{abnfDiagram-O67JEVCF-0rs86b68.js → abnfDiagram-O67JEVCF-02g96sn6.js} +1 -1
  17. package/dist/client/static/js/{architectureDiagram-NJMV4G6O-0k3zzxz1.js → architectureDiagram-NJMV4G6O-7qj2fpwt.js} +1 -1
  18. package/dist/client/static/js/{blockDiagram-BEXU5L5S-t1n1fx96.js → blockDiagram-BEXU5L5S-grdr1j2h.js} +3 -3
  19. package/dist/client/static/js/{c4Diagram-YGBWAQC7-93b7eds9.js → c4Diagram-YGBWAQC7-7y980xpx.js} +2 -2
  20. package/dist/client/static/js/{classDiagram-v2-NBCMYWYE-bnf85z0f.js → classDiagram-v2-NBCMYWYE-29ag4js1.js} +1 -1
  21. package/dist/client/static/js/{cose-bilkent-JH36ORCC-e290161f.js → cose-bilkent-JH36ORCC-e5dvgehd.js} +1 -1
  22. package/dist/client/static/js/{cynefinDiagram-VND7K2PF-s13ra9ag.js → cynefinDiagram-VND7K2PF-eq6fmx0b.js} +1 -1
  23. package/dist/client/static/js/{dagre-6A5THRUB-83wshh5e.js → dagre-6A5THRUB-xfhwp8ha.js} +1 -1
  24. package/dist/client/static/js/{diagram-22UHCM2B-ywh4wqna.js → diagram-22UHCM2B-1bw6x6zt.js} +1 -1
  25. package/dist/client/static/js/{diagram-3UASUU5V-cb53z698.js → diagram-3UASUU5V-076ej5n5.js} +1 -1
  26. package/dist/client/static/js/{diagram-ATOU4E4O-btf55c44.js → diagram-ATOU4E4O-cvf9fhdq.js} +1 -1
  27. package/dist/client/static/js/{diagram-CDSNMT55-p6tbbm1n.js → diagram-CDSNMT55-hn1wdx54.js} +3 -3
  28. package/dist/client/static/js/{diagram-MLGK6HIB-6kzssf4y.js → diagram-MLGK6HIB-76gk27b5.js} +1 -1
  29. package/dist/client/static/js/{diagram-MPIPVDR6-4v0yncvv.js → diagram-MPIPVDR6-0cbajhpx.js} +1 -1
  30. package/dist/client/static/js/{dockerfile-r422htmd.js → dockerfile-7atfjhnf.js} +1 -1
  31. package/dist/client/static/js/{ebnfDiagram-ZINNZB2B-mw1gh30z.js → ebnfDiagram-ZINNZB2B-n0g3b9m2.js} +1 -1
  32. package/dist/client/static/js/{elk-276RUBZZ-1pe786ap.js → elk-276RUBZZ-f6wrjcv9.js} +1 -1
  33. package/dist/client/static/js/{erDiagram-OPXOYQCR-x7rk70q6.js → erDiagram-OPXOYQCR-jz622yrg.js} +1 -1
  34. package/dist/client/static/js/flowDiagram-KWPJA3E3-5bvd5k2t.js +1 -0
  35. package/dist/client/static/js/{ganttDiagram-FUAMR5RP-j3m5km4p.js → ganttDiagram-FUAMR5RP-2ex4nxyg.js} +2 -2
  36. package/dist/client/static/js/{gitGraphDiagram-X574FWY7-fd1kebdy.js → gitGraphDiagram-X574FWY7-38eyay6g.js} +1 -1
  37. package/dist/client/static/js/{index-zkef5q39.js → index-1q934wfk.js} +1 -1
  38. package/dist/client/static/js/{index-5fxm2tpg.js → index-28wv94gz.js} +1 -1
  39. package/dist/client/static/js/{index-4jg10xtp.js → index-3wgjtp2k.js} +1 -1
  40. package/dist/client/static/js/{index-29b1ysz6.js → index-4cff0zg2.js} +1 -1
  41. package/dist/client/static/js/{index-8e66p2a7.js → index-55v3qv04.js} +1 -1
  42. package/dist/client/static/js/{index-s4v3vcsn.js → index-63mk2qk6.js} +1 -1
  43. package/dist/client/static/js/{index-4dzvjfkd.js → index-6z30g3ha.js} +1 -1
  44. package/dist/client/static/js/{index-473wm10a.js → index-7trfm17d.js} +1 -1
  45. package/dist/client/static/js/{index-drsy400d.js → index-8444mec5.js} +1 -1
  46. package/dist/client/static/js/{index-j1prebvy.js → index-9gfn1a3h.js} +1 -1
  47. package/dist/client/static/js/{index-qdabc51h.js → index-ays8t3t3.js} +2 -2
  48. package/dist/client/static/js/{index-q4t5j3x7.js → index-cxe75e06.js} +1 -1
  49. package/dist/client/static/js/{index-22frp78d.js → index-db7vsjkd.js} +1 -1
  50. package/dist/client/static/js/{index-7tsdw8wt.js → index-dmb1pykr.js} +1 -1
  51. package/dist/client/static/js/{index-tcp5cp53.js → index-ep99arz1.js} +1 -1
  52. package/dist/client/static/js/{index-0mhxw0a1.js → index-ewst55j2.js} +1 -1
  53. package/dist/client/static/js/{index-hgsjynb0.js → index-fqc1snjw.js} +1 -1
  54. package/dist/client/static/js/{index-rm5b3kn8.js → index-g2e0m757.js} +3 -3
  55. package/dist/client/static/js/{index-3k45gspr.js → index-jaxhfk9x.js} +1 -1
  56. package/dist/client/static/js/{index-satnfvaz.js → index-jsn2kedv.js} +1 -1
  57. package/dist/client/static/js/{index-bxhszdcz.js → index-n1xmkf2g.js} +1 -1
  58. package/dist/client/static/js/{index-004x0a3p.js → index-pe4d9wht.js} +1 -1
  59. package/dist/client/static/js/{index-cbbwq25c.js → index-pjf5wak8.js} +1 -1
  60. package/dist/client/static/js/{index-8n4qwd64.js → index-sm8gpk3g.js} +2 -2
  61. package/dist/client/static/js/{index-qrwjxqdh.js → index-st6a8q5z.js} +176 -176
  62. package/dist/client/static/js/{index-dfha2z56.js → index-stmwbavz.js} +1 -1
  63. package/dist/client/static/js/index-swaveqxg.css +1 -0
  64. package/dist/client/static/js/{index-3hrvhyym.js → index-t82q5t6m.js} +1 -1
  65. package/dist/client/static/js/{index-s6nv35dv.js → index-t9zjfxvc.js} +1 -1
  66. package/dist/client/static/js/{index-jbaceghb.js → index-tdbcp70z.js} +1 -1
  67. package/dist/client/static/js/{index-kbk0vmex.js → index-tdryzzy9.js} +1 -1
  68. package/dist/client/static/js/{index-jtyzeynv.js → index-tksrpqkh.js} +1 -1
  69. package/dist/client/static/js/{index-g84dwmvr.js → index-v38j2zxn.js} +1 -1
  70. package/dist/client/static/js/{index-4nyajpeg.js → index-x17y7xdr.js} +1 -1
  71. package/dist/client/static/js/{index-4fpyzg5e.js → index-xfnjwhan.js} +20 -20
  72. package/dist/client/static/js/{index-72v57e07.js → index-xrb4kjr3.js} +1 -1
  73. package/dist/client/static/js/{index-4acka5fn.js → index-zv8wrvha.js} +1 -1
  74. package/dist/client/static/js/{index-q178zgxp.js → index-zynbvm7x.js} +1 -1
  75. package/dist/client/static/js/{index-bnamrpm6.js → index-zzggk17b.js} +1 -1
  76. package/dist/client/static/js/{infoDiagram-VRGFBTTK-1m0br602.js → infoDiagram-VRGFBTTK-c55t0tvd.js} +2 -2
  77. package/dist/client/static/js/{ishikawaDiagram-OU5B5YK6-zryzhpq6.js → ishikawaDiagram-OU5B5YK6-r9kg5kg5.js} +2 -2
  78. package/dist/client/static/js/{journeyDiagram-ZHPQQLJL-6apqr7h4.js → journeyDiagram-ZHPQQLJL-zmmst4v8.js} +2 -2
  79. package/dist/client/static/js/{kanban-definition-PNTS6WVX-am385c1e.js → kanban-definition-PNTS6WVX-3tt6sc9a.js} +1 -1
  80. package/dist/client/static/js/{mermaid.core-k937exrm.js → mermaid.core-pkrs8zp5.js} +2 -2
  81. package/dist/client/static/js/{mindmap-definition-NLK3R4M7-hx8qq866.js → mindmap-definition-NLK3R4M7-b4c6gxg4.js} +1 -1
  82. package/dist/client/static/js/one-dark-pro-sstqnzcf.js +1 -0
  83. package/dist/client/static/js/one-light-6fpxxq2j.js +1 -0
  84. package/dist/client/static/js/{pegDiagram-GJSIUBJH-1hasj2h7.js → pegDiagram-GJSIUBJH-9jkat1mz.js} +1 -1
  85. package/dist/client/static/js/{pieDiagram-5QR66LMP-x5nwff8r.js → pieDiagram-5QR66LMP-6pbchjh7.js} +2 -2
  86. package/dist/client/static/js/{quadrantDiagram-O4NWA36T-gmrcr5jb.js → quadrantDiagram-O4NWA36T-p9brea19.js} +2 -2
  87. package/dist/client/static/js/{railroadDiagram-XR7U4H2S-rdznfhfb.js → railroadDiagram-XR7U4H2S-3cep8css.js} +1 -1
  88. package/dist/client/static/js/{requirementDiagram-PLB6GJNP-v9wb3ppf.js → requirementDiagram-PLB6GJNP-x1yjgsrr.js} +1 -1
  89. package/dist/client/static/js/{rust-9cgnbbcs.js → rust-yy8gekx8.js} +1 -1
  90. package/dist/client/static/js/{sankeyDiagram-IPEJSGJF-3p4ddd2h.js → sankeyDiagram-IPEJSGJF-23wzf4aj.js} +1 -1
  91. package/dist/client/static/js/{sequenceDiagram-PO4LG4MO-wfcqxjfq.js → sequenceDiagram-PO4LG4MO-w4wr3zzr.js} +4 -4
  92. package/dist/client/static/js/{sizeCapture-INFHLROL-g02k0k8x.js → sizeCapture-INFHLROL-aabfesnr.js} +1 -1
  93. package/dist/client/static/js/{stateDiagram-v2-GCMORJYK-7k449yvg.js → stateDiagram-v2-GCMORJYK-t0n288xw.js} +1 -1
  94. package/dist/client/static/js/{swimlanes-2SLR337P-zkf2bgm8.js → swimlanes-2SLR337P-1nnm0p7h.js} +1 -1
  95. package/dist/client/static/js/{swimlanesDiagram-TC7HE7FX-yex8g4fx.js → swimlanesDiagram-TC7HE7FX-cx3f29mq.js} +1 -1
  96. package/dist/client/static/js/{timeline-definition-EJHVYXUP-qsfpjr1c.js → timeline-definition-EJHVYXUP-8pyssn0q.js} +1 -1
  97. package/dist/client/static/js/{usecaseDiagram-POWQR4AR-b2vprhsr.js → usecaseDiagram-POWQR4AR-vveepvt6.js} +1 -1
  98. package/dist/client/static/js/{vennDiagram-UO4OBE2U-x0ffeg2t.js → vennDiagram-UO4OBE2U-tqyvmqxc.js} +4 -4
  99. package/dist/client/static/js/{wardleyDiagram-VNRHLVJA-hsnhaf4f.js → wardleyDiagram-VNRHLVJA-p8rs34em.js} +2 -2
  100. package/dist/client/static/js/{xychartDiagram-PMCCYNJV-90f9aadp.js → xychartDiagram-PMCCYNJV-pgnvxtps.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/components/workspace/chat-timeline/tool-renderers/shared/card-header.ts +10 -8
  108. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/toggle-label.test.ts +37 -0
  109. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/toggle-label.ts +17 -1
  110. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.test.tsx +18 -15
  111. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.tsx +7 -8
  112. package/src/client/data/settings/omp-schema.json +59 -7
  113. package/src/client/hooks/chat/timeline/ask-frames-form.test.ts +29 -0
  114. package/src/server/lib/dictation/capability.server.test.ts +9 -6
  115. package/src/server/lib/dictation/worker-process.ts +9 -2
  116. package/src/shared/lib/chat/ask-form/data.ts +25 -6
  117. package/src/shared/lib/chat/ask-form/deck.ts +80 -0
  118. package/src/shared/lib/chat/ask-form/fields.ts +26 -1
  119. package/src/shared/lib/chat/ask-form/index.ts +18 -310
  120. package/src/shared/lib/chat/ask-form/types.ts +14 -2
  121. package/src/shared/lib/chat/ask-form/walker.ts +350 -0
  122. package/src/shared/lib/chat/ask-form.test.ts +41 -0
  123. package/src/shared/lib/omp/config/schema-releases-19-4.test.ts +47 -0
  124. package/src/shared/lib/omp/config/schema-releases.test.ts +4 -2
  125. package/dist/client/static/js/MergeDiffView-bv00y63x.js +0 -1
  126. package/dist/client/static/js/flowDiagram-KWPJA3E3-kfwaac44.js +0 -1
  127. package/dist/client/static/js/index-gedsa0z7.css +0 -1
  128. package/dist/client/static/js/one-dark-pro-phxqe9mx.js +0 -1
  129. 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-swaveqxg.css"><script type="module" crossorigin src="./static/js/index-st6a8q5z.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.1",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
@@ -2146,7 +2146,7 @@ Target file: @$ARGUMENTS`},{id:"cmd-git-master",name:"git-master",description:"M
2146
2146
  $ARGUMENTS`},{id:"cmd-hyperplan",name:"hyperplan",description:"(builtin) Adversarial multi-agent plan builder",scope:"user",template:"Construct a detailed plan with review gates and adversarial critiques for $ARGUMENTS."},{id:"cmd-init-deep",name:"init-deep",description:"(builtin) Initialize hierarchical AGENTS.md setup",scope:"user",template:"Analyze directory structure and construct domain-specific AGENTS.md files for subpackages: $ARGUMENTS"},{id:"cmd-playwright",name:"playwright",description:"MUST USE for any browser-related testing",scope:"user",template:"Run playwright tests for scenario: $ARGUMENTS\n!`bunx playwright test`"},{id:"cmd-pty-spy",name:"pty-open-background-spy",description:"Open PTY Sessions Web Interface",scope:"user",template:"Launch PTY background session monitor with target: $ARGUMENTS"},{id:"cmd-pty-url",name:"pty-show-server-url",description:"Show PTY Sessions Web Interface URL",scope:"user",template:"Output the active PTY session web socket endpoint and UI URL."},{id:"cmd-refactor",name:"refactor",description:"(builtin) Intelligent refactoring coordinator",scope:"user",template:"Refactor module @$ARGUMENTS into decoupled single-responsibility files without changing public behavior. Keep files under 350 lines."},{id:"cmd-benchmark",name:"benchmark",description:"Run performance benchmark suites and record timings",scope:"user",template:"Execute benchmark suite on target: $ARGUMENTS"},{id:"cmd-bundle-analyze",name:"bundle-analyze",description:"Inspect vendor bundle size and dynamic chunk splitting",scope:"user",template:"Run build analyzer and report chunk weight statistics: !`bun run build`"},{id:"cmd-db-migrate",name:"db-migrate",description:"Review and execute database migrations safely",scope:"user",template:"Review pending schema migrations and verify backward compatibility: $ARGUMENTS"},{id:"cmd-doc-generate",name:"doc-generate",description:"Generate API documentation and usage guides",scope:"user",template:"Draft comprehensive technical documentation for module @$ARGUMENTS"},{id:"cmd-security-scan",name:"security-scan",description:"Run static security analysis and check dependency vulnerabilities",scope:"user",template:"Scan repository for leaked secrets and outdated dependencies: !`npm audit`"},{id:"cmd-test-unit",name:"test-unit",description:"Run unit test suite with coverage report",scope:"user",template:"Run test suite with coverage: !`bun test` - Focus: $ARGUMENTS"},{id:"cmd-typecheck",name:"typecheck",description:"Run strict TypeScript compiler verification",scope:"user",template:"Run strict typecheck without emitting files: !`bunx tsc --noEmit`"}];async function As(e,t){if(t==="user")return{workspace:null,cwd:pe()};if(!e||!e.trim())return{workspace:process.cwd(),cwd:process.cwd()};let n=await be(e,"");return n?{workspace:n,cwd:n}:{workspace:null,cwd:pe()}}import ND from"fs";import{join as fh,resolve as OD}from"path";var LXe=524288,DXe=r3;function FXe(){return th().filter((e)=>e.scope==="user").map(({dir:e,suffix:t})=>({dir:e,suffix:t}))}function ace(e){let t=e.trim().replace(/^\/+/,"");if(!t)return null;if(/[\\/]/.test(t.replace(/:/g,"/"))||t==="."||t==="..")return null;return t}async function sR(e,t){let n=ace(e);if(!n)return null;let r=n.replace(/:/g,"/"),o=[];if(t)for(let i of DXe)o.push({...i,dir:fh(t,i.dir),scope:"project",managed:i.dir===".omp/commands"});for(let i of FXe())o.push({...i,scope:"user",managed:i.dir===fh(pe(),"commands")});for(let i of o){let s=fh(i.dir,`${r}${i.suffix}`);if(await Z(s))return{filePath:s,scope:i.scope,managed:i.managed}}return null}async function cce(e){try{let t=Bun.file(e);if(!await t.exists()||(await t.stat()).size>LXe)return null;let{data:n,body:r}=cg(await t.text());return{description:n.description??"",argumentHint:n["argument-hint"]??n.argumentHint??"",body:r.replace(/^\r?\n/,"")}}catch{return null}}function UXe(e){let t=["---"];if(e.description)t.push(`description: ${JSON.stringify(e.description)}`);if(e.argumentHint)t.push(`argument-hint: ${JSON.stringify(e.argumentHint)}`);return t.push("---","",e.body.replace(/\r\n/g,`
2147
2147
  `).replace(/\s*$/,""),""),t.join(`
2148
2148
  `)}async function lce(e){let t=ace(e.name);if(!t)throw Error("Command name is required");if(e.scope==="project"&&!e.projectDir)throw Error("A workspace root is required to write a project command");let n=e.scope==="project"?fh(e.projectDir,".omp","commands"):fh(pe(),"commands"),r=fh(n,`${t.replace(/:/g,"/")}.md`),o=e.previousName?.trim().replace(/^\/+/,"");if(o&&o!==t){let i=await sR(o,e.projectDir);if(i?.managed&&OD(i.filePath)!==OD(r))await ND.promises.rm(i.filePath,{force:!0})}return await ND.promises.mkdir(OD(r,".."),{recursive:!0}),await kt(r,UXe({description:e.description,argumentHint:e.argumentHint,body:e.body}),{createMode:420}),{filePath:r}}async function uce(e,t){let n=await sR(e,t);if(!n)throw Error(`"${e}" is not a command file Kabmo can delete`);if(!n.managed)throw Error(`"${e}" is provided by ${n.filePath}; Kabmo cannot delete it`);return await ND.promises.rm(n.filePath,{force:!0}),!0}function dce(e){return e instanceof Error?e.message:String(e)}var Fp=pf({key:"omp_commands_settings",mockDefaults:MD,idOf:(e)=>e.id,singular:"command",plural:"commands"}),BXe={builtin:!0,skill:!0,custom:!0,extension:!0,file:!0};function jXe(e){if(!w(e))return null;let t=typeof e.name==="string"?e.name:"";if(!t)return null;if(typeof e.source!=="string"||!BXe[e.source])return null;let n=Array.isArray(e.aliases)?e.aliases.filter((i)=>typeof i==="string"&&i.length>0):[],r=w(e.input)&&typeof e.input.hint==="string"?e.input.hint:void 0,o=Array.isArray(e.subcommands)?e.subcommands.flatMap((i)=>{if(!w(i)||typeof i.name!=="string"||!i.name)return[];return[{name:i.name,...typeof i.description==="string"?{description:i.description}:{},...typeof i.usage==="string"?{usage:i.usage}:{}}]}):[];return{id:`omp-live-${t}`,name:t,description:typeof e.description==="string"?e.description:"",scope:"system",source:e.source,template:`/${t}`,isBuiltIn:e.source!=="file",...n.length?{aliases:n}:{},...o.length?{subcommands:o}:{},...r?{inputHint:r}:{}}}async function HXe(e){try{let t=await Ur({type:"get_available_commands"},30000,e);if(!Array.isArray(t.commands))return[];return t.commands.flatMap((n)=>{let r=jXe(n);return r?[r]:[]})}catch{return[]}}async function WXe(e,t){let n=await sR(e.name,t.workspace);if(!n)return{...e,isBuiltIn:!0,managed:!1};let r=await cce(n.filePath);return{...e,scope:n.scope,isBuiltIn:!1,managed:n.managed,filePath:n.filePath,...r?{template:r.body,description:r.description||e.description}:{}}}async function LD(e,t){let n=await Promise.all((await HXe(t.cwd)).map((o)=>WXe(o,t))),r=new Set(n.map((o)=>o.name.toLowerCase()));return[...n,...e.filter((o)=>!r.has(o.name.toLowerCase()))]}async function $Xe({request:e}){try{let t=await k(),n=L(),r=await Fp.read(t);if(n)return f({commands:r,isMock:!0});let o=new URL(e.url),i=o.searchParams.get("sessionId");if(i){let c=Le(i);if(c&&c.isAlive()&&Gt(c)!=="omp-rpc"){let l=await c.send({type:"get_commands"}).catch(()=>null),u=Array.isArray(l?.commands)?l.commands:[],d=new Set(u.map((p)=>p.name.toLowerCase()));return f({commands:[...u,...r.filter((p)=>!d.has(p.name.toLowerCase()))],isMock:!1})}}let s=await As(o.searchParams.get("root"),o.searchParams.get("scope")),a=await LD(r,s);return f({commands:a,isMock:!1})}catch(t){let n=L();return f({error:dce(t),commands:n?MD:[],isMock:n},{status:500})}}async function KXe({request:e,params:t}){try{let n=await k(),r=new URL(e.url);if(e.method==="DELETE"){let o=r.searchParams.get("id");if(!o)return f({error:"id is required"},{status:400});if(L()){let c=await Fp.remove(n,o);return f({success:!0,commands:c})}let i=o.startsWith("omp-live-")?o.slice(9):null,s=await As(r.searchParams.get("root"),r.searchParams.get("scope"));if(i)return await uce(i,s.workspace),await Tr(),f({success:!0,commands:await LD(await Fp.read(n),s)});let a=await Fp.remove(n,o);return f({success:!0,commands:a})}if(e.method==="POST"||e.method==="PUT"){let o=await e.json(),i=await As(r.searchParams.get("root")??(typeof o.root==="string"?o.root:null),r.searchParams.get("scope")??(typeof o.scope==="string"?o.scope:null)),s=w(o.command)?o.command:null;if(!L()&&s&&(s.managed===!0||!s.source&&s.isBuiltIn!==!0)){let c=typeof o.previousName==="string"?o.previousName:null,l=s.scope==="project"?"project":"user";return await lce({scope:l,projectDir:i.workspace,previousName:c,name:s.name,description:s.description??"",argumentHint:s.inputHint??"",body:s.template??""}),await Tr(),f({success:!0,commands:await LD(await Fp.read(n),i)})}let a=await Fp.upsert(n,o);return await Fp.write(n,a),f({success:!0,commands:a})}return K({request:e,params:t})}catch(n){return f({error:dce(n)},{status:500})}}function gh(e){return Ts(e)}function Ts(e){let t=e.headers.get("origin");if(!t)return!0;let n=e.headers.get("host");if(!n)return!1;try{return new URL(t).host===n}catch{return!1}}import Mce from"fs/promises";var FD=[{key:"whisper-base",label:"Fast (Whisper base)",sizeHint:"~60 MB",multilingual:!0},{key:"whisper-small",label:"Balanced (Whisper small)",sizeHint:"~190 MB",multilingual:!0},{key:"whisper-large-v3-turbo",label:"Turbo (Whisper large-v3)",sizeHint:"~600 MB",multilingual:!0},{key:"parakeet-tdt-0.6b-v3",label:"Parakeet TDT v3 (SoTA)",sizeHint:"~680 MB",multilingual:!1},{key:"nemotron-streaming-en-0.6b",label:"Nemotron 0.6B (English, live in omp TUI)",sizeHint:"~630 MB",multilingual:!1}],aR="whisper-base";function pce(e){return typeof e==="string"&&FD.some((t)=>t.key===e)}function mce(e){let t=e.status??"";if(t==="progress_total"&&typeof e.progress==="number"){let n=Math.round(e.progress);return{percent:n<0||n>100?null:n,file:e.file,decoding:!1}}if(t==="initiate"||t==="download"||t==="progress")return{percent:null,file:e.file,decoding:!1};return{percent:null,decoding:!0}}var fce="Local speech-to-text is unavailable. Pick an external engine in Settings \u2192 Dictation.",GXe=FD.map((e)=>({id:e.key,label:e.label,hint:e.sizeHint})),UD=[{id:"omp",label:"This machine (omp)",where:"Audio never leaves this machine. omp downloads the model on first use.",needsKey:!1,editableBaseUrl:!1,baseUrl:"",defaultModel:aR,models:GXe,language:"hint",maxBytes:1/0,docs:"https://github.com/kabmo-labs/kabmo/wiki/Chat-Stream-and-Tools"},{id:"openai",label:"OpenAI-compatible API",where:"Audio is uploaded to the endpoint below.",needsKey:!0,editableBaseUrl:!0,baseUrl:"https://api.openai.com/v1",defaultModel:"gpt-4o-mini-transcribe",models:[{id:"gpt-4o-mini-transcribe",label:"gpt-4o-mini-transcribe",hint:"Fast and cheap; multilingual."},{id:"gpt-4o-transcribe",label:"gpt-4o-transcribe",hint:"More accurate, slower, dearer."},{id:"gpt-transcribe",label:"gpt-transcribe",hint:"OpenAI\u2019s newest; also reports detected languages."},{id:"whisper-1",label:"whisper-1",hint:"Widest compatibility; deprecated 2027-02-26."},{id:"whisper-large-v3-turbo",label:"whisper-large-v3-turbo",hint:"Groq / local servers."},{id:"whisper-large-v3",label:"whisper-large-v3",hint:"Groq / local servers; slower, best accuracy."}],language:"detect",maxBytes:26214400,docs:"https://platform.openai.com/docs/guides/speech-to-text"},{id:"deepgram",label:"Deepgram",where:"Audio is uploaded to api.deepgram.com.",needsKey:!0,editableBaseUrl:!1,baseUrl:"",defaultModel:"nova-3",models:[{id:"nova-3",label:"nova-3",hint:"Best accuracy; multilingual mode available."},{id:"nova-2",label:"nova-2",hint:"Previous generation."}],language:"detect",maxBytes:2147483648,docs:"https://developers.deepgram.com/docs/models-languages-overview"},{id:"elevenlabs",label:"ElevenLabs",where:"Audio is uploaded to api.elevenlabs.io.",needsKey:!0,editableBaseUrl:!1,baseUrl:"",defaultModel:"scribe_v2",models:[{id:"scribe_v2",label:"scribe_v2",hint:"Accurate, 90+ languages."},{id:"scribe_v3",label:"scribe_v3",hint:"Newest; multilingual mode available."}],language:"detect",maxBytes:5368709120,docs:"https://elevenlabs.io/docs/capabilities/speech-to-text"}];function cR(e){return typeof e==="string"&&UD.some((t)=>t.id===e)}function uu(e){return UD.find((t)=>t.id===e)??UD[0]}function gce(e,t){let n=uu(e);return(t??"").trim()||n.defaultModel}function lR(e){return e==="id"||e==="en"||e==="auto"}function hce(e){return(e??"").trim().toLowerCase().startsWith("id")?"id":"en"}function yce(e,t,n){let r=t??"auto",o=uu(e);if(r!=="auto")return r;if(o.language==="detect")return;let i=(n??"").trim();return/^[a-z]{2,3}$/.test(i)?i:"en"}var bce=16000;var wce=33554432;function Sce(e){let t=e?.engine,n=e?.language,r=e?.model;return{...cR(t)?{engine:t}:{},...lR(n)?{language:n}:{},...typeof r==="string"&&r.trim()?{model:r.trim().slice(0,120)}:{}}}function BD(e){return JSON.stringify(e)}var xce=300,kce=120000,qXe=0.003;function vce(e,t=bce){return Math.floor(e/2)/t*1000}var Ace="The microphone sent no audio \u2014 check the input device in Settings \u2192 Dictation.";function Tce(e){let t=e.byteLength>>1;if(e.byteOffset%2===0)return new Int16Array(e.buffer,e.byteOffset,t);return new Int16Array(e.slice(0,t*2).buffer,0,t)}function Ece(e){let t=Tce(e);for(let n=0;n<t.length;n++)if(t[n]!==0)return!1;return!0}function Rce(e,t=qXe){let n=e.byteLength>>1;if(n===0)return!0;let r=Tce(e),o=0;for(let i=0;i<n;i++){let s=r[i]/32768;o+=s*s}return Math.sqrt(o/n)<t}function hh(e){let t=e.trim();if(!t)return null;let n;try{n=new URL(t)}catch{return null}if(n.protocol!=="http:"&&n.protocol!=="https:")return null;if(n.username||n.password)return null;return t.replace(/\/+$/,"")}var uR={engine:"omp",model:"",language:hce(typeof navigator>"u"?void 0:navigator.language),baseUrl:"",prompt:"",deviceId:"",minMs:xce,maxMs:kce};function Ice(e,t,n,r){let o=typeof e==="number"?e:Number(e);if(!Number.isFinite(o))return t;return Math.min(r,Math.max(n,Math.round(o)))}function Pce(e){let t=typeof e==="object"&&e!==null&&!Array.isArray(e)?e:{},n=cR(t.engine)?t.engine:uR.engine,r=lR(t.language)?t.language:uR.language;return{engine:n,model:typeof t.model==="string"?t.model.trim().slice(0,120):"",language:r,baseUrl:hh(typeof t.baseUrl==="string"?t.baseUrl:"")??"",prompt:typeof t.prompt==="string"?t.prompt.slice(0,800):"",deviceId:typeof t.deviceId==="string"?t.deviceId.slice(0,200):"",minMs:Ice(t.minMs,uR.minMs,100,5000),maxMs:Ice(t.maxMs,uR.maxMs,1000,300000)}}function Cce(e){let t=(hh(e)??"").trim();if(!t)return"";return/\/audio\/transcriptions$/.test(t)?t:`${t}/audio/transcriptions`}async function jD(){let e=await k(),t=await fi(e),n=Vn(t);return Pce(n.dictation)}async function HD(){try{let e=await Mce.readFile(DM(),"utf8"),t=JSON.parse(e);if(typeof t!=="object"||t===null)return null;let n=t.apiKey;return typeof n==="string"&&n.trim()?n.trim():null}catch{return null}}async function WD(e){let t=DM();if(e===null){await Mce.rm(t,{force:!0});return}let n=JSON.stringify({version:1,apiKey:e,updatedAt:new Date().toISOString()},null,2);await kt(t,`${n}
2149
- `,{createMode:384})}async function Oce(){let[e,t]=await Promise.all([jD(),HD()]);return{...e,hasApiKey:t!==null}}var Lce=new TextEncoder,Nce=new TextDecoder;function Dce(e){for(let[r,o]of Object.entries(e)){if(!(o instanceof Float32Array))continue;let i={...e,["$pcm"]:r};delete i[r];let s=new Uint8Array(o.buffer,o.byteOffset,o.byteLength);return VXe(i,s)}let t=Lce.encode(JSON.stringify(e)),n=new Uint8Array(5+t.length);return new DataView(n.buffer).setUint32(0,1+t.length,!0),n[4]=0,n.set(t,5),n}function VXe(e,t){let n=Lce.encode(JSON.stringify(e)),r=new Uint8Array(9+n.length+t.length),o=new DataView(r.buffer);return o.setUint32(0,5+n.length+t.length,!0),r[4]=1,o.setUint32(5,n.length,!0),r.set(n,9),r.set(t,9+n.length),r}class $D{constructor(){this.buffer=new Uint8Array(0)}push(e){this.append(e);let t=[],n=0;for(;;){if(this.buffer.length-n<4)break;let r=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),o=r.getUint32(n,!0);if(o<1)throw Error("speech frame: empty frame");if(o>536870912)throw Error(`speech frame: ${o} bytes exceeds the frame limit`);if(this.buffer.length-n-4<o)break;t.push(this.decodeAt(r,n,o)),n+=4+o}if(n>0)this.buffer=this.buffer.slice(n);return t}decodeAt(e,t,n){let r=this.buffer[t+4],o=this.buffer.subarray(t+5,t+4+n);if(r===0)return JSON.parse(Nce.decode(o));if(r!==1)throw Error(`speech frame: unknown type ${r}`);if(o.length<4)throw Error("speech frame: truncated PCM header");let i=e.getUint32(t+5,!0);if(4+i>o.length)throw Error("speech frame: PCM header overruns frame");let s=JSON.parse(Nce.decode(o.subarray(4,4+i))),a=s.$pcm;if(delete s.$pcm,typeof a==="string"){let c=o.slice(4+i);s[a]=new Float32Array(c.buffer,c.byteOffset,Math.floor(c.byteLength/4))}return s}append(e){if(this.buffer.length===0){this.buffer=e.slice();return}let t=new Uint8Array(this.buffer.length+e.length);t.set(this.buffer),t.set(e,this.buffer.length),this.buffer=t}}var zXe=2000;function Fce(e,t){let n=Bun.spawn({cmd:[e,"__omp_worker_stt"],stdin:"pipe",stdout:"pipe",stderr:"pipe",env:process.env,onExit:()=>t.onExit("exit")}),r="",o=async()=>{let s=new $D,a=n.stdout.getReader();try{for(;;){let{done:c,value:l}=await a.read();if(c)return;for(let u of s.push(l))t.onFrame(u)}}catch(c){t.onExit("broken",c instanceof Error?c:Error(String(c)))}},i=async()=>{let s=n.stderr.getReader(),a=new TextDecoder;try{for(;;){let{done:c,value:l}=await s.read();if(c)return;r=(r+a.decode(l,{stream:!0})).slice(-zXe)}}catch{}};return o(),i(),{send:(s)=>{try{n.stdin.write(Dce(s)),n.stdin.flush()}catch{}},kill:()=>{try{n.kill()}catch{}},stderrTail:()=>r}}var _Xe=600000,Uce=1e4,JXe="The local speech-to-text worker did not answer.",YXe="The speech-to-text worker exited before answering \u2014 usually a Kabmo/omp version mismatch. Update Kabmo on the machine running the server.";class Bce{constructor(){this.worker=null;this.pending=new Map;this.nextId=1;this.ready=null;this.answered=!1}async ensureWorker(){if(this.worker)return this.worker;if(this.ready){if(await this.ready,this.worker)return this.worker}let e=ke();if(!e)throw Error("omp binary not found \u2014 install omp to use speech-to-text.");let t=Fce(e,{onFrame:(n)=>this.handleFrame(n),onExit:(n,r)=>this.handleExit(t,n,r)});return this.worker=t,this.answered=!1,this.ready=this.ping(t).catch((n)=>{throw this.teardown(),n}),await this.ready,t}ping(e){let t=this.newId();return new Promise((n,r)=>{let o=setTimeout(()=>{this.pending.delete(t),r(Error(`${JXe} (no ping within ${Uce/1000}s)`))},Uce);this.pending.set(t,{resolve:()=>{clearTimeout(o),n()},reject:(i)=>{clearTimeout(o),r(i)}}),e.send({type:"ping",id:t})})}newId(){return String(this.nextId++)}handleFrame(e){if(e.type==="log")return;let t=e.id?this.pending.get(e.id):void 0;if(e.type==="pong"){this.answered=!0,t?.resolve("");return}if(e.type==="progress"){t?.onProgress?.(e.event);return}if(e.type==="transcription"){if(!e.id)return;this.pending.delete(e.id),t?.resolve(typeof e.text==="string"?e.text:""),this.scheduleIdleShutdown();return}if(e.type==="error"){if(!e.id)return;this.pending.delete(e.id),t?.reject(Error(typeof e.error==="string"?e.error:"Speech transcription failed.")),this.scheduleIdleShutdown()}}handleExit(e,t,n){if(this.worker!==e)return;if(t==="broken"){this.release(n??Error("The speech-to-text worker stream broke."));return}if(!this.answered&&this.pending.size>0){let r=e.stderrTail().trim();if(r)console.error(`[dictation] the stt worker died before answering:
2149
+ `,{createMode:384})}async function Oce(){let[e,t]=await Promise.all([jD(),HD()]);return{...e,hasApiKey:t!==null}}var Lce=new TextEncoder,Nce=new TextDecoder;function Dce(e){for(let[r,o]of Object.entries(e)){if(!(o instanceof Float32Array))continue;let i={...e,["$pcm"]:r};delete i[r];let s=new Uint8Array(o.buffer,o.byteOffset,o.byteLength);return VXe(i,s)}let t=Lce.encode(JSON.stringify(e)),n=new Uint8Array(5+t.length);return new DataView(n.buffer).setUint32(0,1+t.length,!0),n[4]=0,n.set(t,5),n}function VXe(e,t){let n=Lce.encode(JSON.stringify(e)),r=new Uint8Array(9+n.length+t.length),o=new DataView(r.buffer);return o.setUint32(0,5+n.length+t.length,!0),r[4]=1,o.setUint32(5,n.length,!0),r.set(n,9),r.set(t,9+n.length),r}class $D{constructor(){this.buffer=new Uint8Array(0)}push(e){this.append(e);let t=[],n=0;for(;;){if(this.buffer.length-n<4)break;let r=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),o=r.getUint32(n,!0);if(o<1)throw Error("speech frame: empty frame");if(o>536870912)throw Error(`speech frame: ${o} bytes exceeds the frame limit`);if(this.buffer.length-n-4<o)break;t.push(this.decodeAt(r,n,o)),n+=4+o}if(n>0)this.buffer=this.buffer.slice(n);return t}decodeAt(e,t,n){let r=this.buffer[t+4],o=this.buffer.subarray(t+5,t+4+n);if(r===0)return JSON.parse(Nce.decode(o));if(r!==1)throw Error(`speech frame: unknown type ${r}`);if(o.length<4)throw Error("speech frame: truncated PCM header");let i=e.getUint32(t+5,!0);if(4+i>o.length)throw Error("speech frame: PCM header overruns frame");let s=JSON.parse(Nce.decode(o.subarray(4,4+i))),a=s.$pcm;if(delete s.$pcm,typeof a==="string"){let c=o.slice(4+i);s[a]=new Float32Array(c.buffer,c.byteOffset,Math.floor(c.byteLength/4))}return s}append(e){if(this.buffer.length===0){this.buffer=e.slice();return}let t=new Uint8Array(this.buffer.length+e.length);t.set(this.buffer),t.set(e,this.buffer.length),this.buffer=t}}var zXe=2000;function Fce(e,t){let n=Bun.spawn({cmd:[e,"__omp_worker_stt"],stdin:"pipe",stdout:"pipe",stderr:"pipe",env:process.env,onExit:()=>t.onExit("exit")}),r="",o=async()=>{let s=new $D,a=n.stdout.getReader();try{for(;;){let{done:c,value:l}=await a.read();if(c)return;for(let u of s.push(l))t.onFrame(u)}}catch(c){t.onExit("broken",c instanceof Error?c:Error(String(c)))}},i=async()=>{let s=n.stderr.getReader(),a=new TextDecoder;try{for(;;){let{done:c,value:l}=await s.read();if(c)return;r=(r+a.decode(l,{stream:!0})).slice(-zXe)}}catch{}};return o(),i(),{send:(s)=>{try{Promise.resolve(n.stdin.write(Dce(s))).catch(()=>{}),Promise.resolve(n.stdin.flush()).catch(()=>{})}catch{}},kill:()=>{try{n.kill()}catch{}},stderrTail:()=>r}}var _Xe=600000,Uce=1e4,JXe="The local speech-to-text worker did not answer.",YXe="The speech-to-text worker exited before answering \u2014 usually a Kabmo/omp version mismatch. Update Kabmo on the machine running the server.";class Bce{constructor(){this.worker=null;this.pending=new Map;this.nextId=1;this.ready=null;this.answered=!1}async ensureWorker(){if(this.worker)return this.worker;if(this.ready){if(await this.ready,this.worker)return this.worker}let e=ke();if(!e)throw Error("omp binary not found \u2014 install omp to use speech-to-text.");let t=Fce(e,{onFrame:(n)=>this.handleFrame(n),onExit:(n,r)=>this.handleExit(t,n,r)});return this.worker=t,this.answered=!1,this.ready=this.ping(t).catch((n)=>{throw this.teardown(),n}),await this.ready,t}ping(e){let t=this.newId();return new Promise((n,r)=>{let o=setTimeout(()=>{this.pending.delete(t),r(Error(`${JXe} (no ping within ${Uce/1000}s)`))},Uce);this.pending.set(t,{resolve:()=>{clearTimeout(o),n()},reject:(i)=>{clearTimeout(o),r(i)}}),e.send({type:"ping",id:t})})}newId(){return String(this.nextId++)}handleFrame(e){if(e.type==="log")return;let t=e.id?this.pending.get(e.id):void 0;if(e.type==="pong"){this.answered=!0,t?.resolve("");return}if(e.type==="progress"){t?.onProgress?.(e.event);return}if(e.type==="transcription"){if(!e.id)return;this.pending.delete(e.id),t?.resolve(typeof e.text==="string"?e.text:""),this.scheduleIdleShutdown();return}if(e.type==="error"){if(!e.id)return;this.pending.delete(e.id),t?.reject(Error(typeof e.error==="string"?e.error:"Speech transcription failed.")),this.scheduleIdleShutdown()}}handleExit(e,t,n){if(this.worker!==e)return;if(t==="broken"){this.release(n??Error("The speech-to-text worker stream broke."));return}if(!this.answered&&this.pending.size>0){let r=e.stderrTail().trim();if(r)console.error(`[dictation] the stt worker died before answering:
2150
2150
  ${r}`)}this.teardown()}release(e){let t=this.worker;this.worker=null,this.ready=null,this.answered=!1,this.clearIdle();for(let n of this.pending.values())n.reject(e);this.pending.clear(),t?.kill()}teardown(){let e=this.answered;this.release(Error(e?"STT worker exited.":YXe))}clearIdle(){if(this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=void 0}scheduleIdleShutdown(){this.clearIdle(),this.idleTimer=setTimeout(()=>this.teardown(),_Xe),this.idleTimer.unref?.()}async transcribe(e,t){let n=await this.ensureWorker(),r=this.newId(),o=pce(t.modelKey)?t.modelKey:aR;return this.clearIdle(),new Promise((i,s)=>{this.pending.set(r,{resolve:i,reject:s,onProgress:t.onProgress}),n.send({type:"transcribe",id:r,modelKey:o,audio:e,...t.language?{language:t.language}:{}})})}get alive(){return this.worker!==null}async probe(){try{return await this.ensureWorker(),this.scheduleIdleShutdown(),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}shutdown(){this.teardown()}}var XXe=globalThis;function dR(){return XXe.__kabmoSttWorker??=new Bce}var QXe=60000,KD="__kabmoDictationCapability";function jce(){globalThis[KD]=null}async function Uw(e=!1){if(L())return{available:!1,reason:"Mock mode has no local speech-to-text worker."};let t=globalThis,n=t[KD];if(!e&&n&&Date.now()-n.at<QXe)return n.value;let r=await dR().probe(),o=r.ok?{available:!0}:{available:!1,reason:r.error?`${r.error} Or pick an external engine in Settings \u2192 Dictation.`:fce};return t[KD]={at:Date.now(),value:o},o}async function ZXe({request:e}){try{let[t,n]=await Promise.all([Oce(),Uw()]);return f({settings:t,local:n,isMock:L()})}catch(t){return f({error:t instanceof Error?t.message:"Could not read the dictation settings."},{status:500})}}async function eQe({request:e,params:t}){if(e.method!=="POST")return K({request:e,params:t});if(!Ts(e))return f({error:"Cross-origin dictation settings write rejected"},{status:403});try{let n=await e.json(),r=typeof n==="object"&&n!==null?n:{};if(r.action==="clear-key")return await WD(null),f({success:!0,hasApiKey:!1});if(r.action==="probe")return jce(),f({success:!0,local:await Uw(!0)});if(typeof r.apiKey==="string"){let o=r.apiKey.trim();if(!o)return f({error:"The API key is empty."},{status:400});if(o.length>500)return f({error:"That is not an API key."},{status:400});return await WD(o),f({success:!0,hasApiKey:!0})}return f({error:"Unknown dictation action."},{status:400})}catch(n){return f({error:n instanceof Error?n.message:"Could not save the dictation settings."},{status:500})}}import Yce from"fs/promises";var Hce=[{id:"marin",label:"Marin (recommended)"},{id:"cedar",label:"Cedar (recommended)"},{id:"alloy",label:"Alloy"},{id:"ash",label:"Ash"},{id:"ballad",label:"Ballad"},{id:"coral",label:"Coral"},{id:"echo",label:"Echo"},{id:"fable",label:"Fable"},{id:"nova",label:"Nova"},{id:"onyx",label:"Onyx"},{id:"sage",label:"Sage"},{id:"shimmer",label:"Shimmer"},{id:"verse",label:"Verse"}],Wce=[{id:"21m00Tcm4TlvDq8ikWAM",label:"Rachel (public)"},{id:"pNInz6obpgDQGcFmaJgB",label:"Adam (public)"},{id:"EXAVITQu4vr4xnSDxMaL",label:"Bella (public)"},{id:"JBFqnCBsd6RMkjVDRZzb",label:"George (public)"}],tQe=[{id:"aura-2-thalia-en",label:"Thalia \u2014 English (American, female)",hint:"Default; clear and neutral."},{id:"aura-2-andromeda-en",label:"Andromeda \u2014 English (American, female)",hint:"Warm and conversational."},{id:"aura-2-helena-en",label:"Helena \u2014 English (American, female)",hint:"Bright and friendly."},{id:"aura-2-apollo-en",label:"Apollo \u2014 English (American, male)",hint:"Confident, news-like."},{id:"aura-2-arcas-en",label:"Arcas \u2014 English (American, male)",hint:"Calm and steady."},{id:"aura-2-orion-en",label:"Orion \u2014 English (American, male)",hint:"Deep and measured."},{id:"aura-2-zeus-en",label:"Zeus \u2014 English (American, male)",hint:"Authoritative."},{id:"aura-2-agustina-es",label:"Agustina \u2014 Spanish (female)",hint:"Spanish; codeswitches with English."},{id:"aura-2-alvaro-es",label:"Alvaro \u2014 Spanish (male)",hint:"Spanish."},{id:"aura-2-agathe-fr",label:"Agathe \u2014 French (female)",hint:"French."},{id:"aura-2-hector-fr",label:"Hector \u2014 French (male)",hint:"French."},{id:"aura-2-aurelia-de",label:"Aurelia \u2014 German (female)",hint:"German."},{id:"aura-2-julius-de",label:"Julius \u2014 German (male)",hint:"German."},{id:"aura-2-cesare-it",label:"Cesare \u2014 Italian (male)",hint:"Italian."},{id:"aura-2-livia-it",label:"Livia \u2014 Italian (female)",hint:"Italian."},{id:"aura-2-ama-ja",label:"Ama \u2014 Japanese (female)",hint:"Japanese."},{id:"aura-2-ebisu-ja",label:"Ebisu \u2014 Japanese (male)",hint:"Japanese."}],nQe=[{id:"flux-haley-en",label:"Haley \u2014 English (American, female)",hint:"Flux \xB7 English."},{id:"flux-hannah-en",label:"Hannah \u2014 English (American, female)",hint:"Flux \xB7 English."},{id:"flux-brooke-en",label:"Brooke \u2014 English (American, female)",hint:"Flux \xB7 English."},{id:"flux-sienna-en",label:"Sienna \u2014 English (American, female)",hint:"Flux \xB7 English."},{id:"flux-heather-en",label:"Heather \u2014 English (American, female)",hint:"Flux \xB7 English."},{id:"flux-kit-en",label:"Kit \u2014 English (British, male)",hint:"Flux \xB7 English."},{id:"flux-colin-en",label:"Colin \u2014 English (British, male)",hint:"Flux \xB7 English."},{id:"flux-sean-en",label:"Sean \u2014 English (British, male)",hint:"Flux \xB7 English."},{id:"flux-gemma-en",label:"Gemma \u2014 English (British, female)",hint:"Flux \xB7 English."},{id:"flux-cole-en",label:"Cole \u2014 English (American, male)",hint:"Flux \xB7 English."},{id:"flux-cliff-en",label:"Cliff \u2014 English (American, male)",hint:"Flux \xB7 English."},{id:"flux-miles-en",label:"Miles \u2014 English (American, male)",hint:"Flux \xB7 English."},{id:"flux-alexis-en",label:"Alexis \u2014 English (American, female)",hint:"Flux \xB7 English."},{id:"flux-afsana-bn",label:"Afsana \u2014 Bengali (female)",hint:"Flux \xB7 Bengali, early access."},{id:"flux-mamun-bn",label:"Mamun \u2014 Bengali (male)",hint:"Flux \xB7 Bengali, early access."},{id:"flux-desislava-bg",label:"Desislava \u2014 Bulgarian (female)",hint:"Flux \xB7 Bulgarian, early access."},{id:"flux-judit-ca",label:"Judit \u2014 Catalan (female)",hint:"Flux \xB7 Catalan, early access."},{id:"flux-jordi-ca",label:"Jordi \u2014 Catalan (male)",hint:"Flux \xB7 Catalan, early access."},{id:"flux-lijuan-zh",label:"Lijuan \u2014 Chinese (female)",hint:"Flux \xB7 Chinese, early access."},{id:"flux-bo-zh",label:"Bo \u2014 Chinese (male)",hint:"Flux \xB7 Chinese, early access."},{id:"flux-danijela-hr",label:"Danijela \u2014 Croatian (female)",hint:"Flux \xB7 Croatian, early access."},{id:"flux-dalibor-hr",label:"Dalibor \u2014 Croatian (male)",hint:"Flux \xB7 Croatian, early access."},{id:"flux-jakub-cs",label:"Jakub \u2014 Czech (male)",hint:"Flux \xB7 Czech, early access."},{id:"flux-pernille-da",label:"Pernille \u2014 Danish (female)",hint:"Flux \xB7 Danish, early access."},{id:"flux-rasmus-da",label:"Rasmus \u2014 Danish (male)",hint:"Flux \xB7 Danish, early access."},{id:"flux-anouk-nl",label:"Anouk \u2014 Dutch (female)",hint:"Flux \xB7 Dutch."},{id:"flux-bram-nl",label:"Bram \u2014 Dutch (male)",hint:"Flux \xB7 Dutch."},{id:"flux-triin-et",label:"Triin \u2014 Estonian (female)",hint:"Flux \xB7 Estonian, early access."},{id:"flux-kirsi-fi",label:"Kirsi \u2014 Finnish (female)",hint:"Flux \xB7 Finnish, early access."},{id:"flux-teemu-fi",label:"Teemu \u2014 Finnish (male)",hint:"Flux \xB7 Finnish, early access."},{id:"flux-brigitte-fr",label:"Brigitte \u2014 French (female)",hint:"Flux \xB7 French."},{id:"flux-arnaud-fr",label:"Arnaud \u2014 French (male)",hint:"Flux \xB7 French."},{id:"flux-janine-de",label:"Janine \u2014 German (female)",hint:"Flux \xB7 German."},{id:"flux-benjamin-de",label:"Benjamin \u2014 German (male)",hint:"Flux \xB7 German."},{id:"flux-kostas-el",label:"Kostas \u2014 Greek (male)",hint:"Flux \xB7 Greek, early access."},{id:"flux-bhavna-gu",label:"Bhavna \u2014 Gujarati (female)",hint:"Flux \xB7 Gujarati, early access."},{id:"flux-jignesh-gu",label:"Jignesh \u2014 Gujarati (male)",hint:"Flux \xB7 Gujarati, early access."},{id:"flux-anjali-hi",label:"Anjali \u2014 Hindi (female)",hint:"Flux \xB7 Hindi."},{id:"flux-ajay-hi",label:"Ajay \u2014 Hindi (male)",hint:"Flux \xB7 Hindi."},{id:"flux-eszter-hu",label:"Eszter \u2014 Hungarian (female)",hint:"Flux \xB7 Hungarian, early access."},{id:"flux-bence-hu",label:"Bence \u2014 Hungarian (male)",hint:"Flux \xB7 Hungarian, early access."},{id:"flux-dewi-id",label:"Dewi \u2014 Indonesian (female)",hint:"Flux \xB7 Indonesian; recommended for Bahasa."},{id:"flux-fajar-id",label:"Fajar \u2014 Indonesian (male)",hint:"Flux \xB7 Indonesian."},{id:"flux-fitri-id",label:"Fitri \u2014 Indonesian (female)",hint:"Flux \xB7 Indonesian."},{id:"flux-rizky-id",label:"Rizky \u2014 Indonesian (male)",hint:"Flux \xB7 Indonesian."},{id:"flux-teguh-id",label:"Teguh \u2014 Indonesian (male)",hint:"Flux \xB7 Indonesian."},{id:"flux-angela-it",label:"Angela \u2014 Italian (female)",hint:"Flux \xB7 Italian."},{id:"flux-federico-it",label:"Federico \u2014 Italian (male)",hint:"Flux \xB7 Italian."},{id:"flux-ayumi-ja",label:"Ayumi \u2014 Japanese (female)",hint:"Flux \xB7 Japanese."},{id:"flux-hayato-ja",label:"Hayato \u2014 Japanese (male)",hint:"Flux \xB7 Japanese."},{id:"flux-manjunath-kn",label:"Manjunath \u2014 Kannada (male)",hint:"Flux \xB7 Kannada, early access."},{id:"flux-eunji-ko",label:"Eunji \u2014 Korean (female)",hint:"Flux \xB7 Korean, early access."},{id:"flux-hyunwoo-ko",label:"Hyunwoo \u2014 Korean (male)",hint:"Flux \xB7 Korean, early access."},{id:"flux-agnese-lv",label:"Agnese \u2014 Latvian (female)",hint:"Flux \xB7 Latvian, early access."},{id:"flux-edgars-lv",label:"Edgars \u2014 Latvian (male)",hint:"Flux \xB7 Latvian, early access."},{id:"flux-goda-lt",label:"Goda \u2014 Lithuanian (female)",hint:"Flux \xB7 Lithuanian, early access."},{id:"flux-izzah-ms",label:"Izzah \u2014 Malay (female)",hint:"Flux \xB7 Malay, early access."},{id:"flux-haziq-ms",label:"Haziq \u2014 Malay (male)",hint:"Flux \xB7 Malay, early access."},{id:"flux-pooja-mr",label:"Pooja \u2014 Marathi (female)",hint:"Flux \xB7 Marathi, early access."},{id:"flux-pratik-mr",label:"Pratik \u2014 Marathi (male)",hint:"Flux \xB7 Marathi, early access."},{id:"flux-ida-no",label:"Ida \u2014 Norwegian (female)",hint:"Flux \xB7 Norwegian, early access."},{id:"flux-erlend-no",label:"Erlend \u2014 Norwegian (male)",hint:"Flux \xB7 Norwegian, early access."},{id:"flux-ewa-pl",label:"Ewa \u2014 Polish (female)",hint:"Flux \xB7 Polish, early access."},{id:"flux-bartosz-pl",label:"Bartosz \u2014 Polish (male)",hint:"Flux \xB7 Polish, early access."},{id:"flux-bianca-pt",label:"Bianca \u2014 Portuguese (female)",hint:"Flux \xB7 Portuguese."},{id:"flux-bruno-pt",label:"Bruno \u2014 Portuguese (male)",hint:"Flux \xB7 Portuguese."},{id:"flux-ioana-ro",label:"Ioana \u2014 Romanian (female)",hint:"Flux \xB7 Romanian, early access."},{id:"flux-cosmin-ro",label:"Cosmin \u2014 Romanian (male)",hint:"Flux \xB7 Romanian, early access."},{id:"flux-natalia-ru",label:"Natalia \u2014 Russian (female)",hint:"Flux \xB7 Russian."},{id:"flux-andrei-ru",label:"Andrei \u2014 Russian (male)",hint:"Flux \xB7 Russian."},{id:"flux-dominika-sk",label:"Dominika \u2014 Slovak (female)",hint:"Flux \xB7 Slovak, early access."},{id:"flux-juraj-sk",label:"Juraj \u2014 Slovak (male)",hint:"Flux \xB7 Slovak, early access."},{id:"flux-katja-sl",label:"Katja \u2014 Slovenian (female)",hint:"Flux \xB7 Slovenian, early access."},{id:"flux-gregor-sl",label:"Gregor \u2014 Slovenian (male)",hint:"Flux \xB7 Slovenian, early access."},{id:"flux-aina-es",label:"Aina \u2014 Spanish (female)",hint:"Flux \xB7 Spanish."},{id:"flux-alfredo-es",label:"Alfredo \u2014 Spanish (male)",hint:"Flux \xB7 Spanish."},{id:"flux-charlotta-sv",label:"Charlotta \u2014 Swedish (female)",hint:"Flux \xB7 Swedish, early access."},{id:"flux-axel-sv",label:"Axel \u2014 Swedish (male)",hint:"Flux \xB7 Swedish, early access."},{id:"flux-liezel-tl",label:"Liezel \u2014 Tagalog (female)",hint:"Flux \xB7 Tagalog, early access."},{id:"flux-jerome-tl",label:"Jerome \u2014 Tagalog (male)",hint:"Flux \xB7 Tagalog, early access."},{id:"flux-kavya-ta",label:"Kavya \u2014 Tamil (female)",hint:"Flux \xB7 Tamil, early access."},{id:"flux-gokul-ta",label:"Gokul \u2014 Tamil (male)",hint:"Flux \xB7 Tamil, early access."},{id:"flux-sravani-te",label:"Sravani \u2014 Telugu (female)",hint:"Flux \xB7 Telugu, early access."},{id:"flux-pavan-te",label:"Pavan \u2014 Telugu (male)",hint:"Flux \xB7 Telugu, early access."},{id:"flux-dilek-tr",label:"Dilek \u2014 Turkish (female)",hint:"Flux \xB7 Turkish, early access."},{id:"flux-emre-tr",label:"Emre \u2014 Turkish (male)",hint:"Flux \xB7 Turkish, early access."},{id:"flux-solomiya-uk",label:"Solomiya \u2014 Ukrainian (female)",hint:"Flux \xB7 Ukrainian, early access."},{id:"flux-denys-uk",label:"Denys \u2014 Ukrainian (male)",hint:"Flux \xB7 Ukrainian, early access."},{id:"flux-ambreen-ur",label:"Ambreen \u2014 Urdu (female)",hint:"Flux \xB7 Urdu, early access."},{id:"flux-usman-ur",label:"Usman \u2014 Urdu (male)",hint:"Flux \xB7 Urdu, early access."},{id:"flux-hoa-vi",label:"Hoa \u2014 Vietnamese (female)",hint:"Flux \xB7 Vietnamese, early access."},{id:"flux-minh-vi",label:"Minh \u2014 Vietnamese (male)",hint:"Flux \xB7 Vietnamese, early access."}],$ce=[...tQe,...nQe],Kce=[{id:"eve",label:"Eve (default)"},{id:"ara",label:"Ara"}],Gce=[{id:"Kore",label:"Kore (firm)"},{id:"Puck",label:"Puck (upbeat)"},{id:"Charon",label:"Charon (informative)"},{id:"Zephyr",label:"Zephyr (bright)"},{id:"Fenrir",label:"Fenrir (excitable)"},{id:"Leda",label:"Leda (youthful)"},{id:"Orus",label:"Orus (firm)"},{id:"Aoede",label:"Aoede (breezy)"},{id:"Callirrhoe",label:"Callirrhoe (easy-going)"},{id:"Autonoe",label:"Autonoe (bright)"},{id:"Enceladus",label:"Enceladus (breathy)"},{id:"Iapetus",label:"Iapetus (clear)"},{id:"Umbriel",label:"Umbriel (easy-going)"},{id:"Algieba",label:"Algieba (smooth)"},{id:"Despina",label:"Despina (smooth)"},{id:"Erinome",label:"Erinome (clear)"},{id:"Algenib",label:"Algenib (gravelly)"},{id:"Rasalgethi",label:"Rasalgethi (informative)"},{id:"Laomedeia",label:"Laomedeia (upbeat)"},{id:"Achernar",label:"Achernar (soft)"},{id:"Alnilam",label:"Alnilam (firm)"},{id:"Schedar",label:"Schedar (even)"},{id:"Gacrux",label:"Gacrux (mature)"},{id:"Pulcherrima",label:"Pulcherrima (forward)"},{id:"Achird",label:"Achird (friendly)"},{id:"Zubenelgenubi",label:"Zubenelgenubi (casual)"},{id:"Vindemiatrix",label:"Vindemiatrix (gentle)"},{id:"Sadachbia",label:"Sadachbia (lively)"},{id:"Sadaltager",label:"Sadaltager (knowledgeable)"},{id:"Sulafat",label:"Sulafat (warm)"}];var Bw=[{id:"omp",label:"This machine (omp)",where:"Text never leaves this machine. omp downloads its voice on first use.",needsKey:!1,keyOptional:!1,editableBaseUrl:!1,baseUrl:"",defaultModel:"",defaultVoice:"",models:[],voices:[],voiceEditable:!1,maxChars:4000,speed:{min:0.8,max:1.3},language:"none",docs:"https://github.com/kabmo-labs/kabmo/wiki/Chat-Stream-and-Tools"},{id:"local",label:"This machine (ONNX)",where:"Text never leaves this machine. Runs inside Kabmo\u2019s own server; the model is downloaded once.",needsKey:!1,keyOptional:!1,editableBaseUrl:!1,baseUrl:"",defaultModel:"",defaultVoice:"",models:[],voices:[],voiceEditable:!0,maxChars:4000,speed:{min:0.7,max:2},language:"parameter",docs:"https://github.com/kabmo-labs/kabmo/wiki/Chat-Stream-and-Tools"},{id:"openai",label:"OpenAI-compatible API",where:"Text is uploaded to the endpoint below.",needsKey:!0,keyOptional:!0,editableBaseUrl:!0,baseUrl:"https://api.openai.com/v1",defaultModel:"gpt-4o-mini-tts",defaultVoice:"marin",models:[{id:"gpt-4o-mini-tts",label:"gpt-4o-mini-tts",hint:"Steerable voice; OpenAI is retiring it 2027-01-06."},{id:"tts-1",label:"tts-1",hint:"Lowest latency; narrower voice set."},{id:"tts-1-hd",label:"tts-1-hd",hint:"Higher quality, slower."},{id:"canopylabs/orpheus-v1-english",label:"Orpheus v1 (Groq)",hint:"Groq; English."},{id:"canopylabs/orpheus-arabic-saudi",label:"Orpheus Arabic (Groq)",hint:"Groq; Saudi Arabic."},{id:"kokoro",label:"Kokoro (local server)",hint:"Kokoro-FastAPI; no key needed."}],voices:Hce,voiceEditable:!0,maxChars:4096,speed:{min:0.25,max:4},language:"instructions",docs:"https://platform.openai.com/docs/guides/text-to-speech"},{id:"elevenlabs",label:"ElevenLabs",where:"Text is uploaded to api.elevenlabs.io.",needsKey:!0,keyOptional:!1,editableBaseUrl:!1,baseUrl:"https://api.elevenlabs.io",defaultModel:"eleven_multilingual_v2",defaultVoice:"21m00Tcm4TlvDq8ikWAM",models:[{id:"eleven_multilingual_v2",label:"Multilingual v2",hint:"Natural long-form; 29 languages; 10k chars."},{id:"eleven_flash_v2_5",label:"Flash v2.5",hint:"Fastest and cheapest; 40k chars."},{id:"eleven_v3",label:"v3",hint:"Expressive; 70+ languages; 5k chars."},{id:"eleven_v4",label:"v4",hint:"Most expressive; 90+ languages; 100k chars."}],voices:Wce,voiceEditable:!0,maxChars:5000,speed:{min:0.7,max:1.2},language:"parameter",docs:"https://elevenlabs.io/docs/api-reference/text-to-speech/convert"},{id:"deepgram",label:"Deepgram",where:"Text is uploaded to api.deepgram.com. Aura and Flux voices are both offered.",needsKey:!0,keyOptional:!1,editableBaseUrl:!1,baseUrl:"https://api.deepgram.com",defaultModel:"aura-2-thalia-en",defaultVoice:"",models:$ce,voices:[],voiceEditable:!1,maxChars:2000,speed:{min:0.7,max:1.5},language:"none",docs:"https://developers.deepgram.com/docs/tts-models-languages-overview"},{id:"xai",label:"xAI Grok Voice",where:"Text is uploaded to api.x.ai.",needsKey:!0,keyOptional:!1,editableBaseUrl:!1,baseUrl:"https://api.x.ai",defaultModel:"grok-tts",defaultVoice:"eve",models:[{id:"grok-tts",label:"Grok TTS",hint:"One model; pick a voice."}],voices:Kce,voiceEditable:!0,maxChars:60000,speed:{min:0.7,max:1.5},language:"required",docs:"https://docs.x.ai/docs/guides/voice"},{id:"gemini",label:"Google Gemini TTS",where:"Text is uploaded to generativelanguage.googleapis.com.",needsKey:!0,keyOptional:!1,editableBaseUrl:!1,baseUrl:"https://generativelanguage.googleapis.com",defaultModel:"gemini-3.8-flash-tts",defaultVoice:"Kore",models:[{id:"gemini-3.8-flash-tts",label:"Gemini 3.8 Flash TTS",hint:"Studio-grade, expressive; 130+ languages."},{id:"gemini-3.8-flash-lite-tts",label:"Gemini 3.8 Flash-Lite TTS",hint:"Faster and cheaper; 100+ languages."},{id:"gemini-3.1-flash-tts-preview",label:"Gemini 3.1 Flash TTS (preview)",hint:"Previous generation; low latency."},{id:"gemini-2.5-flash-preview-tts",label:"Gemini 2.5 Flash TTS (preview)",hint:"Legacy preview model."}],voices:Gce,voiceEditable:!0,maxChars:4000,speed:{min:1,max:1},language:"auto",docs:"https://ai.google.dev/gemini-api/docs/speech-generation"}];var qce=[{id:"auto",label:"Detect automatically"},{id:"en",label:"English"},{id:"id",label:"Indonesian"},{id:"zh",label:"Chinese"},{id:"ja",label:"Japanese"},{id:"ko",label:"Korean"},{id:"fr",label:"French"},{id:"de",label:"German"},{id:"es-ES",label:"Spanish (Spain)"},{id:"es-MX",label:"Spanish (Mexico)"},{id:"pt-BR",label:"Portuguese (Brazil)"},{id:"it",label:"Italian"},{id:"ru",label:"Russian"},{id:"tr",label:"Turkish"},{id:"vi",label:"Vietnamese"},{id:"hi",label:"Hindi"},{id:"bn",label:"Bengali"},{id:"ar-EG",label:"Arabic (Egypt)"},{id:"ar-SA",label:"Arabic (Saudi)"},{id:"ar-AE",label:"Arabic (UAE)"}];function pR(e){return typeof e==="string"&&Bw.some((t)=>t.id===e)}function du(e){return Bw.find((t)=>t.id===e)??Bw[0]}function Vce(e,t){return(t??"").trim()||du(e).defaultModel}function zce(e,t){return(t??"").trim()||du(e).defaultVoice}function qD(e,t){let n=du(e),r=Number.isFinite(t)?Number(t):1;return Math.min(n.speed.max,Math.max(n.speed.min,r))}function _ce(e){let t=e.trim().replace(/\/+$/,"");if(!t)return"";return/\/audio\/speech$/.test(t)?t:`${t}/audio/speech`}var rQe={engine:"omp",model:"",voice:"",speed:1,baseUrl:"",language:"",autoplay:!1};function mR(e,t){return typeof e==="string"?e.trim().slice(0,t):""}function fR(e){let t=typeof e==="object"&&e!==null&&!Array.isArray(e)?e:{},n=pR(t.engine)?t.engine:rQe.engine;return{engine:n,model:mR(t.model,120),voice:mR(t.voice,120),speed:qD(n,typeof t.speed==="number"?t.speed:Number(t.speed)),baseUrl:hh(mR(t.baseUrl,500))??"",language:mR(t.language,35),autoplay:t.autoplay===!0}}function oQe(e,t){return hh(t)??du(e).baseUrl}function Jce(e){let t=du(e.engine);return{engine:e.engine,model:Vce(e.engine,e.model),voice:zce(e.engine,e.voice),speed:qD(e.engine,e.speed),baseUrl:t.editableBaseUrl?oQe(e.engine,e.baseUrl):t.baseUrl,language:e.language.trim()||(t.language==="required"?"auto":"")}}var VD=Bw.filter((e)=>e.needsKey).map((e)=>e.id);async function zD(){let e=await k(),t=await fi(e),n=Vn(t);return fR(n.tts)}async function _D(){try{let e=JSON.parse(await Yce.readFile(ov(),"utf8"));if(typeof e!=="object"||e===null)return{version:1,keys:{}};let t=e.keys;if(typeof t!=="object"||t===null)return{version:1,keys:{}};let n={};for(let[r,o]of Object.entries(t))if(pR(r)&&r!=="omp"&&r!=="local"&&typeof o==="string"&&o.trim())n[r]=o.trim();return{version:1,keys:n}}catch{return{version:1,keys:{}}}}async function Xce(e){if(e==="omp"||e==="local")return null;return(await _D()).keys[e]??null}async function JD(e,t){let r={...(await _D()).keys};if(t===null)delete r[e];else r[e]=t;if(Object.keys(r).length===0){await Yce.rm(ov(),{force:!0});return}let o=JSON.stringify({version:1,keys:r,updatedAt:new Date().toISOString()},null,2);await kt(ov(),`${o}
2151
2151
  `,{createMode:384})}async function iQe(){let e=await _D(),t={};for(let n of VD)t[n]=Boolean(e.keys[n]);return t}async function Qce(){let[e,t]=await Promise.all([zD(),iQe()]);return{...e,hasKeys:t}}import YD from"fs/promises";import dQe from"os";import XD from"path";class Ue extends Error{constructor(e,t){super(e);this.retryable=t;this.name="TtsEngineError"}}var sQe=90000,aQe=200;async function ga(e,t,n){let r;try{r=await fetch(t,{...n,signal:AbortSignal.timeout(sQe)})}catch(o){let i=o instanceof Error?o.name:"";if(i==="TimeoutError"||i==="AbortError")throw new Ue(`${e} did not answer within 90 seconds.`,!0);throw new Ue(`Could not reach ${e}.`,!0)}if(r.ok)return r;throw new Ue(await cQe(e,r),r.status===408||r.status===429||r.status>=500)}async function cQe(e,t){let n=await lQe(t),r=n?` \u2014 ${n}`:"";switch(t.status){case 401:case 403:return`${e} rejected the API key (HTTP ${t.status})${r}`;case 402:return`${e} reports the account has no credit (HTTP 402)${r}`;case 413:return`The answer is too long for ${e} (HTTP 413)${r}`;case 429:return`${e} rate-limited the request (HTTP 429)${r}`;default:return`${e} failed (HTTP ${t.status})${r}`}}async function lQe(e){let t="";try{t=(await e.text()).trim()}catch{return""}if(!t)return"";try{let n=uQe(JSON.parse(t));if(n)return n}catch{}return t.slice(0,aQe)}function uQe(e){if(typeof e!=="object"||e===null)return null;let t=e;for(let n of["message","detail","error","err_msg"]){let r=t[n];if(typeof r==="string"&&r.trim())return r.trim();if(typeof r==="object"&&r!==null){let o=r.message;if(typeof o==="string"&&o.trim())return o.trim()}}return null}async function pu(e,t){let n=new Uint8Array(await e.arrayBuffer());if(n.byteLength===0)throw new Ue("The speech engine returned no audio.",!0);let r=e.headers.get("content-type")?.split(";")[0]?.trim();return{bytes:n,mimeType:r&&r.startsWith("audio/")?r:t}}function mu(e,t){let n=(t??"").trim();if(!n)throw new Ue(`${e} needs an API key. Add one in Settings \u2192 Voice \u2192 Speech.`,!1);return n}var pQe=60000,mQe=8000,fQe=120000,Up=null;function Zce(){Up=null}async function QD(e=!1){if(!e&&Up&&Date.now()-Up.at<pQe)return Up.value;let t=ke();if(!t){let r={available:!1,reason:"omp is not installed. Install omp, or pick a hosted engine in Settings \u2192 Voice \u2192 Speech."};return Up={at:Date.now(),value:r},r}let n;try{let r=Bun.spawn({cmd:[t,"say","--help"],stdin:"ignore",stdout:"ignore",stderr:"ignore",env:process.env}),o=Promise.withResolvers();n=setTimeout(()=>{r.kill(),o.reject(Error("timed out"))},mQe);let i=await Promise.race([r.exited,o.promise]),s=i===0?{available:!0}:{available:!1,reason:`This omp build has no \`say\` command (exit ${i}). Update omp, or pick a hosted engine.`};return Up={at:Date.now(),value:s},s}catch{let r={available:!1,reason:"This omp build did not answer `omp say --help`. Update omp, or pick a hosted engine."};return Up={at:Date.now(),value:r},r}finally{clearTimeout(n)}}function gQe(e,t,n,r,o){let i=[e,"say","--file",t,"--out",n];if(r)i.push("--voice",r);if(o!==1)i.push("--speed",String(o));return i}async function ele(e){let t=ke();if(!t)throw new Ue("omp is not installed. Install omp, or pick a hosted engine in Settings \u2192 Voice \u2192 Speech.",!1);if(e.voice&&!/^[a-z0-9_-]{1,40}$/i.test(e.voice))throw new Ue("That is not an omp voice id.",!1);let n=await YD.mkdtemp(XD.join(dQe.tmpdir(),"kabmo-tts-")),r=XD.join(n,"text.txt"),o=XD.join(n,"speech.wav"),i;try{await Bun.write(r,e.text),await YD.chmod(r,384);let s=Bun.spawn({cmd:gQe(t,r,o,e.voice,e.speed),stdin:"ignore",stdout:"ignore",stderr:"pipe",env:process.env,cwd:n}),a=new Response(s.stderr).text().catch(()=>""),c=Promise.withResolvers();i=setTimeout(()=>{s.kill(),c.reject(Error("timed out"))},fQe);let l;try{l=await Promise.race([s.exited,c.promise])}catch{throw new Ue("Local speech did not finish within two minutes.",!0)}if(l!==0){let p=(await a).trim().split(`
2152
2152
  `).filter(Boolean).at(-1)?.slice(0,200);throw new Ue(`Local speech failed (exit ${l})${p?` \u2014 ${p}`:""}.`,!0)}let u=new Uint8Array(await Bun.file(o).arrayBuffer());if(u.byteLength===0)throw new Ue("Local speech returned no audio.",!0);return{bytes:u,mimeType:"audio/wav"}}finally{clearTimeout(i),await YD.rm(n,{recursive:!0,force:!0}).catch(()=>{return})}}function hQe(e){return typeof e==="string"&&VD.includes(e)}async function yQe({request:e}){try{let[t,n]=await Promise.all([Qce(),QD()]);return f({settings:t,local:n,isMock:L()})}catch(t){return f({error:t instanceof Error?t.message:"Could not read the speech settings."},{status:500})}}async function bQe({request:e,params:t}){if(e.method!=="POST")return K({request:e,params:t});if(!Ts(e))return f({error:"Cross-origin speech settings write rejected"},{status:403});try{let n=await e.json(),r=typeof n==="object"&&n!==null?n:{};if(r.action==="probe")return Zce(),f({success:!0,local:await QD(!0)});if(!hQe(r.engine))return f({error:"Pick a hosted speech engine first."},{status:400});if(r.action==="clear-key")return await JD(r.engine,null),f({success:!0,engine:r.engine,hasKey:!1});if(typeof r.apiKey==="string"){let o=r.apiKey.trim();if(!o)return f({error:"The API key is empty."},{status:400});if(o.length>500)return f({error:"That is not an API key."},{status:400});return await JD(r.engine,o),f({success:!0,engine:r.engine,hasKey:!0})}return f({error:"Unknown speech action."},{status:400})}catch(n){return f({error:n instanceof Error?n.message:"Could not save the speech settings."},{status:500})}}var wQe=/^[A-Za-z0-9_-]{1,64}$/,tle=/[<>\n\r]/;function SQe(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let t=e;return typeof t.id==="string"&&wQe.test(t.id)&&typeof t.name==="string"&&t.name.trim().length>0&&t.name.length<=128&&!tle.test(t.name)&&typeof t.email==="string"&&t.email.trim().length>0&&t.email.length<=254&&t.email.includes("@")&&!tle.test(t.email)}function nle(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e){if(!SQe(r)||t.has(r.id))continue;t.add(r.id),n.push({id:r.id,name:r.name.trim(),email:r.email.trim()})}return n}var jw="kabmo.identity.applied",eF="kabmo.identity.previousName",tF="kabmo.identity.previousEmail";async function rle(){try{let e=await k(),t=await ue(e,ra,null);return{identities:nle(t?.gitIdentities)}}catch{return{identities:[]}}}async function xc(e,t){let n=await ie(["config",...e,"--get",t],{cwd:process.cwd(),timeout:5000});if(n.error||n.exitCode!==0)return null;let r=n.stdout.trim();return r.length>0?r:null}async function ha(e,t,n){let r=await ie(n===null?["config",...e,"--unset",t]:["config",...e,t,n],{cwd:process.cwd(),timeout:5000});if(r.error)throw r.error;if(r.exitCode!==0&&!(n===null&&r.exitCode===5))throw Error(r.stderr.trim()||`git config ${t} failed`)}function xQe(e,t){return e&&t?{name:e,email:t}:null}async function gR(e={}){let t=e.configArgs??["--global"],[n,r,o]=await Promise.all([xc(t,"user.name"),xc(t,"user.email"),xc(t,jw)]);return{global:xQe(n,r),appliedId:o}}async function nF(e,t={}){let n=t.configArgs??["--global"];if(e){if(!await xc(n,jw)){let i=await xc(n,"user.name"),s=await xc(n,"user.email");await ha(n,eF,i),await ha(n,tF,s)}return await ha(n,"user.name",e.name),await ha(n,"user.email",e.email),await ha(n,jw,e.id),gR(t)}if(await xc(n,jw)){let o=await xc(n,eF),i=await xc(n,tF);await ha(n,"user.name",o),await ha(n,"user.email",i),await ha(n,eF,null),await ha(n,tF,null),await ha(n,jw,null)}return gR(t)}async function kQe({request:e}){return f({success:!0,...await gR()})}async function vQe({request:e,params:t}){if(e.method!=="POST")return K({request:e,params:t});let n=await e.json().catch(()=>null);if(!n||typeof n!=="object"||Array.isArray(n))return f({error:"Invalid JSON body"},{status:400});let r=typeof n.identityId==="string"?n.identityId.trim():"";if(!r)return f({success:!0,...await nF(null)});let{identities:o}=await rle(),i=o.find((s)=>s.id===r);if(!i)return f({error:"That identity no longer exists."},{status:400});return f({success:!0,...await nF(i)})}async function oF(e){if(!await Bun.file(e).exists())return{mcpServers:{}};let t=JSON.parse(await Bun.file(e).text());if(!w(t))throw Error(`${e} must contain a JSON object`);if(t.mcpServers!==void 0&&!w(t.mcpServers))throw Error("mcpServers must be an object");return t}async function iF(e,t){await kt(e,`${JSON.stringify(t,null,2)}