blade-code 0.10.36 → 0.10.37

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 (84) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-qvdcesry.js → chunk-0dw58ycv.js} +2 -2
  3. package/dist/{chunk-ekzck3x7.js → chunk-0e4nc00e.js} +1 -1
  4. package/dist/{chunk-7c5tnz4y.js → chunk-0nvc6y56.js} +1 -1
  5. package/dist/chunk-15w4crsc.js +1 -0
  6. package/dist/{chunk-95n8g52h.js → chunk-232bcv23.js} +1 -1
  7. package/dist/{chunk-acw8q8w9.js → chunk-46r1m8yn.js} +1 -1
  8. package/dist/chunk-4mpx8rad.js +1 -0
  9. package/dist/{chunk-e23sz81n.js → chunk-5cjy9yj1.js} +1 -1
  10. package/dist/chunk-5ckfx738.js +1 -0
  11. package/dist/{chunk-1raz6s2b.js → chunk-61h0d0gq.js} +2 -2
  12. package/dist/chunk-73pqjvxk.js +1 -0
  13. package/dist/chunk-8bczq0xe.js +1 -0
  14. package/dist/{chunk-s4enbe93.js → chunk-8pcfmzq0.js} +36 -36
  15. package/dist/{chunk-y990fa4r.js → chunk-9hjhbsna.js} +41 -41
  16. package/dist/{chunk-6jpspf3v.js → chunk-ahkpjvaq.js} +1 -1
  17. package/dist/{chunk-qxvk42rf.js → chunk-ak37gg0n.js} +1 -1
  18. package/dist/{chunk-g510tpqt.js → chunk-asqah231.js} +1 -1
  19. package/dist/{chunk-phgqzja3.js → chunk-atdb1pks.js} +1 -1
  20. package/dist/{chunk-gy8esxaa.js → chunk-b6ve4vyt.js} +2 -2
  21. package/dist/{chunk-2mvp3rqw.js → chunk-cm4t4cz6.js} +2 -2
  22. package/dist/{chunk-6gcmfvfj.js → chunk-d63dczf8.js} +1 -1
  23. package/dist/{chunk-q15qd9x4.js → chunk-dgks1che.js} +1 -1
  24. package/dist/chunk-e6frdh2s.js +1 -0
  25. package/dist/{chunk-4bbnytq5.js → chunk-e6ttz45s.js} +1 -1
  26. package/dist/{chunk-n4555gej.js → chunk-e8wpd0s4.js} +1 -1
  27. package/dist/{chunk-xrhtwcd0.js → chunk-fj6frvhd.js} +1 -1
  28. package/dist/chunk-fjpqxdct.js +1 -0
  29. package/dist/{chunk-m2w03hpc.js → chunk-fqcf0n0h.js} +1 -1
  30. package/dist/{chunk-0m4s8r87.js → chunk-g5429yjs.js} +3 -3
  31. package/dist/{chunk-95k17p11.js → chunk-gh0vdddb.js} +1 -1
  32. package/dist/chunk-jd764yqg.js +5 -0
  33. package/dist/{chunk-8ft7j7aw.js → chunk-jsd6d2f5.js} +1 -1
  34. package/dist/{chunk-4s0c6tkd.js → chunk-jtjcg93t.js} +1 -1
  35. package/dist/chunk-jtv91ez8.js +2 -0
  36. package/dist/{chunk-cnctwxqn.js → chunk-jz6esh56.js} +1 -1
  37. package/dist/{chunk-250vpvr5.js → chunk-kw543czm.js} +1 -1
  38. package/dist/{chunk-0dj2qm8a.js → chunk-m0a2zdm8.js} +1 -1
  39. package/dist/chunk-m377j9bs.js +1 -0
  40. package/dist/chunk-mznx9gg6.js +1 -0
  41. package/dist/{chunk-09qkatb5.js → chunk-njb4rjhs.js} +1 -1
  42. package/dist/{chunk-qwrdss51.js → chunk-q0mwwhpw.js} +3 -3
  43. package/dist/{chunk-hq1wrf1g.js → chunk-qavfq2vp.js} +1 -1
  44. package/dist/{chunk-y9nq48st.js → chunk-qc5qwgpt.js} +2 -2
  45. package/dist/chunk-qzn3rb8r.js +1 -0
  46. package/dist/{chunk-cc7dmst6.js → chunk-r48jmc74.js} +2 -2
  47. package/dist/{chunk-rshbnfr8.js → chunk-r9pz4z1p.js} +3 -3
  48. package/dist/{chunk-5xc50n8e.js → chunk-rj1z55m8.js} +1 -1
  49. package/dist/{chunk-9g6rzbcv.js → chunk-rtzd076h.js} +1 -1
  50. package/dist/chunk-s3xfr72w.js +6 -0
  51. package/dist/{chunk-m6dh31kb.js → chunk-tczrjn95.js} +2 -2
  52. package/dist/{chunk-99ywfge1.js → chunk-v2wka1pq.js} +1 -1
  53. package/dist/chunk-vk3e2w5h.js +44 -0
  54. package/dist/chunk-vxxhd72z.js +1 -0
  55. package/dist/{chunk-ck5tvxkj.js → chunk-x4yfhp8j.js} +1 -1
  56. package/dist/chunk-xfrdwxde.js +1 -0
  57. package/dist/chunk-xsew6530.js +6 -0
  58. package/dist/{chunk-1t8ebwsp.js → chunk-y5jxkynb.js} +1 -1
  59. package/dist/web/assets/{ChatView-Dx9j7CGg.js → ChatView-BB4nYdEf.js} +12 -12
  60. package/dist/web/assets/{CodeBlockHighlighter-CZADKR6S.js → CodeBlockHighlighter-CAFugWXU.js} +1 -1
  61. package/dist/web/assets/{FilePreview-BOIDa_oJ.js → FilePreview-O5aDfFS4.js} +1 -1
  62. package/dist/web/assets/{MarkdownRenderer-DXsfHVUX.js → MarkdownRenderer-C_qekwq_.js} +3 -3
  63. package/dist/web/assets/{SettingsModal-lQveNhC6.js → SettingsModal-FADlD0Da.js} +1 -1
  64. package/dist/web/assets/{TaskSwitcher-BSrmpJ2u.js → TaskSwitcher-D3k3tRpI.js} +1 -1
  65. package/dist/web/assets/{TerminalPanel-BFre9Shc.js → TerminalPanel-DBmKVVbI.js} +1 -1
  66. package/dist/web/assets/{index-DGZjm9wT.js → index-CMIW4J1Q.js} +3 -3
  67. package/dist/web/index.html +1 -1
  68. package/package.json +1 -1
  69. package/dist/chunk-3pxn6gcj.js +0 -1
  70. package/dist/chunk-4f1g8f6q.js +0 -1
  71. package/dist/chunk-4vq34v09.js +0 -5
  72. package/dist/chunk-515mkr66.js +0 -44
  73. package/dist/chunk-5c5qh3ab.js +0 -1
  74. package/dist/chunk-5vkxcjn1.js +0 -1
  75. package/dist/chunk-738a282r.js +0 -1
  76. package/dist/chunk-8m87dnk2.js +0 -1
  77. package/dist/chunk-e5yage6p.js +0 -1
  78. package/dist/chunk-hh158y4e.js +0 -6
  79. package/dist/chunk-j2tmdkmw.js +0 -1
  80. package/dist/chunk-psgt2pq7.js +0 -6
  81. package/dist/chunk-q3r0zfec.js +0 -1
  82. package/dist/chunk-rv6kca90.js +0 -1
  83. package/dist/chunk-ve7kp9rr.js +0 -1
  84. package/dist/chunk-xf2kjb9a.js +0 -1
@@ -1,8 +1,8 @@
1
- import{j as n4,k as t4}from"./chunk-qxvk42rf.js";import{l as h$}from"./chunk-4bbnytq5.js";import{s as k0}from"./chunk-95n8g52h.js";import{t as L4,u as S1,v as f1,w as y1,x as n0,y as m1}from"./chunk-q15qd9x4.js";import{$ as u4,A as zO,D as D4,E as Y$,F as V1,G as S$,H as $1,I as T0,J as O1,K as r0,L as F$,O as A$,P as M$,R as _4,S as B4,T as S4,U as f4,V as y4,W as m4,X as h4,Y as g4,Z as v4,_ as p4,aa as o4,da as MO,ia as KO}from"./chunk-0m4s8r87.js";import{la as o1,ra as N0}from"./chunk-7c5tnz4y.js";import{Aa as WO,Ba as N1,Ca as FO,Da as d0,Ea as s4,Fa as e4,Ga as $O,Ha as M4,Ia as E4,Ja as T4,Ka as k1,La as D1,ta as l$,wa as NO,xa as GO,ya as w4,za as A4}from"./chunk-95k17p11.js";import{Sa as I0,Ta as h,Va as j,Wa as H4,ib as e$,rb as p0}from"./chunk-y990fa4r.js";import{Ab as V4}from"./chunk-5cgyevqj.js";import{$b as L$,Tb as N4,Vb as f$,ac as Y1,bc as w$,dc as G4,jc as W4,kc as F4,mc as O$,pc as t$,uc as U4,vc as r$,wc as s$,xc as C}from"./chunk-6gcmfvfj.js";import{Fd as _0,ud as $0,yd as s1}from"./chunk-e23sz81n.js";import{Gd as n$}from"./chunk-atsw605q.js";import{Sd as z4}from"./chunk-3rjmkaey.js";import{Ud as P$}from"./chunk-acw8q8w9.js";import{be as ZO,ce as YO,fe as P4,je as G$,ke as W$,oe as W0}from"./chunk-9g6rzbcv.js";import{ye as e1,ze as K4}from"./chunk-zwt7f9ab.js";import{De as l1,Ee as s0}from"./chunk-cc7dmst6.js";import{We as a1,nf as c1,yf as N$}from"./chunk-515mkr66.js";import{Bf as m,Df as D,Gf as V0}from"./chunk-93jx06kq.js";import{If as y$}from"./chunk-thstqcg3.js";import{Nf as g}from"./chunk-6360fg4j.js";import{Rf as d}from"./chunk-qvdcesry.js";import{Xf as g0}from"./chunk-2mvp3rqw.js";import{Zf as t1,_f as x4,ag as r1,bg as X4}from"./chunk-g510tpqt.js";import{dg as t0}from"./chunk-gy8esxaa.js";import{ig as U1}from"./chunk-m6dh31kb.js";import{ng as C$,rg as g1}from"./chunk-y9nq48st.js";import{ug as G1}from"./chunk-4s0c6tkd.js";var C5={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 k5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as H1,readFileSync as q$}from"node:fs";import{createServer as X5}from"node:http";import{networkInterfaces as z5}from"node:os";import{dirname as K5,extname as V5,join as y0}from"node:path";import{fileURLToPath as N5}from"node:url";import{brotliCompressSync as G5,gzipSync as W5,constants as F5}from"node:zlib";import{Hono as U5}from"hono";import{cors as D5}from"hono/cors";import{WebSocketServer as H5}from"ws";var a0=d("Service"),PO=30000,SO=new Set(["completed","failed","cancelled","interrupted"]);class c${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor($){this.dispatch=$.dispatch,this.store=$.store??k1.getInstance(),this.tickMs=$.tickMs??PO}start(){if(this.timer)return;a0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=j.subscribe(($)=>{if($.type!=="task.status")return;let O=$.properties.taskStatus;if(typeof O!=="string"||!SO.has(O))return;this.recordTerminalStatus($.sessionId,O,typeof $.properties.taskStatusReason==="string"?$.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,a0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick($=new Date){if(this.ticking)return;this.ticking=!0;try{let O=await this.store.list();for(let J of O)await this.evaluate(J,$)}catch(O){a0.warn("[TaskScheduler] Tick failed:",O)}finally{this.ticking=!1}}async evaluate($,O){if(!$.enabled)return;if(this.inFlight.has($.id))return;if($.expiresAt&&new Date($.expiresAt).getTime()<=O.getTime()){await this.store.update($.id,{enabled:!1,nextRunAt:null}),a0.info(`[TaskScheduler] Schedule ${$.id} expired; disabled`);return}if(!$.nextRunAt)return;if(!(new Date($.nextRunAt).getTime()<=O.getTime()))return;await this.fire($,O)}async fire($,O=new Date,J={}){if(this.inFlight.has($.id))throw Error(`Schedule ${$.id} is already dispatching`);this.inFlight.add($.id);let Z=O.toISOString();try{let Y=await this.dispatch({prompt:$.prompt,title:$.title??fO($),sourceProjectPath:$.projectPath,isolation:$.dispatch.isolation??"worktree",permissionMode:$.dispatch.permissionMode??"default",modelId:$.dispatch.modelId,reasoningEffort:$.dispatch.reasoningEffort,serviceTier:$.dispatch.serviceTier,responseVerbosity:$.dispatch.responseVerbosity,communicationStyle:$.dispatch.communicationStyle}),z=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:l$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastRunSessionId:Y.session.sessionId,lastStatus:Y.status,lastError:void 0,runCount:$.runCount+1,nextRunAt:z?z.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled}),j.publish({sessionId:Y.session.sessionId,projectPath:$.projectPath},"schedule.fired",{scheduleId:$.id,firedAt:Z,sessionId:Y.session.sessionId,runId:Y.runId,status:Y.status}),a0.info(`[TaskScheduler] Fired schedule ${$.id} -> session ${Y.session.sessionId} (${Y.status})`)}catch(Y){let z=Y instanceof Error?Y.message:String(Y);a0.warn(`[TaskScheduler] Schedule ${$.id} dispatch failed:`,Y);let X=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:l$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastStatus:"error",lastError:z,nextRunAt:X?X.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled})}finally{this.inFlight.delete($.id)}}async recordTerminalStatus($,O,J){let Y=(await this.store.list()).find((z)=>z.lastRunSessionId===$);if(!Y)return;await this.store.update(Y.id,{lastStatus:O,...J?{lastError:J}:{lastError:void 0}})}}function fO($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class e extends Error{code;statusCode;constructor($,O,J=500){super(O);this.code=$;this.statusCode=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class f extends e{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class _ extends e{constructor($){super("BAD_REQUEST",$,400)}}class k extends e{constructor($){super("CONFLICT",$,409)}}class o0 extends e{constructor($){super("TOO_MANY_REQUESTS",$,429)}}class h0 extends e{constructor($="Server is shutting down"){super("SERVICE_UNAVAILABLE",$,503)}}class H0 extends e{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class a extends e{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var g5=D.Object({error:D.Object({code:D.String(),message:D.String()})});import{Hono as yO}from"hono";var i$=d("Service"),mO=D.Object({updates:D.Record(D.String(),D.Any()),options:D.Optional(D.Object({scope:D.Optional(V0(["local","project","global"])),immediate:D.Optional(D.Boolean())}))});function hO($){return{currentModelId:$.currentModelId,permissionMode:$.permissionMode,language:$.language,codeTheme:$.codeTheme,uiTheme:$.uiTheme,autoSaveSessions:$.autoSaveSessions,notifyBuild:$.notifyBuild,notifyErrors:$.notifyErrors,notifySounds:$.notifySounds,privacyTelemetry:$.privacyTelemetry,privacyCrash:$.privacyCrash,communicationStyle:$.communicationStyle,maxConcurrentTasks:$.maxConcurrentTasks,maxQueuedTasks:$.maxQueuedTasks}}var I1=()=>{let $=new yO;return $.get("/",async(O)=>{try{let J=$0();return O.json(J?hO(J):{})}catch(J){return i$.error("[ConfigRoutes] Failed to get config:",J),O.json({})}}),$.put("/",async(O)=>{try{let J=await O.req.json(),Z=m(mO,J);if(!Z.success)throw new _("Invalid config update format");let{updates:Y,options:z}=Z.data;return await _0().updateConfig(Y,z),O.json({success:!0,updates:Y})}catch(J){throw i$.error("[ConfigRoutes] Failed to update config:",J),J}}),$.get("/permissions",async(O)=>{try{let J=$0();return O.json(J?.permissions||{})}catch(J){return i$.error("[ConfigRoutes] Failed to get permissions:",J),O.json({})}}),$};import{Hono as gO}from"hono";import{streamSSE as vO}from"hono/streaming";function P1($){let O="";if($.id!==void 0)O+=`id: ${$.id}
1
+ import{j as n4,k as t4}from"./chunk-ak37gg0n.js";import{l as h$}from"./chunk-e6ttz45s.js";import{s as k0}from"./chunk-232bcv23.js";import{t as L4,u as S1,v as f1,w as y1,x as n0,y as m1}from"./chunk-dgks1che.js";import{$ as u4,A as zO,D as D4,E as Y$,F as V1,G as S$,H as $1,I as T0,J as O1,K as r0,L as F$,O as A$,P as M$,R as _4,S as B4,T as S4,U as f4,V as y4,W as m4,X as h4,Y as g4,Z as v4,_ as p4,aa as o4,da as MO,ia as KO}from"./chunk-g5429yjs.js";import{la as o1,ra as N0}from"./chunk-0nvc6y56.js";import{Aa as WO,Ba as N1,Ca as FO,Da as d0,Ea as s4,Fa as e4,Ga as $O,Ha as M4,Ia as E4,Ja as T4,Ka as k1,La as D1,ta as l$,wa as NO,xa as GO,ya as w4,za as A4}from"./chunk-gh0vdddb.js";import{Sa as I0,Ta as h,Va as j,Wa as H4,ib as e$,rb as p0}from"./chunk-9hjhbsna.js";import{Ab as V4}from"./chunk-5cgyevqj.js";import{$b as L$,Tb as N4,Vb as f$,ac as Y1,bc as w$,dc as G4,jc as W4,kc as F4,mc as O$,pc as t$,uc as U4,vc as r$,wc as s$,xc as C}from"./chunk-d63dczf8.js";import{Fd as _0,ud as $0,yd as s1}from"./chunk-5cjy9yj1.js";import{Gd as n$}from"./chunk-atsw605q.js";import{Sd as z4}from"./chunk-3rjmkaey.js";import{Ud as P$}from"./chunk-46r1m8yn.js";import{be as ZO,ce as YO,fe as P4,je as G$,ke as W$,oe as W0}from"./chunk-rtzd076h.js";import{ye as e1,ze as K4}from"./chunk-zwt7f9ab.js";import{De as l1,Ee as s0}from"./chunk-r48jmc74.js";import{We as a1,nf as c1,yf as N$}from"./chunk-vk3e2w5h.js";import{Bf as m,Df as D,Gf as V0}from"./chunk-93jx06kq.js";import{If as y$}from"./chunk-thstqcg3.js";import{Nf as g}from"./chunk-6360fg4j.js";import{Yf as d}from"./chunk-0dw58ycv.js";import{cg as g0}from"./chunk-cm4t4cz6.js";import{eg as t1,fg as x4,hg as r1,ig as X4}from"./chunk-asqah231.js";import{kg as t0}from"./chunk-b6ve4vyt.js";import{pg as U1}from"./chunk-tczrjn95.js";import{ug as C$,yg as g1}from"./chunk-qc5qwgpt.js";import{Bg as G1}from"./chunk-jtjcg93t.js";var C5={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 k5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as H1,readFileSync as q$}from"node:fs";import{createServer as X5}from"node:http";import{networkInterfaces as z5}from"node:os";import{dirname as K5,extname as V5,join as y0}from"node:path";import{fileURLToPath as N5}from"node:url";import{brotliCompressSync as G5,gzipSync as W5,constants as F5}from"node:zlib";import{Hono as U5}from"hono";import{cors as D5}from"hono/cors";import{WebSocketServer as H5}from"ws";var a0=d("Service"),PO=30000,SO=new Set(["completed","failed","cancelled","interrupted"]);class c${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor($){this.dispatch=$.dispatch,this.store=$.store??k1.getInstance(),this.tickMs=$.tickMs??PO}start(){if(this.timer)return;a0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=j.subscribe(($)=>{if($.type!=="task.status")return;let O=$.properties.taskStatus;if(typeof O!=="string"||!SO.has(O))return;this.recordTerminalStatus($.sessionId,O,typeof $.properties.taskStatusReason==="string"?$.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,a0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick($=new Date){if(this.ticking)return;this.ticking=!0;try{let O=await this.store.list();for(let J of O)await this.evaluate(J,$)}catch(O){a0.warn("[TaskScheduler] Tick failed:",O)}finally{this.ticking=!1}}async evaluate($,O){if(!$.enabled)return;if(this.inFlight.has($.id))return;if($.expiresAt&&new Date($.expiresAt).getTime()<=O.getTime()){await this.store.update($.id,{enabled:!1,nextRunAt:null}),a0.info(`[TaskScheduler] Schedule ${$.id} expired; disabled`);return}if(!$.nextRunAt)return;if(!(new Date($.nextRunAt).getTime()<=O.getTime()))return;await this.fire($,O)}async fire($,O=new Date,J={}){if(this.inFlight.has($.id))throw Error(`Schedule ${$.id} is already dispatching`);this.inFlight.add($.id);let Z=O.toISOString();try{let Y=await this.dispatch({prompt:$.prompt,title:$.title??fO($),sourceProjectPath:$.projectPath,isolation:$.dispatch.isolation??"worktree",permissionMode:$.dispatch.permissionMode??"default",modelId:$.dispatch.modelId,reasoningEffort:$.dispatch.reasoningEffort,serviceTier:$.dispatch.serviceTier,responseVerbosity:$.dispatch.responseVerbosity,communicationStyle:$.dispatch.communicationStyle}),z=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:l$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastRunSessionId:Y.session.sessionId,lastStatus:Y.status,lastError:void 0,runCount:$.runCount+1,nextRunAt:z?z.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled}),j.publish({sessionId:Y.session.sessionId,projectPath:$.projectPath},"schedule.fired",{scheduleId:$.id,firedAt:Z,sessionId:Y.session.sessionId,runId:Y.runId,status:Y.status}),a0.info(`[TaskScheduler] Fired schedule ${$.id} -> session ${Y.session.sessionId} (${Y.status})`)}catch(Y){let z=Y instanceof Error?Y.message:String(Y);a0.warn(`[TaskScheduler] Schedule ${$.id} dispatch failed:`,Y);let X=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:l$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastStatus:"error",lastError:z,nextRunAt:X?X.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled})}finally{this.inFlight.delete($.id)}}async recordTerminalStatus($,O,J){let Y=(await this.store.list()).find((z)=>z.lastRunSessionId===$);if(!Y)return;await this.store.update(Y.id,{lastStatus:O,...J?{lastError:J}:{lastError:void 0}})}}function fO($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class e extends Error{code;statusCode;constructor($,O,J=500){super(O);this.code=$;this.statusCode=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class f extends e{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class _ extends e{constructor($){super("BAD_REQUEST",$,400)}}class k extends e{constructor($){super("CONFLICT",$,409)}}class o0 extends e{constructor($){super("TOO_MANY_REQUESTS",$,429)}}class h0 extends e{constructor($="Server is shutting down"){super("SERVICE_UNAVAILABLE",$,503)}}class H0 extends e{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class a extends e{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var g5=D.Object({error:D.Object({code:D.String(),message:D.String()})});import{Hono as yO}from"hono";var i$=d("Service"),mO=D.Object({updates:D.Record(D.String(),D.Any()),options:D.Optional(D.Object({scope:D.Optional(V0(["local","project","global"])),immediate:D.Optional(D.Boolean())}))});function hO($){return{currentModelId:$.currentModelId,permissionMode:$.permissionMode,language:$.language,codeTheme:$.codeTheme,uiTheme:$.uiTheme,autoSaveSessions:$.autoSaveSessions,notifyBuild:$.notifyBuild,notifyErrors:$.notifyErrors,notifySounds:$.notifySounds,privacyTelemetry:$.privacyTelemetry,privacyCrash:$.privacyCrash,communicationStyle:$.communicationStyle,maxConcurrentTasks:$.maxConcurrentTasks,maxQueuedTasks:$.maxQueuedTasks}}var I1=()=>{let $=new yO;return $.get("/",async(O)=>{try{let J=$0();return O.json(J?hO(J):{})}catch(J){return i$.error("[ConfigRoutes] Failed to get config:",J),O.json({})}}),$.put("/",async(O)=>{try{let J=await O.req.json(),Z=m(mO,J);if(!Z.success)throw new _("Invalid config update format");let{updates:Y,options:z}=Z.data;return await _0().updateConfig(Y,z),O.json({success:!0,updates:Y})}catch(J){throw i$.error("[ConfigRoutes] Failed to update config:",J),J}}),$.get("/permissions",async(O)=>{try{let J=$0();return O.json(J?.permissions||{})}catch(J){return i$.error("[ConfigRoutes] Failed to get permissions:",J),O.json({})}}),$};import{Hono as gO}from"hono";import{streamSSE as vO}from"hono/streaming";function P1($){let O="";if($.id!==void 0)O+=`id: ${$.id}
2
2
  `;if($.event!==void 0)O+=`event: ${$.event}
3
3
  `;for(let J of $.data.split(/\r\n|\r|\n/))O+=`data: ${J}
4
4
  `;if($.retry!==void 0)O+=`retry: ${$.retry}
5
5
  `;return O+=`
6
- `,Buffer.byteLength(O)}class K${serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor($){this.maxPendingItems=$.maxPendingItems??S1,this.maxPendingBytes=$.maxPendingBytes??f1,this.serial=new m1({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:$.writeTimeoutMs??y1,sizeOf:P1,write:$.write,onFailure:(O)=>{this.failure=O,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,$.onFailure?.(O)}})}async writeInitial($){await this.offerDirect($)}observe($,O){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer($,O);return}this.offerLive($,O)}async writeReplay($,O){if(!Number.isSafeInteger(O)||O<=0)throw this.fail(new n0("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if(O<=this.highestReplaySequence)return;await this.offerDirect($),this.highestReplaySequence=O,this.highestDeliveredSequence=O}finishInitialization($){if(this.phase!=="buffering")return;let O=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let J=$.replayed?O.filter((Y)=>Y.sequence!==void 0&&Y.sequence>this.highestReplaySequence).sort((Y,z)=>Y.sequence-z.sequence||Y.order-z.order):O.sort((Y,z)=>Y.order-z.order),Z;for(let Y of J){if($.replayed&&Y.sequence!==void 0&&Y.sequence===Z)continue;if(this.offerLive(Y.message,Y.sequence),this.serial.stats().closed)return;Z=Y.sequence}}offerHeartbeat($){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive($),!this.serial.stats().closed}async flush(){await this.serial.flush()}close($){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close($)}stats(){let $=this.serial.stats();return{closed:this.phase==="closed",pendingItems:$.pendingItems+this.buffered.length,pendingBytes:$.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer($,O){let J=P1($),Z=this.serial.stats();if(J>this.maxPendingBytes){this.fail(new n0("oversized",`SSE frame requires ${J} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:Z.pendingItems+this.buffered.length,pendingBytes:Z.pendingBytes+this.bufferedBytes}));return}if(Z.pendingItems+this.buffered.length>=this.maxPendingItems||Z.pendingBytes+this.bufferedBytes+J>this.maxPendingBytes){this.fail(new n0("overflow","SSE initialization buffer limit exceeded",{pendingItems:Z.pendingItems+this.buffered.length,pendingBytes:Z.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:$,bytes:J,sequence:O,order:this.nextOrder}),this.bufferedBytes+=J}offerLive($,O){if(O!==void 0){if(O<=this.highestReplaySequence)return;if(O<=this.highestDeliveredSequence){this.fail(new n0("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=O}if(!this.serial.offer($).accepted)this.phase="closed"}async offerDirect($){if(this.phase==="closed")throw this.currentFailure();let O=this.serial.offer($);if(!O.accepted)throw this.phase="closed",O.error;await O.completion}fail($){this.serial.close($)}currentFailure(){return this.failure??new n0("closed","SSE egress is closed")}}var pO=15000,uO=d("Service"),dO=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),lO=new Set(["queued","running","completed","failed","cancelled","interrupted"]);function cO($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$,J=["changedFiles","additions","deletions","commits"];if(J.some((Z)=>typeof O[Z]!=="number"||!Number.isInteger(O[Z])||O[Z]<0))return;return Object.fromEntries(J.map((Z)=>[Z,O[Z]]))}function V$($,O){return typeof $==="number"&&Number.isInteger($)&&$>=O?$:void 0}function iO($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$;if(!["applied","discarded","conflicted"].includes(String(O.status))||typeof O.updatedAt!=="string")return;return{status:O.status,updatedAt:O.updatedAt,...typeof O.sourceCommit==="string"?{sourceCommit:O.sourceCommit}:{},...V$(O.changedFiles,0)!==void 0?{changedFiles:O.changedFiles}:{},...typeof O.message==="string"?{message:O.message}:{}}}var h1=()=>{let $=new gO;return $.get("/",(O)=>vO(O,async(J)=>{let Z,Y,z=!1,X,F,b=new Promise((G)=>{F=G}),B=()=>{if(Y!==void 0)clearInterval(Y),Y=void 0;Z?.(),Z=void 0},M=(G)=>{if(z)return;z=!0,B(),X?.close(G),F()};J.onAbort(M),X=new K$({write:async(G)=>{await J.writeSSE(G)},onFailure:(G)=>{uO.warn(`[EventRoutes] SSE egress closed: kind=${G.kind} pendingItems=${G.pendingItems??0} pendingBytes=${G.pendingBytes??0}`),M(G)}});let E=(G,u)=>{X?.observe({data:JSON.stringify({type:G,properties:u})})};Z=j.subscribe((G)=>{if(!dO.has(G.type))return;if(G.type==="permission.asked"||G.type==="question.required"||G.type==="elicitation.required"){let v=G.properties.requestId;if(typeof v!=="string"||!v)return;E("interaction.pending",{sessionId:G.sessionId,projectPath:G.projectPath,interactionType:G.type==="question.required"?"question":G.type==="elicitation.required"?"elicitation":"permission",requestId:v});return}if(G.type==="interaction.resolved"){let v=G.properties.requestId;if(typeof v!=="string"||!v)return;E(G.type,{sessionId:G.sessionId,projectPath:G.projectPath,requestId:v});return}if(G.type==="session.created"||G.type==="session.deleted"){E(G.type,{sessionId:G.sessionId,projectPath:G.projectPath});return}if(G.type==="session.updated"){let v=G.properties.title;if(typeof v!=="string"||!v.trim())return;E(G.type,{sessionId:G.sessionId,projectPath:G.projectPath,title:v});return}if(G.type==="task.delivery"){let v=iO(G.properties.taskDelivery);if(!v)return;E(G.type,{sessionId:G.sessionId,projectPath:G.projectPath,taskDelivery:v,...G.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof G.properties.updatedAt==="string"?{updatedAt:G.properties.updatedAt}:{}});return}if(G.type==="schedule.fired"){let v=G.properties.scheduleId,m0=G.properties.firedAt;if(typeof v!=="string"||typeof m0!=="string")return;E(G.type,{scheduleId:v,firedAt:m0,sessionId:G.sessionId,projectPath:G.projectPath,...typeof G.properties.runId==="string"?{runId:G.properties.runId}:{},...typeof G.properties.status==="string"?{status:G.properties.status}:{}});return}let u=G.properties.taskStatus;if(typeof u!=="string"||!lO.has(u))return;let Y0=cO(G.properties.taskDiffStat),q=V$(G.properties.taskQueuePosition,1),t=V$(G.properties.taskQueueDepth,0),I=V$(G.properties.taskConcurrencyLimit,1),O0=V$(G.properties.taskInFlight,0);E(G.type,{sessionId:G.sessionId,projectPath:G.projectPath,taskStatus:u,...typeof G.properties.taskStatusReason==="string"?{taskStatusReason:G.properties.taskStatusReason}:{},...G.properties.taskFailure&&typeof G.properties.taskFailure==="object"?{taskFailure:G.properties.taskFailure}:{},...typeof G.properties.taskStartedAt==="string"?{taskStartedAt:G.properties.taskStartedAt}:{},...typeof G.properties.taskCompletedAt==="string"?{taskCompletedAt:G.properties.taskCompletedAt}:{},...typeof G.properties.updatedAt==="string"?{updatedAt:G.properties.updatedAt}:{},...Y0?{taskDiffStat:Y0}:{},...q!==void 0?{taskQueuePosition:q}:{},...t!==void 0?{taskQueueDepth:t}:{},...I!==void 0?{taskConcurrencyLimit:I}:{},...O0!==void 0?{taskInFlight:O0}:{}})});try{if(J.aborted||z)return;if(await X.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),J.aborted||z)return;if(X.finishInitialization({replayed:!1}),J.aborted||z)return;Y=setInterval(()=>{if(J.aborted||z)return;X?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},pO),await b}finally{M()}})),$};import{Hono as aO}from"hono";var v1=()=>{let $=new aO;return $.get("/health",(O)=>{return O.json({healthy:!0,version:t0()})}),$.get("/info",(O)=>{let J=g(),Z=$0();if(Z)r0.configure(Z.maxConcurrentTasks,Z.maxQueuedTasks);return O.json({version:t0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:J,gitBranch:g1(J),taskAdmission:r0.getStats()})}),$};import p1 from"node:path";import{Hono as oO}from"hono";var nO=D.Object({projectPath:D.String({minLength:1}),action:V0(["trust","revoke"]),expectedDigest:D.Optional(D.String())}),tO=D.Object({projectPath:D.String({minLength:1}),sessionId:D.String({minLength:1}),enabled:D.Boolean()});function a$($){if(!$||!p1.isAbsolute($))throw new _("projectPath must be absolute");return p1.resolve($)}function u1($){if(!$)throw new _("sessionId is required");try{C$($)}catch(O){throw new _(O instanceof Error?O.message:"sessionId is invalid")}return $}async function j$($){let O=a$($),J=$0()?.hooks??c1.hooks,Z=await N$.getInstance().loadWorkspaceHooks(O,J,{includeBaseForCurrentWorkspace:!1});await W0(O),W$(O);let Y=s0.getInstance();return Y.loadConfig(Z,O),await G$(O),Y.getConfig(O)}function d1($,O){let J=s0.getInstance(),Z=J.getConfig(O).enabled,Y=J.isSessionPaused($,O);return{sessionId:$,projectPath:O,enabled:J.isSessionEnabled($,O),paused:Y,configEnabled:Z}}var i1=()=>{let $=new oO;return $.get("/trust",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return await j$(J),O.json(await s0.getInstance().getTrustStatus(J))}),$.post("/trust",async(O)=>{let J=m(nO,await O.req.json());if(!J.success)throw new _("Invalid hook trust request");let{projectPath:Z,action:Y,expectedDigest:z}=J.data;await j$(Z);let X=s0.getInstance(),F;try{F=Y==="trust"?await X.trustProject(Z,z):await X.revokeProjectTrust(Z)}catch(b){if(b instanceof l1)throw new k(b.message);throw b}return O.json(F)}),$.get("/session",async(O)=>{let J=a$(O.req.query("projectPath")),Z=u1(O.req.query("sessionId"));return await j$(J),O.json(d1(Z,J))}),$.post("/session",async(O)=>{let J=m(tO,await O.req.json());if(!J.success)throw new _("Invalid hook session request");let Z=a$(J.data.projectPath),Y=u1(J.data.sessionId);await j$(Z);let z=s0.getInstance();if(J.data.enabled)z.enableSession(Y,Z);else z.disableSession(Y,Z);return O.json(d1(Y,Z))}),$};import{Hono as rO}from"hono";var E0=d("Service");function sO($){try{return o1($)}catch{return[]}}function eO($){if(!k$($)||!k$($.reference)||!k$($.argument))throw Error("Invalid MCP completion request");let O=$.reference.type,J=O==="prompt"&&typeof $.reference.name==="string"?{type:"prompt",name:$.reference.name}:O==="resource"&&typeof $.reference.uri==="string"?{type:"resource",uri:$.reference.uri}:void 0;if(!J||typeof $.argument.name!=="string"||typeof $.argument.value!=="string")throw Error("Invalid MCP completion request");let Z;if($.context!==void 0){if(!k$($.context))throw Error("Invalid MCP completion context");Z=Object.create(null);for(let[Y,z]of Object.entries($.context)){if(typeof z!=="string")throw Error("Invalid MCP completion context");Z[Y]=z}}return{reference:J,argument:{name:$.argument.name,value:$.argument.value},...Z?{context:Z}:{}}}function k$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}async function C0($,O){let J=$0()?.mcpServers??{};for(let[Z,Y]of Object.entries(J)){if(O&&Z!==O)continue;if(!$.getServerStatus(Z))await $.registerServer(Z,Y,{connect:!1})}}var n1=()=>{let $=new rO;return $.get("/",async(O)=>{try{let J=N0.getInstance();await C0(J);let Z=J.getAllServers(),Y=await Promise.all(Array.from(Z.entries()).map(async([z,X])=>({id:z,name:z,status:X.status==="connected"?"connected":X.status==="reconnecting"?"reconnecting":X.status==="connecting"?"connecting":X.lastError?"error":"offline",endpoint:X.config.command?`${X.config.command} ${(X.config.args||[]).join(" ")}`.trim():X.config.url||"Unknown",description:`MCP server: ${z}`,tools:X.tools.map((F)=>F.name),completionSupported:X.client.completionSupported,tasks:X.client.tasks,resources:X.contentCatalog.resources,resourceTemplates:X.contentCatalog.resourceTemplates.map((F)=>({...F,variables:sO(F.uriTemplate)})),prompts:X.contentCatalog.prompts,connectedAt:X.connectedAt?.toISOString(),error:X.lastError?.message,recovery:X.recovery,logging:X.logging,instructions:X.instructions,oauthEnabled:X.client.oauthEnabled,oauthStatus:await X.client.getOAuthStatus()})));return O.json(Y)}catch(J){return E0.error("[McpRoutes] Failed to get MCP servers:",J),O.json({error:J instanceof Error?J.message:"Failed to get MCP servers"},500)}}),$.post("/:name/connect",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();return await C0(Z,J),await Z.connectServer(J),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to connect MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.post("/:name/disconnect",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();return await C0(Z,J),await Z.disconnectServer(J),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to disconnect MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.get("/:name/logs",async(O)=>{try{let J=O.req.param("name"),Z=Number(O.req.query("limit")??20),Y=Number(O.req.query("afterRevision")??0);if(!Number.isSafeInteger(Z)||Z<1||Z>100||!Number.isSafeInteger(Y)||Y<0)return O.json({error:"Invalid MCP log pagination"},400);let z=N0.getInstance();return await C0(z,J),O.json(z.getLogSnapshot(J,{limit:Z,afterRevision:Y}))}catch(J){return E0.error("[McpRoutes] Failed to get MCP logs:",J),O.json({error:J.message},500)}}),$.post("/:name/logging-level",async(O)=>{try{let J=O.req.param("name"),Z=await O.req.json();if(!a1(Z.level))return O.json({success:!1,error:"Invalid MCP logging level"},400);let Y=N0.getInstance();return await C0(Y,J),await Y.setServerLoggingLevel(J,Z.level),O.json({success:!0,level:Z.level})}catch(J){return E0.error("[McpRoutes] Failed to set MCP logging level:",J),O.json({success:!1,error:J.message},400)}}),$.post("/:name/complete",async(O)=>{try{let J=O.req.param("name"),Z=eO(await O.req.json()),Y=N0.getInstance();await C0(Y,J);let z=await Y.complete(J,Z);return O.json(z)}catch(J){return E0.error("[McpRoutes] Failed to complete MCP argument:",J),O.json({error:J.message},400)}}),$.post("/:name/oauth/login",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();await C0(Z,J);let Y=await Z.beginOAuthLogin(J);return O.json({success:!0,flowId:Y.flowId,authorizationUrl:Y.authorizationUrl},202)}catch(J){return E0.error("[McpRoutes] Failed to start MCP OAuth login:",J),O.json({success:!1,error:J.message},400)}}),$.post("/:name/oauth/logout",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();return await C0(Z,J),await Z.logoutOAuth(J),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to log out MCP OAuth:",J),O.json({success:!1,error:J.message},400)}}),$.delete("/:name",async(O)=>{try{let J=O.req.param("name");await N0.getInstance().unregisterServer(J);let Y=$0();if(Y?.mcpServers){let{[J]:z,...X}=Y.mcpServers;await _0().updateConfig({mcpServers:X})}return O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to delete MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.post("/",async(O)=>{try{let J=await O.req.json(),{name:Z,config:Y}=J;if(!Z||!Y)return O.json({success:!1,error:"Missing name or config"},400);await N0.getInstance().registerServer(Z,Y);let X=$0();return await _0().updateConfig({mcpServers:{...X?.mcpServers,[Z]:Y}}),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to add MCP server:",J),O.json({success:!1,error:J.message},500)}}),$};import{getSupportedThinkingLevels as $2}from"@earendil-works/pi-ai";import{Hono as O2}from"hono";var I$=d("Service");function J2($,O,J=e1.list()){return{id:$.id,displayName:$.displayName,provider:$.provider,model:$.model,overrides:$.overrides,fallbackModels:$.fallbackModels,contextWindow:O.contextWindow,maxTokens:O.maxTokens,reasoning:O.reasoning,supportedReasoningEfforts:$2(O),supportedServiceTiers:r1(O),supportedResponseVerbosities:t1(O),communicationStyles:J,input:O.input}}function Z2($){$4($.overrides);let O={displayName:$.displayName||void 0,overrides:$.overrides||void 0};if($.model)O.model=$.model;return O}function $4($){let O=$?.streamIdleTimeout;if(O!==void 0&&(!Number.isFinite(O)||O<1000))throw new _("streamIdleTimeout must be at least 1000ms")}var O4=()=>{let $=new O2;return $.get("/",async(O)=>{try{let J=$0();if(!J)throw Error("Config not initialized");let Z=O.get("directory")||g(),[Y,z]=await Promise.all([P$(Z,J),W0(Z)]),X=Y.config.models,F=X.find((E)=>E.id===Y.config.currentModelId)??X[0],b=Y.catalog,B=z.communicationStyles.list(),M=(E)=>J2(E,b.resolveConfig(E),B);return O.json({configured:X.map(M),current:F?M(F):null})}catch(J){I$.error("[ModelsRoutes] Failed to get models:",J);let Z=new a("Failed to get models");return O.json(Z.toObject(),500)}}),$.post("/",async(O)=>{let J=g0(),Z,Y;try{let z=await O.req.json(),{provider:X,displayName:F,model:b,overrides:B,apiKey:M,modelProvider:E}=z;if(!X||!b)throw new _("provider and model are required");$4(B);let G;if(E){if(E.id!==X)throw new _("modelProvider.id must match the model provider");if($0()?.modelProviders[X])throw new _(`model provider already exists: ${X}`);G={name:E.name,baseUrl:E.baseUrl,wireApi:E.wireApi,...E.apiKeyEnv?{apiKeyEnv:E.apiKeyEnv}:{}};try{J.registerModelProvider(X,G,[b]),Y=X}catch(q){throw new _(q instanceof Error?q.message:"Invalid model provider")}}else J.getModel(X,b);if(M?.trim()){if(await J.setApiKey(X,M.trim()),G)Z=X}let u={provider:X,displayName:F||void 0,model:b,overrides:B||void 0},Y0=G?await _0().addModelWithProvider(u,G):await _0().addModel(u);return O.json({success:!0,model:Y0})}catch(z){if(Z)await J.credentials.delete(Z);if(Y){let X=$0();J.configureModelProviders(X?.modelProviders??{},X?.models??[])}throw I$.error("[ModelsRoutes] Failed to add model:",z),z}}),$.put("/:modelId",async(O)=>{try{let J=O.req.param("modelId"),Z=await O.req.json(),{displayName:Y,overrides:z,model:X}=Z,F=s1(J);if(!F)throw new _("model config not found");if(X)g0().getModel(F.provider,X);return await _0().updateModel(J,Z2({displayName:Y,overrides:z,model:X})),O.json({success:!0})}catch(J){throw I$.error("[ModelsRoutes] Failed to update model:",J),J}}),$.delete("/:modelId",async(O)=>{try{let J=O.req.param("modelId");return await _0().removeModel(J),O.json({success:!0})}catch(J){throw I$.error("[ModelsRoutes] Failed to delete model:",J),J}}),$};import{Hono as w2}from"hono";import J4 from"node:path";import{Mutex as Z4}from"async-mutex";import{Hono as Y2}from"hono";import{streamSSE as Q2}from"hono/streaming";import{LRUCache as x2}from"lru-cache";import{nanoid as $$}from"nanoid";var y=d("Service"),X2=D.Object({title:D.Optional(D.String()),projectPath:D.Optional(D.String())}),z2=M4,K2=D.Object({title:D.Optional(D.String()),projectPath:D.Optional(D.String())}),V2=D.Object({projectPath:D.String()}),N2=D.Object({objective:D.String({minLength:1}),tokenBudget:D.Optional(D.Integer({minimum:1})),permissionMode:D.Optional(V0(["default","autoEdit","plan","yolo"]))}),G2=D.Union([D.Object({action:D.Literal("pause")}),D.Object({action:D.Literal("resume")}),D.Object({action:D.Literal("edit"),objective:D.String({minLength:1})})]),n=new Map,J$,q0=new Map,v0=new Map,b0=new Map,m$=new x2({max:100,ttl:1800000});function Y4($){return{sessionId:$.sessionId,projectPath:$.projectPath}}function G0($){if(!$)return;return q0.get($)??m$.get($)}function W2($){if(q0.get($.id)!==$)return;q0.delete($.id),m$.set($.id,$)}function F2($){q0.delete($),m$.delete($)}function F0($){return $?.status==="queued"||$?.status==="running"||$?.status==="waiting_permission"}function H$($,O="user-cancel"){if($.status==="cancelled"||$.status==="completed"||$.status==="failed")return!1;let J=$.pendingPermission;if($.pendingPermission=void 0,J?.resolve({approved:!1,reason:V4}),J)j.publish(Y4($),"interaction.resolved",{requestId:J.permissionId});return $.abortController.abort(O),$.status="cancelled",j.publish(Y4($),"run.cancelled",{runId:$.id}),!0}function q4($,O=!1){let{permissionId:J,details:Z}=$;if(Z.type==="askUserQuestion"&&Z.questions)return{type:"question.required",properties:{requestId:J,toolCallId:Z.toolCallId??J,questions:Z.questions,details:Z,...O?{replayed:!0}:{}}};if(Z.type==="mcpElicitation"&&Z.mcpElicitation)return{type:"elicitation.required",properties:{requestId:J,toolCallId:Z.toolCallId??J,elicitation:Z.mcpElicitation,...O?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:J,toolName:Z.toolName,description:Z.message,args:Z.args,details:Z,...O?{replayed:!0}:{}}}}function U2($){return{...typeof $.seq==="number"?{id:String($.seq)}:{},data:JSON.stringify({type:$.type,...typeof $.seq==="number"?{seq:$.seq}:{},properties:{...$.properties,sessionId:$.sessionId,projectPath:$.projectPath}})}}function D2(){for(let $ of q0.values())H$($,"route-reset");q0.clear();for(let $ of v0.values())$.controller.abort("route-reset");v0.clear(),m$.clear(),J$=void 0,n.clear()}function H2($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$,J=O.code,Z=O.reason,Y=O.scope,z=O.kind,X=O.limit;if(J!=="tool_busy"&&J!=="tool_batch_full"||Z!=="queue_full"&&Z!=="wait_timeout"&&Z!=="turn_limit"||Y!=="global"&&Y!=="session"||typeof O.retryable!=="boolean"||!Number.isSafeInteger(X)||X<=0||z!==void 0&&z!=="readonly"&&z!=="write"&&z!=="execute")return;return{code:J,reason:Z,scope:Y,retryable:O.retryable,...z===void 0?{}:{kind:z},limit:X}}var _$=($,O)=>{if(!O||typeof O!=="object")return O;let J={...O},Z=H2(J.tool_admission);if(Z)J.tool_admission=Z;else delete J.tool_admission;if($==="Bash"){let X={},F=["message","signal","status","summary"],b=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],B=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let E of F){let G=J[E];if(typeof G==="string")X[E]=G.slice(0,8192)}for(let E of b){let G=J[E];if(typeof G==="boolean")X[E]=G}for(let E of B){let G=J[E];if(typeof G==="number"&&Number.isSafeInteger(G)&&G>=0)X[E]=G}if(J.exit_code===null||typeof J.exit_code==="number"&&Number.isSafeInteger(J.exit_code))X.exit_code=J.exit_code;if(J.terminal_transport==="local"||J.terminal_transport==="acp"||J.terminal_transport==="local_fallback")X.terminal_transport=J.terminal_transport;if(J.background_reason==="explicit"||J.background_reason==="foreground_budget")X.background_reason=J.background_reason;for(let E of["bash_id","shell_id"]){let G=J[E];if(typeof G==="string"&&G.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(G))X[E]=G}if(Z)X.tool_admission=Z;let M=J.background_shell_admission;if(M&&typeof M==="object"&&!Array.isArray(M)){let E=M;if(E.code==="background_shell_busy"&&(E.scope==="session"||E.scope==="global")&&E.retryable===!0&&Number.isSafeInteger(E.limit)&&E.limit>0)X.background_shell_admission={code:E.code,scope:E.scope,retryable:E.retryable,limit:E.limit}}return X}let Y=200000,z=(X,F)=>typeof X==="number"&&Number.isSafeInteger(X)&&X>=0&&X<=F?X:0;if(typeof J.oldContent==="string"&&J.oldContent.length>Y)delete J.oldContent;if(typeof J.newContent==="string"&&J.newContent.length>Y)delete J.newContent;if(J.mcpResult&&typeof J.mcpResult==="object"&&!Array.isArray(J.mcpResult)){let X=J.mcpResult,F=Array.isArray(X.artifacts)?X.artifacts.slice(0,64).flatMap((b)=>{if(!b||typeof b!=="object"||Array.isArray(b))return[];let B=b,M=new Set(["text","image","audio","resource"]);if(typeof B.id!=="string"||!/^[a-f0-9]{64}$/.test(B.id)||typeof B.sha256!=="string"||B.sha256!==B.id||typeof B.kind!=="string"||!M.has(B.kind)||z(B.size,67108864)!==B.size||typeof B.persisted!=="boolean")return[];return[{id:B.id.slice(0,128),sha256:B.sha256.slice(0,128),kind:B.kind,size:B.size,persisted:B.persisted,...typeof B.mimeType==="string"?{mimeType:B.mimeType.slice(0,256)}:{},...typeof B.sourceUri==="string"?{sourceUri:B.sourceUri.slice(0,8192)}:{},...typeof B.path==="string"?{path:B.path.slice(0,8192)}:{}}]}):[];J.mcpResult={isError:X.isError===!0,contentCount:z(X.contentCount,64),textBytes:z(X.textBytes,4194304),structuredBytes:z(X.structuredBytes,4194304),artifactCount:z(X.artifactCount,64),truncated:X.truncated===!0,binaryOmitted:X.binaryOmitted===!0,artifacts:F}}else delete J.mcpResult;return J};function _2($){let O=typeof $.seq==="number"?{seq:$.seq}:{};if($.type==="part_created"&&$.data.partType==="tool_call"){let J=$.data.payload;return{type:"tool.start",...O,properties:{messageId:$.data.messageId,toolCallId:J.toolCallId??$.data.partId,toolName:J.toolName??"unknown",arguments:JSON.stringify(J.input??{})}}}if($.type==="part_created"&&$.data.partType==="tool_result"){let J=$.data.payload,Z=J.toolName??"unknown",Y=Y1(J),z=w$(A$(Z,Y),L$);return{type:"tool.result",...O,properties:{messageId:$.data.messageId,toolCallId:J.toolCallId??$.data.partId,toolName:Z,success:Y.success,status:Y.success?"completed":"failed",summary:Y.metadata?.summary,output:M$(z),metadata:_$(Z,Y.metadata)}}}return{type:`committed.${$.type}`,...O,properties:{event:$}}}function B2($,O,J){switch(J.kind){case"tool_start":if("function"in J.toolCall)j.publish($,"subagent.update",{subagentSessionId:O,toolName:J.toolCall.function.name}),j.publish($,"subagent.tool.start",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,arguments:J.toolCall.function.arguments,toolKind:J.toolKind});break;case"tool_result":if("function"in J.toolCall)j.publish($,"subagent.tool.result",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,success:J.result.success,summary:J.result.metadata?.summary,output:M$(w$(A$(J.toolCall.function.name,J.result),L$)),metadata:_$(J.toolCall.function.name,J.result.metadata)});break;case"tool_progress":if("function"in J.toolCall)j.publish($,"subagent.tool.progress",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,...J.update});break;case"content_delta":j.publish($,"subagent.delta",{subagentSessionId:O,delta:J.delta});break;case"thinking_delta":j.publish($,"subagent.thinking.delta",{subagentSessionId:O,delta:J.delta});break;case"stream_end":j.publish($,"subagent.stream.end",{subagentSessionId:O});break;case"provider_retry":j.publish($,"subagent.provider.retry",{subagentSessionId:O,phase:J.phase,attempt:J.attempt,maxRetries:J.maxRetries,reason:J.reason,statusCode:J.statusCode,delayMs:J.delayMs,nextRetryAt:J.nextRetryAt});break;case"provider_stall":j.publish($,"subagent.provider.stall",{subagentSessionId:O,phase:J.phase,stallCount:J.stallCount,durationMs:J.durationMs,warningAfterMs:J.warningAfterMs,timeoutMs:J.timeoutMs,outputStarted:J.outputStarted});break;case"action_stationarity":j.publish($,"subagent.action.stationarity",{subagentSessionId:O,phase:J.phase,toolName:J.toolName,runLength:J.runLength,nudgeThreshold:J.nudgeThreshold,haltThreshold:J.haltThreshold,progressAware:J.progressAware});break;case"mcp_catalog_changed":j.publish($,"subagent.mcp.catalog.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,added:J.added,removed:J.removed,updated:J.updated});break;case"mcp_content_changed":j.publish($,"subagent.mcp.content.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,contentKind:J.contentKind,added:J.added,removed:J.removed,updated:J.updated});break;case"mcp_resource_updated":j.publish($,"subagent.mcp.resource.updated",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,uri:J.uri});break;case"mcp_connection_changed":j.publish($,"subagent.mcp.connection.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,maxAttempts:J.maxAttempts,nextRetryAt:J.nextRetryAt,error:J.error});break;case"mcp_log":j.publish($,"subagent.mcp.log",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,level:J.level,logger:J.logger,message:J.message,projectedBytes:J.projectedBytes,dataSha256:J.dataSha256,truncated:J.truncated,detailsOmitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});break;case"mcp_instructions_changed":j.publish($,"subagent.mcp.instructions.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,action:J.action,reason:J.reason,text:J.text,sourceBytes:J.sourceBytes,projectedBytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,detailsOmitted:J.detailsOmitted});break;case"mcp_task_changed":j.publish($,"subagent.mcp.task.changed",{subagentSessionId:O,revision:J.revision,taskId:J.taskId,serverName:J.serverName,toolName:J.toolName,status:J.status,statusMessage:J.statusMessage,createdAt:J.createdAt,updatedAt:J.updatedAt,completedAt:J.completedAt,hasResult:J.hasResult,error:J.error});break;case"project_rules_loaded":j.publish($,"subagent.project.rules.loaded",{subagentSessionId:O,files:J.files,triggerPaths:J.triggerPaths,blockedWrite:J.blockedWrite});break;default:break}}function U$($,O="projectPath"){if(!J4.isAbsolute($))throw new _(`${O} must be absolute`);return J4.resolve($)}function J1($){try{C$($)}catch(O){throw new _(O instanceof Error?O.message:`Invalid session ID: ${$}`)}}function x0($){return{sessionId:$.id,projectPath:$.projectPath}}function D$($,O,J){return{id:$.sessionId,projectPath:$.projectPath,title:$.title??`Session ${$.sessionId.slice(0,6)}`,createdAt:new Date($.firstMessageTime),updatedAt:new Date($.lastMessageTime),rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,taskStatus:$.taskStatus,taskStatusReason:$.taskStatusReason,taskFailure:$.taskFailure,taskStartedAt:$.taskStartedAt,taskCompletedAt:$.taskCompletedAt,taskPromptSummary:$.taskPromptSummary,taskModelId:$.taskModelId,selectedModelId:$.selectedModelId,permissionMode:$.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,communicationStyleDigest:$.communicationStyleDigest,projectInstructionsDigest:$.projectInstructionsDigest,pendingInteraction:$.pendingInteraction,taskRetryAvailable:$.taskRetryAvailable,taskRetriedFrom:$.taskRetriedFrom,taskDelivery:$.taskDelivery,taskIsolation:$.taskIsolation,taskSourceProjectPath:$.taskSourceProjectPath,taskWorktreePath:$.taskWorktreePath,taskWorktreeBranch:$.taskWorktreeBranch,taskBaseCommit:$.taskBaseCommit,taskDiffStat:$.taskDiffStat,taskQueuePosition:$.taskQueuePosition,taskQueueDepth:$.taskQueueDepth,taskConcurrencyLimit:$.taskConcurrencyLimit,archivedAt:$.archivedAt,archivedBySessionId:$.archivedBySessionId,taskWorktree:J,messages:O}}function o$($){return $.flatMap((O)=>{if(!G4(O)||O.role==="system"||O.role==="tool"&&O.name===O$)return[];let J=O.tool_calls?.filter((X)=>!("function"in X)||X.function.name!==O$),Z=typeof O.content==="string"?O.content.trim():"";if(O.role==="assistant"&&O.tool_calls?.length&&!J?.length&&!Z&&!O.reasoningContent&&!O.metadata)return[];let Y={...O,...O.tool_calls?{tool_calls:J&&J.length>0?J:void 0}:{}};if(O.role==="tool"){let X=O.metadata&&typeof O.metadata==="object"&&!Array.isArray(O.metadata)?O.metadata:void 0,F=O.name??(typeof X?.toolName==="string"?X.toolName:"unknown");if(X!==void 0&&(Object.hasOwn(X,"output")||Object.hasOwn(X,"error"))){let B=Y1(X),M=w$(A$(F,B),L$);return[{...Y,name:F,content:M$(M),metadata:_$(F,{...B.metadata,status:B.success?"completed":"failed"})}]}return[{...Y,name:F,metadata:_$(F,X)}]}let z=F4(O.metadata);return[z?{...Y,content:W4(z)}:Y]})}function B$($,O){$.taskStatus=O.taskStatus,$.taskStatusReason=O.taskStatusReason,$.taskFailure=O.taskFailure,$.taskStartedAt=O.taskStartedAt,$.taskCompletedAt=O.taskCompletedAt,$.taskPromptSummary=O.taskPromptSummary,$.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,$.updatedAt=new Date(O.lastMessageTime)}async function u0($){let O=await C.findSessionMetadata($.id,$.projectPath);if(O)B$($,O)}function e0($){let O=G0($.currentRunId),J=O?.status==="waiting_permission"?"running":O?.status??$.taskStatus;return{sessionId:$.id,projectPath:$.projectPath,title:$.title,rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,status:void 0,taskStatus:J,taskStatusReason:$.taskStatusReason,taskFailure:$.taskFailure,taskStartedAt:$.taskStartedAt,taskCompletedAt:$.taskCompletedAt,taskPromptSummary:$.taskPromptSummary,taskModelId:$.taskModelId,selectedModelId:$.selectedModelId,permissionMode:$.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,communicationStyleDigest:$.communicationStyleDigest,projectInstructionsDigest:$.projectInstructionsDigest,taskRetryAvailable:$.taskRetryAvailable,taskRetriedFrom:$.taskRetriedFrom,taskDelivery:$.taskDelivery,taskIsolation:$.taskIsolation,taskSourceProjectPath:$.taskSourceProjectPath,taskWorktreePath:$.taskWorktreePath,taskWorktreeBranch:$.taskWorktreeBranch,taskBaseCommit:$.taskBaseCommit,taskDiffStat:$.taskDiffStat,taskQueuePosition:O?.status==="queued"?O.taskQueuePosition:J==="queued"?$.taskQueuePosition:void 0,taskQueueDepth:O?.status==="queued"?O.taskQueueDepth:J==="queued"?$.taskQueueDepth:void 0,taskConcurrencyLimit:O?.taskConcurrencyLimit??$.taskConcurrencyLimit,archivedAt:$.archivedAt,archivedBySessionId:$.archivedBySessionId,pendingInteraction:O?.pendingPermission?{type:O.pendingPermission.details.type==="askUserQuestion"?"question":O.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:O.pendingPermission.permissionId}:$.pendingInteraction,agentType:void 0,model:void 0,messageCount:$.messages.length,firstMessageTime:$.createdAt.toISOString(),lastMessageTime:$.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function z0($,O){if(J1($),O!==void 0){let Z=I0({sessionId:$,projectPath:U$(O)});if(n.has(h(Z)))return Z;let Y=await C.findSessionMetadata(Z.sessionId,Z.projectPath);if(!Y)throw new f("Session",$);return I0({sessionId:Y.sessionId,projectPath:Y.projectPath})}let J=new Map;for(let Z of n.values()){if(Z.id!==$)continue;let Y=x0(Z);J.set(h(Y),Y)}for(let Z of await C.listSessions()){if(Z.sessionId!==$)continue;let Y=I0({sessionId:Z.sessionId,projectPath:Z.projectPath});J.set(h(Y),Y)}if(J.size===0)try{let Z=await C.findSessionMetadata($);if(!Z)throw new f("Session",$);return I0({sessionId:Z.sessionId,projectPath:Z.projectPath})}catch(Z){if(Z instanceof f)throw Z;if(Z instanceof Error&&Z.message.startsWith("Ambiguous session ID:"))throw new H0;throw Z}if(J.size>1)throw new H0;return J.values().next().value}function Z1($){if(typeof $==="string")return $;return $.filter((O)=>O.type==="text").map((O)=>O.text).join(`
7
- `)}function Q4($,O){let J=(O??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(J.length===0)return $;let Z=[];if($.trim())Z.push({type:"text",text:$});return Z.push(...J),Z}var b4=()=>{D2();let $=new Y2;$.onError((x,N)=>{if(x instanceof e)return N.json(x.toObject(),x.statusCode);return y.error("[SessionRoutes] Unhandled route error:",x),N.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let O=new Map,J=new Map,Z=new Map,Y=new Map,z=new Map,X=new Map,F=new _4,b,B=async(x)=>{let N;try{N=F.enter()}catch{throw new h0}try{return await x()}finally{N.release()}};$.use("*",async(x,N)=>{if(x.req.method==="GET"||x.req.method==="HEAD")return N();return B(N)});let M=(x)=>{let N=h(x),Q=z.get(N);if(!Q)Q=new Z4,z.set(N,Q);return Q},E=(x)=>{let N=h(x),Q=X.get(N);if(!Q)Q=new Z4,X.set(N,Q);return Q},G=async(x,N={})=>{let Q=h(x0(x));await Z.get(Q);let K=O.get(Q);if(K)return K;let V=J.get(Q);if(!V){let U=N.communicationStyle??x.communicationStyle;V=F$.create({sessionId:x.id,workspaceRoot:x.projectPath,...x.selectedModelId??x.taskModelId?{modelId:x.selectedModelId??x.taskModelId}:{},permissionMode:N.permissionMode??x.permissionMode??"default",...x.reasoningEffort?{reasoningEffort:x.reasoningEffort}:{},...x.serviceTier?{serviceTier:x.serviceTier}:{},...x.responseVerbosity?{responseVerbosity:x.responseVerbosity}:{},...U?{communicationStyle:U}:{},...U===x.communicationStyle&&x.communicationStyleDigest?{communicationStyleDigest:x.communicationStyleDigest}:{},...x.projectInstructionsDigest?{projectInstructionsDigest:x.projectInstructionsDigest}:{},...x.taskWorktree?{taskWorktree:x.taskWorktree}:{},...x.taskIsolation?{taskIsolation:x.taskIsolation}:{},...x.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:x.id}}:{}}),J.set(Q,V)}try{let U=await V;return O.set(Q,U),U}finally{if(J.get(Q)===V)J.delete(Q)}},u=async(x,N)=>{let Q=h(x0(x)),K=Z.get(Q);if(!K)K=(async()=>{let V=J.get(Q);if(V)await V.catch(()=>{return});J.delete(Q);let U=N??O.get(Q);if(O.delete(Q),U){for(let[H,L]of O)if(L===U)O.delete(H)}await U?.dispose()})().finally(()=>{if(Z.get(Q)===K)Z.delete(Q)}),Z.set(Q,K);await K},Y0=async(x)=>{let N=h(x),Q=n.get(N);if(Q)return Q;let K=Y.get(N);if(!K)K=(async()=>{let V=await C.findSessionMetadata(x.sessionId,x.projectPath);if(!V)throw new f("Session",x.sessionId);let[U,H]=await Promise.all([C.loadSession(x.sessionId,x.projectPath),C.findSessionTaskWorktree(x.sessionId,x.projectPath)]),L=D$(V,U,H);return n.set(N,L),L})(),Y.set(N,K);try{return await K}finally{if(Y.get(N)===K)Y.delete(N)}},q=async(x,N)=>{let Q=await z0(x,N);try{await C.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(K){if(K instanceof r$)throw new k(K.message);throw K}return Y0(Q)},t=async(x,N)=>{if(x.permissionMode===N)return;let Q=await C.setSessionPermissionMode(x.id,x.projectPath,N);x.permissionMode=Q.permissionMode,x.updatedAt=new Date(Q.lastMessageTime),j.publish(x0(x),"session.updated",{permissionMode:N})},I=(x,N,Q,K={})=>{if(!F.stats().accepting)throw new h0;let V=$$(12),U={id:V,sessionId:x.id,projectPath:x.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:K.taskRuntime!==void 0,createdAt:new Date};if(K.taskRuntime){let H=K.taskRuntime,L=r0.admit({key:`${x.projectPath}\x00${x.id}`,...H.getTaskAdmissionLimits(),signal:U.abortController.signal,onUpdate:(T)=>{U.status=T.state,U.taskQueuePosition=T.queuePosition,U.taskQueueDepth=T.queueDepth,U.taskConcurrencyLimit=T.maxConcurrent,x.taskStatus=T.state,x.taskQueuePosition=T.queuePosition,x.taskQueueDepth=T.queueDepth,x.taskConcurrencyLimit=T.maxConcurrent,U.taskAdmissionUpdate=(U.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await H.setTaskAdmission(T)}).catch((w)=>{y.warn(`[SessionRoutes] Failed to persist admission for ${x.id}:`,w)})}});U.taskAdmission=L;let A=L.getSnapshot();U.status=A.state,U.taskQueuePosition=A.queuePosition,U.taskQueueDepth=A.queueDepth,U.taskConcurrencyLimit=A.maxConcurrent}return q0.set(V,U),x.currentRunId=V,U.completion=L2(U,x,N,Q,G,{pendingInputOnly:K.pendingInputOnly,preparedInputTurn:K.preparedInputTurn,goalContinuationOnly:K.goalContinuationOnly,outputSchema:K.outputSchema,taskAdmission:U.taskAdmission,disposeRuntime:u}).catch((H)=>{y.error(`[SessionRoutes] Run ${V} failed:`,H)}),U},O0=async(x)=>{let N;if(x.outputSchema)try{N=t$(x.outputSchema).schema}catch(R){throw new _(R instanceof Error?R.message:"Invalid output schema")}let Q=n$("task",12),K=U$(x.sourceProjectPath),V=x.modelId?.trim(),U=$0();if(!U)throw new _("Config not initialized");let[H,L]=await Promise.all([P$(K,U),W0(K)]);if(V&&!H.config.models.some((R)=>R.id===V))throw new _(`Task model not found: ${V}`);let A=V||H.config.models.find((R)=>R.id===H.config.currentModelId)?.id||H.config.models[0]?.id;if(!A)throw new _("No model is configured. Add or select a model before dispatching a task.");let T=H.config.models.find((R)=>R.id===A);if(!T)throw new _(`Task model not found: ${A}`);let w=x.reasoningEffort??"off",r=x.serviceTier??"auto",U0=x.responseVerbosity??"auto",j0=x.communicationStyle??"auto",w0,Q0=L.projectRules?.staticRules(K),i=Q0&&Q0.files.length>0?Q0.provenanceSha256:void 0;try{let R=H.catalog.resolveConfig(T);z4(R,w),X4(R,r),x4(R,U0);let o=K4(j0,L.communicationStyles);w0=o.source==="built-in"?void 0:o.contentSha256}catch(R){throw new _(R instanceof Error?R.message:"Invalid reasoning effort")}let c0={version:1,prompt:x.prompt,...x.title?{title:x.title}:{},sourceProjectPath:K,isolation:x.isolation,permissionMode:x.permissionMode,modelId:A,reasoningEffort:w,serviceTier:r,responseVerbosity:U0,communicationStyle:j0,...w0?{communicationStyleDigest:w0}:{},...i?{projectInstructionsDigest:i}:{},...x.attachments?{attachments:x.attachments.map((R)=>({...R}))}:{},...N?{outputSchema:N}:{}},P,S;try{let R=await L4.createSessionTask({sessionId:Q,prompt:x.prompt,title:x.title,sourceProjectPath:K,isolation:x.isolation,dispatch:c0,retriedFrom:x.retriedFrom}),{metadata:o}=R;P=R.taskWorktree,S=D$(o,[],P);let Z0=x0(S);n.set(h(Z0),S),j.publish(Z0,"task.status",{taskStatus:o.taskStatus,updatedAt:o.lastMessageTime});let l=Q4(x.prompt,x.attachments),p=await G(S),s=N?await p.prepareInputTurn(l,{outputSchema:N}):await p.prepareInputTurn(l);if(!s.accepted)throw new k(`Task prompt was not accepted: ${s.reason}`);let A0=I(S,l,x.permissionMode,{preparedInputTurn:s,taskRuntime:p,outputSchema:N});return await A0.taskAdmissionUpdate,{session:e0(S),runId:A0.id,messageId:s.messageId,status:A0.status==="queued"?"queued":"running",queuePosition:A0.taskQueuePosition,queueDepth:A0.taskQueueDepth,maxConcurrentTasks:A0.taskConcurrencyLimit}}catch(R){if(R instanceof O1&&S){let o=x0(S),Z0=h(o);if(P)await T0.exit({sessionId:S.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await O.get(Z0)?.dispose().catch(()=>{return}),O.delete(Z0),await C.deleteSession(S.id,S.projectPath).catch(()=>{return}),n.delete(Z0),new o0("Task admission queue is full")}if(S){let o=await C.findSessionMetadata(S.id,S.projectPath).catch(()=>{return});if(!o||o.taskStatus==="queued"){let Z0=f$(R),l=await C.updateSessionMetadata(S.id,S.projectPath,{taskStatus:"failed",taskStatusReason:Z0.message,taskFailure:Z0,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});S.taskStatus=l?.taskStatus??"failed",S.taskStatusReason=l?.taskStatusReason??Z0.message,S.taskFailure=l?.taskFailure??Z0,S.taskCompletedAt=l?.taskCompletedAt}else S.taskStatus=o.taskStatus,S.taskStatusReason=o.taskStatusReason,S.taskFailure=o.taskFailure,S.taskCompletedAt=o.taskCompletedAt}throw R}},v=(x)=>B(()=>O0(x)),m0=async(x,N)=>{let Q=await z0(x,N),K=await C.findSessionMetadata(Q.sessionId,Q.projectPath);if(!K)throw new f("Session",Q.sessionId);if(!["failed","interrupted","cancelled"].includes(K.taskStatus))throw new k(`Task cannot be retried while status is ${K.taskStatus}`);let V=await C.findSessionTaskDispatch(Q.sessionId,Q.projectPath);if(!V)throw new k("Task retry payload is unavailable");return v({prompt:V.prompt,title:V.title,sourceProjectPath:V.sourceProjectPath,isolation:V.isolation,permissionMode:V.permissionMode,modelId:V.modelId,reasoningEffort:V.reasoningEffort,serviceTier:V.serviceTier,responseVerbosity:V.responseVerbosity,communicationStyle:V.communicationStyle,attachments:V.attachments,outputSchema:V.outputSchema,retriedFrom:Q})},b$=(x,N)=>B(()=>m0(x,N)),X0=async(x,N)=>{let Q=await q(x,N);if(!Q.taskWorktree)throw new _("Session does not have a task worktree");try{await T0.restoreSession(Q.taskWorktree);let K=await T0.getDiffArtifact(Q.id);if(!K)throw new k("Task diff artifact is unavailable");return{sessionId:Q.id,projectPath:Q.projectPath,...K}}catch(K){if(K instanceof k)throw K;throw y.error("[SessionRoutes] Failed to load task diff artifact:",K),new k("Task diff artifact is unavailable")}},R$=async(x,N,Q)=>{let K=await z0(x,Q);return E(K).runExclusive(async()=>{let V=await q(K.sessionId,K.projectPath);if(["queued","running"].includes(V.taskStatus))throw new k(`Task artifacts cannot be delivered while status is ${V.taskStatus}`);if(V.taskDelivery?.status==="applied")throw new k("Task changes have already been applied");if(V.taskDelivery?.status==="discarded")throw new k("Task changes have already been discarded");if(!V.taskWorktree)throw new k("Task worktree is unavailable");let U=async(H,L=!1)=>{let A=await C.updateSessionMetadata(V.id,V.projectPath,{taskDelivery:H,...L?{taskWorktree:null}:{}});if(B$(V,A),L)V.taskWorktree=void 0;return j.publish(K,"task.delivery",{taskDelivery:H,...L?{taskWorktreeRemoved:!0}:{},updatedAt:A.lastMessageTime}),e0(V)};try{if(N==="discard"){try{await T0.restoreSession(V.taskWorktree)}catch(A){return y.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${V.id}:`,A),U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:V.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let L=await T0.exit({sessionId:V.id,action:"remove",discardChanges:!0});return U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:L.discardedFiles??0,message:"Task worktree removed"},!0)}try{await T0.restoreSession(V.taskWorktree)}catch(L){throw y.warn(`[SessionRoutes] Task worktree is unavailable for ${V.id}:`,L),new $1("artifact_unavailable","Task worktree is unavailable")}let H=await T0.apply(V.id);return U({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:H.sourceCommit,changedFiles:H.changedFiles,message:"Task changes applied to the source workspace"})}catch(H){if(H instanceof $1)throw await U({status:"conflicted",updatedAt:new Date().toISOString(),message:H.message}),new k(H.message);throw H}})},R0=(x,N,Q)=>B(()=>R$(x,N,Q)),W=async(x)=>{let N=G0(x.currentRunId);if(F0(N))return;if(x.taskIsolation&&x.taskStatus!=="queued"&&x.taskStatus!=="running")return;let Q=await F$.hasPendingInbox(x.projectPath,x.id),K=!Q&&await F$.hasActiveGoal(x.projectPath,x.id);if(!Q&&!K)return;let V=await G(x),U=G0(x.currentRunId);if(F0(U))return;if(Q&&V.getPendingSteeringCount()===0)await V.reloadPendingInbox();let H=V.getPendingSteeringCount()>0,L=H?null:await V.getGoal(),A=L?.status==="active"||L?.status==="verifying";if(!H&&!A||V.hasTurnOwner())return;I(x,"",x.permissionMode??"default",{pendingInputOnly:H,goalContinuationOnly:A,...x.taskIsolation?{taskRuntime:V}:{}})},J0=async(x)=>{let N;try{N=F.enter()}catch{return}try{await W(x)}finally{N.release()}};J$=J0;let B1=async()=>{let x={scheduled:0,failed:0,deferred:0};if(!F.stats().accepting)return x;let N=(await C.listSessions()).filter((Q)=>Q.taskStatus==="queued"&&Q.taskIsolation!==void 0).sort((Q,K)=>Q.firstMessageTime.localeCompare(K.firstMessageTime)||Q.projectPath.localeCompare(K.projectPath)||Q.sessionId.localeCompare(K.sessionId));for(let[Q,K]of N.entries()){let V={sessionId:K.sessionId,projectPath:K.projectPath};try{if(!await F$.hasPendingInbox(K.projectPath,K.sessionId)){let H=f$("Queued task input is missing");await C.updateSessionMetadata(K.sessionId,K.projectPath,{taskStatus:"failed",taskStatusReason:H.message,taskFailure:H,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),x.failed++;continue}let U=await Y0(V);if(await J0(U),U.currentRunId)x.scheduled++}catch(U){if(U instanceof O1){x.deferred+=N.length-Q;break}y.warn(`[SessionRoutes] Failed to recover queued task ${K.sessionId}:`,U),x.deferred++}}return x};return $.get("/",async(x)=>{try{let N=await C.listSessions(),Q=new Set(N.filter((T)=>T.relationType==="subagent").map((T)=>h({sessionId:T.sessionId,projectPath:T.projectPath}))),K=Array.from(n.values()).filter((T)=>!Q.has(h(x0(T)))&&T.relationType!=="subagent").map((T)=>e0(T)),V=new Set(K.map((T)=>h({sessionId:T.sessionId,projectPath:T.projectPath}))),U=N.filter((T)=>{if(T.relationType==="subagent")return!1;return!V.has(h({sessionId:T.sessionId,projectPath:T.projectPath}))}),H=new Set(V),L=U.filter((T)=>{let w=h({sessionId:T.sessionId,projectPath:T.projectPath});if(H.has(w))return!1;return H.add(w),!0}),A=[...K,...L];return x.json(A)}catch(N){throw y.error("[SessionRoutes] Failed to list sessions:",N),new a("Failed to list sessions")}}),$.get("/catalog",async(x)=>{try{let N=x.req.query("limit"),Q=N===void 0?void 0:Number(N),K=x.req.query("cursor"),V=x.req.query("projectPath"),U=x.req.query("archived");if(U!==void 0&&U!=="true"&&U!=="false")throw new _("archived must be true or false");let H=U==="true",L=await C.listSessionPage({...V?{cwd:U$(V)}:{},...K?{cursor:K}:{},...Q===void 0?{}:{limit:Q},includeSubagents:!1,archived:H}),A=new Map((H?[]:Array.from(n.values())).filter((T)=>T.relationType!=="subagent").map((T)=>[h(x0(T)),e0(T)]));return x.json({sessions:L.sessions.map((T)=>A.get(h({sessionId:T.sessionId,projectPath:T.projectPath}))??T),...L.nextCursor?{nextCursor:L.nextCursor}:{}})}catch(N){if(N instanceof _)throw N;if(N instanceof Error&&(N.message.startsWith("Invalid session cursor")||N.message.startsWith("Session cursor scope")||N.message.startsWith("Session catalog")))throw new _(N.message);throw y.error("[SessionRoutes] Failed to list session catalog:",N),new a("Failed to list session catalog")}}),$.post("/",async(x)=>{try{let N=await x.req.json(),Q=m(X2,N);if(!Q.success)throw new _("Invalid request body");let{title:K,projectPath:V}=Q.data,U=n$("web",12),H=U$(V||x.get("directory")||g(),V?"projectPath":"directory"),L=await C.createSessionMetadata(U,H,{title:K,taskStatus:"completed"}),A=D$(L,[]),T=x0(A);return n.set(h(T),A),j.publish(T,"session.created",{}),x.json({...e0(A),status:void 0,agentType:void 0,model:void 0})}catch(N){if(y.error("[SessionRoutes] Failed to create session:",N),N instanceof _)throw N;throw new a("Failed to create session")}}),$.get("/:sessionId/export",async(x)=>{let N=x.req.param("sessionId");try{let Q=x.req.query("includeReasoning");if(Q!==void 0&&Q!=="true"&&Q!=="false")throw new _("includeReasoning must be true or false");let K=await z0(N,x.req.query("projectPath")),V=await C.exportSessionMarkdown(K.sessionId,K.projectPath,{includeReasoning:Q==="true"});return x.body(V.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${V.filename}"`,"Content-Length":String(Buffer.byteLength(V.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":V.contentSha256,"X-Blade-Export-Activities":String(V.activityCount),"X-Blade-Export-Messages":String(V.messageCount),"X-Blade-Export-Redactions":String(V.redactionCount)})}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;if(Q instanceof Error&&Q.message==="No conversation content to export")throw new k(Q.message);throw y.error("[SessionRoutes] Failed to export session:",Q),new a("Failed to export session")}}),$.post("/:sessionId/fork",async(x)=>{let N=x.req.param("sessionId");try{J1(N);let Q=await x.req.json(),K=m(V2,Q);if(!K.success)throw new _("Invalid request body");let V=U$(K.data.projectPath),U=await C.findSessionMetadata(N,V);if(!U)throw new f("Session",N);let H=await C.forkSession(N,{sourceProjectPath:U.projectPath,targetProjectPath:U.projectPath}),L=D$(H.metadata,H.messages),A=x0(L);return n.set(h(A),L),j.publish(A,"task.status",{taskStatus:H.metadata.taskStatus,...H.metadata.taskCompletedAt?{taskCompletedAt:H.metadata.taskCompletedAt}:{},updatedAt:H.metadata.lastMessageTime}),x.json({session:H.metadata,messages:o$(H.messages)},201)}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof k)throw Q;if(Q instanceof U4)throw new k("Session has no durable creation record");throw y.error("[SessionRoutes] Failed to fork session:",Q),new a("Failed to fork session")}}),$.get("/:sessionId",async(x)=>{let N=x.req.param("sessionId");try{let Q=await z0(N,x.req.query("projectPath")),K=n.get(h(Q));if(K)return x.json(e0(K));let V=await C.findSessionMetadata(Q.sessionId,Q.projectPath);if(!V)throw new f("Session",N);return x.json(V)}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;throw y.error("[SessionRoutes] Failed to get session:",Q),new a("Failed to get session")}}),$.patch("/:sessionId",async(x)=>{let N=x.req.param("sessionId");try{let Q=await x.req.json(),K=m(K2,Q);if(!K.success)throw new _("Invalid request body");if(K.data.title===void 0)throw new _("title is required");let V=await z0(N,K.data.projectPath),U=await C.updateSessionMetadata(V.sessionId,V.projectPath,{title:K.data.title}),H=n.get(h(V));if(H)H.title=U.title??H.title,H.updatedAt=new Date(U.lastMessageTime);if(U.title)j.publish(V,"session.updated",{title:U.title});return x.json({success:!0,title:U.title})}catch(Q){if(y.error("[SessionRoutes] Failed to update session:",Q),Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;throw new a("Failed to update session")}}),$.get("/:sessionId/rewind",async(x)=>{let N=await q(x.req.param("sessionId"),x.req.query("projectPath")),Q=await G(N);return x.json({checkpoints:await Q.listRewindCheckpoints()})}),$.post("/:sessionId/rewind",async(x)=>{let N=m(w4,await x.req.json());if(!N.success)throw new _("Invalid rewind request");let Q=await q(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let V=G0(Q.currentRunId);if(F0(V))throw new k("Cannot rewind while a run is active");let U=await G(Q),H;try{H=await U.rewindSession(N.data)}catch(A){if(A instanceof Error&&A.message.startsWith("Cannot rewind while"))throw new k(A.message);throw A}Q.messages=[...H.messages],Q.updatedAt=new Date;let L=o$(H.messages);return j.publish(K,"session.rewound",{targetMessageId:H.checkpoint.messageId,mode:H.mode,removedTurns:H.removedTurns,restoredFiles:H.restoredFiles,messages:L}),x.json({...H,messages:L})})}),$.get("/:sessionId/review",async(x)=>{let N=x.req.param("sessionId"),Q=await z0(N,x.req.query("projectPath")),K=await k0.list(Q.projectPath,Q.sessionId);return x.json({reviews:K.map((V)=>({...V,content:V.completion?N4(V.start,V.completion):void 0}))})}),$.post("/:sessionId/review",async(x)=>{let N=x.req.param("sessionId"),Q=m(T4,await x.req.json());if(!Q.success)throw new _("Invalid code review request");let K=await q(N,Q.data.projectPath),V=x0(K),U=h(V);return M(V).runExclusive(async()=>{if(F0(G0(K.currentRunId)))throw new k("Cannot start a review during an active turn");if(b0.has(U))throw new k("Session already has an active review");let H=await G(K);if(await k0.recoverInterrupted(V.projectPath,V.sessionId,H),Q.data.modelId&&!H.getModelById(Q.data.modelId))throw new _(`Model not found: ${Q.data.modelId}`);if(Q.data.modelId&&H.getCurrentModelId()!==Q.data.modelId)await H.refresh({modelId:Q.data.modelId});if(Q.data.modelId&&K.selectedModelId!==Q.data.modelId){let w=await C.updateSessionMetadata(K.id,K.projectPath,{selectedModelId:Q.data.modelId});B$(K,w)}let L=new AbortController,A;try{A=await k0.start({sessionId:V.sessionId,projectPath:V.projectPath,runtime:H,request:{kind:Q.data.kind,...Q.data.ref?{ref:Q.data.ref}:{},...Q.data.instructions?{instructions:Q.data.instructions}:{}},signal:L.signal,onEvent:(w)=>{if(w.kind==="tool_start")j.publish(V,"review.tool.started",{reviewId:A?.reviewId,toolCallId:w.toolCall.id,toolName:w.toolCall.function.name});else if(w.kind==="tool_progress")j.publish(V,"review.tool.progress",{reviewId:A?.reviewId,toolCallId:w.toolCall.id,message:w.update.message.slice(0,1000)});else if(w.kind==="tool_result")j.publish(V,"review.tool.completed",{reviewId:A?.reviewId,toolCallId:w.toolCall.id,success:w.result.success})}})}catch(w){if(w instanceof Error&&(w.message.includes("active review")||w.message.includes("interrupted review")||w.message.includes("active turn")))throw new k(w.message);if(w instanceof Error&&(w.message.includes("review")||w.message.includes("Git")||w.message.includes("changes")||w.message.includes("ref")))throw new _(w.message);throw w}if(!A)throw new a("Code review failed to start");await u0(K),j.publish(V,"review.started",{reviewId:A.reviewId,kind:Q.data.kind}),j.publish(V,"task.status",{taskStatus:K.taskStatus,...K.taskStatusReason?{taskStatusReason:K.taskStatusReason}:{},...K.taskStartedAt?{taskStartedAt:K.taskStartedAt}:{},...K.taskPromptSummary?{taskPromptSummary:K.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let T=A.completion.then(async(w)=>{K.messages=await C.loadSession(V.sessionId,V.projectPath),await u0(K),j.publish(V,"task.status",{taskStatus:K.taskStatus,...K.taskStatusReason?{taskStatusReason:K.taskStatusReason}:{},...K.taskFailure?{taskFailure:K.taskFailure}:{},...K.taskStartedAt?{taskStartedAt:K.taskStartedAt}:{},...K.taskCompletedAt?{taskCompletedAt:K.taskCompletedAt}:{},...K.taskPromptSummary?{taskPromptSummary:K.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),j.publish(V,"review.completed",{reviewId:A.reviewId,status:w.status,findings:w.findings.length})}).catch((w)=>{y.error(`[SessionRoutes] Code review ${A.reviewId} failed:`,w)}).finally(()=>{if(b0.get(U)?.reviewId===A.reviewId)b0.delete(U)});return b0.set(U,{reviewId:A.reviewId,controller:L,completion:T}),x.json({reviewId:A.reviewId,status:"running"},202)})}),$.get("/:sessionId/subagents",async(x)=>{let N=await q(x.req.param("sessionId"),x.req.query("projectPath")),Q=await G(N);return x.json({subagents:Q.listSubagents().map(S$)})}),$.post("/:sessionId/subagents/:agentId/resume",async(x)=>{J1(x.req.param("agentId"));let N=A4.safeParse(await x.req.json());if(!N.success)throw new _("Invalid subagent resume request");let Q=await q(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let V=G0(Q.currentRunId);if(F0(V))throw new k("Cannot resume a subagent while a parent run is active");let U=await G(Q),H=!1,L,A=(w)=>{j.publish(K,"subagent.complete",{subagentSessionId:w.id,success:w.status==="completed",status:w.status,summary:w.result?.message?.slice(0,500),type:w.subagentType,verificationVerdict:w.result?.verificationVerdict,resumedFrom:w.resumedFrom,rootAgentId:w.rootAgentId,resumeDepth:w.resumeDepth})},T;try{T=U.resumeSubagent({agentId:x.req.param("agentId"),prompt:N.data.prompt,onEvent:(w,r)=>{B2(K,r,w)},onCompleted:(w)=>{if(H)A(w);else L=w}})}catch(w){if(w instanceof Error&&(w.message.startsWith("Cannot resume")||w.message.startsWith("Subagent cannot")))throw new k(w.message);if(w instanceof Error&&w.message.startsWith("Subagent not found"))throw new f(w.message);throw w}if(j.publish(K,"subagent.start",{subagentSessionId:T.session.id,type:T.session.subagentType,description:T.session.description,resumedFrom:T.source.id,rootAgentId:T.session.rootAgentId,resumeDepth:T.session.resumeDepth}),H=!0,L)A(L);return x.json({source:S$(T.source),session:S$(T.session)})})}),$.get("/:sessionId/goal",async(x)=>{let N=await q(x.req.param("sessionId"),x.req.query("projectPath"));return x.json({goal:await new D4(N.projectPath,N.id).get()})}),$.put("/:sessionId/goal",async(x)=>{let N=m(N2,await x.req.json());if(!N.success)throw new _("Invalid goal request");let Q=await q(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let V=G0(Q.currentRunId);if(F0(V))return x.json({status:"rejected",reason:"run_active"},409);let H=N.data.permissionMode??Q.permissionMode??"default";if(Q.permissionMode!==H)await t(Q,H);let L=await G(Q),A=await L.createGoal(N.data);j.publish(K,"goal.updated",{goal:A});let T=I(Q,"",H,{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:L}:{}});return await T.taskAdmissionUpdate,x.json({status:T.status==="queued"?"queued":"running",runId:T.id,goal:A,queuePosition:T.taskQueuePosition,queueDepth:T.taskQueueDepth,maxConcurrentTasks:T.taskConcurrencyLimit},202)})}),$.patch("/:sessionId/goal",async(x)=>{let N=m(G2,await x.req.json());if(!N.success)throw new _("Invalid goal update");let Q=await q(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let V=await G(Q),U;if(N.data.action==="pause")U=await V.pauseGoal();else if(N.data.action==="edit")U=await V.editGoal(N.data.objective);else U=await V.resumeGoal();if(j.publish(K,"goal.updated",{goal:U}),U.status==="active"&&!F0(G0(Q.currentRunId))){let H=I(Q,"","default",{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:V}:{}});return await H.taskAdmissionUpdate,x.json({status:H.status==="queued"?"queued":"running",runId:H.id,goal:U,queuePosition:H.taskQueuePosition,queueDepth:H.taskQueueDepth,maxConcurrentTasks:H.taskConcurrencyLimit},202)}return x.json({status:U.status,goal:U})})}),$.delete("/:sessionId/goal",async(x)=>{let N=await q(x.req.param("sessionId"),x.req.query("projectPath")),Q=x0(N),V=await(await G(N)).clearGoal();if(V)j.publish(Q,"goal.cleared",{});return x.json({cleared:V})}),$.post("/:sessionId/archive",async(x)=>{let N=x.req.param("sessionId");try{let Q=await z0(N,x.req.query("projectPath")),K=await C.listSessionArchiveMembers(Q.sessionId,Q.projectPath);for(let U of K){let H=I0({sessionId:U.sessionId,projectPath:U.projectPath}),L=n.get(h(H));if(F0(G0(L?.currentRunId)))throw new k(`Stop session ${U.sessionId} before archiving this session tree`)}for(let U of K){let H=I0({sessionId:U.sessionId,projectPath:U.projectPath}),L=n.get(h(H));if(L)await u(L)}let V=await C.archiveSession(Q.sessionId,Q.projectPath);for(let U of K){let H=I0({sessionId:U.sessionId,projectPath:U.projectPath}),L=h(H);n.delete(L),Y.delete(L),J.delete(L),z.delete(L),j.publish(H,"session.archived",{archiveRootId:Q.sessionId,archivedAt:V.archivedAt})}if(O.size===0)await N0.getInstance().disconnectAll();return x.json({session:V,archivedSessionIds:K.map((U)=>U.sessionId)})}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0||Q instanceof k)throw Q;if(Q instanceof s$)throw new k(Q.message);throw y.error("[SessionRoutes] Failed to archive session:",Q),new a("Failed to archive session")}}),$.post("/:sessionId/unarchive",async(x)=>{let N=x.req.param("sessionId");try{let Q=await z0(N,x.req.query("projectPath")),K=await C.listSessionArchiveMembers(Q.sessionId,Q.projectPath),V=await C.unarchiveSession(Q.sessionId,Q.projectPath),U=K.filter((H)=>H.sessionId===Q.sessionId||H.archivedBySessionId===Q.sessionId).map((H)=>H.sessionId);for(let H of U)j.publish({sessionId:H,projectPath:Q.projectPath},"session.unarchived",{archiveRootId:Q.sessionId});return x.json({session:V,restoredSessionIds:U})}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;if(Q instanceof s$)throw new k(Q.message);throw y.error("[SessionRoutes] Failed to unarchive session:",Q),new a("Failed to unarchive session")}}),$.delete("/:sessionId",async(x)=>{let N=x.req.param("sessionId"),Q=x.req.query("projectPath");try{let K=await z0(N,Q),V=h(K),U=n.get(V),H=O.get(V),L=U?.taskWorktree??await C.findSessionTaskWorktree(K.sessionId,K.projectPath),A;if(U?.currentRunId){let w=G0(U.currentRunId);if(w)H$(w),await w.completion,A=w.id}let T=b0.get(V);if(T)T.controller.abort("session-delete"),await T.completion;if(H)await H.clearGoal().catch((w)=>{y.warn("[SessionRoutes] Failed to clear session goal:",w)});if(await C.deleteSession(K.sessionId,K.projectPath),j.publish(K,"session.deleted",{}),A)F2(A);if(n.delete(V),Y.delete(V),J.delete(V),z.delete(V),H){if(await H.dispose(),O.delete(V),O.size===0)await N0.getInstance().disconnectAll()}if(L)try{await T0.restoreSession(L),await T0.exit({sessionId:K.sessionId,action:"remove",discardChanges:!0})}catch(w){y.warn(`[SessionRoutes] Failed to remove deleted task worktree ${K.sessionId}:`,w)}return x.json({success:!0})}catch(K){if(y.error("[SessionRoutes] Failed to delete session:",K),K instanceof _||K instanceof f||K instanceof H0)throw K;throw new a("Failed to delete session")}}),$.get("/:sessionId/message",async(x)=>{let N=x.req.param("sessionId");try{let Q=await z0(N,x.req.query("projectPath")),K=n.get(h(Q)),V=K?.messages?K.messages:await C.loadSession(Q.sessionId,Q.projectPath);return x.json(o$(V))}catch(Q){if(y.error("[SessionRoutes] Failed to get messages:",Q),Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;throw new a("Failed to get messages")}}),$.get("/:sessionId/events",async(x)=>{let N=x.req.param("sessionId"),Q=await z0(N,x.req.query("projectPath"));try{await C.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(L){if(L instanceof r$)throw new k(L.message);throw L}let K=await Y0(Q),V=x.req.header("Last-Event-ID")??x.req.query("lastEventId"),U=V?Number.parseInt(V,10):Number.NaN,H=Number.isInteger(U)?U+1:void 0;return Q2(x,async(L)=>{let T,w,r=!1,U0,j0,w0=new Promise((P)=>{j0=P}),Q0=()=>{if(w!==void 0)clearInterval(w),w=void 0;T?.(),T=void 0},i=(P)=>{if(r)return;r=!0,Q0(),U0?.close(P),j0()},c0=new Set;L.onAbort(i),U0=new K$({write:async(P)=>{await L.writeSSE(P)},onFailure:(P)=>{y.warn(`[SessionRoutes] SSE egress closed for ${Q.sessionId}: kind=${P.kind} pendingItems=${P.pendingItems??0} pendingBytes=${P.pendingBytes??0}`),i(P)}}),T=j.subscribe((P)=>{if(P.sessionId!==Q.sessionId||P.projectPath!==Q.projectPath)return;let S=P.properties.requestId;if((P.type==="permission.asked"||P.type==="question.required"||P.type==="elicitation.required")&&typeof S==="string"){if(c0.has(S))return;c0.add(S)}if(P.type==="subagent.completion.queued")M(Q).runExclusive(()=>J0(K)).catch((R)=>{y.error(`[SessionRoutes] Failed to wake background completion for ${K.id}:`,R)});U0?.observe(U2(P),P.seq)});try{if(L.aborted||r)return;let P=G0(K.currentRunId),S=F0(P)?await G(K):void 0,R=S?.getPendingSteeringCount()??0;if(await U0.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:Q.sessionId,projectPath:Q.projectPath,timestamp:Date.now(),status:F0(P)?P.status:"idle",runId:F0(P)?P.id:void 0,queued:R,pendingInputDelivery:R>0?S?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:S?.getRecoveredSteeringCount()??0}})}),L.aborted||r)return;if(H!==void 0){if(await H4.for(Q.sessionId,Q.projectPath).replay({onCommitted:async(p)=>{if(L.aborted||r)return;let s=_2(p);if(s.seq===void 0)return;await U0.writeReplay({...typeof p.seq==="number"?{id:String(p.seq)}:{},data:JSON.stringify({type:s.type,...s.seq!==void 0?{seq:s.seq}:{},properties:{...s.properties,sessionId:Q.sessionId,projectPath:Q.projectPath}})},s.seq)}},H),L.aborted||r)return}if(U0.finishInitialization({replayed:H!==void 0}),L.aborted||r)return;if(!P&&!b0.has(h(Q))){let p=(await k0.list(Q.projectPath,Q.sessionId)).some((s)=>s.completion===void 0)?await k0.recoverInterrupted(Q.projectPath,Q.sessionId,await G(K)):void 0;if(p)K.messages=await C.loadSession(Q.sessionId,Q.projectPath),await u0(K),j.publish(Q,"review.completed",{reviewId:p.reviewId,status:p.status,findings:0,recovered:!0})}if(L.aborted||r)return;if(!P)await p0.recoverResponded(Q.projectPath,Q.sessionId);if(L.aborted||r)return;let o=P?void 0:await p0.findPending(Q.projectPath,Q.sessionId),Z0=P?.pendingPermission??(o?{permissionId:o.request.requestId,details:p0.confirmationDetails(o),resolve:()=>{return}}:void 0);if(Z0){c0.add(Z0.permissionId);let l=q4(Z0,!0);U0.observe({data:JSON.stringify({type:l.type,properties:{...l.properties,sessionId:Q.sessionId,projectPath:Q.projectPath}})})}if(L.aborted||r)return;if(J0(K).catch((l)=>{y.error(`[SessionRoutes] Failed to resume pending input for ${N}:`,l)}),L.aborted||r)return;w=setInterval(()=>{if(L.aborted||r)return;U0?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await w0}finally{i()}})}),$.post("/:sessionId/message",async(x)=>{let N=x.req.param("sessionId"),Q=await x.req.json(),K=m(z2,Q);if(!K.success)throw new _("Invalid message format");let{content:V,attachments:U,modelId:H,reasoningEffort:L,serviceTier:A,responseVerbosity:T,communicationStyle:w,permissionMode:r,projectPath:U0,outputSchema:j0}=K.data,w0;if(j0)try{w0=t$(j0).schema}catch(l){throw new _(l instanceof Error?l.message:"Invalid output schema")}let Q0=w,i=H?.trim();if((U??[]).reduce((l,p)=>l+(typeof p.content==="string"?Buffer.byteLength(p.content):0),0)>y$)throw new _("Message attachments exceed the 5 MiB limit");let P=r,S=Q4(V,U),R=await q(N,U0??x.req.query("projectPath")),o=P??R.permissionMode??"default",Z0=x0(R);return M(Z0).runExclusive(async()=>{let l=G0(R.currentRunId);if(F0(l)){if(w0)throw new k("Wait for the active turn to finish before setting an output schema");let c=await G(R);if(i&&!c.getModelById(i))throw new _(`Model not found: ${i}`);if(i&&c.getCurrentModelId()!==i)throw new k("Wait for the active turn to finish before switching models");if(L&&c.getReasoningConfiguration().selection!==L)throw new k("Wait for the active turn to finish before switching reasoning effort");if(A&&c.getServiceTierConfiguration().selection!==A)throw new k("Wait for the active turn to finish before switching service tier");if(T&&c.getResponseVerbosityConfiguration().selection!==T)throw new k("Wait for the active turn to finish before switching response verbosity");if(Q0&&c.getCommunicationStyleConfiguration().selection!==Q0)throw new k("Wait for the active turn to finish before switching communication style");if(P&&R.permissionMode!==P)throw new k("Wait for the active turn to finish before switching permission mode");let M0=await c.enqueueSteering(S,{allowBeforeTurn:!0});if(!M0.accepted)return x.json({status:"rejected",reason:M0.reason??"turn_unavailable"},409);let d$=M0.messageId??$$(12),C1=M0.queued;j.publish(Z0,"message.created",{messageId:d$,role:"user",content:Z1(S)});let kO=M0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(j.publish(Z0,kO,{runId:l.id,messageId:d$,queued:C1}),M0.delivery==="next_turn"&&l.status!=="running"&&l.status!=="waiting_permission")J0(R).catch((IO)=>{y.error(`[SessionRoutes] Failed to wake queued follow-up for ${N}:`,IO)});if(M0.delivery==="next_turn")l.pendingFollowUpRequested=!0;return x.json({runId:l.id,messageId:d$,status:M0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:C1},202)}if(R.permissionMode!==o)await t(R,o);let p=await G(R,{permissionMode:o,...Q0&&!Q0.includes(":")?{communicationStyle:Q0}:{}});if(i&&!p.getModelById(i))throw new _(`Model not found: ${i}`);if(L)try{p.resolveReasoningConfiguration(L,i)}catch(c){throw new _(c instanceof Error?c.message:"Invalid reasoning effort")}if(A)try{p.resolveServiceTierConfiguration(A,i)}catch(c){throw new _(c instanceof Error?c.message:"Invalid service tier")}if(T)try{p.resolveResponseVerbosityConfiguration(T,i)}catch(c){throw new _(c instanceof Error?c.message:"Invalid response verbosity")}let s=Q0?p.resolveCommunicationStyleConfiguration(Q0):void 0;if(s?.source!==void 0&&s.source!=="built-in"&&!s.contentSha256)throw new _("Custom communication style has no provenance");let A0=p.getCurrentModelId(),w1=p.getReasoningConfiguration(),A1=p.getServiceTierConfiguration(),M1=p.getResponseVerbosityConfiguration(),E1=p.getCommunicationStyleConfiguration(),T1=Boolean(i)&&A0!==i,q1=Boolean(L)&&w1.selection!==L,b1=Boolean(A)&&A1.selection!==A,R1=Boolean(T)&&M1.selection!==T,j1=Boolean(Q0)&&E1.selection!==Q0;if(T1||q1||b1||R1||j1)await p.refresh({...i?{modelId:i}:{},...L?{reasoningEffort:L}:{},...A?{serviceTier:A}:{},...T?{responseVerbosity:T}:{},...Q0?{communicationStyle:Q0}:{}});let u$={...i&&R.selectedModelId!==i?{selectedModelId:i}:{},...L&&R.reasoningEffort!==L?{reasoningEffort:L}:{},...A&&R.serviceTier!==A?{serviceTier:A}:{},...T&&R.responseVerbosity!==T?{responseVerbosity:T}:{},...s&&(R.communicationStyle!==Q0||R.communicationStyleDigest!==s.contentSha256)?{communicationStyle:Q0,communicationStyleDigest:s.source==="built-in"?null:s.contentSha256}:{}};if(Object.keys(u$).length>0)try{let c=await C.updateSessionMetadata(R.id,R.projectPath,u$);R.permissionMode=c.permissionMode,R.selectedModelId=c.selectedModelId,R.reasoningEffort=c.reasoningEffort,R.serviceTier=c.serviceTier,R.responseVerbosity=c.responseVerbosity,R.communicationStyle=c.communicationStyle,R.communicationStyleDigest=c.communicationStyleDigest,R.updatedAt=new Date(c.lastMessageTime),j.publish(Z0,"session.updated",u$)}catch(c){if(T1||q1||b1||R1||j1)await p.refresh({...A0?{modelId:A0}:{},reasoningEffort:w1.selection,serviceTier:A1.selection,responseVerbosity:M1.selection,communicationStyle:E1.selection}).catch((M0)=>y.error("[SessionRoutes] Failed to roll back non-durable model settings:",M0));throw c}let z$=w0?await p.prepareInputTurn(S,{outputSchema:w0}):await p.prepareInputTurn(S);if(!z$.accepted)return x.json({status:"rejected",reason:z$.reason},z$.reason==="queue_full"?429:409);let i0=I(R,S,o,{preparedInputTurn:z$,outputSchema:w0,...R.taskIsolation?{taskRuntime:p}:{}});return await i0.taskAdmissionUpdate,x.json({runId:i0.id,messageId:z$.messageId,status:i0.status==="queued"?"queued":"running",queuePosition:i0.taskQueuePosition,queueDepth:i0.taskQueueDepth,maxConcurrentTasks:i0.taskConcurrencyLimit},202)})}),$.post("/:sessionId/shell",async(x)=>{let N=x.req.param("sessionId"),Q=m(E4,await x.req.json());if(!Q.success)throw new _("Invalid user shell command");let K=await q(N,Q.data.projectPath??x.req.query("projectPath")),V=x0(K),U=h(V);return M(V).runExclusive(async()=>{if(v0.has(U))throw new k("A user shell command is already running in this Session");let H=await G(K),L=new AbortController,A,T=new Promise((w)=>{A=w});v0.set(U,{controller:L,completion:T});try{let w=await H.executeUserShellCommand(Q.data.command,{signal:L.signal});K.messages=await C.loadSession(K.id,K.projectPath),K.updatedAt=new Date;let r=G0(K.currentRunId);if(w.delivery==="next_turn"&&F0(r))r.pendingFollowUpRequested=!0;return x.json({executionId:w.executionId,messageId:w.messageId,record:w.record,auxiliary:w.auxiliary,...w.delivery?{delivery:w.delivery}:{},...w.queued!==void 0?{queued:w.queued}:{}})}finally{v0.delete(U),A()}})}),$.post("/:sessionId/abort",async(x)=>{let N=x.req.param("sessionId"),Q=await z0(N,x.req.query("projectPath")),K=n.get(h(Q));if(K?.currentRunId){let H=G0(K.currentRunId);if(H)H$(H),await H.completion}let V=v0.get(h(Q));if(V)V.controller.abort("user-cancel"),await V.completion;let U=b0.get(h(Q));if(U)U.controller.abort("user-cancel"),await U.completion;return x.json({success:!0})}),$.get("/:sessionId/status",async(x)=>{let N=x.req.param("sessionId"),Q=await z0(N,x.req.query("projectPath")),K=n.get(h(Q)),V=b0.get(h(Q));if(V)return x.json({sessionId:N,projectPath:Q.projectPath,reviewId:V.reviewId,status:"reviewing"});if(!K?.currentRunId)return x.json({sessionId:N,projectPath:Q.projectPath,status:"idle"});let U=G0(K.currentRunId);return x.json({sessionId:N,projectPath:Q.projectPath,runId:K.currentRunId,status:U?.status||"idle"})}),{app:$,dispatchTask:v,retryTask:b$,getTaskDiff:X0,deliverTask:R0,recoverQueuedTasks:B1,shutdown:(x="server-shutdown")=>{if(b)return b;return F.close(x),b=(async()=>{let N,Q=async(A)=>{let T=await Promise.allSettled(A);for(let w of T)if(w.status==="rejected")N??=w.reason},K=new Set,V=()=>{for(let A of q0.values()){if(A.completion)K.add(A.completion);if(F0(A))H$(A,x)}for(let A of v0.values())A.controller.abort(x),K.add(A.completion);for(let A of b0.values())A.controller.abort(x),K.add(A.completion)},U=F.waitForIdle(),H=!1;U.then(()=>{H=!0});while(!H)V(),await Promise.race([U,new Promise((A)=>setImmediate(A))]);await U,V(),await Q([...K]),await Q([...J.values()]),V(),await Q([...K]);let L=new Set(O.values());if(O.clear(),await Q([...L].map((A)=>A.dispose())),await Q([...Z.values()]),await Q([N0.getInstance().disconnectAll()]),J.clear(),Z.clear(),Y.clear(),z.clear(),X.clear(),n.clear(),J$===J0)J$=void 0;if(N!==void 0)throw N})(),b}}};async function L2($,O,J,Z,Y,z={}){let{abortController:X,sessionId:F,id:b}=$,B=z.preparedInputTurn?.messageId??$$(12),E=z.pendingInputOnly===!0||z.preparedInputTurn?.mode==="pending"||z.goalContinuationOnly===!0?void 0:$$(12),G,u,Y0=x0(O),q=(I,O0)=>{j.publish(Y0,I,O0)},t=async()=>{let I=String(X.signal.reason||"Task run cancelled");if(O.taskIsolation){let O0=G??await Y(O).catch(()=>{return});if(I==="user-cancel")await O0?.discardPendingInput().catch((m0)=>{y.warn(`[SessionRoutes] Failed to discard cancelled input for ${O.id}:`,m0)});let v=await O0?.setTaskStatus("cancelled",I).catch(()=>{return});if(v)B$(O,v);else await u0(O).catch(()=>{return})}O.taskStatus="cancelled",O.taskStatusReason=I,O.taskCompletedAt??=new Date().toISOString()};try{if(z.taskAdmission){if(await z.taskAdmission.ready,await $.taskAdmissionUpdate,X.signal.aborted)throw Error(String(X.signal.reason||"Task run cancelled"))}if(O.taskStatus="running",O.taskStatusReason=void 0,O.taskStartedAt=new Date().toISOString(),O.taskCompletedAt=void 0,!z.pendingInputOnly&&!z.goalContinuationOnly)q("message.created",{messageId:B,role:"user",content:Z1(J)});if(q("session.status",{status:"running"}),E)q("message.created",{messageId:E,role:"assistant",content:""});G=await Y(O);let I=G,O0=Boolean(z.outputSchema??I.getPendingSteeringMessages().find((W)=>W.outputSchema)?.outputSchema);u=await B4.createWithRuntime(I,{sessionId:F,...O.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let v=async(W)=>{let J0=W.interactionRequestId??$$(12),B1=300000;$.status="waiting_permission";let L1=new Promise((K)=>{let V=setTimeout(()=>{y.warn(`[SessionRoutes] Permission ${J0} timed out after 300000ms`),q("permission.timeout",{requestId:J0}),K({approved:!1,reason:"timeout"})},300000);$.pendingPermission={permissionId:J0,resolve:(U)=>{clearTimeout(V),K(U)},details:W}}),x=$.pendingPermission;if(!x)throw Error("Permission request was not registered");let N=q4(x);q(N.type,N.properties),y.info(`[SessionRoutes] Permission request created: ${J0}, runId: ${b}`);let Q=await L1;if(y.info(`[SessionRoutes] Permission response received: ${J0}, approved: ${Q.approved}`),!X.signal.aborted)$.status="running";if($.pendingPermission===x)$.pendingPermission=void 0;return q("interaction.resolved",{requestId:J0}),Q},b$={messages:await C.loadSessionModelContext(O.id,O.projectPath),userId:"web-user",sessionId:F,workspaceRoot:O.projectPath,signal:X.signal,permissionMode:Z,onPermissionModeChange:async(W)=>{O.permissionMode=W,O.updatedAt=new Date,q("session.updated",{permissionMode:W})},...O.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:v}},X0=()=>{if(!E)E=$$(12),q("message.created",{messageId:E,role:"assistant",content:""});return E},R$=async(W)=>{switch(W.kind){case"content_delta":if(O0)break;q("message.delta",{messageId:X0(),delta:W.delta});break;case"structured_output":q("structured.output",{messageId:X0(),output:W.output,schemaDigest:W.schemaDigest});break;case"thinking_delta":q("thinking.delta",{messageId:X0(),delta:W.delta});break;case"tool_start":if("function"in W.toolCall){if(W.toolCall.function.name===O$)break;q("tool.start",{messageId:X0(),toolName:W.toolCall.function.name,toolCallId:W.toolCall.id,arguments:W.toolCall.function.arguments,toolKind:W.toolKind})}break;case"tool_result":if("function"in W.toolCall){if(W.toolCall.function.name===O$)break;q("tool.result",{messageId:X0(),toolName:W.toolCall.function.name,toolCallId:W.toolCall.id,success:W.result.success,summary:W.result.metadata?.summary,output:M$(w$(A$(W.toolCall.function.name,W.result),L$)),metadata:_$(W.toolCall.function.name,W.result.metadata)})}break;case"tool_progress":if("function"in W.toolCall){if(W.toolCall.function.name===O$)break;q("tool.progress",{messageId:X0(),toolName:W.toolCall.function.name,toolCallId:W.toolCall.id,...W.update})}break;case"token_usage":q("token.usage",{...W.usage});break;case"turn_start":q("turn.started",{turn:W.turn,maxTurns:W.maxTurns});break;case"provider_retry":q("provider.retry",{phase:W.phase,attempt:W.attempt,maxRetries:W.maxRetries,reason:W.reason,statusCode:W.statusCode,delayMs:W.delayMs,nextRetryAt:W.nextRetryAt});break;case"provider_stall":q("provider.stall",{phase:W.phase,stallCount:W.stallCount,durationMs:W.durationMs,warningAfterMs:W.warningAfterMs,timeoutMs:W.timeoutMs,outputStarted:W.outputStarted});break;case"action_stationarity":q("action.stationarity",{phase:W.phase,toolName:W.toolName,runLength:W.runLength,nudgeThreshold:W.nudgeThreshold,haltThreshold:W.haltThreshold,progressAware:W.progressAware});break;case"mcp_catalog_changed":q("mcp.catalog.changed",{messageId:X0(),revision:W.revision,serverName:W.serverName,added:W.added,removed:W.removed,updated:W.updated});break;case"mcp_content_changed":q("mcp.content.changed",{messageId:X0(),revision:W.revision,serverName:W.serverName,contentKind:W.contentKind,added:W.added,removed:W.removed,updated:W.updated});break;case"mcp_resource_updated":q("mcp.resource.updated",{messageId:X0(),revision:W.revision,serverName:W.serverName,uri:W.uri});break;case"mcp_connection_changed":q("mcp.connection.changed",{messageId:X0(),revision:W.revision,serverName:W.serverName,phase:W.phase,reason:W.reason,attempt:W.attempt,maxAttempts:W.maxAttempts,nextRetryAt:W.nextRetryAt,error:W.error});break;case"mcp_log":q("mcp.log",{messageId:X0(),revision:W.revision,serverName:W.serverName,level:W.level,logger:W.logger,message:W.message,projectedBytes:W.projectedBytes,dataSha256:W.dataSha256,truncated:W.truncated,detailsOmitted:W.detailsOmitted,timestamp:W.timestamp,synthetic:W.synthetic});break;case"mcp_instructions_changed":q("mcp.instructions.changed",{messageId:X0(),revision:W.revision,serverName:W.serverName,action:W.action,reason:W.reason,text:W.text,sourceBytes:W.sourceBytes,projectedBytes:W.projectedBytes,sha256:W.sha256,truncated:W.truncated,detailsOmitted:W.detailsOmitted});break;case"mcp_task_changed":q("mcp.task.changed",{messageId:X0(),revision:W.revision,taskId:W.taskId,serverName:W.serverName,toolName:W.toolName,status:W.status,statusMessage:W.statusMessage,createdAt:W.createdAt,updatedAt:W.updatedAt,completedAt:W.completedAt,hasResult:W.hasResult,error:W.error});break;case"project_rules_loaded":q("project.rules.loaded",{messageId:X0(),files:W.files,triggerPaths:W.triggerPaths,blockedWrite:W.blockedWrite});break;case"steering_applied":q("steering.applied",{runId:b,messageIds:W.messageIds,count:W.count,recovered:W.recovered,delivery:W.delivery,queued:I.getPendingSteeringCount()});break;case"follow_up_started":{if(E)q("message.complete",{messageId:E}),E=void 0;for(let J0 of W.messages){if(!J0.recovered||J0.persisted)continue;q("message.created",{messageId:J0.id,role:"user",content:Z1(J0.content),recovered:!0})}q("follow_up.started",{runId:b,queued:W.queued,recovered:W.recovered}),X0();break}case"goal_updated":q("goal.updated",{goal:W.goal});break;case"goal_continuation_started":q("goal.continuation.started",{goal:W.goal,continuation:W.continuation}),X0();break;case"compaction":q(W.phase==="start"?"compaction.started":"compaction.completed",{...W.reason?{reason:W.reason}:{},...W.strategy?{strategy:W.strategy}:{},...W.outcome?{outcome:W.outcome}:{},...W.preTokens!==void 0?{preTokens:W.preTokens}:{},...W.postTokens!==void 0?{postTokens:W.postTokens}:{}});break;case"model_fallback":q("model.fallback",{});break;case"task_update":q("task.updated",{tasks:W.tasks});break;default:break}},R0=await e$(u.chatStream(J,b$,{stream:!0,pendingInputOnly:z.pendingInputOnly,preparedInputTurn:z.preparedInputTurn,goalContinuationOnly:z.goalContinuationOnly,outputSchema:z.outputSchema,taskAdmission:z.taskAdmission}),R$);if(!R0.success)throw Error(R0.error?.message??"Agent run failed");for(let W=0;W<20;W++){let J0=$.pendingFollowUpRequested===!0;if($.pendingFollowUpRequested=!1,I.getPendingSteeringCount()===0){if(!J0)break;continue}if(X.signal.aborted)break;if(R0=await e$(u.chatStream("",b$,{stream:!0,pendingInputOnly:!0,taskAdmission:z.taskAdmission}),R$),!R0.success)throw Error(R0.error?.message??"Agent follow-up failed")}if(O.messages=await C.loadSession(O.id,O.projectPath),O.updatedAt=new Date,await u0(O),X.signal.aborted||$.status==="cancelled"){await t(),q("session.status",{status:"idle"});return}if(E)q("message.complete",{messageId:E});q("thinking.completed",{}),$.status="completed",O.taskStatus="completed",O.taskCompletedAt??=new Date().toISOString(),q("session.completed",{runId:b,outputTruncated:R0.metadata?.outputTruncated??!1}),q("session.status",{status:"idle"})}catch(I){if(G&&z.preparedInputTurn)await G.finishTurn(z.preparedInputTurn.handle).catch(()=>{return});if(X.signal.aborted||$.status==="cancelled"){H$($,"runtime-abort"),await t(),q("session.status",{status:"idle"});return}await u0(O).catch(()=>{return}),y.error("[SessionRoutes] Agent execution error:",I),$.status="failed",O.taskStatus="failed",O.taskCompletedAt??=new Date().toISOString();let O0=f$(I);if(!O.taskFailure){let v=G?await G.setTaskStatus("failed",I).catch(()=>{return}):await C.updateSessionMetadata(O.id,O.projectPath,{taskStatus:"failed",taskStatusReason:O0.message,taskFailure:O0,taskCompletedAt:O.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(v)B$(O,v)}O.taskStatusReason??=O0.message,O.taskFailure??=O0,q("session.error",{error:O.taskFailure.message,taskFailure:O.taskFailure}),q("session.status",{status:"error"})}finally{if(z.taskAdmission?.release(),z.taskAdmission){let I=r0.getStats();q("task.status",{taskStatus:O.taskStatus,...O.taskStatusReason?{taskStatusReason:O.taskStatusReason}:{},...O.taskFailure?{taskFailure:O.taskFailure}:{},...O.taskStartedAt?{taskStartedAt:O.taskStartedAt}:{},...O.taskCompletedAt?{taskCompletedAt:O.taskCompletedAt}:{},...O.taskDiffStat?{taskDiffStat:O.taskDiffStat}:{},taskQueueDepth:I.queued,taskConcurrencyLimit:I.maxConcurrent,taskInFlight:I.inFlight,updatedAt:new Date().toISOString()})}if(await u?.destroy().catch(()=>{return}),$.disposeRuntimeOnSettle&&z.disposeRuntime)await z.disposeRuntime(O,G).catch((I)=>{y.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${O.id}:`,I)});W2($)}}async function R4($,O,J){y.info(`[SessionRoutes] Looking for permission ${O} in session ${$.sessionId}`),y.info(`[SessionRoutes] Active runs: ${q0.size}`);for(let[z,X]of q0.entries())if(y.info(`[SessionRoutes] Checking run ${z}: sessionId=${X.sessionId}, projectPath=${X.projectPath}, pendingPermission=${X.pendingPermission?.permissionId}`),X.sessionId===$.sessionId&&X.projectPath===$.projectPath&&X.pendingPermission?.permissionId===O){if(X.pendingPermission.details.interactionRequestId)await p0.respond($.projectPath,$.sessionId,O,J);return X.pendingPermission.resolve(J),y.info(`[SessionRoutes] Permission ${O} responded, runId: ${X.id}`),!0}let Z=await p0.findPending($.projectPath,$.sessionId);if(!Z||Z.request.requestId!==O)return y.error(`[SessionRoutes] Permission not found: ${O}`),!1;await p0.respondAndRecover($.projectPath,$.sessionId,O,J);let Y=n.get(h($));if(!Y){let z=await C.findSessionMetadata($.sessionId,$.projectPath);if(!z)return!1;let[X,F]=await Promise.all([C.loadSession($.sessionId,$.projectPath),C.findSessionTaskWorktree($.sessionId,$.projectPath)]);Y=D$(z,X,F),n.set(h($),Y)}else await u0(Y);if(j.publish($,"interaction.resolved",{requestId:O}),J$)J$(Y).catch((z)=>{y.error(`[SessionRoutes] Failed to resume recovered interaction ${O}:`,z)});return!0}var Q1=d("Service"),A2=D.Object({approved:D.Boolean(),remember:D.Optional(D.Boolean()),scope:D.Optional(V0(["once","session","project"])),targetMode:D.Optional(V0(["default","autoEdit","plan","yolo"])),feedback:D.Optional(D.String({maxLength:4000})),answers:D.Optional(D.Record(D.String({maxLength:80}),D.Union([D.String({maxLength:4000}),D.Array(D.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:D.Optional(D.Object({action:V0(["accept","decline","cancel"]),content:D.Optional(D.Record(D.String(),D.Union([D.String({maxLength:4000}),D.Number(),D.Boolean(),D.Array(D.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),j4=()=>{let $=new w2;return $.post("/:permissionId",async(O)=>{let J=O.req.param("permissionId"),Z=O.req.query("sessionId"),Y=O.req.query("projectPath");Q1.info(`[PermissionRoutes] Received permission response: permissionId=${J}, sessionId=${Z}`);try{let z=await O.req.json(),X=m(A2,z);if(!X.success)throw new _("Invalid permission response format");let{approved:F,remember:b,scope:B,targetMode:M,feedback:E,answers:G,elicitation:u}=X.data;if(!Z)throw new _("sessionId query parameter is required");let Y0=await z0(Z,Y);if(!await R4(Y0,J,{approved:F,reason:E,scope:B,targetMode:M,feedback:E,answers:G,elicitation:u}))throw new f("Permission request",J);return Q1.info(`[PermissionRoutes] Permission ${J} ${F?"approved":"denied"}`),O.json({success:!0,approved:F,remember:b})}catch(z){if(Q1.error("[PermissionRoutes] Failed to respond to permission:",z),z instanceof _||z instanceof H0||z instanceof f||z instanceof e)throw z;throw z}}),$};import C4 from"node:path";import{Hono as M2}from"hono";var E2=D.Object({projectPath:D.String({minLength:1}),enabled:D.Boolean(),scope:D.Optional(V0(["local","project","global"]))}),T2=D.Object({projectPath:D.String({minLength:1})}),q2=D.Object({projectPath:D.String({minLength:1}),source:D.String({minLength:1}),trust:D.Literal(!0),ref:D.Optional(D.String({minLength:1}))}),b2=D.Object({projectPath:D.String({minLength:1}),trust:D.Literal(!0)}),R2=D.Object({projectPath:D.String({minLength:1}),confirm:D.Literal(!0)}),j2=D.Object({projectPath:D.String({minLength:1}),source:D.String({minLength:1}),ref:D.Optional(D.String({minLength:1}))}),k4=D.Object({projectPath:D.String({minLength:1}),confirm:D.Optional(D.Literal(!0))}),C2=D.Object({projectPath:D.String({minLength:1}),scope:D.Optional(V0(["local","project","global"])),policy:D.Object({restrictToAllowedSources:D.Boolean(),requireGitCommitSha:D.Boolean(),allowedGitHosts:D.Array(D.String()),allowedMarketplaces:D.Array(D.String()),allowedLocalRoots:D.Array(D.String())})});function B0($){if(!$||!C4.isAbsolute($))throw new _("projectPath must be absolute");return C4.resolve($)}async function I4($){let[O,J]=await Promise.all([W0($),N$.getInstance().loadWorkspacePluginSettingsResolution($)]);return O.plugins.getAll().map((Z)=>({name:Z.manifest.name,description:Z.manifest.description,version:Z.manifest.version,source:Z.source,enabled:Z.status==="active",status:Z.status,commands:Z.commands.length,skills:Z.skills.length,agents:Z.agents.length,hooks:Z.hooks?Object.values(Z.hooks).reduce((Y,z)=>Y+(Array.isArray(z)?z.length:0),0):0,mcpServers:Object.keys(Z.mcpServers??{}).length,configurable:Z.source!=="cli",managed:Z.installation!==void 0,marketplace:Z.installation?.source.type==="marketplace"?Z.installation.source.marketplace:void 0,revision:Z.installation?.revision,installedAt:Z.installation?.installedAt,updatedAt:Z.installation?.updatedAt,compatibilityIssues:Z.compatibilityIssues??[],effectiveScope:Z.source==="cli"?"invocation":J.settings[Z.manifest.name]?.effectiveScope??"default",settingLayers:Z.source==="cli"?{invocation:!0}:J.settings[Z.manifest.name]?.layers??{}}))}async function k2(){let $=P4(),[O,J]=await Promise.all([$.listCatalogs(),$.listInstallationRecords()]),Z=new Map(J.map((Y)=>[Y.name,Y]));return O.map(({marketplace:Y,manifest:z})=>({name:Y.name,description:z.description??z.metadata?.description??"",sourceType:Y.source.type,revision:Y.revision,updatedAt:Y.updatedAt,plugins:z.plugins.map((X)=>{let F=Z.get(X.name);return{name:X.name,description:X.description??"",version:X.version,category:X.category,tags:X.tags??[],installed:F!==void 0,installedVersion:F?.version}})}))}function Z$($,O){if(!$.success)throw new _($.error??O)}var d4=()=>{let $=new M2;return $.get("/",async(O)=>{let J=B0(O.req.query("projectPath"));return O.json(await I4(J))}),$.post("/refresh",async(O)=>{let J=m(T2,await O.req.json());if(!J.success)throw new _("Invalid plugin refresh request");let Z=B0(J.data.projectPath),Y=await f4(Z);return O.json({plugins:await I4(Z),errors:Y.discovery.errors.map((z)=>({code:z.code??"LOAD_ERROR",error:z.error}))})}),$.get("/catalog",async(O)=>{return B0(O.req.query("projectPath")),O.json(await k2())}),$.get("/policy",async(O)=>{let J=B0(O.req.query("projectPath")),Z=await N$.getInstance().loadWorkspacePluginSourcePolicy(J);return O.json({policy:Z,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),$.post("/policy",async(O)=>{let J=m(C2,await O.req.json());if(!J.success)throw new _("Invalid plugin source policy request");let Z=B0(J.data.projectPath),Y=await y4(Z,J.data.policy,J.data.scope??"global");return O.json({policy:Y})}),$.post("/install",async(O)=>{let J=m(q2,await O.req.json());if(!J.success)throw new _("Invalid plugin install request; explicit source trust is required");let Z=B0(J.data.projectPath),{result:Y}=await m4(Z,J.data.source,{trusted:J.data.trust,ref:J.data.ref});return Z$(Y,"Plugin installation failed"),O.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,installedDependencies:Y.installedDependencies??[]})}),$.post("/marketplaces",async(O)=>{let J=m(j2,await O.req.json());if(!J.success)throw new _("Invalid marketplace add request");let Z=B0(J.data.projectPath),Y=await v4(Z,J.data.source,J.data.ref);return Z$(Y,"Marketplace installation failed"),O.json({name:Y.marketplace?.name,plugins:Y.manifest?.plugins.length??0,revision:Y.marketplace?.revision,changed:Y.changed})}),$.post("/marketplaces/:name/refresh",async(O)=>{let J=m(k4,await O.req.json());if(!J.success)throw new _("Invalid marketplace refresh request");let Z=await p4(B0(J.data.projectPath),O.req.param("name"));return Z$(Z,"Marketplace refresh failed"),O.json({name:Z.marketplace?.name,plugins:Z.manifest?.plugins.length??0,revision:Z.marketplace?.revision,changed:Z.changed})}),$.post("/marketplaces/:name/remove",async(O)=>{let J=m(k4,await O.req.json());if(!J.success||J.data.confirm!==!0)throw new _("Invalid marketplace removal request; explicit confirmation is required");B0(J.data.projectPath);let Z=await u4(O.req.param("name"),!0);return Z$(Z,"Marketplace removal failed"),O.json({name:Z.marketplace?.name,removed:!0})}),$.post("/:name/update",async(O)=>{let J=m(b2,await O.req.json());if(!J.success)throw new _("Invalid plugin update request; explicit source trust is required");let Z=B0(J.data.projectPath),{result:Y}=await h4(Z,O.req.param("name"),{trusted:J.data.trust});return Z$(Y,"Plugin update failed"),O.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,updatedDependencies:Y.updatedDependencies??[]})}),$.post("/:name/uninstall",async(O)=>{let J=m(R2,await O.req.json());if(!J.success)throw new _("Invalid plugin uninstall request; explicit confirmation is required");let Z=B0(J.data.projectPath),{result:Y}=await g4(Z,O.req.param("name"),J.data.confirm);return Z$(Y,"Plugin uninstall failed"),O.json({name:Y.pluginName,removed:!0})}),$.post("/:name/state",async(O)=>{let J=m(E2,await O.req.json());if(!J.success)throw new _("Invalid plugin state request");let Z=B0(J.data.projectPath),Y=O.req.param("name"),X=(await W0(Z)).plugins.get(Y);if(!X)throw new f("Plugin",Y);if(X.source==="cli")throw new _(`Plugin "${Y}" was loaded with --plugin-dir and is invocation-scoped`);let F=await S4(Z,Y,J.data.enabled,J.data.scope??"local");return O.json(F)}),$};import{Hono as y2}from"hono";import{execFile as I2}from"node:child_process";import P2 from"node:path";var z1="__BLADE_DIRECTORY_PICKER_CANCELLED__",S2=900000;function f2($,O){return new Promise((J)=>{I2($,[...O],{timeout:S2,maxBuffer:65536,windowsHide:!0},(Z,Y,z)=>{let X=Z?.code;J({stdout:Y,stderr:z,exitCode:typeof X==="number"?X:Z?1:0,...typeof X==="string"?{errorCode:X}:{}})})})}function x1($){let O=$.replace(/[\r\n]+$/,"");if(!O||O===z1)return{cancelled:!0};if(!P2.isAbsolute(O))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:O}}function X1($){return $.exitCode!==0||Boolean($.errorCode)}class l4{platform;runCommand;activeSelection=null;constructor($={}){this.platform=$.platform??process.platform,this.runCommand=$.runCommand??f2}pick(){if(this.activeSelection)return this.activeSelection;let $=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=$,$}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 $=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${z1}"`,"end try"].join(`
6
+ `,Buffer.byteLength(O)}class K${serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor($){this.maxPendingItems=$.maxPendingItems??S1,this.maxPendingBytes=$.maxPendingBytes??f1,this.serial=new m1({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:$.writeTimeoutMs??y1,sizeOf:P1,write:$.write,onFailure:(O)=>{this.failure=O,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,$.onFailure?.(O)}})}async writeInitial($){await this.offerDirect($)}observe($,O){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer($,O);return}this.offerLive($,O)}async writeReplay($,O){if(!Number.isSafeInteger(O)||O<=0)throw this.fail(new n0("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if(O<=this.highestReplaySequence)return;await this.offerDirect($),this.highestReplaySequence=O,this.highestDeliveredSequence=O}finishInitialization($){if(this.phase!=="buffering")return;let O=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let J=$.replayed?O.filter((Y)=>Y.sequence!==void 0&&Y.sequence>this.highestReplaySequence).sort((Y,z)=>Y.sequence-z.sequence||Y.order-z.order):O.sort((Y,z)=>Y.order-z.order),Z;for(let Y of J){if($.replayed&&Y.sequence!==void 0&&Y.sequence===Z)continue;if(this.offerLive(Y.message,Y.sequence),this.serial.stats().closed)return;Z=Y.sequence}}offerHeartbeat($){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive($),!this.serial.stats().closed}async flush(){await this.serial.flush()}close($){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close($)}stats(){let $=this.serial.stats();return{closed:this.phase==="closed",pendingItems:$.pendingItems+this.buffered.length,pendingBytes:$.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer($,O){let J=P1($),Z=this.serial.stats();if(J>this.maxPendingBytes){this.fail(new n0("oversized",`SSE frame requires ${J} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:Z.pendingItems+this.buffered.length,pendingBytes:Z.pendingBytes+this.bufferedBytes}));return}if(Z.pendingItems+this.buffered.length>=this.maxPendingItems||Z.pendingBytes+this.bufferedBytes+J>this.maxPendingBytes){this.fail(new n0("overflow","SSE initialization buffer limit exceeded",{pendingItems:Z.pendingItems+this.buffered.length,pendingBytes:Z.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:$,bytes:J,sequence:O,order:this.nextOrder}),this.bufferedBytes+=J}offerLive($,O){if(O!==void 0){if(O<=this.highestReplaySequence)return;if(O<=this.highestDeliveredSequence){this.fail(new n0("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=O}if(!this.serial.offer($).accepted)this.phase="closed"}async offerDirect($){if(this.phase==="closed")throw this.currentFailure();let O=this.serial.offer($);if(!O.accepted)throw this.phase="closed",O.error;await O.completion}fail($){this.serial.close($)}currentFailure(){return this.failure??new n0("closed","SSE egress is closed")}}var pO=15000,uO=d("Service"),dO=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),lO=new Set(["queued","running","completed","failed","cancelled","interrupted"]);function cO($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$,J=["changedFiles","additions","deletions","commits"];if(J.some((Z)=>typeof O[Z]!=="number"||!Number.isInteger(O[Z])||O[Z]<0))return;return Object.fromEntries(J.map((Z)=>[Z,O[Z]]))}function V$($,O){return typeof $==="number"&&Number.isInteger($)&&$>=O?$:void 0}function iO($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$;if(!["applied","discarded","conflicted"].includes(String(O.status))||typeof O.updatedAt!=="string")return;return{status:O.status,updatedAt:O.updatedAt,...typeof O.sourceCommit==="string"?{sourceCommit:O.sourceCommit}:{},...V$(O.changedFiles,0)!==void 0?{changedFiles:O.changedFiles}:{},...typeof O.message==="string"?{message:O.message}:{}}}var h1=()=>{let $=new gO;return $.get("/",(O)=>vO(O,async(J)=>{let Z,Y,z=!1,X,F,b=new Promise((G)=>{F=G}),B=()=>{if(Y!==void 0)clearInterval(Y),Y=void 0;Z?.(),Z=void 0},M=(G)=>{if(z)return;z=!0,B(),X?.close(G),F()};J.onAbort(M),X=new K$({write:async(G)=>{await J.writeSSE(G)},onFailure:(G)=>{uO.warn(`[EventRoutes] SSE egress closed: kind=${G.kind} pendingItems=${G.pendingItems??0} pendingBytes=${G.pendingBytes??0}`),M(G)}});let E=(G,u)=>{X?.observe({data:JSON.stringify({type:G,properties:u})})};Z=j.subscribe((G)=>{if(!dO.has(G.type))return;if(G.type==="permission.asked"||G.type==="question.required"||G.type==="elicitation.required"){let v=G.properties.requestId;if(typeof v!=="string"||!v)return;E("interaction.pending",{sessionId:G.sessionId,projectPath:G.projectPath,interactionType:G.type==="question.required"?"question":G.type==="elicitation.required"?"elicitation":"permission",requestId:v});return}if(G.type==="interaction.resolved"){let v=G.properties.requestId;if(typeof v!=="string"||!v)return;E(G.type,{sessionId:G.sessionId,projectPath:G.projectPath,requestId:v});return}if(G.type==="session.created"||G.type==="session.deleted"){E(G.type,{sessionId:G.sessionId,projectPath:G.projectPath});return}if(G.type==="session.updated"){let v=G.properties.title;if(typeof v!=="string"||!v.trim())return;E(G.type,{sessionId:G.sessionId,projectPath:G.projectPath,title:v});return}if(G.type==="task.delivery"){let v=iO(G.properties.taskDelivery);if(!v)return;E(G.type,{sessionId:G.sessionId,projectPath:G.projectPath,taskDelivery:v,...G.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof G.properties.updatedAt==="string"?{updatedAt:G.properties.updatedAt}:{}});return}if(G.type==="schedule.fired"){let v=G.properties.scheduleId,m0=G.properties.firedAt;if(typeof v!=="string"||typeof m0!=="string")return;E(G.type,{scheduleId:v,firedAt:m0,sessionId:G.sessionId,projectPath:G.projectPath,...typeof G.properties.runId==="string"?{runId:G.properties.runId}:{},...typeof G.properties.status==="string"?{status:G.properties.status}:{}});return}let u=G.properties.taskStatus;if(typeof u!=="string"||!lO.has(u))return;let Y0=cO(G.properties.taskDiffStat),q=V$(G.properties.taskQueuePosition,1),t=V$(G.properties.taskQueueDepth,0),I=V$(G.properties.taskConcurrencyLimit,1),O0=V$(G.properties.taskInFlight,0);E(G.type,{sessionId:G.sessionId,projectPath:G.projectPath,taskStatus:u,...typeof G.properties.taskStatusReason==="string"?{taskStatusReason:G.properties.taskStatusReason}:{},...G.properties.taskFailure&&typeof G.properties.taskFailure==="object"?{taskFailure:G.properties.taskFailure}:{},...typeof G.properties.taskStartedAt==="string"?{taskStartedAt:G.properties.taskStartedAt}:{},...typeof G.properties.taskCompletedAt==="string"?{taskCompletedAt:G.properties.taskCompletedAt}:{},...typeof G.properties.updatedAt==="string"?{updatedAt:G.properties.updatedAt}:{},...Y0?{taskDiffStat:Y0}:{},...q!==void 0?{taskQueuePosition:q}:{},...t!==void 0?{taskQueueDepth:t}:{},...I!==void 0?{taskConcurrencyLimit:I}:{},...O0!==void 0?{taskInFlight:O0}:{}})});try{if(J.aborted||z)return;if(await X.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),J.aborted||z)return;if(X.finishInitialization({replayed:!1}),J.aborted||z)return;Y=setInterval(()=>{if(J.aborted||z)return;X?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},pO),await b}finally{M()}})),$};import{Hono as aO}from"hono";var v1=()=>{let $=new aO;return $.get("/health",(O)=>{return O.json({healthy:!0,version:t0()})}),$.get("/info",(O)=>{let J=g(),Z=$0();if(Z)r0.configure(Z.maxConcurrentTasks,Z.maxQueuedTasks);return O.json({version:t0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:J,gitBranch:g1(J),taskAdmission:r0.getStats()})}),$};import p1 from"node:path";import{Hono as oO}from"hono";var nO=D.Object({projectPath:D.String({minLength:1}),action:V0(["trust","revoke"]),expectedDigest:D.Optional(D.String())}),tO=D.Object({projectPath:D.String({minLength:1}),sessionId:D.String({minLength:1}),enabled:D.Boolean()});function a$($){if(!$||!p1.isAbsolute($))throw new _("projectPath must be absolute");return p1.resolve($)}function u1($){if(!$)throw new _("sessionId is required");try{C$($)}catch(O){throw new _(O instanceof Error?O.message:"sessionId is invalid")}return $}async function j$($){let O=a$($),J=$0()?.hooks??c1.hooks,Z=await N$.getInstance().loadWorkspaceHooks(O,J,{includeBaseForCurrentWorkspace:!1});await W0(O),W$(O);let Y=s0.getInstance();return Y.loadConfig(Z,O),await G$(O),Y.getConfig(O)}function d1($,O){let J=s0.getInstance(),Z=J.getConfig(O).enabled,Y=J.isSessionPaused($,O);return{sessionId:$,projectPath:O,enabled:J.isSessionEnabled($,O),paused:Y,configEnabled:Z}}var i1=()=>{let $=new oO;return $.get("/trust",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return await j$(J),O.json(await s0.getInstance().getTrustStatus(J))}),$.post("/trust",async(O)=>{let J=m(nO,await O.req.json());if(!J.success)throw new _("Invalid hook trust request");let{projectPath:Z,action:Y,expectedDigest:z}=J.data;await j$(Z);let X=s0.getInstance(),F;try{F=Y==="trust"?await X.trustProject(Z,z):await X.revokeProjectTrust(Z)}catch(b){if(b instanceof l1)throw new k(b.message);throw b}return O.json(F)}),$.get("/session",async(O)=>{let J=a$(O.req.query("projectPath")),Z=u1(O.req.query("sessionId"));return await j$(J),O.json(d1(Z,J))}),$.post("/session",async(O)=>{let J=m(tO,await O.req.json());if(!J.success)throw new _("Invalid hook session request");let Z=a$(J.data.projectPath),Y=u1(J.data.sessionId);await j$(Z);let z=s0.getInstance();if(J.data.enabled)z.enableSession(Y,Z);else z.disableSession(Y,Z);return O.json(d1(Y,Z))}),$};import{Hono as rO}from"hono";var E0=d("Service");function sO($){try{return o1($)}catch{return[]}}function eO($){if(!k$($)||!k$($.reference)||!k$($.argument))throw Error("Invalid MCP completion request");let O=$.reference.type,J=O==="prompt"&&typeof $.reference.name==="string"?{type:"prompt",name:$.reference.name}:O==="resource"&&typeof $.reference.uri==="string"?{type:"resource",uri:$.reference.uri}:void 0;if(!J||typeof $.argument.name!=="string"||typeof $.argument.value!=="string")throw Error("Invalid MCP completion request");let Z;if($.context!==void 0){if(!k$($.context))throw Error("Invalid MCP completion context");Z=Object.create(null);for(let[Y,z]of Object.entries($.context)){if(typeof z!=="string")throw Error("Invalid MCP completion context");Z[Y]=z}}return{reference:J,argument:{name:$.argument.name,value:$.argument.value},...Z?{context:Z}:{}}}function k$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}async function C0($,O){let J=$0()?.mcpServers??{};for(let[Z,Y]of Object.entries(J)){if(O&&Z!==O)continue;if(!$.getServerStatus(Z))await $.registerServer(Z,Y,{connect:!1})}}var n1=()=>{let $=new rO;return $.get("/",async(O)=>{try{let J=N0.getInstance();await C0(J);let Z=J.getAllServers(),Y=await Promise.all(Array.from(Z.entries()).map(async([z,X])=>({id:z,name:z,status:X.status==="connected"?"connected":X.status==="reconnecting"?"reconnecting":X.status==="connecting"?"connecting":X.lastError?"error":"offline",endpoint:X.config.command?`${X.config.command} ${(X.config.args||[]).join(" ")}`.trim():X.config.url||"Unknown",description:`MCP server: ${z}`,tools:X.tools.map((F)=>F.name),completionSupported:X.client.completionSupported,tasks:X.client.tasks,resources:X.contentCatalog.resources,resourceTemplates:X.contentCatalog.resourceTemplates.map((F)=>({...F,variables:sO(F.uriTemplate)})),prompts:X.contentCatalog.prompts,connectedAt:X.connectedAt?.toISOString(),error:X.lastError?.message,recovery:X.recovery,logging:X.logging,instructions:X.instructions,oauthEnabled:X.client.oauthEnabled,oauthStatus:await X.client.getOAuthStatus()})));return O.json(Y)}catch(J){return E0.error("[McpRoutes] Failed to get MCP servers:",J),O.json({error:J instanceof Error?J.message:"Failed to get MCP servers"},500)}}),$.post("/:name/connect",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();return await C0(Z,J),await Z.connectServer(J),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to connect MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.post("/:name/disconnect",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();return await C0(Z,J),await Z.disconnectServer(J),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to disconnect MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.get("/:name/logs",async(O)=>{try{let J=O.req.param("name"),Z=Number(O.req.query("limit")??20),Y=Number(O.req.query("afterRevision")??0);if(!Number.isSafeInteger(Z)||Z<1||Z>100||!Number.isSafeInteger(Y)||Y<0)return O.json({error:"Invalid MCP log pagination"},400);let z=N0.getInstance();return await C0(z,J),O.json(z.getLogSnapshot(J,{limit:Z,afterRevision:Y}))}catch(J){return E0.error("[McpRoutes] Failed to get MCP logs:",J),O.json({error:J.message},500)}}),$.post("/:name/logging-level",async(O)=>{try{let J=O.req.param("name"),Z=await O.req.json();if(!a1(Z.level))return O.json({success:!1,error:"Invalid MCP logging level"},400);let Y=N0.getInstance();return await C0(Y,J),await Y.setServerLoggingLevel(J,Z.level),O.json({success:!0,level:Z.level})}catch(J){return E0.error("[McpRoutes] Failed to set MCP logging level:",J),O.json({success:!1,error:J.message},400)}}),$.post("/:name/complete",async(O)=>{try{let J=O.req.param("name"),Z=eO(await O.req.json()),Y=N0.getInstance();await C0(Y,J);let z=await Y.complete(J,Z);return O.json(z)}catch(J){return E0.error("[McpRoutes] Failed to complete MCP argument:",J),O.json({error:J.message},400)}}),$.post("/:name/oauth/login",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();await C0(Z,J);let Y=await Z.beginOAuthLogin(J);return O.json({success:!0,flowId:Y.flowId,authorizationUrl:Y.authorizationUrl},202)}catch(J){return E0.error("[McpRoutes] Failed to start MCP OAuth login:",J),O.json({success:!1,error:J.message},400)}}),$.post("/:name/oauth/logout",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();return await C0(Z,J),await Z.logoutOAuth(J),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to log out MCP OAuth:",J),O.json({success:!1,error:J.message},400)}}),$.delete("/:name",async(O)=>{try{let J=O.req.param("name");await N0.getInstance().unregisterServer(J);let Y=$0();if(Y?.mcpServers){let{[J]:z,...X}=Y.mcpServers;await _0().updateConfig({mcpServers:X})}return O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to delete MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.post("/",async(O)=>{try{let J=await O.req.json(),{name:Z,config:Y}=J;if(!Z||!Y)return O.json({success:!1,error:"Missing name or config"},400);await N0.getInstance().registerServer(Z,Y);let X=$0();return await _0().updateConfig({mcpServers:{...X?.mcpServers,[Z]:Y}}),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to add MCP server:",J),O.json({success:!1,error:J.message},500)}}),$};import{getSupportedThinkingLevels as $2}from"@earendil-works/pi-ai";import{Hono as O2}from"hono";var I$=d("Service");function J2($,O,J=e1.list()){return{id:$.id,displayName:$.displayName,provider:$.provider,model:$.model,overrides:$.overrides,fallbackModels:$.fallbackModels,contextWindow:O.contextWindow,maxTokens:O.maxTokens,reasoning:O.reasoning,supportedReasoningEfforts:$2(O),supportedServiceTiers:r1(O),supportedResponseVerbosities:t1(O),communicationStyles:J,input:O.input}}function Z2($){$4($.overrides);let O={displayName:$.displayName||void 0,overrides:$.overrides||void 0};if($.model)O.model=$.model;return O}function $4($){let O=$?.streamIdleTimeout;if(O!==void 0&&(!Number.isFinite(O)||O<1000))throw new _("streamIdleTimeout must be at least 1000ms")}var O4=()=>{let $=new O2;return $.get("/",async(O)=>{try{let J=$0();if(!J)throw Error("Config not initialized");let Z=O.get("directory")||g(),[Y,z]=await Promise.all([P$(Z,J),W0(Z)]),X=Y.config.models,F=X.find((E)=>E.id===Y.config.currentModelId)??X[0],b=Y.catalog,B=z.communicationStyles.list(),M=(E)=>J2(E,b.resolveConfig(E),B);return O.json({configured:X.map(M),current:F?M(F):null})}catch(J){I$.error("[ModelsRoutes] Failed to get models:",J);let Z=new a("Failed to get models");return O.json(Z.toObject(),500)}}),$.post("/",async(O)=>{let J=g0(),Z,Y;try{let z=await O.req.json(),{provider:X,displayName:F,model:b,overrides:B,apiKey:M,modelProvider:E}=z;if(!X||!b)throw new _("provider and model are required");$4(B);let G;if(E){if(E.id!==X)throw new _("modelProvider.id must match the model provider");if($0()?.modelProviders[X])throw new _(`model provider already exists: ${X}`);G={name:E.name,baseUrl:E.baseUrl,wireApi:E.wireApi,...E.apiKeyEnv?{apiKeyEnv:E.apiKeyEnv}:{}};try{J.registerModelProvider(X,G,[b]),Y=X}catch(q){throw new _(q instanceof Error?q.message:"Invalid model provider")}}else J.getModel(X,b);if(M?.trim()){if(await J.setApiKey(X,M.trim()),G)Z=X}let u={provider:X,displayName:F||void 0,model:b,overrides:B||void 0},Y0=G?await _0().addModelWithProvider(u,G):await _0().addModel(u);return O.json({success:!0,model:Y0})}catch(z){if(Z)await J.credentials.delete(Z);if(Y){let X=$0();J.configureModelProviders(X?.modelProviders??{},X?.models??[])}throw I$.error("[ModelsRoutes] Failed to add model:",z),z}}),$.put("/:modelId",async(O)=>{try{let J=O.req.param("modelId"),Z=await O.req.json(),{displayName:Y,overrides:z,model:X}=Z,F=s1(J);if(!F)throw new _("model config not found");if(X)g0().getModel(F.provider,X);return await _0().updateModel(J,Z2({displayName:Y,overrides:z,model:X})),O.json({success:!0})}catch(J){throw I$.error("[ModelsRoutes] Failed to update model:",J),J}}),$.delete("/:modelId",async(O)=>{try{let J=O.req.param("modelId");return await _0().removeModel(J),O.json({success:!0})}catch(J){throw I$.error("[ModelsRoutes] Failed to delete model:",J),J}}),$};import{Hono as w2}from"hono";import J4 from"node:path";import{Mutex as Z4}from"async-mutex";import{Hono as Y2}from"hono";import{streamSSE as Q2}from"hono/streaming";import{LRUCache as x2}from"lru-cache";import{nanoid as $$}from"nanoid";var y=d("Service"),X2=D.Object({title:D.Optional(D.String()),projectPath:D.Optional(D.String())}),z2=M4,K2=D.Object({title:D.Optional(D.String()),projectPath:D.Optional(D.String())}),V2=D.Object({projectPath:D.String()}),N2=D.Object({objective:D.String({minLength:1}),tokenBudget:D.Optional(D.Integer({minimum:1})),permissionMode:D.Optional(V0(["default","autoEdit","plan","yolo"]))}),G2=D.Union([D.Object({action:D.Literal("pause")}),D.Object({action:D.Literal("resume")}),D.Object({action:D.Literal("edit"),objective:D.String({minLength:1})})]),n=new Map,J$,q0=new Map,v0=new Map,b0=new Map,m$=new x2({max:100,ttl:1800000});function Y4($){return{sessionId:$.sessionId,projectPath:$.projectPath}}function G0($){if(!$)return;return q0.get($)??m$.get($)}function W2($){if(q0.get($.id)!==$)return;q0.delete($.id),m$.set($.id,$)}function F2($){q0.delete($),m$.delete($)}function F0($){return $?.status==="queued"||$?.status==="running"||$?.status==="waiting_permission"}function H$($,O="user-cancel"){if($.status==="cancelled"||$.status==="completed"||$.status==="failed")return!1;let J=$.pendingPermission;if($.pendingPermission=void 0,J?.resolve({approved:!1,reason:V4}),J)j.publish(Y4($),"interaction.resolved",{requestId:J.permissionId});return $.abortController.abort(O),$.status="cancelled",j.publish(Y4($),"run.cancelled",{runId:$.id}),!0}function q4($,O=!1){let{permissionId:J,details:Z}=$;if(Z.type==="askUserQuestion"&&Z.questions)return{type:"question.required",properties:{requestId:J,toolCallId:Z.toolCallId??J,questions:Z.questions,details:Z,...O?{replayed:!0}:{}}};if(Z.type==="mcpElicitation"&&Z.mcpElicitation)return{type:"elicitation.required",properties:{requestId:J,toolCallId:Z.toolCallId??J,elicitation:Z.mcpElicitation,...O?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:J,toolName:Z.toolName,description:Z.message,args:Z.args,details:Z,...O?{replayed:!0}:{}}}}function U2($){return{...typeof $.seq==="number"?{id:String($.seq)}:{},data:JSON.stringify({type:$.type,...typeof $.seq==="number"?{seq:$.seq}:{},properties:{...$.properties,sessionId:$.sessionId,projectPath:$.projectPath}})}}function D2(){for(let $ of q0.values())H$($,"route-reset");q0.clear();for(let $ of v0.values())$.controller.abort("route-reset");v0.clear(),m$.clear(),J$=void 0,n.clear()}function H2($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$,J=O.code,Z=O.reason,Y=O.scope,z=O.kind,X=O.limit;if(J!=="tool_busy"&&J!=="tool_batch_full"||Z!=="queue_full"&&Z!=="wait_timeout"&&Z!=="turn_limit"||Y!=="global"&&Y!=="session"||typeof O.retryable!=="boolean"||!Number.isSafeInteger(X)||X<=0||z!==void 0&&z!=="readonly"&&z!=="write"&&z!=="execute")return;return{code:J,reason:Z,scope:Y,retryable:O.retryable,...z===void 0?{}:{kind:z},limit:X}}var _$=($,O)=>{if(!O||typeof O!=="object")return O;let J={...O},Z=H2(J.tool_admission);if(Z)J.tool_admission=Z;else delete J.tool_admission;if($==="Bash"){let X={},F=["message","signal","status","summary"],b=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],B=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let E of F){let G=J[E];if(typeof G==="string")X[E]=G.slice(0,8192)}for(let E of b){let G=J[E];if(typeof G==="boolean")X[E]=G}for(let E of B){let G=J[E];if(typeof G==="number"&&Number.isSafeInteger(G)&&G>=0)X[E]=G}if(J.exit_code===null||typeof J.exit_code==="number"&&Number.isSafeInteger(J.exit_code))X.exit_code=J.exit_code;if(J.terminal_transport==="local"||J.terminal_transport==="acp"||J.terminal_transport==="local_fallback")X.terminal_transport=J.terminal_transport;if(J.background_reason==="explicit"||J.background_reason==="foreground_budget")X.background_reason=J.background_reason;for(let E of["bash_id","shell_id"]){let G=J[E];if(typeof G==="string"&&G.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(G))X[E]=G}if(Z)X.tool_admission=Z;let M=J.background_shell_admission;if(M&&typeof M==="object"&&!Array.isArray(M)){let E=M;if(E.code==="background_shell_busy"&&(E.scope==="session"||E.scope==="global")&&E.retryable===!0&&Number.isSafeInteger(E.limit)&&E.limit>0)X.background_shell_admission={code:E.code,scope:E.scope,retryable:E.retryable,limit:E.limit}}return X}let Y=200000,z=(X,F)=>typeof X==="number"&&Number.isSafeInteger(X)&&X>=0&&X<=F?X:0;if(typeof J.oldContent==="string"&&J.oldContent.length>Y)delete J.oldContent;if(typeof J.newContent==="string"&&J.newContent.length>Y)delete J.newContent;if(J.mcpResult&&typeof J.mcpResult==="object"&&!Array.isArray(J.mcpResult)){let X=J.mcpResult,F=Array.isArray(X.artifacts)?X.artifacts.slice(0,64).flatMap((b)=>{if(!b||typeof b!=="object"||Array.isArray(b))return[];let B=b,M=new Set(["text","image","audio","resource"]);if(typeof B.id!=="string"||!/^[a-f0-9]{64}$/.test(B.id)||typeof B.sha256!=="string"||B.sha256!==B.id||typeof B.kind!=="string"||!M.has(B.kind)||z(B.size,67108864)!==B.size||typeof B.persisted!=="boolean")return[];return[{id:B.id.slice(0,128),sha256:B.sha256.slice(0,128),kind:B.kind,size:B.size,persisted:B.persisted,...typeof B.mimeType==="string"?{mimeType:B.mimeType.slice(0,256)}:{},...typeof B.sourceUri==="string"?{sourceUri:B.sourceUri.slice(0,8192)}:{},...typeof B.path==="string"?{path:B.path.slice(0,8192)}:{}}]}):[];J.mcpResult={isError:X.isError===!0,contentCount:z(X.contentCount,64),textBytes:z(X.textBytes,4194304),structuredBytes:z(X.structuredBytes,4194304),artifactCount:z(X.artifactCount,64),truncated:X.truncated===!0,binaryOmitted:X.binaryOmitted===!0,artifacts:F}}else delete J.mcpResult;return J};function _2($){let O=typeof $.seq==="number"?{seq:$.seq}:{};if($.type==="part_created"&&$.data.partType==="tool_call"){let J=$.data.payload;return{type:"tool.start",...O,properties:{messageId:$.data.messageId,toolCallId:J.toolCallId??$.data.partId,toolName:J.toolName??"unknown",arguments:JSON.stringify(J.input??{})}}}if($.type==="part_created"&&$.data.partType==="tool_result"){let J=$.data.payload,Z=J.toolName??"unknown",Y=Y1(J),z=w$(A$(Z,Y),L$);return{type:"tool.result",...O,properties:{messageId:$.data.messageId,toolCallId:J.toolCallId??$.data.partId,toolName:Z,success:Y.success,status:Y.success?"completed":"failed",summary:Y.metadata?.summary,output:M$(z),metadata:_$(Z,Y.metadata)}}}return{type:`committed.${$.type}`,...O,properties:{event:$}}}function B2($,O,J){switch(J.kind){case"tool_start":if("function"in J.toolCall)j.publish($,"subagent.update",{subagentSessionId:O,toolName:J.toolCall.function.name}),j.publish($,"subagent.tool.start",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,arguments:J.toolCall.function.arguments,toolKind:J.toolKind});break;case"tool_result":if("function"in J.toolCall)j.publish($,"subagent.tool.result",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,success:J.result.success,summary:J.result.metadata?.summary,output:M$(w$(A$(J.toolCall.function.name,J.result),L$)),metadata:_$(J.toolCall.function.name,J.result.metadata)});break;case"tool_progress":if("function"in J.toolCall)j.publish($,"subagent.tool.progress",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,...J.update});break;case"content_delta":j.publish($,"subagent.delta",{subagentSessionId:O,delta:J.delta});break;case"thinking_delta":j.publish($,"subagent.thinking.delta",{subagentSessionId:O,delta:J.delta});break;case"stream_end":j.publish($,"subagent.stream.end",{subagentSessionId:O});break;case"provider_retry":j.publish($,"subagent.provider.retry",{subagentSessionId:O,phase:J.phase,attempt:J.attempt,maxRetries:J.maxRetries,reason:J.reason,statusCode:J.statusCode,delayMs:J.delayMs,nextRetryAt:J.nextRetryAt,mode:J.mode,recoveryBudgetMs:J.recoveryBudgetMs,recoveryElapsedMs:J.recoveryElapsedMs,recoveryRemainingMs:J.recoveryRemainingMs,exhaustedBy:J.exhaustedBy});break;case"provider_stall":j.publish($,"subagent.provider.stall",{subagentSessionId:O,phase:J.phase,stallCount:J.stallCount,durationMs:J.durationMs,warningAfterMs:J.warningAfterMs,timeoutMs:J.timeoutMs,outputStarted:J.outputStarted});break;case"action_stationarity":j.publish($,"subagent.action.stationarity",{subagentSessionId:O,phase:J.phase,toolName:J.toolName,runLength:J.runLength,nudgeThreshold:J.nudgeThreshold,haltThreshold:J.haltThreshold,progressAware:J.progressAware});break;case"mcp_catalog_changed":j.publish($,"subagent.mcp.catalog.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,added:J.added,removed:J.removed,updated:J.updated});break;case"mcp_content_changed":j.publish($,"subagent.mcp.content.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,contentKind:J.contentKind,added:J.added,removed:J.removed,updated:J.updated});break;case"mcp_resource_updated":j.publish($,"subagent.mcp.resource.updated",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,uri:J.uri});break;case"mcp_connection_changed":j.publish($,"subagent.mcp.connection.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,maxAttempts:J.maxAttempts,nextRetryAt:J.nextRetryAt,error:J.error});break;case"mcp_log":j.publish($,"subagent.mcp.log",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,level:J.level,logger:J.logger,message:J.message,projectedBytes:J.projectedBytes,dataSha256:J.dataSha256,truncated:J.truncated,detailsOmitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});break;case"mcp_instructions_changed":j.publish($,"subagent.mcp.instructions.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,action:J.action,reason:J.reason,text:J.text,sourceBytes:J.sourceBytes,projectedBytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,detailsOmitted:J.detailsOmitted});break;case"mcp_task_changed":j.publish($,"subagent.mcp.task.changed",{subagentSessionId:O,revision:J.revision,taskId:J.taskId,serverName:J.serverName,toolName:J.toolName,status:J.status,statusMessage:J.statusMessage,createdAt:J.createdAt,updatedAt:J.updatedAt,completedAt:J.completedAt,hasResult:J.hasResult,error:J.error});break;case"project_rules_loaded":j.publish($,"subagent.project.rules.loaded",{subagentSessionId:O,files:J.files,triggerPaths:J.triggerPaths,blockedWrite:J.blockedWrite});break;default:break}}function U$($,O="projectPath"){if(!J4.isAbsolute($))throw new _(`${O} must be absolute`);return J4.resolve($)}function J1($){try{C$($)}catch(O){throw new _(O instanceof Error?O.message:`Invalid session ID: ${$}`)}}function x0($){return{sessionId:$.id,projectPath:$.projectPath}}function D$($,O,J){return{id:$.sessionId,projectPath:$.projectPath,title:$.title??`Session ${$.sessionId.slice(0,6)}`,createdAt:new Date($.firstMessageTime),updatedAt:new Date($.lastMessageTime),rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,taskStatus:$.taskStatus,taskStatusReason:$.taskStatusReason,taskFailure:$.taskFailure,taskStartedAt:$.taskStartedAt,taskCompletedAt:$.taskCompletedAt,taskPromptSummary:$.taskPromptSummary,taskModelId:$.taskModelId,selectedModelId:$.selectedModelId,permissionMode:$.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,communicationStyleDigest:$.communicationStyleDigest,projectInstructionsDigest:$.projectInstructionsDigest,pendingInteraction:$.pendingInteraction,taskRetryAvailable:$.taskRetryAvailable,taskRetriedFrom:$.taskRetriedFrom,taskDelivery:$.taskDelivery,taskIsolation:$.taskIsolation,taskSourceProjectPath:$.taskSourceProjectPath,taskWorktreePath:$.taskWorktreePath,taskWorktreeBranch:$.taskWorktreeBranch,taskBaseCommit:$.taskBaseCommit,taskDiffStat:$.taskDiffStat,taskQueuePosition:$.taskQueuePosition,taskQueueDepth:$.taskQueueDepth,taskConcurrencyLimit:$.taskConcurrencyLimit,archivedAt:$.archivedAt,archivedBySessionId:$.archivedBySessionId,taskWorktree:J,messages:O}}function o$($){return $.flatMap((O)=>{if(!G4(O)||O.role==="system"||O.role==="tool"&&O.name===O$)return[];let J=O.tool_calls?.filter((X)=>!("function"in X)||X.function.name!==O$),Z=typeof O.content==="string"?O.content.trim():"";if(O.role==="assistant"&&O.tool_calls?.length&&!J?.length&&!Z&&!O.reasoningContent&&!O.metadata)return[];let Y={...O,...O.tool_calls?{tool_calls:J&&J.length>0?J:void 0}:{}};if(O.role==="tool"){let X=O.metadata&&typeof O.metadata==="object"&&!Array.isArray(O.metadata)?O.metadata:void 0,F=O.name??(typeof X?.toolName==="string"?X.toolName:"unknown");if(X!==void 0&&(Object.hasOwn(X,"output")||Object.hasOwn(X,"error"))){let B=Y1(X),M=w$(A$(F,B),L$);return[{...Y,name:F,content:M$(M),metadata:_$(F,{...B.metadata,status:B.success?"completed":"failed"})}]}return[{...Y,name:F,metadata:_$(F,X)}]}let z=F4(O.metadata);return[z?{...Y,content:W4(z)}:Y]})}function B$($,O){$.taskStatus=O.taskStatus,$.taskStatusReason=O.taskStatusReason,$.taskFailure=O.taskFailure,$.taskStartedAt=O.taskStartedAt,$.taskCompletedAt=O.taskCompletedAt,$.taskPromptSummary=O.taskPromptSummary,$.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,$.updatedAt=new Date(O.lastMessageTime)}async function u0($){let O=await C.findSessionMetadata($.id,$.projectPath);if(O)B$($,O)}function e0($){let O=G0($.currentRunId),J=O?.status==="waiting_permission"?"running":O?.status??$.taskStatus;return{sessionId:$.id,projectPath:$.projectPath,title:$.title,rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,status:void 0,taskStatus:J,taskStatusReason:$.taskStatusReason,taskFailure:$.taskFailure,taskStartedAt:$.taskStartedAt,taskCompletedAt:$.taskCompletedAt,taskPromptSummary:$.taskPromptSummary,taskModelId:$.taskModelId,selectedModelId:$.selectedModelId,permissionMode:$.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,communicationStyleDigest:$.communicationStyleDigest,projectInstructionsDigest:$.projectInstructionsDigest,taskRetryAvailable:$.taskRetryAvailable,taskRetriedFrom:$.taskRetriedFrom,taskDelivery:$.taskDelivery,taskIsolation:$.taskIsolation,taskSourceProjectPath:$.taskSourceProjectPath,taskWorktreePath:$.taskWorktreePath,taskWorktreeBranch:$.taskWorktreeBranch,taskBaseCommit:$.taskBaseCommit,taskDiffStat:$.taskDiffStat,taskQueuePosition:O?.status==="queued"?O.taskQueuePosition:J==="queued"?$.taskQueuePosition:void 0,taskQueueDepth:O?.status==="queued"?O.taskQueueDepth:J==="queued"?$.taskQueueDepth:void 0,taskConcurrencyLimit:O?.taskConcurrencyLimit??$.taskConcurrencyLimit,archivedAt:$.archivedAt,archivedBySessionId:$.archivedBySessionId,pendingInteraction:O?.pendingPermission?{type:O.pendingPermission.details.type==="askUserQuestion"?"question":O.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:O.pendingPermission.permissionId}:$.pendingInteraction,agentType:void 0,model:void 0,messageCount:$.messages.length,firstMessageTime:$.createdAt.toISOString(),lastMessageTime:$.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function z0($,O){if(J1($),O!==void 0){let Z=I0({sessionId:$,projectPath:U$(O)});if(n.has(h(Z)))return Z;let Y=await C.findSessionMetadata(Z.sessionId,Z.projectPath);if(!Y)throw new f("Session",$);return I0({sessionId:Y.sessionId,projectPath:Y.projectPath})}let J=new Map;for(let Z of n.values()){if(Z.id!==$)continue;let Y=x0(Z);J.set(h(Y),Y)}for(let Z of await C.listSessions()){if(Z.sessionId!==$)continue;let Y=I0({sessionId:Z.sessionId,projectPath:Z.projectPath});J.set(h(Y),Y)}if(J.size===0)try{let Z=await C.findSessionMetadata($);if(!Z)throw new f("Session",$);return I0({sessionId:Z.sessionId,projectPath:Z.projectPath})}catch(Z){if(Z instanceof f)throw Z;if(Z instanceof Error&&Z.message.startsWith("Ambiguous session ID:"))throw new H0;throw Z}if(J.size>1)throw new H0;return J.values().next().value}function Z1($){if(typeof $==="string")return $;return $.filter((O)=>O.type==="text").map((O)=>O.text).join(`
7
+ `)}function Q4($,O){let J=(O??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(J.length===0)return $;let Z=[];if($.trim())Z.push({type:"text",text:$});return Z.push(...J),Z}var b4=()=>{D2();let $=new Y2;$.onError((x,N)=>{if(x instanceof e)return N.json(x.toObject(),x.statusCode);return y.error("[SessionRoutes] Unhandled route error:",x),N.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let O=new Map,J=new Map,Z=new Map,Y=new Map,z=new Map,X=new Map,F=new _4,b,B=async(x)=>{let N;try{N=F.enter()}catch{throw new h0}try{return await x()}finally{N.release()}};$.use("*",async(x,N)=>{if(x.req.method==="GET"||x.req.method==="HEAD")return N();return B(N)});let M=(x)=>{let N=h(x),Q=z.get(N);if(!Q)Q=new Z4,z.set(N,Q);return Q},E=(x)=>{let N=h(x),Q=X.get(N);if(!Q)Q=new Z4,X.set(N,Q);return Q},G=async(x,N={})=>{let Q=h(x0(x));await Z.get(Q);let K=O.get(Q);if(K)return K;let V=J.get(Q);if(!V){let U=N.communicationStyle??x.communicationStyle;V=F$.create({sessionId:x.id,workspaceRoot:x.projectPath,...x.selectedModelId??x.taskModelId?{modelId:x.selectedModelId??x.taskModelId}:{},permissionMode:N.permissionMode??x.permissionMode??"default",...x.reasoningEffort?{reasoningEffort:x.reasoningEffort}:{},...x.serviceTier?{serviceTier:x.serviceTier}:{},...x.responseVerbosity?{responseVerbosity:x.responseVerbosity}:{},...U?{communicationStyle:U}:{},...U===x.communicationStyle&&x.communicationStyleDigest?{communicationStyleDigest:x.communicationStyleDigest}:{},...x.projectInstructionsDigest?{projectInstructionsDigest:x.projectInstructionsDigest}:{},...x.taskWorktree?{taskWorktree:x.taskWorktree}:{},...x.taskIsolation?{taskIsolation:x.taskIsolation}:{},...x.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:x.id}}:{}}),J.set(Q,V)}try{let U=await V;return O.set(Q,U),U}finally{if(J.get(Q)===V)J.delete(Q)}},u=async(x,N)=>{let Q=h(x0(x)),K=Z.get(Q);if(!K)K=(async()=>{let V=J.get(Q);if(V)await V.catch(()=>{return});J.delete(Q);let U=N??O.get(Q);if(O.delete(Q),U){for(let[H,L]of O)if(L===U)O.delete(H)}await U?.dispose()})().finally(()=>{if(Z.get(Q)===K)Z.delete(Q)}),Z.set(Q,K);await K},Y0=async(x)=>{let N=h(x),Q=n.get(N);if(Q)return Q;let K=Y.get(N);if(!K)K=(async()=>{let V=await C.findSessionMetadata(x.sessionId,x.projectPath);if(!V)throw new f("Session",x.sessionId);let[U,H]=await Promise.all([C.loadSession(x.sessionId,x.projectPath),C.findSessionTaskWorktree(x.sessionId,x.projectPath)]),L=D$(V,U,H);return n.set(N,L),L})(),Y.set(N,K);try{return await K}finally{if(Y.get(N)===K)Y.delete(N)}},q=async(x,N)=>{let Q=await z0(x,N);try{await C.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(K){if(K instanceof r$)throw new k(K.message);throw K}return Y0(Q)},t=async(x,N)=>{if(x.permissionMode===N)return;let Q=await C.setSessionPermissionMode(x.id,x.projectPath,N);x.permissionMode=Q.permissionMode,x.updatedAt=new Date(Q.lastMessageTime),j.publish(x0(x),"session.updated",{permissionMode:N})},I=(x,N,Q,K={})=>{if(!F.stats().accepting)throw new h0;let V=$$(12),U={id:V,sessionId:x.id,projectPath:x.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:K.taskRuntime!==void 0,createdAt:new Date};if(K.taskRuntime){let H=K.taskRuntime,L=r0.admit({key:`${x.projectPath}\x00${x.id}`,...H.getTaskAdmissionLimits(),signal:U.abortController.signal,onUpdate:(T)=>{U.status=T.state,U.taskQueuePosition=T.queuePosition,U.taskQueueDepth=T.queueDepth,U.taskConcurrencyLimit=T.maxConcurrent,x.taskStatus=T.state,x.taskQueuePosition=T.queuePosition,x.taskQueueDepth=T.queueDepth,x.taskConcurrencyLimit=T.maxConcurrent,U.taskAdmissionUpdate=(U.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await H.setTaskAdmission(T)}).catch((w)=>{y.warn(`[SessionRoutes] Failed to persist admission for ${x.id}:`,w)})}});U.taskAdmission=L;let A=L.getSnapshot();U.status=A.state,U.taskQueuePosition=A.queuePosition,U.taskQueueDepth=A.queueDepth,U.taskConcurrencyLimit=A.maxConcurrent}return q0.set(V,U),x.currentRunId=V,U.completion=L2(U,x,N,Q,G,{pendingInputOnly:K.pendingInputOnly,preparedInputTurn:K.preparedInputTurn,goalContinuationOnly:K.goalContinuationOnly,outputSchema:K.outputSchema,taskAdmission:U.taskAdmission,disposeRuntime:u}).catch((H)=>{y.error(`[SessionRoutes] Run ${V} failed:`,H)}),U},O0=async(x)=>{let N;if(x.outputSchema)try{N=t$(x.outputSchema).schema}catch(R){throw new _(R instanceof Error?R.message:"Invalid output schema")}let Q=n$("task",12),K=U$(x.sourceProjectPath),V=x.modelId?.trim(),U=$0();if(!U)throw new _("Config not initialized");let[H,L]=await Promise.all([P$(K,U),W0(K)]);if(V&&!H.config.models.some((R)=>R.id===V))throw new _(`Task model not found: ${V}`);let A=V||H.config.models.find((R)=>R.id===H.config.currentModelId)?.id||H.config.models[0]?.id;if(!A)throw new _("No model is configured. Add or select a model before dispatching a task.");let T=H.config.models.find((R)=>R.id===A);if(!T)throw new _(`Task model not found: ${A}`);let w=x.reasoningEffort??"off",r=x.serviceTier??"auto",U0=x.responseVerbosity??"auto",j0=x.communicationStyle??"auto",w0,Q0=L.projectRules?.staticRules(K),i=Q0&&Q0.files.length>0?Q0.provenanceSha256:void 0;try{let R=H.catalog.resolveConfig(T);z4(R,w),X4(R,r),x4(R,U0);let o=K4(j0,L.communicationStyles);w0=o.source==="built-in"?void 0:o.contentSha256}catch(R){throw new _(R instanceof Error?R.message:"Invalid reasoning effort")}let c0={version:1,prompt:x.prompt,...x.title?{title:x.title}:{},sourceProjectPath:K,isolation:x.isolation,permissionMode:x.permissionMode,modelId:A,reasoningEffort:w,serviceTier:r,responseVerbosity:U0,communicationStyle:j0,...w0?{communicationStyleDigest:w0}:{},...i?{projectInstructionsDigest:i}:{},...x.attachments?{attachments:x.attachments.map((R)=>({...R}))}:{},...N?{outputSchema:N}:{}},P,S;try{let R=await L4.createSessionTask({sessionId:Q,prompt:x.prompt,title:x.title,sourceProjectPath:K,isolation:x.isolation,dispatch:c0,retriedFrom:x.retriedFrom}),{metadata:o}=R;P=R.taskWorktree,S=D$(o,[],P);let Z0=x0(S);n.set(h(Z0),S),j.publish(Z0,"task.status",{taskStatus:o.taskStatus,updatedAt:o.lastMessageTime});let l=Q4(x.prompt,x.attachments),p=await G(S),s=N?await p.prepareInputTurn(l,{outputSchema:N}):await p.prepareInputTurn(l);if(!s.accepted)throw new k(`Task prompt was not accepted: ${s.reason}`);let A0=I(S,l,x.permissionMode,{preparedInputTurn:s,taskRuntime:p,outputSchema:N});return await A0.taskAdmissionUpdate,{session:e0(S),runId:A0.id,messageId:s.messageId,status:A0.status==="queued"?"queued":"running",queuePosition:A0.taskQueuePosition,queueDepth:A0.taskQueueDepth,maxConcurrentTasks:A0.taskConcurrencyLimit}}catch(R){if(R instanceof O1&&S){let o=x0(S),Z0=h(o);if(P)await T0.exit({sessionId:S.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await O.get(Z0)?.dispose().catch(()=>{return}),O.delete(Z0),await C.deleteSession(S.id,S.projectPath).catch(()=>{return}),n.delete(Z0),new o0("Task admission queue is full")}if(S){let o=await C.findSessionMetadata(S.id,S.projectPath).catch(()=>{return});if(!o||o.taskStatus==="queued"){let Z0=f$(R),l=await C.updateSessionMetadata(S.id,S.projectPath,{taskStatus:"failed",taskStatusReason:Z0.message,taskFailure:Z0,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});S.taskStatus=l?.taskStatus??"failed",S.taskStatusReason=l?.taskStatusReason??Z0.message,S.taskFailure=l?.taskFailure??Z0,S.taskCompletedAt=l?.taskCompletedAt}else S.taskStatus=o.taskStatus,S.taskStatusReason=o.taskStatusReason,S.taskFailure=o.taskFailure,S.taskCompletedAt=o.taskCompletedAt}throw R}},v=(x)=>B(()=>O0(x)),m0=async(x,N)=>{let Q=await z0(x,N),K=await C.findSessionMetadata(Q.sessionId,Q.projectPath);if(!K)throw new f("Session",Q.sessionId);if(!["failed","interrupted","cancelled"].includes(K.taskStatus))throw new k(`Task cannot be retried while status is ${K.taskStatus}`);let V=await C.findSessionTaskDispatch(Q.sessionId,Q.projectPath);if(!V)throw new k("Task retry payload is unavailable");return v({prompt:V.prompt,title:V.title,sourceProjectPath:V.sourceProjectPath,isolation:V.isolation,permissionMode:V.permissionMode,modelId:V.modelId,reasoningEffort:V.reasoningEffort,serviceTier:V.serviceTier,responseVerbosity:V.responseVerbosity,communicationStyle:V.communicationStyle,attachments:V.attachments,outputSchema:V.outputSchema,retriedFrom:Q})},b$=(x,N)=>B(()=>m0(x,N)),X0=async(x,N)=>{let Q=await q(x,N);if(!Q.taskWorktree)throw new _("Session does not have a task worktree");try{await T0.restoreSession(Q.taskWorktree);let K=await T0.getDiffArtifact(Q.id);if(!K)throw new k("Task diff artifact is unavailable");return{sessionId:Q.id,projectPath:Q.projectPath,...K}}catch(K){if(K instanceof k)throw K;throw y.error("[SessionRoutes] Failed to load task diff artifact:",K),new k("Task diff artifact is unavailable")}},R$=async(x,N,Q)=>{let K=await z0(x,Q);return E(K).runExclusive(async()=>{let V=await q(K.sessionId,K.projectPath);if(["queued","running"].includes(V.taskStatus))throw new k(`Task artifacts cannot be delivered while status is ${V.taskStatus}`);if(V.taskDelivery?.status==="applied")throw new k("Task changes have already been applied");if(V.taskDelivery?.status==="discarded")throw new k("Task changes have already been discarded");if(!V.taskWorktree)throw new k("Task worktree is unavailable");let U=async(H,L=!1)=>{let A=await C.updateSessionMetadata(V.id,V.projectPath,{taskDelivery:H,...L?{taskWorktree:null}:{}});if(B$(V,A),L)V.taskWorktree=void 0;return j.publish(K,"task.delivery",{taskDelivery:H,...L?{taskWorktreeRemoved:!0}:{},updatedAt:A.lastMessageTime}),e0(V)};try{if(N==="discard"){try{await T0.restoreSession(V.taskWorktree)}catch(A){return y.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${V.id}:`,A),U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:V.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let L=await T0.exit({sessionId:V.id,action:"remove",discardChanges:!0});return U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:L.discardedFiles??0,message:"Task worktree removed"},!0)}try{await T0.restoreSession(V.taskWorktree)}catch(L){throw y.warn(`[SessionRoutes] Task worktree is unavailable for ${V.id}:`,L),new $1("artifact_unavailable","Task worktree is unavailable")}let H=await T0.apply(V.id);return U({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:H.sourceCommit,changedFiles:H.changedFiles,message:"Task changes applied to the source workspace"})}catch(H){if(H instanceof $1)throw await U({status:"conflicted",updatedAt:new Date().toISOString(),message:H.message}),new k(H.message);throw H}})},R0=(x,N,Q)=>B(()=>R$(x,N,Q)),W=async(x)=>{let N=G0(x.currentRunId);if(F0(N))return;if(x.taskIsolation&&x.taskStatus!=="queued"&&x.taskStatus!=="running")return;let Q=await F$.hasPendingInbox(x.projectPath,x.id),K=!Q&&await F$.hasActiveGoal(x.projectPath,x.id);if(!Q&&!K)return;let V=await G(x),U=G0(x.currentRunId);if(F0(U))return;if(Q&&V.getPendingSteeringCount()===0)await V.reloadPendingInbox();let H=V.getPendingSteeringCount()>0,L=H?null:await V.getGoal(),A=L?.status==="active"||L?.status==="verifying";if(!H&&!A||V.hasTurnOwner())return;I(x,"",x.permissionMode??"default",{pendingInputOnly:H,goalContinuationOnly:A,...x.taskIsolation?{taskRuntime:V}:{}})},J0=async(x)=>{let N;try{N=F.enter()}catch{return}try{await W(x)}finally{N.release()}};J$=J0;let B1=async()=>{let x={scheduled:0,failed:0,deferred:0};if(!F.stats().accepting)return x;let N=(await C.listSessions()).filter((Q)=>Q.taskStatus==="queued"&&Q.taskIsolation!==void 0).sort((Q,K)=>Q.firstMessageTime.localeCompare(K.firstMessageTime)||Q.projectPath.localeCompare(K.projectPath)||Q.sessionId.localeCompare(K.sessionId));for(let[Q,K]of N.entries()){let V={sessionId:K.sessionId,projectPath:K.projectPath};try{if(!await F$.hasPendingInbox(K.projectPath,K.sessionId)){let H=f$("Queued task input is missing");await C.updateSessionMetadata(K.sessionId,K.projectPath,{taskStatus:"failed",taskStatusReason:H.message,taskFailure:H,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),x.failed++;continue}let U=await Y0(V);if(await J0(U),U.currentRunId)x.scheduled++}catch(U){if(U instanceof O1){x.deferred+=N.length-Q;break}y.warn(`[SessionRoutes] Failed to recover queued task ${K.sessionId}:`,U),x.deferred++}}return x};return $.get("/",async(x)=>{try{let N=await C.listSessions(),Q=new Set(N.filter((T)=>T.relationType==="subagent").map((T)=>h({sessionId:T.sessionId,projectPath:T.projectPath}))),K=Array.from(n.values()).filter((T)=>!Q.has(h(x0(T)))&&T.relationType!=="subagent").map((T)=>e0(T)),V=new Set(K.map((T)=>h({sessionId:T.sessionId,projectPath:T.projectPath}))),U=N.filter((T)=>{if(T.relationType==="subagent")return!1;return!V.has(h({sessionId:T.sessionId,projectPath:T.projectPath}))}),H=new Set(V),L=U.filter((T)=>{let w=h({sessionId:T.sessionId,projectPath:T.projectPath});if(H.has(w))return!1;return H.add(w),!0}),A=[...K,...L];return x.json(A)}catch(N){throw y.error("[SessionRoutes] Failed to list sessions:",N),new a("Failed to list sessions")}}),$.get("/catalog",async(x)=>{try{let N=x.req.query("limit"),Q=N===void 0?void 0:Number(N),K=x.req.query("cursor"),V=x.req.query("projectPath"),U=x.req.query("archived");if(U!==void 0&&U!=="true"&&U!=="false")throw new _("archived must be true or false");let H=U==="true",L=await C.listSessionPage({...V?{cwd:U$(V)}:{},...K?{cursor:K}:{},...Q===void 0?{}:{limit:Q},includeSubagents:!1,archived:H}),A=new Map((H?[]:Array.from(n.values())).filter((T)=>T.relationType!=="subagent").map((T)=>[h(x0(T)),e0(T)]));return x.json({sessions:L.sessions.map((T)=>A.get(h({sessionId:T.sessionId,projectPath:T.projectPath}))??T),...L.nextCursor?{nextCursor:L.nextCursor}:{}})}catch(N){if(N instanceof _)throw N;if(N instanceof Error&&(N.message.startsWith("Invalid session cursor")||N.message.startsWith("Session cursor scope")||N.message.startsWith("Session catalog")))throw new _(N.message);throw y.error("[SessionRoutes] Failed to list session catalog:",N),new a("Failed to list session catalog")}}),$.post("/",async(x)=>{try{let N=await x.req.json(),Q=m(X2,N);if(!Q.success)throw new _("Invalid request body");let{title:K,projectPath:V}=Q.data,U=n$("web",12),H=U$(V||x.get("directory")||g(),V?"projectPath":"directory"),L=await C.createSessionMetadata(U,H,{title:K,taskStatus:"completed"}),A=D$(L,[]),T=x0(A);return n.set(h(T),A),j.publish(T,"session.created",{}),x.json({...e0(A),status:void 0,agentType:void 0,model:void 0})}catch(N){if(y.error("[SessionRoutes] Failed to create session:",N),N instanceof _)throw N;throw new a("Failed to create session")}}),$.get("/:sessionId/export",async(x)=>{let N=x.req.param("sessionId");try{let Q=x.req.query("includeReasoning");if(Q!==void 0&&Q!=="true"&&Q!=="false")throw new _("includeReasoning must be true or false");let K=await z0(N,x.req.query("projectPath")),V=await C.exportSessionMarkdown(K.sessionId,K.projectPath,{includeReasoning:Q==="true"});return x.body(V.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${V.filename}"`,"Content-Length":String(Buffer.byteLength(V.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":V.contentSha256,"X-Blade-Export-Activities":String(V.activityCount),"X-Blade-Export-Messages":String(V.messageCount),"X-Blade-Export-Redactions":String(V.redactionCount)})}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;if(Q instanceof Error&&Q.message==="No conversation content to export")throw new k(Q.message);throw y.error("[SessionRoutes] Failed to export session:",Q),new a("Failed to export session")}}),$.post("/:sessionId/fork",async(x)=>{let N=x.req.param("sessionId");try{J1(N);let Q=await x.req.json(),K=m(V2,Q);if(!K.success)throw new _("Invalid request body");let V=U$(K.data.projectPath),U=await C.findSessionMetadata(N,V);if(!U)throw new f("Session",N);let H=await C.forkSession(N,{sourceProjectPath:U.projectPath,targetProjectPath:U.projectPath}),L=D$(H.metadata,H.messages),A=x0(L);return n.set(h(A),L),j.publish(A,"task.status",{taskStatus:H.metadata.taskStatus,...H.metadata.taskCompletedAt?{taskCompletedAt:H.metadata.taskCompletedAt}:{},updatedAt:H.metadata.lastMessageTime}),x.json({session:H.metadata,messages:o$(H.messages)},201)}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof k)throw Q;if(Q instanceof U4)throw new k("Session has no durable creation record");throw y.error("[SessionRoutes] Failed to fork session:",Q),new a("Failed to fork session")}}),$.get("/:sessionId",async(x)=>{let N=x.req.param("sessionId");try{let Q=await z0(N,x.req.query("projectPath")),K=n.get(h(Q));if(K)return x.json(e0(K));let V=await C.findSessionMetadata(Q.sessionId,Q.projectPath);if(!V)throw new f("Session",N);return x.json(V)}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;throw y.error("[SessionRoutes] Failed to get session:",Q),new a("Failed to get session")}}),$.patch("/:sessionId",async(x)=>{let N=x.req.param("sessionId");try{let Q=await x.req.json(),K=m(K2,Q);if(!K.success)throw new _("Invalid request body");if(K.data.title===void 0)throw new _("title is required");let V=await z0(N,K.data.projectPath),U=await C.updateSessionMetadata(V.sessionId,V.projectPath,{title:K.data.title}),H=n.get(h(V));if(H)H.title=U.title??H.title,H.updatedAt=new Date(U.lastMessageTime);if(U.title)j.publish(V,"session.updated",{title:U.title});return x.json({success:!0,title:U.title})}catch(Q){if(y.error("[SessionRoutes] Failed to update session:",Q),Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;throw new a("Failed to update session")}}),$.get("/:sessionId/rewind",async(x)=>{let N=await q(x.req.param("sessionId"),x.req.query("projectPath")),Q=await G(N);return x.json({checkpoints:await Q.listRewindCheckpoints()})}),$.post("/:sessionId/rewind",async(x)=>{let N=m(w4,await x.req.json());if(!N.success)throw new _("Invalid rewind request");let Q=await q(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let V=G0(Q.currentRunId);if(F0(V))throw new k("Cannot rewind while a run is active");let U=await G(Q),H;try{H=await U.rewindSession(N.data)}catch(A){if(A instanceof Error&&A.message.startsWith("Cannot rewind while"))throw new k(A.message);throw A}Q.messages=[...H.messages],Q.updatedAt=new Date;let L=o$(H.messages);return j.publish(K,"session.rewound",{targetMessageId:H.checkpoint.messageId,mode:H.mode,removedTurns:H.removedTurns,restoredFiles:H.restoredFiles,messages:L}),x.json({...H,messages:L})})}),$.get("/:sessionId/review",async(x)=>{let N=x.req.param("sessionId"),Q=await z0(N,x.req.query("projectPath")),K=await k0.list(Q.projectPath,Q.sessionId);return x.json({reviews:K.map((V)=>({...V,content:V.completion?N4(V.start,V.completion):void 0}))})}),$.post("/:sessionId/review",async(x)=>{let N=x.req.param("sessionId"),Q=m(T4,await x.req.json());if(!Q.success)throw new _("Invalid code review request");let K=await q(N,Q.data.projectPath),V=x0(K),U=h(V);return M(V).runExclusive(async()=>{if(F0(G0(K.currentRunId)))throw new k("Cannot start a review during an active turn");if(b0.has(U))throw new k("Session already has an active review");let H=await G(K);if(await k0.recoverInterrupted(V.projectPath,V.sessionId,H),Q.data.modelId&&!H.getModelById(Q.data.modelId))throw new _(`Model not found: ${Q.data.modelId}`);if(Q.data.modelId&&H.getCurrentModelId()!==Q.data.modelId)await H.refresh({modelId:Q.data.modelId});if(Q.data.modelId&&K.selectedModelId!==Q.data.modelId){let w=await C.updateSessionMetadata(K.id,K.projectPath,{selectedModelId:Q.data.modelId});B$(K,w)}let L=new AbortController,A;try{A=await k0.start({sessionId:V.sessionId,projectPath:V.projectPath,runtime:H,request:{kind:Q.data.kind,...Q.data.ref?{ref:Q.data.ref}:{},...Q.data.instructions?{instructions:Q.data.instructions}:{}},signal:L.signal,onEvent:(w)=>{if(w.kind==="tool_start")j.publish(V,"review.tool.started",{reviewId:A?.reviewId,toolCallId:w.toolCall.id,toolName:w.toolCall.function.name});else if(w.kind==="tool_progress")j.publish(V,"review.tool.progress",{reviewId:A?.reviewId,toolCallId:w.toolCall.id,message:w.update.message.slice(0,1000)});else if(w.kind==="tool_result")j.publish(V,"review.tool.completed",{reviewId:A?.reviewId,toolCallId:w.toolCall.id,success:w.result.success})}})}catch(w){if(w instanceof Error&&(w.message.includes("active review")||w.message.includes("interrupted review")||w.message.includes("active turn")))throw new k(w.message);if(w instanceof Error&&(w.message.includes("review")||w.message.includes("Git")||w.message.includes("changes")||w.message.includes("ref")))throw new _(w.message);throw w}if(!A)throw new a("Code review failed to start");await u0(K),j.publish(V,"review.started",{reviewId:A.reviewId,kind:Q.data.kind}),j.publish(V,"task.status",{taskStatus:K.taskStatus,...K.taskStatusReason?{taskStatusReason:K.taskStatusReason}:{},...K.taskStartedAt?{taskStartedAt:K.taskStartedAt}:{},...K.taskPromptSummary?{taskPromptSummary:K.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let T=A.completion.then(async(w)=>{K.messages=await C.loadSession(V.sessionId,V.projectPath),await u0(K),j.publish(V,"task.status",{taskStatus:K.taskStatus,...K.taskStatusReason?{taskStatusReason:K.taskStatusReason}:{},...K.taskFailure?{taskFailure:K.taskFailure}:{},...K.taskStartedAt?{taskStartedAt:K.taskStartedAt}:{},...K.taskCompletedAt?{taskCompletedAt:K.taskCompletedAt}:{},...K.taskPromptSummary?{taskPromptSummary:K.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),j.publish(V,"review.completed",{reviewId:A.reviewId,status:w.status,findings:w.findings.length})}).catch((w)=>{y.error(`[SessionRoutes] Code review ${A.reviewId} failed:`,w)}).finally(()=>{if(b0.get(U)?.reviewId===A.reviewId)b0.delete(U)});return b0.set(U,{reviewId:A.reviewId,controller:L,completion:T}),x.json({reviewId:A.reviewId,status:"running"},202)})}),$.get("/:sessionId/subagents",async(x)=>{let N=await q(x.req.param("sessionId"),x.req.query("projectPath")),Q=await G(N);return x.json({subagents:Q.listSubagents().map(S$)})}),$.post("/:sessionId/subagents/:agentId/resume",async(x)=>{J1(x.req.param("agentId"));let N=A4.safeParse(await x.req.json());if(!N.success)throw new _("Invalid subagent resume request");let Q=await q(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let V=G0(Q.currentRunId);if(F0(V))throw new k("Cannot resume a subagent while a parent run is active");let U=await G(Q),H=!1,L,A=(w)=>{j.publish(K,"subagent.complete",{subagentSessionId:w.id,success:w.status==="completed",status:w.status,summary:w.result?.message?.slice(0,500),type:w.subagentType,verificationVerdict:w.result?.verificationVerdict,resumedFrom:w.resumedFrom,rootAgentId:w.rootAgentId,resumeDepth:w.resumeDepth})},T;try{T=U.resumeSubagent({agentId:x.req.param("agentId"),prompt:N.data.prompt,onEvent:(w,r)=>{B2(K,r,w)},onCompleted:(w)=>{if(H)A(w);else L=w}})}catch(w){if(w instanceof Error&&(w.message.startsWith("Cannot resume")||w.message.startsWith("Subagent cannot")))throw new k(w.message);if(w instanceof Error&&w.message.startsWith("Subagent not found"))throw new f(w.message);throw w}if(j.publish(K,"subagent.start",{subagentSessionId:T.session.id,type:T.session.subagentType,description:T.session.description,resumedFrom:T.source.id,rootAgentId:T.session.rootAgentId,resumeDepth:T.session.resumeDepth}),H=!0,L)A(L);return x.json({source:S$(T.source),session:S$(T.session)})})}),$.get("/:sessionId/goal",async(x)=>{let N=await q(x.req.param("sessionId"),x.req.query("projectPath"));return x.json({goal:await new D4(N.projectPath,N.id).get()})}),$.put("/:sessionId/goal",async(x)=>{let N=m(N2,await x.req.json());if(!N.success)throw new _("Invalid goal request");let Q=await q(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let V=G0(Q.currentRunId);if(F0(V))return x.json({status:"rejected",reason:"run_active"},409);let H=N.data.permissionMode??Q.permissionMode??"default";if(Q.permissionMode!==H)await t(Q,H);let L=await G(Q),A=await L.createGoal(N.data);j.publish(K,"goal.updated",{goal:A});let T=I(Q,"",H,{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:L}:{}});return await T.taskAdmissionUpdate,x.json({status:T.status==="queued"?"queued":"running",runId:T.id,goal:A,queuePosition:T.taskQueuePosition,queueDepth:T.taskQueueDepth,maxConcurrentTasks:T.taskConcurrencyLimit},202)})}),$.patch("/:sessionId/goal",async(x)=>{let N=m(G2,await x.req.json());if(!N.success)throw new _("Invalid goal update");let Q=await q(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let V=await G(Q),U;if(N.data.action==="pause")U=await V.pauseGoal();else if(N.data.action==="edit")U=await V.editGoal(N.data.objective);else U=await V.resumeGoal();if(j.publish(K,"goal.updated",{goal:U}),U.status==="active"&&!F0(G0(Q.currentRunId))){let H=I(Q,"","default",{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:V}:{}});return await H.taskAdmissionUpdate,x.json({status:H.status==="queued"?"queued":"running",runId:H.id,goal:U,queuePosition:H.taskQueuePosition,queueDepth:H.taskQueueDepth,maxConcurrentTasks:H.taskConcurrencyLimit},202)}return x.json({status:U.status,goal:U})})}),$.delete("/:sessionId/goal",async(x)=>{let N=await q(x.req.param("sessionId"),x.req.query("projectPath")),Q=x0(N),V=await(await G(N)).clearGoal();if(V)j.publish(Q,"goal.cleared",{});return x.json({cleared:V})}),$.post("/:sessionId/archive",async(x)=>{let N=x.req.param("sessionId");try{let Q=await z0(N,x.req.query("projectPath")),K=await C.listSessionArchiveMembers(Q.sessionId,Q.projectPath);for(let U of K){let H=I0({sessionId:U.sessionId,projectPath:U.projectPath}),L=n.get(h(H));if(F0(G0(L?.currentRunId)))throw new k(`Stop session ${U.sessionId} before archiving this session tree`)}for(let U of K){let H=I0({sessionId:U.sessionId,projectPath:U.projectPath}),L=n.get(h(H));if(L)await u(L)}let V=await C.archiveSession(Q.sessionId,Q.projectPath);for(let U of K){let H=I0({sessionId:U.sessionId,projectPath:U.projectPath}),L=h(H);n.delete(L),Y.delete(L),J.delete(L),z.delete(L),j.publish(H,"session.archived",{archiveRootId:Q.sessionId,archivedAt:V.archivedAt})}if(O.size===0)await N0.getInstance().disconnectAll();return x.json({session:V,archivedSessionIds:K.map((U)=>U.sessionId)})}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0||Q instanceof k)throw Q;if(Q instanceof s$)throw new k(Q.message);throw y.error("[SessionRoutes] Failed to archive session:",Q),new a("Failed to archive session")}}),$.post("/:sessionId/unarchive",async(x)=>{let N=x.req.param("sessionId");try{let Q=await z0(N,x.req.query("projectPath")),K=await C.listSessionArchiveMembers(Q.sessionId,Q.projectPath),V=await C.unarchiveSession(Q.sessionId,Q.projectPath),U=K.filter((H)=>H.sessionId===Q.sessionId||H.archivedBySessionId===Q.sessionId).map((H)=>H.sessionId);for(let H of U)j.publish({sessionId:H,projectPath:Q.projectPath},"session.unarchived",{archiveRootId:Q.sessionId});return x.json({session:V,restoredSessionIds:U})}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;if(Q instanceof s$)throw new k(Q.message);throw y.error("[SessionRoutes] Failed to unarchive session:",Q),new a("Failed to unarchive session")}}),$.delete("/:sessionId",async(x)=>{let N=x.req.param("sessionId"),Q=x.req.query("projectPath");try{let K=await z0(N,Q),V=h(K),U=n.get(V),H=O.get(V),L=U?.taskWorktree??await C.findSessionTaskWorktree(K.sessionId,K.projectPath),A;if(U?.currentRunId){let w=G0(U.currentRunId);if(w)H$(w),await w.completion,A=w.id}let T=b0.get(V);if(T)T.controller.abort("session-delete"),await T.completion;if(H)await H.clearGoal().catch((w)=>{y.warn("[SessionRoutes] Failed to clear session goal:",w)});if(await C.deleteSession(K.sessionId,K.projectPath),j.publish(K,"session.deleted",{}),A)F2(A);if(n.delete(V),Y.delete(V),J.delete(V),z.delete(V),H){if(await H.dispose(),O.delete(V),O.size===0)await N0.getInstance().disconnectAll()}if(L)try{await T0.restoreSession(L),await T0.exit({sessionId:K.sessionId,action:"remove",discardChanges:!0})}catch(w){y.warn(`[SessionRoutes] Failed to remove deleted task worktree ${K.sessionId}:`,w)}return x.json({success:!0})}catch(K){if(y.error("[SessionRoutes] Failed to delete session:",K),K instanceof _||K instanceof f||K instanceof H0)throw K;throw new a("Failed to delete session")}}),$.get("/:sessionId/message",async(x)=>{let N=x.req.param("sessionId");try{let Q=await z0(N,x.req.query("projectPath")),K=n.get(h(Q)),V=K?.messages?K.messages:await C.loadSession(Q.sessionId,Q.projectPath);return x.json(o$(V))}catch(Q){if(y.error("[SessionRoutes] Failed to get messages:",Q),Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;throw new a("Failed to get messages")}}),$.get("/:sessionId/events",async(x)=>{let N=x.req.param("sessionId"),Q=await z0(N,x.req.query("projectPath"));try{await C.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(L){if(L instanceof r$)throw new k(L.message);throw L}let K=await Y0(Q),V=x.req.header("Last-Event-ID")??x.req.query("lastEventId"),U=V?Number.parseInt(V,10):Number.NaN,H=Number.isInteger(U)?U+1:void 0;return Q2(x,async(L)=>{let T,w,r=!1,U0,j0,w0=new Promise((P)=>{j0=P}),Q0=()=>{if(w!==void 0)clearInterval(w),w=void 0;T?.(),T=void 0},i=(P)=>{if(r)return;r=!0,Q0(),U0?.close(P),j0()},c0=new Set;L.onAbort(i),U0=new K$({write:async(P)=>{await L.writeSSE(P)},onFailure:(P)=>{y.warn(`[SessionRoutes] SSE egress closed for ${Q.sessionId}: kind=${P.kind} pendingItems=${P.pendingItems??0} pendingBytes=${P.pendingBytes??0}`),i(P)}}),T=j.subscribe((P)=>{if(P.sessionId!==Q.sessionId||P.projectPath!==Q.projectPath)return;let S=P.properties.requestId;if((P.type==="permission.asked"||P.type==="question.required"||P.type==="elicitation.required")&&typeof S==="string"){if(c0.has(S))return;c0.add(S)}if(P.type==="subagent.completion.queued")M(Q).runExclusive(()=>J0(K)).catch((R)=>{y.error(`[SessionRoutes] Failed to wake background completion for ${K.id}:`,R)});U0?.observe(U2(P),P.seq)});try{if(L.aborted||r)return;let P=G0(K.currentRunId),S=F0(P)?await G(K):void 0,R=S?.getPendingSteeringCount()??0;if(await U0.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:Q.sessionId,projectPath:Q.projectPath,timestamp:Date.now(),status:F0(P)?P.status:"idle",runId:F0(P)?P.id:void 0,queued:R,pendingInputDelivery:R>0?S?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:S?.getRecoveredSteeringCount()??0}})}),L.aborted||r)return;if(H!==void 0){if(await H4.for(Q.sessionId,Q.projectPath).replay({onCommitted:async(p)=>{if(L.aborted||r)return;let s=_2(p);if(s.seq===void 0)return;await U0.writeReplay({...typeof p.seq==="number"?{id:String(p.seq)}:{},data:JSON.stringify({type:s.type,...s.seq!==void 0?{seq:s.seq}:{},properties:{...s.properties,sessionId:Q.sessionId,projectPath:Q.projectPath}})},s.seq)}},H),L.aborted||r)return}if(U0.finishInitialization({replayed:H!==void 0}),L.aborted||r)return;if(!P&&!b0.has(h(Q))){let p=(await k0.list(Q.projectPath,Q.sessionId)).some((s)=>s.completion===void 0)?await k0.recoverInterrupted(Q.projectPath,Q.sessionId,await G(K)):void 0;if(p)K.messages=await C.loadSession(Q.sessionId,Q.projectPath),await u0(K),j.publish(Q,"review.completed",{reviewId:p.reviewId,status:p.status,findings:0,recovered:!0})}if(L.aborted||r)return;if(!P)await p0.recoverResponded(Q.projectPath,Q.sessionId);if(L.aborted||r)return;let o=P?void 0:await p0.findPending(Q.projectPath,Q.sessionId),Z0=P?.pendingPermission??(o?{permissionId:o.request.requestId,details:p0.confirmationDetails(o),resolve:()=>{return}}:void 0);if(Z0){c0.add(Z0.permissionId);let l=q4(Z0,!0);U0.observe({data:JSON.stringify({type:l.type,properties:{...l.properties,sessionId:Q.sessionId,projectPath:Q.projectPath}})})}if(L.aborted||r)return;if(J0(K).catch((l)=>{y.error(`[SessionRoutes] Failed to resume pending input for ${N}:`,l)}),L.aborted||r)return;w=setInterval(()=>{if(L.aborted||r)return;U0?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await w0}finally{i()}})}),$.post("/:sessionId/message",async(x)=>{let N=x.req.param("sessionId"),Q=await x.req.json(),K=m(z2,Q);if(!K.success)throw new _("Invalid message format");let{content:V,attachments:U,modelId:H,reasoningEffort:L,serviceTier:A,responseVerbosity:T,communicationStyle:w,permissionMode:r,projectPath:U0,outputSchema:j0}=K.data,w0;if(j0)try{w0=t$(j0).schema}catch(l){throw new _(l instanceof Error?l.message:"Invalid output schema")}let Q0=w,i=H?.trim();if((U??[]).reduce((l,p)=>l+(typeof p.content==="string"?Buffer.byteLength(p.content):0),0)>y$)throw new _("Message attachments exceed the 5 MiB limit");let P=r,S=Q4(V,U),R=await q(N,U0??x.req.query("projectPath")),o=P??R.permissionMode??"default",Z0=x0(R);return M(Z0).runExclusive(async()=>{let l=G0(R.currentRunId);if(F0(l)){if(w0)throw new k("Wait for the active turn to finish before setting an output schema");let c=await G(R);if(i&&!c.getModelById(i))throw new _(`Model not found: ${i}`);if(i&&c.getCurrentModelId()!==i)throw new k("Wait for the active turn to finish before switching models");if(L&&c.getReasoningConfiguration().selection!==L)throw new k("Wait for the active turn to finish before switching reasoning effort");if(A&&c.getServiceTierConfiguration().selection!==A)throw new k("Wait for the active turn to finish before switching service tier");if(T&&c.getResponseVerbosityConfiguration().selection!==T)throw new k("Wait for the active turn to finish before switching response verbosity");if(Q0&&c.getCommunicationStyleConfiguration().selection!==Q0)throw new k("Wait for the active turn to finish before switching communication style");if(P&&R.permissionMode!==P)throw new k("Wait for the active turn to finish before switching permission mode");let M0=await c.enqueueSteering(S,{allowBeforeTurn:!0});if(!M0.accepted)return x.json({status:"rejected",reason:M0.reason??"turn_unavailable"},409);let d$=M0.messageId??$$(12),C1=M0.queued;j.publish(Z0,"message.created",{messageId:d$,role:"user",content:Z1(S)});let kO=M0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(j.publish(Z0,kO,{runId:l.id,messageId:d$,queued:C1}),M0.delivery==="next_turn"&&l.status!=="running"&&l.status!=="waiting_permission")J0(R).catch((IO)=>{y.error(`[SessionRoutes] Failed to wake queued follow-up for ${N}:`,IO)});if(M0.delivery==="next_turn")l.pendingFollowUpRequested=!0;return x.json({runId:l.id,messageId:d$,status:M0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:C1},202)}if(R.permissionMode!==o)await t(R,o);let p=await G(R,{permissionMode:o,...Q0&&!Q0.includes(":")?{communicationStyle:Q0}:{}});if(i&&!p.getModelById(i))throw new _(`Model not found: ${i}`);if(L)try{p.resolveReasoningConfiguration(L,i)}catch(c){throw new _(c instanceof Error?c.message:"Invalid reasoning effort")}if(A)try{p.resolveServiceTierConfiguration(A,i)}catch(c){throw new _(c instanceof Error?c.message:"Invalid service tier")}if(T)try{p.resolveResponseVerbosityConfiguration(T,i)}catch(c){throw new _(c instanceof Error?c.message:"Invalid response verbosity")}let s=Q0?p.resolveCommunicationStyleConfiguration(Q0):void 0;if(s?.source!==void 0&&s.source!=="built-in"&&!s.contentSha256)throw new _("Custom communication style has no provenance");let A0=p.getCurrentModelId(),w1=p.getReasoningConfiguration(),A1=p.getServiceTierConfiguration(),M1=p.getResponseVerbosityConfiguration(),E1=p.getCommunicationStyleConfiguration(),T1=Boolean(i)&&A0!==i,q1=Boolean(L)&&w1.selection!==L,b1=Boolean(A)&&A1.selection!==A,R1=Boolean(T)&&M1.selection!==T,j1=Boolean(Q0)&&E1.selection!==Q0;if(T1||q1||b1||R1||j1)await p.refresh({...i?{modelId:i}:{},...L?{reasoningEffort:L}:{},...A?{serviceTier:A}:{},...T?{responseVerbosity:T}:{},...Q0?{communicationStyle:Q0}:{}});let u$={...i&&R.selectedModelId!==i?{selectedModelId:i}:{},...L&&R.reasoningEffort!==L?{reasoningEffort:L}:{},...A&&R.serviceTier!==A?{serviceTier:A}:{},...T&&R.responseVerbosity!==T?{responseVerbosity:T}:{},...s&&(R.communicationStyle!==Q0||R.communicationStyleDigest!==s.contentSha256)?{communicationStyle:Q0,communicationStyleDigest:s.source==="built-in"?null:s.contentSha256}:{}};if(Object.keys(u$).length>0)try{let c=await C.updateSessionMetadata(R.id,R.projectPath,u$);R.permissionMode=c.permissionMode,R.selectedModelId=c.selectedModelId,R.reasoningEffort=c.reasoningEffort,R.serviceTier=c.serviceTier,R.responseVerbosity=c.responseVerbosity,R.communicationStyle=c.communicationStyle,R.communicationStyleDigest=c.communicationStyleDigest,R.updatedAt=new Date(c.lastMessageTime),j.publish(Z0,"session.updated",u$)}catch(c){if(T1||q1||b1||R1||j1)await p.refresh({...A0?{modelId:A0}:{},reasoningEffort:w1.selection,serviceTier:A1.selection,responseVerbosity:M1.selection,communicationStyle:E1.selection}).catch((M0)=>y.error("[SessionRoutes] Failed to roll back non-durable model settings:",M0));throw c}let z$=w0?await p.prepareInputTurn(S,{outputSchema:w0}):await p.prepareInputTurn(S);if(!z$.accepted)return x.json({status:"rejected",reason:z$.reason},z$.reason==="queue_full"?429:409);let i0=I(R,S,o,{preparedInputTurn:z$,outputSchema:w0,...R.taskIsolation?{taskRuntime:p}:{}});return await i0.taskAdmissionUpdate,x.json({runId:i0.id,messageId:z$.messageId,status:i0.status==="queued"?"queued":"running",queuePosition:i0.taskQueuePosition,queueDepth:i0.taskQueueDepth,maxConcurrentTasks:i0.taskConcurrencyLimit},202)})}),$.post("/:sessionId/shell",async(x)=>{let N=x.req.param("sessionId"),Q=m(E4,await x.req.json());if(!Q.success)throw new _("Invalid user shell command");let K=await q(N,Q.data.projectPath??x.req.query("projectPath")),V=x0(K),U=h(V);return M(V).runExclusive(async()=>{if(v0.has(U))throw new k("A user shell command is already running in this Session");let H=await G(K),L=new AbortController,A,T=new Promise((w)=>{A=w});v0.set(U,{controller:L,completion:T});try{let w=await H.executeUserShellCommand(Q.data.command,{signal:L.signal});K.messages=await C.loadSession(K.id,K.projectPath),K.updatedAt=new Date;let r=G0(K.currentRunId);if(w.delivery==="next_turn"&&F0(r))r.pendingFollowUpRequested=!0;return x.json({executionId:w.executionId,messageId:w.messageId,record:w.record,auxiliary:w.auxiliary,...w.delivery?{delivery:w.delivery}:{},...w.queued!==void 0?{queued:w.queued}:{}})}finally{v0.delete(U),A()}})}),$.post("/:sessionId/abort",async(x)=>{let N=x.req.param("sessionId"),Q=await z0(N,x.req.query("projectPath")),K=n.get(h(Q));if(K?.currentRunId){let H=G0(K.currentRunId);if(H)H$(H),await H.completion}let V=v0.get(h(Q));if(V)V.controller.abort("user-cancel"),await V.completion;let U=b0.get(h(Q));if(U)U.controller.abort("user-cancel"),await U.completion;return x.json({success:!0})}),$.get("/:sessionId/status",async(x)=>{let N=x.req.param("sessionId"),Q=await z0(N,x.req.query("projectPath")),K=n.get(h(Q)),V=b0.get(h(Q));if(V)return x.json({sessionId:N,projectPath:Q.projectPath,reviewId:V.reviewId,status:"reviewing"});if(!K?.currentRunId)return x.json({sessionId:N,projectPath:Q.projectPath,status:"idle"});let U=G0(K.currentRunId);return x.json({sessionId:N,projectPath:Q.projectPath,runId:K.currentRunId,status:U?.status||"idle"})}),{app:$,dispatchTask:v,retryTask:b$,getTaskDiff:X0,deliverTask:R0,recoverQueuedTasks:B1,shutdown:(x="server-shutdown")=>{if(b)return b;return F.close(x),b=(async()=>{let N,Q=async(A)=>{let T=await Promise.allSettled(A);for(let w of T)if(w.status==="rejected")N??=w.reason},K=new Set,V=()=>{for(let A of q0.values()){if(A.completion)K.add(A.completion);if(F0(A))H$(A,x)}for(let A of v0.values())A.controller.abort(x),K.add(A.completion);for(let A of b0.values())A.controller.abort(x),K.add(A.completion)},U=F.waitForIdle(),H=!1;U.then(()=>{H=!0});while(!H)V(),await Promise.race([U,new Promise((A)=>setImmediate(A))]);await U,V(),await Q([...K]),await Q([...J.values()]),V(),await Q([...K]);let L=new Set(O.values());if(O.clear(),await Q([...L].map((A)=>A.dispose())),await Q([...Z.values()]),await Q([N0.getInstance().disconnectAll()]),J.clear(),Z.clear(),Y.clear(),z.clear(),X.clear(),n.clear(),J$===J0)J$=void 0;if(N!==void 0)throw N})(),b}}};async function L2($,O,J,Z,Y,z={}){let{abortController:X,sessionId:F,id:b}=$,B=z.preparedInputTurn?.messageId??$$(12),E=z.pendingInputOnly===!0||z.preparedInputTurn?.mode==="pending"||z.goalContinuationOnly===!0?void 0:$$(12),G,u,Y0=x0(O),q=(I,O0)=>{j.publish(Y0,I,O0)},t=async()=>{let I=String(X.signal.reason||"Task run cancelled");if(O.taskIsolation){let O0=G??await Y(O).catch(()=>{return});if(I==="user-cancel")await O0?.discardPendingInput().catch((m0)=>{y.warn(`[SessionRoutes] Failed to discard cancelled input for ${O.id}:`,m0)});let v=await O0?.setTaskStatus("cancelled",I).catch(()=>{return});if(v)B$(O,v);else await u0(O).catch(()=>{return})}O.taskStatus="cancelled",O.taskStatusReason=I,O.taskCompletedAt??=new Date().toISOString()};try{if(z.taskAdmission){if(await z.taskAdmission.ready,await $.taskAdmissionUpdate,X.signal.aborted)throw Error(String(X.signal.reason||"Task run cancelled"))}if(O.taskStatus="running",O.taskStatusReason=void 0,O.taskStartedAt=new Date().toISOString(),O.taskCompletedAt=void 0,!z.pendingInputOnly&&!z.goalContinuationOnly)q("message.created",{messageId:B,role:"user",content:Z1(J)});if(q("session.status",{status:"running"}),E)q("message.created",{messageId:E,role:"assistant",content:""});G=await Y(O);let I=G,O0=Boolean(z.outputSchema??I.getPendingSteeringMessages().find((W)=>W.outputSchema)?.outputSchema);u=await B4.createWithRuntime(I,{sessionId:F,...O.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let v=async(W)=>{let J0=W.interactionRequestId??$$(12),B1=300000;$.status="waiting_permission";let L1=new Promise((K)=>{let V=setTimeout(()=>{y.warn(`[SessionRoutes] Permission ${J0} timed out after 300000ms`),q("permission.timeout",{requestId:J0}),K({approved:!1,reason:"timeout"})},300000);$.pendingPermission={permissionId:J0,resolve:(U)=>{clearTimeout(V),K(U)},details:W}}),x=$.pendingPermission;if(!x)throw Error("Permission request was not registered");let N=q4(x);q(N.type,N.properties),y.info(`[SessionRoutes] Permission request created: ${J0}, runId: ${b}`);let Q=await L1;if(y.info(`[SessionRoutes] Permission response received: ${J0}, approved: ${Q.approved}`),!X.signal.aborted)$.status="running";if($.pendingPermission===x)$.pendingPermission=void 0;return q("interaction.resolved",{requestId:J0}),Q},b$={messages:await C.loadSessionModelContext(O.id,O.projectPath),userId:"web-user",sessionId:F,workspaceRoot:O.projectPath,signal:X.signal,permissionMode:Z,onPermissionModeChange:async(W)=>{O.permissionMode=W,O.updatedAt=new Date,q("session.updated",{permissionMode:W})},...O.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:v}},X0=()=>{if(!E)E=$$(12),q("message.created",{messageId:E,role:"assistant",content:""});return E},R$=async(W)=>{switch(W.kind){case"content_delta":if(O0)break;q("message.delta",{messageId:X0(),delta:W.delta});break;case"structured_output":q("structured.output",{messageId:X0(),output:W.output,schemaDigest:W.schemaDigest});break;case"thinking_delta":q("thinking.delta",{messageId:X0(),delta:W.delta});break;case"tool_start":if("function"in W.toolCall){if(W.toolCall.function.name===O$)break;q("tool.start",{messageId:X0(),toolName:W.toolCall.function.name,toolCallId:W.toolCall.id,arguments:W.toolCall.function.arguments,toolKind:W.toolKind})}break;case"tool_result":if("function"in W.toolCall){if(W.toolCall.function.name===O$)break;q("tool.result",{messageId:X0(),toolName:W.toolCall.function.name,toolCallId:W.toolCall.id,success:W.result.success,summary:W.result.metadata?.summary,output:M$(w$(A$(W.toolCall.function.name,W.result),L$)),metadata:_$(W.toolCall.function.name,W.result.metadata)})}break;case"tool_progress":if("function"in W.toolCall){if(W.toolCall.function.name===O$)break;q("tool.progress",{messageId:X0(),toolName:W.toolCall.function.name,toolCallId:W.toolCall.id,...W.update})}break;case"token_usage":q("token.usage",{...W.usage});break;case"turn_start":q("turn.started",{turn:W.turn,maxTurns:W.maxTurns});break;case"provider_retry":q("provider.retry",{phase:W.phase,attempt:W.attempt,maxRetries:W.maxRetries,reason:W.reason,statusCode:W.statusCode,delayMs:W.delayMs,nextRetryAt:W.nextRetryAt,mode:W.mode,recoveryBudgetMs:W.recoveryBudgetMs,recoveryElapsedMs:W.recoveryElapsedMs,recoveryRemainingMs:W.recoveryRemainingMs,exhaustedBy:W.exhaustedBy});break;case"provider_stall":q("provider.stall",{phase:W.phase,stallCount:W.stallCount,durationMs:W.durationMs,warningAfterMs:W.warningAfterMs,timeoutMs:W.timeoutMs,outputStarted:W.outputStarted});break;case"action_stationarity":q("action.stationarity",{phase:W.phase,toolName:W.toolName,runLength:W.runLength,nudgeThreshold:W.nudgeThreshold,haltThreshold:W.haltThreshold,progressAware:W.progressAware});break;case"mcp_catalog_changed":q("mcp.catalog.changed",{messageId:X0(),revision:W.revision,serverName:W.serverName,added:W.added,removed:W.removed,updated:W.updated});break;case"mcp_content_changed":q("mcp.content.changed",{messageId:X0(),revision:W.revision,serverName:W.serverName,contentKind:W.contentKind,added:W.added,removed:W.removed,updated:W.updated});break;case"mcp_resource_updated":q("mcp.resource.updated",{messageId:X0(),revision:W.revision,serverName:W.serverName,uri:W.uri});break;case"mcp_connection_changed":q("mcp.connection.changed",{messageId:X0(),revision:W.revision,serverName:W.serverName,phase:W.phase,reason:W.reason,attempt:W.attempt,maxAttempts:W.maxAttempts,nextRetryAt:W.nextRetryAt,error:W.error});break;case"mcp_log":q("mcp.log",{messageId:X0(),revision:W.revision,serverName:W.serverName,level:W.level,logger:W.logger,message:W.message,projectedBytes:W.projectedBytes,dataSha256:W.dataSha256,truncated:W.truncated,detailsOmitted:W.detailsOmitted,timestamp:W.timestamp,synthetic:W.synthetic});break;case"mcp_instructions_changed":q("mcp.instructions.changed",{messageId:X0(),revision:W.revision,serverName:W.serverName,action:W.action,reason:W.reason,text:W.text,sourceBytes:W.sourceBytes,projectedBytes:W.projectedBytes,sha256:W.sha256,truncated:W.truncated,detailsOmitted:W.detailsOmitted});break;case"mcp_task_changed":q("mcp.task.changed",{messageId:X0(),revision:W.revision,taskId:W.taskId,serverName:W.serverName,toolName:W.toolName,status:W.status,statusMessage:W.statusMessage,createdAt:W.createdAt,updatedAt:W.updatedAt,completedAt:W.completedAt,hasResult:W.hasResult,error:W.error});break;case"project_rules_loaded":q("project.rules.loaded",{messageId:X0(),files:W.files,triggerPaths:W.triggerPaths,blockedWrite:W.blockedWrite});break;case"steering_applied":q("steering.applied",{runId:b,messageIds:W.messageIds,count:W.count,recovered:W.recovered,delivery:W.delivery,queued:I.getPendingSteeringCount()});break;case"follow_up_started":{if(E)q("message.complete",{messageId:E}),E=void 0;for(let J0 of W.messages){if(!J0.recovered||J0.persisted)continue;q("message.created",{messageId:J0.id,role:"user",content:Z1(J0.content),recovered:!0})}q("follow_up.started",{runId:b,queued:W.queued,recovered:W.recovered}),X0();break}case"goal_updated":q("goal.updated",{goal:W.goal});break;case"goal_continuation_started":q("goal.continuation.started",{goal:W.goal,continuation:W.continuation}),X0();break;case"compaction":q(W.phase==="start"?"compaction.started":"compaction.completed",{...W.reason?{reason:W.reason}:{},...W.strategy?{strategy:W.strategy}:{},...W.outcome?{outcome:W.outcome}:{},...W.preTokens!==void 0?{preTokens:W.preTokens}:{},...W.postTokens!==void 0?{postTokens:W.postTokens}:{}});break;case"model_fallback":q("model.fallback",{});break;case"task_update":q("task.updated",{tasks:W.tasks});break;default:break}},R0=await e$(u.chatStream(J,b$,{stream:!0,pendingInputOnly:z.pendingInputOnly,preparedInputTurn:z.preparedInputTurn,goalContinuationOnly:z.goalContinuationOnly,outputSchema:z.outputSchema,taskAdmission:z.taskAdmission}),R$);if(!R0.success)throw Error(R0.error?.message??"Agent run failed");for(let W=0;W<20;W++){let J0=$.pendingFollowUpRequested===!0;if($.pendingFollowUpRequested=!1,I.getPendingSteeringCount()===0){if(!J0)break;continue}if(X.signal.aborted)break;if(R0=await e$(u.chatStream("",b$,{stream:!0,pendingInputOnly:!0,taskAdmission:z.taskAdmission}),R$),!R0.success)throw Error(R0.error?.message??"Agent follow-up failed")}if(O.messages=await C.loadSession(O.id,O.projectPath),O.updatedAt=new Date,await u0(O),X.signal.aborted||$.status==="cancelled"){await t(),q("session.status",{status:"idle"});return}if(E)q("message.complete",{messageId:E});q("thinking.completed",{}),$.status="completed",O.taskStatus="completed",O.taskCompletedAt??=new Date().toISOString(),q("session.completed",{runId:b,outputTruncated:R0.metadata?.outputTruncated??!1}),q("session.status",{status:"idle"})}catch(I){if(G&&z.preparedInputTurn)await G.finishTurn(z.preparedInputTurn.handle).catch(()=>{return});if(X.signal.aborted||$.status==="cancelled"){H$($,"runtime-abort"),await t(),q("session.status",{status:"idle"});return}await u0(O).catch(()=>{return}),y.error("[SessionRoutes] Agent execution error:",I),$.status="failed",O.taskStatus="failed",O.taskCompletedAt??=new Date().toISOString();let O0=f$(I);if(!O.taskFailure){let v=G?await G.setTaskStatus("failed",I).catch(()=>{return}):await C.updateSessionMetadata(O.id,O.projectPath,{taskStatus:"failed",taskStatusReason:O0.message,taskFailure:O0,taskCompletedAt:O.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(v)B$(O,v)}O.taskStatusReason??=O0.message,O.taskFailure??=O0,q("session.error",{error:O.taskFailure.message,taskFailure:O.taskFailure}),q("session.status",{status:"error"})}finally{if(z.taskAdmission?.release(),z.taskAdmission){let I=r0.getStats();q("task.status",{taskStatus:O.taskStatus,...O.taskStatusReason?{taskStatusReason:O.taskStatusReason}:{},...O.taskFailure?{taskFailure:O.taskFailure}:{},...O.taskStartedAt?{taskStartedAt:O.taskStartedAt}:{},...O.taskCompletedAt?{taskCompletedAt:O.taskCompletedAt}:{},...O.taskDiffStat?{taskDiffStat:O.taskDiffStat}:{},taskQueueDepth:I.queued,taskConcurrencyLimit:I.maxConcurrent,taskInFlight:I.inFlight,updatedAt:new Date().toISOString()})}if(await u?.destroy().catch(()=>{return}),$.disposeRuntimeOnSettle&&z.disposeRuntime)await z.disposeRuntime(O,G).catch((I)=>{y.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${O.id}:`,I)});W2($)}}async function R4($,O,J){y.info(`[SessionRoutes] Looking for permission ${O} in session ${$.sessionId}`),y.info(`[SessionRoutes] Active runs: ${q0.size}`);for(let[z,X]of q0.entries())if(y.info(`[SessionRoutes] Checking run ${z}: sessionId=${X.sessionId}, projectPath=${X.projectPath}, pendingPermission=${X.pendingPermission?.permissionId}`),X.sessionId===$.sessionId&&X.projectPath===$.projectPath&&X.pendingPermission?.permissionId===O){if(X.pendingPermission.details.interactionRequestId)await p0.respond($.projectPath,$.sessionId,O,J);return X.pendingPermission.resolve(J),y.info(`[SessionRoutes] Permission ${O} responded, runId: ${X.id}`),!0}let Z=await p0.findPending($.projectPath,$.sessionId);if(!Z||Z.request.requestId!==O)return y.error(`[SessionRoutes] Permission not found: ${O}`),!1;await p0.respondAndRecover($.projectPath,$.sessionId,O,J);let Y=n.get(h($));if(!Y){let z=await C.findSessionMetadata($.sessionId,$.projectPath);if(!z)return!1;let[X,F]=await Promise.all([C.loadSession($.sessionId,$.projectPath),C.findSessionTaskWorktree($.sessionId,$.projectPath)]);Y=D$(z,X,F),n.set(h($),Y)}else await u0(Y);if(j.publish($,"interaction.resolved",{requestId:O}),J$)J$(Y).catch((z)=>{y.error(`[SessionRoutes] Failed to resume recovered interaction ${O}:`,z)});return!0}var Q1=d("Service"),A2=D.Object({approved:D.Boolean(),remember:D.Optional(D.Boolean()),scope:D.Optional(V0(["once","session","project"])),targetMode:D.Optional(V0(["default","autoEdit","plan","yolo"])),feedback:D.Optional(D.String({maxLength:4000})),answers:D.Optional(D.Record(D.String({maxLength:80}),D.Union([D.String({maxLength:4000}),D.Array(D.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:D.Optional(D.Object({action:V0(["accept","decline","cancel"]),content:D.Optional(D.Record(D.String(),D.Union([D.String({maxLength:4000}),D.Number(),D.Boolean(),D.Array(D.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),j4=()=>{let $=new w2;return $.post("/:permissionId",async(O)=>{let J=O.req.param("permissionId"),Z=O.req.query("sessionId"),Y=O.req.query("projectPath");Q1.info(`[PermissionRoutes] Received permission response: permissionId=${J}, sessionId=${Z}`);try{let z=await O.req.json(),X=m(A2,z);if(!X.success)throw new _("Invalid permission response format");let{approved:F,remember:b,scope:B,targetMode:M,feedback:E,answers:G,elicitation:u}=X.data;if(!Z)throw new _("sessionId query parameter is required");let Y0=await z0(Z,Y);if(!await R4(Y0,J,{approved:F,reason:E,scope:B,targetMode:M,feedback:E,answers:G,elicitation:u}))throw new f("Permission request",J);return Q1.info(`[PermissionRoutes] Permission ${J} ${F?"approved":"denied"}`),O.json({success:!0,approved:F,remember:b})}catch(z){if(Q1.error("[PermissionRoutes] Failed to respond to permission:",z),z instanceof _||z instanceof H0||z instanceof f||z instanceof e)throw z;throw z}}),$};import C4 from"node:path";import{Hono as M2}from"hono";var E2=D.Object({projectPath:D.String({minLength:1}),enabled:D.Boolean(),scope:D.Optional(V0(["local","project","global"]))}),T2=D.Object({projectPath:D.String({minLength:1})}),q2=D.Object({projectPath:D.String({minLength:1}),source:D.String({minLength:1}),trust:D.Literal(!0),ref:D.Optional(D.String({minLength:1}))}),b2=D.Object({projectPath:D.String({minLength:1}),trust:D.Literal(!0)}),R2=D.Object({projectPath:D.String({minLength:1}),confirm:D.Literal(!0)}),j2=D.Object({projectPath:D.String({minLength:1}),source:D.String({minLength:1}),ref:D.Optional(D.String({minLength:1}))}),k4=D.Object({projectPath:D.String({minLength:1}),confirm:D.Optional(D.Literal(!0))}),C2=D.Object({projectPath:D.String({minLength:1}),scope:D.Optional(V0(["local","project","global"])),policy:D.Object({restrictToAllowedSources:D.Boolean(),requireGitCommitSha:D.Boolean(),allowedGitHosts:D.Array(D.String()),allowedMarketplaces:D.Array(D.String()),allowedLocalRoots:D.Array(D.String())})});function B0($){if(!$||!C4.isAbsolute($))throw new _("projectPath must be absolute");return C4.resolve($)}async function I4($){let[O,J]=await Promise.all([W0($),N$.getInstance().loadWorkspacePluginSettingsResolution($)]);return O.plugins.getAll().map((Z)=>({name:Z.manifest.name,description:Z.manifest.description,version:Z.manifest.version,source:Z.source,enabled:Z.status==="active",status:Z.status,commands:Z.commands.length,skills:Z.skills.length,agents:Z.agents.length,hooks:Z.hooks?Object.values(Z.hooks).reduce((Y,z)=>Y+(Array.isArray(z)?z.length:0),0):0,mcpServers:Object.keys(Z.mcpServers??{}).length,configurable:Z.source!=="cli",managed:Z.installation!==void 0,marketplace:Z.installation?.source.type==="marketplace"?Z.installation.source.marketplace:void 0,revision:Z.installation?.revision,installedAt:Z.installation?.installedAt,updatedAt:Z.installation?.updatedAt,compatibilityIssues:Z.compatibilityIssues??[],effectiveScope:Z.source==="cli"?"invocation":J.settings[Z.manifest.name]?.effectiveScope??"default",settingLayers:Z.source==="cli"?{invocation:!0}:J.settings[Z.manifest.name]?.layers??{}}))}async function k2(){let $=P4(),[O,J]=await Promise.all([$.listCatalogs(),$.listInstallationRecords()]),Z=new Map(J.map((Y)=>[Y.name,Y]));return O.map(({marketplace:Y,manifest:z})=>({name:Y.name,description:z.description??z.metadata?.description??"",sourceType:Y.source.type,revision:Y.revision,updatedAt:Y.updatedAt,plugins:z.plugins.map((X)=>{let F=Z.get(X.name);return{name:X.name,description:X.description??"",version:X.version,category:X.category,tags:X.tags??[],installed:F!==void 0,installedVersion:F?.version}})}))}function Z$($,O){if(!$.success)throw new _($.error??O)}var d4=()=>{let $=new M2;return $.get("/",async(O)=>{let J=B0(O.req.query("projectPath"));return O.json(await I4(J))}),$.post("/refresh",async(O)=>{let J=m(T2,await O.req.json());if(!J.success)throw new _("Invalid plugin refresh request");let Z=B0(J.data.projectPath),Y=await f4(Z);return O.json({plugins:await I4(Z),errors:Y.discovery.errors.map((z)=>({code:z.code??"LOAD_ERROR",error:z.error}))})}),$.get("/catalog",async(O)=>{return B0(O.req.query("projectPath")),O.json(await k2())}),$.get("/policy",async(O)=>{let J=B0(O.req.query("projectPath")),Z=await N$.getInstance().loadWorkspacePluginSourcePolicy(J);return O.json({policy:Z,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),$.post("/policy",async(O)=>{let J=m(C2,await O.req.json());if(!J.success)throw new _("Invalid plugin source policy request");let Z=B0(J.data.projectPath),Y=await y4(Z,J.data.policy,J.data.scope??"global");return O.json({policy:Y})}),$.post("/install",async(O)=>{let J=m(q2,await O.req.json());if(!J.success)throw new _("Invalid plugin install request; explicit source trust is required");let Z=B0(J.data.projectPath),{result:Y}=await m4(Z,J.data.source,{trusted:J.data.trust,ref:J.data.ref});return Z$(Y,"Plugin installation failed"),O.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,installedDependencies:Y.installedDependencies??[]})}),$.post("/marketplaces",async(O)=>{let J=m(j2,await O.req.json());if(!J.success)throw new _("Invalid marketplace add request");let Z=B0(J.data.projectPath),Y=await v4(Z,J.data.source,J.data.ref);return Z$(Y,"Marketplace installation failed"),O.json({name:Y.marketplace?.name,plugins:Y.manifest?.plugins.length??0,revision:Y.marketplace?.revision,changed:Y.changed})}),$.post("/marketplaces/:name/refresh",async(O)=>{let J=m(k4,await O.req.json());if(!J.success)throw new _("Invalid marketplace refresh request");let Z=await p4(B0(J.data.projectPath),O.req.param("name"));return Z$(Z,"Marketplace refresh failed"),O.json({name:Z.marketplace?.name,plugins:Z.manifest?.plugins.length??0,revision:Z.marketplace?.revision,changed:Z.changed})}),$.post("/marketplaces/:name/remove",async(O)=>{let J=m(k4,await O.req.json());if(!J.success||J.data.confirm!==!0)throw new _("Invalid marketplace removal request; explicit confirmation is required");B0(J.data.projectPath);let Z=await u4(O.req.param("name"),!0);return Z$(Z,"Marketplace removal failed"),O.json({name:Z.marketplace?.name,removed:!0})}),$.post("/:name/update",async(O)=>{let J=m(b2,await O.req.json());if(!J.success)throw new _("Invalid plugin update request; explicit source trust is required");let Z=B0(J.data.projectPath),{result:Y}=await h4(Z,O.req.param("name"),{trusted:J.data.trust});return Z$(Y,"Plugin update failed"),O.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,updatedDependencies:Y.updatedDependencies??[]})}),$.post("/:name/uninstall",async(O)=>{let J=m(R2,await O.req.json());if(!J.success)throw new _("Invalid plugin uninstall request; explicit confirmation is required");let Z=B0(J.data.projectPath),{result:Y}=await g4(Z,O.req.param("name"),J.data.confirm);return Z$(Y,"Plugin uninstall failed"),O.json({name:Y.pluginName,removed:!0})}),$.post("/:name/state",async(O)=>{let J=m(E2,await O.req.json());if(!J.success)throw new _("Invalid plugin state request");let Z=B0(J.data.projectPath),Y=O.req.param("name"),X=(await W0(Z)).plugins.get(Y);if(!X)throw new f("Plugin",Y);if(X.source==="cli")throw new _(`Plugin "${Y}" was loaded with --plugin-dir and is invocation-scoped`);let F=await S4(Z,Y,J.data.enabled,J.data.scope??"local");return O.json(F)}),$};import{Hono as y2}from"hono";import{execFile as I2}from"node:child_process";import P2 from"node:path";var z1="__BLADE_DIRECTORY_PICKER_CANCELLED__",S2=900000;function f2($,O){return new Promise((J)=>{I2($,[...O],{timeout:S2,maxBuffer:65536,windowsHide:!0},(Z,Y,z)=>{let X=Z?.code;J({stdout:Y,stderr:z,exitCode:typeof X==="number"?X:Z?1:0,...typeof X==="string"?{errorCode:X}:{}})})})}function x1($){let O=$.replace(/[\r\n]+$/,"");if(!O||O===z1)return{cancelled:!0};if(!P2.isAbsolute(O))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:O}}function X1($){return $.exitCode!==0||Boolean($.errorCode)}class l4{platform;runCommand;activeSelection=null;constructor($={}){this.platform=$.platform??process.platform,this.runCommand=$.runCommand??f2}pick(){if(this.activeSelection)return this.activeSelection;let $=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=$,$}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 $=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${z1}"`,"end try"].join(`
8
8
  `),O=await this.runCommand("osascript",["-e",$]);if(X1(O))throw Error("Unable to open the macOS folder picker");return x1(O.stdout)}async pickOnWindows(){let $=["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("${z1}")`,"}"].join("; "),O=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",$]);if(X1(O))throw Error("Unable to open the Windows folder picker");return x1(O.stdout)}async pickOnLinux(){let $=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let O of $){let J=await this.runCommand(O.command,O.args);if(J.errorCode==="ENOENT")continue;if(J.exitCode===1&&!J.stdout.trim()&&!J.stderr.trim())return{cancelled:!0};if(X1(J))throw Error("Unable to open the Linux folder picker");return x1(J.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var c4=new l4;var m2=D.Object({path:D.String({minLength:1})});function h2($){if(!$)return!1;if($==="tauri://localhost"||$==="http://tauri.localhost")return!0;try{let O=new URL($).hostname;return O==="localhost"||O==="127.0.0.1"||O==="::1"||O==="[::1]"}catch{return!1}}var i4=($={})=>{let O=new y2,J=$.pickDirectory??(()=>c4.pick()),Z=$.allowDirectoryPickerRequest??h2;return O.get("/",async(Y)=>{return Y.json(await h$.list(g()))}),O.post("/",async(Y)=>{let z;try{z=await Y.req.json()}catch{throw new _("A valid JSON body is required")}let X=m(m2,z);if(!X.success)throw new _("A project path is required");try{let F=await h$.bind(X.data.path,g());return Y.json(F,201)}catch(F){throw new _(F instanceof Error?F.message:"Failed to bind project")}}),O.post("/pick",async(Y)=>{if(!Z(Y.req.header("Origin")))throw new e("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Y.json(await J())}catch(z){throw new _(z instanceof Error?z.message:"Failed to select a folder")}}),O.delete("/",async(Y)=>{let z=Y.req.query("path");if(!z)throw new _("A project path is required");try{let X=await h$.unbind(z);return Y.json({success:!0,removed:X})}catch(X){throw new _(X instanceof Error?X.message:"Failed to unbind project")}}),O};import{Hono as g2}from"hono";var a4=d("Service"),r4=()=>{let $=new g2;return $.get("/",async(O)=>{try{let J=await n4();return O.json(J)}catch(J){return a4.error("[ProviderRoutes] Failed to list providers:",J),O.json([])}}),$.get("/:provider/models",async(O)=>{let J=O.req.param("provider");try{let Z=await t4(J);return O.json(Z)}catch(Z){return a4.error("[ProviderRoutes] Failed to list models:",Z),O.json([])}}),$.put("/:provider/credential",async(O)=>{let J=O.req.param("provider"),Z=await O.req.json();if(!Z.apiKey?.trim())throw new _("apiKey is required");return await g0().setApiKey(J,Z.apiKey.trim()),O.json({success:!0})}),$.delete("/:provider/credential",async(O)=>{return await g0().clearCredential(O.req.param("provider")),O.json({success:!0})}),$.put("/:provider",async(O)=>{let J=O.req.param("provider"),Z=$0(),Y=Z?.modelProviders[J];if(!Z||!Y)throw new f("Model provider",J);let z=await O.req.json();if(!z.name||!z.baseUrl||!z.wireApi)throw new _("name, baseUrl and wireApi are required");let X="apiKeyEnv"in z?z.apiKeyEnv?.trim():Y.apiKeyEnv,F={name:z.name,baseUrl:z.baseUrl,wireApi:z.wireApi,...X?{apiKeyEnv:X}:{}},b=g0(),B=z.apiKey?.trim()?await b.credentials.read(J):void 0;if(z.apiKey?.trim())await b.setApiKey(J,z.apiKey.trim());try{return await _0().updateModelProvider(J,F),O.json({success:!0})}catch(M){if(z.apiKey?.trim())if(B)await b.credentials.modify(J,async()=>B);else await b.credentials.delete(J);if(M instanceof Error&&(M.message.includes("modelProviders.")||M.message.includes("built-in provider")))throw new _(M.message);throw M}}),$.delete("/:provider",async(O)=>{let J=O.req.param("provider");if(!$0()?.modelProviders[J])throw new f("Model provider",J);let Y=O.req.query("removeModels");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new _("removeModels must be true or false");try{let z=await _0().removeModelProvider(J,{removeModels:Y==="true"});return O.json({success:!0,...z})}catch(z){if(z instanceof Error&&(z.message.includes("still referenced")||z.message.includes("owns the only model")))throw new k(z.message);throw z}}),$.post("/:provider/probe",async(O)=>{let J=O.req.param("provider"),Z=$0();if(!Z?.modelProviders[J])throw new f("Model provider",J);let Y=await O.req.json().catch(()=>({})),z=Z.models.filter((F)=>F.provider===J),X=Y.modelId?z.find((F)=>F.id===Y.modelId):z[0];if(!X)throw new _(Y.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return O.json(await o4(X,Z))}),$};import{Hono as v2}from"hono";var p2=d("Service"),OO=($,O)=>{let J=new v2;return J.onError((Z,Y)=>{if(Z instanceof e)return Y.json(Z.toObject(),Z.statusCode);return p2.error("[ScheduleRoutes] Unhandled route error:",Z),Y.json(new a("Schedule request failed").toObject(),500)}),J.get("/",async(Z)=>{let Y=await $.list();return Z.json($O.parse({schedules:Y}))}),J.post("/",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let z=m(s4,Y);if(!z.success)throw new _("Invalid schedule request");let X=z.data.projectPath||Z.get("directory")||g();try{let F=await $.create({...z.data,projectPath:X});return Z.json(d0.parse(F),201)}catch(F){throw new _(F instanceof Error?F.message:"Failed to create schedule")}}),J.get("/:id",async(Z)=>{let Y=await $.get(Z.req.param("id"));if(!Y)throw new f("Schedule not found");return Z.json(d0.parse(Y))}),J.patch("/:id",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let z=m(e4,Y);if(!z.success)throw new _("Invalid schedule update");let{modelId:X,reasoningEffort:F,serviceTier:b,responseVerbosity:B,communicationStyle:M,isolation:E,permissionMode:G,...u}=z.data,Y0={...X!==void 0?{modelId:X}:{},...F!==void 0?{reasoningEffort:F}:{},...b!==void 0?{serviceTier:b}:{},...B!==void 0?{responseVerbosity:B}:{},...M!==void 0?{communicationStyle:M}:{},...E!==void 0?{isolation:E}:{},...G!==void 0?{permissionMode:G}:{}};try{let q=await $.update(Z.req.param("id"),{...u,...Object.keys(Y0).length>0?{dispatch:Y0}:{}});if(!q)throw new f("Schedule not found");return Z.json(d0.parse(q))}catch(q){if(q instanceof e)throw q;throw new _(q instanceof Error?q.message:"Failed to update schedule")}}),J.delete("/:id",async(Z)=>{if(!await $.remove(Z.req.param("id")))throw new f("Schedule not found");return Z.json({ok:!0})}),J.post("/:id/enable",async(Z)=>{let Y=await $.setEnabled(Z.req.param("id"),!0);if(!Y)throw new f("Schedule not found");return Z.json(d0.parse(Y))}),J.post("/:id/disable",async(Z)=>{let Y=await $.setEnabled(Z.req.param("id"),!1);if(!Y)throw new f("Schedule not found");return Z.json(d0.parse(Y))}),J.post("/:id/run",async(Z)=>{let Y=await $.get(Z.req.param("id"));if(!Y)throw new f("Schedule not found");if(!O)throw new a("Scheduler is not running in this process");await O.fire(Y,new Date,{manual:!0});let z=await $.get(Y.id);return Z.json(d0.parse(z??Y),202)}),J};import*as S0 from"node:fs/promises";import{homedir as QO}from"node:os";import*as L0 from"node:path";import{Hono as u2}from"hono";var l0=d("Service"),JO=L0.join(QO(),".blade","skills"),K1=L0.join(QO(),".blade","skills-config.json");async function xO(){try{let $=await S0.readFile(K1,"utf-8");return JSON.parse($)}catch{return{disabled:[]}}}async function d2($){await S0.mkdir(L0.dirname(K1),{recursive:!0}),await S0.writeFile(K1,JSON.stringify($,null,2))}async function l2($,O){let J=await xO();if(O)J.disabled=J.disabled.filter((Z)=>Z!==$);else if(!J.disabled.includes($))J.disabled.push($);await d2(J)}var P0=null,c2=300000,i2=6;async function a2(){if(P0&&Date.now()-P0.timestamp<c2)return P0.data;try{let $=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!$.ok){if(l0.warn(`GitHub API returned ${$.status}`),P0)return P0.data;throw Error(`GitHub skills catalog returned ${$.status}`)}let J=(await $.json()).filter((X)=>X.type==="dir"),Z=Array(J.length),Y=0,z=Math.min(i2,J.length);return await Promise.all(Array.from({length:z},async()=>{while(Y<J.length){let X=Y++,F=J[X];if(!F)continue;let b=`Official ${F.name} skill`;try{let B=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${F.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(B.ok){let E=(await B.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(E)b=E[1].trim().slice(0,100)}}catch{}Z[X]={name:F.name,description:b,tag:"Official",author:"Anthropic"}}})),P0={data:Z,timestamp:Date.now()},Z}catch($){if(l0.warn("Failed to fetch skills catalog from GitHub:",$),P0)return P0.data;throw $}}var XO=()=>{let $=new u2;return $.get("/",async(O)=>{try{let J=O.get("directory")||g(),Y=(await W0(J)).skills.getAll(),z=await xO(),X=Y.map((F)=>({id:F.name,name:F.name,enabled:!z.disabled.includes(F.name),description:F.description||"",version:F.version||"1.0.0",provider:"Local",location:F.source==="builtin"?"Built-in":F.basePath,removable:F.source==="user"&&L0.dirname(L0.resolve(F.basePath))===L0.resolve(JO),capabilities:["prompts"],allowedTools:F.allowedTools||[]}));return O.json(X)}catch(J){return l0.error("[SkillsRoutes] Failed to get skills:",J),O.json({error:J instanceof Error?J.message:"Failed to get skills"},500)}}),$.post("/:name/toggle",async(O)=>{try{let J=O.req.param("name"),Z=await O.req.json();return await l2(J,Z.enabled),O.json({success:!0,enabled:Z.enabled})}catch(J){return l0.error("[SkillsRoutes] Failed to toggle skill:",J),O.json({success:!1,error:J.message},500)}}),$.delete("/:name",async(O)=>{try{let J=O.req.param("name"),Z=O.get("directory")||g(),Y=(await W0(Z)).skills,z=Y.get(J);if(!z)return O.json({success:!1,error:"Skill not found"},404);let X=L0.resolve(z.basePath),F=L0.resolve(JO);if(z.source!=="user"||L0.dirname(X)!==F)return O.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await S0.rm(X,{recursive:!0,force:!0}),await Y.refresh(),W$(Z),await G$(Z),O.json({success:!0})}catch(J){return l0.error("[SkillsRoutes] Failed to uninstall skill:",J),O.json({success:!1,error:J.message},500)}}),$.post("/install",async(O)=>{try{let J=await O.req.json(),Z=ZO(),Y=O.get("directory")||g(),z=YO({cwd:Y}),X=!1;if(J.source==="catalog"&&J.name){if(X=await Z.installOfficialSkill(J.name),!X)return O.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(J.source==="repo"&&J.url){if(X=await Z.installFromRepo(J.url,J.name),!X)return O.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){if(X=await Z.installFromLocal(J.path,J.name),!X)return O.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 O.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await z.refresh(),W$(Y),await G$(Y),O.json({success:!0})}catch(J){return l0.error("[SkillsRoutes] Failed to install skill:",J),O.json({success:!1,error:J.message},500)}}),$.get("/catalog",async(O)=>{try{let J=await a2();return O.json(J)}catch(J){return l0.error("[SkillsRoutes] Failed to get catalog:",J),O.json({error:J instanceof Error?J.message:"Failed to get skills catalog"},502)}}),$};import{execSync as o2}from"node:child_process";import{readdir as n2}from"node:fs/promises";import g$ from"node:path";import t2 from"fast-glob";import{Hono as r2}from"hono";var E$=d("Service"),s2=($)=>{try{return o2("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},e2=[...Y$.map(($)=>`${$}/**`),...Y$,...Y$.map(($)=>`**/${$}/**`),...Y$.map(($)=>`**/${$}`),...V1.map(($)=>`**/${$}`)],$5=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),VO=()=>{let $=new r2;return $.get("/commands",async(O)=>{try{let J=O.req.query("q")||"",Z=O.get("directory")||g();await W0(Z);let Y=KO(J,Z).filter((z)=>!$5.has(z.command));return O.json(Y)}catch(J){return E$.error("[SuggestionsRoutes] Failed to get command suggestions:",J),O.json([])}}),$.get("/files",async(O)=>{try{let J=O.req.query("q")||"",Z=O.get("directory")||g(),Y=Math.min(Number(O.req.query("limit"))||100,1000),z=O.req.query("type")==="file",F=(await t2("**/*",{cwd:Z,dot:!1,followSymbolicLinks:!1,onlyFiles:z,markDirectories:!0,unique:!0,ignore:e2})).map((M)=>M.replace(/\\/g,"/"));if(!J)return O.json(F.slice(0,Y));let b=J.toLowerCase(),B=F.filter((M)=>M.toLowerCase().includes(b)).slice(0,Y);return O.json(B)}catch(J){return E$.error("[SuggestionsRoutes] Failed to get file suggestions:",J),O.json([])}}),$.get("/files/tree",async(O)=>{try{let J=O.get("directory")||g(),Z=O.req.query("path")||"",Y=Z?g$.join(J,Z):J,X=(await n2(Y,{withFileTypes:!0})).map((B)=>({name:B.name,path:Z?`${Z}/${B.name}`:B.name,type:B.isDirectory()?"dir":"file"}));X.sort((B,M)=>{if(B.type!==M.type)return B.type==="dir"?-1:1;return B.name.localeCompare(M.name)});let F=new Set(Y$),b=X.filter((B)=>{let M=B.name;if(M.startsWith("."))return!1;if(F.has(M))return!1;for(let E of V1)if(M.match(new RegExp(E.replace("*",".*"))))return!1;return!0});return O.json(b)}catch(J){return E$.error("[SuggestionsRoutes] Failed to get file tree:",J),O.json([])}}),$.get("/files/content",async(O)=>{try{let J=O.req.query("path");if(!J)return O.json({error:"Missing file path"},400);let Z=O.get("directory")||g(),Y=g$.resolve(Z,J),z=g$.relative(Z,Y);if(z.startsWith("..")||g$.isAbsolute(z))return O.json({error:"Invalid file path"},400);let X=zO(),F=await X.stat(Y);if(!F?.isFile)return O.json({error:"File not found"},404);let b=200000,B=await X.readTextFile(Y),M=B.length>b;return O.json({path:J,content:M?B.slice(0,b):B,truncated:M,size:F.size})}catch(J){return E$.error("[SuggestionsRoutes] Failed to get file content:",J),O.json({error:"Failed to read file"},500)}}),$.get("/git-info",async(O)=>{try{let J=O.get("directory")||g(),Z=s2(J);return O.json({branch:Z})}catch(J){return E$.error("[SuggestionsRoutes] Failed to get git info:",J),O.json({branch:null})}}),$};import{Hono as O5}from"hono";var T$=d("Service"),UO=($)=>{let O=new O5;return O.onError((J,Z)=>{if(J instanceof e)return Z.json(J.toObject(),J.statusCode);return T$.error("[TaskRoutes] Unhandled route error:",J),Z.json(new a("Failed to dispatch task").toObject(),500)}),O.post("/",async(J)=>{let Z;try{Z=await J.req.json()}catch{throw new _("Invalid request body")}let Y=m(WO,Z);if(!Y.success)throw new _("Invalid task request");if((Y.data.attachments??[]).reduce((X,F)=>X+(typeof F.content==="string"?Buffer.byteLength(F.content):0),0)>y$)throw new _("Task attachments exceed the 5 MiB limit");try{let X=await $.dispatchTask({prompt:Y.data.prompt,title:Y.data.title,sourceProjectPath:Y.data.projectPath||J.get("directory")||g(),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 J.json(N1.parse(X),202)}catch(X){if(X instanceof _||X instanceof k||X instanceof h0||X instanceof o0)throw X;throw T$.error("[TaskRoutes] Failed to dispatch task:",X),new a("Failed to dispatch task")}}),O.post("/:sessionId/retry",async(J)=>{try{let Z=await $.retryTask(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(N1.parse(Z),202)}catch(Z){if(Z instanceof _||Z instanceof f||Z instanceof k||Z instanceof h0||Z instanceof o0)throw Z;throw T$.error("[TaskRoutes] Failed to retry task:",Z),new a("Failed to retry task")}}),O.get("/:sessionId/diff",async(J)=>{try{let Z=await $.getTaskDiff(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(NO.parse(Z))}catch(Z){if(Z instanceof _||Z instanceof f||Z instanceof k)throw Z;throw T$.error("[TaskRoutes] Failed to load task diff:",Z),new a("Failed to load task diff")}}),O.post("/:sessionId/delivery",async(J)=>{let Z;try{Z=await J.req.json()}catch{throw new _("Invalid request body")}let Y=m(FO,Z);if(!Y.success)throw new _("Invalid task delivery request");try{let z=await $.deliverTask(J.req.param("sessionId"),Y.data.action,J.req.query("projectPath"));return J.json(GO.parse(z))}catch(z){if(z instanceof _||z instanceof f||z instanceof k)throw z;throw T$.error("[TaskRoutes] Failed to deliver task:",z),new a("Failed to deliver task")}}),O};import{Hono as J5}from"hono";var f0=d("Service"),Q$=new Map,DO=2097152,HO=65536;function _O(){return typeof globalThis.Bun<"u"}async function Z5($,O,J){if(_O()){let{spawn:z}=await import("bun-pty"),X=z($,O,{name:"xterm-256color",cwd:J.cwd,env:J.env});return{pid:X.pid,write:(F)=>X.write(F),resize:(F,b)=>X.resize(F,b),kill:()=>X.kill(),onData:(F)=>X.onData(F),onExit:(F)=>X.onExit(F)}}let Y=(await import("node-pty")).spawn($,O,{name:"xterm-256color",cwd:J.cwd,env:J.env,cols:80,rows:24});return{pid:Y.pid,write:(z)=>Y.write(z),resize:(z,X)=>Y.resize(z,X),kill:()=>Y.kill(),onData:(z)=>{Y.onData(z)},onExit:(z)=>{Y.onExit(z)}}}var F1=void 0,W1;if(_O())try{let{createBunWebSocket:$}=await import("hono/bun"),O=$();W1=O.upgradeWebSocket,F1=O.websocket}catch($){f0.warn("[Terminal] Failed to initialize Bun WebSocket support:",$)}async function BO($,O){let J=`term-${Date.now()}`;f0.info(`[Terminal] New connection: ${J}, cwd: ${$}`);let Z=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=Z.endsWith("sh")?["-l"]:[],z=await Z5(Z,Y,{cwd:$,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),X={id:J,process:z,cwd:$,buffer:"",subscribers:new Set};if(Q$.set(J,X),X.subscribers.add(O),z.onData((F)=>{let b=!1;for(let B of X.subscribers)try{B.send(F),b=!0}catch{X.subscribers.delete(B)}if(b)return;if(X.buffer+=F,X.buffer.length>DO)X.buffer=X.buffer.slice(-DO)}),z.onExit(({exitCode:F})=>{f0.info(`[Terminal] Process exited: ${J}, code: ${F}`);for(let b of X.subscribers)try{b.close()}catch{}Q$.delete(J)}),X.buffer){let F=X.buffer;X.buffer="";for(let b=0;b<F.length;b+=HO)O.send(F.slice(b,b+HO))}return{session:X,cleanup:()=>{if(f0.info(`[Terminal] Connection closed: ${J}`),X.subscribers.delete(O),X.subscribers.size===0){try{X.process.kill()}catch{}Q$.delete(J)}}}}function LO($,O){$.on("connection",async(J,Z)=>{let Y=new URL(Z.url||"/",`http://${Z.headers.host}`);if(!Y.pathname.endsWith("/terminal/ws")){J.close();return}let z=Y.searchParams.get("cwd")||O()||g();try{let{session:X,cleanup:F}=await BO(z,{send:(b)=>J.send(b),close:()=>J.close()});J.on("message",(b)=>{try{X.process.write(String(b))}catch(B){f0.error("[Terminal] Failed to write to PTY:",B)}}),J.on("close",F),J.on("error",F)}catch(X){f0.error("[Terminal] Failed to spawn PTY:",X),J.close()}})}var wO=()=>{let $=new J5;if($.get("/status",(O)=>{let J=Array.from(Q$.values()).map((Z)=>({id:Z.id,cwd:Z.cwd}));return O.json({active:J.length,terminals:J})}),$.post("/kill/:terminalId",(O)=>{let J=O.req.param("terminalId"),Z=Q$.get(J);if(Z){try{Z.process.kill()}catch{}for(let Y of Z.subscribers)Y.close();return Q$.delete(J),O.json({success:!0})}return O.json({success:!1,error:"Terminal not found"},404)}),W1)$.get("/ws",W1((O)=>{let J=O.req.query("cwd")||O.get("directory")||g(),Z;return{async onOpen(Y,z){try{Z=await BO(J,{send:(X)=>z.send(X),close:()=>z.close()})}catch(X){f0.error("[Terminal] Failed to spawn PTY:",X),z.close()}},onMessage(Y){if(!Z)return;try{Z.session.process.write(String(Y.data))}catch(z){f0.error("[Terminal] Failed to write to PTY:",z)}},onClose(){Z?.cleanup()}}}));else $.get("/ws",(O)=>{return O.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return $};import Y5 from"node:path";import{Hono as Q5}from"hono";var x5=D.Object({projectPath:D.String({minLength:1}),action:V0(["trust","revoke"])});function AO($){if(!Y5.isAbsolute($))throw new _("projectPath must be absolute")}var EO=()=>{let $=new Q5;return $.get("/",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return AO(J),O.json(await U1.getInstance().getStatus(J))}),$.post("/",async(O)=>{let J=m(x5,await O.req.json());if(!J.success)throw new _("Invalid workspace trust request");let{projectPath:Z,action:Y}=J.data;AO(Z);let z=U1.getInstance(),X=Y==="trust"?await z.trust(Z):await z.revoke(Z);return await MO(),O.json({...X,reloadRequired:X.sensitiveSources>0})}),$};var K0=d("Service"),_1=[],v$,x$,X$,p$,TO=new Map,qO=new Map,_5=new Set([".css",".html",".js",".json",".svg"]),B5=1024,L5=3600000;function w5($,O){if(!$)return 0;let J=$.split(",").map((Z)=>{let[Y,...z]=Z.trim().toLowerCase().split(";"),X=z.find((b)=>b.trim().startsWith("q=")),F=X?Number(X.trim().slice(2)):1;return{name:Y,quality:Number.isFinite(F)?Math.max(0,Math.min(1,F)):0}});return J.find((Z)=>Z.name===O)?.quality??J.find((Z)=>Z.name==="*")?.quality??0}function bO(){if(X$)return;let $=()=>{C.collectStaleEmptySessions().then((O)=>{if(O>0)K0.info(`[SessionGC] removed ${O} stale empty session(s)`)}).catch((O)=>{K0.warn("[SessionGC] failed to collect stale empty sessions:",O)})};$(),X$=setInterval($,L5),X$.unref?.()}function A5(){if(!X$)return;clearInterval(X$),X$=void 0}function M5($){return["br","gzip"].map((J)=>({encoding:J,quality:w5($,J)})).filter((J)=>J.quality>0).sort((J,Z)=>Z.quality-J.quality||(J.encoding==="br"?-1:1))[0]?.encoding}function E5($){let O=TO.get($);if(O)return O;let J=q$($);return TO.set($,J),J}function T5($,O,J){let Z=`${J}:${$}`,Y=qO.get(Z);if(Y)return Y;let z=J==="br"?G5(O,{params:{[F5.BROTLI_PARAM_QUALITY]:5}}):W5(O,{level:6});return qO.set(Z,z),z}function q5(){let $=K5(N5(import.meta.url)),O=[y0($,"web"),y0(g(),"dist/web"),y0(g(),"packages/cli/dist/web")];for(let J of O){let Z=y0(J,"index.html");if(H1(Z)){if(q$(Z,"utf-8").includes("/assets/"))return K0.debug(`[Server] Found web dist at: ${J}`),J}}return null}function b5(){let $=new U5;$.onError((Z,Y)=>{if(K0.error("[Server] Request error:",Z),Z instanceof e)return Y.json(Z.toObject(),Z.statusCode);let z=Z instanceof Error?Z.message:String(Z);return Y.json({error:{code:"INTERNAL_ERROR",message:z}},500)}),$.use(async(Z,Y)=>{let z=process.env.BLADE_SERVER_PASSWORD;if(!z)return Y();let X=Z.req.path;if(X==="/"||X==="/favicon.svg"||X.startsWith("/assets/")||X.endsWith(".html")||X.endsWith(".js")||X.endsWith(".css"))return Y();let F=Z.req.header("Authorization");if(!F?.startsWith("Basic "))return Z.header("WWW-Authenticate",'Basic realm="Blade Server"'),Z.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let b=Buffer.from(F.slice(6),"base64").toString(),[B,M]=b.split(":"),E=process.env.BLADE_SERVER_USERNAME??"blade";if(B!==E||M!==z)return Z.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Y()}),$.use(async(Z,Y)=>{let z=Z.req.path==="/health"||Z.req.path==="/global/health"||Z.req.path.startsWith("/assets/");if(!z)K0.debug(`[Server] ${Z.req.method} ${Z.req.path}`);let X=Date.now();if(await Y(),!z){let F=Date.now()-X;K0.debug(`[Server] ${Z.req.method} ${Z.req.path} - ${Z.res.status} (${F}ms)`)}}),$.use(D5({origin(Z){if(!Z)return;if(Z.startsWith("http://localhost:"))return Z;if(Z.startsWith("http://127.0.0.1:"))return Z;if(Z==="tauri://localhost"||Z==="http://tauri.localhost")return Z;if(_1.includes(Z))return Z;return}})),$.use(async(Z,Y)=>{let z=Z.req.query("directory")||Z.req.header("x-blade-directory")||g();try{z=decodeURIComponent(z)}catch{}return Z.set("directory",z),Y()});let O=b4();p$=O,v$=O.recoverQueuedTasks,x$=new c$({dispatch:(Z)=>O.dispatchTask(Z),store:D1}),$.route("/global",v1()),$.route("/events",h1()),$.route("/sessions",O.app),$.route("/tasks",UO(O)),$.route("/schedules",OO(D1,x$)),$.route("/configs",I1()),$.route("/permissions",j4()),$.route("/plugins",d4()),$.route("/hooks",i1()),$.route("/workspace-trust",EO()),$.route("/providers",r4()),$.route("/models",O4()),$.route("/projects",i4()),$.route("/suggestions",VO()),$.route("/terminal",wO()),$.route("/mcp",n1()),$.route("/skills",XO()),$.get("/health",(Z)=>{return Z.json({healthy:!0,version:t0()})});let J=q5();if(J)K0.info(`[Server] Serving static files from ${J}`),$.get("/favicon.svg",()=>{let Z=y0(J,"favicon.svg");if(!H1(Z))return new Response(null,{status:404});return new Response(q$(Z),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),$.get("/assets/*",(Z)=>{let Y=y0(J,Z.req.path);if(!H1(Y))return Z.json({error:{code:"NOT_FOUND",message:`File not found: ${Z.req.path}`}},404);let z=E5(Y),X=V5(Y).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"}[X]||"application/octet-stream",B=_5.has(X)&&z.byteLength>=B5?M5(Z.req.header("Accept-Encoding")):void 0,M=B?T5(Y,z,B):z;return new Response(new Uint8Array(M),{headers:{"Content-Type":b,"Content-Length":String(M.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...B?{"Content-Encoding":B}:{}}})}),$.get("/",(Z)=>{let Y=y0(J,"index.html"),z=q$(Y,"utf-8");return Z.html(z,200,{"Cache-Control":"no-cache"})}),$.get("*",(Z)=>{let Y=Z.req.path;if(Y.includes("."))return Z.json({error:{code:"NOT_FOUND",message:`File not found: ${Y}`}},404);let z=y0(J,"index.html"),X=q$(z,"utf-8");return Z.html(X,200,{"Cache-Control":"no-cache"})});else K0.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),$.get("/",(Z)=>{return Z.json({message:"Blade API Server",version:t0(),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"}})}),$.all("*",(Z)=>{return Z.json({error:{code:"NOT_FOUND",message:`Route not found: ${Z.req.path}`}},404)});return $}function R5(){let $=z5(),O=[];for(let J of Object.keys($)){let Z=$[J];if(!Z)continue;for(let Y of Z){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;O.push(Y.address)}}return O}function RO(){return typeof globalThis.Bun<"u"}function jO($,O){let J=globalThis.Bun,Z=(z)=>{try{return J.serve({hostname:O.hostname,port:z,fetch:$.fetch,idleTimeout:0,websocket:F1})}catch(X){K0.error("Failed to start Bun server:",X);return}},Y=O.port===0?Z(4096)??Z(0):Z(O.port);if(!Y)throw Error(`Failed to start Bun server on port ${O.port}`);return{url:Y.url,port:Y.port,hostname:Y.hostname,stop:async()=>{Y.stop(!0)}}}function j5($,O){return new Promise((J,Z)=>{let Y=X5(async(B,M)=>{let E=new URL(B.url||"/",`http://${B.headers.host}`),G=new Headers;for(let[q,t]of Object.entries(B.headers))if(t)if(Array.isArray(t))for(let I of t)G.append(q,I);else G.set(q,t);let u;if(B.method!=="GET"&&B.method!=="HEAD")u=(await new Promise((t)=>{let I=[];B.on("data",(O0)=>I.push(O0)),B.on("end",()=>t(Buffer.concat(I)))})).toString();let Y0=new Request(E.toString(),{method:B.method,headers:G,body:u});try{let q=await $.fetch(Y0);if(M.statusCode=q.status,q.headers.forEach((t,I)=>{M.setHeader(I,t)}),q.body){let t=q.body.getReader(),I=async()=>{let{done:O0,value:v}=await t.read();if(O0){M.end();return}return M.write(v),I()};await I()}else{let t=await q.text();M.end(t)}}catch(q){K0.error("[Server] Node request error:",q),M.statusCode=500,M.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),z=new H5({noServer:!0}),X=g();LO(z,()=>X),Y.on("upgrade",(B,M,E)=>{if(new URL(B.url||"/",`http://${B.headers.host}`).pathname==="/terminal/ws")z.handleUpgrade(B,M,E,(u)=>{z.emit("connection",u,B)});else M.destroy()});let F=(B)=>{return new Promise((M,E)=>{Y.once("error",(G)=>{if(G.code==="EADDRINUSE")E(G);else E(G)}),Y.listen(B,O.hostname,()=>{let G=Y.address();if(G&&typeof G==="object")M(G.port);else M(B)})})};(async()=>{let B;if(O.port===0)try{B=await F(4096)}catch{B=await F(0)}else B=await F(O.port);let M=new URL(`http://${O.hostname==="0.0.0.0"?"localhost":O.hostname}:${B}`);J({url:M,port:B,hostname:O.hostname,stop:async()=>{return new Promise((E)=>{z.close(()=>{Y.close(()=>E())})})}})})().catch(Z)})}var CO;((u6)=>{let $,O,J,Z=(b,B)=>{if($!==b)return Promise.resolve();if(J)return J;let M=B?.shutdown("server-shutdown");return x$?.stop(),A5(),J=(async()=>{let E,G=async(u)=>{if(!u)return;try{await u()}catch(Y0){E??=Y0}};if(await G(()=>b.stop()),await G(M?()=>M:void 0),$===b)$=void 0,O=void 0,p$=void 0,v$=void 0,x$=void 0;if(K0.info("[Server] Blade server stopped"),E!==void 0)throw E})(),J};function Y(){if(!O)O=b5();return O}u6.getApp=Y;function z(b){_1=b.cors??[];let B=Y();if(RO())$=jO(B,b),J=void 0,K0.info(`[Server] Blade server listening on ${$.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");let M=$,E=p$;return v$?.().catch((G)=>{K0.warn("[Server] Failed to recover queued tasks:",G)}),x$?.start(),bO(),{url:M.url,port:M.port,hostname:M.hostname,stop:()=>Z(M,E)}}u6.listen=z;async function X(b){_1=b.cors??[];let B=Y();if(RO())$=jO(B,b),K0.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else $=await j5(B,b),K0.info(`[Server] Blade server listening on ${$.url} (Node.js runtime)`);J=void 0;let M=$,E=p$;try{await v$?.()}catch(G){K0.warn("[Server] Failed to recover queued tasks:",G)}return x$?.start(),bO(),{url:M.url,port:M.port,hostname:M.hostname,stop:()=>Z(M,E)}}u6.listenAsync=X;function F(){return $!==void 0}u6.isRunning=F})(CO||={});export{C5 as f,k5 as g,R5 as h,CO as i};