blade-code 0.10.206 → 0.11.2

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 (175) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-65wc1h38.js → chunk-04qhtx2w.js} +1 -1
  3. package/dist/{chunk-9kj19a8t.js → chunk-0eajnhrj.js} +1 -1
  4. package/dist/{chunk-pga8gxtf.js → chunk-0kxya4ye.js} +1 -1
  5. package/dist/{chunk-nj6kpdte.js → chunk-0wxnrjes.js} +2 -2
  6. package/dist/{chunk-hv8nt7wj.js → chunk-1cy4ab77.js} +1 -1
  7. package/dist/chunk-21qsfewd.js +1 -0
  8. package/dist/{chunk-e45r1a8r.js → chunk-290p3r7a.js} +2 -2
  9. package/dist/{chunk-av799ng5.js → chunk-2fdghgmf.js} +2 -2
  10. package/dist/chunk-3d4wgfkr.js +1 -0
  11. package/dist/{chunk-az3rehz9.js → chunk-3ee357pw.js} +399 -392
  12. package/dist/{chunk-09kqfdpa.js → chunk-4e4qtpca.js} +2 -2
  13. package/dist/{chunk-3crwyd2r.js → chunk-5s2x98rx.js} +2 -2
  14. package/dist/chunk-634ymwg5.js +1 -0
  15. package/dist/chunk-65v1vjvg.js +1 -0
  16. package/dist/{chunk-870szc6v.js → chunk-6v23hdt8.js} +1 -1
  17. package/dist/{chunk-fc1gz532.js → chunk-6x5f6she.js} +2 -2
  18. package/dist/{chunk-erhaedch.js → chunk-7ajvrtb3.js} +1 -1
  19. package/dist/chunk-7p8r4q6f.js +1 -0
  20. package/dist/chunk-7rz5dt79.js +94 -0
  21. package/dist/{chunk-5k8k56f2.js → chunk-8q6zsznc.js} +11 -9
  22. package/dist/{chunk-1n4v80hy.js → chunk-9qxch6sy.js} +1 -1
  23. package/dist/{chunk-9sf1t8gw.js → chunk-a3dz41pd.js} +1 -1
  24. package/dist/{chunk-ed2hdrwe.js → chunk-a95jmx2j.js} +1 -1
  25. package/dist/{chunk-n34qsnks.js → chunk-amabfzc8.js} +1 -1
  26. package/dist/{chunk-6xzk4hsg.js → chunk-b22ab7yw.js} +1 -1
  27. package/dist/{chunk-dnpkf5mv.js → chunk-crv3sghv.js} +2 -2
  28. package/dist/chunk-d4xsrx3z.js +357 -0
  29. package/dist/{chunk-n5jzmwhy.js → chunk-ebvzp8tn.js} +6 -6
  30. package/dist/chunk-eg0s155w.js +1 -0
  31. package/dist/chunk-enmn892r.js +10 -0
  32. package/dist/{chunk-p8vpvx07.js → chunk-er6zghgg.js} +1 -1
  33. package/dist/{chunk-h6ahwwpa.js → chunk-f9qrjd2f.js} +1 -1
  34. package/dist/chunk-fb2x1026.js +171 -0
  35. package/dist/chunk-g0xtk1yy.js +8 -0
  36. package/dist/{chunk-pdna2qvv.js → chunk-g2295k8s.js} +2 -2
  37. package/dist/{chunk-826xegd8.js → chunk-g7pjgspy.js} +2 -2
  38. package/dist/chunk-gff7a5q0.js +1 -0
  39. package/dist/chunk-gymecxcc.js +1 -0
  40. package/dist/{chunk-sqk8cnej.js → chunk-h4b4fn3t.js} +2 -2
  41. package/dist/{chunk-e0ft3vwg.js → chunk-jbpasjg9.js} +1 -1
  42. package/dist/{chunk-xcq0cehr.js → chunk-k2rgg45h.js} +3 -3
  43. package/dist/chunk-kaj8jaj5.js +6 -0
  44. package/dist/{chunk-ewwrss2w.js → chunk-kehgewqh.js} +1 -1
  45. package/dist/{chunk-53vh6vpt.js → chunk-kkzznz4w.js} +1 -1
  46. package/dist/chunk-m2x6pb4f.js +2 -0
  47. package/dist/{chunk-0ef47wgr.js → chunk-n30najxq.js} +2 -2
  48. package/dist/{chunk-h4k69z1b.js → chunk-p36k2e96.js} +1 -1
  49. package/dist/chunk-p665f6pn.js +1 -0
  50. package/dist/chunk-pjeks4cz.js +1 -0
  51. package/dist/{chunk-50vwafn5.js → chunk-pm163dfm.js} +1 -1
  52. package/dist/{chunk-asgmmaec.js → chunk-px45q235.js} +2 -2
  53. package/dist/{chunk-28n945me.js → chunk-q6sr4979.js} +2 -2
  54. package/dist/{chunk-67wy9mm7.js → chunk-qa86anwd.js} +2 -2
  55. package/dist/{chunk-tzvb0nd2.js → chunk-qhcd0ww0.js} +1 -1
  56. package/dist/chunk-qyfbeg5h.js +1 -0
  57. package/dist/{chunk-fnmqxhv1.js → chunk-re8p2y22.js} +1 -1
  58. package/dist/{chunk-9tpzmy8v.js → chunk-s7x4x6xw.js} +1 -1
  59. package/dist/{chunk-gmpsfkgg.js → chunk-sdapqhj0.js} +1 -1
  60. package/dist/{chunk-tsm8rhmd.js → chunk-skktstg8.js} +1 -1
  61. package/dist/chunk-sqsfztrv.js +1 -0
  62. package/dist/chunk-t3pkk95s.js +1 -0
  63. package/dist/{chunk-fd0a8h55.js → chunk-tx9tb485.js} +2 -2
  64. package/dist/{chunk-v4cxk10d.js → chunk-v0eanse2.js} +1 -1
  65. package/dist/chunk-vemyfx92.js +14 -0
  66. package/dist/{chunk-yjjxv7fn.js → chunk-wan9q99y.js} +2 -2
  67. package/dist/{chunk-ebpg1srd.js → chunk-wnzr9h84.js} +2 -2
  68. package/dist/{chunk-t0gm0pn1.js → chunk-x6k5ye1z.js} +1 -1
  69. package/dist/{chunk-gz84aewr.js → chunk-xnys4bgs.js} +1 -1
  70. package/dist/{chunk-v5vx6nz9.js → chunk-xrgeakpy.js} +1 -1
  71. package/dist/{chunk-vx2g1faw.js → chunk-yeandcre.js} +1 -1
  72. package/dist/chunk-yjcp8jk1.js +2 -0
  73. package/dist/{chunk-28tzj187.js → chunk-ys8gysg8.js} +1 -1
  74. package/dist/{chunk-1j39te3t.js → chunk-zf72e5w8.js} +14 -6
  75. package/dist/{chunk-p2y1zqsb.js → chunk-zwe1a7xe.js} +2 -2
  76. package/dist/web/assets/ChatView-DysPZPwF.js +17 -0
  77. package/dist/web/assets/CodeBlockHighlighter-OvLyFs9U.js +8 -0
  78. package/dist/web/assets/FilePreview-CkSPwPdW.js +8 -0
  79. package/dist/web/assets/KanbanBoard-DH1wApt6.js +1 -0
  80. package/dist/web/assets/MarkdownRenderer-BTxnqChi.js +30 -0
  81. package/dist/web/assets/ScrollArea-BdOqyQ3g.js +1 -0
  82. package/dist/web/assets/SessionHistorySurface-DaKE2oKU.js +1 -0
  83. package/dist/web/assets/SettingsModal-CWlSSO_E.js +5 -0
  84. package/dist/web/assets/Sidebar-Dirk-XAQ.js +1 -0
  85. package/dist/web/assets/TaskSwitcher-DKelLFZm.js +1 -0
  86. package/dist/web/assets/TerminalPanel-D5Rieq62.js +1 -0
  87. package/dist/web/assets/archive-CsFSEMp9.js +1 -0
  88. package/dist/web/assets/arrow-left-gaino9Tb.js +1 -0
  89. package/dist/web/assets/calendar-clock-DfHUrEw9.js +1 -0
  90. package/dist/web/assets/chevron-right-Bvu2j6hB.js +1 -0
  91. package/dist/web/assets/clock-3-dWIDc9IF.js +1 -0
  92. package/dist/web/assets/copy-BPfhyh47.js +1 -0
  93. package/dist/web/assets/dist-RGayDvc-.js +11 -0
  94. package/dist/web/assets/download-BR2L5Wme.js +1 -0
  95. package/dist/web/assets/folder-8dmZJ2a6.js +1 -0
  96. package/dist/web/assets/index-B7RyuO2x.css +1 -0
  97. package/dist/web/assets/index-DSa8Dzp7.js +11 -0
  98. package/dist/web/assets/message-square-plus-BgC981WF.js +1 -0
  99. package/dist/web/assets/pause-DLZIDFMB.js +1 -0
  100. package/dist/web/assets/pencil-DkC0bPYD.js +1 -0
  101. package/dist/web/assets/play-BVeNn6fv.js +1 -0
  102. package/dist/web/assets/plus-kzdwas-3.js +1 -0
  103. package/dist/web/assets/preload-helper-DvgLbiBV.js +1 -0
  104. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  105. package/dist/web/assets/session-events-BuMTbIwu.js +23 -0
  106. package/dist/web/assets/settings-msYyNDKx.js +1 -0
  107. package/dist/web/assets/team-D3XOVbxL.js +1 -0
  108. package/dist/web/assets/teamService-Bus5RDi1.js +1 -0
  109. package/dist/web/assets/terminal-Cp5WYo8w.js +1 -0
  110. package/dist/web/assets/triangle-alert-cGqHxFsZ.js +1 -0
  111. package/dist/web/assets/vendor-radix-L0yJCKJX.js +41 -0
  112. package/dist/web/assets/vendor-react-CHEIQMI-.js +9 -0
  113. package/dist/web/assets/vendor-xterm-CANZO_wP.js +16 -0
  114. package/dist/web/assets/vendor-xterm-CHOd7Rch.css +1 -0
  115. package/dist/web/index.html +6 -4
  116. package/package.json +11 -10
  117. package/dist/chunk-514va7ce.js +0 -2
  118. package/dist/chunk-6p0hkf4f.js +0 -1
  119. package/dist/chunk-793wjhvz.js +0 -332
  120. package/dist/chunk-867bpjzg.js +0 -1
  121. package/dist/chunk-983hqzat.js +0 -1
  122. package/dist/chunk-af0m5227.js +0 -1
  123. package/dist/chunk-dpg006xj.js +0 -1
  124. package/dist/chunk-g7tphxme.js +0 -6
  125. package/dist/chunk-gpnkxh4c.js +0 -1
  126. package/dist/chunk-hpge30p8.js +0 -8
  127. package/dist/chunk-mtvbm7xe.js +0 -1
  128. package/dist/chunk-mys9mmcp.js +0 -1
  129. package/dist/chunk-new78c3h.js +0 -1
  130. package/dist/chunk-nng1xbsm.js +0 -10
  131. package/dist/chunk-pt0y4zrg.js +0 -14
  132. package/dist/chunk-q6abav45.js +0 -171
  133. package/dist/chunk-r4em0ha7.js +0 -1
  134. package/dist/chunk-rdzbd5vk.js +0 -1
  135. package/dist/chunk-sbfe9vh3.js +0 -94
  136. package/dist/chunk-w6zat4v4.js +0 -1
  137. package/dist/chunk-wsd3rn0q.js +0 -1
  138. package/dist/chunk-yzf2jpam.js +0 -2
  139. package/dist/web/assets/ChatView-lUD-61n0.js +0 -70
  140. package/dist/web/assets/CodeBlockHighlighter--TbfcBxW.js +0 -8
  141. package/dist/web/assets/FilePreview-R6OKQPf2.js +0 -55
  142. package/dist/web/assets/KanbanBoard-BHOKtiv5.js +0 -16
  143. package/dist/web/assets/MarkdownRenderer-DqxNq8pa.js +0 -30
  144. package/dist/web/assets/ScrollArea-Dhu0B-zB.js +0 -1
  145. package/dist/web/assets/SessionHistorySurface-aZvoj3ma.js +0 -6
  146. package/dist/web/assets/SettingsModal-C7QBnIqa.js +0 -20
  147. package/dist/web/assets/Sidebar-Bznnq91x.js +0 -31
  148. package/dist/web/assets/TaskSwitcher-DJczhDRp.js +0 -26
  149. package/dist/web/assets/TerminalPanel-Vk4p0V3p.js +0 -6
  150. package/dist/web/assets/archive-0hLYBKQf.js +0 -6
  151. package/dist/web/assets/arrow-left-CXb6Gqf3.js +0 -6
  152. package/dist/web/assets/calendar-clock-DiaFI9Jk.js +0 -6
  153. package/dist/web/assets/chevron-right-CcPXH37D.js +0 -6
  154. package/dist/web/assets/clock-3-D6VR6gJc.js +0 -6
  155. package/dist/web/assets/copy-C3eUAQgp.js +0 -6
  156. package/dist/web/assets/download-DHvS9tI3.js +0 -6
  157. package/dist/web/assets/external-link-BDVaEuqY.js +0 -11
  158. package/dist/web/assets/folder-B80Ac6rr.js +0 -11
  159. package/dist/web/assets/index-B5mUEr6D.js +0 -11
  160. package/dist/web/assets/index-VwIiNjc8.css +0 -1
  161. package/dist/web/assets/index-YqughEZk.js +0 -211
  162. package/dist/web/assets/message-square-plus-D15quyPH.js +0 -21
  163. package/dist/web/assets/pause-BjMlj6Bx.js +0 -6
  164. package/dist/web/assets/pencil-BMoJvcB7.js +0 -6
  165. package/dist/web/assets/play-BHh4py3p.js +0 -6
  166. package/dist/web/assets/plus-DeFz_gQq.js +0 -6
  167. package/dist/web/assets/session-events-DCHBz9We.js +0 -25
  168. package/dist/web/assets/settings-CI8xbId2.js +0 -6
  169. package/dist/web/assets/team-zZ803hH9.js +0 -6
  170. package/dist/web/assets/teamService-CgLBXgmv.js +0 -1
  171. package/dist/web/assets/terminal-1WxSJ47E.js +0 -6
  172. package/dist/web/assets/vendor-radix-D6QrtXqd.js +0 -45
  173. package/dist/web/assets/vendor-react-DofNRwfy.js +0 -49
  174. package/dist/web/assets/vendor-xterm-9CEnUXvW.css +0 -32
  175. package/dist/web/assets/vendor-xterm-DuYZoU4T.js +0 -49
@@ -1,14 +0,0 @@
1
- import{e as B3,f as x3,g as f3,h as r0,i as S3}from"./chunk-gz84aewr.js";import{j as a1}from"./chunk-870szc6v.js";import{w as t0,x as d2,y as b1,z as d1}from"./chunk-tzvb0nd2.js";import{A as c2,B as l2,C as i2,D as m0}from"./chunk-fnmqxhv1.js";import{E as h2,F as _$,G as N$,H as B$,I as G0,J as x$}from"./chunk-h6ahwwpa.js";import{$ as M$,Ca as U5,Ha as i3,N as y1,O as l3,R as T2,S as O1,T as l4,U as l1,V as p$,W as L4,X as A4,Y as W0,Z as I2,_ as C2,aa as U1,ca as S2,da as P2,ea as j4,fa as _0,ga as N0,ja as I4,ka as C4,la as Q5,ma as k2,na as J2,oa as Z3,pa as J3,qa as Q3,ra as Y3,sa as X3,ta as V3,ua as z3,va as G3,wa as K3,za as N3}from"./chunk-az3rehz9.js";import{Oa as E$,Ua as dO}from"./chunk-e45r1a8r.js";import{$a as f2,Xa as Z2,Za as R2,_a as E2,fb as X4,ib as a3,jb as i4,kb as y2,lb as m2,mb as o3,nb as t3,ob as n4,pb as s3,qb as v0,rb as M3,sb as L3,tb as A3,ub as g2,vb as v2,wb as p2,xb as u2,yb as H$,zb as O$}from"./chunk-fc1gz532.js";import{Nb as cO,Ob as i,Qb as m,Rb as q2,ac as F4,lc as g0}from"./chunk-793wjhvz.js";import{wc as m1}from"./chunk-1n4v80hy.js";import{Gd as M2,Mc as D2,Qd as o0,Rd as T0,Yd as b4,Zd as T4,_d as q4,ae as M1,de as x4,ed as d$,id as W4,ie as b2,je as D4,ke as M4,le as g}from"./chunk-sbfe9vh3.js";import{Je as L2,Qe as A2,Re as j2}from"./chunk-yjjxv7fn.js";import{kf as b3,of as T3,pf as q3,qf as I3,rf as C3,sf as v4,tf as R3,uf as E3}from"./chunk-0ef47wgr.js";import{$f as k$,Tf as Z5,Xf as LO,cg as aO}from"./chunk-n5jzmwhy.js";import{dg as c1}from"./chunk-t0gm0pn1.js";import{wg as N2}from"./chunk-50vwafn5.js";import{yg as x1}from"./chunk-p2y1zqsb.js";import{$g as e4,Hg as J5,Kg as $3,Og as _1,Pg as N1,Tg as L5,Wg as eO,Xg as B1,Zg as x2}from"./chunk-5k8k56f2.js";import{sh as h$,th as B2}from"./chunk-hv8nt7wj.js";import{xh as q$,yh as n0}from"./chunk-xcq0cehr.js";import{Ai as _2,Gh as N4,Ni as I$,Sh as R$,Si as F1,gi as K2,ji as w2,li as H2,mi as W2,ni as g$,oi as v$,pi as W$,vi as U2,yi as F2}from"./chunk-sqk8cnej.js";import{Vi as n1,Yi as B4}from"./chunk-514va7ce.js";import{aj as KO}from"./chunk-6xzk4hsg.js";import{Cj as $O,Ej as h,Gj as z,Hj as oO,Jj as GO}from"./chunk-09kqfdpa.js";import{Oj as P0}from"./chunk-3crwyd2r.js";import{Qj as S$,Rj as z2,Tj as P$,Uj as G2}from"./chunk-9kj19a8t.js";import{Wj as i0}from"./chunk-yzf2jpam.js";import{ck as r4}from"./chunk-asgmmaec.js";import{Hk as A$,dk as i1,xk as HO,zk as P1}from"./chunk-ed2hdrwe.js";import{Jk as o4}from"./chunk-gmpsfkgg.js";var F8={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function _8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as $$,readFileSync as I1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as l6}from"node:os";import{dirname as i6,extname as n6,join as E0}from"node:path";import{fileURLToPath as a6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var l0=$O("Service"),y5=30000,m5=new Set(["completed","failed","cancelled","interrupted"]);class V4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??H$.getInstance(),this.tickMs=O.tickMs??y5}start(){if(this.timer)return;l0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=m.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!m5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,l0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Z of $)await this.evaluate(Z,O)}catch($){l0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),l0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Z={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Y=await this.dispatch({prompt:O.prompt,title:O.title??g5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Z.manual?O.nextRunAt?new Date(O.nextRunAt):null:X4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Y.session.sessionId,lastStatus:Y.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),m.publish({sessionId:Y.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Y.session.sessionId,runId:Y.runId,status:Y.status}),l0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Y.session.sessionId} (${Y.status})`)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);l0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Y);let G=O.trigger.kind==="once"?null:Z.manual?O.nextRunAt?new Date(O.nextRunAt):null:X4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:X,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Z){let Y=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!Y)return;await this.store.update(Y.id,{lastStatus:$,...Z?{lastError:Z}:{lastError:void 0}})}}function g5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class wO extends Error{code;statusCode;details;constructor(O,$,Z=500,J){super($);this.code=O;this.statusCode=Z;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class l extends wO{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class U extends wO{constructor(O){super("BAD_REQUEST",O,400)}}class p extends wO{constructor(O){super("CONFLICT",O,409)}}class rO extends wO{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class MO extends wO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class j0 extends wO{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class uO extends wO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class zO extends wO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=z.Object({error:z.Object({code:z.String(),message:z.String(),details:z.Optional(z.Record(z.String(),z.Unknown()))})});import{Hono as v5}from"hono";var z4=$O("Service"),p5=z.Object({updates:z.Record(z.String(),z.Any()),options:z.Optional(z.Object({scope:z.Optional(GO(["local","project","global"])),immediate:z.Optional(z.Boolean())}))});function u5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var U$=()=>{let O=new v5;return O.get("/",async($)=>{try{let Z=LO();return $.json(Z?u5(Z):{})}catch(Z){return z4.error("[ConfigRoutes] Failed to get config:",Z),$.json({})}}),O.put("/",async($)=>{try{let Z=await $.req.json(),J=h(p5,Z);if(!J.success)throw new U("Invalid config update format");let{updates:Y,options:X}=J.data;return await aO().updateConfig(Y,X),$.json({success:!0,updates:Y})}catch(Z){if(Z instanceof W$)throw new U(Z.message);throw z4.error("[ConfigRoutes] Failed to update config:",Z),Z}}),O.get("/permissions",async($)=>{try{let Z=LO();return $.json(Z?.permissions||{})}catch(Z){return z4.error("[ConfigRoutes] Failed to get permissions:",Z),$.json({})}}),O};import{Hono as d5}from"hono";import{streamSSE as c5}from"hono/streaming";function F$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
- `;if(O.event!==void 0)$+=`event: ${O.event}
3
- `;for(let Z of O.data.split(/\r\n|\r|\n/))$+=`data: ${Z}
4
- `;if(O.retry!==void 0)$+=`retry: ${O.retry}
5
- `;return $+=`
6
- `,Buffer.byteLength($)}class H1{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??_$,this.maxPendingBytes=O.maxPendingBytes??N$,this.serial=new x$({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??B$,sizeOf:F$,write:O.write,onFailure:($)=>{this.failure=$,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,O.onFailure?.($)}})}async writeInitial(O){await this.offerDirect(O)}observe(O,$){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer(O,$);return}this.offerLive(O,$)}async writeReplay(O,$){if(!Number.isSafeInteger($)||$<=0)throw this.fail(new G0("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if($<=this.highestReplaySequence)return;await this.offerDirect(O),this.highestReplaySequence=$,this.highestDeliveredSequence=$}finishInitialization(O){if(this.phase!=="buffering")return;let $=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let Z=O.replayed?$.filter((Y)=>Y.sequence!==void 0&&Y.sequence>this.highestReplaySequence).sort((Y,X)=>Y.sequence-X.sequence||Y.order-X.order):$.sort((Y,X)=>Y.order-X.order),J;for(let Y of Z){if(O.replayed&&Y.sequence!==void 0&&Y.sequence===J)continue;if(this.offerLive(Y.message,Y.sequence),this.serial.stats().closed)return;J=Y.sequence}}offerHeartbeat(O){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive(O),!this.serial.stats().closed}async flush(){await this.serial.flush()}close(O){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close(O)}stats(){let O=this.serial.stats();return{closed:this.phase==="closed",pendingItems:O.pendingItems+this.buffered.length,pendingBytes:O.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer(O,$){let Z=F$(O),J=this.serial.stats();if(Z>this.maxPendingBytes){this.fail(new G0("oversized",`SSE frame requires ${Z} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}if(J.pendingItems+this.buffered.length>=this.maxPendingItems||J.pendingBytes+this.bufferedBytes+Z>this.maxPendingBytes){this.fail(new G0("overflow","SSE initialization buffer limit exceeded",{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:Z,sequence:$,order:this.nextOrder}),this.bufferedBytes+=Z}offerLive(O,$){if($!==void 0){if($<=this.highestReplaySequence)return;if($<=this.highestDeliveredSequence){this.fail(new G0("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=$}if(!this.serial.offer(O).accepted)this.phase="closed"}async offerDirect(O){if(this.phase==="closed")throw this.currentFailure();let $=this.serial.offer(O);if(!$.accepted)throw this.phase="closed",$.error;await $.completion}fail(O){this.serial.close(O)}currentFailure(){return this.failure??new G0("closed","SSE egress is closed")}}var l5=15000,i5=$O("Service"),n5=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","session.archived","session.unarchived","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),a5=new Set(["queued","running","completed","failed","cancelled","interrupted"]),o5=new Set(["high","medium","low"]),t5=new Set(["feature","bug","maintenance","research"]);function s5(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,Z=["changedFiles","additions","deletions","commits"];if(Z.some((J)=>typeof $[J]!=="number"||!Number.isInteger($[J])||$[J]<0))return;return Object.fromEntries(Z.map((J)=>[J,$[J]]))}function W1(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function r5(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if(!["applied","discarded","conflicted"].includes(String($.status))||typeof $.updatedAt!=="string")return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},...W1($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}function D$(O,$){return $&&O instanceof G0&&(O.kind==="closed"||O.kind==="aborted")}var L$=()=>{let O=new d5,$=new U1;return O.onError((Z,J)=>{if(Z instanceof MO)return J.json(Z.toObject(),503);throw Z}),O.get("/",async(Z)=>{let J;try{J=$.enter(Z.req.raw.signal)}catch(X){if(X instanceof M$)throw new MO;throw X}let Y=!1;try{let X=c5(Z,async(G)=>{let W,B,M=!1,b,I,A=new Promise((_)=>{I=_}),f,L=()=>{if(B!==void 0)clearInterval(B),B=void 0;W?.(),W=void 0},R=(_)=>{if(f)return f;return M=!0,f=(async()=>{try{L(),b?.close(_),G.close()}finally{I()}})(),f},P=()=>{R(J.signal.reason)};if(J.signal.addEventListener("abort",P,{once:!0}),G.onAbort(()=>{R()}),J.signal.aborted){await R(J.signal.reason),J.signal.removeEventListener("abort",P),J.release();return}b=new H1({write:async(_)=>{await G.writeSSE(_)},onFailure:(_)=>{if(D$(_,M))return;i5.warn(`[EventRoutes] SSE egress closed: kind=${_.kind} pendingItems=${_.pendingItems??0} pendingBytes=${_.pendingBytes??0}`),R(_)}});let k=(_,e)=>{b?.observe({data:JSON.stringify({type:_,properties:e})})};W=m.subscribe((_)=>{if(!n5.has(_.type))return;if(_.type==="permission.asked"||_.type==="question.required"||_.type==="elicitation.required"){let n=_.properties.requestId;if(typeof n!=="string"||!n)return;k("interaction.pending",{sessionId:_.sessionId,projectPath:_.projectPath,interactionType:_.type==="question.required"?"question":_.type==="elicitation.required"?"elicitation":"permission",requestId:n});return}if(_.type==="interaction.resolved"){let n=_.properties.requestId;if(typeof n!=="string"||!n)return;k(_.type,{sessionId:_.sessionId,projectPath:_.projectPath,requestId:n});return}if(_.type==="session.created"||_.type==="session.deleted"||_.type==="session.archived"||_.type==="session.unarchived"){k(_.type,{sessionId:_.sessionId,projectPath:_.projectPath});return}if(_.type==="session.updated"){let n=_.properties.title,_O=_.properties.taskPriority,CO=_.properties.taskKind,PO=_.properties.taskDueAt,RO=typeof n==="string"&&Boolean(n.trim()),Z0=o5.has(String(_O)),tO=t5.has(String(CO)),vO=PO===null||typeof PO==="string"&&Number.isFinite(Date.parse(PO));if(!RO&&!Z0&&!tO&&!vO)return;k(_.type,{sessionId:_.sessionId,projectPath:_.projectPath,...RO?{title:n}:{},...Z0?{taskPriority:_O}:{},...tO?{taskKind:CO}:{},...vO?{taskDueAt:PO}:{}});return}if(_.type==="task.delivery"){let n=r5(_.properties.taskDelivery);if(!n)return;k(_.type,{sessionId:_.sessionId,projectPath:_.projectPath,taskDelivery:n,..._.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof _.properties.updatedAt==="string"?{updatedAt:_.properties.updatedAt}:{}});return}if(_.type==="schedule.fired"){let n=_.properties.scheduleId,_O=_.properties.firedAt;if(typeof n!=="string"||typeof _O!=="string")return;k(_.type,{scheduleId:n,firedAt:_O,sessionId:_.sessionId,projectPath:_.projectPath,...typeof _.properties.runId==="string"?{runId:_.properties.runId}:{},...typeof _.properties.status==="string"?{status:_.properties.status}:{}});return}let e=_.properties.taskStatus;if(typeof e!=="string"||!a5.has(e))return;let u=s5(_.properties.taskDiffStat),FO=W1(_.properties.taskQueuePosition,1),y=W1(_.properties.taskQueueDepth,0),SO=W1(_.properties.taskConcurrencyLimit,1),XO=W1(_.properties.taskInFlight,0),d=typeof _.properties.taskAdmissionPaused==="boolean"?_.properties.taskAdmissionPaused:void 0;k(_.type,{sessionId:_.sessionId,projectPath:_.projectPath,taskStatus:e,...typeof _.properties.taskStatusReason==="string"?{taskStatusReason:_.properties.taskStatusReason}:{},..._.properties.taskFailure&&typeof _.properties.taskFailure==="object"?{taskFailure:_.properties.taskFailure}:{},...typeof _.properties.taskStartedAt==="string"?{taskStartedAt:_.properties.taskStartedAt}:{},...typeof _.properties.taskCompletedAt==="string"?{taskCompletedAt:_.properties.taskCompletedAt}:{},...typeof _.properties.updatedAt==="string"?{updatedAt:_.properties.updatedAt}:{},...u?{taskDiffStat:u}:{},...FO!==void 0?{taskQueuePosition:FO}:{},...y!==void 0?{taskQueueDepth:y}:{},...SO!==void 0?{taskConcurrencyLimit:SO}:{},...XO!==void 0?{taskInFlight:XO}:{},...d!==void 0?{taskAdmissionPaused:d}:{}})});try{if(G.aborted||M)return;if(await b.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),G.aborted||M)return;if(b.finishInitialization({replayed:!1}),G.aborted||M)return;B=setInterval(()=>{if(G.aborted||M)return;b?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},l5),await A}catch(_){if(D$(_,M))return;throw _}finally{await R(),J.signal.removeEventListener("abort",P),J.release()}});return Y=!0,X}catch(X){if(!Y)J.release();throw X}}),{app:O,shutdown:(Z)=>$.shutdown(Z),getSseConnectionStats:()=>$.stats()}};import{Hono as e5}from"hono";var O9=z.Object({paused:z.Boolean()}),j$=()=>{let O=new e5;return O.get("/health",($)=>{return $.json({healthy:!0,version:i0()})}),O.get("/info",($)=>{let Z=KO(),J=LO();if(J)_0.configure(J.maxConcurrentTasks,J.maxQueuedTasks,J.maxQueuedTaskBytes);let Y=_0.getStats();return $.json({version:i0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:Z,gitBranch:A$(Z),taskAdmission:{inFlight:Y.inFlight,queued:Y.queued,maxConcurrent:Y.maxConcurrent,maxQueued:Y.maxQueued,paused:Y.paused}})}),O.put("/task-admission",async($)=>{let Z;try{Z=await $.req.json()}catch{throw new U("Invalid request body")}let J=h(O9,Z);if(!J.success)throw new U("Invalid task admission control request");_0.setPaused(J.data.paused);let Y=_0.getStats();return $.json({inFlight:Y.inFlight,queued:Y.queued,maxConcurrent:Y.maxConcurrent,maxQueued:Y.maxQueued,paused:Y.paused})}),O};import{Hono as $9}from"hono";var Z9=z.Object({projectPath:z.String({minLength:1}),action:GO(["trust","revoke"]),expectedDigest:z.Optional(z.String())}),J9=z.Object({projectPath:z.String({minLength:1}),sessionId:z.String({minLength:1}),enabled:z.Boolean()});function G4(O){if(!O)throw new U("projectPath must be absolute");try{return HO(O)}catch{throw new U("projectPath must reference a local workspace")}}function b$(O){if(!O)throw new U("sessionId is required");try{P1(O)}catch($){throw new U($ instanceof Error?$.message:"sessionId is invalid")}return O}async function S1(O){let $=G4(O),Z=LO()?.hooks??I$.hooks,J=await F1.getInstance().loadWorkspaceHooks($,Z,{includeBaseForCurrentWorkspace:!1});return B1($,async()=>{N1($);let Y=n0.getInstance();return Y.loadConfig(J,$),await _1($),Y.getConfig($)})}function T$(O,$){let Z=n0.getInstance(),J=Z.getConfig($).enabled,Y=Z.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:Z.isSessionEnabled(O,$),paused:Y,configEnabled:J}}var C$=()=>{let O=new $9;return O.get("/trust",async($)=>{let Z=$.req.query("projectPath");if(!Z)throw new U("projectPath query parameter is required");return await S1(Z),$.json(await n0.getInstance().getTrustStatus(Z))}),O.post("/trust",async($)=>{let Z=h(Z9,await $.req.json());if(!Z.success)throw new U("Invalid hook trust request");let{projectPath:J,action:Y,expectedDigest:X}=Z.data;await S1(J);let G=n0.getInstance(),W;try{W=Y==="trust"?await G.trustProject(J,X):await G.revokeProjectTrust(J)}catch(B){if(B instanceof q$)throw new p(B.message);throw B}return $.json(W)}),O.get("/session",async($)=>{let Z=G4($.req.query("projectPath")),J=b$($.req.query("sessionId"));return await S1(Z),$.json(T$(J,Z))}),O.post("/session",async($)=>{let Z=h(J9,await $.req.json());if(!Z.success)throw new U("Invalid hook session request");let J=G4(Z.data.projectPath),Y=b$(Z.data.sessionId);await S1(J);let X=n0.getInstance();if(Z.data.enabled)X.enableSession(Y,J);else X.disableSession(Y,J);return $.json(T$(Y,J))}),O};import{Hono as Q9}from"hono";var K0=$O("Service");function Y9(O){try{return E$(O)}catch{return[]}}function X9(O){if(!k1(O)||!k1(O.reference)||!k1(O.argument))throw Error("Invalid MCP completion request");let $=O.reference.type,Z=$==="prompt"&&typeof O.reference.name==="string"?{type:"prompt",name:O.reference.name}:$==="resource"&&typeof O.reference.uri==="string"?{type:"resource",uri:O.reference.uri}:void 0;if(!Z||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let J;if(O.context!==void 0){if(!k1(O.context))throw Error("Invalid MCP completion context");J=Object.create(null);for(let[Y,X]of Object.entries(O.context)){if(typeof X!=="string")throw Error("Invalid MCP completion context");J[Y]=X}}return{reference:Z,argument:{name:O.argument.name,value:O.argument.value},...J?{context:J}:{}}}function k1(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function b0(O,$){let Z=LO()?.mcpServers??{};for(let[J,Y]of Object.entries(Z)){if($&&J!==$)continue;if(!O.getServerStatus(J))await O.registerServer(J,Y,{connect:!1})}}var f$=()=>{let O=new Q9;return O.get("/",async($)=>{try{let Z=dO.getInstance();await b0(Z);let J=Z.getAllServers(),Y=await Promise.all(Array.from(J.entries()).map(async([X,G])=>({id:X,name:X,status:G.status==="connected"?"connected":G.status==="reconnecting"?"reconnecting":G.status==="connecting"?"connecting":G.lastError?"error":"offline",endpoint:G.config.command?`${G.config.command} ${(G.config.args||[]).join(" ")}`.trim():G.config.url||"Unknown",description:`MCP server: ${X}`,tools:G.tools.map((W)=>W.name),completionSupported:G.client.completionSupported,tasks:G.client.tasks,resources:G.contentCatalog.resources,resourceTemplates:G.contentCatalog.resourceTemplates.map((W)=>({...W,variables:Y9(W.uriTemplate)})),prompts:G.contentCatalog.prompts,connectedAt:G.connectedAt?.toISOString(),error:G.lastError?.message,recovery:G.recovery,logging:G.logging,instructions:G.instructions,oauthEnabled:G.client.oauthEnabled,oauthStatus:await G.client.getOAuthStatus()})));return $.json(Y)}catch(Z){return K0.error("[McpRoutes] Failed to get MCP servers:",Z),$.json({error:Z instanceof Error?Z.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async($)=>{try{let Z=$.req.param("name"),J=dO.getInstance();return await b0(J,Z),await J.connectServer(Z),$.json({success:!0})}catch(Z){return K0.error("[McpRoutes] Failed to connect MCP server:",Z),$.json({success:!1,error:Z.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let Z=$.req.param("name"),J=dO.getInstance();return await b0(J,Z),await J.disconnectServer(Z),$.json({success:!0})}catch(Z){return K0.error("[McpRoutes] Failed to disconnect MCP server:",Z),$.json({success:!1,error:Z.message},500)}}),O.get("/:name/logs",async($)=>{try{let Z=$.req.param("name"),J=Number($.req.query("limit")??20),Y=Number($.req.query("afterRevision")??0);if(!Number.isSafeInteger(J)||J<1||J>100||!Number.isSafeInteger(Y)||Y<0)return $.json({error:"Invalid MCP log pagination"},400);let X=dO.getInstance();return await b0(X,Z),$.json(X.getLogSnapshot(Z,{limit:J,afterRevision:Y}))}catch(Z){return K0.error("[McpRoutes] Failed to get MCP logs:",Z),$.json({error:Z.message},500)}}),O.post("/:name/logging-level",async($)=>{try{let Z=$.req.param("name"),J=await $.req.json();if(!R$(J.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let Y=dO.getInstance();return await b0(Y,Z),await Y.setServerLoggingLevel(Z,J.level),$.json({success:!0,level:J.level})}catch(Z){return K0.error("[McpRoutes] Failed to set MCP logging level:",Z),$.json({success:!1,error:Z.message},400)}}),O.post("/:name/complete",async($)=>{try{let Z=$.req.param("name"),J=X9(await $.req.json()),Y=dO.getInstance();await b0(Y,Z);let X=await Y.complete(Z,J);return $.json(X)}catch(Z){return K0.error("[McpRoutes] Failed to complete MCP argument:",Z),$.json({error:Z.message},400)}}),O.post("/:name/oauth/login",async($)=>{try{let Z=$.req.param("name"),J=dO.getInstance();await b0(J,Z);let Y=await J.beginOAuthLogin(Z);return $.json({success:!0,flowId:Y.flowId,authorizationUrl:Y.authorizationUrl},202)}catch(Z){return K0.error("[McpRoutes] Failed to start MCP OAuth login:",Z),$.json({success:!1,error:Z.message},400)}}),O.post("/:name/oauth/logout",async($)=>{try{let Z=$.req.param("name"),J=dO.getInstance();return await b0(J,Z),await J.logoutOAuth(Z),$.json({success:!0})}catch(Z){return K0.error("[McpRoutes] Failed to log out MCP OAuth:",Z),$.json({success:!1,error:Z.message},400)}}),O.delete("/:name",async($)=>{try{let Z=$.req.param("name");await dO.getInstance().unregisterServer(Z);let Y=LO();if(Y?.mcpServers){let{[Z]:X,...G}=Y.mcpServers;await aO().updateConfig({mcpServers:G})}return $.json({success:!0})}catch(Z){return K0.error("[McpRoutes] Failed to delete MCP server:",Z),$.json({success:!1,error:Z.message},500)}}),O.post("/",async($)=>{try{let Z=await $.req.json(),{name:J,config:Y}=Z;if(!J||!Y)return $.json({success:!1,error:"Missing name or config"},400);await dO.getInstance().registerServer(J,Y);let G=LO();return await aO().updateConfig({mcpServers:{...G?.mcpServers,[J]:Y}}),$.json({success:!0})}catch(Z){return K0.error("[McpRoutes] Failed to add MCP server:",Z),$.json({success:!1,error:Z.message},500)}}),O};import{getSupportedThinkingLevels as V9}from"@earendil-works/pi-ai";import{Hono as z9}from"hono";var h1=$O("Service");function G9(O){let $=O||KO();try{return HO($,O?"directory":"cwd")}catch(Z){throw new U(Z instanceof Error?Z.message:"directory is invalid")}}function K9(O,$,Z=h$.list()){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,supportedReasoningEfforts:V9($),supportedServiceTiers:P$($),supportedResponseVerbosities:S$($),communicationStyles:Z,input:$.input}}function w9(O){y$(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function y$(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new U("streamIdleTimeout must be at least 1000ms")}var m$=()=>{let O=new z9;return O.get("/",async($)=>{try{let Z=LO();if(!Z)throw Error("Config not initialized");let J=G9($.get("directory")),[Y,X]=await Promise.all([x1(J,Z),eO(J)]),G=Y.config.models,W=G.find((I)=>I.id===Y.config.currentModelId)??G[0],B=Y.catalog,M=X.communicationStyles.list(),b=(I)=>K9(I,B.resolveConfig(I),M);return $.json({configured:G.map(b),current:W?b(W):null})}catch(Z){if(Z instanceof U)throw Z;h1.error("[ModelsRoutes] Failed to get models:",Z);let J=new zO("Failed to get models");return $.json(J.toObject(),500)}}),O.post("/",async($)=>{let Z=P0(),J,Y;try{let X=await $.req.json(),{provider:G,displayName:W,model:B,overrides:M,apiKey:b,modelProvider:I}=X;if(!G||!B)throw new U("provider and model are required");y$(M);let A;if(I){if(I.id!==G)throw new U("modelProvider.id must match the model provider");if(LO()?.modelProviders[G])throw new U(`model provider already exists: ${G}`);A={name:I.name,baseUrl:I.baseUrl,wireApi:I.wireApi,...I.apiKeyEnv?{apiKeyEnv:I.apiKeyEnv}:{}};try{Z.registerModelProvider(G,A,[B]),Y=G}catch(R){throw new U(R instanceof Error?R.message:"Invalid model provider")}}else Z.getModel(G,B);if(b?.trim()){if(await Z.setApiKey(G,b.trim()),A)J=G}let f={provider:G,displayName:W||void 0,model:B,overrides:M||void 0},L=A?await aO().addModelWithProvider(f,A):await aO().addModel(f);return $.json({success:!0,model:L})}catch(X){if(J)await Z.credentials.delete(J);if(Y){let G=LO();Z.configureModelProviders(G?.modelProviders??{},G?.models??[])}throw h1.error("[ModelsRoutes] Failed to add model:",X),X}}),O.put("/:modelId",async($)=>{try{let Z=$.req.param("modelId"),J=await $.req.json(),{displayName:Y,overrides:X,model:G}=J,W=k$(Z);if(!W)throw new U("model config not found");if(G)P0().getModel(W.provider,G);return await aO().updateModel(Z,w9({displayName:Y,overrides:X,model:G})),$.json({success:!0})}catch(Z){throw h1.error("[ModelsRoutes] Failed to update model:",Z),Z}}),O.delete("/:modelId",async($)=>{try{let Z=$.req.param("modelId");return await aO().removeModel(Z),$.json({success:!0})}catch(Z){throw h1.error("[ModelsRoutes] Failed to delete model:",Z),Z}}),O};import{Hono as P9}from"hono";import{Mutex as B9}from"async-mutex";import{Hono as x9}from"hono";import{streamSSE as D9}from"hono/streaming";import{nanoid as Y2}from"nanoid";class Q0 extends Error{limit;resource="resident_session_projections";retryable=!0;constructor(O){super("Session projection capacity is full");this.limit=O;this.name="SessionProjectionCapacityError"}}class k0 extends Error{reason;constructor(O="Session projection residency is closed"){super(O);this.reason=O;this.name="SessionProjectionResidencyClosedError"}}class w0 extends Error{key;constructor(O,$=`Session projection residency already owns key: ${O}`){super($);this.key=O;this.name="SessionProjectionResidencyConflictError"}}class K4 extends Error{deadlineAt;constructor(O){super(`Session projection close wait timed out at ${O}`);this.deadlineAt=O;this.name="SessionProjectionResidencyCloseTimeoutError"}}function H9(O,$){if(O.size!==$.size)return!1;for(let[Z,J]of O)if(!$.has(Z)||$.get(Z)!==J)return!1;return!0}class w4{maxResident;idleMs;toSnapshot;now;residents=new Map;reservations=new Map;closings=new Map;closeStates=new Set;capacityListeners=new Set;nextGeneration=1;closed=!1;closedReason="Session projection residency is closed";invalidationPromise;resolveInvalidation;constructor(O){if(!g$(O.maxResident))throw Error("Invalid max resident Session projection limit");if(!v$(O.idleMs))throw Error("Invalid Session projection idle timeout");this.maxResident=O.maxResident,this.idleMs=O.idleMs,this.toSnapshot=O.toSnapshot,this.now=O.now??Date.now}acquire(O){if(this.assertNotClosed(),this.closings.has(O))throw new w0(O);let $=this.residents.get(O);if(!$||$.value===void 0)return;return $.pins++,this.createLease($)}reserve(O){this.assertNotClosed(),this.assertKeyOpen(O),this.makeCapacityForReservation();let $={key:O,generation:this.allocateGeneration()};return this.reservations.set(O,$),this.createReservation($)}snapshot(O){let $=this.residents.get(O);if(!$||$.value===void 0)return;return this.projectSnapshot($.value)}snapshotAll(){let O=[];for(let $ of this.residents.values()){if($.value===void 0)continue;let Z=this.projectSnapshot($.value);if(Z!==void 0)O.push(Z)}return O}beginCloseMany(O,$){this.assertNotClosed();let Z=[...new Set(O)].sort((L,R)=>L.localeCompare(R));for(let L of Z)if(this.closings.has(L))throw new w0(L,`Session projection residency is already closing key: ${L}`);let J=new Map,Y=new Map,X=new Map,G=new Set;for(let L of Z){let R=this.reservations.get(L);if(R)this.reservations.delete(L);let P=this.residents.get(L);if(P){if(this.residents.delete(L),P.phase="closing",X.set(L,P),this.closings.set(L,P),J.set(L,P.generation),G.add(L),P.value!==void 0){let _=this.projectSnapshot(P.value);if(_!==void 0)Y.set(L,_)}continue}let k={key:L,generation:R?.generation??this.allocateGeneration(),value:void 0,pins:0,lastUsedAt:this.now(),phase:"closing"};X.set(L,k),this.closings.set(L,k),J.set(L,k.generation)}let W={keys:Z,generations:J,snapshots:Y,entries:X,originalResidentKeys:G,waiters:new Set,state:"open"};this.closeStates.add(W),this.notifyCapacityAvailableIf(!0);let B=()=>{if(W.state==="committed")throw new k0("Session projection close set is already committed");if(W.state==="rolled_back")throw new k0("Session projection close set is already rolled back")},M=()=>{for(let L of W.entries.values())if(L.pins>0)return!1;return!0},b=()=>{if(!M())return;for(let L of W.waiters){if(L.timer!==void 0)clearTimeout(L.timer);L.removeAbortListener?.(),L.resolve()}W.waiters.clear()},I=({signal:L,deadlineAt:R}={})=>{if(W.state!=="open"||M())return Promise.resolve();if(R!==void 0&&R<=this.now())return Promise.reject(new K4(R));return new Promise((P,k)=>{let _={resolve:()=>P(),reject:k,timer:void 0,removeAbortListener:void 0};if(W.waiters.add(_),R!==void 0){let e=Math.max(0,R-this.now());_.timer=setTimeout(()=>{W.waiters.delete(_),_.removeAbortListener?.(),k(new K4(R))},e)}if(L){let e=()=>{if(W.waiters.delete(_),_.timer!==void 0)clearTimeout(_.timer);L.removeEventListener("abort",e),k(L.reason instanceof Error?L.reason:Error(String(L.reason??"AbortError")))};if(L.addEventListener("abort",e,{once:!0}),_.removeAbortListener=()=>{L.removeEventListener("abort",e)},L.aborted)e()}})},A=()=>{if(W.state==="committed")return;if(B(),!M())throw new w0(W.keys[0]??"","Session projection close set still has active pins");let L=!1;for(let R of W.keys){let P=W.entries.get(R);if(!P)continue;if(this.closings.get(R)===P){if(this.closings.delete(R),P.value!==void 0)L=!0}}W.state="committed",this.closeStates.delete(W),b(),this.notifyCapacityAvailableIf(L)},f=(L)=>{if(this.closed)throw new k0(this.closedReason);if(W.state==="committed")throw new k0("Session projection close set is already committed");if(W.state==="rolled_back"){if(!W.rollbackReplacements)return;if(!H9(W.rollbackReplacements,L))throw new w0(W.keys[0]??"","Session projection close set rollback replacements changed");return}if(!M())throw new w0(W.keys[0]??"","Session projection close set still has active pins");for(let _ of W.originalResidentKeys)if(!L.has(_))throw new w0(_,`Session projection close rollback requires replacement for key: ${_}`);let R=!1,P=!1,k=this.now();for(let _ of W.keys){let e=W.entries.get(_);if(!e)continue;if(this.closings.get(_)===e)this.closings.delete(_);if(!W.originalResidentKeys.has(_)){R||=e.value!==void 0;continue}let u=L.get(_);if(u===void 0){R||=e.value!==void 0;continue}if(e.value=u,e.phase="resident",e.lastUsedAt=k,this.residents.set(_,e),e.pins===0)P=!0}W.rollbackReplacements=new Map(L),W.state="rolled_back",this.closeStates.delete(W),b(),this.notifyCapacityAvailableIf(R||P)};return{keys:W.keys,generations:W.generations,snapshots:W.snapshots,waitForIdle:I,commit:A,rollback:f}}invalidateAll(O){if(this.closed&&this.invalidationPromise)return this.invalidationPromise;this.closed=!0,this.closedReason=O;for(let $ of[...this.reservations.keys()])this.reservations.delete($);for(let[$,Z]of[...this.residents.entries()])this.residents.delete($),Z.phase="closing",this.closings.set($,Z);return this.invalidationPromise=new Promise(($)=>{this.resolveInvalidation=$}),this.maybeFinishInvalidation(),this.invalidationPromise}sweepIdle(){if(this.closed)return 0;let O=this.now(),$=0;while(!0){let Z=[...this.residents.values()].filter((J)=>J.pins===0).sort((J,Y)=>J.lastUsedAt-Y.lastUsedAt||J.generation-Y.generation).find((J)=>O-J.lastUsedAt>=this.idleMs);if(!Z)return $;this.residents.delete(Z.key),$++,this.notifyCapacityAvailableIf(!0)}}onCapacityAvailable(O){return this.capacityListeners.add(O),()=>{this.capacityListeners.delete(O)}}getStats(){let O=0,$=0,Z=this.reservations.size,J=0;for(let Y of this.residents.values())if(O++,Y.pins>0)J++;for(let Y of this.closings.values())if($++,Y.pins>0)J++;return{resident:O,closing:$,reserved:Z,pinned:J,retained:O+Z+this.countClosingWithValue(),maxResident:this.maxResident,idleMs:this.idleMs}}getDebugStats(){let O=0,$=0;for(let Z of this.closings.values())if(Z.value===void 0)O++;for(let Z of this.closeStates)$+=Z.waiters.size;return{tombstones:O,waiters:$,listeners:this.capacityListeners.size}}assertNotClosed(){if(this.closed)throw new k0(this.closedReason)}assertKeyOpen(O){if(this.residents.has(O)||this.reservations.has(O)||this.closings.has(O))throw new w0(O)}retainedCount(){return this.residents.size+this.reservations.size+this.countClosingWithValue()}countClosingWithValue(){let O=0;for(let $ of this.closings.values())if($.value!==void 0)O++;return O}allocateGeneration(){let O=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,O}createReservation(O){let $=!1;return{key:O.key,generation:O.generation,commit:(Z)=>{if($)throw new w0(O.key);if(this.closed)throw this.reservations.delete(O.key),$=!0,new k0(this.closedReason);if(this.reservations.get(O.key)!==O)throw $=!0,new w0(O.key);this.reservations.delete(O.key);let J={key:O.key,generation:O.generation,value:Z,pins:1,lastUsedAt:this.now(),phase:"resident"};return this.residents.set(O.key,J),$=!0,this.createLease(J)},cancel:()=>{if($)return;if(this.reservations.get(O.key)===O)this.reservations.delete(O.key),this.notifyCapacityAvailableIf(!0);$=!0}}}createLease(O){let $=!1;return{key:O.key,generation:O.generation,get value(){return O.value},isCurrent:()=>{let Z=this.residents.get(O.key);if(Z===O&&Z.generation===O.generation)return!0;let J=this.closings.get(O.key);return J===O&&J.generation===O.generation},release:()=>{if($)return;$=!0;let Z=this.residents.get(O.key),J=this.closings.get(O.key),Y=Z===O&&Z.generation===O.generation?Z:J===O&&J.generation===O.generation?J:void 0;if(!Y)return;Y.pins=Math.max(0,Y.pins-1),Y.lastUsedAt=this.now(),this.notifyCapacityAvailableIf(!0),this.resolveIdleWaitersForEntry(Y),this.maybeFinishInvalidation()}}}makeCapacityForReservation(){while(this.retainedCount()>=this.maxResident){let O=[...this.residents.values()].filter(($)=>$.pins===0).sort(($,Z)=>$.lastUsedAt-Z.lastUsedAt||$.generation-Z.generation)[0];if(!O)throw new Q0(this.maxResident);this.residents.delete(O.key)}}projectSnapshot(O){try{return this.toSnapshot(O)}catch{return}}resolveIdleWaitersForEntry(O){if(O.pins>0)return;for(let $ of this.closeStates){if(!$.entries.has(O.key))continue;let Z=!0;for(let J of $.entries.values())if(J.pins>0){Z=!1;break}if(!Z)continue;for(let J of $.waiters){if(J.timer!==void 0)clearTimeout(J.timer);J.removeAbortListener?.(),J.resolve()}$.waiters.clear()}}maybeFinishInvalidation(){if(!this.closed||!this.resolveInvalidation)return;for(let $ of this.closings.values())if($.pins>0)return;this.closings.clear();let O=this.resolveInvalidation;this.resolveInvalidation=void 0,O()}notifyCapacityAvailableIf(O){if(!O)return;for(let $ of[...this.capacityListeners])try{$()}catch{}}}class H4{runtimes=new Map;createRuntime;constructor(O={}){this.createRuntime=O.createRuntime??(($)=>new p$($.projectPath,`web-browser:${$.sessionId}`,{exposeArtifactPaths:!1}))}get(O){let $=i(O),Z=this.runtimes.get($);if(Z?.state==="live")return Z.runtime;if(Z)throw new y1("browser_disposed","Browser Session Runtime is closed",{retryable:!0});let J=this.createRuntime(O);return this.runtimes.set($,{state:"live",runtime:J}),J}async reset(O){let $=this.runtimes.get(i(O));if($?.state==="live")await $.runtime.page({action:{kind:"reset"}})}dispose(O){let $=i(O),Z=this.runtimes.get($);if(!Z)return Promise.resolve();if(Z.state==="disposing")return Z.disposePromise;return this.disposeKey($,Z.runtime)}async disposeAll(){let $=(await Promise.allSettled([...this.runtimes.keys()].map((Z)=>{let J=this.runtimes.get(Z);if(!J)return Promise.resolve();if(J.state==="disposing")return J.disposePromise;return this.disposeKey(Z,J.runtime)}))).find((Z)=>Z.status==="rejected");if($)throw $.reason}stats(){let O=0,$=0,Z=0;for(let J of this.runtimes.values()){if(J.state==="live")O++;if(J.state==="disposing")$++;if(J.state==="failed")Z++}return{sessions:this.runtimes.size,live:O,disposing:$,failed:Z}}disposeKey(O,$){let Z=$.dispose().then(()=>{if(this.runtimes.get(O)?.runtime===$)this.runtimes.delete(O)},(J)=>{if(this.runtimes.get(O)?.runtime===$)this.runtimes.set(O,{state:"failed",runtime:$,error:J});throw J});return this.runtimes.set(O,{state:"disposing",runtime:$,disposePromise:Z}),Z}}import{Hono as U9}from"hono";var u$=z.Object({action:GO(["accept","dismiss"])},{additionalProperties:!1}),W9=oO(z.Union([z.Object({kind:z.Literal("click"),dialog:z.Optional(u$)},{additionalProperties:!1}),z.Object({kind:z.Literal("click_at"),screenshotId:z.String({minLength:1,maxLength:d$}),x:z.Integer({minimum:0,maximum:W4}),y:z.Integer({minimum:0,maximum:W4}),dialog:z.Optional(u$)},{additionalProperties:!1}),z.Object({kind:z.Literal("hover")},{additionalProperties:!1}),z.Object({kind:z.Literal("fill"),value:z.String()},{additionalProperties:!1}),z.Object({kind:z.Literal("type"),value:z.String()},{additionalProperties:!1}),z.Object({kind:z.Literal("press"),key:GO(["Enter","Tab","Escape","Backspace","Delete","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown","Space"])},{additionalProperties:!1}),z.Object({kind:z.Literal("select"),values:z.Array(z.String())},{additionalProperties:!1}),z.Object({kind:z.Literal("check")},{additionalProperties:!1}),z.Object({kind:z.Literal("uncheck")},{additionalProperties:!1}),z.Object({kind:z.Literal("scroll"),direction:GO(["up","down","left","right"]),amount:z.Integer()},{additionalProperties:!1})])),c$=oO(z.Object({action:z.Optional(GO(["goto","back","forward","reload"])),url:z.Optional(z.String()),pageId:z.Optional(z.String()),expectedOrigin:z.Optional(z.String()),waitUntil:z.Optional(GO(["commit","domcontentloaded","load"])),timeoutMs:z.Optional(z.Integer())},{additionalProperties:!1})),l$=oO(z.Object({pageId:z.String(),snapshotId:z.String(),ref:z.Optional(z.String()),expectedOrigin:z.String(),action:W9,timeoutMs:z.Optional(z.Integer())},{additionalProperties:!1}));function i$(O,$){if(O===void 0)return;let Z=Number(O);if(!Number.isSafeInteger(Z))throw new U(`${$} must be an integer`);return Z}function F9(O,$){if(O===void 0)return;if(O==="true")return!0;if(O==="false")return!1;throw new U(`${$} must be true or false`)}function _9(O){let $=O.code==="browser_not_installed"||O.code==="browser_disconnected"||O.code==="browser_disposed"?503:O.code==="browser_capacity"?429:O.code==="browser_unsupported"?400:409;return new wO(O.code.toUpperCase(),O.message,$,O.details)}function n$(O){let $=new U9;$.use("*",(J,Y)=>O.withAdmission(Y)),$.onError((J,Y)=>{let X=J instanceof y1?_9(J):J instanceof wO?J:new zO;return Y.json(X.toObject(),X.statusCode)});let Z=(J,Y)=>O.resolveSessionRef(J,Y);return $.post("/:sessionId/browser/navigate",async(J)=>{let Y=await J.req.json().catch(()=>{return}),X=h(c$,Y);if(!X.success)throw new U("Invalid browser navigation request");let G=await Z(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(await O.getRuntime(G).navigate(X.data))}),$.post("/:sessionId/browser/interact",async(J)=>{let Y=await J.req.json().catch(()=>{return}),X=h(l$,Y);if(!X.success)throw new U("Invalid browser interaction request");let G=await Z(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(await O.getRuntime(G).interact(X.data))}),$.get("/:sessionId/browser/snapshot",async(J)=>{let Y=await Z(J.req.param("sessionId"),J.req.query("projectPath")),X=i$(J.req.query("depth"),"depth"),G=F9(J.req.query("includeBoxes"),"includeBoxes");return J.json(await O.getRuntime(Y).snapshot({...J.req.query("pageId")?{pageId:J.req.query("pageId")}:{},...X===void 0?{}:{depth:X},...G===void 0?{}:{includeBoxes:G}}))}),$.get("/:sessionId/browser/inspect",async(J)=>{let Y=await Z(J.req.param("sessionId"),J.req.query("projectPath")),X=J.req.query("target"),G=J.req.query("pageId"),W=J.req.query("expectedOrigin");if(X==="screenshot"){let b=J.req.query("source")??"user";if(b!=="user"&&b!=="agent")throw new U("Unsupported browser screenshot source");if(b==="agent"&&(!G||!W))throw new U("Agent browser screenshots require pageId and expectedOrigin");let I={...G?{pageId:G}:{},...W?{expectedOrigin:W}:{}},A=b==="agent"?await O.captureAgentScreenshot(Y,I):await O.getRuntime(Y).screenshot(I);return new Response(new Uint8Array(A),{headers:{"Content-Type":"image/png","Content-Length":String(A.length),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}let B=i$(J.req.query("limit"),"limit"),M={...G?{pageId:G}:{},...W?{expectedOrigin:W}:{}};if(X==="find"){let b=J.req.query("text");if(!b)throw new U("text is required for browser find");return J.json(await O.getRuntime(Y).inspect({...M,target:{kind:"find",text:b,...B===void 0?{}:{limit:B}}}))}if(X!=="console"&&X!=="page-errors"&&X!=="network")throw new U("Unsupported browser inspection target");return J.json(await O.getRuntime(Y).inspect({...M,target:{kind:X,...B===void 0?{}:{limit:B}}}))}),$.post("/:sessionId/browser/reset",async(J)=>{let Y=await Z(J.req.param("sessionId"),J.req.query("projectPath"));return await O.resetRuntime(Y),J.json({success:!0})}),$}import{nanoid as p1}from"nanoid";import{LRUCache as N9}from"lru-cache";var H0=new Map,g1=new N9({max:100,ttl:1800000});function YO(O){return{sessionId:O.id,projectPath:O.projectPath}}function a$(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function o$(O){H0.set(O.id,O)}function hO(O){if(!O)return;return H0.get(O)??g1.get(O)}function t$(O){if(H0.get(O.id)!==O)return;H0.delete(O.id),g1.set(O.id,O)}function s$(O){H0.delete(O),g1.delete(O)}function yO(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function h0(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed"||O.status==="attention_required")return!1;let Z=O.pendingPermission;if(O.pendingPermission=void 0,Z?.resolve({approved:!1,reason:m1}),Z)m.publish(a$(O),"interaction.resolved",{requestId:Z.permissionId});return O.abortController.abort($),O.status="cancelled",m.publish(a$(O),"run.cancelled",{runId:O.id}),!0}function r$(O){for(let $ of H0.values())h0($,O);H0.clear(),g1.clear()}function U4(){return[...H0.values()]}function e$(){return H0.size}function O2(O,$){return[...H0.values()].find((Z)=>Z.sessionId===O.sessionId&&Z.projectPath===O.projectPath&&Z.pendingPermission?.permissionId===$)}function v1(O,$=!1){let{permissionId:Z,details:J}=O;if(J.type==="askUserQuestion"&&J.questions)return{type:"question.required",properties:{requestId:Z,toolCallId:J.toolCallId??Z,questions:J.questions,details:J,...$?{replayed:!0}:{}}};if(J.type==="mcpElicitation"&&J.mcpElicitation)return{type:"elicitation.required",properties:{requestId:Z,toolCallId:J.toolCallId??Z,elicitation:J.mcpElicitation,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:Z,toolName:J.toolName,description:J.message,args:J.args,details:J,...$?{replayed:!0}:{}}}}function O0(O,$){O.title=$.title??O.title,O.taskStatus=$.taskStatus,O.taskStatusReason=$.taskStatusReason,O.taskFailure=$.taskFailure,O.taskStartedAt=$.taskStartedAt,O.taskCompletedAt=$.taskCompletedAt,O.taskPromptSummary=$.taskPromptSummary,O.taskPriority=$.taskPriority,O.taskKind=$.taskKind,O.taskDueAt=$.taskDueAt,O.taskModelId=$.taskModelId,O.selectedModelId=$.selectedModelId,O.permissionMode=$.permissionMode,O.reasoningEffort=$.reasoningEffort,O.serviceTier=$.serviceTier,O.responseVerbosity=$.responseVerbosity,O.communicationStyle=$.communicationStyle,O.communicationStyleDigest=$.communicationStyleDigest,O.projectInstructionsDigest=$.projectInstructionsDigest,O.pendingInteraction=$.pendingInteraction,O.taskRetryAvailable=$.taskRetryAvailable,O.taskRetriedFrom=$.taskRetriedFrom,O.taskDelivery=$.taskDelivery,O.taskIsolation=$.taskIsolation,O.taskSourceProjectPath=$.taskSourceProjectPath,O.taskWorktreePath=$.taskWorktreePath,O.taskWorktreeBranch=$.taskWorktreeBranch,O.taskBaseCommit=$.taskBaseCommit,O.taskDiffStat=$.taskDiffStat,O.taskQueuePosition=$.taskQueuePosition,O.taskQueueDepth=$.taskQueueDepth,O.taskConcurrencyLimit=$.taskConcurrencyLimit,O.archivedAt=$.archivedAt,O.archivedBySessionId=$.archivedBySessionId,O.messageCount=$.messageCount,O.updatedAt=new Date($.lastMessageTime)}async function Y0(O){let $=await g.findSessionMetadata(O.id,O.projectPath);if($)O0(O,$)}var a0=$O("Service"),u1="web-pending-resume-recovery-budget-exhausted";class D1 extends Error{evidence;constructor(O){super(O.taskFailure.message);this.evidence=O;this.name="WebAgentRunFailure"}}function $2(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
7
- `)}async function Q2(O,$,Z,J,Y,X={}){let{abortController:G,sessionId:W,id:B}=O,M=X.preparedInputTurn?.messageId??p1(12),I=X.pendingInputOnly===!0||X.preparedInputTurn?.mode==="pending"||X.goalContinuationOnly===!0?void 0:p1(12),A=X.runtimeLease,f=X.projectionLease,L,R,P=!1,k=!1,_,e=YO($),u=X.pendingResume?.projectedInputIds??new Set,FO=(d)=>{if(u.has(d))return;if(u.size>=Z2){let n=u.values().next().value;if(n!==void 0)u.delete(n)}u.add(d)},y=(d,n)=>{m.publish(e,d,n)},SO=async(d)=>{let n=d.metadata?.recoveryAttention;if(!n||!L)return!1;if(X.preparedInputTurn)await L.finishTurn(X.preparedInputTurn.handle,{preserveStartupRecovery:!0,outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}}).catch(()=>{return});let _O=`Turn recovery requires attention: ${n.reason}`,CO=await L.setTaskStatus("interrupted",_O).catch(()=>{return});if(CO)O0($,CO);else $.taskStatus="interrupted",$.taskStatusReason=_O,$.taskCompletedAt=void 0;return O.status="attention_required",y("session.status",{status:"idle"}),!0},XO=async()=>{let d=String(G.signal.reason||"Task run cancelled");if($.taskIsolation){if(!A)A=await Y($).catch(()=>{return});let n=L??A?.value;if(d==="user-cancel")await n?.discardPendingInput().catch((CO)=>{a0.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,CO)});let _O=await n?.setTaskStatus("cancelled",d).catch(()=>{return});if(_O)O0($,_O);else await Y0($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=d,$.taskCompletedAt??=new Date().toISOString()};try{if(X.pendingResume){let T=X.pendingResume.deadlineAt-Date.now();if(T<=0)throw G.abort(u1),new D1({taskFailure:o0("timeout"),outputStarted:!1,toolExecutionStarted:!1,toolCallsCount:0});_=setTimeout(()=>{G.abort(u1);let JO=O.pendingPermission;if(O.pendingPermission=void 0,JO?.resolve({approved:!1,reason:m1}),JO)y("interaction.resolved",{requestId:JO.permissionId})},T),_.unref?.()}if(X.taskAdmission){if(await X.taskAdmission.ready,await O.taskAdmissionUpdate,G.signal.aborted)throw Error(String(G.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!X.pendingInputOnly&&!X.goalContinuationOnly)y("message.created",{messageId:M,role:"user",content:$2(Z),...X.preparedInputTurn?.metadata?{metadata:X.preparedInputTurn.metadata}:{}});if(y("session.status",{status:"running"}),I)y("message.created",{messageId:I,role:"assistant",content:""});A??=await Y($),L=A.value;let d=L,n=Boolean(X.outputSchema??d.getPendingSteeringMessages().find((T)=>T.outputSchema)?.outputSchema);R=await J2.createWithRuntime(d,{sessionId:W,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let _O=async(T)=>{let JO=T.interactionRequestId??p1(12),NO=300000;O.status="waiting_permission";let C1=new Promise((d0)=>{let e1=setTimeout(()=>{a0.warn(`[SessionRoutes] Permission ${JO} timed out after 300000ms`),y("permission.timeout",{requestId:JO}),d0({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:JO,resolve:(c0)=>{clearTimeout(e1),d0(c0)},details:T}}),z1=O.pendingPermission;if(!z1)throw Error("Permission request was not registered");let R1=v1(z1);y(R1.type,R1.properties),a0.info(`[SessionRoutes] Permission request created: ${JO}, runId: ${B}`);let G1=await C1;if(a0.info(`[SessionRoutes] Permission response received: ${JO}, approved: ${G1.approved}`),!G.signal.aborted)O.status="running";if(O.pendingPermission===z1)O.pendingPermission=void 0;return y("interaction.resolved",{requestId:JO}),G1},PO={messages:await g.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:W,workspaceRoot:$.projectPath,signal:G.signal,permissionMode:J,onPermissionModeChange:async(T)=>{$.permissionMode=T,$.updatedAt=new Date,y("session.updated",{permissionMode:T})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:_O}},RO=()=>{if(!I)I=p1(12),y("message.created",{messageId:I,role:"assistant",content:""});return I},Z0=async(T)=>{if(T.kind==="tool_start"||T.kind==="tool_progress"||T.kind==="tool_result")k=!0;let JO=d1(T);if(JO){if(JO.toolName===M1)return;y(JO.type,{...JO.messageScoped?{messageId:RO()}:{},...JO.properties});return}switch(T.kind){case"content_delta":if(T.delta.length>0)P=!0;if(n)break;y("message.delta",{messageId:RO(),delta:T.delta});break;case"structured_output":P=!0,y("structured.output",{messageId:RO(),output:T.output,schemaDigest:T.schemaDigest});break;case"thinking_delta":if(T.delta.length>0)P=!0;y("thinking.delta",{messageId:RO(),delta:T.delta});break;case"token_usage":y("token.usage",{...T.usage});break;case"turn_start":y("turn.started",{turn:T.turn,maxTurns:T.maxTurns});break;case"turn_recovery":y("turn.recovery",{assessment:T.assessment});break;case"provider_recovery":case"turn_activity":break;case"steering_applied":for(let NO of T.messages){if((NO.origin??"user")!=="user")continue;if(NO.persisted)continue;if(u.has(NO.id))continue;y("message.created",{messageId:NO.id,role:"user",content:$2(NO.content),...NO.metadata?{metadata:NO.metadata}:{},...NO.recovered?{recovered:!0}:{}}),FO(NO.id)}y("steering.applied",{runId:B,messageIds:T.messageIds,count:T.count,recovered:T.recovered,delivery:T.delivery,queued:d.getPendingSteeringCount()}),y("follow_up.queue.changed",{queue:T.queue});break;case"follow_up_started":if(I)y("message.complete",{messageId:I}),I=void 0;y("follow_up.started",{runId:B,queued:T.queued,recovered:T.recovered}),y("follow_up.queue.changed",{queue:T.queue}),RO();break;case"follow_up_queue_changed":y("follow_up.queue.changed",{queue:T.queue});break;case"goal_updated":y("goal.updated",{goal:T.goal});break;case"goal_continuation_started":y("goal.continuation.started",{goal:T.goal,continuation:T.continuation,...T.prematureStopPattern?{prematureStopPattern:T.prematureStopPattern}:{},...T.prematureStopCount!==void 0?{prematureStopCount:T.prematureStopCount}:{}}),RO();break;case"compaction":y(T.phase==="start"?"compaction.started":"compaction.completed",{...T.reason?{reason:T.reason}:{},...T.strategy?{strategy:T.strategy}:{},...T.outcome?{outcome:T.outcome}:{},...T.preTokens!==void 0?{preTokens:T.preTokens}:{},...T.preTokenSource?{preTokenSource:T.preTokenSource}:{},...T.estimatedPendingTokens!==void 0?{estimatedPendingTokens:T.estimatedPendingTokens}:{},...T.postTokens!==void 0?{postTokens:T.postTokens}:{},...T.sampleAttempts!==void 0?{sampleAttempts:T.sampleAttempts}:{},...T.inputReductions!==void 0?{inputReductions:T.inputReductions}:{},...T.messagesOmitted!==void 0?{messagesOmitted:T.messagesOmitted}:{},...T.filesOmitted!==void 0?{filesOmitted:T.filesOmitted}:{},...T.imagesOmitted!==void 0?{imagesOmitted:T.imagesOmitted}:{},...T.fallbackTargetTokens!==void 0?{fallbackTargetTokens:T.fallbackTargetTokens}:{},...T.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:T.fallbackMessagesOmitted}:{},...T.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:T.fallbackMessagesTruncated}:{},...T.failureReason?{failureReason:T.failureReason}:{},...T.memory?{memory:T.memory}:{}});break;case"model_fallback":y("model.fallback",{from:T.from,to:T.to,candidate:T.candidate,candidateCount:T.candidateCount,trigger:T.trigger});break;case"task_update":y("task.updated",{tasks:T.tasks});break;case"goal_frontier_updated":y("goal.frontier.updated",{goalId:T.goal.goalId,goalStatus:T.goal.status,frontier:T.frontier,stall:T.goal.frontierStall});break;default:break}},tO=(T)=>{let JO=T.metadata?.toolCallsCount;return new D1({taskFailure:T0(T.error?.details??T.error?.message??"Agent run failed"),outputStarted:P,toolExecutionStarted:k,toolCallsCount:typeof JO==="number"&&Number.isInteger(JO)?JO:-1})},vO=await F4(R.chatStream(Z,PO,{stream:!0,pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:X.taskAdmission}),Z0);if(await SO(vO))return;if(!vO.success)throw tO(vO);for(let T=0;T<20;T++){let JO=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,d.getPendingSteeringCount()===0){if(!JO)break;continue}if(G.signal.aborted)break;if(vO=await F4(R.chatStream("",PO,{stream:!0,pendingInputOnly:!0,taskAdmission:X.taskAdmission}),Z0),await SO(vO))return;if(!vO.success)throw tO(vO)}if(await Y0($),X.pendingResume&&G.signal.aborted&&G.signal.reason===u1)throw new D1({taskFailure:o0("timeout"),outputStarted:P,toolExecutionStarted:k,toolCallsCount:Number.isInteger(vO.metadata?.toolCallsCount)?vO.metadata?.toolCallsCount??-1:-1});if(G.signal.aborted||O.status==="cancelled"){await XO(),y("session.status",{status:"idle"});return}if(X.pendingResume)X.onPendingResumeSuccess?.(X.pendingResume);if(I)y("message.complete",{messageId:I});y("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),y("session.completed",{runId:B,outputTruncated:vO.metadata?.outputTruncated??!1}),y("session.status",{status:"idle"})}catch(d){if(L&&X.preparedInputTurn)await(L.getTurnRecoveryAssessment().state==="requires_attention"?L.finishTurn(X.preparedInputTurn.handle,{preserveStartupRecovery:!0}):L.finishTurn(X.preparedInputTurn.handle)).catch(()=>{return});let n=X.pendingResume!==void 0&&G.signal.aborted&&G.signal.reason===u1;if(G.signal.aborted&&!n||O.status==="cancelled"){if(X.pendingResume)X.onPendingResumeCancelled?.(X.pendingResume);h0(O,"runtime-abort"),await XO(),y("session.status",{status:"idle"});return}let _O=d instanceof D1?d.evidence:n?{taskFailure:o0("timeout"),outputStarted:P,toolExecutionStarted:k,toolCallsCount:-1}:X.pendingResume?{taskFailure:T0(d),outputStarted:!0,toolExecutionStarted:!0,toolCallsCount:-1}:void 0,CO=X.pendingResume!==void 0&&_O!==void 0&&X.onPendingResumeFailure?.(X.pendingResume,_O,n||(L?.getPendingSteeringCount()??0)>0,n)===!0;if(O.status="failed",CO){let RO=await L?.setTaskStatus("running").catch(()=>{return});if(RO)O0($,RO);$.taskStatus="running",$.taskStatusReason=void 0,$.taskFailure=void 0,$.taskCompletedAt=void 0,y("session.status",{status:"running"});return}await Y0($).catch(()=>{return}),a0.error("[SessionRoutes] Agent execution error:",d),$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let PO=_O?.taskFailure??T0(d);if(!$.taskFailure){let RO=L?await L.setTaskStatus("failed",d).catch(()=>{return}):await g.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:PO.message,taskFailure:PO,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(RO)O0($,RO)}$.taskStatusReason??=PO.message,$.taskFailure??=PO,y("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),y("session.status",{status:"error"})}finally{if(_)clearTimeout(_);if(X.taskAdmission?.release(),X.taskAdmission){let d=_0.getStats();y("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:d.queued,taskConcurrencyLimit:d.maxConcurrent,taskInFlight:d.inFlight,taskAdmissionPaused:d.paused,updatedAt:new Date().toISOString()})}if(await R?.destroy().catch(()=>{return}),A?.release(),f?.release(),O.disposeRuntimeOnSettle&&X.disposeRuntime)await X.disposeRuntime($,L).catch((d)=>{a0.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,d)});t$(O)}}var t=$O("Service"),M9=z.Object({title:z.Optional(z.String()),projectPath:z.Optional(z.String())}),L9=g2,A9=oO(z.Object({projectPath:z.Optional(z.String()),expectedVersion:R2,operation:f2},{additionalProperties:!1})),j9=new Set(["revision_conflict","already_claimed","immutable_origin","immutable_boundary","not_found","runtime_unavailable","invalid_mutation","storage_unavailable"]);function b9(O){if(!(O instanceof Error)||O.name!=="FollowUpQueueMutationError")return!1;if(!("code"in O)||!("snapshot"in O))return!1;let $=O;return typeof $.code==="string"&&j9.has($.code)&&h(E2,$.snapshot).success}var T9=z.Object({title:z.Optional(z.String()),projectPath:z.Optional(z.String())}),q9=z.Object({projectPath:z.String()}),I9=z.Object({objective:z.String({minLength:1}),tokenBudget:z.Optional(z.Integer({minimum:1})),permissionMode:z.Optional(GO(["default","autoEdit","plan","yolo"]))}),C9=z.Union([z.Object({action:z.Literal("pause")}),z.Object({action:z.Literal("resume")}),z.Object({action:z.Literal("edit"),objective:z.String({minLength:1})})]),U0,j1,B0=new Map,X0=new Map;function R9(O){let $=structuredClone({...O,createdAt:O.createdAt.toISOString(),updatedAt:O.updatedAt.toISOString()});return{...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)}}function E9(O){if(O.type.startsWith("committed.")){let $=O.properties.event;if(!$||typeof $!=="object"||Array.isArray($))return;let Z=n2($);if(!Z)return;return{...Z.seq!==void 0?{id:String(Z.seq)}:{},data:JSON.stringify({type:Z.type,...Z.seq!==void 0?{seq:Z.seq}:{},properties:{...Z.properties,sessionId:O.sessionId,projectPath:O.projectPath}})}}return{...typeof O.seq==="number"?{id:String(O.seq)}:{},data:JSON.stringify({type:O.type,...typeof O.seq==="number"?{seq:O.seq}:{},properties:{...O.properties,sessionId:O.sessionId,projectPath:O.projectPath}})}}function f9(){let O=U0;if(O)O.accepting=!1,O.invalidateAll("route-reset");U0=void 0,r$("route-reset");for(let $ of B0.values())$.controller.abort("route-reset");B0.clear(),j1?.(),j1=void 0}function n2(O){let $=typeof O.seq==="number"?{seq:O.seq}:{};if(O.type==="message_created"&&O.data.metadata!==null&&typeof O.data.metadata==="object"&&!Array.isArray(O.data.metadata)&&O.data.metadata.clientVisible===!1)return;if((O.type==="part_created"||O.type==="part_updated")&&O.data.partType!=="tool_call"&&O.data.partType!=="tool_result")return;if(O.type==="part_created"&&O.data.partType==="tool_call"){let Z=O.data.payload;return{type:"tool.start",...$,properties:{messageId:O.data.messageId,toolCallId:Z.toolCallId??O.data.partId,toolName:Z.toolName??"unknown",arguments:JSON.stringify(Z.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let Z=O.data.payload,J=Z.toolName??"unknown",Y=T4(Z),X=q4(I4(J,Y),b4);return{type:"tool.result",...$,properties:{messageId:O.data.messageId,toolCallId:Z.toolCallId??O.data.partId,toolName:J,success:Y.success,status:Y.success?"completed":"failed",summary:Y.metadata?.summary,output:C4(X),metadata:b1(J,Y.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function S9(O,$,Z){let J=d1(Z);if(J){if(J.type==="tool.start")m.publish(O,"subagent.update",{subagentSessionId:$,toolName:J.toolName});m.publish(O,`subagent.${J.type}`,{subagentSessionId:$,...J.properties});return}switch(Z.kind){case"content_delta":m.publish(O,"subagent.delta",{subagentSessionId:$,delta:Z.delta});break;case"thinking_delta":m.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:Z.delta});break;case"stream_end":m.publish(O,"subagent.stream.end",{subagentSessionId:$});break;default:break}}function q0(O,$="projectPath"){try{return HO(O,$)}catch(Z){throw new U(Z instanceof Error?Z.message:`${$} is invalid`)}}function A1(O){try{P1(O)}catch($){throw new U($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function L1(O,$){return{id:O.sessionId,projectPath:O.projectPath,title:O.title??`Session ${O.sessionId.slice(0,6)}`,createdAt:new Date(O.firstMessageTime),updatedAt:new Date(O.lastMessageTime),rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,taskStatus:O.taskStatus,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,pendingInteraction:O.pendingInteraction,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:O.taskQueuePosition,taskQueueDepth:O.taskQueueDepth,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,taskWorktree:$,messageCount:O.messageCount}}function _4(O){return O.flatMap(($)=>{if(!L2($)||$.role==="system"||$.role==="tool"&&$.name===M1)return[];let Z=$.tool_calls?.filter((G)=>!("function"in G)||G.function.name!==M1),J=typeof $.content==="string"?$.content.trim():"";if($.role==="assistant"&&$.tool_calls?.length&&!Z?.length&&!J&&!$.reasoningContent&&!$.metadata)return[];let Y={...$,...$.tool_calls?{tool_calls:Z&&Z.length>0?Z:void 0}:{}};if($.role==="tool"){let G=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0,W=$.name??(typeof G?.toolName==="string"?G.toolName:"unknown");if(G!==void 0&&(Object.hasOwn(G,"output")||Object.hasOwn(G,"error"))){let M=T4(G),b=q4(I4(W,M),b4);return[{...Y,name:W,content:C4(b),metadata:b1(W,{...M.metadata,status:M.success?"completed":"failed"})}]}return[{...Y,name:W,metadata:b1(W,G)}]}let X=j2($.metadata);return[X?{...Y,content:A2(X)}:Y]})}function y0(O){let $=hO(O.currentRunId),Z=$?.status==="waiting_permission"?"running":$?.status==="attention_required"?"interrupted":$?.status??O.taskStatus;return{sessionId:O.id,projectPath:O.projectPath,title:O.title,rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,status:void 0,taskStatus:Z,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:Z==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:Z==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:$?.pendingPermission?{type:$.pendingPermission.details.type==="askUserQuestion"?"question":$.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:$.pendingPermission.permissionId}:O.pendingInteraction,agentType:void 0,model:void 0,messageCount:O.messageCount,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function mO(O,$){let Z=U0;if(Z?.accepting)return Z.resolveSessionRef(O,$);if(A1(O),$!==void 0){let Y=cO({sessionId:O,projectPath:q0($)}),X=await g.findSessionMetadata(Y.sessionId,Y.projectPath);if(!X)throw new l("Session",O);return cO({sessionId:X.sessionId,projectPath:X.projectPath})}let J=new Map;for(let Y of await g.listSessions()){if(Y.sessionId!==O)continue;let X=cO({sessionId:Y.sessionId,projectPath:Y.projectPath});J.set(i(X),X)}if(J.size===0)try{let Y=await g.findSessionMetadata(O);if(!Y)throw new l("Session",O);return cO({sessionId:Y.sessionId,projectPath:Y.projectPath})}catch(Y){if(Y instanceof l)throw Y;if(Y instanceof Error&&Y.message.startsWith("Ambiguous session ID:"))throw new uO;throw Y}if(J.size>1)throw new uO;return J.values().next().value}function X2(O,$){let Z=($??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(Z.length===0)return O;let J=[];if(O.trim())J.push({type:"text",text:O});return J.push(...Z),J}function V2(O,$){return $&&O instanceof G0&&(O.kind==="closed"||O.kind==="aborted")}var a2=()=>{f9();let O=new x9;O.onError((Q,w)=>{if(Q instanceof t0){let V=new rO("Session runtime capacity is full",{resource:Q.resource,limit:Q.limit});return w.json(V.toObject(),429)}if(Q instanceof Q0){let V=new rO("Session projection capacity is full",{resource:Q.resource,limit:Q.limit,retryable:Q.retryable});return w.json(V.toObject(),429)}if(Q instanceof wO)return w.json(Q.toObject(),Q.statusCode);return t.error("[SessionRoutes] Unhandled route error:",Q),w.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,Z=new H4,J=new Map,Y=new Map,X=new Map,G=new Set,W=new N4,B=new N4,M=new B9,b=LO(),I=new d2({maxResident:b?.maxResidentSessionRuntimes??U2,idleMs:b?.sessionRuntimeIdleMs??F2}),A=new w4({maxResident:b?.maxResidentSessionProjections??K2,idleMs:b?.sessionProjectionIdleMs??w2,toSnapshot:R9}),f=new U1,L=new U1,R=setInterval(()=>{I.sweepIdle().catch((Q)=>{t.warn("[SessionRoutes] Session Runtime idle sweep failed:",Q)})},_2);R.unref?.();let P=setInterval(()=>{try{A.sweepIdle()}catch(Q){t.warn("[SessionRoutes] Session projection idle sweep failed:",Q)}},H2);P.unref?.();let k,_=new Map,e=1,u,FO=(Q)=>{let w=Q.projectionLease;Q.projectionLease=void 0,w?.release()},y=()=>{for(let Q of _.values()){if(Q.timer)clearTimeout(Q.timer);FO(Q)}_.clear()};j1=y;let SO=async(Q,w)=>{let V;try{V=f.enter(w)}catch{throw new MO}try{return await Q(V.signal)}finally{V.release()}};O.use("*",async(Q,w)=>{if(Q.req.method==="GET"||Q.req.method==="HEAD")return w();return SO((V)=>{return Q.set("requestSignal",V),w()},Q.req.raw.signal)});let XO=(Q,w)=>W.runExclusive(i(Q),w),d=(Q,w)=>{let V=i(Q),K=_.get(V);if(!K||w!==void 0&&K.generation!==w)return;if(K.timer)clearTimeout(K.timer);FO(K),_.delete(V)},n=(Q,w)=>{let V=_.get(i(YO(Q)));return V?.generation===w.generation&&V.attempt===w.attempt&&V.inFlight&&!V.terminal},_O=(Q,w)=>{let V=i(YO(Q)),K=_.get(V);if(K){if(w?.release(),K.inFlight||K.timer||K.terminal)return}else{if(!w)throw new MO;K={attempt:0,generation:e++,inFlight:!1,projectedInputIds:new Set,projectionLease:w,startedAt:Date.now(),terminal:!1,timer:void 0},_.set(V,K)}return K.inFlight=!0,K.attempt++,{attempt:K.attempt,deadlineAt:K.startedAt+l2,generation:K.generation,projectedInputIds:K.projectedInputIds}},CO=(Q,w,V,K,H)=>{m.publish(Q,"pending.resume",{phase:w,kind:"pending_input",attempt:V,maxAttempts:c2,...H===void 0?{}:{delayMs:H,nextRetryAt:Date.now()+H},...K?{failure:{code:K.code,retryable:K.retryable,...K.resource?{resource:K.resource}:{}}}:{}})},PO=(Q,w,V,K,H,N)=>{let F=YO(Q),D=i(F),j=_.get(D);if(!j||j.generation!==w.generation)return!1;if(N)return j.inFlight=!1,j.terminal=!0,FO(j),CO(F,"exhausted",w.attempt,V.taskFailure),!1;let x=i2({sessionIdentity:D,failedAttempt:w.attempt,recoveryStartedAt:j.startedAt,workStillPending:K,evidence:V});if(x.phase!=="retry_scheduled")return j.inFlight=!1,j.terminal=!0,FO(j),CO(F,x.phase,w.attempt,V.taskFailure),!1;if(!j.projectionLease)return!1;let C=setTimeout(()=>{(async()=>{if(await H.completion,_.get(D)!==j||j.timer!==C)return;await XO(F,async()=>{if(_.get(D)!==j||j.timer!==C)return;j.timer=void 0,j.inFlight=!1;let q=_O(Q);if(!q)return;try{await u(Q,q)}catch(E){if(_.get(D)!==j)return;let v=T0(E);j.inFlight=!1,j.terminal=!0;try{let BO=new Date().toISOString(),AO;try{AO=await g.updateSessionMetadata(Q.id,Q.projectPath,{taskStatus:"failed",taskStatusReason:v.message,taskFailure:v,taskCompletedAt:BO,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null})}catch{t.error(`[SessionRoutes] Failed to persist terminal pending input state for ${Q.id}`)}if(_.get(D)!==j||!j.terminal)return;if(Q.taskStatus="failed",Q.taskStatusReason=v.message,Q.taskFailure=v,Q.taskCompletedAt=BO,AO)O0(Q,AO);CO(F,"failed",q.attempt,v),m.publish(F,"session.error",{error:v.message,taskFailure:v}),m.publish(F,"session.status",{status:"error"})}finally{FO(j)}}})})().catch((q)=>{t.error(`[SessionRoutes] Failed to retry pending input for ${Q.id}:`,q)})},x.delayMs);return C.unref?.(),j.timer=C,j.inFlight=!1,CO(F,"retry_scheduled",w.attempt+1,V.taskFailure,x.delayMs),!0},RO=(Q,w)=>{let V=YO(Q),K=_.get(i(V));if(!K||K.generation!==w.generation)return!1;if(w.attempt>1)CO(V,"recovered",w.attempt);return d(V,w.generation),!0},Z0=(Q,w)=>B.runExclusive(i(Q),w),tO=(Q)=>U4().some((w)=>w.sessionId===Q.sessionId&&w.projectPath===Q.projectPath&&yO(w)),vO=async(Q,w,V)=>{let K=Y.get(w);if(!K)K=(async()=>{if($.get(w)===V)$.delete(w);for(let[N,F]of $)if(F===V)$.delete(N);let H=YO(Q);if(V0(H)?.id===Q.id&&!tO(H)&&!B0.has(w)&&!X0.has(w))await $4(H,"route-reset").catch(()=>{return});if(await V.dispose(),$.size===0)await dO.getInstance().disconnectAll()})().finally(()=>{if(Y.get(w)===K)Y.delete(w)}),Y.set(w,K);await K},T=(Q,w={})=>{let V=w.communicationStyle??Q.communicationStyle;return{sessionId:Q.id,workspaceRoot:Q.projectPath,permissionMode:w.permissionMode??Q.permissionMode??"default",...Q.reasoningEffort?{reasoningEffort:Q.reasoningEffort}:{},...Q.serviceTier?{serviceTier:Q.serviceTier}:{},...Q.responseVerbosity?{responseVerbosity:Q.responseVerbosity}:{},...V?{communicationStyle:V}:{},...V===Q.communicationStyle&&Q.communicationStyleDigest?{communicationStyleDigest:Q.communicationStyleDigest}:{},...Q.projectInstructionsDigest?{projectInstructionsDigest:Q.projectInstructionsDigest}:{},...Q.taskWorktree?{taskWorktree:Q.taskWorktree}:{},...Q.taskIsolation?{taskIsolation:Q.taskIsolation}:{},...Q.messageCount>0?{sessionStart:{isResume:!0,resumeSessionId:Q.id}}:{}}},JO=async(Q,w={})=>{let V=YO(Q),K=i(V);await Y.get(K);let H=I.acquire(K);if(H){if($.get(K)!==H.value)throw H.release(),Error("Session Runtime residency identity is inconsistent");return H}if(I.owns(K))throw new t0(I.getStats().maxResident);let N=J.get(K);if(!N)N=(async()=>{let F=await I.reserve(K,{surface:"web",allowEviction:!0}),D;try{D=await N0.create(T(Q,w));let j=D.getCurrentModelId();if(j&&(Q.selectedModelId||Q.taskModelId)&&j!==Q.selectedModelId){let q=await g.updateSessionMetadata(Q.id,Q.projectPath,{selectedModelId:j}).catch((E)=>{t.warn(`[SessionRoutes] Failed to migrate restored model for ${Q.id}:`,E);return});if(q)Q.selectedModelId=q.selectedModelId,Q.updatedAt=new Date(q.lastMessageTime)}let x=D,C=F.commit({key:K,surface:"web",value:x,canEvict:()=>!tO(V)&&!B0.has(K)&&!X0.has(K)&&!J.has(K)&&!Y.has(K)&&x.isIdleForResidency(),dispose:()=>vO(Q,K,x)});return D=void 0,$.set(K,x),{runtime:x,claimLease:()=>{if(C){let E=C;return C=void 0,E}let q=I.acquire(K);if(!q||q.value!==x)throw Error("Initialized Session Runtime lost residency");return q}}}catch(j){if(F.cancel(),D)await D.dispose().catch((x)=>{t.warn(`[SessionRoutes] Failed to dispose uncommitted Runtime for ${Q.id}:`,x)});if(j instanceof A4)throw new j0(j.reason);throw j}})(),J.set(K,N);try{return(await N).claimLease()}finally{if(J.get(K)===N)J.delete(K)}},NO=async(Q,w,V={})=>{let K=await JO(Q,V);try{return await w(K.value)}finally{K.release()}},C1=(Q)=>{if(Q instanceof j0||Q instanceof wO)return Q;if(Q instanceof A4)return new j0(Q.reason);if(Q instanceof D2)return new p(Q.message);if(Q instanceof Error&&"code"in Q&&(Q.code==="ENOENT"||Q.code==="ENOTDIR"))return new j0("workspace_missing");return Q instanceof Error?Q:Error(String(Q))},z1=(Q)=>{if(Q.taskIsolation!=="worktree"||Q.taskWorktree)return;if(!Q.taskSourceProjectPath)throw new j0("task_source_project_missing");return q0(Q.taskSourceProjectPath)},R1=async(Q,w)=>{let V=YO(Q),K=i(V),H=z1(Q);if(!H||$.has(K)||J.has(K))try{return await NO(Q,w)}catch(D){throw C1(D)}let N=LO();if(!N)throw new MO("Configuration is not initialized");let F;try{let[D,j]=await Promise.all([x1(H,N),eO(H)]);return F=await N0.create({...T(Q),workspace:P2(H),modelResources:D,agentResources:x2(j),lspResources:{projectRoot:H,servers:{}},auxiliaryReadOnly:!0}),await w(F)}catch(D){throw C1(D)}finally{await F?.dispose()}},G1=async(Q)=>{let w=i(YO(Q));if(!$.has(w)&&!J.has(w)&&!await N0.hasDurableFollowUpInbox(Q.projectPath,Q.id))return S2();return NO(Q,(V)=>V.getFollowUpQueueSnapshot())},d0=async(Q,w)=>{let V=i(YO(Q)),K=J.get(V);if(K)await K.catch(()=>{return});J.delete(V);let H=w??$.get(V);if(!H)return;if(!await I.remove(V,H))throw Error(`Session Runtime is pinned and cannot be disposed: ${V}`)},e1=(Q,w)=>{if(w==="delete")throw new l("Session",Q.sessionId);if(w==="archive")throw new p("Session is archived");throw new MO},c0=(Q,w,V)=>{if(V.invalidatedBy)e1(Q,V.invalidatedBy);if(X.get(w)!==V)throw new MO},O4=(Q,w)=>{let V=i(Q),K=X.get(V);if(!K)return;if(K.invalidatedBy??=w,K.cancelReservation?.(),K.cancelReservation=void 0,X.get(V)===K)X.delete(V)},J$=(Q)=>{for(let w of G)w.invalidatedBy??=Q,w.cancelReservation?.(),w.cancelReservation=void 0;X.clear()},V0=(Q)=>A.snapshot(i(Q)),E1=()=>A.snapshotAll(),$4=async(Q,w)=>{O4(Q,w);let V=i(Q);if(!V0(Q))return;let K=A.beginCloseMany([V],w);await K.waitForIdle({deadlineAt:Date.now()+W2}),K.commit()},b5=async(Q,w)=>{if(w!==void 0)return A1(Q),cO({sessionId:Q,projectPath:q0(w)});return Z4(Q,w)},Z4=async(Q,w)=>{if(A1(Q),w!==void 0){let K=cO({sessionId:Q,projectPath:q0(w)});if(V0(K))return K;let H=await g.findSessionMetadata(K.sessionId,K.projectPath);if(!H)throw new l("Session",Q);return cO({sessionId:H.sessionId,projectPath:H.projectPath})}let V=new Map;for(let K of E1()){if(K.id!==Q)continue;let H=YO(K);V.set(i(H),H)}for(let K of await g.listSessions()){if(K.sessionId!==Q)continue;let H=cO({sessionId:K.sessionId,projectPath:K.projectPath});V.set(i(H),H)}if(V.size===0)try{let K=await g.findSessionMetadata(Q);if(!K)throw new l("Session",Q);return cO({sessionId:K.sessionId,projectPath:K.projectPath})}catch(K){if(K instanceof l)throw K;if(K instanceof Error&&K.message.startsWith("Ambiguous session ID:"))throw new uO;throw K}if(V.size>1)throw new uO;return V.values().next().value},A0=async(Q)=>{let w=U0;if(!w?.accepting||w.acquireOrHydrateSession!==A0)throw new MO;let V=i(Q),K=A.acquire(V);if(K)return K;let H=X.get(V);if(!H){let F;F={promise:Promise.resolve().then(async()=>{let j=A.acquire(V);if(j){j.release();return}c0(Q,V,F);let x=A.reserve(V);F.cancelReservation=()=>x.cancel();try{let C=await g.findSessionMetadata(Q.sessionId,Q.projectPath);if(c0(Q,V,F),!C)throw new l("Session",Q.sessionId);let q=await g.findSessionTaskWorktree(Q.sessionId,Q.projectPath);c0(Q,V,F);let E=L1(C,q);c0(Q,V,F);let v=x.commit(E);F.cancelReservation=void 0,v.release()}catch(C){throw F.cancelReservation?.(),F.cancelReservation=void 0,C}})},H=F,X.set(V,H),G.add(H)}try{await H.promise}finally{if(G.delete(H),X.get(V)===H)X.delete(V)}let N=A.acquire(V);if(!N)throw new MO;return N},T5=async(Q,w)=>{let V=await A0(Q);try{return await w(V.value)}finally{V.release()}},f1=async(Q,w)=>{let V=await Z4(Q,w);try{await g.assertSessionWritable(V.sessionId,V.projectPath)}catch(K){if(K instanceof D4)throw new p(K.message);throw K}return A0(V)},f0=(Q)=>{let w=A.acquire(Q.key);if(!w||w.generation!==Q.generation)throw w?.release(),new MO;return w},Q$=async(Q)=>{let w=await A0(Q);try{return f0(w)}finally{w.release()}},iO=async(Q,w,V)=>{let K=await f1(Q,w);try{let H=K.value;return await V(H,YO(H),K)}finally{K.release()}},q5=async(Q,w)=>{let V=await f1(Q.sessionId,Q.projectPath);try{return await w(V.value,V)}finally{V.release()}},Y$=async(Q,w)=>{if(Q.permissionMode===w)return;let V=await g.setSessionPermissionMode(Q.id,Q.projectPath,w);Q.permissionMode=V.permissionMode,Q.updatedAt=new Date(V.lastMessageTime),m.publish(YO(Q),"session.updated",{permissionMode:w})},K1=(Q,w,V,K)=>{if(!f.stats().accepting)throw new MO;let H=Y2(12),N={id:H,sessionId:Q.id,projectPath:Q.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:Q.taskIsolation!==void 0&&K.runtimeLease!==void 0,pendingResume:K.pendingResume,projectionLease:K.projectionLease,createdAt:new Date};if(Q.taskIsolation&&K.runtimeLease){let F=K.runtimeLease.value,D=_0.admit({key:`${Q.projectPath}\x00${Q.id}`,...F.getTaskAdmissionLimits(),pendingBytes:k2({content:w,outputSchema:K.outputSchema,pendingMessages:F.getPendingSteeringMessages()}),signal:N.abortController.signal,onUpdate:(x)=>{N.status=x.state,Q.taskStatus=x.state,Q.taskQueuePosition=x.queuePosition,Q.taskQueueDepth=x.queueDepth,Q.taskConcurrencyLimit=x.maxConcurrent,N.taskAdmissionUpdate=(N.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await F.setTaskAdmission(x)}).catch((C)=>{t.warn(`[SessionRoutes] Failed to persist admission for ${Q.id}:`,C)})}});N.taskAdmission=D;let j=D.getSnapshot();N.status=j.state,Q.taskStatus=j.state,Q.taskQueuePosition=j.queuePosition,Q.taskQueueDepth=j.queueDepth,Q.taskConcurrencyLimit=j.maxConcurrent}return o$(N),Q.currentRunId=H,N.completion=Q2(N,Q,w,V,JO,{pendingInputOnly:K.pendingInputOnly,preparedInputTurn:K.preparedInputTurn,goalContinuationOnly:K.goalContinuationOnly,outputSchema:K.outputSchema,taskAdmission:N.taskAdmission,runtimeLease:K.runtimeLease,projectionLease:K.projectionLease,disposeRuntime:d0,pendingResume:K.pendingResume,onPendingResumeFailure:(F,D,j,x)=>PO(Q,F,D,j,N,x),onPendingResumeSuccess:(F)=>RO(Q,F),onPendingResumeCancelled:(F)=>d(YO(Q),F.generation)}).catch((F)=>{t.error(`[SessionRoutes] Run ${H} failed:`,F)}),N},I5=async(Q)=>{let w;if(Q.outputSchema)try{w=x4(Q.outputSchema).schema}catch(c){throw new U(c instanceof Error?c.message:"Invalid output schema")}let V=c1("task",12),K=q0(Q.sourceProjectPath),H=Q.modelId?.trim(),N=LO();if(!N)throw new U("Config not initialized");let[F,D]=await Promise.all([x1(K,N),eO(K)]);if(H&&!F.config.models.some((c)=>c.id===H))throw new U(`Task model not found: ${H}`);let j=H||F.config.models.find((c)=>c.id===F.config.currentModelId)?.id||F.config.models[0]?.id;if(!j)throw new U("No model is configured. Add or select a model before dispatching a task.");let x=F.config.models.find((c)=>c.id===j);if(!x)throw new U(`Task model not found: ${j}`);let C=Q.reasoningEffort??"off",q=Q.serviceTier??"auto",E=Q.responseVerbosity??"auto",v=Q.communicationStyle??"auto",BO,AO=D.projectRules?.staticRules(K),a=AO&&AO.files.length>0?AO.provenanceSha256:void 0;try{let c=F.catalog.resolveConfig(x);N2(c,C),G2(c,q),z2(c,E);let bO=B2(v,D.communicationStyles);BO=bO.source==="built-in"?void 0:bO.contentSha256}catch(c){throw new U(c instanceof Error?c.message:"Invalid reasoning effort")}let QO={version:1,prompt:Q.prompt,...Q.title?{title:Q.title}:{},...Q.taskPriority?{taskPriority:Q.taskPriority}:{},...Q.taskKind?{taskKind:Q.taskKind}:{},...Q.taskDueAt?{taskDueAt:Q.taskDueAt}:{},sourceProjectPath:K,isolation:Q.isolation,permissionMode:Q.permissionMode,modelId:j,reasoningEffort:C,serviceTier:q,responseVerbosity:E,communicationStyle:v,...BO?{communicationStyleDigest:BO}:{},...a?{projectInstructionsDigest:a}:{},...Q.attachments?{attachments:Q.attachments.map((c)=>({...c}))}:{},...w?{outputSchema:w}:{}},J0,o,WO,UO,jO,r;try{let c=await M.runExclusive(async()=>{r=i(cO({sessionId:V,projectPath:K})),jO=A.reserve(r);try{return await h2.createSessionTask({sessionId:V,prompt:Q.prompt,title:Q.title,taskPriority:Q.taskPriority,taskKind:Q.taskKind,taskDueAt:Q.taskDueAt,sourceProjectPath:K,isolation:Q.isolation,dispatch:QO,retriedFrom:Q.retriedFrom})}catch(sO){throw jO?.cancel(),jO=void 0,sO}}),{metadata:bO}=c;if(J0=c.taskWorktree,o=L1(bO,J0),!jO)throw new MO;let xO=i(YO(o));if(r!==xO)jO.cancel(),jO=A.reserve(xO),r=xO;UO=jO.commit(o),jO=void 0,r=void 0;let S=YO(o);m.publish(S,"task.status",{taskStatus:bO.taskStatus,updatedAt:bO.lastMessageTime});let pO=X2(Q.prompt,Q.attachments);WO=await JO(o);let nO=WO.value,OO=w?await nO.prepareInputTurn(pO,{outputSchema:w}):await nO.prepareInputTurn(pO);if(!OO.accepted)throw new p(`Task prompt was not accepted: ${OO.reason}`);if(!UO)throw new MO;let VO=K1(o,pO,Q.permissionMode,{preparedInputTurn:OO,runtimeLease:WO,projectionLease:UO,outputSchema:w});return UO=void 0,WO=void 0,await VO.taskAdmissionUpdate,{session:y0(o),runId:VO.id,messageId:OO.messageId,status:VO.status==="queued"?"queued":"running",queuePosition:o.taskQueuePosition,queueDepth:o.taskQueueDepth,maxConcurrentTasks:o.taskConcurrencyLimit}}catch(c){if(jO?.cancel(),jO=void 0,r=void 0,UO?.release(),UO=void 0,WO?.release(),WO=void 0,c instanceof Q0&&!o)throw new rO("Session projection capacity is full",{resource:c.resource,limit:c.limit,retryable:c.retryable});if((c instanceof j4||c instanceof t0||c instanceof Q0)&&o){if(J0)await W0.exit({sessionId:o.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await d0(o).catch(()=>{return}),await g.deleteSession(o.id,o.projectPath).catch(()=>{return}),new rO(c instanceof Q0?"Session projection capacity is full":c instanceof t0?"Session runtime capacity is full":"Task admission capacity is full",{resource:c.resource,limit:c.limit,...c instanceof Q0?{retryable:c.retryable}:{}})}if(o){let bO=await g.findSessionMetadata(o.id,o.projectPath).catch(()=>{return});if(!bO||bO.taskStatus==="queued"){let xO=T0(c),S=await g.updateSessionMetadata(o.id,o.projectPath,{taskStatus:"failed",taskStatusReason:xO.message,taskFailure:xO,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});o.taskStatus=S?.taskStatus??"failed",o.taskStatusReason=S?.taskStatusReason??xO.message,o.taskFailure=S?.taskFailure??xO,o.taskCompletedAt=S?.taskCompletedAt}else o.taskStatus=bO.taskStatus,o.taskStatusReason=bO.taskStatusReason,o.taskFailure=bO.taskFailure,o.taskCompletedAt=bO.taskCompletedAt}throw c}},X$=(Q)=>SO(()=>I5(Q)),C5=async(Q,w)=>{let V=await mO(Q,w),K=await g.findSessionMetadata(V.sessionId,V.projectPath);if(!K)throw new l("Session",V.sessionId);if(!["failed","interrupted","cancelled"].includes(K.taskStatus))throw new p(`Task cannot be retried while status is ${K.taskStatus}`);let H=await g.findSessionTaskDispatch(V.sessionId,V.projectPath);if(!H)throw new p("Task retry payload is unavailable");return X$({prompt:H.prompt,title:K.title??H.title,taskPriority:K.taskPriority??H.taskPriority,taskKind:K.taskKind??H.taskKind,taskDueAt:K.taskDueAt,sourceProjectPath:H.sourceProjectPath,isolation:H.isolation,permissionMode:H.permissionMode,modelId:H.modelId,reasoningEffort:H.reasoningEffort,serviceTier:H.serviceTier,responseVerbosity:H.responseVerbosity,communicationStyle:H.communicationStyle,attachments:H.attachments,outputSchema:H.outputSchema,retriedFrom:V})},R5=(Q,w)=>SO(()=>C5(Q,w)),E5=(Q,w,V)=>SO(async()=>{let K=await mO(Q,V);if(!await g.findSessionMetadata(K.sessionId,K.projectPath))throw new l("Session",K.sessionId);let N=await g.updateSessionMetadata(K.sessionId,K.projectPath,w),F=V0(K);if(F)O0(F,N);return m.publish(K,"session.updated",{...N.title?{title:N.title}:{},...N.taskPriority?{taskPriority:N.taskPriority}:{},...N.taskKind?{taskKind:N.taskKind}:{},taskDueAt:N.taskDueAt??null}),F?y0(F):{...N,isActive:!1}}),f5=async(Q,w)=>{return iO(Q,w,async(V)=>{if(!V.taskWorktree)throw new U("Session does not have a task worktree");try{await W0.restoreSession(V.taskWorktree);let K=await W0.getDiffArtifact(V.id);if(!K)throw new p("Task diff artifact is unavailable");return{sessionId:V.id,projectPath:V.projectPath,...K}}catch(K){if(K instanceof p)throw K;throw t.error("[SessionRoutes] Failed to load task diff artifact:",K),new p("Task diff artifact is unavailable")}})},S5=async(Q,w,V)=>{let K=await mO(Q,V);return Z0(K,async()=>{return q5(K,async(H)=>{if(["queued","running"].includes(H.taskStatus))throw new p(`Task artifacts cannot be delivered while status is ${H.taskStatus}`);if(H.taskDelivery?.status==="applied")throw new p("Task changes have already been applied");if(H.taskDelivery?.status==="discarded")throw new p("Task changes have already been discarded");if(!H.taskWorktree)throw new p("Task worktree is unavailable");let N=async(F,D=!1)=>{let j=await g.updateSessionMetadata(H.id,H.projectPath,{taskDelivery:F,...D?{taskWorktree:null}:{}});if(O0(H,j),D)H.taskWorktree=void 0;return m.publish(K,"task.delivery",{taskDelivery:F,...D?{taskWorktreeRemoved:!0}:{},updatedAt:j.lastMessageTime}),y0(H)};try{if(w==="discard"){try{await W0.restoreSession(H.taskWorktree)}catch(j){return t.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${H.id}:`,j),N({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:H.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let D=await W0.exit({sessionId:H.id,action:"remove",discardChanges:!0});return N({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:D.discardedFiles??0,message:"Task worktree removed"},!0)}try{await W0.restoreSession(H.taskWorktree)}catch(D){throw t.warn(`[SessionRoutes] Task worktree is unavailable for ${H.id}:`,D),new L4("artifact_unavailable","Task worktree is unavailable")}let F=await W0.apply(H.id);return N({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:F.sourceCommit,changedFiles:F.changedFiles,message:"Task changes applied to the source workspace"})}catch(F){if(F instanceof L4)throw await N({status:"conflicted",updatedAt:new Date().toISOString(),message:F.message}),new p(F.message);throw F}})})},P5=(Q,w,V)=>SO(()=>S5(Q,w,V)),V$=async(Q,w)=>{let V=YO(Q),K=i(V),H=_.get(K);if(!w&&H?.terminal)return;let N=hO(Q.currentRunId);if(yO(N)){if(w)d(YO(Q),w.generation);return}let F=Q.taskIsolation&&Q.taskStatus!=="queued"&&Q.taskStatus!=="running",D=F?await N0.hasRecoverableTurn(Q.projectPath,Q.id):!1;if(F&&!D){if(w)d(YO(Q),w.generation);return}let j=await N0.hasPendingInbox(Q.projectPath,Q.id),x=!j&&await N0.hasActiveGoal(Q.projectPath,Q.id);if(!j&&!x&&!D)D=await N0.hasRecoverableTurn(Q.projectPath,Q.id);if(!j&&!x&&!D){d(YO(Q));return}if(w&&!j){d(YO(Q),w.generation);return}let C=await JO(Q),q=!1,E,v;try{let BO=C.value,AO=hO(Q.currentRunId);if(yO(AO)){if(w)d(YO(Q),w.generation);return}if(j&&BO.getPendingSteeringCount()===0)await BO.reloadPendingInbox();let a=BO.getPendingSteeringCount()>0,QO=a?null:await BO.getGoal(),J0=QO?.status==="active"||QO?.status==="verifying",o=BO.getTurnRecoveryAssessment();if(o.state!=="none"&&(o.state==="requires_attention"||!a&&!J0))m.publish({sessionId:Q.id,projectPath:Q.projectPath},"turn.recovery",{assessment:o});if(o.state==="requires_attention"||F||!a&&!J0||BO.hasTurnOwner()){if(w||!a)d(YO(Q),w?.generation);return}let WO=w;if(a&&!Q.taskIsolation&&!WO){let UO=await Q$(V);try{WO=_O(Q,UO);let jO=_.get(K);if(WO&&jO?.generation===WO.generation&&jO.projectionLease===UO)v=WO,UO=void 0}finally{UO?.release()}}if(a&&!Q.taskIsolation&&!WO)return;if(w&&!n(Q,w))return;E=w?(()=>{let UO=H?.projectionLease;if(!UO)throw new MO;return f0(UO)})():await Q$(YO(Q)),K1(Q,"",Q.permissionMode??"default",{pendingInputOnly:a,goalContinuationOnly:J0,runtimeLease:C,projectionLease:E,pendingResume:a?WO:void 0}),E=void 0,v=void 0,q=!0}finally{if(E?.release(),v)d(V,v.generation);if(!q)C.release()}};u=async(Q,w)=>{let V;try{V=f.enter()}catch{return}try{let K=hO(Q.currentRunId);if(yO(K)){if(w)d(YO(Q),w.generation);return}if(Q.taskIsolation){await V$(Q);return}await V$(Q,w)}finally{V.release()}};let J4={accepting:!0,resolveSessionRef:Z4,getProjectionSnapshot:V0,snapshotAll:E1,acquireOrHydrateSession:A0,invalidateAll:J$,resumeRecoveredInteraction:u};U0=J4;let k5=async()=>{let Q={scheduled:0,failed:0,deferred:0};if(!f.stats().accepting)return Q;let w=(await g.listSessions({taskStatus:"queued"})).filter((V)=>V.taskIsolation!==void 0).sort((V,K)=>V.firstMessageTime.localeCompare(K.firstMessageTime)||V.projectPath.localeCompare(K.projectPath)||V.sessionId.localeCompare(K.sessionId));for(let[V,K]of w.entries()){let H={sessionId:K.sessionId,projectPath:K.projectPath};try{if(!await N0.hasPendingInbox(K.projectPath,K.sessionId)){let D=T0("Queued task input is missing");await g.updateSessionMetadata(K.sessionId,K.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Q.failed++;continue}let N=await A0(H),F=N.value;if(N.release(),await u(F),F.currentRunId)Q.scheduled++}catch(N){if(N instanceof j4||N instanceof t0){Q.deferred+=w.length-V;break}t.warn(`[SessionRoutes] Failed to recover queued task ${K.sessionId}:`,N),Q.deferred++}}return Q};return O.route("/",n$({withAdmission:SO,resolveSessionRef:async(Q,w)=>{try{let V=await b5(Q,w);return(await A0(V)).release(),V}catch(V){if(V instanceof Q0)throw new rO("Session projection capacity is full",{resource:V.resource,limit:V.limit,retryable:V.retryable});throw V}},getRuntime:(Q)=>Z.get(Q),captureAgentScreenshot:async(Q,w)=>{return T5(Q,(V)=>NO(V,(K)=>K.captureBrowserScreenshot(w)))},resetRuntime:(Q)=>Z.reset(Q)})),O.get("/",async(Q)=>{try{let w=await g.listSessions(),V=new Set(w.filter((x)=>x.relationType==="subagent").map((x)=>i({sessionId:x.sessionId,projectPath:x.projectPath}))),K=E1().filter((x)=>!V.has(i(YO(x)))&&x.relationType!=="subagent").map((x)=>y0(x)),H=new Set(K.map((x)=>i({sessionId:x.sessionId,projectPath:x.projectPath}))),N=w.filter((x)=>{if(x.relationType==="subagent")return!1;return!H.has(i({sessionId:x.sessionId,projectPath:x.projectPath}))}),F=new Set(H),D=N.filter((x)=>{let C=i({sessionId:x.sessionId,projectPath:x.projectPath});if(F.has(C))return!1;return F.add(C),!0}),j=[...K,...D.map((x)=>({...x,isActive:!1}))];return Q.json(j)}catch(w){throw t.error("[SessionRoutes] Failed to list sessions:",w),new zO("Failed to list sessions")}}),O.get("/catalog",async(Q)=>{try{let w=Q.req.query("limit"),V=w===void 0?void 0:Number(w),K=Q.req.query("cursor"),H=Q.req.query("projectPath"),N=Q.req.query("archived");if(N!==void 0&&N!=="true"&&N!=="false")throw new U("archived must be true or false");let F=N==="true",D=await g.listSessionPage({...H?{cwd:q0(H)}:{},...K?{cursor:K}:{},...V===void 0?{}:{limit:V},includeSubagents:!1,archived:F}),j=new Map((F?[]:E1()).filter((x)=>x.relationType!=="subagent").map((x)=>[i(YO(x)),y0(x)]));return Q.json({sessions:D.sessions.map((x)=>j.get(i({sessionId:x.sessionId,projectPath:x.projectPath}))??x),...D.nextCursor?{nextCursor:D.nextCursor}:{}})}catch(w){if(w instanceof U)throw w;if(w instanceof Error&&(w.message.startsWith("Invalid session cursor")||w.message.startsWith("Session cursor scope")||w.message.startsWith("Session catalog")))throw new U(w.message);throw t.error("[SessionRoutes] Failed to list session catalog:",w),new zO("Failed to list session catalog")}}),O.post("/",async(Q)=>{try{let w=await Q.req.json(),V=h(M9,w);if(!V.success)throw new U("Invalid request body");let{title:K,projectPath:H}=V.data,N=c1("web",12),F=q0(H||Q.get("directory")||KO(),H?"projectPath":"directory"),D=cO({sessionId:N,projectPath:F}),j=await M.runExclusive(async()=>{let C=A.reserve(i(D));try{let q=await g.createSessionMetadata(N,F,{title:K,taskStatus:"completed"}),E=L1(q);return C.commit(E)}catch(q){throw C.cancel(),q}}),x=j.value;return j.release(),m.publish(D,"session.created",{}),Q.json({...y0(x),status:void 0,agentType:void 0,model:void 0})}catch(w){if(t.error("[SessionRoutes] Failed to create session:",w),w instanceof U||w instanceof wO||w instanceof Q0)throw w;throw new zO("Failed to create session")}}),O.get("/:sessionId/export",async(Q)=>{let w=Q.req.param("sessionId");try{let V=Q.req.query("includeReasoning");if(V!==void 0&&V!=="true"&&V!=="false")throw new U("includeReasoning must be true or false");let K=await mO(w,Q.req.query("projectPath")),H=await g.exportSessionMarkdown(K.sessionId,K.projectPath,{includeReasoning:V==="true"});return Q.body(H.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${H.filename}"`,"Content-Length":String(Buffer.byteLength(H.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":H.contentSha256,"X-Blade-Export-Activities":String(H.activityCount),"X-Blade-Export-Messages":String(H.messageCount),"X-Blade-Export-Redactions":String(H.redactionCount)})}catch(V){if(V instanceof U||V instanceof l||V instanceof uO)throw V;if(V instanceof Error&&V.message==="No conversation content to export")throw new p(V.message);throw t.error("[SessionRoutes] Failed to export session:",V),new zO("Failed to export session")}}),O.post("/:sessionId/fork",async(Q)=>{let w=Q.req.param("sessionId");try{A1(w);let V=await Q.req.json(),K=h(q9,V);if(!K.success)throw new U("Invalid request body");let H=q0(K.data.projectPath),N=c1("fork"),F,D=await M.runExclusive(async()=>{let C=await g.findSessionMetadata(w,H);if(!C)throw new l("Session",w);let q;try{q=A.reserve(i({sessionId:N,projectPath:C.projectPath}))}catch(E){if(!(E instanceof Q0))throw E}try{let E=await g.forkSession(w,{newSessionId:N,sourceProjectPath:C.projectPath,targetProjectPath:C.projectPath});if(q){let v=L1(E.metadata);F=q.commit(v)}return E}catch(E){throw q?.cancel(),E}}),j=L1(D.metadata),x=YO(j);return F?.release(),m.publish(x,"task.status",{taskStatus:D.metadata.taskStatus,...D.metadata.taskCompletedAt?{taskCompletedAt:D.metadata.taskCompletedAt}:{},updatedAt:D.metadata.lastMessageTime}),Q.json({session:D.metadata,messages:_4(D.messages)},201)}catch(V){if(V instanceof U||V instanceof l||V instanceof p)throw V;if(V instanceof b2)throw new p("Session has no durable creation record");throw t.error("[SessionRoutes] Failed to fork session:",V),new zO("Failed to fork session")}}),O.get("/:sessionId",async(Q)=>{let w=Q.req.param("sessionId");try{let V=await mO(w,Q.req.query("projectPath")),K=V0(V);if(K)return Q.json(y0(K));let H=await g.findSessionMetadata(V.sessionId,V.projectPath);if(!H)throw new l("Session",w);return Q.json(H)}catch(V){if(V instanceof U||V instanceof l||V instanceof uO)throw V;throw t.error("[SessionRoutes] Failed to get session:",V),new zO("Failed to get session")}}),O.patch("/:sessionId",async(Q)=>{let w=Q.req.param("sessionId");try{let V=await Q.req.json(),K=h(T9,V);if(!K.success)throw new U("Invalid request body");if(K.data.title===void 0)throw new U("title is required");let H=await mO(w,K.data.projectPath),N=await g.updateSessionMetadata(H.sessionId,H.projectPath,{title:K.data.title}),F=A.acquire(i(H));try{let D=F?.value;if(D)D.title=N.title??D.title,D.updatedAt=new Date(N.lastMessageTime)}finally{F?.release()}if(N.title)m.publish(H,"session.updated",{title:N.title});return Q.json({success:!0,title:N.title})}catch(V){if(t.error("[SessionRoutes] Failed to update session:",V),V instanceof U||V instanceof l||V instanceof uO)throw V;throw new zO("Failed to update session")}}),O.get("/:sessionId/rewind",async(Q)=>{return iO(Q.req.param("sessionId"),Q.req.query("projectPath"),(w)=>NO(w,async(V)=>Q.json({checkpoints:await V.listRewindCheckpoints()})))}),O.post("/:sessionId/rewind",async(Q)=>{let w=h(y2,await Q.req.json());if(!w.success)throw new U("Invalid rewind request");return iO(Q.req.param("sessionId"),Q.req.query("projectPath"),async(V,K,H)=>XO(K,async()=>{let N=hO(V.currentRunId);if(yO(N))throw new p("Cannot rewind while a run is active");return NO(V,async(F)=>{let D;try{D=await F.rewindSession(w.data)}catch(x){if(x instanceof Error&&x.message.startsWith("Cannot rewind while"))throw new p(x.message);throw x}await Y0(V);let j=_4(D.messages);return m.publish(K,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:j}),Q.json({...D,messages:j})})}))}),O.get("/:sessionId/review",async(Q)=>{let w=Q.req.param("sessionId"),V=await mO(w,Q.req.query("projectPath")),K=await m0.list(V.projectPath,V.sessionId);return Q.json({reviews:K.map((H)=>({...H,content:H.completion?M2(H.start,H.completion):void 0}))})}),O.post("/:sessionId/review",async(Q)=>{let w=Q.req.param("sessionId"),V=h(u2,await Q.req.json());if(!V.success)throw new U("Invalid code review request");let K=await f1(w,V.data.projectPath),H=K.value,N=YO(H),F=i(N);try{return await XO(N,async()=>{if(yO(hO(H.currentRunId)))throw new p("Cannot start a review during an active turn");if(X0.has(F))throw new p("Session already has an active review");return NO(H,async(D)=>{if(await m0.recoverInterrupted(N.projectPath,N.sessionId,D),V.data.modelId&&!D.getModelById(V.data.modelId))throw new U(`Model not found: ${V.data.modelId}`);if(V.data.modelId&&D.getCurrentModelId()!==V.data.modelId)await D.refresh({modelId:V.data.modelId});if(V.data.modelId&&H.selectedModelId!==V.data.modelId){let E=await g.updateSessionMetadata(H.id,H.projectPath,{selectedModelId:V.data.modelId});O0(H,E)}let j=new AbortController,x,C;try{x=f0(K),C=await m0.start({sessionId:N.sessionId,projectPath:N.projectPath,runtime:D,request:{kind:V.data.kind,...V.data.ref?{ref:V.data.ref}:{},...V.data.instructions?{instructions:V.data.instructions}:{}},signal:j.signal,onEvent:(E)=>{if(E.kind==="tool_start")m.publish(N,"review.tool.started",{reviewId:C?.reviewId,toolCallId:E.toolCall.id,toolName:E.toolCall.function.name});else if(E.kind==="tool_progress")m.publish(N,"review.tool.progress",{reviewId:C?.reviewId,toolCallId:E.toolCall.id,message:E.update.message.slice(0,1000)});else if(E.kind==="tool_result")m.publish(N,"review.tool.completed",{reviewId:C?.reviewId,toolCallId:E.toolCall.id,success:E.result.success})}})}catch(E){if(x?.release(),E instanceof Error&&(E.message.includes("active review")||E.message.includes("interrupted review")||E.message.includes("active turn")))throw new p(E.message);if(E instanceof Error&&(E.message.includes("review")||E.message.includes("Git")||E.message.includes("changes")||E.message.includes("ref")))throw new U(E.message);throw E}if(!C)throw new zO("Code review failed to start");await Y0(H),m.publish(N,"review.started",{reviewId:C.reviewId,kind:V.data.kind}),m.publish(N,"task.status",{taskStatus:H.taskStatus,...H.taskStatusReason?{taskStatusReason:H.taskStatusReason}:{},...H.taskStartedAt?{taskStartedAt:H.taskStartedAt}:{},...H.taskPromptSummary?{taskPromptSummary:H.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let q=C.completion.then(async(E)=>{await Y0(H),m.publish(N,"task.status",{taskStatus:H.taskStatus,...H.taskStatusReason?{taskStatusReason:H.taskStatusReason}:{},...H.taskFailure?{taskFailure:H.taskFailure}:{},...H.taskStartedAt?{taskStartedAt:H.taskStartedAt}:{},...H.taskCompletedAt?{taskCompletedAt:H.taskCompletedAt}:{},...H.taskPromptSummary?{taskPromptSummary:H.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),m.publish(N,"review.completed",{reviewId:C.reviewId,status:E.status,findings:E.findings.length})}).catch((E)=>{t.error(`[SessionRoutes] Code review ${C.reviewId} failed:`,E)}).finally(()=>{if(X0.get(F)?.reviewId===C.reviewId)X0.delete(F);x?.release()});return X0.set(F,{reviewId:C.reviewId,controller:j,completion:q,projectionLease:x}),Q.json({reviewId:C.reviewId,status:"running"},202)})})}finally{K.release()}}),O.get("/:sessionId/subagents",async(Q)=>{return iO(Q.req.param("sessionId"),Q.req.query("projectPath"),(w)=>NO(w,(V)=>Q.json({subagents:V.listSubagents().map(l1)})))}),O.post("/:sessionId/subagents/:agentId/resume",async(Q)=>{A1(Q.req.param("agentId"));let w=m2.safeParse(await Q.req.json());if(!w.success)throw new U("Invalid subagent resume request");return iO(Q.req.param("sessionId"),Q.req.query("projectPath"),async(V,K,H)=>XO(K,async()=>{let N=hO(V.currentRunId);if(yO(N))throw new p("Cannot resume a subagent while a parent run is active");return NO(V,async(F)=>{let D=!1,j,x=(q)=>{m.publish(K,"subagent.complete",{subagentSessionId:q.id,success:q.status==="completed",status:q.status,summary:q.result?.message?.slice(0,500),type:q.subagentType,verificationVerdict:q.result?.verificationVerdict,resumedFrom:q.resumedFrom,rootAgentId:q.rootAgentId,resumeDepth:q.resumeDepth})},C;try{C=F.resumeSubagent({agentId:Q.req.param("agentId"),prompt:w.data.prompt,onEvent:(q,E)=>{S9(K,E,q)},onCompleted:(q)=>{if(D)x(q);else j=q}})}catch(q){if(q instanceof Error&&(q.message.startsWith("Cannot resume")||q.message.startsWith("Subagent cannot")))throw new p(q.message);if(q instanceof Error&&q.message.startsWith("Subagent not found"))throw new l(q.message);throw q}if(m.publish(K,"subagent.start",{subagentSessionId:C.session.id,type:C.session.subagentType,description:C.session.description,resumedFrom:C.source.id,rootAgentId:C.session.rootAgentId,resumeDepth:C.session.resumeDepth}),D=!0,j)x(j);return Q.json({source:l1(C.source),session:l1(C.session)})})}))}),O.get("/:sessionId/goal",async(Q)=>{return iO(Q.req.param("sessionId"),Q.req.query("projectPath"),async(w)=>Q.json({goal:await new T2(w.projectPath,w.id).get()}))}),O.put("/:sessionId/goal",async(Q)=>{let w=h(I9,await Q.req.json());if(!w.success)throw new U("Invalid goal request");return iO(Q.req.param("sessionId"),Q.req.query("projectPath"),async(V,K,H)=>XO(K,async()=>{let N=hO(V.currentRunId);if(yO(N))return Q.json({status:"rejected",reason:"run_active"},409);let D=w.data.permissionMode??V.permissionMode??"default";if(V.permissionMode!==D)await Y$(V,D);let j=await JO(V),x=!1,C;try{let q=await j.value.createGoal(w.data);m.publish(K,"goal.updated",{goal:q}),C=f0(H);let E=K1(V,"",D,{goalContinuationOnly:!0,runtimeLease:j,projectionLease:C});return x=!0,C=void 0,await E.taskAdmissionUpdate,Q.json({status:E.status==="queued"?"queued":"running",runId:E.id,goal:q,queuePosition:V.taskQueuePosition,queueDepth:V.taskQueueDepth,maxConcurrentTasks:V.taskConcurrencyLimit},202)}finally{if(C?.release(),!x)j.release()}}))}),O.patch("/:sessionId/goal",async(Q)=>{let w=h(C9,await Q.req.json());if(!w.success)throw new U("Invalid goal update");return iO(Q.req.param("sessionId"),Q.req.query("projectPath"),async(V,K,H)=>XO(K,async()=>{let N=await JO(V),F=!1,D;try{let j=N.value,x;if(w.data.action==="pause")x=await j.pauseGoal();else if(w.data.action==="edit")x=await j.editGoal(w.data.objective);else x=await j.resumeGoal();if(m.publish(K,"goal.updated",{goal:x}),x.status==="active"&&!yO(hO(V.currentRunId))){D=f0(H);let C=K1(V,"","default",{goalContinuationOnly:!0,runtimeLease:N,projectionLease:D});return F=!0,D=void 0,await C.taskAdmissionUpdate,Q.json({status:C.status==="queued"?"queued":"running",runId:C.id,goal:x,queuePosition:V.taskQueuePosition,queueDepth:V.taskQueueDepth,maxConcurrentTasks:V.taskConcurrencyLimit},202)}return Q.json({status:x.status,goal:x})}finally{if(D?.release(),!F)N.release()}}))}),O.delete("/:sessionId/goal",async(Q)=>{return iO(Q.req.param("sessionId"),Q.req.query("projectPath"),(w,V)=>NO(w,async(K)=>{let H=await K.clearGoal();if(H)m.publish(V,"goal.cleared",{});return Q.json({cleared:H})}))}),O.post("/:sessionId/archive",async(Q)=>{let w=Q.req.param("sessionId");try{let V=await mO(w,Q.req.query("projectPath")),K=await g.listSessionArchiveMembers(V.sessionId,V.projectPath);for(let N of K){let F=cO({sessionId:N.sessionId,projectPath:N.projectPath}),D=V0(F);if(yO(hO(D?.currentRunId)))throw new p(`Stop session ${N.sessionId} before archiving this session tree`)}for(let N of K){let F=cO({sessionId:N.sessionId,projectPath:N.projectPath}),D=V0(F);if(D)await d0(D)}let H=await g.archiveSession(V.sessionId,V.projectPath);for(let N of K){let F=cO({sessionId:N.sessionId,projectPath:N.projectPath}),D=i(F);O4(F,"archive"),await $4(F,"archive").catch(()=>{return}),J.delete(D),m.publish(F,"session.archived",{archiveRootId:V.sessionId,archivedAt:H.archivedAt})}if($.size===0)await dO.getInstance().disconnectAll();return Q.json({session:H,archivedSessionIds:K.map((N)=>N.sessionId)})}catch(V){if(V instanceof U||V instanceof l||V instanceof uO||V instanceof p)throw V;if(V instanceof M4)throw new p(V.message);throw t.error("[SessionRoutes] Failed to archive session:",V),new zO("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Q)=>{let w=Q.req.param("sessionId");try{let V=await mO(w,Q.req.query("projectPath")),K=await g.listSessionArchiveMembers(V.sessionId,V.projectPath),H=await g.unarchiveSession(V.sessionId,V.projectPath),N=K.filter((F)=>F.sessionId===V.sessionId||F.archivedBySessionId===V.sessionId).map((F)=>F.sessionId);for(let F of N)m.publish({sessionId:F,projectPath:V.projectPath},"session.unarchived",{archiveRootId:V.sessionId});return Q.json({session:H,restoredSessionIds:N})}catch(V){if(V instanceof U||V instanceof l||V instanceof uO)throw V;if(V instanceof M4)throw new p(V.message);throw t.error("[SessionRoutes] Failed to unarchive session:",V),new zO("Failed to unarchive session")}}),O.delete("/:sessionId",async(Q)=>{let w=Q.req.param("sessionId"),V=Q.req.query("projectPath");try{let K=await mO(w,V);d(K);let H=i(K),N=A.acquire(H),F=N?.value,D=F?.currentRunId,j=$.get(H),x=F?.taskWorktree??await g.findSessionTaskWorktree(K.sessionId,K.projectPath);N?.release();let C;if(D){let v=hO(D);if(v)h0(v),await v.completion,C=v.id}let q=X0.get(H);if(q)q.controller.abort("session-delete"),await q.completion;if(j)await j.clearGoal().catch((v)=>{t.warn("[SessionRoutes] Failed to clear session goal:",v)});if(await Z.dispose(K),await g.deleteSession(K.sessionId,K.projectPath),O4(K,"delete"),C)s$(C);await $4(K,"delete").catch(()=>{return}),J.delete(H),m.publish(K,"session.deleted",{});let E=$.get(H);if(E){if(!await I.remove(H,E))throw new p("Session Runtime is still active and cannot be deleted")}if(x)try{await W0.restoreSession(x),await W0.exit({sessionId:K.sessionId,action:"remove",discardChanges:!0})}catch(v){t.warn(`[SessionRoutes] Failed to remove deleted task worktree ${K.sessionId}:`,v)}return Q.json({success:!0})}catch(K){if(t.error("[SessionRoutes] Failed to delete session:",K),K instanceof U||K instanceof l||K instanceof uO)throw K;throw new zO("Failed to delete session")}}),O.get("/:sessionId/message",async(Q)=>{let w=Q.req.param("sessionId");try{let V=await mO(w,Q.req.query("projectPath")),K=await g.loadSession(V.sessionId,V.projectPath);return Q.json(_4(K))}catch(V){if(t.error("[SessionRoutes] Failed to get messages:",V),V instanceof U||V instanceof l||V instanceof uO)throw V;throw new zO("Failed to get messages")}}),O.get("/:sessionId/follow-ups",async(Q)=>{return iO(Q.req.param("sessionId"),Q.req.query("projectPath"),(w,V)=>XO(V,async()=>Q.json(await G1(w))))}),O.post("/:sessionId/follow-ups/mutate",async(Q)=>{let w=A9.safeParse(await Q.req.json());if(!w.success)throw new U("Invalid follow-up queue mutation");return iO(Q.req.param("sessionId"),w.data.projectPath??Q.req.query("projectPath"),(V,K)=>XO(K,async()=>{try{return await NO(V,async(H)=>{let N={expectedVersion:w.data.expectedVersion,operation:w.data.operation},F=await H.mutateFollowUpQueue(N);if(F.snapshot.version!==N.expectedVersion)m.publish(K,"follow_up.queue.changed",{queue:F.snapshot});return Q.json(F)})}catch(H){if(!b9(H))throw H;let N=H.code==="not_found"?404:H.code==="invalid_mutation"?400:H.code==="storage_unavailable"||H.code==="runtime_unavailable"?503:409;return Q.json({error:{code:H.code,message:H.message},snapshot:H.snapshot},N)}}))}),O.get("/:sessionId/events",async(Q)=>{let w=Q.req.param("sessionId"),V;try{V=L.enter(Q.req.raw.signal)}catch{throw new MO}let K=!1;try{let H=await mO(w,Q.req.query("projectPath"));try{await g.assertSessionWritable(H.sessionId,H.projectPath)}catch(q){if(q instanceof D4)throw new p(q.message);throw q}let N=await A0(H),F=N.value,D=Q.req.header("Last-Event-ID")??Q.req.query("lastEventId"),j=D?Number.parseInt(D,10):Number.NaN,x=Number.isInteger(j)?j+1:void 0,C=D9(Q,async(q)=>{let v=new Set,BO,AO,a=!1,QO,J0,o=new Promise((S)=>{J0=S}),WO,UO=new Set,jO=(S)=>{let pO=S;return v.add(pO),S.finally(()=>{v.delete(pO)})},r=()=>{if(BO?.(),BO=void 0,AO!==void 0)clearInterval(AO),AO=void 0},c=(S)=>{if(WO)return WO;return a=!0,WO=(async()=>{try{r(),QO?.close(S),q.close()}finally{J0()}})(),WO},bO=()=>{c(V.signal.reason)},xO=async(S)=>{await c(S),await Promise.allSettled([...v]),V.signal.removeEventListener("abort",bO),V.release()};if(V.signal.addEventListener("abort",bO,{once:!0}),q.onAbort(()=>{c()}),V.signal.aborted){await xO(V.signal.reason);return}QO=new H1({write:async(S)=>{await q.writeSSE(S)},onFailure:(S)=>{if(V2(S,a))return;t.warn(`[SessionRoutes] SSE egress closed for ${H.sessionId}: kind=${S.kind} pendingItems=${S.pendingItems??0} pendingBytes=${S.pendingBytes??0}`),c(S)}}),BO=m.subscribe((S)=>{if(a)return;if(S.sessionId!==H.sessionId||S.projectPath!==H.projectPath)return;let pO=S.properties.requestId;if((S.type==="permission.asked"||S.type==="question.required"||S.type==="elicitation.required")&&typeof pO==="string"){if(UO.has(pO))return;UO.add(pO)}if(S.type==="subagent.completion.queued"){let OO=XO(H,()=>u(F)).catch((VO)=>{t.error(`[SessionRoutes] Failed to wake background completion for ${F.id}:`,VO)});jO(OO)}if(S.type==="team.message.received"&&typeof S.properties.teamName==="string"&&typeof S.properties.messageId==="string"&&typeof S.properties.content==="string"&&C2(S.properties.metadata,{messageId:S.properties.messageId,teamName:S.properties.teamName})){let OO=S.properties.teamName,VO=S.properties.messageId,sO=S.properties.content,TO=S.properties.metadata,DO=XO(H,async()=>{let qO=await JO(F),S0=!1;try{let z0=await qO.value.enqueueSteering(sO,{allowBeforeTurn:!0,messageId:VO,origin:"team_message",metadata:TO});if(!z0.accepted)return;if(z0.queue&&!z0.duplicate)m.publish(H,"follow_up.queue.changed",{queue:z0.queue});await new I2(OO,i1()).markDelivered([VO]),S0=z0.delivery==="next_turn"}finally{qO.release()}if(!S0)return;await u(F).catch((z0)=>{t.error(`[SessionRoutes] Failed to wake teammate delivery for ${F.id}:`,z0)})}).catch((qO)=>{t.error(`[SessionRoutes] Failed to deliver teammate message for ${F.id}:`,qO)});jO(DO)}if(S.type==="subagent.completion.queued"||S.type==="team.message.received")return;let nO=E9(S);if(nO)QO?.observe(nO,S.seq)});try{if(q.aborted||a)return;let S=hO(F.currentRunId),pO=await XO(H,()=>G1(F)),nO=yO(S)?await JO(F):void 0;try{let TO=nO?.value,DO=TO?.getPendingSteeringCount()??0;await QO.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:H.sessionId,projectPath:H.projectPath,timestamp:Date.now(),status:yO(S)?S.status:"idle",runId:yO(S)?S.id:void 0,queued:DO,pendingInputDelivery:DO>0?TO?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:TO?.getRecoveredSteeringCount()??0,followUpQueue:pO,providerRecovery:TO?.getProviderRecoveryProjection()??null,turnActivity:TO?.getTurnActivityProjection()??null}})})}finally{nO?.release()}if(q.aborted||a)return;if(x!==void 0){if(await q2.for(H.sessionId,H.projectPath).replay({onCommitted:async(DO)=>{if(q.aborted||a)return;let qO=n2(DO);if(!qO||qO.seq===void 0)return;await QO.writeReplay({...typeof DO.seq==="number"?{id:String(DO.seq)}:{},data:JSON.stringify({type:qO.type,...qO.seq!==void 0?{seq:qO.seq}:{},properties:{...qO.properties,sessionId:H.sessionId,projectPath:H.projectPath}})},qO.seq)}},x),q.aborted||a)return}if(QO.finishInitialization({replayed:x!==void 0}),q.aborted||a)return;if(!S&&!X0.has(i(H))){let DO=(await m0.list(H.projectPath,H.sessionId)).some((qO)=>qO.completion===void 0)?await NO(F,(qO)=>m0.recoverInterrupted(H.projectPath,H.sessionId,qO)):void 0;if(DO)await Y0(F),m.publish(H,"review.completed",{reviewId:DO.reviewId,status:DO.status,findings:0,recovered:!0})}if(q.aborted||a)return;if(!S)await g0.recoverResponded(H.projectPath,H.sessionId);if(q.aborted||a)return;let OO=S?void 0:await g0.findPending(H.projectPath,H.sessionId),VO=S?.pendingPermission??(OO?{permissionId:OO.request.requestId,details:g0.confirmationDetails(OO),resolve:()=>{return}}:void 0);if(VO){UO.add(VO.permissionId);let TO=v1(VO,!0);QO.observe({data:JSON.stringify({type:TO.type,properties:{...TO.properties,sessionId:H.sessionId,projectPath:H.projectPath}})})}if(q.aborted||a)return;let sO=u(F).catch(async(TO)=>{if(TO instanceof j0){await Y0(F).catch(()=>{return});let DO=F.taskFailure?.code==="workspace_unavailable"?F.taskFailure:o0("workspace_unavailable");F.taskStatus="failed",F.taskStatusReason=DO.message,F.taskFailure=DO,m.publish(H,"session.error",{error:DO.message,taskFailure:DO}),m.publish(H,"session.status",{status:"error"})}t.error(`[SessionRoutes] Failed to resume pending input for ${w}:`,TO)});if(jO(sO),q.aborted||a)return;AO=setInterval(()=>{if(q.aborted||a)return;QO?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await o}catch(S){if(V2(S,a))return;throw S}finally{await xO()}});return K=!0,N.release(),C}catch(H){if(!K)V.release();throw H}}),O.post("/:sessionId/message",async(Q)=>{let w=Q.req.param("sessionId"),V=await Q.req.json(),K=h(L9,V);if(!K.success)throw new U("Invalid message format");let{content:H,attachments:N,modelId:F,reasoningEffort:D,serviceTier:j,responseVerbosity:x,communicationStyle:C,permissionMode:q,projectPath:E,annotations:v,outputSchema:BO}=K.data,AO;if(BO)try{AO=x4(BO).schema}catch(xO){throw new U(xO instanceof Error?xO.message:"Invalid output schema")}let a=C;if(Buffer.byteLength(H,"utf8")>B4)throw new U(`Message text exceeds the ${B4}-byte limit`);let QO=F?.trim();if((N??[]).reduce((xO,S)=>xO+(typeof S.content==="string"?Buffer.byteLength(S.content):0),0)>n1)throw new U("Message attachments exceed the 5 MiB limit");let o=q,WO=X2(H,N),UO=v&&v.length>0?{selectedConversationAnnotations:v}:void 0,jO=await f1(w,E??Q.req.query("projectPath")),r=jO.value,c=YO(r),bO=o??r.permissionMode??"default";try{return await XO(c,async()=>{let xO=hO(r.currentRunId);if(yO(xO)){if(AO)throw new p("Wait for the active turn to finish before setting an output schema");return NO(r,async(OO)=>{if(QO&&!OO.getModelById(QO))throw new U(`Model not found: ${QO}`);if(QO&&OO.getCurrentModelId()!==QO)throw new p("Wait for the active turn to finish before switching models");if(D&&OO.getReasoningConfiguration().selection!==D)throw new p("Wait for the active turn to finish before switching reasoning effort");if(j&&OO.getServiceTierConfiguration().selection!==j)throw new p("Wait for the active turn to finish before switching service tier");if(x&&OO.getResponseVerbosityConfiguration().selection!==x)throw new p("Wait for the active turn to finish before switching response verbosity");if(a&&OO.getCommunicationStyleConfiguration().selection!==a)throw new p("Wait for the active turn to finish before switching communication style");if(o&&r.permissionMode!==o)throw new p("Wait for the active turn to finish before switching permission mode");let VO=await OO.enqueueSteering(WO,{allowBeforeTurn:!0,...UO?{metadata:UO}:{}});if(!VO.accepted)return Q.json({status:"rejected",reason:VO.reason??"turn_unavailable"},409);let sO=VO.messageId??Y2(12),TO=VO.queued,DO=VO.queue??await OO.getFollowUpQueueSnapshot(),qO=VO.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(m.publish(c,qO,{runId:xO.id,messageId:sO,queued:TO}),!VO.duplicate)m.publish(c,"follow_up.queue.changed",{queue:DO});if(VO.delivery==="next_turn"&&xO.status!=="running"&&xO.status!=="waiting_permission")u(r).catch((S0)=>{t.error(`[SessionRoutes] Failed to wake queued follow-up for ${w}:`,S0)});if(VO.delivery==="next_turn")xO.pendingFollowUpRequested=!0;return Q.json({runId:xO.id,messageId:sO,status:VO.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:TO,followUpQueue:DO},202)})}if(d(c),r.permissionMode!==bO)await Y$(r,bO);let S=await JO(r,{permissionMode:bO,...a&&!a.includes(":")?{communicationStyle:a}:{}}),pO=!1,nO;try{let OO=S.value;if(QO&&!OO.getModelById(QO))throw new U(`Model not found: ${QO}`);if(D)try{OO.resolveReasoningConfiguration(D,QO)}catch(EO){throw new U(EO instanceof Error?EO.message:"Invalid reasoning effort")}if(j)try{OO.resolveServiceTierConfiguration(j,QO)}catch(EO){throw new U(EO instanceof Error?EO.message:"Invalid service tier")}if(x)try{OO.resolveResponseVerbosityConfiguration(x,QO)}catch(EO){throw new U(EO instanceof Error?EO.message:"Invalid response verbosity")}let VO=a?OO.resolveCommunicationStyleConfiguration(a):void 0;if(VO?.source!==void 0&&VO.source!=="built-in"&&!VO.contentSha256)throw new U("Custom communication style has no provenance");let sO=OO.getCurrentModelId(),TO=OO.getReasoningConfiguration(),DO=OO.getServiceTierConfiguration(),qO=OO.getResponseVerbosityConfiguration(),S0=OO.getCommunicationStyleConfiguration(),z0=Boolean(QO)&&sO!==QO,z$=Boolean(D)&&TO.selection!==D,G$=Boolean(j)&&DO.selection!==j,K$=Boolean(x)&&qO.selection!==x,w$=Boolean(a)&&S0.selection!==a;if(z0||z$||G$||K$||w$)await OO.refresh({...QO?{modelId:QO}:{},...D?{reasoningEffort:D}:{},...j?{serviceTier:j}:{},...x?{responseVerbosity:x}:{},...a?{communicationStyle:a}:{}});let Q4={...QO&&r.selectedModelId!==QO?{selectedModelId:QO}:{},...D&&r.reasoningEffort!==D?{reasoningEffort:D}:{},...j&&r.serviceTier!==j?{serviceTier:j}:{},...x&&r.responseVerbosity!==x?{responseVerbosity:x}:{},...VO&&(r.communicationStyle!==a||r.communicationStyleDigest!==VO.contentSha256)?{communicationStyle:a,communicationStyleDigest:VO.source==="built-in"?null:VO.contentSha256}:{}};if(Object.keys(Q4).length>0)try{let EO=await g.updateSessionMetadata(r.id,r.projectPath,Q4);r.permissionMode=EO.permissionMode,r.selectedModelId=EO.selectedModelId,r.reasoningEffort=EO.reasoningEffort,r.serviceTier=EO.serviceTier,r.responseVerbosity=EO.responseVerbosity,r.communicationStyle=EO.communicationStyle,r.communicationStyleDigest=EO.communicationStyleDigest,r.updatedAt=new Date(EO.lastMessageTime),m.publish(c,"session.updated",Q4)}catch(EO){if(z0||z$||G$||K$||w$)await OO.refresh({...sO?{modelId:sO}:{},reasoningEffort:TO.selection,serviceTier:DO.selection,responseVerbosity:qO.selection,communicationStyle:S0.selection}).catch((h5)=>t.error("[SessionRoutes] Failed to roll back non-durable model settings:",h5));throw EO}let w1=AO||UO?await OO.prepareInputTurn(WO,{...AO?{outputSchema:AO}:{},...UO?{metadata:UO}:{}}):await OO.prepareInputTurn(WO);if(!w1.accepted)return Q.json({status:"rejected",reason:w1.reason},w1.reason==="queue_full"?429:409);nO=f0(jO);let Y4=K1(r,WO,bO,{preparedInputTurn:w1,outputSchema:AO,runtimeLease:S,projectionLease:nO});return pO=!0,nO=void 0,await Y4.taskAdmissionUpdate,Q.json({runId:Y4.id,messageId:w1.messageId,status:Y4.status==="queued"?"queued":"running",queuePosition:r.taskQueuePosition,queueDepth:r.taskQueueDepth,maxConcurrentTasks:r.taskConcurrencyLimit},202)}finally{if(nO?.release(),!pO)S.release()}})}finally{jO.release()}}),O.post("/:sessionId/side-question",async(Q)=>{let w=Q.req.param("sessionId"),V=h(p2,await Q.req.json());if(!V.success)throw new U("Invalid side conversation request");return iO(w,V.data.projectPath??Q.req.query("projectPath"),(K)=>R1(K,async(H)=>{let N=await H.askSideQuestion(V.data.question,{signal:Q.get("requestSignal")});return Q.json({...N,...H.getCurrentModelId()?{modelId:H.getCurrentModelId()}:{}})}))}),O.post("/:sessionId/shell",async(Q)=>{let w=Q.req.param("sessionId"),V=h(v2,await Q.req.json());if(!V.success)throw new U("Invalid user shell command");return iO(w,V.data.projectPath??Q.req.query("projectPath"),(K,H,N)=>{let F=i(H);return XO(H,async()=>{if(B0.has(F))throw new p("A user shell command is already running in this Session");let D=await JO(K),j=f0(N),x=D.value,C=new AbortController,q,E=new Promise((v)=>{q=v});B0.set(F,{controller:C,completion:E,projectionLease:j});try{let v=await x.executeUserShellCommand(V.data.command,{signal:C.signal});await Y0(K);let BO=hO(K.currentRunId);if(v.delivery==="next_turn"&&yO(BO))BO.pendingFollowUpRequested=!0;if(v.queue)m.publish(H,"follow_up.queue.changed",{queue:v.queue});return Q.json({executionId:v.executionId,messageId:v.messageId,record:v.record,auxiliary:v.auxiliary,...v.delivery?{delivery:v.delivery}:{},...v.queued!==void 0?{queued:v.queued}:{}})}finally{B0.delete(F),q(),D.release(),j.release()}})})}),O.post("/:sessionId/abort",async(Q)=>{let w=Q.req.param("sessionId"),V=await mO(w,Q.req.query("projectPath"));d(V);let K=V0(V);if(K?.currentRunId){let F=hO(K.currentRunId);if(F)h0(F),await F.completion}let H=B0.get(i(V));if(H)H.controller.abort("user-cancel"),await H.completion;let N=X0.get(i(V));if(N)N.controller.abort("user-cancel"),await N.completion;return Q.json({success:!0})}),O.get("/:sessionId/status",async(Q)=>{let w=Q.req.param("sessionId"),V=await mO(w,Q.req.query("projectPath")),K=V0(V),H=X0.get(i(V));if(H)return Q.json({sessionId:w,projectPath:V.projectPath,reviewId:H.reviewId,status:"reviewing"});if(!K?.currentRunId)return Q.json({sessionId:w,projectPath:V.projectPath,status:"idle"});let N=hO(K.currentRunId);return Q.json({sessionId:w,projectPath:V.projectPath,runId:K.currentRunId,status:N?.status==="attention_required"?"idle":N?.status??"idle"})}),{app:O,dispatchTask:X$,retryTask:R5,updateTask:E5,getTaskDiff:f5,deliverTask:P5,recoverQueuedTasks:k5,getRuntimeResidencyStats:()=>I.getStats(),getProjectionResidencyStats:()=>A.getStats(),getCoordinationStats:()=>({messageSubmissions:W.getStats(),taskDeliveries:B.getStats()}),getSseConnectionStats:()=>L.stats(),shutdown:(Q="server-shutdown")=>{if(k)return k;f.close(Q);let w=L.shutdown(Q);J4.accepting=!1,J$("server-shutdown");let V=Promise.allSettled([...G].map((K)=>K.promise));return clearInterval(R),clearInterval(P),y(),k=(async()=>{let K,H=async(x)=>{let C=await Promise.allSettled(x);for(let q of C)if(q.status==="rejected")K??=q.reason},N=new Set,F=()=>{for(let x of U4()){if(x.completion)N.add(x.completion);if(yO(x))h0(x,Q)}for(let x of B0.values())x.controller.abort(Q),N.add(x.completion);for(let x of X0.values())x.controller.abort(Q),N.add(x.completion)},D=f.waitForIdle(),j=!1;D.then(()=>{j=!0});while(!j)F(),await Promise.race([D,new Promise((x)=>setImmediate(x))]);if(await D,F(),await H([...N]),await V,await H([...J.values()]),F(),await H([...N]),await H([w]),await H([...J.values()]),await H([I.disposeAll()]),$.clear(),await H([...Y.values()]),await H([Z.disposeAll()]),await H([dO.getInstance().disconnectAll()]),J.clear(),Y.clear(),X.clear(),G.clear(),U0===J4)U0=void 0;if(j1===y)j1=void 0;if(K!==void 0)throw K})(),k}}};async function o2(O,$,Z){t.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),t.info(`[SessionRoutes] Active runs: ${e$()}`);let J=O2(O,$);if(J){t.info(`[SessionRoutes] Found permission ${$} in run ${J.id}`);let W=J.pendingPermission;if(!W)throw Error("Active permission run lost its pending interaction");if(W.details.interactionRequestId)await g0.respond(O.projectPath,O.sessionId,$,Z);return W.resolve(Z),t.info(`[SessionRoutes] Permission ${$} responded, runId: ${J.id}`),!0}let Y=await g0.findPending(O.projectPath,O.sessionId);if(!Y||Y.request.requestId!==$)return t.error(`[SessionRoutes] Permission not found: ${$}`),!1;await g0.respondAndRecover(O.projectPath,O.sessionId,$,Z),m.publish(O,"interaction.resolved",{requestId:$});let X=U0;if(!X?.accepting)return!0;let G;try{G=await X.acquireOrHydrateSession(O);let W=G.value,B=await g.findSessionMetadata(O.sessionId,O.projectPath);if(U0!==X||!X.accepting||!G.isCurrent())return!0;if(B)O0(W,B);X.resumeRecoveredInteraction(W).catch((M)=>{t.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,M)})}catch(W){if(U0!==X||!X.accepting)return!0;throw W}finally{G?.release()}return!0}var R4=$O("Service"),k9=z.Object({approved:z.Boolean(),remember:z.Optional(z.Boolean()),scope:z.Optional(GO(["once","session","project"])),targetMode:z.Optional(GO(["default","autoEdit","plan","yolo"])),feedback:z.Optional(z.String({maxLength:4000})),answers:z.Optional(z.Record(z.String({maxLength:80}),z.Union([z.String({maxLength:4000}),z.Array(z.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:z.Optional(z.Object({action:GO(["accept","decline","cancel"]),content:z.Optional(z.Record(z.String(),z.Union([z.String({maxLength:4000}),z.Number(),z.Boolean(),z.Array(z.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),t2=()=>{let O=new P9;return O.post("/:permissionId",async($)=>{let Z=$.req.param("permissionId"),J=$.req.query("sessionId"),Y=$.req.query("projectPath");R4.info(`[PermissionRoutes] Received permission response: permissionId=${Z}, sessionId=${J}`);try{let X=await $.req.json(),G=h(k9,X);if(!G.success)throw new U("Invalid permission response format");let{approved:W,remember:B,scope:M,targetMode:b,feedback:I,answers:A,elicitation:f}=G.data;if(!J)throw new U("sessionId query parameter is required");let L=await mO(J,Y);if(!await o2(L,Z,{approved:W,reason:I,scope:M,targetMode:b,feedback:I,answers:A,elicitation:f}))throw new l("Permission request",Z);return R4.info(`[PermissionRoutes] Permission ${Z} ${W?"approved":"denied"}`),$.json({success:!0,approved:W,remember:B})}catch(X){if(R4.error("[PermissionRoutes] Failed to respond to permission:",X),X instanceof U||X instanceof uO||X instanceof l||X instanceof wO)throw X;throw X}}),O};import{homedir as s2}from"node:os";import E4 from"node:path";import{Hono as h9}from"hono";var y9=z.Object({projectPath:z.String({minLength:1}),enabled:z.Boolean(),scope:z.Optional(GO(["local","project","global"]))}),m9=z.Object({projectPath:z.String({minLength:1})}),g9=z.Object({projectPath:z.String({minLength:1}),source:z.String({minLength:1}),trust:z.Literal(!0),ref:z.Optional(z.String({minLength:1}))}),v9=z.Object({projectPath:z.String({minLength:1}),trust:z.Literal(!0)}),p9=z.Object({projectPath:z.String({minLength:1}),confirm:z.Literal(!0)}),u9=z.Object({projectPath:z.String({minLength:1}),source:z.String({minLength:1}),ref:z.Optional(z.String({minLength:1}))}),r2=z.Object({projectPath:z.String({minLength:1}),confirm:z.Optional(z.Literal(!0))}),d9=z.Object({projectPath:z.String({minLength:1}),scope:z.Optional(GO(["local","project","global"])),policy:z.Object({restrictToAllowedSources:z.Boolean(),requireGitCommitSha:z.Boolean(),allowedGitHosts:z.Array(z.String()),allowedMarketplaces:z.Array(z.String()),allowedLocalRoots:z.Array(z.String())})});function $0(O){if(!O)throw new U("projectPath must be absolute");try{return HO(O)}catch{throw new U("projectPath must reference a local workspace")}}function c9(O){return E4.isAbsolute(O)||O.startsWith("./")||O.startsWith("../")||O==="~"||O.startsWith("~/")}function e2(O,$){if(!c9(O))return;let Z=O==="~"?s2():O.startsWith("~/")?E4.join(s2(),O.slice(2)):O;try{HO(E4.resolve($,Z))}catch{throw new U("Plugin source must reference a local workspace")}}async function O3(O){let[$,Z]=await Promise.all([eO(O),F1.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((J)=>({name:J.manifest.name,description:J.manifest.description,version:J.manifest.version,source:J.source,enabled:J.status==="active",status:J.status,commands:J.commands.length,skills:J.skills.length,agents:J.agents.length,hooks:J.hooks?Object.values(J.hooks).reduce((Y,X)=>Y+(Array.isArray(X)?X.length:0),0):0,mcpServers:Object.keys(J.mcpServers??{}).length,configurable:J.source!=="cli",managed:J.installation!==void 0,marketplace:J.installation?.source.type==="marketplace"?J.installation.source.marketplace:void 0,revision:J.installation?.revision,installedAt:J.installation?.installedAt,updatedAt:J.installation?.updatedAt,compatibilityIssues:J.compatibilityIssues??[],effectiveScope:J.source==="cli"?"invocation":Z.settings[J.manifest.name]?.effectiveScope??"default",settingLayers:J.source==="cli"?{invocation:!0}:Z.settings[J.manifest.name]?.layers??{}}))}async function l9(){let O=$3(),[$,Z]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),J=new Map(Z.map((Y)=>[Y.name,Y]));return $.map(({marketplace:Y,manifest:X})=>({name:Y.name,description:X.description??X.metadata?.description??"",sourceType:Y.source.type,revision:Y.revision,updatedAt:Y.updatedAt,plugins:X.plugins.map((G)=>{let W=J.get(G.name);return{name:G.name,description:G.description??"",version:G.version,category:G.category,tags:G.tags??[],installed:W!==void 0,installedVersion:W?.version}})}))}function s0(O,$){if(!O.success)throw new U(O.error??$)}var w3=()=>{let O=new h9;return O.get("/",async($)=>{let Z=$0($.req.query("projectPath"));return $.json(await O3(Z))}),O.post("/refresh",async($)=>{let Z=h(m9,await $.req.json());if(!Z.success)throw new U("Invalid plugin refresh request");let J=$0(Z.data.projectPath),Y=await J3(J);return $.json({plugins:await O3(J),errors:Y.discovery.errors.map((X)=>({code:X.code??"LOAD_ERROR",error:X.error}))})}),O.get("/catalog",async($)=>{return $0($.req.query("projectPath")),$.json(await l9())}),O.get("/policy",async($)=>{let Z=$0($.req.query("projectPath")),J=await F1.getInstance().loadWorkspacePluginSourcePolicy(Z);return $.json({policy:J,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let Z=h(d9,await $.req.json());if(!Z.success)throw new U("Invalid plugin source policy request");let J=$0(Z.data.projectPath),Y=await Q3(J,Z.data.policy,Z.data.scope??"global");return $.json({policy:Y})}),O.post("/install",async($)=>{let Z=h(g9,await $.req.json());if(!Z.success)throw new U("Invalid plugin install request; explicit source trust is required");let J=$0(Z.data.projectPath);e2(Z.data.source,J);let{result:Y}=await Y3(J,Z.data.source,{trusted:Z.data.trust,ref:Z.data.ref});return s0(Y,"Plugin installation failed"),$.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,installedDependencies:Y.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let Z=h(u9,await $.req.json());if(!Z.success)throw new U("Invalid marketplace add request");let J=$0(Z.data.projectPath);e2(Z.data.source,J);let Y=await z3(J,Z.data.source,Z.data.ref);return s0(Y,"Marketplace installation failed"),$.json({name:Y.marketplace?.name,plugins:Y.manifest?.plugins.length??0,revision:Y.marketplace?.revision,changed:Y.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let Z=h(r2,await $.req.json());if(!Z.success)throw new U("Invalid marketplace refresh request");let J=await G3($0(Z.data.projectPath),$.req.param("name"));return s0(J,"Marketplace refresh failed"),$.json({name:J.marketplace?.name,plugins:J.manifest?.plugins.length??0,revision:J.marketplace?.revision,changed:J.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let Z=h(r2,await $.req.json());if(!Z.success||Z.data.confirm!==!0)throw new U("Invalid marketplace removal request; explicit confirmation is required");$0(Z.data.projectPath);let J=await K3($.req.param("name"),!0);return s0(J,"Marketplace removal failed"),$.json({name:J.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let Z=h(v9,await $.req.json());if(!Z.success)throw new U("Invalid plugin update request; explicit source trust is required");let J=$0(Z.data.projectPath),{result:Y}=await X3(J,$.req.param("name"),{trusted:Z.data.trust});return s0(Y,"Plugin update failed"),$.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,updatedDependencies:Y.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let Z=h(p9,await $.req.json());if(!Z.success)throw new U("Invalid plugin uninstall request; explicit confirmation is required");let J=$0(Z.data.projectPath),{result:Y}=await V3(J,$.req.param("name"),Z.data.confirm);return s0(Y,"Plugin uninstall failed"),$.json({name:Y.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let Z=h(y9,await $.req.json());if(!Z.success)throw new U("Invalid plugin state request");let J=$0(Z.data.projectPath),Y=$.req.param("name"),G=(await eO(J)).plugins.get(Y);if(!G)throw new l("Plugin",Y);if(G.source==="cli")throw new U(`Plugin "${Y}" was loaded with --plugin-dir and is invocation-scoped`);let W=await Z3(J,Y,Z.data.enabled,Z.data.scope??"local");return $.json(W)}),O};import{Hono as t9}from"hono";import{execFile as i9}from"node:child_process";import n9 from"node:path";var P4="__BLADE_DIRECTORY_PICKER_CANCELLED__",a9=900000;function o9(O,$){return new Promise((Z)=>{i9(O,[...$],{timeout:a9,maxBuffer:65536,windowsHide:!0},(J,Y,X)=>{let G=J?.code;Z({stdout:Y,stderr:X,exitCode:typeof G==="number"?G:J?1:0,...typeof G==="string"?{errorCode:G}:{}})})})}function f4(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===P4)return{cancelled:!0};if(!n9.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function S4(O){return O.exitCode!==0||Boolean(O.errorCode)}class H3{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??o9}pick(){if(this.activeSelection)return this.activeSelection;let O=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=O,O}async pickForPlatform(){switch(this.platform){case"darwin":return this.pickOnMac();case"win32":return this.pickOnWindows();case"linux":return this.pickOnLinux();default:throw Error("Native folder selection is unavailable on this system")}}async pickOnMac(){let O=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${P4}"`,"end try"].join(`
8
- `),$=await this.runCommand("osascript",["-e",O]);if(S4($))throw Error("Unable to open the macOS folder picker");return f4($.stdout)}async pickOnWindows(){let O=["Add-Type -AssemblyName System.Windows.Forms","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog",'$dialog.Description = "Choose a project folder"',"$dialog.ShowNewFolderButton = $true","if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {"," [Console]::Out.Write($dialog.SelectedPath)","} else {",` [Console]::Out.Write("${P4}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(S4($))throw Error("Unable to open the Windows folder picker");return f4($.stdout)}async pickOnLinux(){let O=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let $ of O){let Z=await this.runCommand($.command,$.args);if(Z.errorCode==="ENOENT")continue;if(Z.exitCode===1&&!Z.stdout.trim()&&!Z.stderr.trim())return{cancelled:!0};if(S4(Z))throw Error("Unable to open the Linux folder picker");return f4(Z.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var W3=new H3;var s9=z.Object({path:z.String({minLength:1})});function U3(O){try{return HO(O)}catch($){throw new U($ instanceof Error?$.message:"Project path is invalid")}}function r9(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let $=new URL(O).hostname;return $==="localhost"||$==="127.0.0.1"||$==="::1"||$==="[::1]"}catch{return!1}}var F3=(O={})=>{let $=new t9,Z=O.pickDirectory??(()=>W3.pick()),J=O.allowDirectoryPickerRequest??r9;return $.get("/",async(Y)=>{return Y.json(await a1.list(KO()))}),$.post("/",async(Y)=>{let X;try{X=await Y.req.json()}catch{throw new U("A valid JSON body is required")}let G=h(s9,X);if(!G.success)throw new U("A project path is required");try{let W=U3(G.data.path),B=await a1.bind(W,KO());return Y.json(B,201)}catch(W){throw new U(W instanceof Error?W.message:"Failed to bind project")}}),$.post("/pick",async(Y)=>{if(!J(Y.req.header("Origin")))throw new wO("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Y.json(await Z())}catch(X){throw new U(X instanceof Error?X.message:"Failed to select a folder")}}),$.delete("/",async(Y)=>{let X=Y.req.query("path");if(!X)throw new U("A project path is required");try{let G=await a1.unbind(U3(X));return Y.json({success:!0,removed:G})}catch(G){throw new U(G instanceof Error?G.message:"Failed to unbind project")}}),$};import{Hono as e9}from"hono";var _3=$O("Service"),D3=()=>{let O=new e9;return O.get("/",async($)=>{try{let Z=await B3();return $.json(Z)}catch(Z){return _3.error("[ProviderRoutes] Failed to list providers:",Z),$.json([])}}),O.get("/:provider/models",async($)=>{let Z=$.req.param("provider");try{let J=await x3(Z);return $.json(J)}catch(J){return _3.error("[ProviderRoutes] Failed to list models:",J),$.json([])}}),O.put("/:provider/credential",async($)=>{let Z=$.req.param("provider"),J=await $.req.json();if(!J.apiKey?.trim())throw new U("apiKey is required");return await P0().setApiKey(Z,J.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await P0().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let Z=$.req.param("provider"),J=LO(),Y=J?.modelProviders[Z];if(!J||!Y)throw new l("Model provider",Z);let X=await $.req.json();if(!X.name||!X.baseUrl||!X.wireApi)throw new U("name, baseUrl and wireApi are required");let G="apiKeyEnv"in X?X.apiKeyEnv?.trim():Y.apiKeyEnv,W={name:X.name,baseUrl:X.baseUrl,wireApi:X.wireApi,...G?{apiKeyEnv:G}:{}},B=P0(),M=X.apiKey?.trim()?await B.credentials.read(Z):void 0;if(X.apiKey?.trim())await B.setApiKey(Z,X.apiKey.trim());try{return await aO().updateModelProvider(Z,W),$.json({success:!0})}catch(b){if(X.apiKey?.trim())if(M)await B.credentials.modify(Z,async()=>M);else await B.credentials.delete(Z);if(b instanceof Error&&(b.message.includes("modelProviders.")||b.message.includes("built-in provider")))throw new U(b.message);throw b}}),O.delete("/:provider",async($)=>{let Z=$.req.param("provider");if(!LO()?.modelProviders[Z])throw new l("Model provider",Z);let Y=$.req.query("removeModels");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new U("removeModels must be true or false");try{let X=await aO().removeModelProvider(Z,{removeModels:Y==="true"});return $.json({success:!0,...X})}catch(X){if(X instanceof Error&&(X.message.includes("still referenced")||X.message.includes("owns the only model")))throw new p(X.message);throw X}}),O.post("/:provider/probe",async($)=>{let Z=$.req.param("provider"),J=LO();if(!J?.modelProviders[Z])throw new l("Model provider",Z);let Y=await $.req.json().catch(()=>({})),X=J.models.filter((W)=>W.provider===Z),G=Y.modelId?X.find((W)=>W.id===Y.modelId):X[0];if(!G)throw new U(Y.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return $.json(await N3(G,J))}),O};import{Hono as O6}from"hono";var $6=$O("Service"),j3=(O,$)=>{let Z=new O6;return Z.onError((J,Y)=>{if(J instanceof wO)return Y.json(J.toObject(),J.statusCode);return $6.error("[ScheduleRoutes] Unhandled route error:",J),Y.json(new zO("Schedule request failed").toObject(),500)}),Z.get("/",async(J)=>{let Y=await O.list();return J.json(A3.parse({schedules:Y}))}),Z.post("/",async(J)=>{let Y;try{Y=await J.req.json()}catch{throw new U("Invalid request body")}let X=h(M3,Y);if(!X.success)throw new U("Invalid schedule request");let G;try{G=HO(X.data.projectPath||J.get("directory")||KO())}catch{throw new U("projectPath must reference a local workspace")}try{let W=await O.create({...X.data,projectPath:G});return J.json(v0.parse(W),201)}catch(W){throw new U(W instanceof Error?W.message:"Failed to create schedule")}}),Z.get("/:id",async(J)=>{let Y=await O.get(J.req.param("id"));if(!Y)throw new l("Schedule not found");return J.json(v0.parse(Y))}),Z.patch("/:id",async(J)=>{let Y;try{Y=await J.req.json()}catch{throw new U("Invalid request body")}let X=h(L3,Y);if(!X.success)throw new U("Invalid schedule update");let{modelId:G,reasoningEffort:W,serviceTier:B,responseVerbosity:M,communicationStyle:b,isolation:I,permissionMode:A,...f}=X.data,L={...G!==void 0?{modelId:G}:{},...W!==void 0?{reasoningEffort:W}:{},...B!==void 0?{serviceTier:B}:{},...M!==void 0?{responseVerbosity:M}:{},...b!==void 0?{communicationStyle:b}:{},...I!==void 0?{isolation:I}:{},...A!==void 0?{permissionMode:A}:{}};try{let R=await O.update(J.req.param("id"),{...f,...Object.keys(L).length>0?{dispatch:L}:{}});if(!R)throw new l("Schedule not found");return J.json(v0.parse(R))}catch(R){if(R instanceof wO)throw R;throw new U(R instanceof Error?R.message:"Failed to update schedule")}}),Z.delete("/:id",async(J)=>{if(!await O.remove(J.req.param("id")))throw new l("Schedule not found");return J.json({ok:!0})}),Z.post("/:id/enable",async(J)=>{let Y=await O.setEnabled(J.req.param("id"),!0);if(!Y)throw new l("Schedule not found");return J.json(v0.parse(Y))}),Z.post("/:id/disable",async(J)=>{let Y=await O.setEnabled(J.req.param("id"),!1);if(!Y)throw new l("Schedule not found");return J.json(v0.parse(Y))}),Z.post("/:id/run",async(J)=>{let Y=await O.get(J.req.param("id"));if(!Y)throw new l("Schedule not found");if(!$)throw new zO("Scheduler is not running in this process");await $.fire(Y,new Date,{manual:!0});let X=await O.get(Y.id);return J.json(v0.parse(X??Y),202)}),Z};import{createHash as Z6}from"node:crypto";import{Hono as J6}from"hono";var k4={invalid_session_surface_request:400,invalid_session_locator:400,session_surface_not_found:404,workspace_binding_mismatch:409,session_surface_cursor_invalid:400,session_surface_snapshot_changed:409,session_surface_read_only:409,session_surface_capability_unavailable:403,session_surface_capacity:429,session_surface_unavailable:503,session_surface_state_invalid:500},Q6=z.Object({cursor:z.Optional(z.String({minLength:1})),limit:z.Optional(z.String({pattern:"^(?:[1-9]|[1-9][0-9]|100)$"})),archived:z.Optional(GO(["true","false"])),workspaceKind:z.Optional(GO(["local","acp-remote"]))},{additionalProperties:!1}),o1=65536,Y6=new Set(["cursor","limit","archived","workspaceKind"]),X6=new Set(["locator","limit"]),V6=new Set(["locator","cursor","expectedSnapshot","limit"]),z6=new Set(["locator"]),G6=new Set(["version","sessionId","workspace"]),K6=new Set(["kind","projectPath","workspaceRef"]),w6=$O("Service");function P3(O={}){let $=O.service?void 0:new f3(O.cursorRegistryOptions),Z=O.service??new S3({database:O.database,cursorRegistry:$}),J=O.logger??w6,Y=new J6,X=!0,G=0,W,B=new Set,M=()=>new r0("session_surface_unavailable"),b=()=>{if(G===0)return Promise.resolve();return new Promise((A)=>B.add(A))};return Y.onError((A,f)=>{let L=U6(A);return J.warn(`[SessionSurfaceRoutes] method=${f.req.method} path=${f.req.path} code=${L.error.code} kind=${f.get("surfaceKind")??"unknown"} locator=${f.get("surfaceLocatorDigest")??"none"}`),f.json(L,k4[L.error.code])}),Y.use("*",async(A,f)=>{if(A.set("surfaceKind","unknown"),A.set("surfaceLocatorDigest","none"),!X){let L=t1(M());return A.json(L,k4[L.error.code])}G+=1;try{if(await f(),!X){let L=t1(M());A.res=A.json(L,k4[L.error.code])}return A.res}finally{if(G-=1,G===0){for(let L of B)L();B.clear()}}}),Y.get("/catalog",async(A)=>{let f=H6(A.req.url),L=await Z.listPage(f);return A.json(q3.parse(L))}),Y.post("/open",async(A)=>{h4(A.req.url);let f=await g4(A.req.raw);T1(f,X6,gO());let L=y4(f);m4(A,L);let R=h(C3,f);if(!R.success)throw gO();let P=await Z.open(L,{limit:R.data.limit});return A.json(v4.parse(P))}),Y.post("/history",async(A)=>{h4(A.req.url);let f=await g4(A.req.raw);T1(f,V6,gO());let L=y4(f);m4(A,L);let R=h(R3,f);if(!R.success)throw gO();let P=await Z.historyPage(L,{cursor:R.data.cursor,expectedSnapshot:R.data.expectedSnapshot,limit:R.data.limit});return A.json(I3.parse(P))}),Y.post("/fork",async(A)=>{h4(A.req.url);let f=await g4(A.req.raw);T1(f,z6,gO());let L=y4(f);if(m4(A,L),!h(E3,f).success)throw gO();let P=await Z.fork(L);return A.json(v4.parse(P))}),{app:Y,getStats:()=>({accepting:X,active:G,cursors:$?.stats().entryCount??0}),shutdown:(A="server-shutdown")=>{if(W)return W;return X=!1,W=(async()=>{let L=(await Promise.allSettled([Promise.resolve().then(()=>Z.close(A)),b()])).find((R)=>R.status==="rejected");if(L)throw L.reason})(),W}}}function gO(){return new r0("invalid_session_surface_request")}function H6(O){let $=new URL(O).searchParams,Z={},J=new Set;for(let[X,G]of $){if(!Y6.has(X)||J.has(X))throw gO();J.add(X),Z[X]=G}let Y=h(Q6,Z);if(!Y.success)throw gO();return{...Y.data.archived!==void 0?{archived:Y.data.archived==="true"}:{},...Y.data.cursor!==void 0?{cursor:Y.data.cursor}:{},...Y.data.limit!==void 0?{limit:Number(Y.data.limit)}:{},...Y.data.workspaceKind!==void 0?{workspaceKind:Y.data.workspaceKind}:{}}}function h4(O){if(new URL(O).searchParams.size>0)throw gO()}function T1(O,$,Z){if(!O||typeof O!=="object"||Array.isArray(O))throw Z;if(Object.keys(O).some((J)=>!$.has(J)))throw Z}function y4(O){if(!O||typeof O!=="object"||Array.isArray(O))throw gO();let $=Reflect.get(O,"locator");if($===void 0)throw gO();let Z=new r0("invalid_session_locator");T1($,G6,Z),T1(Reflect.get($,"workspace"),K6,Z);let J=h(b3,$);if(!J.success)throw Z;return J.data}function m4(O,$){O.set("surfaceKind",$.workspace.kind),O.set("surfaceLocatorDigest",F6($))}async function g4(O){let $=O.headers.get("content-length");if($!==null&&(!/^\d+$/.test($)||Number($)>o1))throw gO();let Z=O.body?.getReader();if(!Z)throw gO();let J=[],Y=0;try{while(!0){let{done:B,value:M}=await Z.read();if(B)break;if(Y+=M.byteLength,Y>o1){try{await Z.cancel()}catch{}throw gO()}J.push(M)}}finally{Z.releaseLock()}let X=new Uint8Array(Y),G=0;for(let B of J)X.set(B,G),G+=B.byteLength;let W=new TextDecoder().decode(X);if(!W)throw gO();try{return W6(W),JSON.parse(W)}catch{throw gO()}}function W6(O){let $=0,Z=()=>{while(/\s/.test(O[$]??""))$+=1},J=()=>{let X=$;if(O[$]!=='"')throw Error("expected string");$+=1;while($<O.length){let G=O[$];if(G==="\\"){$+=2;continue}if($+=1,G==='"')return JSON.parse(O.slice(X,$))}throw Error("unterminated string")},Y=()=>{Z();let X=O[$];if(X==="{"){$+=1,Z();let W=new Set;if(O[$]==="}"){$+=1;return}while($<O.length){Z();let B=J();if(W.has(B))throw Error("duplicate key");if(W.add(B),Z(),O[$]!==":")throw Error("expected colon");if($+=1,Y(),Z(),O[$]==="}"){$+=1;return}if(O[$]!==",")throw Error("expected comma");$+=1}throw Error("unterminated object")}if(X==="["){if($+=1,Z(),O[$]==="]"){$+=1;return}while($<O.length){if(Y(),Z(),O[$]==="]"){$+=1;return}if(O[$]!==",")throw Error("expected comma");$+=1}throw Error("unterminated array")}if(X==='"'){J();return}let G=/^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(O.slice($))?.[0];if(!G)throw Error("invalid primitive");$+=G.length};if(Y(),Z(),$!==O.length)throw Error("trailing JSON")}function U6(O){if(O instanceof r0)return t1(O);return t1(new r0("session_surface_state_invalid"))}function t1(O){return T3.parse({error:{code:O.code,message:O.message,retryable:O.retryable}})}function F6(O){if(!O)return"none";return Z6("sha256").update("session-surface-route-locator-v2\x00").update(JSON.stringify(O)).digest("hex").slice(0,16)}import*as C0 from"node:fs/promises";import{homedir as g3}from"node:os";import*as lO from"node:path";import{Hono as D6}from"hono";import{execFile as _6}from"node:child_process";import*as s from"node:fs/promises";import{homedir as N6}from"node:os";import*as ZO from"node:path";import{promisify as B6}from"node:util";var x6=B6(_6),IO=$O("General");function p0(O){return typeof O==="string"&&O===O.trim()&&/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/.test(O)}function u4(O){if(typeof O!=="string"||!O||/\s/.test(O))return!1;if([...O].some(($)=>$.charCodeAt(0)<32||$.charCodeAt(0)===127))return!1;if(O.startsWith("git@"))return/^git@[A-Za-z0-9][A-Za-z0-9.-]*:[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+$/.test(O);if(!/^(https|ssh):\/\//.test(O))return!1;try{let $=new URL(O);return($.protocol==="https:"||$.protocol==="ssh:")&&Boolean($.hostname)&&!$.hostname.startsWith("-")&&!$.password&&!($.protocol==="https:"&&$.username)&&!($.username&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test($.username))&&!$.search&&!$.hash&&$.pathname!=="/"}catch{return!1}}function d4(O){let $=O.startsWith("git@")?O.slice(O.indexOf(":")+1):new URL(O).pathname;return ZO.posix.basename($.replace(/\/+$/,"")).replace(/\.git$/,"")}var k3={url:"https://github.com/anthropics/skills.git",branch:"main"};class h3{skillsDir;constructor(O){this.skillsDir=O||ZO.join(N6(),".blade","skills")}async isGitAvailable(){try{return await this.runGit(["--version"],5000),!0}catch{return!1}}async runGit(O,$){await x6("git",O,{shell:!1,timeout:$,maxBuffer:4194304,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}async installOfficialSkill(O){if(!p0(O))return!1;let{url:$,branch:Z}=k3,J=ZO.join(this.skillsDir,O),Y=ZO.join(this.skillsDir,`.tmp-${O}-${Date.now()}`);try{if(!await this.isGitAvailable())return IO.warn("Git not available, skipping skill installation"),!1;IO.info(`Installing official skill: ${O}...`),await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),await this.runGit(["clone","--depth","1","--branch",Z,"--single-branch","--",$,Y],30000);let X=ZO.join(Y,"skills",O);try{await s.access(X)}catch{return IO.warn(`Skill ${O} not found in official repository`),await s.rm(Y,{recursive:!0,force:!0}),!1}try{await s.rm(J,{recursive:!0,force:!0})}catch{}return await s.cp(X,J,{recursive:!0}),await s.rm(Y,{recursive:!0,force:!0}),IO.info(`Successfully installed: ${O}`),!0}catch(X){try{await s.rm(Y,{recursive:!0,force:!0})}catch{}return IO.warn(`Failed to install ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installFromRepo(O,$){if(!u4(O))return!1;let Z=$??d4(O);if(!p0(Z))return!1;let J=ZO.join(this.skillsDir,Z),Y=ZO.join(this.skillsDir,`.tmp-repo-${Z}-${Date.now()}`);try{if(!await this.isGitAvailable())return IO.warn("Git not available, cannot install from repo"),!1;IO.info(`Installing skill from repo: ${O}...`),await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),await this.runGit(["clone","--depth","1","--",O,Y],60000);let X=ZO.join(Y,"SKILL.md");try{await s.access(X)}catch{return IO.warn(`No SKILL.md found in repository ${O}`),await s.rm(Y,{recursive:!0,force:!0}),!1}await s.rm(J,{recursive:!0,force:!0}),await s.rename(Y,J);try{await s.rm(ZO.join(J,".git"),{recursive:!0,force:!0})}catch{}return IO.info(`Successfully installed skill from repo: ${Z}`),!0}catch(X){try{await s.rm(Y,{recursive:!0,force:!0})}catch{}return IO.warn(`Failed to install from repo ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installFromLocal(O,$,Z=!0){if(typeof O!=="string"||!O.trim()||O.includes("\x00"))return!1;let J=$??ZO.basename(O);if(!p0(J))return!1;let Y=ZO.resolve(this.skillsDir,J);try{let X=await s.realpath(ZO.resolve(O)),G=ZO.dirname(Y),W=[];while(!0)try{G=ZO.join(await s.realpath(G),...W);break}catch(b){if(b.code!=="ENOENT")throw b;W.unshift(ZO.basename(G)),G=ZO.dirname(G)}let B=ZO.join(G,J);try{if(!(await s.lstat(B)).isSymbolicLink())B=await s.realpath(B)}catch(b){if(b.code!=="ENOENT")throw b}if([ZO.relative(B,X),ZO.relative(X,B)].some((b)=>b===""||!b.startsWith(`..${ZO.sep}`)&&b!==".."&&!ZO.isAbsolute(b)))return!1;let M=ZO.join(X,"SKILL.md");try{await s.access(M)}catch{return IO.warn(`No SKILL.md found in local path: ${X}`),!1}if(IO.info(`Installing skill from local path: ${X}...`),await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),await s.rm(Y,{recursive:!0,force:!0}),Z)await s.symlink(X,Y,"dir"),IO.info(`Created symlink for skill: ${J}`);else await s.cp(X,Y,{recursive:!0}),IO.info(`Copied skill to: ${J}`);return!0}catch(X){return IO.warn(`Failed to install from local path ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installAllOfficialSkills(){let{url:O,branch:$}=k3,Z=ZO.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],Y=[];try{if(!await this.isGitAvailable())return IO.warn("Git not available, skipping skill installation"),{installed:J,failed:Y};await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),IO.info("Cloning official skills repository..."),await this.runGit(["clone","--depth","1","--branch",$,"--single-branch","--",O,Z],60000);let X=ZO.join(Z,"skills"),G=await s.readdir(X,{withFileTypes:!0});for(let W of G){if(!W.isDirectory())continue;let B=W.name;if(!p0(B)){Y.push(B);continue}let M=ZO.join(X,B),b=ZO.join(this.skillsDir,B);try{await s.access(ZO.join(M,"SKILL.md")),await s.rm(b,{recursive:!0,force:!0}),await s.cp(M,b,{recursive:!0}),IO.info(`Installed: ${B}`),J.push(B)}catch(I){IO.warn(`Failed to install ${B}`),Y.push(B)}}await s.rm(Z,{recursive:!0,force:!0})}catch(X){try{await s.rm(Z,{recursive:!0,force:!0})}catch{}IO.warn(`Failed to install skills: ${X instanceof Error?X.message:"Unknown error"}`)}return{installed:J,failed:Y}}}var p4=null;function y3(O){if(!p4)p4=new h3(O);return p4}var u0=$O("Service"),m3=lO.join(g3(),".blade","skills"),c4=lO.join(g3(),".blade","skills-config.json"),M6=z.Union([z.Object({source:z.Literal("catalog"),name:z.String({minLength:1,maxLength:64})}),z.Object({source:z.Literal("repo"),url:z.String({minLength:1,maxLength:4096}),name:z.Optional(z.String({minLength:1,maxLength:64}))}),z.Object({source:z.Literal("local"),path:z.String({minLength:1,maxLength:4096}),name:z.Optional(z.String({minLength:1,maxLength:64}))})]);function s1(O){try{return HO(O,"directory")}catch{throw new U("directory must reference a local workspace")}}async function v3(){try{let O=await C0.readFile(c4,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function L6(O){await C0.mkdir(lO.dirname(c4),{recursive:!0}),await C0.writeFile(c4,JSON.stringify(O,null,2))}async function A6(O,$){let Z=await v3();if($)Z.disabled=Z.disabled.filter((J)=>J!==O);else if(!Z.disabled.includes(O))Z.disabled.push(O);await L6(Z)}var I0=null,j6=300000,b6=6;async function T6(){if(I0&&Date.now()-I0.timestamp<j6)return I0.data;try{let O=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!O.ok){if(u0.warn(`GitHub API returned ${O.status}`),I0)return I0.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let Z=(await O.json()).filter((G)=>G.type==="dir"),J=Array(Z.length),Y=0,X=Math.min(b6,Z.length);return await Promise.all(Array.from({length:X},async()=>{while(Y<Z.length){let G=Y++,W=Z[G];if(!W)continue;let B=`Official ${W.name} skill`;try{let M=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${W.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(M.ok){let I=(await M.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(I)B=I[1].trim().slice(0,100)}}catch{}J[G]={name:W.name,description:B,tag:"Official",author:"Anthropic"}}})),I0={data:J,timestamp:Date.now()},J}catch(O){if(u0.warn("Failed to fetch skills catalog from GitHub:",O),I0)return I0.data;throw O}}var p3=()=>{let O=new D6;return O.get("/",async($)=>{try{let Z=s1($.get("directory")||KO()),Y=(await eO(Z)).skills.getAll(),X=await v3(),G=Y.map((W)=>({id:W.name,name:W.name,enabled:!X.disabled.includes(W.name),description:W.description||"",version:W.version||"1.0.0",provider:"Local",location:W.source==="builtin"?"Built-in":W.basePath,removable:W.source==="user"&&lO.dirname(lO.resolve(W.basePath))===lO.resolve(m3),capabilities:["prompts"],allowedTools:W.allowedTools||[]}));return $.json(G)}catch(Z){if(Z instanceof U)throw Z;return u0.error("[SkillsRoutes] Failed to get skills:",Z),$.json({error:Z instanceof Error?Z.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async($)=>{try{let Z=$.req.param("name"),J=await $.req.json();return await A6(Z,J.enabled),$.json({success:!0,enabled:J.enabled})}catch(Z){return u0.error("[SkillsRoutes] Failed to toggle skill:",Z),$.json({success:!1,error:Z.message},500)}}),O.delete("/:name",async($)=>{try{let Z=$.req.param("name"),J=s1($.get("directory")||KO());return B1(J,async(Y)=>{let X=Y.skills,G=X.get(Z);if(!G)return $.json({success:!1,error:"Skill not found"},404);let W=lO.resolve(G.basePath),B=lO.resolve(m3);if(G.source!=="user"||lO.dirname(W)!==B)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await C0.rm(W,{recursive:!0,force:!0}),await X.refresh(),N1(J),await _1(J),$.json({success:!0})})}catch(Z){if(Z instanceof U)throw Z;return u0.error("[SkillsRoutes] Failed to uninstall skill:",Z),$.json({success:!1,error:Z.message},500)}}),O.post("/install",async($)=>{try{let Z=h(M6,await $.req.json().catch(()=>null));if(!Z.success)throw new U("Invalid skill install request");let J=Z.data;if(J.name!==void 0&&!p0(J.name))throw new U("Invalid skill name");if(J.source==="repo"&&!u4(J.url))throw new U("Skill repositories must use HTTPS or SSH without embedded credentials");if(J.source==="local"&&(!J.path.trim()||J.path.includes("\x00")))throw new U("Invalid local skill path");let Y=J.name??(J.source==="repo"?d4(J.url):J.source==="local"?lO.basename(J.path):void 0);if(!p0(Y))throw new U("Invalid skill name");let X=y3(),G=s1($.get("directory")||KO());return B1(G,async(W)=>{let B=W.skills,M=!1;if(J.source==="catalog"&&J.name){if(M=await X.installOfficialSkill(J.name),!M)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(J.source==="repo"&&J.url){if(M=await X.installFromRepo(J.url,J.name),!M)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(J.source==="local"&&J.path){let b=s1(lO.resolve(J.path));if(M=await X.installFromLocal(b,J.name),!M)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await B.refresh(),N1(G),await _1(G),$.json({success:!0})})}catch(Z){if(Z instanceof U)throw Z;return u0.error("[SkillsRoutes] Failed to install skill:",Z),$.json({success:!1,error:Z.message},500)}}),O.get("/catalog",async($)=>{try{let Z=await T6();return $.json(Z)}catch(Z){return u0.error("[SkillsRoutes] Failed to get catalog:",Z),$.json({error:Z instanceof Error?Z.message:"Failed to get skills catalog"},502)}}),O};import{execSync as q6}from"node:child_process";import{readdir as I6,realpath as C6}from"node:fs/promises";import x0 from"node:path";import R6 from"fast-glob";import{Hono as E6}from"hono";var q1=$O("Service"),f6=(O)=>{try{return q6("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},S6=[...O1.map((O)=>`${O}/**`),...O1,...O1.map((O)=>`**/${O}/**`),...O1.map((O)=>`**/${O}`),...l4.map((O)=>`**/${O}`)],P6=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]);function e0(O){try{return HO(O,"directory")}catch($){throw new U($ instanceof Error?$.message:"directory is invalid")}}function u3(O,$){let Z=x0.relative(O,$);return Z===""||Z!==".."&&!Z.startsWith(`..${x0.sep}`)&&!x0.isAbsolute(Z)}async function d3(O){let $=x0.resolve(O),Z=[];while(!0)try{return x0.resolve(await C6($),...Z.reverse())}catch(J){let Y=J.code;if(Y!=="ENOENT"&&Y!=="ENOTDIR")throw J;let X=x0.dirname($);if(X===$)return x0.resolve(O);Z.push(x0.basename($)),$=X}}async function c3(O,$){let Z=x0.resolve(O,$);if(!u3(O,Z))return null;let J=await d3(O),Y=await d3(Z);if(!u3(J,Y))return null;try{e0(Y)}catch{return null}return Y}var n3=()=>{let O=new E6;return O.get("/commands",async($)=>{let Z=e0($.get("directory")||KO());try{let J=$.req.query("q")||"",Y=await eO(Z),X=i3(J,Z,Y).filter((G)=>!P6.has(G.command));return $.json(X)}catch(J){return q1.error("[SuggestionsRoutes] Failed to get command suggestions:",J),$.json([])}}),O.get("/files",async($)=>{let Z=e0($.get("directory")||KO());try{let J=$.req.query("q")||"",Y=Math.min(Number($.req.query("limit"))||100,1000),X=$.req.query("type")==="file",W=(await R6("**/*",{cwd:Z,dot:!1,followSymbolicLinks:!1,onlyFiles:X,markDirectories:!0,unique:!0,ignore:S6})).map((b)=>b.replace(/\\/g,"/"));if(!J)return $.json(W.slice(0,Y));let B=J.toLowerCase(),M=W.filter((b)=>b.toLowerCase().includes(B)).slice(0,Y);return $.json(M)}catch(J){return q1.error("[SuggestionsRoutes] Failed to get file suggestions:",J),$.json([])}}),O.get("/files/tree",async($)=>{let Z=e0($.get("directory")||KO());try{let J=$.req.query("path")||"",Y=await c3(Z,J);if(!Y)return $.json({error:"Invalid file path"},400);let G=(await I6(Y,{withFileTypes:!0})).map((M)=>({name:M.name,path:J?`${J}/${M.name}`:M.name,type:M.isDirectory()?"dir":"file"}));G.sort((M,b)=>{if(M.type!==b.type)return M.type==="dir"?-1:1;return M.name.localeCompare(b.name)});let W=new Set(O1),B=G.filter((M)=>{let b=M.name;if(b.startsWith("."))return!1;if(W.has(b))return!1;for(let I of l4)if(b.match(new RegExp(I.replace("*",".*"))))return!1;return!0});return $.json(B)}catch(J){return q1.error("[SuggestionsRoutes] Failed to get file tree:",J),$.json([])}}),O.get("/files/content",async($)=>{let Z=e0($.get("directory")||KO());try{let J=$.req.query("path");if(!J)return $.json({error:"Missing file path"},400);let Y=await c3(Z,J);if(!Y)return $.json({error:"Invalid file path"},400);let X=l3(),G=await X.stat(Y);if(!G?.isFile)return $.json({error:"File not found"},404);let W=200000,B=await X.readTextFile(Y),M=B.length>W;return $.json({path:J,content:M?B.slice(0,W):B,truncated:M,size:G.size})}catch(J){return q1.error("[SuggestionsRoutes] Failed to get file content:",J),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{let Z=e0($.get("directory")||KO());try{let J=f6(Z);return $.json({branch:J})}catch(J){return q1.error("[SuggestionsRoutes] Failed to get git info:",J),$.json({branch:null})}}),O};import{Hono as k6}from"hono";var $1=$O("Service"),r3=(O)=>{let $=new k6;return $.onError((Z,J)=>{if(Z instanceof wO)return J.json(Z.toObject(),Z.statusCode);return $1.error("[TaskRoutes] Unhandled route error:",Z),J.json(new zO("Failed to dispatch task").toObject(),500)}),$.post("/",async(Z)=>{let J;try{J=await Z.req.json()}catch{throw new U("Invalid request body")}let Y=h(o3,J);if(!Y.success)throw new U("Invalid task request");if((Y.data.attachments??[]).reduce((G,W)=>G+(typeof W.content==="string"?Buffer.byteLength(W.content):0),0)>n1)throw new U("Task attachments exceed the 5 MiB limit");if(Y.data.taskDueAt&&!Number.isFinite(Date.parse(Y.data.taskDueAt)))throw new U("Invalid task due date");try{let G=await O.dispatchTask({prompt:Y.data.prompt,title:Y.data.title,taskPriority:Y.data.taskPriority,taskKind:Y.data.taskKind,taskDueAt:Y.data.taskDueAt?new Date(Y.data.taskDueAt).toISOString():void 0,sourceProjectPath:Y.data.projectPath||Z.get("directory")||KO(),isolation:Y.data.isolation,permissionMode:Y.data.permissionMode,modelId:Y.data.modelId,reasoningEffort:Y.data.reasoningEffort,serviceTier:Y.data.serviceTier,responseVerbosity:Y.data.responseVerbosity,communicationStyle:Y.data.communicationStyle,attachments:Y.data.attachments,outputSchema:Y.data.outputSchema});return Z.json(n4.parse(G),202)}catch(G){if(G instanceof U||G instanceof p||G instanceof MO||G instanceof rO)throw G;throw $1.error("[TaskRoutes] Failed to dispatch task:",G),new zO("Failed to dispatch task")}}),$.patch("/:sessionId",async(Z)=>{let J;try{J=await Z.req.json()}catch{throw new U("Invalid request body")}let Y=h(t3,J);if(!Y.success)throw new U("Invalid task update");if(Y.data.title===void 0&&Y.data.taskPriority===void 0&&Y.data.taskKind===void 0&&Y.data.taskDueAt===void 0)throw new U("Task update must include at least one field");if(typeof Y.data.taskDueAt==="string"&&!Number.isFinite(Date.parse(Y.data.taskDueAt)))throw new U("Invalid task due date");try{let X=await O.updateTask(Z.req.param("sessionId"),{...Y.data,...typeof Y.data.taskDueAt==="string"?{taskDueAt:new Date(Y.data.taskDueAt).toISOString()}:{}},Z.req.query("projectPath"));return Z.json(i4.parse(X))}catch(X){if(X instanceof U||X instanceof l||X instanceof p)throw X;throw $1.error("[TaskRoutes] Failed to update task:",X),new zO("Failed to update task")}}),$.post("/:sessionId/retry",async(Z)=>{try{let J=await O.retryTask(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json(n4.parse(J),202)}catch(J){if(J instanceof U||J instanceof l||J instanceof p||J instanceof MO||J instanceof rO)throw J;throw $1.error("[TaskRoutes] Failed to retry task:",J),new zO("Failed to retry task")}}),$.get("/:sessionId/diff",async(Z)=>{try{let J=await O.getTaskDiff(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json(a3.parse(J))}catch(J){if(J instanceof U||J instanceof l||J instanceof p)throw J;throw $1.error("[TaskRoutes] Failed to load task diff:",J),new zO("Failed to load task diff")}}),$.post("/:sessionId/delivery",async(Z)=>{let J;try{J=await Z.req.json()}catch{throw new U("Invalid request body")}let Y=h(s3,J);if(!Y.success)throw new U("Invalid task delivery request");try{let X=await O.deliverTask(Z.req.param("sessionId"),Y.data.action,Z.req.query("projectPath"));return Z.json(i4.parse(X))}catch(X){if(X instanceof U||X instanceof l||X instanceof p)throw X;throw $1.error("[TaskRoutes] Failed to deliver task:",X),new zO("Failed to deliver task")}}),$};import{Hono as m6}from"hono";var h6=oO(z.Object({id:z.String(),name:z.String(),subagentType:z.String(),description:z.String(),agentId:z.Optional(z.String()),status:GO(["leader","running","completed","failed","cancelled","unknown"]),result:z.Optional(z.Unknown()),stats:z.Optional(z.Unknown()),worktreePath:z.Optional(z.String())})),y6=oO(z.Object({id:z.String(),subject:z.String(),description:z.String(),status:GO(["pending","blocked","running","completed"]),owner:z.Optional(z.String()),priority:GO(["high","medium","low"]),dependsOn:z.Array(z.String()),blocks:z.Array(z.String()),result:z.Optional(z.String()),createdAt:z.String(),startedAt:z.Optional(z.String()),completedAt:z.Optional(z.String())})),XY=oO(z.Object({name:z.String(),description:z.Optional(z.String()),status:GO(["idle","running","completed","failed","deleted"]),leadAgentId:z.String(),leadSessionId:z.Optional(z.String()),workspaceRoot:z.Optional(z.String()),peerMessagingEnabled:z.Boolean(),createdAt:z.Number(),updatedAt:z.Number(),deletedAt:z.Optional(z.Number()),members:z.Array(h6),tasks:z.Array(y6)})),e3=oO(z.Object({sessionId:z.String({minLength:1}),projectPath:z.String({minLength:1}),name:z.String({minLength:1}),description:z.Optional(z.String()),leadAgentType:z.Optional(z.String()),peerMessagingEnabled:z.Optional(z.Boolean()),members:z.Array(z.Object({name:z.String({minLength:1}),subagentType:z.String({minLength:1}),description:z.Optional(z.String()),prompt:z.String({minLength:10,maxLength:32768})}),{maxItems:32}),tasks:z.Optional(z.Array(z.Object({subject:z.String({minLength:1}),description:z.String({minLength:1}),dependsOn:z.Optional(z.Array(z.String())),assignedTo:z.Optional(z.String()),priority:z.Optional(GO(["high","medium","low"]))}),{maxItems:256}))})),O5=oO(z.Object({sessionId:z.String({minLength:1}),projectPath:z.String({minLength:1}),to:z.String({minLength:1}),message:z.String({minLength:1,maxLength:32768})})),$5=oO(z.Object({sessionId:z.String({minLength:1}),projectPath:z.String({minLength:1}),memberId:z.String({minLength:1})}));var g6=$O("Service"),Y5=()=>{let O=new m6;return O.onError(($,Z)=>{if($ instanceof wO)return Z.json($.toObject(),$.statusCode);return g6.error("[TeamRoutes] Unhandled route error:",$),Z.json(new zO("Team operation failed").toObject(),500)}),O.get("/",async($)=>{J1();let Z=await Q1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await Z1(Z.projectPath).list(Z))}),O.post("/",async($)=>{J1();let Z=h(e3,await a4($.req));if(!Z.success)throw new U("Invalid team request");let J=await Q1(Z.data.sessionId,Z.data.projectPath),Y=await g.findSessionMetadata(J.sessionId,J.projectPath);return $.json(await Z1(J.projectPath).create({name:Z.data.name,description:Z.data.description,leadAgentType:Z.data.leadAgentType,owner:J,modelId:Y?.selectedModelId,peerMessagingEnabled:Z.data.peerMessagingEnabled,members:Z.data.members,tasks:Z.data.tasks}),201)}),O.get("/:teamName",async($)=>{J1();let Z=await Q1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await Z1(Z.projectPath).getSnapshot($.req.param("teamName"),Z))}),O.post("/:teamName/messages",async($)=>{J1();let Z=h(O5,await a4($.req));if(!Z.success)throw new U("Invalid team message");let J=await Q1(Z.data.sessionId,Z.data.projectPath),Y=await Z1(J.projectPath).sendMessage({name:$.req.param("teamName"),to:Z.data.to,body:Z.data.message,owner:J});return $.json({messages:Y})}),O.post("/:teamName/tasks/claim",async($)=>{J1();let Z=h($5,await a4($.req));if(!Z.success)throw new U("Invalid team task claim");let J=await Q1(Z.data.sessionId,Z.data.projectPath);return $.json({task:await Z1(J.projectPath).claimTask($.req.param("teamName"),Z.data.memberId,J)})}),O.delete("/:teamName",async($)=>{J1();let Z=await Q1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await Z1(Z.projectPath).delete($.req.param("teamName"),{owner:Z,killRunning:!0}))}),O};function Z1(O){return new Q5({configDir:i1(),subagentRegistry:J5(O)})}function J1(){if(Z5().config.config?.agentTeamsEnabled!==!0)throw new MO("Agent Teams are disabled")}async function Q1(O,$){if(!O||!$)throw new U("sessionId and absolute projectPath are required");let Z;try{Z=HO($)}catch{throw new U("sessionId and local projectPath are required")}if(!await g.findSessionMetadata(O,Z))throw new l(`Session not found: ${O}`);return{sessionId:O,projectPath:Z}}async function a4(O){try{return await O.json()}catch{throw new U("Invalid request body")}}import{Hono as v6}from"hono";var R0=$O("Service"),Y1=new Map,X5=2097152,V5=65536;function z5(){return typeof globalThis.Bun<"u"}function G5(O,$){return HO(O||$||KO(),"cwd")}async function p6(O,$,Z){if(z5()){let{spawn:X}=await import("bun-pty"),G=X(O,$,{name:"xterm-256color",cwd:Z.cwd,env:Z.env});return{pid:G.pid,write:(W)=>G.write(W),resize:(W,B)=>G.resize(W,B),kill:()=>G.kill(),onData:(W)=>G.onData(W),onExit:(W)=>G.onExit(W)}}let Y=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:Z.cwd,env:Z.env,cols:80,rows:24});return{pid:Y.pid,write:(X)=>Y.write(X),resize:(X,G)=>Y.resize(X,G),kill:()=>Y.kill(),onData:(X)=>{Y.onData(X)},onExit:(X)=>{Y.onExit(X)}}}var s4=void 0,t4;if(z5())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();t4=$.upgradeWebSocket,s4=$.websocket}catch(O){R0.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function K5(O,$){let Z=`term-${Date.now()}`;R0.info(`[Terminal] New connection: ${Z}, cwd: ${O}`);let J=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=J.endsWith("sh")?["-l"]:[],X=await p6(J,Y,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),G={id:Z,process:X,cwd:O,buffer:"",subscribers:new Set};if(Y1.set(Z,G),G.subscribers.add($),X.onData((W)=>{let B=!1;for(let M of G.subscribers)try{M.send(W),B=!0}catch{G.subscribers.delete(M)}if(B)return;if(G.buffer+=W,G.buffer.length>X5)G.buffer=G.buffer.slice(-X5)}),X.onExit(({exitCode:W})=>{R0.info(`[Terminal] Process exited: ${Z}, code: ${W}`);for(let B of G.subscribers)try{B.close()}catch{}Y1.delete(Z)}),G.buffer){let W=G.buffer;G.buffer="";for(let B=0;B<W.length;B+=V5)$.send(W.slice(B,B+V5))}return{session:G,cleanup:()=>{if(R0.info(`[Terminal] Connection closed: ${Z}`),G.subscribers.delete($),G.subscribers.size===0){try{G.process.kill()}catch{}Y1.delete(Z)}}}}function w5(O,$){O.on("connection",async(Z,J)=>{try{let Y=new URL(J.url||"/",`http://${J.headers.host}`);if(!Y.pathname.endsWith("/terminal/ws")){Z.close();return}let X=G5(Y.searchParams.get("cwd")??void 0,$()),{session:G,cleanup:W}=await K5(X,{send:(B)=>Z.send(B),close:()=>Z.close()});Z.on("message",(B)=>{try{G.process.write(String(B))}catch(M){R0.error("[Terminal] Failed to write to PTY:",M)}}),Z.on("close",W),Z.on("error",W)}catch(Y){R0.error("[Terminal] Failed to spawn PTY:",Y),Z.close()}})}var H5=()=>{let O=new v6;if(O.get("/status",($)=>{let Z=Array.from(Y1.values()).map((J)=>({id:J.id,cwd:J.cwd}));return $.json({active:Z.length,terminals:Z})}),O.post("/kill/:terminalId",($)=>{let Z=$.req.param("terminalId"),J=Y1.get(Z);if(J){try{J.process.kill()}catch{}for(let Y of J.subscribers)Y.close();return Y1.delete(Z),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),t4)O.get("/ws",async($,Z)=>{let J=$.req.query("cwd")??void 0,Y;try{Y=G5(J,$.get("directory"))}catch(W){let B=W instanceof Error?W.message:"cwd must reference a local workspace";return $.text(B,400)}let X;return t4(()=>{return{async onOpen(W,B){try{X=await K5(Y,{send:(M)=>B.send(M),close:()=>B.close()})}catch(M){R0.error("[Terminal] Failed to spawn PTY:",M),B.close()}},onMessage(W){if(!X)return;try{X.session.process.write(String(W.data))}catch(B){R0.error("[Terminal] Failed to write to PTY:",B)}},onClose(){X?.cleanup()}}})($,Z)});else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import{Hono as u6}from"hono";var d6=z.Object({projectPath:z.String({minLength:1}),action:GO(["trust","revoke"])});function W5(O){try{return HO(O)}catch{throw new U("projectPath must reference a local workspace")}}var F5=()=>{let O=new u6;return O.get("/",async($)=>{let Z=$.req.query("projectPath");if(!Z)throw new U("projectPath query parameter is required");let J=W5(Z);return $.json(await r4.getInstance().getStatus(J))}),O.post("/",async($)=>{let Z=h(d6,await $.req.json());if(!Z.success)throw new U("Invalid workspace trust request");let{action:J}=Z.data,Y=W5(Z.data.projectPath),X=r4.getInstance(),G=J==="trust"?await X.trust(Y):await X.revoke(Y);return await U5(),$.json({...G,reloadRequired:G.sensitiveSources>0})}),O};var fO=$O("Service"),Z$=[],X1,L0,V1,F0,D0,M0,_5=new Map,N5=new Map,$8=new Set([".css",".html",".js",".json",".svg"]),Z8=1024,J8=3600000;class r1 extends Error{}function Q8(O){return O==="/sessions/v2"||O.startsWith("/sessions/v2/")}function Y8(O,$,Z){return new Promise((J,Y)=>{let X=[],G=0,W=()=>{O.off("data",B),O.off("end",M),O.off("error",b),$.removeEventListener("abort",I)},B=(f)=>{if(G+=f.byteLength,Z!==void 0&&G>Z){W(),O.resume(),Y(new r1);return}X.push(f)},M=()=>{W(),J(Buffer.concat(X,G))},b=(f)=>{W(),Y(f)},I=()=>{W(),Y($.reason)},A=O.headers["content-length"];if(Z!==void 0&&A!==void 0&&(!/^\d+$/.test(A)||Number(A)>Z)){O.resume(),Y(new r1);return}if(O.on("data",B),O.once("end",M),O.once("error",b),$.addEventListener("abort",I,{once:!0}),$.aborted)I()})}function X8(O,$){if(!O)return 0;let Z=O.split(",").map((J)=>{let[Y,...X]=J.trim().toLowerCase().split(";"),G=X.find((B)=>B.trim().startsWith("q=")),W=G?Number(G.trim().slice(2)):1;return{name:Y,quality:Number.isFinite(W)?Math.max(0,Math.min(1,W)):0}});return Z.find((J)=>J.name===$)?.quality??Z.find((J)=>J.name==="*")?.quality??0}function B5(){if(V1)return;let O=()=>{g.collectStaleEmptySessions().then(($)=>{if($>0)fO.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{fO.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),V1=setInterval(O,J8),V1.unref?.()}function x5(){if(!V1)return;clearInterval(V1),V1=void 0}function V8(O){return["br","gzip"].map((Z)=>({encoding:Z,quality:X8(O,Z)})).filter((Z)=>Z.quality>0).sort((Z,J)=>J.quality-Z.quality||(Z.encoding==="br"?-1:1))[0]?.encoding}function z8(O){let $=_5.get(O);if($)return $;let Z=I1(O);return _5.set(O,Z),Z}function G8(O,$,Z){let J=`${Z}:${O}`,Y=N5.get(J);if(Y)return Y;let X=Z==="br"?o6($,{params:{[s6.BROTLI_PARAM_QUALITY]:5}}):t6($,{level:6});return N5.set(J,X),X}function K8(){let O=i6(a6(import.meta.url)),$=[E0(O,"web"),E0(KO(),"dist/web"),E0(KO(),"packages/cli/dist/web")];for(let Z of $){let J=E0(Z,"index.html");if($$(J)){if(I1(J,"utf-8").includes("/assets/"))return fO.debug(`[Server] Found web dist at: ${Z}`),Z}}return null}function w8(){let O=new r6;O.onError((X,G)=>{if(fO.error("[Server] Request error:",X),X instanceof L5){let B=new rO(X.message,{resource:"workspace_agent_resources",limit:X.capacity});return G.json(B.toObject(),429)}if(X instanceof wO)return G.json(X.toObject(),X.statusCode);let W=X instanceof Error?X.message:String(X);return G.json({error:{code:"INTERNAL_ERROR",message:W}},500)}),O.use(async(X,G)=>{let W=process.env.BLADE_SERVER_PASSWORD;if(!W)return G();let B=X.req.path;if(B==="/"||B==="/favicon.svg"||B.startsWith("/assets/")||B.endsWith(".html")||B.endsWith(".js")||B.endsWith(".css"))return G();let M=X.req.header("Authorization");if(!M?.startsWith("Basic "))return X.header("WWW-Authenticate",'Basic realm="Blade Server"'),X.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let b=Buffer.from(M.slice(6),"base64").toString(),[I,A]=b.split(":"),f=process.env.BLADE_SERVER_USERNAME??"blade";if(I!==f||A!==W)return X.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return G()}),O.use(async(X,G)=>{let W=X.req.path==="/health"||X.req.path==="/global/health"||X.req.path.startsWith("/assets/");if(!W)fO.debug(`[Server] ${X.req.method} ${X.req.path}`);let B=Date.now();if(await G(),!W){let M=Date.now()-B;fO.debug(`[Server] ${X.req.method} ${X.req.path} - ${X.res.status} (${M}ms)`)}}),O.use(e6({origin(X){if(!X)return;if(X.startsWith("http://localhost:"))return X;if(X.startsWith("http://127.0.0.1:"))return X;if(X==="tauri://localhost"||X==="http://tauri.localhost")return X;if(Z$.includes(X))return X;return}})),O.use(async(X,G)=>{let W=X.req.query("directory")||X.req.header("x-blade-directory")||KO();try{W=decodeURIComponent(W)}catch{}return X.set("directory",W),G()});let $,Z,J;try{$=a2(),Z=P3(),J=L$(),F0=$,D0=Z,M0=J,X1=$.recoverQueuedTasks,L0=new V4({dispatch:(X)=>$.dispatchTask(X),store:O$}),O.route("/global",j$()),O.route("/events",J.app),O.route("/sessions/v2",Z.app),O.route("/sessions",$.app),O.route("/tasks",r3($)),O.route("/teams",Y5()),O.route("/schedules",j3(O$,L0)),O.route("/configs",U$()),O.route("/permissions",t2()),O.route("/plugins",w3()),O.route("/hooks",C$()),O.route("/workspace-trust",F5()),O.route("/providers",D3()),O.route("/models",m$()),O.route("/projects",F3()),O.route("/suggestions",n3()),O.route("/terminal",H5()),O.route("/mcp",f$()),O.route("/skills",p3())}catch(X){throw A5($,Z,J,"server-startup-failure").catch((G)=>{fO.error("[Server] Failed to clean up route controllers:",G)}),F0=void 0,D0=void 0,M0=void 0,X1=void 0,L0=void 0,X}O.get("/health",(X)=>{return X.json({healthy:!0,version:i0()})});let Y=K8();if(Y)fO.info(`[Server] Serving static files from ${Y}`),O.get("/favicon.svg",()=>{let X=E0(Y,"favicon.svg");if(!$$(X))return new Response(null,{status:404});return new Response(I1(X),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(X)=>{let G=E0(Y,X.req.path);if(!$$(G))return X.json({error:{code:"NOT_FOUND",message:`File not found: ${X.req.path}`}},404);let W=z8(G),B=n6(G).toLowerCase(),b={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[B]||"application/octet-stream",I=$8.has(B)&&W.byteLength>=Z8?V8(X.req.header("Accept-Encoding")):void 0,A=I?G8(G,W,I):W;return new Response(new Uint8Array(A),{headers:{"Content-Type":b,"Content-Length":String(A.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...I?{"Content-Encoding":I}:{}}})}),O.get("/",(X)=>{let G=E0(Y,"index.html"),W=I1(G,"utf-8");return X.html(W,200,{"Cache-Control":"no-cache"})}),O.get("*",(X)=>{let G=X.req.path;if(G.includes("."))return X.json({error:{code:"NOT_FOUND",message:`File not found: ${G}`}},404);let W=E0(Y,"index.html"),B=I1(W,"utf-8");return X.html(B,200,{"Cache-Control":"no-cache"})});else fO.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(X)=>{return X.json({message:"Blade API Server",version:i0(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),O.all("*",(X)=>{return X.json({error:{code:"NOT_FOUND",message:`Route not found: ${X.req.path}`}},404)});return O}async function A5(O,$,Z,J){let Y=[],X;for(let B of[O,$,Z])try{Y.push(B?.shutdown(J)??Promise.resolve())}catch(M){X??=M}let W=(await Promise.allSettled(Y)).find((B)=>B.status==="rejected");if(X!==void 0)throw X;if(W)throw W.reason}function H8(){let O=l6(),$=[];for(let Z of Object.keys(O)){let J=O[Z];if(!J)continue;for(let Y of J){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;$.push(Y.address)}}return $}function D5(){return typeof globalThis.Bun<"u"}function M5(O,$){let Z=globalThis.Bun,J=(X)=>{try{return Z.serve({hostname:$.hostname,port:X,fetch:O.fetch,idleTimeout:0,websocket:s4})}catch(G){fO.error("Failed to start Bun server:",G);return}},Y=$.port===0?J(4096)??J(0):J($.port);if(!Y)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Y.url,port:Y.port,hostname:Y.hostname,stop:async()=>{Y.stop(!0)}}}function W8(O,$){return new Promise((Z,J)=>{let Y=c6(async(M,b)=>{let I=new AbortController,A=()=>{if(!I.signal.aborted)I.abort("client-disconnected")},f=()=>A(),L=()=>{if(!b.writableEnded)A()};if(M.once("aborted",f),b.once("close",L),M.aborted||b.destroyed)A();try{let R=new URL(M.url||"/",`http://${M.headers.host}`),P=new Headers;for(let[u,FO]of Object.entries(M.headers))if(FO)if(Array.isArray(FO))for(let y of FO)P.append(u,y);else P.set(u,FO);let k;if(M.method!=="GET"&&M.method!=="HEAD")k=(await Y8(M,I.signal,Q8(R.pathname)?o1:void 0)).toString();let _=new Request(R.toString(),{method:M.method,headers:P,body:k,signal:I.signal}),e=await O.fetch(_);if(b.statusCode=e.status,e.headers.forEach((u,FO)=>{b.setHeader(FO,u)}),e.body){let u=e.body.getReader(),FO=async()=>{let{done:y,value:SO}=await u.read();if(y){b.end();return}return b.write(SO),FO()};await FO()}else{let u=await e.text();b.end(u)}}catch(R){if(I.signal.aborted)return;if(R instanceof r1){b.statusCode=400,b.setHeader("content-type","application/json; charset=UTF-8"),b.setHeader("connection","close"),b.end(JSON.stringify({error:{code:"invalid_session_surface_request",message:"Session surface request is invalid",retryable:!1}}));return}fO.error("[Server] Node request error:",R),b.statusCode=500,b.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}finally{M.off("aborted",f),b.off("close",L)}}),X=new O8({noServer:!0}),G=KO();w5(X,()=>G),Y.on("upgrade",(M,b,I)=>{let A;try{A=new URL(M.url||"/",`http://${M.headers.host}`)}catch{b.end(`HTTP/1.1 400 Bad Request\r
9
- Connection: close\r
10
- \r
11
- `);return}if(A.pathname==="/terminal/ws"){try{HO(A.searchParams.get("cwd")||G,"cwd")}catch{b.end(`HTTP/1.1 400 Bad Request\r
12
- Connection: close\r
13
- \r
14
- `);return}X.handleUpgrade(M,b,I,(f)=>{X.emit("connection",f,M)})}else b.destroy()});let W=(M)=>{return new Promise((b,I)=>{Y.once("error",(A)=>{if(A.code==="EADDRINUSE")I(A);else I(A)}),Y.listen(M,$.hostname,()=>{let A=Y.address();if(A&&typeof A==="object")b(A.port);else b(M)})})};(async()=>{let M;if($.port===0)try{M=await W(4096)}catch{M=await W(0)}else M=await W($.port);let b=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${M}`);Z({url:b,port:M,hostname:$.hostname,stop:async()=>{return new Promise((I)=>{X.close(()=>{Y.close(()=>I())})})}})})().catch(J)})}var j5;((FX)=>{let O,$,Z,J=async(A,f,L,R)=>{let P=[],k=L0,_=[];if($=void 0,F0===A)F0=void 0;if(D0===f)D0=void 0;if(M0===L)M0=void 0;if(X1=void 0,L0=void 0,R&&O===R)O=void 0,Z=void 0;try{_.push(A5(A,f,L,"server-startup-failure"))}catch(u){P.push(u)}try{k?.stop()}catch(u){P.push(u)}try{x5()}catch(u){P.push(u)}try{e4()}catch(u){P.push(u)}if(R)try{_.push(R.stop())}catch(u){P.push(u)}let e=await Promise.allSettled(_);for(let u of e)if(u.status==="rejected")P.push(u.reason);for(let u of P)fO.error("[Server] Startup cleanup failed:",u)},Y=(A,f,L,R)=>{if(O!==A)return Promise.resolve();if(Z)return Z;let P,k,_,e,u,FO,y,SO;try{FO=f?.shutdown("server-shutdown")}catch(XO){P=XO}try{y=L?.shutdown("server-shutdown")}catch(XO){k=XO}try{SO=R?.shutdown("server-shutdown")}catch(XO){_=XO}try{L0?.stop()}catch(XO){e=XO}try{x5()}catch(XO){u=XO}return Z=(async()=>{let XO=Promise.resolve().then(()=>A.stop()),[d,n,_O,CO]=await Promise.allSettled([FO??Promise.resolve(),y??Promise.resolve(),SO??Promise.resolve(),XO]),PO;try{e4()}catch(tO){PO=tO}let Z0=[P,d.status==="rejected"?d.reason:void 0,k,n.status==="rejected"?n.reason:void 0,_,_O.status==="rejected"?_O.reason:void 0,e,u,CO.status==="rejected"?CO.reason:void 0,PO].find((tO)=>tO!==void 0);if(Z0!==void 0){if(O===A)Z=void 0;throw Z0}if(O===A){if(O=void 0,$=void 0,F0===f)F0=void 0;if(D0===L)D0=void 0;if(M0===R)M0=void 0;X1=void 0,L0=void 0}fO.info("[Server] Blade server stopped")})(),Z};function X(){if(!$)$=w8();return $}FX.getApp=X;function G(A){Z$=A.cors??[];let f=X(),L=F0,R=D0,P=M0,k;try{if(D5())k=M5(f,A),O=k,Z=void 0,fO.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");X1?.().catch((_)=>{fO.warn("[Server] Failed to recover queued tasks:",_)}),L0?.start(),B5()}catch(_){throw J(L,R,P,k),_}if(!k)throw Error("Server transport failed to initialize");return{url:k.url,port:k.port,hostname:k.hostname,stop:()=>Y(k,L,R,P)}}FX.listen=G;async function W(A){Z$=A.cors??[];let f=X(),L=F0,R=D0,P=M0,k;try{if(D5())k=M5(f,A),O=k,fO.info(`[Server] Blade server listening on ${k.url} (Bun runtime)`);else k=await W8(f,A),O=k,fO.info(`[Server] Blade server listening on ${k.url} (Node.js runtime)`);Z=void 0;try{await X1?.()}catch(_){fO.warn("[Server] Failed to recover queued tasks:",_)}L0?.start(),B5()}catch(_){throw await J(L,R,P,k),_}if(!k)throw Error("Server transport failed to initialize");return{url:k.url,port:k.port,hostname:k.hostname,stop:()=>Y(k,L,R,P)}}FX.listenAsync=W;function B(){return O!==void 0}FX.isRunning=B;function M(){return F0?.getCoordinationStats()}FX.getSessionCoordinationStatsForTests=M;function b(){return D0?.getStats()}FX.getSessionSurfaceStatsForTests=b;function I(){return{global:M0?.getSseConnectionStats(),session:F0?.getSseConnectionStats()}}FX.getSseConnectionStatsForTests=I})(j5||={});export{F8 as a,_8 as b,H8 as c,j5 as d};