blade-code 0.10.71 → 0.10.72

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 (108) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-fcv8b6ny.js → chunk-06y3rada.js} +2 -2
  3. package/dist/{chunk-k0pa8874.js → chunk-0kat01bw.js} +1 -1
  4. package/dist/{chunk-th4jjfgm.js → chunk-0qj8jfj1.js} +1 -1
  5. package/dist/{chunk-ahg9vjb6.js → chunk-11gdqmbm.js} +1 -1
  6. package/dist/chunk-139s7p91.js +1 -0
  7. package/dist/{chunk-zvz2cnt4.js → chunk-18atvz38.js} +1 -1
  8. package/dist/{chunk-9hchc346.js → chunk-28wsyv32.js} +1 -1
  9. package/dist/{chunk-rm9hbew3.js → chunk-2d2bcyn1.js} +1 -1
  10. package/dist/{chunk-0tm20v38.js → chunk-2fd5trh8.js} +2 -2
  11. package/dist/{chunk-cdy9efgm.js → chunk-2sdnmxts.js} +1 -1
  12. package/dist/chunk-2vkzwqv0.js +1 -0
  13. package/dist/chunk-41smvqs8.js +1 -0
  14. package/dist/{chunk-hat9v5c5.js → chunk-4wvsg8cc.js} +1 -1
  15. package/dist/{chunk-6pyktfa4.js → chunk-4xpj0d6y.js} +1 -1
  16. package/dist/{chunk-byqxaa9v.js → chunk-5va3hhfp.js} +1 -1
  17. package/dist/chunk-61arrvhp.js +1 -0
  18. package/dist/{chunk-yn51162x.js → chunk-6j3k4v08.js} +1 -1
  19. package/dist/{chunk-s7jsadnc.js → chunk-6j9t1xbh.js} +2 -2
  20. package/dist/{chunk-nx31fkkf.js → chunk-6v7f2cv9.js} +53 -53
  21. package/dist/{chunk-j9q1wyxg.js → chunk-7am1z065.js} +1 -1
  22. package/dist/{chunk-2428hhvj.js → chunk-7hf1k2c9.js} +2 -2
  23. package/dist/chunk-8geywf8q.js +1 -0
  24. package/dist/{chunk-wrfay5r3.js → chunk-91qsjpm6.js} +2 -2
  25. package/dist/{chunk-1je1xw6v.js → chunk-a38chc6z.js} +18 -18
  26. package/dist/{chunk-0vrgrw71.js → chunk-awj9aqjy.js} +2 -2
  27. package/dist/chunk-bqz8wera.js +1 -0
  28. package/dist/chunk-brm24s69.js +2 -0
  29. package/dist/{chunk-r9d4mjxj.js → chunk-bs77d8hn.js} +1 -1
  30. package/dist/{chunk-mtphps19.js → chunk-c4j2anbm.js} +2 -2
  31. package/dist/{chunk-82htkvz8.js → chunk-ccgq8nrm.js} +2 -2
  32. package/dist/{chunk-be30r8an.js → chunk-cqeqjtxn.js} +1 -1
  33. package/dist/{chunk-93tvxmqg.js → chunk-cyjnza5n.js} +4 -4
  34. package/dist/chunk-d9a0g85f.js +1 -0
  35. package/dist/{chunk-1pjkgfez.js → chunk-e0hf1317.js} +1 -1
  36. package/dist/chunk-e4ynb9qf.js +1 -0
  37. package/dist/chunk-e6ezndyf.js +22 -0
  38. package/dist/{chunk-jzntxp7f.js → chunk-eh4h7fmr.js} +2 -2
  39. package/dist/chunk-eh9gdzk5.js +160 -0
  40. package/dist/chunk-emqbb5xh.js +1 -0
  41. package/dist/{chunk-h0ft81a3.js → chunk-g8425xh4.js} +1 -1
  42. package/dist/{chunk-t2wgf9tq.js → chunk-gv3ed5gw.js} +2 -2
  43. package/dist/chunk-gzysna9c.js +1 -0
  44. package/dist/{chunk-axtzde5k.js → chunk-hhk5ecpv.js} +2 -2
  45. package/dist/{chunk-gtcxybv5.js → chunk-hhvkzn6m.js} +1 -1
  46. package/dist/{chunk-d3ttqmyt.js → chunk-hryhnmwv.js} +277 -262
  47. package/dist/{chunk-2px6hzdc.js → chunk-hwjmm2br.js} +2 -2
  48. package/dist/{chunk-9q852bsc.js → chunk-j0yvwrd7.js} +2 -2
  49. package/dist/{chunk-m57w4p91.js → chunk-jyds9m8p.js} +1 -1
  50. package/dist/{chunk-v0rsz1rt.js → chunk-m6qgme8k.js} +1 -1
  51. package/dist/{chunk-97aywyzn.js → chunk-mhyat4mq.js} +2 -2
  52. package/dist/{chunk-qgrq04hb.js → chunk-mp4bfn57.js} +1 -1
  53. package/dist/chunk-mrh3vs01.js +2 -0
  54. package/dist/chunk-ph5rn44j.js +1 -0
  55. package/dist/chunk-pqhjrdnq.js +10 -0
  56. package/dist/{chunk-0j22w4wh.js → chunk-q6daf441.js} +1 -1
  57. package/dist/{chunk-0wxkymqv.js → chunk-s9brgcgs.js} +1 -1
  58. package/dist/{chunk-trn6r1g3.js → chunk-ss1znmv0.js} +1 -1
  59. package/dist/{chunk-3hy06st1.js → chunk-tms0pr01.js} +2 -2
  60. package/dist/chunk-v7phc78b.js +1 -0
  61. package/dist/{chunk-t8xmh4w2.js → chunk-wvg81sd9.js} +1 -1
  62. package/dist/{chunk-x9tvjkjv.js → chunk-x4hh8yqg.js} +1 -1
  63. package/dist/{chunk-dwb2nmms.js → chunk-xahapj98.js} +1 -1
  64. package/dist/{chunk-s77sbxr7.js → chunk-xszsveq1.js} +1 -1
  65. package/dist/{chunk-azw0jckv.js → chunk-y858e8pb.js} +2 -2
  66. package/dist/{chunk-bjqjdw34.js → chunk-yhnr8vdb.js} +2 -2
  67. package/dist/{chunk-cff9gphh.js → chunk-yjj7q7hy.js} +1 -1
  68. package/dist/{chunk-zdnk7qtn.js → chunk-ypwjzw5x.js} +2 -2
  69. package/dist/{chunk-4ke8k0xw.js → chunk-z7vj2xrg.js} +3 -3
  70. package/dist/{chunk-5te2jqt3.js → chunk-zac26wwd.js} +1 -1
  71. package/dist/{chunk-wfy851et.js → chunk-zf96d5we.js} +1 -1
  72. package/dist/chunk-zqxj65xc.js +1 -0
  73. package/dist/chunk-zssys78z.js +1 -0
  74. package/dist/web/assets/ChatView-CgUC5rxo.js +18 -0
  75. package/dist/web/assets/{CodeBlockHighlighter-Dy7QpAmC.js → CodeBlockHighlighter-B5DRAEhB.js} +1 -1
  76. package/dist/web/assets/{FilePreview-BI3nkxz1.js → FilePreview-DSpvLsjW.js} +1 -1
  77. package/dist/web/assets/{KanbanBoard-D5dYOyPH.js → KanbanBoard-6K7IeCXi.js} +1 -1
  78. package/dist/web/assets/{MarkdownRenderer-Da1vB81L.js → MarkdownRenderer-D6LiW9kF.js} +3 -3
  79. package/dist/web/assets/{SettingsModal-jcCFqLqS.js → SettingsModal-CFHxLfuL.js} +1 -1
  80. package/dist/web/assets/{TaskSwitcher-CQ--jOLB.js → TaskSwitcher-Bng9nDed.js} +1 -1
  81. package/dist/web/assets/{TerminalPanel-CWzjEXOb.js → TerminalPanel-BnyQZwkN.js} +1 -1
  82. package/dist/web/assets/index-CDdYV8kB.css +1 -0
  83. package/dist/web/assets/index-DId2GJVO.js +11 -0
  84. package/dist/web/assets/{vendor-icons-B63aW_OM.js → vendor-icons-C927DZlr.js} +41 -36
  85. package/dist/web/index.html +3 -3
  86. package/package.json +1 -1
  87. package/dist/chunk-1w83z8j0.js +0 -1
  88. package/dist/chunk-3as0bkqy.js +0 -1
  89. package/dist/chunk-4pexpa3h.js +0 -160
  90. package/dist/chunk-8j568nm6.js +0 -1
  91. package/dist/chunk-92x15fzx.js +0 -2
  92. package/dist/chunk-ckqpt15b.js +0 -1
  93. package/dist/chunk-fcmgwzrj.js +0 -10
  94. package/dist/chunk-gvbx0t4j.js +0 -1
  95. package/dist/chunk-j0p54tqt.js +0 -1
  96. package/dist/chunk-n827nys9.js +0 -1
  97. package/dist/chunk-nwzpnx7m.js +0 -22
  98. package/dist/chunk-qnsvae10.js +0 -1
  99. package/dist/chunk-sp3bn8qh.js +0 -1
  100. package/dist/chunk-v7p533ff.js +0 -1
  101. package/dist/chunk-vthgpdbd.js +0 -1
  102. package/dist/chunk-wneeq8cr.js +0 -1
  103. package/dist/chunk-xdz5zrjt.js +0 -1
  104. package/dist/chunk-xz6y0w4n.js +0 -2
  105. package/dist/chunk-xzz69esf.js +0 -1
  106. package/dist/web/assets/ChatView-BVrhnE2j.js +0 -18
  107. package/dist/web/assets/index-BOgOL4hG.js +0 -11
  108. package/dist/web/assets/index-DbWgTuT3.css +0 -1
@@ -1,8 +1,8 @@
1
- import{j as X4,k as V4}from"./chunk-9hchc346.js";import{l as nO}from"./chunk-rm9hbew3.js";import{s as JO,t as g1}from"./chunk-s77sbxr7.js";import{u as a0}from"./chunk-ahg9vjb6.js";import{A as a$,v as S1,w as l$,x as c$,y as i$,z as OO}from"./chunk-byqxaa9v.js";import{$ as e1,C as w4,F as R1,G as XO,H as A$,I as cO,J as W$,K as E0,L as F$,M as f0,N as jO,Q as kO,R as IO,T as q1,U as k1,V as I1,W as o1,X as n1,Y as t1,Z as s1,_ as r1,aa as O4,ba as $4,ca as x4,fa as G4,ia as y4,na as M4}from"./chunk-d3ttqmyt.js";import{qa as Q1,wa as U0}from"./chunk-qgrq04hb.js";import{Ba as j4,Ca as j$,Da as P1,Ea as f1,Fa as T4,Ga as C4,Ha as T$,Ia as b4,Ja as t0,Ka as K4,La as W4,Ma as F4,Na as y1,Oa as m1,Pa as h1,Qa as u$,Ra as q$,ya as x$}from"./chunk-92x15fzx.js";import{ab as m0,bb as g,db as R,eb as E1,pb as K$,yb as o0}from"./chunk-nx31fkkf.js";import{Hb as M1}from"./chunk-th4jjfgm.js";import{Ac as C1,Cc as ZO,Fc as X$,Kc as b1,Lc as V$,Mc as N$,Nc as E,_b as A1,jc as iO,pc as EO,qc as D$,rc as qO,tc as j1,zc as T1}from"./chunk-97aywyzn.js";import{Ld as x0,Pd as G1,Wd as L0}from"./chunk-1je1xw6v.js";import{Xd as G$}from"./chunk-0j22w4wh.js";import{je as L1}from"./chunk-yn51162x.js";import{le as lO}from"./chunk-fcv8b6ny.js";import{Be as wO,Ce as MO,Ge as d4,Je as T0,Ke as AO,Ne as l4,ue as D4,xe as a1}from"./chunk-axtzde5k.js";import{Ve as X1,We as w1}from"./chunk-cdy9efgm.js";import{$e as xO,_e as O1}from"./chunk-4ke8k0xw.js";import{Lf as D1,Of as H1,Qf as B1,bg as $1,gg as LO,rf as J1}from"./chunk-82htkvz8.js";import{jg as z$}from"./chunk-h0ft81a3.js";import{kg as y,mg as U,pg as F0}from"./chunk-v0rsz1rt.js";import{rg as aO}from"./chunk-xz6y0w4n.js";import{wg as c}from"./chunk-k0pa8874.js";import{Xg as a}from"./chunk-t2wgf9tq.js";import{bh as c0}from"./chunk-2px6hzdc.js";import{dh as Y1,eh as U1,gh as z1,hh as _1}from"./chunk-t8xmh4w2.js";import{jh as $O}from"./chunk-azw0jckv.js";import{qh as E$}from"./chunk-jzntxp7f.js";import{Ah as n$,wh as uO}from"./chunk-9q852bsc.js";import{Dh as C$}from"./chunk-wfy851et.js";var a5={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 o5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as k$,readFileSync as fO}from"node:fs";import{createServer as j5}from"node:http";import{networkInterfaces as T5}from"node:os";import{dirname as C5,extname as b5,join as u0}from"node:path";import{fileURLToPath as R5}from"node:url";import{brotliCompressSync as E5,gzipSync as q5,constants as k5}from"node:zlib";import{Hono as I5}from"hono";import{cors as S5}from"hono/cors";import{WebSocketServer as P5}from"ws";var e0=a("Service"),a4=30000,o4=new Set(["completed","failed","cancelled","interrupted"]);class J${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??u$.getInstance(),this.tickMs=O.tickMs??a4}start(){if(this.timer)return;e0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!o4.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,e0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){e0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),e0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??n4(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),G=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),e0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let G=Q instanceof Error?Q.message:String(Q);e0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:G,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Q=(await this.store.list()).find((G)=>G.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function n4(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Q0 extends Error{code;statusCode;details;constructor(O,$,x=500,J){super($);this.code=O;this.statusCode=x;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class f extends Q0{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class H extends Q0{constructor(O){super("BAD_REQUEST",O,400)}}class q extends Q0{constructor(O){super("CONFLICT",O,409)}}class k0 extends Q0{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class l0 extends Q0{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class B0 extends Q0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class r extends Q0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var x3=U.Object({error:U.Object({code:U.String(),message:U.String(),details:U.Optional(U.Record(U.String(),U.Unknown()))})});import{Hono as t4}from"hono";var Q$=a("Service"),s4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(F0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function r4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var p$=()=>{let O=new t4;return O.get("/",async($)=>{try{let x=x0();return $.json(x?r4(x):{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),J=y(s4,x);if(!J.success)throw new H("Invalid config update format");let{updates:Q,options:G}=J.data;return await L0().updateConfig(Q,G),$.json({success:!0,updates:Q})}catch(x){throw Q$.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=x0();return $.json(x?.permissions||{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as e4}from"hono";import{streamSSE as O2}from"hono/streaming";function d$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
1
+ import{j as V4,k as N4}from"./chunk-28wsyv32.js";import{l as nO}from"./chunk-2d2bcyn1.js";import{s as JO,t as v1}from"./chunk-xszsveq1.js";import{u as a0}from"./chunk-11gdqmbm.js";import{A as a$,v as S1,w as l$,x as c$,y as i$,z as OO}from"./chunk-5va3hhfp.js";import{$ as O4,C as M4,F as R1,G as XO,H as A$,I as cO,J as W$,K as E0,L as q1,M as F$,N as f0,O as jO,R as kO,S as IO,U as k1,V as I1,W as n1,X as t1,Y as s1,Z as r1,_ as e1,aa as $4,ba as x4,ca as J4,fa as X4,ia as m4,na as A4}from"./chunk-hryhnmwv.js";import{qa as Q1,wa as U0}from"./chunk-mp4bfn57.js";import{Aa as x$,Da as T4,Ea as j$,Fa as P1,Ga as f1,Ha as C4,Ia as b4,Ja as T$,Ka as R4,La as t0,Ma as W4,Na as F4,Oa as U4,Pa as y1,Qa as m1,Ra as h1,Sa as g1,Ta as u$,Ua as q$}from"./chunk-brm24s69.js";import{Bb as o0,db as m0,eb as v,gb as R,hb as E1,sb as K$}from"./chunk-6v7f2cv9.js";import{Mb as M1}from"./chunk-0qj8jfj1.js";import{Ec as T1,Fc as C1,Hc as ZO,Kc as X$,Pc as b1,Qc as V$,Rc as N$,Sc as E,dc as A1,oc as iO,uc as EO,vc as D$,wc as qO,yc as j1}from"./chunk-mhyat4mq.js";import{$d as L0,Qd as x0,Ud as G1}from"./chunk-a38chc6z.js";import{ae as G$}from"./chunk-q6daf441.js";import{oe as L1}from"./chunk-6j3k4v08.js";import{qe as lO}from"./chunk-06y3rada.js";import{Ce as o1,Ge as wO,He as MO,Le as l4,Oe as T0,Pe as AO,Se as c4,ze as H4}from"./chunk-hhk5ecpv.js";import{$e as w1,_e as X1}from"./chunk-2sdnmxts.js";import{df as O1,ef as xO}from"./chunk-z7vj2xrg.js";import{Qf as D1,Tf as H1,Vf as B1,gg as $1,lg as LO,wf as J1}from"./chunk-ccgq8nrm.js";import{og as z$}from"./chunk-g8425xh4.js";import{pg as f,rg as U,ug as F0}from"./chunk-m6qgme8k.js";import{wg as aO}from"./chunk-mrh3vs01.js";import{Bg as c}from"./chunk-0kat01bw.js";import{ah as a}from"./chunk-gv3ed5gw.js";import{gh as c0}from"./chunk-hwjmm2br.js";import{ih as Y1,jh as U1,lh as z1,mh as _1}from"./chunk-wvg81sd9.js";import{oh as $O}from"./chunk-y858e8pb.js";import{vh as E$}from"./chunk-eh4h7fmr.js";import{Bh as uO,Fh as n$}from"./chunk-j0yvwrd7.js";import{Ih as C$}from"./chunk-zf96d5we.js";var o5={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 n5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as k$,readFileSync as fO}from"node:fs";import{createServer as T5}from"node:http";import{networkInterfaces as C5}from"node:os";import{dirname as b5,extname as R5,join as u0}from"node:path";import{fileURLToPath as E5}from"node:url";import{brotliCompressSync as q5,gzipSync as k5,constants as I5}from"node:zlib";import{Hono as S5}from"hono";import{cors as P5}from"hono/cors";import{WebSocketServer as f5}from"ws";var e0=a("Service"),o4=30000,n4=new Set(["completed","failed","cancelled","interrupted"]);class J${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??u$.getInstance(),this.tickMs=O.tickMs??o4}start(){if(this.timer)return;e0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!n4.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,e0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){e0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),e0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??t4(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),G=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),e0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let G=Q instanceof Error?Q.message:String(Q);e0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:G,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Q=(await this.store.list()).find((G)=>G.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function t4(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Q0 extends Error{code;statusCode;details;constructor(O,$,x=500,J){super($);this.code=O;this.statusCode=x;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class y extends Q0{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class H extends Q0{constructor(O){super("BAD_REQUEST",O,400)}}class q extends Q0{constructor(O){super("CONFLICT",O,409)}}class k0 extends Q0{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class l0 extends Q0{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class B0 extends Q0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class r extends Q0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var J3=U.Object({error:U.Object({code:U.String(),message:U.String(),details:U.Optional(U.Record(U.String(),U.Unknown()))})});import{Hono as s4}from"hono";var Q$=a("Service"),r4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(F0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function e4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var p$=()=>{let O=new s4;return O.get("/",async($)=>{try{let x=x0();return $.json(x?e4(x):{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),J=f(r4,x);if(!J.success)throw new H("Invalid config update format");let{updates:Q,options:G}=J.data;return await L0().updateConfig(Q,G),$.json({success:!0,updates:Q})}catch(x){throw Q$.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=x0();return $.json(x?.permissions||{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as O2}from"hono";import{streamSSE as $2}from"hono/streaming";function d$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)$+=`event: ${O.event}
3
3
  `;for(let x of O.data.split(/\r\n|\r|\n/))$+=`data: ${x}
4
4
  `;if(O.retry!==void 0)$+=`retry: ${O.retry}
5
5
  `;return $+=`
6
- `,Buffer.byteLength($)}class HO{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??l$,this.maxPendingBytes=O.maxPendingBytes??c$,this.serial=new a$({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??i$,sizeOf:d$,write:O.write,onFailure:($)=>{this.failure=$,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,O.onFailure?.($)}})}async writeInitial(O){await this.offerDirect(O)}observe(O,$){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer(O,$);return}this.offerLive(O,$)}async writeReplay(O,$){if(!Number.isSafeInteger($)||$<=0)throw this.fail(new OO("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if($<=this.highestReplaySequence)return;await this.offerDirect(O),this.highestReplaySequence=$,this.highestDeliveredSequence=$}finishInitialization(O){if(this.phase!=="buffering")return;let $=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let x=O.replayed?$.filter((Q)=>Q.sequence!==void 0&&Q.sequence>this.highestReplaySequence).sort((Q,G)=>Q.sequence-G.sequence||Q.order-G.order):$.sort((Q,G)=>Q.order-G.order),J;for(let Q of x){if(O.replayed&&Q.sequence!==void 0&&Q.sequence===J)continue;if(this.offerLive(Q.message,Q.sequence),this.serial.stats().closed)return;J=Q.sequence}}offerHeartbeat(O){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive(O),!this.serial.stats().closed}async flush(){await this.serial.flush()}close(O){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close(O)}stats(){let O=this.serial.stats();return{closed:this.phase==="closed",pendingItems:O.pendingItems+this.buffered.length,pendingBytes:O.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer(O,$){let x=d$(O),J=this.serial.stats();if(x>this.maxPendingBytes){this.fail(new OO("oversized",`SSE frame requires ${x} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}if(J.pendingItems+this.buffered.length>=this.maxPendingItems||J.pendingBytes+this.bufferedBytes+x>this.maxPendingBytes){this.fail(new OO("overflow","SSE initialization buffer limit exceeded",{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:x,sequence:$,order:this.nextOrder}),this.bufferedBytes+=x}offerLive(O,$){if($!==void 0){if($<=this.highestReplaySequence)return;if($<=this.highestDeliveredSequence){this.fail(new OO("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=$}if(!this.serial.offer(O).accepted)this.phase="closed"}async offerDirect(O){if(this.phase==="closed")throw this.currentFailure();let $=this.serial.offer(O);if(!$.accepted)throw this.phase="closed",$.error;await $.completion}fail(O){this.serial.close(O)}currentFailure(){return this.failure??new OO("closed","SSE egress is closed")}}var $2=15000,x2=a("Service"),J2=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),Q2=new Set(["queued","running","completed","failed","cancelled","interrupted"]),Z2=new Set(["high","medium","low"]),Y2=new Set(["feature","bug","maintenance","research"]);function z2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=["changedFiles","additions","deletions","commits"];if(x.some((J)=>typeof $[J]!=="number"||!Number.isInteger($[J])||$[J]<0))return;return Object.fromEntries(x.map((J)=>[J,$[J]]))}function BO(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function G2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if(!["applied","discarded","conflicted"].includes(String($.status))||typeof $.updatedAt!=="string")return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},...BO($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}var o$=()=>{let O=new e4;return O.get("/",($)=>O2($,async(x)=>{let J,Q,G=!1,z,F,T=new Promise((W)=>{F=W}),B=()=>{if(Q!==void 0)clearInterval(Q),Q=void 0;J?.(),J=void 0},C=(W)=>{if(G)return;G=!0,B(),z?.close(W),F()};x.onAbort(C),z=new HO({write:async(W)=>{await x.writeSSE(W)},onFailure:(W)=>{x2.warn(`[EventRoutes] SSE egress closed: kind=${W.kind} pendingItems=${W.pendingItems??0} pendingBytes=${W.pendingBytes??0}`),C(W)}});let w=(W,I)=>{z?.observe({data:JSON.stringify({type:W,properties:I})})};J=R.subscribe((W)=>{if(!J2.has(W.type))return;if(W.type==="permission.asked"||W.type==="question.required"||W.type==="elicitation.required"){let i=W.properties.requestId;if(typeof i!=="string"||!i)return;w("interaction.pending",{sessionId:W.sessionId,projectPath:W.projectPath,interactionType:W.type==="question.required"?"question":W.type==="elicitation.required"?"elicitation":"permission",requestId:i});return}if(W.type==="interaction.resolved"){let i=W.properties.requestId;if(typeof i!=="string"||!i)return;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,requestId:i});return}if(W.type==="session.created"||W.type==="session.deleted"){w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath});return}if(W.type==="session.updated"){let i=W.properties.title,$0=W.properties.taskPriority,S0=W.properties.taskKind,o=W.properties.taskDueAt,p0=typeof i==="string"&&Boolean(i.trim()),w0=Z2.has(String($0)),V=Y2.has(String(S0)),V0=o===null||typeof o==="string"&&Number.isFinite(Date.parse(o));if(!p0&&!w0&&!V&&!V0)return;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,...p0?{title:i}:{},...w0?{taskPriority:$0}:{},...V?{taskKind:S0}:{},...V0?{taskDueAt:o}:{}});return}if(W.type==="task.delivery"){let i=G2(W.properties.taskDelivery);if(!i)return;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,taskDelivery:i,...W.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{}});return}if(W.type==="schedule.fired"){let i=W.properties.scheduleId,$0=W.properties.firedAt;if(typeof i!=="string"||typeof $0!=="string")return;w(W.type,{scheduleId:i,firedAt:$0,sessionId:W.sessionId,projectPath:W.projectPath,...typeof W.properties.runId==="string"?{runId:W.properties.runId}:{},...typeof W.properties.status==="string"?{status:W.properties.status}:{}});return}let I=W.properties.taskStatus;if(typeof I!=="string"||!Q2.has(I))return;let J0=z2(W.properties.taskDiffStat),p=BO(W.properties.taskQueuePosition,1),b=BO(W.properties.taskQueueDepth,0),e=BO(W.properties.taskConcurrencyLimit,1),v=BO(W.properties.taskInFlight,0),Z0=typeof W.properties.taskAdmissionPaused==="boolean"?W.properties.taskAdmissionPaused:void 0;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,taskStatus:I,...typeof W.properties.taskStatusReason==="string"?{taskStatusReason:W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{taskFailure:W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{taskStartedAt:W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{taskCompletedAt:W.properties.taskCompletedAt}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{},...J0?{taskDiffStat:J0}:{},...p!==void 0?{taskQueuePosition:p}:{},...b!==void 0?{taskQueueDepth:b}:{},...e!==void 0?{taskConcurrencyLimit:e}:{},...v!==void 0?{taskInFlight:v}:{},...Z0!==void 0?{taskAdmissionPaused:Z0}:{}})});try{if(x.aborted||G)return;if(await z.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),x.aborted||G)return;if(z.finishInitialization({replayed:!1}),x.aborted||G)return;Q=setInterval(()=>{if(x.aborted||G)return;z?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},$2),await T}finally{C()}})),O};import{Hono as X2}from"hono";var V2=U.Object({paused:U.Boolean()}),t$=()=>{let O=new X2;return O.get("/health",($)=>{return $.json({healthy:!0,version:$O()})}),O.get("/info",($)=>{let x=c(),J=x0();if(J)f0.configure(J.maxConcurrentTasks,J.maxQueuedTasks,J.maxQueuedTaskBytes);let Q=f0.getStats();return $.json({version:$O(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:x,gitBranch:n$(x),taskAdmission:{inFlight:Q.inFlight,queued:Q.queued,maxConcurrent:Q.maxConcurrent,maxQueued:Q.maxQueued,paused:Q.paused}})}),O.put("/task-admission",async($)=>{let x;try{x=await $.req.json()}catch{throw new H("Invalid request body")}let J=y(V2,x);if(!J.success)throw new H("Invalid task admission control request");f0.setPaused(J.data.paused);let Q=f0.getStats();return $.json({inFlight:Q.inFlight,queued:Q.queued,maxConcurrent:Q.maxConcurrent,maxQueued:Q.maxQueued,paused:Q.paused})}),O};import s$ from"node:path";import{Hono as N2}from"hono";var K2=U.Object({projectPath:U.String({minLength:1}),action:F0(["trust","revoke"]),expectedDigest:U.Optional(U.String())}),W2=U.Object({projectPath:U.String({minLength:1}),sessionId:U.String({minLength:1}),enabled:U.Boolean()});function Z$(O){if(!O||!s$.isAbsolute(O))throw new H("projectPath must be absolute");return s$.resolve(O)}function r$(O){if(!O)throw new H("sessionId is required");try{uO(O)}catch($){throw new H($ instanceof Error?$.message:"sessionId is invalid")}return O}async function vO(O){let $=Z$(O),x=x0()?.hooks??$1.hooks,J=await LO.getInstance().loadWorkspaceHooks($,x,{includeBaseForCurrentWorkspace:!1});return AO($,async()=>{MO($);let Q=xO.getInstance();return Q.loadConfig(J,$),await wO($),Q.getConfig($)})}function e$(O,$){let x=xO.getInstance(),J=x.getConfig($).enabled,Q=x.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:x.isSessionEnabled(O,$),paused:Q,configEnabled:J}}var x1=()=>{let O=new N2;return O.get("/trust",async($)=>{let x=$.req.query("projectPath");if(!x)throw new H("projectPath query parameter is required");return await vO(x),$.json(await xO.getInstance().getTrustStatus(x))}),O.post("/trust",async($)=>{let x=y(K2,await $.req.json());if(!x.success)throw new H("Invalid hook trust request");let{projectPath:J,action:Q,expectedDigest:G}=x.data;await vO(J);let z=xO.getInstance(),F;try{F=Q==="trust"?await z.trustProject(J,G):await z.revokeProjectTrust(J)}catch(T){if(T instanceof O1)throw new q(T.message);throw T}return $.json(F)}),O.get("/session",async($)=>{let x=Z$($.req.query("projectPath")),J=r$($.req.query("sessionId"));return await vO(x),$.json(e$(J,x))}),O.post("/session",async($)=>{let x=y(W2,await $.req.json());if(!x.success)throw new H("Invalid hook session request");let J=Z$(x.data.projectPath),Q=r$(x.data.sessionId);await vO(J);let G=xO.getInstance();if(x.data.enabled)G.enableSession(Q,J);else G.disableSession(Q,J);return $.json(e$(Q,J))}),O};import{Hono as F2}from"hono";var R0=a("Service");function U2(O){try{return Q1(O)}catch{return[]}}function _2(O){if(!pO(O)||!pO(O.reference)||!pO(O.argument))throw Error("Invalid MCP completion request");let $=O.reference.type,x=$==="prompt"&&typeof O.reference.name==="string"?{type:"prompt",name:O.reference.name}:$==="resource"&&typeof O.reference.uri==="string"?{type:"resource",uri:O.reference.uri}:void 0;if(!x||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let J;if(O.context!==void 0){if(!pO(O.context))throw Error("Invalid MCP completion context");J=Object.create(null);for(let[Q,G]of Object.entries(O.context)){if(typeof G!=="string")throw Error("Invalid MCP completion context");J[Q]=G}}return{reference:x,argument:{name:O.argument.name,value:O.argument.value},...J?{context:J}:{}}}function pO(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function y0(O,$){let x=x0()?.mcpServers??{};for(let[J,Q]of Object.entries(x)){if($&&J!==$)continue;if(!O.getServerStatus(J))await O.registerServer(J,Q,{connect:!1})}}var Z1=()=>{let O=new F2;return O.get("/",async($)=>{try{let x=U0.getInstance();await y0(x);let J=x.getAllServers(),Q=await Promise.all(Array.from(J.entries()).map(async([G,z])=>({id:G,name:G,status:z.status==="connected"?"connected":z.status==="reconnecting"?"reconnecting":z.status==="connecting"?"connecting":z.lastError?"error":"offline",endpoint:z.config.command?`${z.config.command} ${(z.config.args||[]).join(" ")}`.trim():z.config.url||"Unknown",description:`MCP server: ${G}`,tools:z.tools.map((F)=>F.name),completionSupported:z.client.completionSupported,tasks:z.client.tasks,resources:z.contentCatalog.resources,resourceTemplates:z.contentCatalog.resourceTemplates.map((F)=>({...F,variables:U2(F.uriTemplate)})),prompts:z.contentCatalog.prompts,connectedAt:z.connectedAt?.toISOString(),error:z.lastError?.message,recovery:z.recovery,logging:z.logging,instructions:z.instructions,oauthEnabled:z.client.oauthEnabled,oauthStatus:await z.client.getOAuthStatus()})));return $.json(Q)}catch(x){return R0.error("[McpRoutes] Failed to get MCP servers:",x),$.json({error:x instanceof Error?x.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();return await y0(J,x),await J.connectServer(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to connect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();return await y0(J,x),await J.disconnectServer(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to disconnect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.get("/:name/logs",async($)=>{try{let x=$.req.param("name"),J=Number($.req.query("limit")??20),Q=Number($.req.query("afterRevision")??0);if(!Number.isSafeInteger(J)||J<1||J>100||!Number.isSafeInteger(Q)||Q<0)return $.json({error:"Invalid MCP log pagination"},400);let G=U0.getInstance();return await y0(G,x),$.json(G.getLogSnapshot(x,{limit:J,afterRevision:Q}))}catch(x){return R0.error("[McpRoutes] Failed to get MCP logs:",x),$.json({error:x.message},500)}}),O.post("/:name/logging-level",async($)=>{try{let x=$.req.param("name"),J=await $.req.json();if(!J1(J.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let Q=U0.getInstance();return await y0(Q,x),await Q.setServerLoggingLevel(x,J.level),$.json({success:!0,level:J.level})}catch(x){return R0.error("[McpRoutes] Failed to set MCP logging level:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/complete",async($)=>{try{let x=$.req.param("name"),J=_2(await $.req.json()),Q=U0.getInstance();await y0(Q,x);let G=await Q.complete(x,J);return $.json(G)}catch(x){return R0.error("[McpRoutes] Failed to complete MCP argument:",x),$.json({error:x.message},400)}}),O.post("/:name/oauth/login",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();await y0(J,x);let Q=await J.beginOAuthLogin(x);return $.json({success:!0,flowId:Q.flowId,authorizationUrl:Q.authorizationUrl},202)}catch(x){return R0.error("[McpRoutes] Failed to start MCP OAuth login:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/oauth/logout",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();return await y0(J,x),await J.logoutOAuth(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to log out MCP OAuth:",x),$.json({success:!1,error:x.message},400)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name");await U0.getInstance().unregisterServer(x);let Q=x0();if(Q?.mcpServers){let{[x]:G,...z}=Q.mcpServers;await L0().updateConfig({mcpServers:z})}return $.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to delete MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/",async($)=>{try{let x=await $.req.json(),{name:J,config:Q}=x;if(!J||!Q)return $.json({success:!1,error:"Missing name or config"},400);await U0.getInstance().registerServer(J,Q);let z=x0();return await L0().updateConfig({mcpServers:{...z?.mcpServers,[J]:Q}}),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to add MCP server:",x),$.json({success:!1,error:x.message},500)}}),O};import{getSupportedThinkingLevels as D2}from"@earendil-works/pi-ai";import{Hono as H2}from"hono";var dO=a("Service");function B2(O,$,x=X1.list()){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,supportedReasoningEfforts:D2($),supportedServiceTiers:z1($),supportedResponseVerbosities:Y1($),communicationStyles:x,input:$.input}}function L2(O){V1(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function V1(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new H("streamIdleTimeout must be at least 1000ms")}var N1=()=>{let O=new H2;return O.get("/",async($)=>{try{let x=x0();if(!x)throw Error("Config not initialized");let J=$.get("directory")||c(),[Q,G]=await Promise.all([lO(J,x),T0(J)]),z=Q.config.models,F=z.find((w)=>w.id===Q.config.currentModelId)??z[0],T=Q.catalog,B=G.communicationStyles.list(),C=(w)=>B2(w,T.resolveConfig(w),B);return $.json({configured:z.map(C),current:F?C(F):null})}catch(x){dO.error("[ModelsRoutes] Failed to get models:",x);let J=new r("Failed to get models");return $.json(J.toObject(),500)}}),O.post("/",async($)=>{let x=c0(),J,Q;try{let G=await $.req.json(),{provider:z,displayName:F,model:T,overrides:B,apiKey:C,modelProvider:w}=G;if(!z||!T)throw new H("provider and model are required");V1(B);let W;if(w){if(w.id!==z)throw new H("modelProvider.id must match the model provider");if(x0()?.modelProviders[z])throw new H(`model provider already exists: ${z}`);W={name:w.name,baseUrl:w.baseUrl,wireApi:w.wireApi,...w.apiKeyEnv?{apiKeyEnv:w.apiKeyEnv}:{}};try{x.registerModelProvider(z,W,[T]),Q=z}catch(p){throw new H(p instanceof Error?p.message:"Invalid model provider")}}else x.getModel(z,T);if(C?.trim()){if(await x.setApiKey(z,C.trim()),W)J=z}let I={provider:z,displayName:F||void 0,model:T,overrides:B||void 0},J0=W?await L0().addModelWithProvider(I,W):await L0().addModel(I);return $.json({success:!0,model:J0})}catch(G){if(J)await x.credentials.delete(J);if(Q){let z=x0();x.configureModelProviders(z?.modelProviders??{},z?.models??[])}throw dO.error("[ModelsRoutes] Failed to add model:",G),G}}),O.put("/:modelId",async($)=>{try{let x=$.req.param("modelId"),J=await $.req.json(),{displayName:Q,overrides:G,model:z}=J,F=G1(x);if(!F)throw new H("model config not found");if(z)c0().getModel(F.provider,z);return await L0().updateModel(x,L2({displayName:Q,overrides:G,model:z})),$.json({success:!0})}catch(x){throw dO.error("[ModelsRoutes] Failed to update model:",x),x}}),O.delete("/:modelId",async($)=>{try{let x=$.req.param("modelId");return await L0().removeModel(x),$.json({success:!0})}catch(x){throw dO.error("[ModelsRoutes] Failed to delete model:",x),x}}),O};import{Hono as h2}from"hono";import K1 from"node:path";import{Hono as w2}from"hono";import{streamSSE as M2}from"hono/streaming";import{LRUCache as A2}from"lru-cache";import{nanoid as QO}from"nanoid";var m=a("Service"),j2=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),T2=y1,C2=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),b2=U.Object({projectPath:U.String()}),R2=U.Object({objective:U.String({minLength:1}),tokenBudget:U.Optional(U.Integer({minimum:1})),permissionMode:U.Optional(F0(["default","autoEdit","plan","yolo"]))}),E2=U.Union([U.Object({action:U.Literal("pause")}),U.Object({action:U.Literal("resume")}),U.Object({action:U.Literal("edit"),objective:U.String({minLength:1})})]),t=new Map,YO,b0=new Map,I0=new Map,C0=new Map,oO=new A2({max:100,ttl:1800000});function W1(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function D0(O){if(!O)return;return b0.get(O)??oO.get(O)}function q2(O){if(b0.get(O.id)!==O)return;b0.delete(O.id),oO.set(O.id,O)}function k2(O){b0.delete(O),oO.delete(O)}function _0(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function bO(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let x=O.pendingPermission;if(O.pendingPermission=void 0,x?.resolve({approved:!1,reason:M1}),x)R.publish(W1(O),"interaction.resolved",{requestId:x.permissionId});return O.abortController.abort($),O.status="cancelled",R.publish(W1(O),"run.cancelled",{runId:O.id}),!0}function v1(O,$=!1){let{permissionId:x,details:J}=O;if(J.type==="askUserQuestion"&&J.questions)return{type:"question.required",properties:{requestId:x,toolCallId:J.toolCallId??x,questions:J.questions,details:J,...$?{replayed:!0}:{}}};if(J.type==="mcpElicitation"&&J.mcpElicitation)return{type:"elicitation.required",properties:{requestId:x,toolCallId:J.toolCallId??x,elicitation:J.mcpElicitation,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:J.toolName,description:J.message,args:J.args,details:J,...$?{replayed:!0}:{}}}}function I2(O){return{...typeof O.seq==="number"?{id:String(O.seq)}:{},data:JSON.stringify({type:O.type,...typeof O.seq==="number"?{seq:O.seq}:{},properties:{...O.properties,sessionId:O.sessionId,projectPath:O.projectPath}})}}function S2(){for(let O of b0.values())bO(O,"route-reset");b0.clear();for(let O of I0.values())O.controller.abort("route-reset");I0.clear(),oO.clear(),YO=void 0,t.clear()}function P2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=$.code,J=$.reason,Q=$.scope,G=$.kind,z=$.limit;if(x!=="tool_busy"&&x!=="tool_batch_full"||J!=="queue_full"&&J!=="wait_timeout"&&J!=="turn_limit"||Q!=="global"&&Q!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(z)||z<=0||G!==void 0&&G!=="readonly"&&G!=="write"&&G!=="execute")return;return{code:x,reason:J,scope:Q,retryable:$.retryable,...G===void 0?{}:{kind:G},limit:z}}var RO=(O,$)=>{if(!$||typeof $!=="object")return $;let x={...$},J=P2(x.tool_admission);if(J)x.tool_admission=J;else delete x.tool_admission;if(O==="Bash"){let z={},F=["message","signal","status","summary"],T=["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 w of F){let W=x[w];if(typeof W==="string")z[w]=W.slice(0,8192)}for(let w of T){let W=x[w];if(typeof W==="boolean")z[w]=W}for(let w of B){let W=x[w];if(typeof W==="number"&&Number.isSafeInteger(W)&&W>=0)z[w]=W}if(x.exit_code===null||typeof x.exit_code==="number"&&Number.isSafeInteger(x.exit_code))z.exit_code=x.exit_code;if(x.terminal_transport==="local"||x.terminal_transport==="acp"||x.terminal_transport==="local_fallback")z.terminal_transport=x.terminal_transport;if(x.background_reason==="explicit"||x.background_reason==="foreground_budget")z.background_reason=x.background_reason;for(let w of["bash_id","shell_id"]){let W=x[w];if(typeof W==="string"&&W.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(W))z[w]=W}if(J)z.tool_admission=J;let C=x.background_shell_admission;if(C&&typeof C==="object"&&!Array.isArray(C)){let w=C;if(w.code==="background_shell_busy"&&(w.scope==="session"||w.scope==="global")&&w.retryable===!0&&Number.isSafeInteger(w.limit)&&w.limit>0)z.background_shell_admission={code:w.code,scope:w.scope,retryable:w.retryable,limit:w.limit}}return z}let Q=200000,G=(z,F)=>typeof z==="number"&&Number.isSafeInteger(z)&&z>=0&&z<=F?z:0;if(typeof x.oldContent==="string"&&x.oldContent.length>Q)delete x.oldContent;if(typeof x.newContent==="string"&&x.newContent.length>Q)delete x.newContent;if(x.mcpResult&&typeof x.mcpResult==="object"&&!Array.isArray(x.mcpResult)){let z=x.mcpResult,F=Array.isArray(z.artifacts)?z.artifacts.slice(0,64).flatMap((T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return[];let B=T,C=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"||!C.has(B.kind)||G(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)}:{}}]}):[];x.mcpResult={isError:z.isError===!0,contentCount:G(z.contentCount,64),textBytes:G(z.textBytes,4194304),structuredBytes:G(z.structuredBytes,4194304),artifactCount:G(z.artifactCount,64),truncated:z.truncated===!0,binaryOmitted:z.binaryOmitted===!0,artifacts:F}}else delete x.mcpResult;return x};function f2(O){let $=typeof O.seq==="number"?{seq:O.seq}:{};if(O.type==="part_created"&&O.data.partType==="tool_call"){let x=O.data.payload;return{type:"tool.start",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let x=O.data.payload,J=x.toolName??"unknown",Q=D$(x),G=qO(kO(J,Q),EO);return{type:"tool.result",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:J,success:Q.success,status:Q.success?"completed":"failed",summary:Q.metadata?.summary,output:IO(G),metadata:RO(J,Q.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function y2(O,$,x){switch(x.kind){case"tool_start":if("function"in x.toolCall)R.publish(O,"subagent.update",{subagentSessionId:$,toolName:x.toolCall.function.name}),R.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,arguments:x.toolCall.function.arguments,toolKind:x.toolKind});break;case"tool_result":if("function"in x.toolCall)R.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,success:x.result.success,summary:x.result.metadata?.summary,output:IO(qO(kO(x.toolCall.function.name,x.result),EO)),metadata:RO(x.toolCall.function.name,x.result.metadata)});break;case"tool_progress":if("function"in x.toolCall)R.publish(O,"subagent.tool.progress",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,...x.update});break;case"content_delta":R.publish(O,"subagent.delta",{subagentSessionId:$,delta:x.delta});break;case"thinking_delta":R.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:x.delta});break;case"stream_end":R.publish(O,"subagent.stream.end",{subagentSessionId:$});break;case"provider_admission":R.publish(O,"subagent.provider.admission",{subagentSessionId:$,phase:x.phase,requestClass:x.requestClass,resource:x.resource,scope:x.scope,reason:x.reason,queuePosition:x.queuePosition,queueDepth:x.queueDepth,inFlight:x.inFlight,limit:x.limit,waitMs:x.waitMs,maxWaitMs:x.maxWaitMs,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_circuit":R.publish(O,"subagent.provider.circuit",{subagentSessionId:$,phase:x.phase,reason:x.reason,statusCode:x.statusCode,retryAfterMs:x.retryAfterMs,nextProbeAt:x.nextProbeAt,openDurationMs:x.openDurationMs,sampleCount:x.sampleCount,failureCount:x.failureCount,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_retry":R.publish(O,"subagent.provider.retry",{subagentSessionId:$,phase:x.phase,attempt:x.attempt,maxRetries:x.maxRetries,reason:x.reason,statusCode:x.statusCode,delayMs:x.delayMs,nextRetryAt:x.nextRetryAt,mode:x.mode,recoveryBudgetMs:x.recoveryBudgetMs,recoveryElapsedMs:x.recoveryElapsedMs,recoveryRemainingMs:x.recoveryRemainingMs,exhaustedBy:x.exhaustedBy});break;case"provider_stall":R.publish(O,"subagent.provider.stall",{subagentSessionId:$,phase:x.phase,stallCount:x.stallCount,durationMs:x.durationMs,warningAfterMs:x.warningAfterMs,timeoutMs:x.timeoutMs,outputStarted:x.outputStarted});break;case"action_stationarity":R.publish(O,"subagent.action.stationarity",{subagentSessionId:$,phase:x.phase,toolName:x.toolName,runLength:x.runLength,nudgeThreshold:x.nudgeThreshold,haltThreshold:x.haltThreshold,progressAware:x.progressAware});break;case"mcp_catalog_changed":R.publish(O,"subagent.mcp.catalog.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_content_changed":R.publish(O,"subagent.mcp.content.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,contentKind:x.contentKind,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_resource_updated":R.publish(O,"subagent.mcp.resource.updated",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,uri:x.uri});break;case"mcp_connection_changed":R.publish(O,"subagent.mcp.connection.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,phase:x.phase,reason:x.reason,attempt:x.attempt,maxAttempts:x.maxAttempts,nextRetryAt:x.nextRetryAt,error:x.error});break;case"mcp_log":R.publish(O,"subagent.mcp.log",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,level:x.level,logger:x.logger,message:x.message,projectedBytes:x.projectedBytes,dataSha256:x.dataSha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted,timestamp:x.timestamp,synthetic:x.synthetic});break;case"mcp_instructions_changed":R.publish(O,"subagent.mcp.instructions.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,action:x.action,reason:x.reason,text:x.text,sourceBytes:x.sourceBytes,projectedBytes:x.projectedBytes,sha256:x.sha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted});break;case"mcp_task_changed":R.publish(O,"subagent.mcp.task.changed",{subagentSessionId:$,revision:x.revision,taskId:x.taskId,serverName:x.serverName,toolName:x.toolName,status:x.status,statusMessage:x.statusMessage,createdAt:x.createdAt,updatedAt:x.updatedAt,completedAt:x.completedAt,hasResult:x.hasResult,error:x.error});break;case"project_rules_loaded":R.publish(O,"subagent.project.rules.loaded",{subagentSessionId:$,files:x.files,triggerPaths:x.triggerPaths,blockedWrite:x.blockedWrite});break;default:break}}function TO(O,$="projectPath"){if(!K1.isAbsolute(O))throw new H(`${$} must be absolute`);return K1.resolve(O)}function U$(O){try{uO(O)}catch($){throw new H($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function z0(O){return{sessionId:O.id,projectPath:O.projectPath}}function CO(O,$,x){return{id:O.sessionId,projectPath:O.projectPath,title:O.title??`Session ${O.sessionId.slice(0,6)}`,createdAt:new Date(O.firstMessageTime),updatedAt:new Date(O.lastMessageTime),rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,taskStatus:O.taskStatus,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,pendingInteraction:O.pendingInteraction,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:O.taskQueuePosition,taskQueueDepth:O.taskQueueDepth,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,taskWorktree:x,messages:$}}function Y$(O){return O.flatMap(($)=>{if(!j1($)||$.role==="system"||$.role==="tool"&&$.name===ZO)return[];let x=$.tool_calls?.filter((z)=>!("function"in z)||z.function.name!==ZO),J=typeof $.content==="string"?$.content.trim():"";if($.role==="assistant"&&$.tool_calls?.length&&!x?.length&&!J&&!$.reasoningContent&&!$.metadata)return[];let Q={...$,...$.tool_calls?{tool_calls:x&&x.length>0?x:void 0}:{}};if($.role==="tool"){let z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0,F=$.name??(typeof z?.toolName==="string"?z.toolName:"unknown");if(z!==void 0&&(Object.hasOwn(z,"output")||Object.hasOwn(z,"error"))){let B=D$(z),C=qO(kO(F,B),EO);return[{...Q,name:F,content:IO(C),metadata:RO(F,{...B.metadata,status:B.success?"completed":"failed"})}]}return[{...Q,name:F,metadata:RO(F,z)}]}let G=C1($.metadata);return[G?{...Q,content:T1(G)}:Q]})}function zO(O,$){O.title=$.title??O.title,O.taskStatus=$.taskStatus,O.taskStatusReason=$.taskStatusReason,O.taskFailure=$.taskFailure,O.taskStartedAt=$.taskStartedAt,O.taskCompletedAt=$.taskCompletedAt,O.taskPromptSummary=$.taskPromptSummary,O.taskPriority=$.taskPriority,O.taskKind=$.taskKind,O.taskDueAt=$.taskDueAt,O.taskModelId=$.taskModelId,O.selectedModelId=$.selectedModelId,O.permissionMode=$.permissionMode,O.reasoningEffort=$.reasoningEffort,O.serviceTier=$.serviceTier,O.responseVerbosity=$.responseVerbosity,O.communicationStyle=$.communicationStyle,O.communicationStyleDigest=$.communicationStyleDigest,O.projectInstructionsDigest=$.projectInstructionsDigest,O.pendingInteraction=$.pendingInteraction,O.taskRetryAvailable=$.taskRetryAvailable,O.taskRetriedFrom=$.taskRetriedFrom,O.taskDelivery=$.taskDelivery,O.taskIsolation=$.taskIsolation,O.taskSourceProjectPath=$.taskSourceProjectPath,O.taskWorktreePath=$.taskWorktreePath,O.taskWorktreeBranch=$.taskWorktreeBranch,O.taskBaseCommit=$.taskBaseCommit,O.taskDiffStat=$.taskDiffStat,O.taskQueuePosition=$.taskQueuePosition,O.taskQueueDepth=$.taskQueueDepth,O.taskConcurrencyLimit=$.taskConcurrencyLimit,O.archivedAt=$.archivedAt,O.archivedBySessionId=$.archivedBySessionId,O.updatedAt=new Date($.lastMessageTime)}async function n0(O){let $=await E.findSessionMetadata(O.id,O.projectPath);if($)zO(O,$)}function i0(O){let $=D0(O.currentRunId),x=$?.status==="waiting_permission"?"running":$?.status??O.taskStatus;return{sessionId:O.id,projectPath:O.projectPath,title:O.title,rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,status:void 0,taskStatus:x,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:x==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:x==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:$?.pendingPermission?{type:$.pendingPermission.details.type==="askUserQuestion"?"question":$.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:$.pendingPermission.permissionId}:O.pendingInteraction,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function N0(O,$){if(U$(O),$!==void 0){let J=m0({sessionId:O,projectPath:TO($)});if(t.has(g(J)))return J;let Q=await E.findSessionMetadata(J.sessionId,J.projectPath);if(!Q)throw new f("Session",O);return m0({sessionId:Q.sessionId,projectPath:Q.projectPath})}let x=new Map;for(let J of t.values()){if(J.id!==O)continue;let Q=z0(J);x.set(g(Q),Q)}for(let J of await E.listSessions()){if(J.sessionId!==O)continue;let Q=m0({sessionId:J.sessionId,projectPath:J.projectPath});x.set(g(Q),Q)}if(x.size===0)try{let J=await E.findSessionMetadata(O);if(!J)throw new f("Session",O);return m0({sessionId:J.sessionId,projectPath:J.projectPath})}catch(J){if(J instanceof f)throw J;if(J instanceof Error&&J.message.startsWith("Ambiguous session ID:"))throw new B0;throw J}if(x.size>1)throw new B0;return x.values().next().value}function _$(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
7
- `)}function F1(O,$){let x=($??[]).filter((Q)=>Q.type==="image"&&typeof Q.content==="string").map((Q)=>({type:"image_url",image_url:{url:Q.content}}));if(x.length===0)return O;let J=[];if(O.trim())J.push({type:"text",text:O});return J.push(...x),J}var u1=()=>{S2();let O=new w2;O.onError((Z,N)=>{if(Z instanceof JO){let Y=new k0("Session runtime capacity is full",{resource:Z.resource,limit:Z.limit});return N.json(Y.toObject(),429)}if(Z instanceof Q0)return N.json(Z.toObject(),Z.statusCode);return m.error("[SessionRoutes] Unhandled route error:",Z),N.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,x=new Map,J=new Map,Q=new Map,G=new z$,z=new z$,F=x0(),T=new g1({maxResident:F?.maxResidentSessionRuntimes??D1,idleMs:F?.sessionRuntimeIdleMs??H1}),B=new q1,C=setInterval(()=>{T.sweepIdle().catch((Z)=>{m.warn("[SessionRoutes] Session Runtime idle sweep failed:",Z)})},B1);C.unref?.();let w,W=async(Z)=>{let N;try{N=B.enter()}catch{throw new l0}try{return await Z()}finally{N.release()}};O.use("*",async(Z,N)=>{if(Z.req.method==="GET"||Z.req.method==="HEAD")return N();return W(N)});let I=(Z,N)=>G.runExclusive(g(Z),N),J0=(Z,N)=>z.runExclusive(g(Z),N),p=(Z)=>[...b0.values()].some((N)=>N.sessionId===Z.sessionId&&N.projectPath===Z.projectPath&&_0(N)),b=async(Z,N,Y)=>{let X=J.get(N);if(!X)X=(async()=>{if($.get(N)===Y)$.delete(N);for(let[D,_]of $)if(_===Y)$.delete(D);let K=z0(Z);if(t.get(N)===Z&&!p(K)&&!I0.has(N)&&!C0.has(N))t.delete(N);if(await Y.dispose(),$.size===0)await U0.getInstance().disconnectAll()})().finally(()=>{if(J.get(N)===X)J.delete(N)}),J.set(N,X);await X},e=async(Z,N={})=>{let Y=z0(Z),X=g(Y);await J.get(X);let K=T.acquire(X);if(K){if($.get(X)!==K.value)throw K.release(),Error("Session Runtime residency identity is inconsistent");return K}if(T.owns(X))throw new JO(T.getStats().maxResident);let D=x.get(X);if(!D){let _=N.communicationStyle??Z.communicationStyle;D=(async()=>{let L=await T.reserve(X,{surface:"web",allowEviction:!0});try{let M=await jO.create({sessionId:Z.id,workspaceRoot:Z.projectPath,...Z.selectedModelId??Z.taskModelId?{modelId:Z.selectedModelId??Z.taskModelId}:{},permissionMode:N.permissionMode??Z.permissionMode??"default",...Z.reasoningEffort?{reasoningEffort:Z.reasoningEffort}:{},...Z.serviceTier?{serviceTier:Z.serviceTier}:{},...Z.responseVerbosity?{responseVerbosity:Z.responseVerbosity}:{},..._?{communicationStyle:_}:{},..._===Z.communicationStyle&&Z.communicationStyleDigest?{communicationStyleDigest:Z.communicationStyleDigest}:{},...Z.projectInstructionsDigest?{projectInstructionsDigest:Z.projectInstructionsDigest}:{},...Z.taskWorktree?{taskWorktree:Z.taskWorktree}:{},...Z.taskIsolation?{taskIsolation:Z.taskIsolation}:{},...Z.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:Z.id}}:{}}),A=L.commit({key:X,surface:"web",value:M,canEvict:()=>!p(Y)&&!I0.has(X)&&!C0.has(X)&&!x.has(X)&&!J.has(X)&&M.isIdleForResidency(),dispose:()=>b(Z,X,M)});return $.set(X,M),{runtime:M,claimLease:()=>{if(A){let k=A;return A=void 0,k}let j=T.acquire(X);if(!j||j.value!==M)throw Error("Initialized Session Runtime lost residency");return j}}}catch(M){throw L.cancel(),M}})(),x.set(X,D)}try{return(await D).claimLease()}finally{if(x.get(X)===D)x.delete(X)}},v=async(Z,N,Y={})=>{let X=await e(Z,Y);try{return await N(X.value)}finally{X.release()}},Z0=async(Z,N)=>{let Y=g(z0(Z)),X=x.get(Y);if(X)await X.catch(()=>{return});x.delete(Y);let K=N??$.get(Y);if(!K)return;if(!await T.remove(Y,K))throw Error(`Session Runtime is pinned and cannot be disposed: ${Y}`)},i=async(Z)=>{let N=g(Z),Y=t.get(N);if(Y)return Y;let X=Q.get(N);if(!X)X=(async()=>{let K=await E.findSessionMetadata(Z.sessionId,Z.projectPath);if(!K)throw new f("Session",Z.sessionId);let[D,_]=await Promise.all([E.loadSession(Z.sessionId,Z.projectPath),E.findSessionTaskWorktree(Z.sessionId,Z.projectPath)]),L=CO(K,D,_);return t.set(N,L),L})(),Q.set(N,X);try{return await X}finally{if(Q.get(N)===X)Q.delete(N)}},$0=async(Z,N)=>{let Y=await N0(Z,N);try{await E.assertSessionWritable(Y.sessionId,Y.projectPath)}catch(X){if(X instanceof V$)throw new q(X.message);throw X}return i(Y)},S0=async(Z,N)=>{if(Z.permissionMode===N)return;let Y=await E.setSessionPermissionMode(Z.id,Z.projectPath,N);Z.permissionMode=Y.permissionMode,Z.updatedAt=new Date(Y.lastMessageTime),R.publish(z0(Z),"session.updated",{permissionMode:N})},o=(Z,N,Y,X={})=>{if(!B.stats().accepting)throw new l0;let K=QO(12),D={id:K,sessionId:Z.id,projectPath:Z.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:Z.taskIsolation!==void 0&&X.runtimeLease!==void 0,createdAt:new Date};if(Z.taskIsolation&&X.runtimeLease){let _=X.runtimeLease.value,L=f0.admit({key:`${Z.projectPath}\x00${Z.id}`,..._.getTaskAdmissionLimits(),pendingBytes:k1({content:N,outputSchema:X.outputSchema,pendingMessages:_.getPendingSteeringMessages()}),signal:D.abortController.signal,onUpdate:(A)=>{D.status=A.state,Z.taskStatus=A.state,Z.taskQueuePosition=A.queuePosition,Z.taskQueueDepth=A.queueDepth,Z.taskConcurrencyLimit=A.maxConcurrent,D.taskAdmissionUpdate=(D.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await _.setTaskAdmission(A)}).catch((j)=>{m.warn(`[SessionRoutes] Failed to persist admission for ${Z.id}:`,j)})}});D.taskAdmission=L;let M=L.getSnapshot();D.status=M.state,Z.taskStatus=M.state,Z.taskQueuePosition=M.queuePosition,Z.taskQueueDepth=M.queueDepth,Z.taskConcurrencyLimit=M.maxConcurrent}return b0.set(K,D),Z.currentRunId=K,D.completion=m2(D,Z,N,Y,e,{pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:D.taskAdmission,runtimeLease:X.runtimeLease,disposeRuntime:Z0}).catch((_)=>{m.error(`[SessionRoutes] Run ${K} failed:`,_)}),D},p0=async(Z)=>{let N;if(Z.outputSchema)try{N=X$(Z.outputSchema).schema}catch(u){throw new H(u instanceof Error?u.message:"Invalid output schema")}let Y=G$("task",12),X=TO(Z.sourceProjectPath),K=Z.modelId?.trim(),D=x0();if(!D)throw new H("Config not initialized");let[_,L]=await Promise.all([lO(X,D),T0(X)]);if(K&&!_.config.models.some((u)=>u.id===K))throw new H(`Task model not found: ${K}`);let M=K||_.config.models.find((u)=>u.id===_.config.currentModelId)?.id||_.config.models[0]?.id;if(!M)throw new H("No model is configured. Add or select a model before dispatching a task.");let A=_.config.models.find((u)=>u.id===M);if(!A)throw new H(`Task model not found: ${M}`);let j=Z.reasoningEffort??"off",k=Z.serviceTier??"auto",K0=Z.responseVerbosity??"auto",P0=Z.communicationStyle??"auto",j0,G0=L.projectRules?.staticRules(X),O0=G0&&G0.files.length>0?G0.provenanceSha256:void 0;try{let u=_.catalog.resolveConfig(A);L1(u,j),_1(u,k),U1(u,K0);let l=w1(P0,L.communicationStyles);j0=l.source==="built-in"?void 0:l.contentSha256}catch(u){throw new H(u instanceof Error?u.message:"Invalid reasoning effort")}let r0={version:1,prompt:Z.prompt,...Z.title?{title:Z.title}:{},...Z.taskPriority?{taskPriority:Z.taskPriority}:{},...Z.taskKind?{taskKind:Z.taskKind}:{},...Z.taskDueAt?{taskDueAt:Z.taskDueAt}:{},sourceProjectPath:X,isolation:Z.isolation,permissionMode:Z.permissionMode,modelId:M,reasoningEffort:j,serviceTier:k,responseVerbosity:K0,communicationStyle:P0,...j0?{communicationStyleDigest:j0}:{},...O0?{projectInstructionsDigest:O0}:{},...Z.attachments?{attachments:Z.attachments.map((u)=>({...u}))}:{},...N?{outputSchema:N}:{}},h,P,S;try{let u=await S1.createSessionTask({sessionId:Y,prompt:Z.prompt,title:Z.title,taskPriority:Z.taskPriority,taskKind:Z.taskKind,taskDueAt:Z.taskDueAt,sourceProjectPath:X,isolation:Z.isolation,dispatch:r0,retriedFrom:Z.retriedFrom}),{metadata:l}=u;h=u.taskWorktree,P=CO(l,[],h);let d=z0(P);t.set(g(d),P),R.publish(d,"task.status",{taskStatus:l.taskStatus,updatedAt:l.lastMessageTime});let s=F1(Z.prompt,Z.attachments);S=await e(P);let UO=S.value,n=N?await UO.prepareInputTurn(s,{outputSchema:N}):await UO.prepareInputTurn(s);if(!n.accepted)throw new q(`Task prompt was not accepted: ${n.reason}`);let Y0=o(P,s,Z.permissionMode,{preparedInputTurn:n,runtimeLease:S,outputSchema:N});return S=void 0,await Y0.taskAdmissionUpdate,{session:i0(P),runId:Y0.id,messageId:n.messageId,status:Y0.status==="queued"?"queued":"running",queuePosition:P.taskQueuePosition,queueDepth:P.taskQueueDepth,maxConcurrentTasks:P.taskConcurrencyLimit}}catch(u){if(S?.release(),S=void 0,(u instanceof F$||u instanceof JO)&&P){let l=z0(P),d=g(l);if(h)await E0.exit({sessionId:P.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await Z0(P).catch(()=>{return}),await E.deleteSession(P.id,P.projectPath).catch(()=>{return}),t.delete(d),new k0(u instanceof JO?"Session runtime capacity is full":"Task admission capacity is full",{resource:u.resource,limit:u.limit})}if(P){let l=await E.findSessionMetadata(P.id,P.projectPath).catch(()=>{return});if(!l||l.taskStatus==="queued"){let d=iO(u),s=await E.updateSessionMetadata(P.id,P.projectPath,{taskStatus:"failed",taskStatusReason:d.message,taskFailure:d,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});P.taskStatus=s?.taskStatus??"failed",P.taskStatusReason=s?.taskStatusReason??d.message,P.taskFailure=s?.taskFailure??d,P.taskCompletedAt=s?.taskCompletedAt}else P.taskStatus=l.taskStatus,P.taskStatusReason=l.taskStatusReason,P.taskFailure=l.taskFailure,P.taskCompletedAt=l.taskCompletedAt}throw u}},w0=(Z)=>W(()=>p0(Z)),V=async(Z,N)=>{let Y=await N0(Z,N),X=await E.findSessionMetadata(Y.sessionId,Y.projectPath);if(!X)throw new f("Session",Y.sessionId);if(!["failed","interrupted","cancelled"].includes(X.taskStatus))throw new q(`Task cannot be retried while status is ${X.taskStatus}`);let K=await E.findSessionTaskDispatch(Y.sessionId,Y.projectPath);if(!K)throw new q("Task retry payload is unavailable");return w0({prompt:K.prompt,title:X.title??K.title,taskPriority:X.taskPriority??K.taskPriority,taskKind:X.taskKind??K.taskKind,taskDueAt:X.taskDueAt,sourceProjectPath:K.sourceProjectPath,isolation:K.isolation,permissionMode:K.permissionMode,modelId:K.modelId,reasoningEffort:K.reasoningEffort,serviceTier:K.serviceTier,responseVerbosity:K.responseVerbosity,communicationStyle:K.communicationStyle,attachments:K.attachments,outputSchema:K.outputSchema,retriedFrom:Y})},V0=(Z,N)=>W(()=>V(Z,N)),S$=(Z,N,Y)=>W(async()=>{let X=await N0(Z,Y);if(!await E.findSessionMetadata(X.sessionId,X.projectPath))throw new f("Session",X.sessionId);let D=await E.updateSessionMetadata(X.sessionId,X.projectPath,N),_=t.get(g(X));if(_)zO(_,D);return R.publish(X,"session.updated",{...D.title?{title:D.title}:{},...D.taskPriority?{taskPriority:D.taskPriority}:{},...D.taskKind?{taskKind:D.taskKind}:{},taskDueAt:D.taskDueAt??null}),_?i0(_):{...D,isActive:!1}}),rO=async(Z,N)=>{let Y=await $0(Z,N);if(!Y.taskWorktree)throw new H("Session does not have a task worktree");try{await E0.restoreSession(Y.taskWorktree);let X=await E0.getDiffArtifact(Y.id);if(!X)throw new q("Task diff artifact is unavailable");return{sessionId:Y.id,projectPath:Y.projectPath,...X}}catch(X){if(X instanceof q)throw X;throw m.error("[SessionRoutes] Failed to load task diff artifact:",X),new q("Task diff artifact is unavailable")}},FO=async(Z,N,Y)=>{let X=await N0(Z,Y);return J0(X,async()=>{let K=await $0(X.sessionId,X.projectPath);if(["queued","running"].includes(K.taskStatus))throw new q(`Task artifacts cannot be delivered while status is ${K.taskStatus}`);if(K.taskDelivery?.status==="applied")throw new q("Task changes have already been applied");if(K.taskDelivery?.status==="discarded")throw new q("Task changes have already been discarded");if(!K.taskWorktree)throw new q("Task worktree is unavailable");let D=async(_,L=!1)=>{let M=await E.updateSessionMetadata(K.id,K.projectPath,{taskDelivery:_,...L?{taskWorktree:null}:{}});if(zO(K,M),L)K.taskWorktree=void 0;return R.publish(X,"task.delivery",{taskDelivery:_,...L?{taskWorktreeRemoved:!0}:{},updatedAt:M.lastMessageTime}),i0(K)};try{if(N==="discard"){try{await E0.restoreSession(K.taskWorktree)}catch(M){return m.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${K.id}:`,M),D({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:K.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let L=await E0.exit({sessionId:K.id,action:"remove",discardChanges:!0});return D({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:L.discardedFiles??0,message:"Task worktree removed"},!0)}try{await E0.restoreSession(K.taskWorktree)}catch(L){throw m.warn(`[SessionRoutes] Task worktree is unavailable for ${K.id}:`,L),new W$("artifact_unavailable","Task worktree is unavailable")}let _=await E0.apply(K.id);return D({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:_.sourceCommit,changedFiles:_.changedFiles,message:"Task changes applied to the source workspace"})}catch(_){if(_ instanceof W$)throw await D({status:"conflicted",updatedAt:new Date().toISOString(),message:_.message}),new q(_.message);throw _}})},yO=(Z,N,Y)=>W(()=>FO(Z,N,Y)),mO=async(Z)=>{let N=D0(Z.currentRunId);if(_0(N))return;if(Z.taskIsolation&&Z.taskStatus!=="queued"&&Z.taskStatus!=="running")return;let Y=await jO.hasPendingInbox(Z.projectPath,Z.id),X=!Y&&await jO.hasActiveGoal(Z.projectPath,Z.id);if(!Y&&!X)return;let K=await e(Z),D=!1;try{let _=K.value,L=D0(Z.currentRunId);if(_0(L))return;if(Y&&_.getPendingSteeringCount()===0)await _.reloadPendingInbox();let M=_.getPendingSteeringCount()>0,A=M?null:await _.getGoal(),j=A?.status==="active"||A?.status==="verifying";if(!M&&!j||_.hasTurnOwner())return;o(Z,"",Z.permissionMode??"default",{pendingInputOnly:M,goalContinuationOnly:j,runtimeLease:K}),D=!0}finally{if(!D)K.release()}},q0=async(Z)=>{let N;try{N=B.enter()}catch{return}try{await mO(Z)}finally{N.release()}};YO=q0;let eO=async()=>{let Z={scheduled:0,failed:0,deferred:0};if(!B.stats().accepting)return Z;let N=(await E.listSessions({taskStatus:"queued"})).filter((Y)=>Y.taskIsolation!==void 0).sort((Y,X)=>Y.firstMessageTime.localeCompare(X.firstMessageTime)||Y.projectPath.localeCompare(X.projectPath)||Y.sessionId.localeCompare(X.sessionId));for(let[Y,X]of N.entries()){let K={sessionId:X.sessionId,projectPath:X.projectPath};try{if(!await jO.hasPendingInbox(X.projectPath,X.sessionId)){let _=iO("Queued task input is missing");await E.updateSessionMetadata(X.sessionId,X.projectPath,{taskStatus:"failed",taskStatusReason:_.message,taskFailure:_,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Z.failed++;continue}let D=await i(K);if(await q0(D),D.currentRunId)Z.scheduled++}catch(D){if(D instanceof F$||D instanceof JO){Z.deferred+=N.length-Y;break}m.warn(`[SessionRoutes] Failed to recover queued task ${X.sessionId}:`,D),Z.deferred++}}return Z};return O.get("/",async(Z)=>{try{let N=await E.listSessions(),Y=new Set(N.filter((A)=>A.relationType==="subagent").map((A)=>g({sessionId:A.sessionId,projectPath:A.projectPath}))),X=Array.from(t.values()).filter((A)=>!Y.has(g(z0(A)))&&A.relationType!=="subagent").map((A)=>i0(A)),K=new Set(X.map((A)=>g({sessionId:A.sessionId,projectPath:A.projectPath}))),D=N.filter((A)=>{if(A.relationType==="subagent")return!1;return!K.has(g({sessionId:A.sessionId,projectPath:A.projectPath}))}),_=new Set(K),L=D.filter((A)=>{let j=g({sessionId:A.sessionId,projectPath:A.projectPath});if(_.has(j))return!1;return _.add(j),!0}),M=[...X,...L];return Z.json(M)}catch(N){throw m.error("[SessionRoutes] Failed to list sessions:",N),new r("Failed to list sessions")}}),O.get("/catalog",async(Z)=>{try{let N=Z.req.query("limit"),Y=N===void 0?void 0:Number(N),X=Z.req.query("cursor"),K=Z.req.query("projectPath"),D=Z.req.query("archived");if(D!==void 0&&D!=="true"&&D!=="false")throw new H("archived must be true or false");let _=D==="true",L=await E.listSessionPage({...K?{cwd:TO(K)}:{},...X?{cursor:X}:{},...Y===void 0?{}:{limit:Y},includeSubagents:!1,archived:_}),M=new Map((_?[]:Array.from(t.values())).filter((A)=>A.relationType!=="subagent").map((A)=>[g(z0(A)),i0(A)]));return Z.json({sessions:L.sessions.map((A)=>M.get(g({sessionId:A.sessionId,projectPath:A.projectPath}))??A),...L.nextCursor?{nextCursor:L.nextCursor}:{}})}catch(N){if(N instanceof H)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 H(N.message);throw m.error("[SessionRoutes] Failed to list session catalog:",N),new r("Failed to list session catalog")}}),O.post("/",async(Z)=>{try{let N=await Z.req.json(),Y=y(j2,N);if(!Y.success)throw new H("Invalid request body");let{title:X,projectPath:K}=Y.data,D=G$("web",12),_=TO(K||Z.get("directory")||c(),K?"projectPath":"directory"),L=await E.createSessionMetadata(D,_,{title:X,taskStatus:"completed"}),M=CO(L,[]),A=z0(M);return t.set(g(A),M),R.publish(A,"session.created",{}),Z.json({...i0(M),status:void 0,agentType:void 0,model:void 0})}catch(N){if(m.error("[SessionRoutes] Failed to create session:",N),N instanceof H)throw N;throw new r("Failed to create session")}}),O.get("/:sessionId/export",async(Z)=>{let N=Z.req.param("sessionId");try{let Y=Z.req.query("includeReasoning");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new H("includeReasoning must be true or false");let X=await N0(N,Z.req.query("projectPath")),K=await E.exportSessionMarkdown(X.sessionId,X.projectPath,{includeReasoning:Y==="true"});return Z.body(K.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${K.filename}"`,"Content-Length":String(Buffer.byteLength(K.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":K.contentSha256,"X-Blade-Export-Activities":String(K.activityCount),"X-Blade-Export-Messages":String(K.messageCount),"X-Blade-Export-Redactions":String(K.redactionCount)})}catch(Y){if(Y instanceof H||Y instanceof f||Y instanceof B0)throw Y;if(Y instanceof Error&&Y.message==="No conversation content to export")throw new q(Y.message);throw m.error("[SessionRoutes] Failed to export session:",Y),new r("Failed to export session")}}),O.post("/:sessionId/fork",async(Z)=>{let N=Z.req.param("sessionId");try{U$(N);let Y=await Z.req.json(),X=y(b2,Y);if(!X.success)throw new H("Invalid request body");let K=TO(X.data.projectPath),D=await E.findSessionMetadata(N,K);if(!D)throw new f("Session",N);let _=await E.forkSession(N,{sourceProjectPath:D.projectPath,targetProjectPath:D.projectPath}),L=CO(_.metadata,_.messages),M=z0(L);return t.set(g(M),L),R.publish(M,"task.status",{taskStatus:_.metadata.taskStatus,..._.metadata.taskCompletedAt?{taskCompletedAt:_.metadata.taskCompletedAt}:{},updatedAt:_.metadata.lastMessageTime}),Z.json({session:_.metadata,messages:Y$(_.messages)},201)}catch(Y){if(Y instanceof H||Y instanceof f||Y instanceof q)throw Y;if(Y instanceof b1)throw new q("Session has no durable creation record");throw m.error("[SessionRoutes] Failed to fork session:",Y),new r("Failed to fork session")}}),O.get("/:sessionId",async(Z)=>{let N=Z.req.param("sessionId");try{let Y=await N0(N,Z.req.query("projectPath")),X=t.get(g(Y));if(X)return Z.json(i0(X));let K=await E.findSessionMetadata(Y.sessionId,Y.projectPath);if(!K)throw new f("Session",N);return Z.json(K)}catch(Y){if(Y instanceof H||Y instanceof f||Y instanceof B0)throw Y;throw m.error("[SessionRoutes] Failed to get session:",Y),new r("Failed to get session")}}),O.patch("/:sessionId",async(Z)=>{let N=Z.req.param("sessionId");try{let Y=await Z.req.json(),X=y(C2,Y);if(!X.success)throw new H("Invalid request body");if(X.data.title===void 0)throw new H("title is required");let K=await N0(N,X.data.projectPath),D=await E.updateSessionMetadata(K.sessionId,K.projectPath,{title:X.data.title}),_=t.get(g(K));if(_)_.title=D.title??_.title,_.updatedAt=new Date(D.lastMessageTime);if(D.title)R.publish(K,"session.updated",{title:D.title});return Z.json({success:!0,title:D.title})}catch(Y){if(m.error("[SessionRoutes] Failed to update session:",Y),Y instanceof H||Y instanceof f||Y instanceof B0)throw Y;throw new r("Failed to update session")}}),O.get("/:sessionId/rewind",async(Z)=>{let N=await $0(Z.req.param("sessionId"),Z.req.query("projectPath"));return v(N,async(Y)=>Z.json({checkpoints:await Y.listRewindCheckpoints()}))}),O.post("/:sessionId/rewind",async(Z)=>{let N=y(P1,await Z.req.json());if(!N.success)throw new H("Invalid rewind request");let Y=await $0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(Y);return I(X,async()=>{let K=D0(Y.currentRunId);if(_0(K))throw new q("Cannot rewind while a run is active");return v(Y,async(D)=>{let _;try{_=await D.rewindSession(N.data)}catch(M){if(M instanceof Error&&M.message.startsWith("Cannot rewind while"))throw new q(M.message);throw M}Y.messages=[..._.messages],Y.updatedAt=new Date;let L=Y$(_.messages);return R.publish(X,"session.rewound",{targetMessageId:_.checkpoint.messageId,mode:_.mode,removedTurns:_.removedTurns,restoredFiles:_.restoredFiles,messages:L}),Z.json({..._,messages:L})})})}),O.get("/:sessionId/review",async(Z)=>{let N=Z.req.param("sessionId"),Y=await N0(N,Z.req.query("projectPath")),X=await a0.list(Y.projectPath,Y.sessionId);return Z.json({reviews:X.map((K)=>({...K,content:K.completion?A1(K.start,K.completion):void 0}))})}),O.post("/:sessionId/review",async(Z)=>{let N=Z.req.param("sessionId"),Y=y(h1,await Z.req.json());if(!Y.success)throw new H("Invalid code review request");let X=await $0(N,Y.data.projectPath),K=z0(X),D=g(K);return I(K,async()=>{if(_0(D0(X.currentRunId)))throw new q("Cannot start a review during an active turn");if(C0.has(D))throw new q("Session already has an active review");return v(X,async(_)=>{if(await a0.recoverInterrupted(K.projectPath,K.sessionId,_),Y.data.modelId&&!_.getModelById(Y.data.modelId))throw new H(`Model not found: ${Y.data.modelId}`);if(Y.data.modelId&&_.getCurrentModelId()!==Y.data.modelId)await _.refresh({modelId:Y.data.modelId});if(Y.data.modelId&&X.selectedModelId!==Y.data.modelId){let j=await E.updateSessionMetadata(X.id,X.projectPath,{selectedModelId:Y.data.modelId});zO(X,j)}let L=new AbortController,M;try{M=await a0.start({sessionId:K.sessionId,projectPath:K.projectPath,runtime:_,request:{kind:Y.data.kind,...Y.data.ref?{ref:Y.data.ref}:{},...Y.data.instructions?{instructions:Y.data.instructions}:{}},signal:L.signal,onEvent:(j)=>{if(j.kind==="tool_start")R.publish(K,"review.tool.started",{reviewId:M?.reviewId,toolCallId:j.toolCall.id,toolName:j.toolCall.function.name});else if(j.kind==="tool_progress")R.publish(K,"review.tool.progress",{reviewId:M?.reviewId,toolCallId:j.toolCall.id,message:j.update.message.slice(0,1000)});else if(j.kind==="tool_result")R.publish(K,"review.tool.completed",{reviewId:M?.reviewId,toolCallId:j.toolCall.id,success:j.result.success})}})}catch(j){if(j instanceof Error&&(j.message.includes("active review")||j.message.includes("interrupted review")||j.message.includes("active turn")))throw new q(j.message);if(j instanceof Error&&(j.message.includes("review")||j.message.includes("Git")||j.message.includes("changes")||j.message.includes("ref")))throw new H(j.message);throw j}if(!M)throw new r("Code review failed to start");await n0(X),R.publish(K,"review.started",{reviewId:M.reviewId,kind:Y.data.kind}),R.publish(K,"task.status",{taskStatus:X.taskStatus,...X.taskStatusReason?{taskStatusReason:X.taskStatusReason}:{},...X.taskStartedAt?{taskStartedAt:X.taskStartedAt}:{},...X.taskPromptSummary?{taskPromptSummary:X.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let A=M.completion.then(async(j)=>{X.messages=await E.loadSession(K.sessionId,K.projectPath),await n0(X),R.publish(K,"task.status",{taskStatus:X.taskStatus,...X.taskStatusReason?{taskStatusReason:X.taskStatusReason}:{},...X.taskFailure?{taskFailure:X.taskFailure}:{},...X.taskStartedAt?{taskStartedAt:X.taskStartedAt}:{},...X.taskCompletedAt?{taskCompletedAt:X.taskCompletedAt}:{},...X.taskPromptSummary?{taskPromptSummary:X.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),R.publish(K,"review.completed",{reviewId:M.reviewId,status:j.status,findings:j.findings.length})}).catch((j)=>{m.error(`[SessionRoutes] Code review ${M.reviewId} failed:`,j)}).finally(()=>{if(C0.get(D)?.reviewId===M.reviewId)C0.delete(D)});return C0.set(D,{reviewId:M.reviewId,controller:L,completion:A}),Z.json({reviewId:M.reviewId,status:"running"},202)})})}),O.get("/:sessionId/subagents",async(Z)=>{let N=await $0(Z.req.param("sessionId"),Z.req.query("projectPath"));return v(N,(Y)=>Z.json({subagents:Y.listSubagents().map(cO)}))}),O.post("/:sessionId/subagents/:agentId/resume",async(Z)=>{U$(Z.req.param("agentId"));let N=f1.safeParse(await Z.req.json());if(!N.success)throw new H("Invalid subagent resume request");let Y=await $0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(Y);return I(X,async()=>{let K=D0(Y.currentRunId);if(_0(K))throw new q("Cannot resume a subagent while a parent run is active");return v(Y,async(D)=>{let _=!1,L,M=(j)=>{R.publish(X,"subagent.complete",{subagentSessionId:j.id,success:j.status==="completed",status:j.status,summary:j.result?.message?.slice(0,500),type:j.subagentType,verificationVerdict:j.result?.verificationVerdict,resumedFrom:j.resumedFrom,rootAgentId:j.rootAgentId,resumeDepth:j.resumeDepth})},A;try{A=D.resumeSubagent({agentId:Z.req.param("agentId"),prompt:N.data.prompt,onEvent:(j,k)=>{y2(X,k,j)},onCompleted:(j)=>{if(_)M(j);else L=j}})}catch(j){if(j instanceof Error&&(j.message.startsWith("Cannot resume")||j.message.startsWith("Subagent cannot")))throw new q(j.message);if(j instanceof Error&&j.message.startsWith("Subagent not found"))throw new f(j.message);throw j}if(R.publish(X,"subagent.start",{subagentSessionId:A.session.id,type:A.session.subagentType,description:A.session.description,resumedFrom:A.source.id,rootAgentId:A.session.rootAgentId,resumeDepth:A.session.resumeDepth}),_=!0,L)M(L);return Z.json({source:cO(A.source),session:cO(A.session)})})})}),O.get("/:sessionId/goal",async(Z)=>{let N=await $0(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json({goal:await new R1(N.projectPath,N.id).get()})}),O.put("/:sessionId/goal",async(Z)=>{let N=y(R2,await Z.req.json());if(!N.success)throw new H("Invalid goal request");let Y=await $0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(Y);return I(X,async()=>{let K=D0(Y.currentRunId);if(_0(K))return Z.json({status:"rejected",reason:"run_active"},409);let _=N.data.permissionMode??Y.permissionMode??"default";if(Y.permissionMode!==_)await S0(Y,_);let L=await e(Y),M=!1;try{let A=await L.value.createGoal(N.data);R.publish(X,"goal.updated",{goal:A});let j=o(Y,"",_,{goalContinuationOnly:!0,runtimeLease:L});return M=!0,await j.taskAdmissionUpdate,Z.json({status:j.status==="queued"?"queued":"running",runId:j.id,goal:A,queuePosition:Y.taskQueuePosition,queueDepth:Y.taskQueueDepth,maxConcurrentTasks:Y.taskConcurrencyLimit},202)}finally{if(!M)L.release()}})}),O.patch("/:sessionId/goal",async(Z)=>{let N=y(E2,await Z.req.json());if(!N.success)throw new H("Invalid goal update");let Y=await $0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(Y);return I(X,async()=>{let K=await e(Y),D=!1;try{let _=K.value,L;if(N.data.action==="pause")L=await _.pauseGoal();else if(N.data.action==="edit")L=await _.editGoal(N.data.objective);else L=await _.resumeGoal();if(R.publish(X,"goal.updated",{goal:L}),L.status==="active"&&!_0(D0(Y.currentRunId))){let M=o(Y,"","default",{goalContinuationOnly:!0,runtimeLease:K});return D=!0,await M.taskAdmissionUpdate,Z.json({status:M.status==="queued"?"queued":"running",runId:M.id,goal:L,queuePosition:Y.taskQueuePosition,queueDepth:Y.taskQueueDepth,maxConcurrentTasks:Y.taskConcurrencyLimit},202)}return Z.json({status:L.status,goal:L})}finally{if(!D)K.release()}})}),O.delete("/:sessionId/goal",async(Z)=>{let N=await $0(Z.req.param("sessionId"),Z.req.query("projectPath")),Y=z0(N);return v(N,async(X)=>{let K=await X.clearGoal();if(K)R.publish(Y,"goal.cleared",{});return Z.json({cleared:K})})}),O.post("/:sessionId/archive",async(Z)=>{let N=Z.req.param("sessionId");try{let Y=await N0(N,Z.req.query("projectPath")),X=await E.listSessionArchiveMembers(Y.sessionId,Y.projectPath);for(let D of X){let _=m0({sessionId:D.sessionId,projectPath:D.projectPath}),L=t.get(g(_));if(_0(D0(L?.currentRunId)))throw new q(`Stop session ${D.sessionId} before archiving this session tree`)}for(let D of X){let _=m0({sessionId:D.sessionId,projectPath:D.projectPath}),L=t.get(g(_));if(L)await Z0(L)}let K=await E.archiveSession(Y.sessionId,Y.projectPath);for(let D of X){let _=m0({sessionId:D.sessionId,projectPath:D.projectPath}),L=g(_);t.delete(L),Q.delete(L),x.delete(L),R.publish(_,"session.archived",{archiveRootId:Y.sessionId,archivedAt:K.archivedAt})}if($.size===0)await U0.getInstance().disconnectAll();return Z.json({session:K,archivedSessionIds:X.map((D)=>D.sessionId)})}catch(Y){if(Y instanceof H||Y instanceof f||Y instanceof B0||Y instanceof q)throw Y;if(Y instanceof N$)throw new q(Y.message);throw m.error("[SessionRoutes] Failed to archive session:",Y),new r("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Z)=>{let N=Z.req.param("sessionId");try{let Y=await N0(N,Z.req.query("projectPath")),X=await E.listSessionArchiveMembers(Y.sessionId,Y.projectPath),K=await E.unarchiveSession(Y.sessionId,Y.projectPath),D=X.filter((_)=>_.sessionId===Y.sessionId||_.archivedBySessionId===Y.sessionId).map((_)=>_.sessionId);for(let _ of D)R.publish({sessionId:_,projectPath:Y.projectPath},"session.unarchived",{archiveRootId:Y.sessionId});return Z.json({session:K,restoredSessionIds:D})}catch(Y){if(Y instanceof H||Y instanceof f||Y instanceof B0)throw Y;if(Y instanceof N$)throw new q(Y.message);throw m.error("[SessionRoutes] Failed to unarchive session:",Y),new r("Failed to unarchive session")}}),O.delete("/:sessionId",async(Z)=>{let N=Z.req.param("sessionId"),Y=Z.req.query("projectPath");try{let X=await N0(N,Y),K=g(X),D=t.get(K),_=$.get(K),L=D?.taskWorktree??await E.findSessionTaskWorktree(X.sessionId,X.projectPath),M;if(D?.currentRunId){let k=D0(D.currentRunId);if(k)bO(k),await k.completion,M=k.id}let A=C0.get(K);if(A)A.controller.abort("session-delete"),await A.completion;if(_)await _.clearGoal().catch((k)=>{m.warn("[SessionRoutes] Failed to clear session goal:",k)});if(await E.deleteSession(X.sessionId,X.projectPath),R.publish(X,"session.deleted",{}),M)k2(M);t.delete(K),Q.delete(K),x.delete(K);let j=$.get(K);if(j){if(!await T.remove(K,j))throw new q("Session Runtime is still active and cannot be deleted")}if(L)try{await E0.restoreSession(L),await E0.exit({sessionId:X.sessionId,action:"remove",discardChanges:!0})}catch(k){m.warn(`[SessionRoutes] Failed to remove deleted task worktree ${X.sessionId}:`,k)}return Z.json({success:!0})}catch(X){if(m.error("[SessionRoutes] Failed to delete session:",X),X instanceof H||X instanceof f||X instanceof B0)throw X;throw new r("Failed to delete session")}}),O.get("/:sessionId/message",async(Z)=>{let N=Z.req.param("sessionId");try{let Y=await N0(N,Z.req.query("projectPath")),X=t.get(g(Y)),K=X?.messages?X.messages:await E.loadSession(Y.sessionId,Y.projectPath);return Z.json(Y$(K))}catch(Y){if(m.error("[SessionRoutes] Failed to get messages:",Y),Y instanceof H||Y instanceof f||Y instanceof B0)throw Y;throw new r("Failed to get messages")}}),O.get("/:sessionId/events",async(Z)=>{let N=Z.req.param("sessionId"),Y=await N0(N,Z.req.query("projectPath"));try{await E.assertSessionWritable(Y.sessionId,Y.projectPath)}catch(L){if(L instanceof V$)throw new q(L.message);throw L}let X=await i(Y),K=Z.req.header("Last-Event-ID")??Z.req.query("lastEventId"),D=K?Number.parseInt(K,10):Number.NaN,_=Number.isInteger(D)?D+1:void 0;return M2(Z,async(L)=>{let A,j,k=!1,K0,P0,j0=new Promise((h)=>{P0=h}),G0=()=>{if(j!==void 0)clearInterval(j),j=void 0;A?.(),A=void 0},O0=(h)=>{if(k)return;k=!0,G0(),K0?.close(h),P0()},r0=new Set;L.onAbort(O0),K0=new HO({write:async(h)=>{await L.writeSSE(h)},onFailure:(h)=>{m.warn(`[SessionRoutes] SSE egress closed for ${Y.sessionId}: kind=${h.kind} pendingItems=${h.pendingItems??0} pendingBytes=${h.pendingBytes??0}`),O0(h)}}),A=R.subscribe((h)=>{if(h.sessionId!==Y.sessionId||h.projectPath!==Y.projectPath)return;let P=h.properties.requestId;if((h.type==="permission.asked"||h.type==="question.required"||h.type==="elicitation.required")&&typeof P==="string"){if(r0.has(P))return;r0.add(P)}if(h.type==="subagent.completion.queued")I(Y,()=>q0(X)).catch((S)=>{m.error(`[SessionRoutes] Failed to wake background completion for ${X.id}:`,S)});K0?.observe(I2(h),h.seq)});try{if(L.aborted||k)return;let h=D0(X.currentRunId),P=_0(h)?await e(X):void 0;try{let l=P?.value,d=l?.getPendingSteeringCount()??0;await K0.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:Y.sessionId,projectPath:Y.projectPath,timestamp:Date.now(),status:_0(h)?h.status:"idle",runId:_0(h)?h.id:void 0,queued:d,pendingInputDelivery:d>0?l?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:l?.getRecoveredSteeringCount()??0}})})}finally{P?.release()}if(L.aborted||k)return;if(_!==void 0){if(await E1.for(Y.sessionId,Y.projectPath).replay({onCommitted:async(d)=>{if(L.aborted||k)return;let s=f2(d);if(s.seq===void 0)return;await K0.writeReplay({...typeof d.seq==="number"?{id:String(d.seq)}:{},data:JSON.stringify({type:s.type,...s.seq!==void 0?{seq:s.seq}:{},properties:{...s.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})},s.seq)}},_),L.aborted||k)return}if(K0.finishInitialization({replayed:_!==void 0}),L.aborted||k)return;if(!h&&!C0.has(g(Y))){let d=(await a0.list(Y.projectPath,Y.sessionId)).some((s)=>s.completion===void 0)?await v(X,(s)=>a0.recoverInterrupted(Y.projectPath,Y.sessionId,s)):void 0;if(d)X.messages=await E.loadSession(Y.sessionId,Y.projectPath),await n0(X),R.publish(Y,"review.completed",{reviewId:d.reviewId,status:d.status,findings:0,recovered:!0})}if(L.aborted||k)return;if(!h)await o0.recoverResponded(Y.projectPath,Y.sessionId);if(L.aborted||k)return;let S=h?void 0:await o0.findPending(Y.projectPath,Y.sessionId),u=h?.pendingPermission??(S?{permissionId:S.request.requestId,details:o0.confirmationDetails(S),resolve:()=>{return}}:void 0);if(u){r0.add(u.permissionId);let l=v1(u,!0);K0.observe({data:JSON.stringify({type:l.type,properties:{...l.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})})}if(L.aborted||k)return;if(q0(X).catch((l)=>{m.error(`[SessionRoutes] Failed to resume pending input for ${N}:`,l)}),L.aborted||k)return;j=setInterval(()=>{if(L.aborted||k)return;K0?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await j0}finally{O0()}})}),O.post("/:sessionId/message",async(Z)=>{let N=Z.req.param("sessionId"),Y=await Z.req.json(),X=y(T2,Y);if(!X.success)throw new H("Invalid message format");let{content:K,attachments:D,modelId:_,reasoningEffort:L,serviceTier:M,responseVerbosity:A,communicationStyle:j,permissionMode:k,projectPath:K0,outputSchema:P0}=X.data,j0;if(P0)try{j0=X$(P0).schema}catch(d){throw new H(d instanceof Error?d.message:"Invalid output schema")}let G0=j,O0=_?.trim();if((D??[]).reduce((d,s)=>d+(typeof s.content==="string"?Buffer.byteLength(s.content):0),0)>aO)throw new H("Message attachments exceed the 5 MiB limit");let h=k,P=F1(K,D),S=await $0(N,K0??Z.req.query("projectPath")),u=h??S.permissionMode??"default",l=z0(S);return I(l,async()=>{let d=D0(S.currentRunId);if(_0(d)){if(j0)throw new q("Wait for the active turn to finish before setting an output schema");return v(S,async(n)=>{if(O0&&!n.getModelById(O0))throw new H(`Model not found: ${O0}`);if(O0&&n.getCurrentModelId()!==O0)throw new q("Wait for the active turn to finish before switching models");if(L&&n.getReasoningConfiguration().selection!==L)throw new q("Wait for the active turn to finish before switching reasoning effort");if(M&&n.getServiceTierConfiguration().selection!==M)throw new q("Wait for the active turn to finish before switching service tier");if(A&&n.getResponseVerbosityConfiguration().selection!==A)throw new q("Wait for the active turn to finish before switching response verbosity");if(G0&&n.getCommunicationStyleConfiguration().selection!==G0)throw new q("Wait for the active turn to finish before switching communication style");if(h&&S.permissionMode!==h)throw new q("Wait for the active turn to finish before switching permission mode");let Y0=await n.enqueueSteering(P,{allowBeforeTurn:!0});if(!Y0.accepted)return Z.json({status:"rejected",reason:Y0.reason??"turn_unavailable"},409);let d0=Y0.messageId??QO(12),_O=Y0.queued;R.publish(l,"message.created",{messageId:d0,role:"user",content:_$(P)});let hO=Y0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(R.publish(l,hO,{runId:d.id,messageId:d0,queued:_O}),Y0.delivery==="next_turn"&&d.status!=="running"&&d.status!=="waiting_permission")q0(S).catch((gO)=>{m.error(`[SessionRoutes] Failed to wake queued follow-up for ${N}:`,gO)});if(Y0.delivery==="next_turn")d.pendingFollowUpRequested=!0;return Z.json({runId:d.id,messageId:d0,status:Y0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:_O},202)})}if(S.permissionMode!==u)await S0(S,u);let s=await e(S,{permissionMode:u,...G0&&!G0.includes(":")?{communicationStyle:G0}:{}}),UO=!1;try{let n=s.value;if(O0&&!n.getModelById(O0))throw new H(`Model not found: ${O0}`);if(L)try{n.resolveReasoningConfiguration(L,O0)}catch(X0){throw new H(X0 instanceof Error?X0.message:"Invalid reasoning effort")}if(M)try{n.resolveServiceTierConfiguration(M,O0)}catch(X0){throw new H(X0 instanceof Error?X0.message:"Invalid service tier")}if(A)try{n.resolveResponseVerbosityConfiguration(A,O0)}catch(X0){throw new H(X0 instanceof Error?X0.message:"Invalid response verbosity")}let Y0=G0?n.resolveCommunicationStyleConfiguration(G0):void 0;if(Y0?.source!==void 0&&Y0.source!=="built-in"&&!Y0.contentSha256)throw new H("Custom communication style has no provenance");let d0=n.getCurrentModelId(),_O=n.getReasoningConfiguration(),hO=n.getServiceTierConfiguration(),gO=n.getResponseVerbosityConfiguration(),f$=n.getCommunicationStyleConfiguration(),y$=Boolean(O0)&&d0!==O0,m$=Boolean(L)&&_O.selection!==L,h$=Boolean(M)&&hO.selection!==M,g$=Boolean(A)&&gO.selection!==A,v$=Boolean(G0)&&f$.selection!==G0;if(y$||m$||h$||g$||v$)await n.refresh({...O0?{modelId:O0}:{},...L?{reasoningEffort:L}:{},...M?{serviceTier:M}:{},...A?{responseVerbosity:A}:{},...G0?{communicationStyle:G0}:{}});let O$={...O0&&S.selectedModelId!==O0?{selectedModelId:O0}:{},...L&&S.reasoningEffort!==L?{reasoningEffort:L}:{},...M&&S.serviceTier!==M?{serviceTier:M}:{},...A&&S.responseVerbosity!==A?{responseVerbosity:A}:{},...Y0&&(S.communicationStyle!==G0||S.communicationStyleDigest!==Y0.contentSha256)?{communicationStyle:G0,communicationStyleDigest:Y0.source==="built-in"?null:Y0.contentSha256}:{}};if(Object.keys(O$).length>0)try{let X0=await E.updateSessionMetadata(S.id,S.projectPath,O$);S.permissionMode=X0.permissionMode,S.selectedModelId=X0.selectedModelId,S.reasoningEffort=X0.reasoningEffort,S.serviceTier=X0.serviceTier,S.responseVerbosity=X0.responseVerbosity,S.communicationStyle=X0.communicationStyle,S.communicationStyleDigest=X0.communicationStyleDigest,S.updatedAt=new Date(X0.lastMessageTime),R.publish(l,"session.updated",O$)}catch(X0){if(y$||m$||h$||g$||v$)await n.refresh({...d0?{modelId:d0}:{},reasoningEffort:_O.selection,serviceTier:hO.selection,responseVerbosity:gO.selection,communicationStyle:f$.selection}).catch((i4)=>m.error("[SessionRoutes] Failed to roll back non-durable model settings:",i4));throw X0}let DO=j0?await n.prepareInputTurn(P,{outputSchema:j0}):await n.prepareInputTurn(P);if(!DO.accepted)return Z.json({status:"rejected",reason:DO.reason},DO.reason==="queue_full"?429:409);let $$=o(S,P,u,{preparedInputTurn:DO,outputSchema:j0,runtimeLease:s});return UO=!0,await $$.taskAdmissionUpdate,Z.json({runId:$$.id,messageId:DO.messageId,status:$$.status==="queued"?"queued":"running",queuePosition:S.taskQueuePosition,queueDepth:S.taskQueueDepth,maxConcurrentTasks:S.taskConcurrencyLimit},202)}finally{if(!UO)s.release()}})}),O.post("/:sessionId/shell",async(Z)=>{let N=Z.req.param("sessionId"),Y=y(m1,await Z.req.json());if(!Y.success)throw new H("Invalid user shell command");let X=await $0(N,Y.data.projectPath??Z.req.query("projectPath")),K=z0(X),D=g(K);return I(K,async()=>{if(I0.has(D))throw new q("A user shell command is already running in this Session");let _=await e(X),L=_.value,M=new AbortController,A,j=new Promise((k)=>{A=k});I0.set(D,{controller:M,completion:j});try{let k=await L.executeUserShellCommand(Y.data.command,{signal:M.signal});X.messages=await E.loadSession(X.id,X.projectPath),X.updatedAt=new Date;let K0=D0(X.currentRunId);if(k.delivery==="next_turn"&&_0(K0))K0.pendingFollowUpRequested=!0;return Z.json({executionId:k.executionId,messageId:k.messageId,record:k.record,auxiliary:k.auxiliary,...k.delivery?{delivery:k.delivery}:{},...k.queued!==void 0?{queued:k.queued}:{}})}finally{I0.delete(D),A(),_.release()}})}),O.post("/:sessionId/abort",async(Z)=>{let N=Z.req.param("sessionId"),Y=await N0(N,Z.req.query("projectPath")),X=t.get(g(Y));if(X?.currentRunId){let _=D0(X.currentRunId);if(_)bO(_),await _.completion}let K=I0.get(g(Y));if(K)K.controller.abort("user-cancel"),await K.completion;let D=C0.get(g(Y));if(D)D.controller.abort("user-cancel"),await D.completion;return Z.json({success:!0})}),O.get("/:sessionId/status",async(Z)=>{let N=Z.req.param("sessionId"),Y=await N0(N,Z.req.query("projectPath")),X=t.get(g(Y)),K=C0.get(g(Y));if(K)return Z.json({sessionId:N,projectPath:Y.projectPath,reviewId:K.reviewId,status:"reviewing"});if(!X?.currentRunId)return Z.json({sessionId:N,projectPath:Y.projectPath,status:"idle"});let D=D0(X.currentRunId);return Z.json({sessionId:N,projectPath:Y.projectPath,runId:X.currentRunId,status:D?.status||"idle"})}),{app:O,dispatchTask:w0,retryTask:V0,updateTask:S$,getTaskDiff:rO,deliverTask:yO,recoverQueuedTasks:eO,getRuntimeResidencyStats:()=>T.getStats(),getCoordinationStats:()=>({messageSubmissions:G.getStats(),taskDeliveries:z.getStats()}),shutdown:(Z="server-shutdown")=>{if(w)return w;return B.close(Z),clearInterval(C),w=(async()=>{let N,Y=async(L)=>{let M=await Promise.allSettled(L);for(let A of M)if(A.status==="rejected")N??=A.reason},X=new Set,K=()=>{for(let L of b0.values()){if(L.completion)X.add(L.completion);if(_0(L))bO(L,Z)}for(let L of I0.values())L.controller.abort(Z),X.add(L.completion);for(let L of C0.values())L.controller.abort(Z),X.add(L.completion)},D=B.waitForIdle(),_=!1;D.then(()=>{_=!0});while(!_)K(),await Promise.race([D,new Promise((L)=>setImmediate(L))]);if(await D,K(),await Y([...X]),await Y([...x.values()]),K(),await Y([...X]),await Y([T.disposeAll()]),$.clear(),await Y([...J.values()]),await Y([U0.getInstance().disconnectAll()]),x.clear(),J.clear(),Q.clear(),t.clear(),YO===q0)YO=void 0;if(N!==void 0)throw N})(),w}}};async function m2(O,$,x,J,Q,G={}){let{abortController:z,sessionId:F,id:T}=O,B=G.preparedInputTurn?.messageId??QO(12),w=G.pendingInputOnly===!0||G.preparedInputTurn?.mode==="pending"||G.goalContinuationOnly===!0?void 0:QO(12),W=G.runtimeLease,I,J0,p=z0($),b=(v,Z0)=>{R.publish(p,v,Z0)},e=async()=>{let v=String(z.signal.reason||"Task run cancelled");if($.taskIsolation){if(!W)W=await Q($).catch(()=>{return});let Z0=I??W?.value;if(v==="user-cancel")await Z0?.discardPendingInput().catch(($0)=>{m.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,$0)});let i=await Z0?.setTaskStatus("cancelled",v).catch(()=>{return});if(i)zO($,i);else await n0($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=v,$.taskCompletedAt??=new Date().toISOString()};try{if(G.taskAdmission){if(await G.taskAdmission.ready,await O.taskAdmissionUpdate,z.signal.aborted)throw Error(String(z.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!G.pendingInputOnly&&!G.goalContinuationOnly)b("message.created",{messageId:B,role:"user",content:_$(x)});if(b("session.status",{status:"running"}),w)b("message.created",{messageId:w,role:"assistant",content:""});W??=await Q($),I=W.value;let v=I,Z0=Boolean(G.outputSchema??v.getPendingSteeringMessages().find((V)=>V.outputSchema)?.outputSchema);J0=await I1.createWithRuntime(v,{sessionId:F,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let i=async(V)=>{let V0=V.interactionRequestId??QO(12),S$=300000;O.status="waiting_permission";let rO=new Promise((q0)=>{let eO=setTimeout(()=>{m.warn(`[SessionRoutes] Permission ${V0} timed out after 300000ms`),b("permission.timeout",{requestId:V0}),q0({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:V0,resolve:(P$)=>{clearTimeout(eO),q0(P$)},details:V}}),FO=O.pendingPermission;if(!FO)throw Error("Permission request was not registered");let yO=v1(FO);b(yO.type,yO.properties),m.info(`[SessionRoutes] Permission request created: ${V0}, runId: ${T}`);let mO=await rO;if(m.info(`[SessionRoutes] Permission response received: ${V0}, approved: ${mO.approved}`),!z.signal.aborted)O.status="running";if(O.pendingPermission===FO)O.pendingPermission=void 0;return b("interaction.resolved",{requestId:V0}),mO},S0={messages:await E.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:F,workspaceRoot:$.projectPath,signal:z.signal,permissionMode:J,onPermissionModeChange:async(V)=>{$.permissionMode=V,$.updatedAt=new Date,b("session.updated",{permissionMode:V})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:i}},o=()=>{if(!w)w=QO(12),b("message.created",{messageId:w,role:"assistant",content:""});return w},p0=async(V)=>{switch(V.kind){case"content_delta":if(Z0)break;b("message.delta",{messageId:o(),delta:V.delta});break;case"structured_output":b("structured.output",{messageId:o(),output:V.output,schemaDigest:V.schemaDigest});break;case"thinking_delta":b("thinking.delta",{messageId:o(),delta:V.delta});break;case"tool_start":if("function"in V.toolCall){if(V.toolCall.function.name===ZO)break;b("tool.start",{messageId:o(),toolName:V.toolCall.function.name,toolCallId:V.toolCall.id,arguments:V.toolCall.function.arguments,toolKind:V.toolKind})}break;case"tool_result":if("function"in V.toolCall){if(V.toolCall.function.name===ZO)break;b("tool.result",{messageId:o(),toolName:V.toolCall.function.name,toolCallId:V.toolCall.id,success:V.result.success,summary:V.result.metadata?.summary,output:IO(qO(kO(V.toolCall.function.name,V.result),EO)),metadata:RO(V.toolCall.function.name,V.result.metadata)})}break;case"tool_progress":if("function"in V.toolCall){if(V.toolCall.function.name===ZO)break;b("tool.progress",{messageId:o(),toolName:V.toolCall.function.name,toolCallId:V.toolCall.id,...V.update})}break;case"token_usage":b("token.usage",{...V.usage});break;case"turn_start":b("turn.started",{turn:V.turn,maxTurns:V.maxTurns});break;case"provider_admission":b("provider.admission",{phase:V.phase,requestClass:V.requestClass,resource:V.resource,scope:V.scope,reason:V.reason,queuePosition:V.queuePosition,queueDepth:V.queueDepth,inFlight:V.inFlight,limit:V.limit,waitMs:V.waitMs,maxWaitMs:V.maxWaitMs,recoveryRemainingMs:V.recoveryRemainingMs});break;case"provider_circuit":b("provider.circuit",{phase:V.phase,reason:V.reason,statusCode:V.statusCode,retryAfterMs:V.retryAfterMs,nextProbeAt:V.nextProbeAt,openDurationMs:V.openDurationMs,sampleCount:V.sampleCount,failureCount:V.failureCount,recoveryRemainingMs:V.recoveryRemainingMs});break;case"provider_retry":b("provider.retry",{phase:V.phase,attempt:V.attempt,maxRetries:V.maxRetries,reason:V.reason,statusCode:V.statusCode,delayMs:V.delayMs,nextRetryAt:V.nextRetryAt,mode:V.mode,recoveryBudgetMs:V.recoveryBudgetMs,recoveryElapsedMs:V.recoveryElapsedMs,recoveryRemainingMs:V.recoveryRemainingMs,exhaustedBy:V.exhaustedBy});break;case"provider_stall":b("provider.stall",{phase:V.phase,stallCount:V.stallCount,durationMs:V.durationMs,warningAfterMs:V.warningAfterMs,timeoutMs:V.timeoutMs,outputStarted:V.outputStarted});break;case"action_stationarity":b("action.stationarity",{phase:V.phase,toolName:V.toolName,runLength:V.runLength,nudgeThreshold:V.nudgeThreshold,haltThreshold:V.haltThreshold,progressAware:V.progressAware});break;case"mcp_catalog_changed":b("mcp.catalog.changed",{messageId:o(),revision:V.revision,serverName:V.serverName,added:V.added,removed:V.removed,updated:V.updated});break;case"mcp_content_changed":b("mcp.content.changed",{messageId:o(),revision:V.revision,serverName:V.serverName,contentKind:V.contentKind,added:V.added,removed:V.removed,updated:V.updated});break;case"mcp_resource_updated":b("mcp.resource.updated",{messageId:o(),revision:V.revision,serverName:V.serverName,uri:V.uri});break;case"mcp_connection_changed":b("mcp.connection.changed",{messageId:o(),revision:V.revision,serverName:V.serverName,phase:V.phase,reason:V.reason,attempt:V.attempt,maxAttempts:V.maxAttempts,nextRetryAt:V.nextRetryAt,error:V.error});break;case"mcp_log":b("mcp.log",{messageId:o(),revision:V.revision,serverName:V.serverName,level:V.level,logger:V.logger,message:V.message,projectedBytes:V.projectedBytes,dataSha256:V.dataSha256,truncated:V.truncated,detailsOmitted:V.detailsOmitted,timestamp:V.timestamp,synthetic:V.synthetic});break;case"mcp_instructions_changed":b("mcp.instructions.changed",{messageId:o(),revision:V.revision,serverName:V.serverName,action:V.action,reason:V.reason,text:V.text,sourceBytes:V.sourceBytes,projectedBytes:V.projectedBytes,sha256:V.sha256,truncated:V.truncated,detailsOmitted:V.detailsOmitted});break;case"mcp_task_changed":b("mcp.task.changed",{messageId:o(),revision:V.revision,taskId:V.taskId,serverName:V.serverName,toolName:V.toolName,status:V.status,statusMessage:V.statusMessage,createdAt:V.createdAt,updatedAt:V.updatedAt,completedAt:V.completedAt,hasResult:V.hasResult,error:V.error});break;case"project_rules_loaded":b("project.rules.loaded",{messageId:o(),files:V.files,triggerPaths:V.triggerPaths,blockedWrite:V.blockedWrite});break;case"steering_applied":b("steering.applied",{runId:T,messageIds:V.messageIds,count:V.count,recovered:V.recovered,delivery:V.delivery,queued:v.getPendingSteeringCount()});break;case"follow_up_started":{if(w)b("message.complete",{messageId:w}),w=void 0;for(let V0 of V.messages){if(!V0.recovered||V0.persisted)continue;b("message.created",{messageId:V0.id,role:"user",content:_$(V0.content),recovered:!0})}b("follow_up.started",{runId:T,queued:V.queued,recovered:V.recovered}),o();break}case"goal_updated":b("goal.updated",{goal:V.goal});break;case"goal_continuation_started":b("goal.continuation.started",{goal:V.goal,continuation:V.continuation}),o();break;case"compaction":b(V.phase==="start"?"compaction.started":"compaction.completed",{...V.reason?{reason:V.reason}:{},...V.strategy?{strategy:V.strategy}:{},...V.outcome?{outcome:V.outcome}:{},...V.preTokens!==void 0?{preTokens:V.preTokens}:{},...V.postTokens!==void 0?{postTokens:V.postTokens}:{}});break;case"model_fallback":b("model.fallback",{});break;case"task_update":b("task.updated",{tasks:V.tasks});break;default:break}},w0=await K$(J0.chatStream(x,S0,{stream:!0,pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly,outputSchema:G.outputSchema,taskAdmission:G.taskAdmission}),p0);if(!w0.success)throw Error(w0.error?.message??"Agent run failed");for(let V=0;V<20;V++){let V0=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,v.getPendingSteeringCount()===0){if(!V0)break;continue}if(z.signal.aborted)break;if(w0=await K$(J0.chatStream("",S0,{stream:!0,pendingInputOnly:!0,taskAdmission:G.taskAdmission}),p0),!w0.success)throw Error(w0.error?.message??"Agent follow-up failed")}if($.messages=await E.loadSession($.id,$.projectPath),$.updatedAt=new Date,await n0($),z.signal.aborted||O.status==="cancelled"){await e(),b("session.status",{status:"idle"});return}if(w)b("message.complete",{messageId:w});b("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),b("session.completed",{runId:T,outputTruncated:w0.metadata?.outputTruncated??!1}),b("session.status",{status:"idle"})}catch(v){if(I&&G.preparedInputTurn)await I.finishTurn(G.preparedInputTurn.handle).catch(()=>{return});if(z.signal.aborted||O.status==="cancelled"){bO(O,"runtime-abort"),await e(),b("session.status",{status:"idle"});return}await n0($).catch(()=>{return}),m.error("[SessionRoutes] Agent execution error:",v),O.status="failed",$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let Z0=iO(v);if(!$.taskFailure){let i=I?await I.setTaskStatus("failed",v).catch(()=>{return}):await E.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:Z0.message,taskFailure:Z0,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(i)zO($,i)}$.taskStatusReason??=Z0.message,$.taskFailure??=Z0,b("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),b("session.status",{status:"error"})}finally{if(G.taskAdmission?.release(),G.taskAdmission){let v=f0.getStats();b("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:v.queued,taskConcurrencyLimit:v.maxConcurrent,taskInFlight:v.inFlight,taskAdmissionPaused:v.paused,updatedAt:new Date().toISOString()})}if(await J0?.destroy().catch(()=>{return}),W?.release(),O.disposeRuntimeOnSettle&&G.disposeRuntime)await G.disposeRuntime($,I).catch((v)=>{m.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,v)});q2(O)}}async function p1(O,$,x){m.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),m.info(`[SessionRoutes] Active runs: ${b0.size}`);for(let[G,z]of b0.entries())if(m.info(`[SessionRoutes] Checking run ${G}: sessionId=${z.sessionId}, projectPath=${z.projectPath}, pendingPermission=${z.pendingPermission?.permissionId}`),z.sessionId===O.sessionId&&z.projectPath===O.projectPath&&z.pendingPermission?.permissionId===$){if(z.pendingPermission.details.interactionRequestId)await o0.respond(O.projectPath,O.sessionId,$,x);return z.pendingPermission.resolve(x),m.info(`[SessionRoutes] Permission ${$} responded, runId: ${z.id}`),!0}let J=await o0.findPending(O.projectPath,O.sessionId);if(!J||J.request.requestId!==$)return m.error(`[SessionRoutes] Permission not found: ${$}`),!1;await o0.respondAndRecover(O.projectPath,O.sessionId,$,x);let Q=t.get(g(O));if(!Q){let G=await E.findSessionMetadata(O.sessionId,O.projectPath);if(!G)return!1;let[z,F]=await Promise.all([E.loadSession(O.sessionId,O.projectPath),E.findSessionTaskWorktree(O.sessionId,O.projectPath)]);Q=CO(G,z,F),t.set(g(O),Q)}else await n0(Q);if(R.publish(O,"interaction.resolved",{requestId:$}),YO)YO(Q).catch((G)=>{m.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,G)});return!0}var H$=a("Service"),g2=U.Object({approved:U.Boolean(),remember:U.Optional(U.Boolean()),scope:U.Optional(F0(["once","session","project"])),targetMode:U.Optional(F0(["default","autoEdit","plan","yolo"])),feedback:U.Optional(U.String({maxLength:4000})),answers:U.Optional(U.Record(U.String({maxLength:80}),U.Union([U.String({maxLength:4000}),U.Array(U.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:U.Optional(U.Object({action:F0(["accept","decline","cancel"]),content:U.Optional(U.Record(U.String(),U.Union([U.String({maxLength:4000}),U.Number(),U.Boolean(),U.Array(U.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),d1=()=>{let O=new h2;return O.post("/:permissionId",async($)=>{let x=$.req.param("permissionId"),J=$.req.query("sessionId"),Q=$.req.query("projectPath");H$.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${J}`);try{let G=await $.req.json(),z=y(g2,G);if(!z.success)throw new H("Invalid permission response format");let{approved:F,remember:T,scope:B,targetMode:C,feedback:w,answers:W,elicitation:I}=z.data;if(!J)throw new H("sessionId query parameter is required");let J0=await N0(J,Q);if(!await p1(J0,x,{approved:F,reason:w,scope:B,targetMode:C,feedback:w,answers:W,elicitation:I}))throw new f("Permission request",x);return H$.info(`[PermissionRoutes] Permission ${x} ${F?"approved":"denied"}`),$.json({success:!0,approved:F,remember:T})}catch(G){if(H$.error("[PermissionRoutes] Failed to respond to permission:",G),G instanceof H||G instanceof B0||G instanceof f||G instanceof Q0)throw G;throw G}}),O};import l1 from"node:path";import{Hono as v2}from"hono";var u2=U.Object({projectPath:U.String({minLength:1}),enabled:U.Boolean(),scope:U.Optional(F0(["local","project","global"]))}),p2=U.Object({projectPath:U.String({minLength:1})}),d2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),trust:U.Literal(!0),ref:U.Optional(U.String({minLength:1}))}),l2=U.Object({projectPath:U.String({minLength:1}),trust:U.Literal(!0)}),c2=U.Object({projectPath:U.String({minLength:1}),confirm:U.Literal(!0)}),i2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),ref:U.Optional(U.String({minLength:1}))}),c1=U.Object({projectPath:U.String({minLength:1}),confirm:U.Optional(U.Literal(!0))}),a2=U.Object({projectPath:U.String({minLength:1}),scope:U.Optional(F0(["local","project","global"])),policy:U.Object({restrictToAllowedSources:U.Boolean(),requireGitCommitSha:U.Boolean(),allowedGitHosts:U.Array(U.String()),allowedMarketplaces:U.Array(U.String()),allowedLocalRoots:U.Array(U.String())})});function M0(O){if(!O||!l1.isAbsolute(O))throw new H("projectPath must be absolute");return l1.resolve(O)}async function i1(O){let[$,x]=await Promise.all([T0(O),LO.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((J)=>({name:J.manifest.name,description:J.manifest.description,version:J.manifest.version,source:J.source,enabled:J.status==="active",status:J.status,commands:J.commands.length,skills:J.skills.length,agents:J.agents.length,hooks:J.hooks?Object.values(J.hooks).reduce((Q,G)=>Q+(Array.isArray(G)?G.length:0),0):0,mcpServers:Object.keys(J.mcpServers??{}).length,configurable:J.source!=="cli",managed:J.installation!==void 0,marketplace:J.installation?.source.type==="marketplace"?J.installation.source.marketplace:void 0,revision:J.installation?.revision,installedAt:J.installation?.installedAt,updatedAt:J.installation?.updatedAt,compatibilityIssues:J.compatibilityIssues??[],effectiveScope:J.source==="cli"?"invocation":x.settings[J.manifest.name]?.effectiveScope??"default",settingLayers:J.source==="cli"?{invocation:!0}:x.settings[J.manifest.name]?.layers??{}}))}async function o2(){let O=a1(),[$,x]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),J=new Map(x.map((Q)=>[Q.name,Q]));return $.map(({marketplace:Q,manifest:G})=>({name:Q.name,description:G.description??G.metadata?.description??"",sourceType:Q.source.type,revision:Q.revision,updatedAt:Q.updatedAt,plugins:G.plugins.map((z)=>{let F=J.get(z.name);return{name:z.name,description:z.description??"",version:z.version,category:z.category,tags:z.tags??[],installed:F!==void 0,installedVersion:F?.version}})}))}function GO(O,$){if(!O.success)throw new H(O.error??$)}var J4=()=>{let O=new v2;return O.get("/",async($)=>{let x=M0($.req.query("projectPath"));return $.json(await i1(x))}),O.post("/refresh",async($)=>{let x=y(p2,await $.req.json());if(!x.success)throw new H("Invalid plugin refresh request");let J=M0(x.data.projectPath),Q=await n1(J);return $.json({plugins:await i1(J),errors:Q.discovery.errors.map((G)=>({code:G.code??"LOAD_ERROR",error:G.error}))})}),O.get("/catalog",async($)=>{return M0($.req.query("projectPath")),$.json(await o2())}),O.get("/policy",async($)=>{let x=M0($.req.query("projectPath")),J=await LO.getInstance().loadWorkspacePluginSourcePolicy(x);return $.json({policy:J,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let x=y(a2,await $.req.json());if(!x.success)throw new H("Invalid plugin source policy request");let J=M0(x.data.projectPath),Q=await t1(J,x.data.policy,x.data.scope??"global");return $.json({policy:Q})}),O.post("/install",async($)=>{let x=y(d2,await $.req.json());if(!x.success)throw new H("Invalid plugin install request; explicit source trust is required");let J=M0(x.data.projectPath),{result:Q}=await s1(J,x.data.source,{trusted:x.data.trust,ref:x.data.ref});return GO(Q,"Plugin installation failed"),$.json({name:Q.pluginName,version:Q.manifest?.version,revision:Q.installation?.revision,changed:Q.changed,installedDependencies:Q.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let x=y(i2,await $.req.json());if(!x.success)throw new H("Invalid marketplace add request");let J=M0(x.data.projectPath),Q=await O4(J,x.data.source,x.data.ref);return GO(Q,"Marketplace installation failed"),$.json({name:Q.marketplace?.name,plugins:Q.manifest?.plugins.length??0,revision:Q.marketplace?.revision,changed:Q.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let x=y(c1,await $.req.json());if(!x.success)throw new H("Invalid marketplace refresh request");let J=await $4(M0(x.data.projectPath),$.req.param("name"));return GO(J,"Marketplace refresh failed"),$.json({name:J.marketplace?.name,plugins:J.manifest?.plugins.length??0,revision:J.marketplace?.revision,changed:J.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let x=y(c1,await $.req.json());if(!x.success||x.data.confirm!==!0)throw new H("Invalid marketplace removal request; explicit confirmation is required");M0(x.data.projectPath);let J=await x4($.req.param("name"),!0);return GO(J,"Marketplace removal failed"),$.json({name:J.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let x=y(l2,await $.req.json());if(!x.success)throw new H("Invalid plugin update request; explicit source trust is required");let J=M0(x.data.projectPath),{result:Q}=await r1(J,$.req.param("name"),{trusted:x.data.trust});return GO(Q,"Plugin update failed"),$.json({name:Q.pluginName,version:Q.manifest?.version,revision:Q.installation?.revision,changed:Q.changed,updatedDependencies:Q.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let x=y(c2,await $.req.json());if(!x.success)throw new H("Invalid plugin uninstall request; explicit confirmation is required");let J=M0(x.data.projectPath),{result:Q}=await e1(J,$.req.param("name"),x.data.confirm);return GO(Q,"Plugin uninstall failed"),$.json({name:Q.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let x=y(u2,await $.req.json());if(!x.success)throw new H("Invalid plugin state request");let J=M0(x.data.projectPath),Q=$.req.param("name"),z=(await T0(J)).plugins.get(Q);if(!z)throw new f("Plugin",Q);if(z.source==="cli")throw new H(`Plugin "${Q}" was loaded with --plugin-dir and is invocation-scoped`);let F=await o1(J,Q,x.data.enabled,x.data.scope??"local");return $.json(F)}),O};import{Hono as e2}from"hono";import{execFile as n2}from"node:child_process";import t2 from"node:path";var w$="__BLADE_DIRECTORY_PICKER_CANCELLED__",s2=900000;function r2(O,$){return new Promise((x)=>{n2(O,[...$],{timeout:s2,maxBuffer:65536,windowsHide:!0},(J,Q,G)=>{let z=J?.code;x({stdout:Q,stderr:G,exitCode:typeof z==="number"?z:J?1:0,...typeof z==="string"?{errorCode:z}:{}})})})}function B$(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===w$)return{cancelled:!0};if(!t2.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function L$(O){return O.exitCode!==0||Boolean(O.errorCode)}class Q4{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??r2}pick(){if(this.activeSelection)return this.activeSelection;let O=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=O,O}async pickForPlatform(){switch(this.platform){case"darwin":return this.pickOnMac();case"win32":return this.pickOnWindows();case"linux":return this.pickOnLinux();default:throw Error("Native folder selection is unavailable on this system")}}async pickOnMac(){let O=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${w$}"`,"end try"].join(`
8
- `),$=await this.runCommand("osascript",["-e",O]);if(L$($))throw Error("Unable to open the macOS folder picker");return B$($.stdout)}async pickOnWindows(){let O=["Add-Type -AssemblyName System.Windows.Forms","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog",'$dialog.Description = "Choose a project folder"',"$dialog.ShowNewFolderButton = $true","if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {"," [Console]::Out.Write($dialog.SelectedPath)","} else {",` [Console]::Out.Write("${w$}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(L$($))throw Error("Unable to open the Windows folder picker");return B$($.stdout)}async pickOnLinux(){let O=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let $ of O){let x=await this.runCommand($.command,$.args);if(x.errorCode==="ENOENT")continue;if(x.exitCode===1&&!x.stdout.trim()&&!x.stderr.trim())return{cancelled:!0};if(L$(x))throw Error("Unable to open the Linux folder picker");return B$(x.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var Z4=new Q4;var O5=U.Object({path:U.String({minLength:1})});function $5(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let $=new URL(O).hostname;return $==="localhost"||$==="127.0.0.1"||$==="::1"||$==="[::1]"}catch{return!1}}var Y4=(O={})=>{let $=new e2,x=O.pickDirectory??(()=>Z4.pick()),J=O.allowDirectoryPickerRequest??$5;return $.get("/",async(Q)=>{return Q.json(await nO.list(c()))}),$.post("/",async(Q)=>{let G;try{G=await Q.req.json()}catch{throw new H("A valid JSON body is required")}let z=y(O5,G);if(!z.success)throw new H("A project path is required");try{let F=await nO.bind(z.data.path,c());return Q.json(F,201)}catch(F){throw new H(F instanceof Error?F.message:"Failed to bind project")}}),$.post("/pick",async(Q)=>{if(!J(Q.req.header("Origin")))throw new Q0("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Q.json(await x())}catch(G){throw new H(G instanceof Error?G.message:"Failed to select a folder")}}),$.delete("/",async(Q)=>{let G=Q.req.query("path");if(!G)throw new H("A project path is required");try{let z=await nO.unbind(G);return Q.json({success:!0,removed:z})}catch(z){throw new H(z instanceof Error?z.message:"Failed to unbind project")}}),$};import{Hono as x5}from"hono";var z4=a("Service"),N4=()=>{let O=new x5;return O.get("/",async($)=>{try{let x=await X4();return $.json(x)}catch(x){return z4.error("[ProviderRoutes] Failed to list providers:",x),$.json([])}}),O.get("/:provider/models",async($)=>{let x=$.req.param("provider");try{let J=await V4(x);return $.json(J)}catch(J){return z4.error("[ProviderRoutes] Failed to list models:",J),$.json([])}}),O.put("/:provider/credential",async($)=>{let x=$.req.param("provider"),J=await $.req.json();if(!J.apiKey?.trim())throw new H("apiKey is required");return await c0().setApiKey(x,J.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await c0().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let x=$.req.param("provider"),J=x0(),Q=J?.modelProviders[x];if(!J||!Q)throw new f("Model provider",x);let G=await $.req.json();if(!G.name||!G.baseUrl||!G.wireApi)throw new H("name, baseUrl and wireApi are required");let z="apiKeyEnv"in G?G.apiKeyEnv?.trim():Q.apiKeyEnv,F={name:G.name,baseUrl:G.baseUrl,wireApi:G.wireApi,...z?{apiKeyEnv:z}:{}},T=c0(),B=G.apiKey?.trim()?await T.credentials.read(x):void 0;if(G.apiKey?.trim())await T.setApiKey(x,G.apiKey.trim());try{return await L0().updateModelProvider(x,F),$.json({success:!0})}catch(C){if(G.apiKey?.trim())if(B)await T.credentials.modify(x,async()=>B);else await T.credentials.delete(x);if(C instanceof Error&&(C.message.includes("modelProviders.")||C.message.includes("built-in provider")))throw new H(C.message);throw C}}),O.delete("/:provider",async($)=>{let x=$.req.param("provider");if(!x0()?.modelProviders[x])throw new f("Model provider",x);let Q=$.req.query("removeModels");if(Q!==void 0&&Q!=="true"&&Q!=="false")throw new H("removeModels must be true or false");try{let G=await L0().removeModelProvider(x,{removeModels:Q==="true"});return $.json({success:!0,...G})}catch(G){if(G instanceof Error&&(G.message.includes("still referenced")||G.message.includes("owns the only model")))throw new q(G.message);throw G}}),O.post("/:provider/probe",async($)=>{let x=$.req.param("provider"),J=x0();if(!J?.modelProviders[x])throw new f("Model provider",x);let Q=await $.req.json().catch(()=>({})),G=J.models.filter((F)=>F.provider===x),z=Q.modelId?G.find((F)=>F.id===Q.modelId):G[0];if(!z)throw new H(Q.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return $.json(await G4(z,J))}),O};import{Hono as J5}from"hono";var Q5=a("Service"),U4=(O,$)=>{let x=new J5;return x.onError((J,Q)=>{if(J instanceof Q0)return Q.json(J.toObject(),J.statusCode);return Q5.error("[ScheduleRoutes] Unhandled route error:",J),Q.json(new r("Schedule request failed").toObject(),500)}),x.get("/",async(J)=>{let Q=await O.list();return J.json(F4.parse({schedules:Q}))}),x.post("/",async(J)=>{let Q;try{Q=await J.req.json()}catch{throw new H("Invalid request body")}let G=y(K4,Q);if(!G.success)throw new H("Invalid schedule request");let z=G.data.projectPath||J.get("directory")||c();try{let F=await O.create({...G.data,projectPath:z});return J.json(t0.parse(F),201)}catch(F){throw new H(F instanceof Error?F.message:"Failed to create schedule")}}),x.get("/:id",async(J)=>{let Q=await O.get(J.req.param("id"));if(!Q)throw new f("Schedule not found");return J.json(t0.parse(Q))}),x.patch("/:id",async(J)=>{let Q;try{Q=await J.req.json()}catch{throw new H("Invalid request body")}let G=y(W4,Q);if(!G.success)throw new H("Invalid schedule update");let{modelId:z,reasoningEffort:F,serviceTier:T,responseVerbosity:B,communicationStyle:C,isolation:w,permissionMode:W,...I}=G.data,J0={...z!==void 0?{modelId:z}:{},...F!==void 0?{reasoningEffort:F}:{},...T!==void 0?{serviceTier:T}:{},...B!==void 0?{responseVerbosity:B}:{},...C!==void 0?{communicationStyle:C}:{},...w!==void 0?{isolation:w}:{},...W!==void 0?{permissionMode:W}:{}};try{let p=await O.update(J.req.param("id"),{...I,...Object.keys(J0).length>0?{dispatch:J0}:{}});if(!p)throw new f("Schedule not found");return J.json(t0.parse(p))}catch(p){if(p instanceof Q0)throw p;throw new H(p instanceof Error?p.message:"Failed to update schedule")}}),x.delete("/:id",async(J)=>{if(!await O.remove(J.req.param("id")))throw new f("Schedule not found");return J.json({ok:!0})}),x.post("/:id/enable",async(J)=>{let Q=await O.setEnabled(J.req.param("id"),!0);if(!Q)throw new f("Schedule not found");return J.json(t0.parse(Q))}),x.post("/:id/disable",async(J)=>{let Q=await O.setEnabled(J.req.param("id"),!1);if(!Q)throw new f("Schedule not found");return J.json(t0.parse(Q))}),x.post("/:id/run",async(J)=>{let Q=await O.get(J.req.param("id"));if(!Q)throw new f("Schedule not found");if(!$)throw new r("Scheduler is not running in this process");await $.fire(Q,new Date,{manual:!0});let G=await O.get(Q.id);return J.json(t0.parse(G??Q),202)}),x};import*as g0 from"node:fs/promises";import{homedir as H4}from"node:os";import*as A0 from"node:path";import{Hono as Z5}from"hono";var s0=a("Service"),_4=A0.join(H4(),".blade","skills"),M$=A0.join(H4(),".blade","skills-config.json");async function B4(){try{let O=await g0.readFile(M$,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function Y5(O){await g0.mkdir(A0.dirname(M$),{recursive:!0}),await g0.writeFile(M$,JSON.stringify(O,null,2))}async function z5(O,$){let x=await B4();if($)x.disabled=x.disabled.filter((J)=>J!==O);else if(!x.disabled.includes(O))x.disabled.push(O);await Y5(x)}var h0=null,G5=300000,X5=6;async function V5(){if(h0&&Date.now()-h0.timestamp<G5)return h0.data;try{let O=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!O.ok){if(s0.warn(`GitHub API returned ${O.status}`),h0)return h0.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let x=(await O.json()).filter((z)=>z.type==="dir"),J=Array(x.length),Q=0,G=Math.min(X5,x.length);return await Promise.all(Array.from({length:G},async()=>{while(Q<x.length){let z=Q++,F=x[z];if(!F)continue;let T=`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 w=(await B.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(w)T=w[1].trim().slice(0,100)}}catch{}J[z]={name:F.name,description:T,tag:"Official",author:"Anthropic"}}})),h0={data:J,timestamp:Date.now()},J}catch(O){if(s0.warn("Failed to fetch skills catalog from GitHub:",O),h0)return h0.data;throw O}}var L4=()=>{let O=new Z5;return O.get("/",async($)=>{try{let x=$.get("directory")||c(),Q=(await T0(x)).skills.getAll(),G=await B4(),z=Q.map((F)=>({id:F.name,name:F.name,enabled:!G.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"&&A0.dirname(A0.resolve(F.basePath))===A0.resolve(_4),capabilities:["prompts"],allowedTools:F.allowedTools||[]}));return $.json(z)}catch(x){return s0.error("[SkillsRoutes] Failed to get skills:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async($)=>{try{let x=$.req.param("name"),J=await $.req.json();return await z5(x,J.enabled),$.json({success:!0,enabled:J.enabled})}catch(x){return s0.error("[SkillsRoutes] Failed to toggle skill:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name"),J=$.get("directory")||c();return AO(J,async(Q)=>{let G=Q.skills,z=G.get(x);if(!z)return $.json({success:!1,error:"Skill not found"},404);let F=A0.resolve(z.basePath),T=A0.resolve(_4);if(z.source!=="user"||A0.dirname(F)!==T)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await g0.rm(F,{recursive:!0,force:!0}),await G.refresh(),MO(J),await wO(J),$.json({success:!0})})}catch(x){return s0.error("[SkillsRoutes] Failed to uninstall skill:",x),$.json({success:!1,error:x.message},500)}}),O.post("/install",async($)=>{try{let x=await $.req.json(),J=D4(),Q=$.get("directory")||c();return AO(Q,async(G)=>{let z=G.skills,F=!1;if(x.source==="catalog"&&x.name){if(F=await J.installOfficialSkill(x.name),!F)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(F=await J.installFromRepo(x.url,x.name),!F)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(x.source==="local"&&x.path){if(F=await J.installFromLocal(x.path,x.name),!F)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await z.refresh(),MO(Q),await wO(Q),$.json({success:!0})})}catch(x){return s0.error("[SkillsRoutes] Failed to install skill:",x),$.json({success:!1,error:x.message},500)}}),O.get("/catalog",async($)=>{try{let x=await V5();return $.json(x)}catch(x){return s0.error("[SkillsRoutes] Failed to get catalog:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills catalog"},502)}}),O};import{execSync as N5}from"node:child_process";import{readdir as K5}from"node:fs/promises";import tO from"node:path";import W5 from"fast-glob";import{Hono as F5}from"hono";var SO=a("Service"),U5=(O)=>{try{return N5("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},_5=[...XO.map((O)=>`${O}/**`),...XO,...XO.map((O)=>`**/${O}/**`),...XO.map((O)=>`**/${O}`),...A$.map((O)=>`**/${O}`)],D5=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),A4=()=>{let O=new F5;return O.get("/commands",async($)=>{try{let x=$.req.query("q")||"",J=$.get("directory")||c(),Q=await T0(J),G=M4(x,J,Q).filter((z)=>!D5.has(z.command));return $.json(G)}catch(x){return SO.error("[SuggestionsRoutes] Failed to get command suggestions:",x),$.json([])}}),O.get("/files",async($)=>{try{let x=$.req.query("q")||"",J=$.get("directory")||c(),Q=Math.min(Number($.req.query("limit"))||100,1000),G=$.req.query("type")==="file",F=(await W5("**/*",{cwd:J,dot:!1,followSymbolicLinks:!1,onlyFiles:G,markDirectories:!0,unique:!0,ignore:_5})).map((C)=>C.replace(/\\/g,"/"));if(!x)return $.json(F.slice(0,Q));let T=x.toLowerCase(),B=F.filter((C)=>C.toLowerCase().includes(T)).slice(0,Q);return $.json(B)}catch(x){return SO.error("[SuggestionsRoutes] Failed to get file suggestions:",x),$.json([])}}),O.get("/files/tree",async($)=>{try{let x=$.get("directory")||c(),J=$.req.query("path")||"",Q=J?tO.join(x,J):x,z=(await K5(Q,{withFileTypes:!0})).map((B)=>({name:B.name,path:J?`${J}/${B.name}`:B.name,type:B.isDirectory()?"dir":"file"}));z.sort((B,C)=>{if(B.type!==C.type)return B.type==="dir"?-1:1;return B.name.localeCompare(C.name)});let F=new Set(XO),T=z.filter((B)=>{let C=B.name;if(C.startsWith("."))return!1;if(F.has(C))return!1;for(let w of A$)if(C.match(new RegExp(w.replace("*",".*"))))return!1;return!0});return $.json(T)}catch(x){return SO.error("[SuggestionsRoutes] Failed to get file tree:",x),$.json([])}}),O.get("/files/content",async($)=>{try{let x=$.req.query("path");if(!x)return $.json({error:"Missing file path"},400);let J=$.get("directory")||c(),Q=tO.resolve(J,x),G=tO.relative(J,Q);if(G.startsWith("..")||tO.isAbsolute(G))return $.json({error:"Invalid file path"},400);let z=w4(),F=await z.stat(Q);if(!F?.isFile)return $.json({error:"File not found"},404);let T=200000,B=await z.readTextFile(Q),C=B.length>T;return $.json({path:x,content:C?B.slice(0,T):B,truncated:C,size:F.size})}catch(x){return SO.error("[SuggestionsRoutes] Failed to get file content:",x),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{try{let x=$.get("directory")||c(),J=U5(x);return $.json({branch:J})}catch(x){return SO.error("[SuggestionsRoutes] Failed to get git info:",x),$.json({branch:null})}}),O};import{Hono as H5}from"hono";var VO=a("Service"),R4=(O)=>{let $=new H5;return $.onError((x,J)=>{if(x instanceof Q0)return J.json(x.toObject(),x.statusCode);return VO.error("[TaskRoutes] Unhandled route error:",x),J.json(new r("Failed to dispatch task").toObject(),500)}),$.post("/",async(x)=>{let J;try{J=await x.req.json()}catch{throw new H("Invalid request body")}let Q=y(T4,J);if(!Q.success)throw new H("Invalid task request");if((Q.data.attachments??[]).reduce((z,F)=>z+(typeof F.content==="string"?Buffer.byteLength(F.content):0),0)>aO)throw new H("Task attachments exceed the 5 MiB limit");if(Q.data.taskDueAt&&!Number.isFinite(Date.parse(Q.data.taskDueAt)))throw new H("Invalid task due date");try{let z=await O.dispatchTask({prompt:Q.data.prompt,title:Q.data.title,taskPriority:Q.data.taskPriority,taskKind:Q.data.taskKind,taskDueAt:Q.data.taskDueAt?new Date(Q.data.taskDueAt).toISOString():void 0,sourceProjectPath:Q.data.projectPath||x.get("directory")||c(),isolation:Q.data.isolation,permissionMode:Q.data.permissionMode,modelId:Q.data.modelId,reasoningEffort:Q.data.reasoningEffort,serviceTier:Q.data.serviceTier,responseVerbosity:Q.data.responseVerbosity,communicationStyle:Q.data.communicationStyle,attachments:Q.data.attachments,outputSchema:Q.data.outputSchema});return x.json(T$.parse(z),202)}catch(z){if(z instanceof H||z instanceof q||z instanceof l0||z instanceof k0)throw z;throw VO.error("[TaskRoutes] Failed to dispatch task:",z),new r("Failed to dispatch task")}}),$.patch("/:sessionId",async(x)=>{let J;try{J=await x.req.json()}catch{throw new H("Invalid request body")}let Q=y(C4,J);if(!Q.success)throw new H("Invalid task update");if(Q.data.title===void 0&&Q.data.taskPriority===void 0&&Q.data.taskKind===void 0&&Q.data.taskDueAt===void 0)throw new H("Task update must include at least one field");if(typeof Q.data.taskDueAt==="string"&&!Number.isFinite(Date.parse(Q.data.taskDueAt)))throw new H("Invalid task due date");try{let G=await O.updateTask(x.req.param("sessionId"),{...Q.data,...typeof Q.data.taskDueAt==="string"?{taskDueAt:new Date(Q.data.taskDueAt).toISOString()}:{}},x.req.query("projectPath"));return x.json(j$.parse(G))}catch(G){if(G instanceof H||G instanceof f||G instanceof q)throw G;throw VO.error("[TaskRoutes] Failed to update task:",G),new r("Failed to update task")}}),$.post("/:sessionId/retry",async(x)=>{try{let J=await O.retryTask(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(T$.parse(J),202)}catch(J){if(J instanceof H||J instanceof f||J instanceof q||J instanceof l0||J instanceof k0)throw J;throw VO.error("[TaskRoutes] Failed to retry task:",J),new r("Failed to retry task")}}),$.get("/:sessionId/diff",async(x)=>{try{let J=await O.getTaskDiff(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(j4.parse(J))}catch(J){if(J instanceof H||J instanceof f||J instanceof q)throw J;throw VO.error("[TaskRoutes] Failed to load task diff:",J),new r("Failed to load task diff")}}),$.post("/:sessionId/delivery",async(x)=>{let J;try{J=await x.req.json()}catch{throw new H("Invalid request body")}let Q=y(b4,J);if(!Q.success)throw new H("Invalid task delivery request");try{let G=await O.deliverTask(x.req.param("sessionId"),Q.data.action,x.req.query("projectPath"));return x.json(j$.parse(G))}catch(G){if(G instanceof H||G instanceof f||G instanceof q)throw G;throw VO.error("[TaskRoutes] Failed to deliver task:",G),new r("Failed to deliver task")}}),$};import{Hono as B5}from"hono";var v0=a("Service"),NO=new Map,E4=2097152,q4=65536;function k4(){return typeof globalThis.Bun<"u"}async function L5(O,$,x){if(k4()){let{spawn:G}=await import("bun-pty"),z=G(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:z.pid,write:(F)=>z.write(F),resize:(F,T)=>z.resize(F,T),kill:()=>z.kill(),onData:(F)=>z.onData(F),onExit:(F)=>z.onExit(F)}}let Q=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:Q.pid,write:(G)=>Q.write(G),resize:(G,z)=>Q.resize(G,z),kill:()=>Q.kill(),onData:(G)=>{Q.onData(G)},onExit:(G)=>{Q.onExit(G)}}}var R$=void 0,b$;if(k4())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();b$=$.upgradeWebSocket,R$=$.websocket}catch(O){v0.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function I4(O,$){let x=`term-${Date.now()}`;v0.info(`[Terminal] New connection: ${x}, cwd: ${O}`);let J=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Q=J.endsWith("sh")?["-l"]:[],G=await L5(J,Q,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),z={id:x,process:G,cwd:O,buffer:"",subscribers:new Set};if(NO.set(x,z),z.subscribers.add($),G.onData((F)=>{let T=!1;for(let B of z.subscribers)try{B.send(F),T=!0}catch{z.subscribers.delete(B)}if(T)return;if(z.buffer+=F,z.buffer.length>E4)z.buffer=z.buffer.slice(-E4)}),G.onExit(({exitCode:F})=>{v0.info(`[Terminal] Process exited: ${x}, code: ${F}`);for(let T of z.subscribers)try{T.close()}catch{}NO.delete(x)}),z.buffer){let F=z.buffer;z.buffer="";for(let T=0;T<F.length;T+=q4)$.send(F.slice(T,T+q4))}return{session:z,cleanup:()=>{if(v0.info(`[Terminal] Connection closed: ${x}`),z.subscribers.delete($),z.subscribers.size===0){try{z.process.kill()}catch{}NO.delete(x)}}}}function S4(O,$){O.on("connection",async(x,J)=>{let Q=new URL(J.url||"/",`http://${J.headers.host}`);if(!Q.pathname.endsWith("/terminal/ws")){x.close();return}let G=Q.searchParams.get("cwd")||$()||c();try{let{session:z,cleanup:F}=await I4(G,{send:(T)=>x.send(T),close:()=>x.close()});x.on("message",(T)=>{try{z.process.write(String(T))}catch(B){v0.error("[Terminal] Failed to write to PTY:",B)}}),x.on("close",F),x.on("error",F)}catch(z){v0.error("[Terminal] Failed to spawn PTY:",z),x.close()}})}var P4=()=>{let O=new B5;if(O.get("/status",($)=>{let x=Array.from(NO.values()).map((J)=>({id:J.id,cwd:J.cwd}));return $.json({active:x.length,terminals:x})}),O.post("/kill/:terminalId",($)=>{let x=$.req.param("terminalId"),J=NO.get(x);if(J){try{J.process.kill()}catch{}for(let Q of J.subscribers)Q.close();return NO.delete(x),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),b$)O.get("/ws",b$(($)=>{let x=$.req.query("cwd")||$.get("directory")||c(),J;return{async onOpen(Q,G){try{J=await I4(x,{send:(z)=>G.send(z),close:()=>G.close()})}catch(z){v0.error("[Terminal] Failed to spawn PTY:",z),G.close()}},onMessage(Q){if(!J)return;try{J.session.process.write(String(Q.data))}catch(G){v0.error("[Terminal] Failed to write to PTY:",G)}},onClose(){J?.cleanup()}}}));else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import w5 from"node:path";import{Hono as M5}from"hono";var A5=U.Object({projectPath:U.String({minLength:1}),action:F0(["trust","revoke"])});function f4(O){if(!w5.isAbsolute(O))throw new H("projectPath must be absolute")}var m4=()=>{let O=new M5;return O.get("/",async($)=>{let x=$.req.query("projectPath");if(!x)throw new H("projectPath query parameter is required");return f4(x),$.json(await E$.getInstance().getStatus(x))}),O.post("/",async($)=>{let x=y(A5,await $.req.json());if(!x.success)throw new H("Invalid workspace trust request");let{projectPath:J,action:Q}=x.data;f4(J);let G=E$.getInstance(),z=Q==="trust"?await G.trust(J):await G.revoke(J);return await y4(),$.json({...z,reloadRequired:z.sensitiveSources>0})}),O};var W0=a("Service"),I$=[],sO,KO,WO,PO,h4=new Map,g4=new Map,f5=new Set([".css",".html",".js",".json",".svg"]),y5=1024,m5=3600000;function h5(O,$){if(!O)return 0;let x=O.split(",").map((J)=>{let[Q,...G]=J.trim().toLowerCase().split(";"),z=G.find((T)=>T.trim().startsWith("q=")),F=z?Number(z.trim().slice(2)):1;return{name:Q,quality:Number.isFinite(F)?Math.max(0,Math.min(1,F)):0}});return x.find((J)=>J.name===$)?.quality??x.find((J)=>J.name==="*")?.quality??0}function v4(){if(WO)return;let O=()=>{E.collectStaleEmptySessions().then(($)=>{if($>0)W0.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{W0.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),WO=setInterval(O,m5),WO.unref?.()}function g5(){if(!WO)return;clearInterval(WO),WO=void 0}function v5(O){return["br","gzip"].map((x)=>({encoding:x,quality:h5(O,x)})).filter((x)=>x.quality>0).sort((x,J)=>J.quality-x.quality||(x.encoding==="br"?-1:1))[0]?.encoding}function u5(O){let $=h4.get(O);if($)return $;let x=fO(O);return h4.set(O,x),x}function p5(O,$,x){let J=`${x}:${O}`,Q=g4.get(J);if(Q)return Q;let G=x==="br"?E5($,{params:{[k5.BROTLI_PARAM_QUALITY]:5}}):q5($,{level:6});return g4.set(J,G),G}function d5(){let O=C5(R5(import.meta.url)),$=[u0(O,"web"),u0(c(),"dist/web"),u0(c(),"packages/cli/dist/web")];for(let x of $){let J=u0(x,"index.html");if(k$(J)){if(fO(J,"utf-8").includes("/assets/"))return W0.debug(`[Server] Found web dist at: ${x}`),x}}return null}function l5(){let O=new I5;O.onError((J,Q)=>{if(W0.error("[Server] Request error:",J),J instanceof d4){let z=new k0(J.message,{resource:"workspace_agent_resources",limit:J.capacity});return Q.json(z.toObject(),429)}if(J instanceof Q0)return Q.json(J.toObject(),J.statusCode);let G=J instanceof Error?J.message:String(J);return Q.json({error:{code:"INTERNAL_ERROR",message:G}},500)}),O.use(async(J,Q)=>{let G=process.env.BLADE_SERVER_PASSWORD;if(!G)return Q();let z=J.req.path;if(z==="/"||z==="/favicon.svg"||z.startsWith("/assets/")||z.endsWith(".html")||z.endsWith(".js")||z.endsWith(".css"))return Q();let F=J.req.header("Authorization");if(!F?.startsWith("Basic "))return J.header("WWW-Authenticate",'Basic realm="Blade Server"'),J.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let T=Buffer.from(F.slice(6),"base64").toString(),[B,C]=T.split(":"),w=process.env.BLADE_SERVER_USERNAME??"blade";if(B!==w||C!==G)return J.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Q()}),O.use(async(J,Q)=>{let G=J.req.path==="/health"||J.req.path==="/global/health"||J.req.path.startsWith("/assets/");if(!G)W0.debug(`[Server] ${J.req.method} ${J.req.path}`);let z=Date.now();if(await Q(),!G){let F=Date.now()-z;W0.debug(`[Server] ${J.req.method} ${J.req.path} - ${J.res.status} (${F}ms)`)}}),O.use(S5({origin(J){if(!J)return;if(J.startsWith("http://localhost:"))return J;if(J.startsWith("http://127.0.0.1:"))return J;if(J==="tauri://localhost"||J==="http://tauri.localhost")return J;if(I$.includes(J))return J;return}})),O.use(async(J,Q)=>{let G=J.req.query("directory")||J.req.header("x-blade-directory")||c();try{G=decodeURIComponent(G)}catch{}return J.set("directory",G),Q()});let $=u1();PO=$,sO=$.recoverQueuedTasks,KO=new J$({dispatch:(J)=>$.dispatchTask(J),store:q$}),O.route("/global",t$()),O.route("/events",o$()),O.route("/sessions",$.app),O.route("/tasks",R4($)),O.route("/schedules",U4(q$,KO)),O.route("/configs",p$()),O.route("/permissions",d1()),O.route("/plugins",J4()),O.route("/hooks",x1()),O.route("/workspace-trust",m4()),O.route("/providers",N4()),O.route("/models",N1()),O.route("/projects",Y4()),O.route("/suggestions",A4()),O.route("/terminal",P4()),O.route("/mcp",Z1()),O.route("/skills",L4()),O.get("/health",(J)=>{return J.json({healthy:!0,version:$O()})});let x=d5();if(x)W0.info(`[Server] Serving static files from ${x}`),O.get("/favicon.svg",()=>{let J=u0(x,"favicon.svg");if(!k$(J))return new Response(null,{status:404});return new Response(fO(J),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(J)=>{let Q=u0(x,J.req.path);if(!k$(Q))return J.json({error:{code:"NOT_FOUND",message:`File not found: ${J.req.path}`}},404);let G=u5(Q),z=b5(Q).toLowerCase(),T={".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"}[z]||"application/octet-stream",B=f5.has(z)&&G.byteLength>=y5?v5(J.req.header("Accept-Encoding")):void 0,C=B?p5(Q,G,B):G;return new Response(new Uint8Array(C),{headers:{"Content-Type":T,"Content-Length":String(C.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...B?{"Content-Encoding":B}:{}}})}),O.get("/",(J)=>{let Q=u0(x,"index.html"),G=fO(Q,"utf-8");return J.html(G,200,{"Cache-Control":"no-cache"})}),O.get("*",(J)=>{let Q=J.req.path;if(Q.includes("."))return J.json({error:{code:"NOT_FOUND",message:`File not found: ${Q}`}},404);let G=u0(x,"index.html"),z=fO(G,"utf-8");return J.html(z,200,{"Cache-Control":"no-cache"})});else W0.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(J)=>{return J.json({message:"Blade API Server",version:$O(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),O.all("*",(J)=>{return J.json({error:{code:"NOT_FOUND",message:`Route not found: ${J.req.path}`}},404)});return O}function c5(){let O=T5(),$=[];for(let x of Object.keys(O)){let J=O[x];if(!J)continue;for(let Q of J){if(Q.internal||Q.family!=="IPv4")continue;if(Q.address.startsWith("172."))continue;$.push(Q.address)}}return $}function u4(){return typeof globalThis.Bun<"u"}function p4(O,$){let x=globalThis.Bun,J=(G)=>{try{return x.serve({hostname:$.hostname,port:G,fetch:O.fetch,idleTimeout:0,websocket:R$})}catch(z){W0.error("Failed to start Bun server:",z);return}},Q=$.port===0?J(4096)??J(0):J($.port);if(!Q)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{Q.stop(!0)}}}function i5(O,$){return new Promise((x,J)=>{let Q=j5(async(B,C)=>{let w=new URL(B.url||"/",`http://${B.headers.host}`),W=new Headers;for(let[p,b]of Object.entries(B.headers))if(b)if(Array.isArray(b))for(let e of b)W.append(p,e);else W.set(p,b);let I;if(B.method!=="GET"&&B.method!=="HEAD")I=(await new Promise((b)=>{let e=[];B.on("data",(v)=>e.push(v)),B.on("end",()=>b(Buffer.concat(e)))})).toString();let J0=new Request(w.toString(),{method:B.method,headers:W,body:I});try{let p=await O.fetch(J0);if(C.statusCode=p.status,p.headers.forEach((b,e)=>{C.setHeader(e,b)}),p.body){let b=p.body.getReader(),e=async()=>{let{done:v,value:Z0}=await b.read();if(v){C.end();return}return C.write(Z0),e()};await e()}else{let b=await p.text();C.end(b)}}catch(p){W0.error("[Server] Node request error:",p),C.statusCode=500,C.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),G=new P5({noServer:!0}),z=c();S4(G,()=>z),Q.on("upgrade",(B,C,w)=>{if(new URL(B.url||"/",`http://${B.headers.host}`).pathname==="/terminal/ws")G.handleUpgrade(B,C,w,(I)=>{G.emit("connection",I,B)});else C.destroy()});let F=(B)=>{return new Promise((C,w)=>{Q.once("error",(W)=>{if(W.code==="EADDRINUSE")w(W);else w(W)}),Q.listen(B,$.hostname,()=>{let W=Q.address();if(W&&typeof W==="object")C(W.port);else C(B)})})};(async()=>{let B;if($.port===0)try{B=await F(4096)}catch{B=await F(0)}else B=await F($.port);let C=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${B}`);x({url:C,port:B,hostname:$.hostname,stop:async()=>{return new Promise((w)=>{G.close(()=>{Q.close(()=>w())})})}})})().catch(J)})}var c4;((V6)=>{let O,$,x,J=(B,C)=>{if(O!==B)return Promise.resolve();if(x)return x;let w=C?.shutdown("server-shutdown");return KO?.stop(),g5(),x=(async()=>{let W,I=async(J0)=>{if(!J0)return;try{await J0()}catch(p){W??=p}};if(await I(()=>B.stop()),await I(w?()=>w:void 0),l4(),O===B)O=void 0,$=void 0,PO=void 0,sO=void 0,KO=void 0;if(W0.info("[Server] Blade server stopped"),W!==void 0)throw W})(),x};function Q(){if(!$)$=l5();return $}V6.getApp=Q;function G(B){I$=B.cors??[];let C=Q();if(u4())O=p4(C,B),x=void 0,W0.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let w=O,W=PO;return sO?.().catch((I)=>{W0.warn("[Server] Failed to recover queued tasks:",I)}),KO?.start(),v4(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>J(w,W)}}V6.listen=G;async function z(B){I$=B.cors??[];let C=Q();if(u4())O=p4(C,B),W0.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await i5(C,B),W0.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);x=void 0;let w=O,W=PO;try{await sO?.()}catch(I){W0.warn("[Server] Failed to recover queued tasks:",I)}return KO?.start(),v4(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>J(w,W)}}V6.listenAsync=z;function F(){return O!==void 0}V6.isRunning=F;function T(){return PO?.getCoordinationStats()}V6.getSessionCoordinationStatsForTests=T})(c4||={});export{a5 as f,o5 as g,c5 as h,c4 as i};
6
+ `,Buffer.byteLength($)}class HO{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??l$,this.maxPendingBytes=O.maxPendingBytes??c$,this.serial=new a$({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??i$,sizeOf:d$,write:O.write,onFailure:($)=>{this.failure=$,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,O.onFailure?.($)}})}async writeInitial(O){await this.offerDirect(O)}observe(O,$){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer(O,$);return}this.offerLive(O,$)}async writeReplay(O,$){if(!Number.isSafeInteger($)||$<=0)throw this.fail(new OO("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if($<=this.highestReplaySequence)return;await this.offerDirect(O),this.highestReplaySequence=$,this.highestDeliveredSequence=$}finishInitialization(O){if(this.phase!=="buffering")return;let $=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let x=O.replayed?$.filter((Q)=>Q.sequence!==void 0&&Q.sequence>this.highestReplaySequence).sort((Q,G)=>Q.sequence-G.sequence||Q.order-G.order):$.sort((Q,G)=>Q.order-G.order),J;for(let Q of x){if(O.replayed&&Q.sequence!==void 0&&Q.sequence===J)continue;if(this.offerLive(Q.message,Q.sequence),this.serial.stats().closed)return;J=Q.sequence}}offerHeartbeat(O){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive(O),!this.serial.stats().closed}async flush(){await this.serial.flush()}close(O){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close(O)}stats(){let O=this.serial.stats();return{closed:this.phase==="closed",pendingItems:O.pendingItems+this.buffered.length,pendingBytes:O.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer(O,$){let x=d$(O),J=this.serial.stats();if(x>this.maxPendingBytes){this.fail(new OO("oversized",`SSE frame requires ${x} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}if(J.pendingItems+this.buffered.length>=this.maxPendingItems||J.pendingBytes+this.bufferedBytes+x>this.maxPendingBytes){this.fail(new OO("overflow","SSE initialization buffer limit exceeded",{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:x,sequence:$,order:this.nextOrder}),this.bufferedBytes+=x}offerLive(O,$){if($!==void 0){if($<=this.highestReplaySequence)return;if($<=this.highestDeliveredSequence){this.fail(new OO("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=$}if(!this.serial.offer(O).accepted)this.phase="closed"}async offerDirect(O){if(this.phase==="closed")throw this.currentFailure();let $=this.serial.offer(O);if(!$.accepted)throw this.phase="closed",$.error;await $.completion}fail(O){this.serial.close(O)}currentFailure(){return this.failure??new OO("closed","SSE egress is closed")}}var x2=15000,J2=a("Service"),Q2=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),Z2=new Set(["queued","running","completed","failed","cancelled","interrupted"]),Y2=new Set(["high","medium","low"]),z2=new Set(["feature","bug","maintenance","research"]);function G2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=["changedFiles","additions","deletions","commits"];if(x.some((J)=>typeof $[J]!=="number"||!Number.isInteger($[J])||$[J]<0))return;return Object.fromEntries(x.map((J)=>[J,$[J]]))}function BO(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function X2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if(!["applied","discarded","conflicted"].includes(String($.status))||typeof $.updatedAt!=="string")return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},...BO($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}var o$=()=>{let O=new O2;return O.get("/",($)=>$2($,async(x)=>{let J,Q,G=!1,z,F,T=new Promise((W)=>{F=W}),B=()=>{if(Q!==void 0)clearInterval(Q),Q=void 0;J?.(),J=void 0},C=(W)=>{if(G)return;G=!0,B(),z?.close(W),F()};x.onAbort(C),z=new HO({write:async(W)=>{await x.writeSSE(W)},onFailure:(W)=>{J2.warn(`[EventRoutes] SSE egress closed: kind=${W.kind} pendingItems=${W.pendingItems??0} pendingBytes=${W.pendingBytes??0}`),C(W)}});let w=(W,I)=>{z?.observe({data:JSON.stringify({type:W,properties:I})})};J=R.subscribe((W)=>{if(!Q2.has(W.type))return;if(W.type==="permission.asked"||W.type==="question.required"||W.type==="elicitation.required"){let i=W.properties.requestId;if(typeof i!=="string"||!i)return;w("interaction.pending",{sessionId:W.sessionId,projectPath:W.projectPath,interactionType:W.type==="question.required"?"question":W.type==="elicitation.required"?"elicitation":"permission",requestId:i});return}if(W.type==="interaction.resolved"){let i=W.properties.requestId;if(typeof i!=="string"||!i)return;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,requestId:i});return}if(W.type==="session.created"||W.type==="session.deleted"){w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath});return}if(W.type==="session.updated"){let i=W.properties.title,$0=W.properties.taskPriority,S0=W.properties.taskKind,o=W.properties.taskDueAt,p0=typeof i==="string"&&Boolean(i.trim()),w0=Y2.has(String($0)),N=z2.has(String(S0)),V0=o===null||typeof o==="string"&&Number.isFinite(Date.parse(o));if(!p0&&!w0&&!N&&!V0)return;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,...p0?{title:i}:{},...w0?{taskPriority:$0}:{},...N?{taskKind:S0}:{},...V0?{taskDueAt:o}:{}});return}if(W.type==="task.delivery"){let i=X2(W.properties.taskDelivery);if(!i)return;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,taskDelivery:i,...W.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{}});return}if(W.type==="schedule.fired"){let i=W.properties.scheduleId,$0=W.properties.firedAt;if(typeof i!=="string"||typeof $0!=="string")return;w(W.type,{scheduleId:i,firedAt:$0,sessionId:W.sessionId,projectPath:W.projectPath,...typeof W.properties.runId==="string"?{runId:W.properties.runId}:{},...typeof W.properties.status==="string"?{status:W.properties.status}:{}});return}let I=W.properties.taskStatus;if(typeof I!=="string"||!Z2.has(I))return;let J0=G2(W.properties.taskDiffStat),p=BO(W.properties.taskQueuePosition,1),b=BO(W.properties.taskQueueDepth,0),e=BO(W.properties.taskConcurrencyLimit,1),h=BO(W.properties.taskInFlight,0),Z0=typeof W.properties.taskAdmissionPaused==="boolean"?W.properties.taskAdmissionPaused:void 0;w(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,taskStatus:I,...typeof W.properties.taskStatusReason==="string"?{taskStatusReason:W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{taskFailure:W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{taskStartedAt:W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{taskCompletedAt:W.properties.taskCompletedAt}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{},...J0?{taskDiffStat:J0}:{},...p!==void 0?{taskQueuePosition:p}:{},...b!==void 0?{taskQueueDepth:b}:{},...e!==void 0?{taskConcurrencyLimit:e}:{},...h!==void 0?{taskInFlight:h}:{},...Z0!==void 0?{taskAdmissionPaused:Z0}:{}})});try{if(x.aborted||G)return;if(await z.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),x.aborted||G)return;if(z.finishInitialization({replayed:!1}),x.aborted||G)return;Q=setInterval(()=>{if(x.aborted||G)return;z?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},x2),await T}finally{C()}})),O};import{Hono as V2}from"hono";var N2=U.Object({paused:U.Boolean()}),t$=()=>{let O=new V2;return O.get("/health",($)=>{return $.json({healthy:!0,version:$O()})}),O.get("/info",($)=>{let x=c(),J=x0();if(J)f0.configure(J.maxConcurrentTasks,J.maxQueuedTasks,J.maxQueuedTaskBytes);let Q=f0.getStats();return $.json({version:$O(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:x,gitBranch:n$(x),taskAdmission:{inFlight:Q.inFlight,queued:Q.queued,maxConcurrent:Q.maxConcurrent,maxQueued:Q.maxQueued,paused:Q.paused}})}),O.put("/task-admission",async($)=>{let x;try{x=await $.req.json()}catch{throw new H("Invalid request body")}let J=f(N2,x);if(!J.success)throw new H("Invalid task admission control request");f0.setPaused(J.data.paused);let Q=f0.getStats();return $.json({inFlight:Q.inFlight,queued:Q.queued,maxConcurrent:Q.maxConcurrent,maxQueued:Q.maxQueued,paused:Q.paused})}),O};import s$ from"node:path";import{Hono as K2}from"hono";var W2=U.Object({projectPath:U.String({minLength:1}),action:F0(["trust","revoke"]),expectedDigest:U.Optional(U.String())}),F2=U.Object({projectPath:U.String({minLength:1}),sessionId:U.String({minLength:1}),enabled:U.Boolean()});function Z$(O){if(!O||!s$.isAbsolute(O))throw new H("projectPath must be absolute");return s$.resolve(O)}function r$(O){if(!O)throw new H("sessionId is required");try{uO(O)}catch($){throw new H($ instanceof Error?$.message:"sessionId is invalid")}return O}async function vO(O){let $=Z$(O),x=x0()?.hooks??$1.hooks,J=await LO.getInstance().loadWorkspaceHooks($,x,{includeBaseForCurrentWorkspace:!1});return AO($,async()=>{MO($);let Q=xO.getInstance();return Q.loadConfig(J,$),await wO($),Q.getConfig($)})}function e$(O,$){let x=xO.getInstance(),J=x.getConfig($).enabled,Q=x.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:x.isSessionEnabled(O,$),paused:Q,configEnabled:J}}var x1=()=>{let O=new K2;return O.get("/trust",async($)=>{let x=$.req.query("projectPath");if(!x)throw new H("projectPath query parameter is required");return await vO(x),$.json(await xO.getInstance().getTrustStatus(x))}),O.post("/trust",async($)=>{let x=f(W2,await $.req.json());if(!x.success)throw new H("Invalid hook trust request");let{projectPath:J,action:Q,expectedDigest:G}=x.data;await vO(J);let z=xO.getInstance(),F;try{F=Q==="trust"?await z.trustProject(J,G):await z.revokeProjectTrust(J)}catch(T){if(T instanceof O1)throw new q(T.message);throw T}return $.json(F)}),O.get("/session",async($)=>{let x=Z$($.req.query("projectPath")),J=r$($.req.query("sessionId"));return await vO(x),$.json(e$(J,x))}),O.post("/session",async($)=>{let x=f(F2,await $.req.json());if(!x.success)throw new H("Invalid hook session request");let J=Z$(x.data.projectPath),Q=r$(x.data.sessionId);await vO(J);let G=xO.getInstance();if(x.data.enabled)G.enableSession(Q,J);else G.disableSession(Q,J);return $.json(e$(Q,J))}),O};import{Hono as U2}from"hono";var R0=a("Service");function _2(O){try{return Q1(O)}catch{return[]}}function D2(O){if(!pO(O)||!pO(O.reference)||!pO(O.argument))throw Error("Invalid MCP completion request");let $=O.reference.type,x=$==="prompt"&&typeof O.reference.name==="string"?{type:"prompt",name:O.reference.name}:$==="resource"&&typeof O.reference.uri==="string"?{type:"resource",uri:O.reference.uri}:void 0;if(!x||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let J;if(O.context!==void 0){if(!pO(O.context))throw Error("Invalid MCP completion context");J=Object.create(null);for(let[Q,G]of Object.entries(O.context)){if(typeof G!=="string")throw Error("Invalid MCP completion context");J[Q]=G}}return{reference:x,argument:{name:O.argument.name,value:O.argument.value},...J?{context:J}:{}}}function pO(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function y0(O,$){let x=x0()?.mcpServers??{};for(let[J,Q]of Object.entries(x)){if($&&J!==$)continue;if(!O.getServerStatus(J))await O.registerServer(J,Q,{connect:!1})}}var Z1=()=>{let O=new U2;return O.get("/",async($)=>{try{let x=U0.getInstance();await y0(x);let J=x.getAllServers(),Q=await Promise.all(Array.from(J.entries()).map(async([G,z])=>({id:G,name:G,status:z.status==="connected"?"connected":z.status==="reconnecting"?"reconnecting":z.status==="connecting"?"connecting":z.lastError?"error":"offline",endpoint:z.config.command?`${z.config.command} ${(z.config.args||[]).join(" ")}`.trim():z.config.url||"Unknown",description:`MCP server: ${G}`,tools:z.tools.map((F)=>F.name),completionSupported:z.client.completionSupported,tasks:z.client.tasks,resources:z.contentCatalog.resources,resourceTemplates:z.contentCatalog.resourceTemplates.map((F)=>({...F,variables:_2(F.uriTemplate)})),prompts:z.contentCatalog.prompts,connectedAt:z.connectedAt?.toISOString(),error:z.lastError?.message,recovery:z.recovery,logging:z.logging,instructions:z.instructions,oauthEnabled:z.client.oauthEnabled,oauthStatus:await z.client.getOAuthStatus()})));return $.json(Q)}catch(x){return R0.error("[McpRoutes] Failed to get MCP servers:",x),$.json({error:x instanceof Error?x.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();return await y0(J,x),await J.connectServer(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to connect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();return await y0(J,x),await J.disconnectServer(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to disconnect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.get("/:name/logs",async($)=>{try{let x=$.req.param("name"),J=Number($.req.query("limit")??20),Q=Number($.req.query("afterRevision")??0);if(!Number.isSafeInteger(J)||J<1||J>100||!Number.isSafeInteger(Q)||Q<0)return $.json({error:"Invalid MCP log pagination"},400);let G=U0.getInstance();return await y0(G,x),$.json(G.getLogSnapshot(x,{limit:J,afterRevision:Q}))}catch(x){return R0.error("[McpRoutes] Failed to get MCP logs:",x),$.json({error:x.message},500)}}),O.post("/:name/logging-level",async($)=>{try{let x=$.req.param("name"),J=await $.req.json();if(!J1(J.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let Q=U0.getInstance();return await y0(Q,x),await Q.setServerLoggingLevel(x,J.level),$.json({success:!0,level:J.level})}catch(x){return R0.error("[McpRoutes] Failed to set MCP logging level:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/complete",async($)=>{try{let x=$.req.param("name"),J=D2(await $.req.json()),Q=U0.getInstance();await y0(Q,x);let G=await Q.complete(x,J);return $.json(G)}catch(x){return R0.error("[McpRoutes] Failed to complete MCP argument:",x),$.json({error:x.message},400)}}),O.post("/:name/oauth/login",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();await y0(J,x);let Q=await J.beginOAuthLogin(x);return $.json({success:!0,flowId:Q.flowId,authorizationUrl:Q.authorizationUrl},202)}catch(x){return R0.error("[McpRoutes] Failed to start MCP OAuth login:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/oauth/logout",async($)=>{try{let x=$.req.param("name"),J=U0.getInstance();return await y0(J,x),await J.logoutOAuth(x),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to log out MCP OAuth:",x),$.json({success:!1,error:x.message},400)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name");await U0.getInstance().unregisterServer(x);let Q=x0();if(Q?.mcpServers){let{[x]:G,...z}=Q.mcpServers;await L0().updateConfig({mcpServers:z})}return $.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to delete MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/",async($)=>{try{let x=await $.req.json(),{name:J,config:Q}=x;if(!J||!Q)return $.json({success:!1,error:"Missing name or config"},400);await U0.getInstance().registerServer(J,Q);let z=x0();return await L0().updateConfig({mcpServers:{...z?.mcpServers,[J]:Q}}),$.json({success:!0})}catch(x){return R0.error("[McpRoutes] Failed to add MCP server:",x),$.json({success:!1,error:x.message},500)}}),O};import{getSupportedThinkingLevels as H2}from"@earendil-works/pi-ai";import{Hono as B2}from"hono";var dO=a("Service");function L2(O,$,x=X1.list()){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,supportedReasoningEfforts:H2($),supportedServiceTiers:z1($),supportedResponseVerbosities:Y1($),communicationStyles:x,input:$.input}}function w2(O){V1(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function V1(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new H("streamIdleTimeout must be at least 1000ms")}var N1=()=>{let O=new B2;return O.get("/",async($)=>{try{let x=x0();if(!x)throw Error("Config not initialized");let J=$.get("directory")||c(),[Q,G]=await Promise.all([lO(J,x),T0(J)]),z=Q.config.models,F=z.find((w)=>w.id===Q.config.currentModelId)??z[0],T=Q.catalog,B=G.communicationStyles.list(),C=(w)=>L2(w,T.resolveConfig(w),B);return $.json({configured:z.map(C),current:F?C(F):null})}catch(x){dO.error("[ModelsRoutes] Failed to get models:",x);let J=new r("Failed to get models");return $.json(J.toObject(),500)}}),O.post("/",async($)=>{let x=c0(),J,Q;try{let G=await $.req.json(),{provider:z,displayName:F,model:T,overrides:B,apiKey:C,modelProvider:w}=G;if(!z||!T)throw new H("provider and model are required");V1(B);let W;if(w){if(w.id!==z)throw new H("modelProvider.id must match the model provider");if(x0()?.modelProviders[z])throw new H(`model provider already exists: ${z}`);W={name:w.name,baseUrl:w.baseUrl,wireApi:w.wireApi,...w.apiKeyEnv?{apiKeyEnv:w.apiKeyEnv}:{}};try{x.registerModelProvider(z,W,[T]),Q=z}catch(p){throw new H(p instanceof Error?p.message:"Invalid model provider")}}else x.getModel(z,T);if(C?.trim()){if(await x.setApiKey(z,C.trim()),W)J=z}let I={provider:z,displayName:F||void 0,model:T,overrides:B||void 0},J0=W?await L0().addModelWithProvider(I,W):await L0().addModel(I);return $.json({success:!0,model:J0})}catch(G){if(J)await x.credentials.delete(J);if(Q){let z=x0();x.configureModelProviders(z?.modelProviders??{},z?.models??[])}throw dO.error("[ModelsRoutes] Failed to add model:",G),G}}),O.put("/:modelId",async($)=>{try{let x=$.req.param("modelId"),J=await $.req.json(),{displayName:Q,overrides:G,model:z}=J,F=G1(x);if(!F)throw new H("model config not found");if(z)c0().getModel(F.provider,z);return await L0().updateModel(x,w2({displayName:Q,overrides:G,model:z})),$.json({success:!0})}catch(x){throw dO.error("[ModelsRoutes] Failed to update model:",x),x}}),O.delete("/:modelId",async($)=>{try{let x=$.req.param("modelId");return await L0().removeModel(x),$.json({success:!0})}catch(x){throw dO.error("[ModelsRoutes] Failed to delete model:",x),x}}),O};import{Hono as g2}from"hono";import K1 from"node:path";import{Hono as M2}from"hono";import{streamSSE as A2}from"hono/streaming";import{LRUCache as j2}from"lru-cache";import{nanoid as QO}from"nanoid";var m=a("Service"),T2=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),C2=y1,b2=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),R2=U.Object({projectPath:U.String()}),E2=U.Object({objective:U.String({minLength:1}),tokenBudget:U.Optional(U.Integer({minimum:1})),permissionMode:U.Optional(F0(["default","autoEdit","plan","yolo"]))}),q2=U.Union([U.Object({action:U.Literal("pause")}),U.Object({action:U.Literal("resume")}),U.Object({action:U.Literal("edit"),objective:U.String({minLength:1})})]),t=new Map,YO,b0=new Map,I0=new Map,C0=new Map,oO=new j2({max:100,ttl:1800000});function W1(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function D0(O){if(!O)return;return b0.get(O)??oO.get(O)}function k2(O){if(b0.get(O.id)!==O)return;b0.delete(O.id),oO.set(O.id,O)}function I2(O){b0.delete(O),oO.delete(O)}function _0(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function bO(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let x=O.pendingPermission;if(O.pendingPermission=void 0,x?.resolve({approved:!1,reason:M1}),x)R.publish(W1(O),"interaction.resolved",{requestId:x.permissionId});return O.abortController.abort($),O.status="cancelled",R.publish(W1(O),"run.cancelled",{runId:O.id}),!0}function u1(O,$=!1){let{permissionId:x,details:J}=O;if(J.type==="askUserQuestion"&&J.questions)return{type:"question.required",properties:{requestId:x,toolCallId:J.toolCallId??x,questions:J.questions,details:J,...$?{replayed:!0}:{}}};if(J.type==="mcpElicitation"&&J.mcpElicitation)return{type:"elicitation.required",properties:{requestId:x,toolCallId:J.toolCallId??x,elicitation:J.mcpElicitation,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:J.toolName,description:J.message,args:J.args,details:J,...$?{replayed:!0}:{}}}}function S2(O){return{...typeof O.seq==="number"?{id:String(O.seq)}:{},data:JSON.stringify({type:O.type,...typeof O.seq==="number"?{seq:O.seq}:{},properties:{...O.properties,sessionId:O.sessionId,projectPath:O.projectPath}})}}function P2(){for(let O of b0.values())bO(O,"route-reset");b0.clear();for(let O of I0.values())O.controller.abort("route-reset");I0.clear(),oO.clear(),YO=void 0,t.clear()}function f2(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=$.code,J=$.reason,Q=$.scope,G=$.kind,z=$.limit;if(x!=="tool_busy"&&x!=="tool_batch_full"||J!=="queue_full"&&J!=="wait_timeout"&&J!=="turn_limit"||Q!=="global"&&Q!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(z)||z<=0||G!==void 0&&G!=="readonly"&&G!=="write"&&G!=="execute")return;return{code:x,reason:J,scope:Q,retryable:$.retryable,...G===void 0?{}:{kind:G},limit:z}}var RO=(O,$)=>{if(!$||typeof $!=="object")return $;let x={...$},J=f2(x.tool_admission);if(J)x.tool_admission=J;else delete x.tool_admission;if(O==="Bash"){let z={},F=["message","signal","status","summary"],T=["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 w of F){let W=x[w];if(typeof W==="string")z[w]=W.slice(0,8192)}for(let w of T){let W=x[w];if(typeof W==="boolean")z[w]=W}for(let w of B){let W=x[w];if(typeof W==="number"&&Number.isSafeInteger(W)&&W>=0)z[w]=W}if(x.exit_code===null||typeof x.exit_code==="number"&&Number.isSafeInteger(x.exit_code))z.exit_code=x.exit_code;if(x.terminal_transport==="local"||x.terminal_transport==="acp"||x.terminal_transport==="local_fallback")z.terminal_transport=x.terminal_transport;if(x.background_reason==="explicit"||x.background_reason==="foreground_budget")z.background_reason=x.background_reason;for(let w of["bash_id","shell_id"]){let W=x[w];if(typeof W==="string"&&W.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(W))z[w]=W}if(J)z.tool_admission=J;let C=x.background_shell_admission;if(C&&typeof C==="object"&&!Array.isArray(C)){let w=C;if(w.code==="background_shell_busy"&&(w.scope==="session"||w.scope==="global")&&w.retryable===!0&&Number.isSafeInteger(w.limit)&&w.limit>0)z.background_shell_admission={code:w.code,scope:w.scope,retryable:w.retryable,limit:w.limit}}return z}let Q=200000,G=(z,F)=>typeof z==="number"&&Number.isSafeInteger(z)&&z>=0&&z<=F?z:0;if(typeof x.oldContent==="string"&&x.oldContent.length>Q)delete x.oldContent;if(typeof x.newContent==="string"&&x.newContent.length>Q)delete x.newContent;if(x.mcpResult&&typeof x.mcpResult==="object"&&!Array.isArray(x.mcpResult)){let z=x.mcpResult,F=Array.isArray(z.artifacts)?z.artifacts.slice(0,64).flatMap((T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return[];let B=T,C=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"||!C.has(B.kind)||G(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)}:{}}]}):[];x.mcpResult={isError:z.isError===!0,contentCount:G(z.contentCount,64),textBytes:G(z.textBytes,4194304),structuredBytes:G(z.structuredBytes,4194304),artifactCount:G(z.artifactCount,64),truncated:z.truncated===!0,binaryOmitted:z.binaryOmitted===!0,artifacts:F}}else delete x.mcpResult;return x};function y2(O){let $=typeof O.seq==="number"?{seq:O.seq}:{};if(O.type==="part_created"&&O.data.partType==="tool_call"){let x=O.data.payload;return{type:"tool.start",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let x=O.data.payload,J=x.toolName??"unknown",Q=D$(x),G=qO(kO(J,Q),EO);return{type:"tool.result",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:J,success:Q.success,status:Q.success?"completed":"failed",summary:Q.metadata?.summary,output:IO(G),metadata:RO(J,Q.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function m2(O,$,x){switch(x.kind){case"tool_start":if("function"in x.toolCall)R.publish(O,"subagent.update",{subagentSessionId:$,toolName:x.toolCall.function.name}),R.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,arguments:x.toolCall.function.arguments,toolKind:x.toolKind});break;case"tool_result":if("function"in x.toolCall)R.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,success:x.result.success,summary:x.result.metadata?.summary,output:IO(qO(kO(x.toolCall.function.name,x.result),EO)),metadata:RO(x.toolCall.function.name,x.result.metadata)});break;case"tool_progress":if("function"in x.toolCall)R.publish(O,"subagent.tool.progress",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,...x.update});break;case"content_delta":R.publish(O,"subagent.delta",{subagentSessionId:$,delta:x.delta});break;case"thinking_delta":R.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:x.delta});break;case"stream_end":R.publish(O,"subagent.stream.end",{subagentSessionId:$});break;case"provider_admission":R.publish(O,"subagent.provider.admission",{subagentSessionId:$,phase:x.phase,requestClass:x.requestClass,resource:x.resource,scope:x.scope,reason:x.reason,queuePosition:x.queuePosition,queueDepth:x.queueDepth,inFlight:x.inFlight,limit:x.limit,waitMs:x.waitMs,maxWaitMs:x.maxWaitMs,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_circuit":R.publish(O,"subagent.provider.circuit",{subagentSessionId:$,phase:x.phase,reason:x.reason,statusCode:x.statusCode,retryAfterMs:x.retryAfterMs,nextProbeAt:x.nextProbeAt,openDurationMs:x.openDurationMs,sampleCount:x.sampleCount,failureCount:x.failureCount,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_retry":R.publish(O,"subagent.provider.retry",{subagentSessionId:$,phase:x.phase,attempt:x.attempt,maxRetries:x.maxRetries,reason:x.reason,statusCode:x.statusCode,delayMs:x.delayMs,nextRetryAt:x.nextRetryAt,mode:x.mode,recoveryBudgetMs:x.recoveryBudgetMs,recoveryElapsedMs:x.recoveryElapsedMs,recoveryRemainingMs:x.recoveryRemainingMs,exhaustedBy:x.exhaustedBy});break;case"provider_stall":R.publish(O,"subagent.provider.stall",{subagentSessionId:$,phase:x.phase,stallCount:x.stallCount,durationMs:x.durationMs,warningAfterMs:x.warningAfterMs,timeoutMs:x.timeoutMs,outputStarted:x.outputStarted});break;case"action_stationarity":R.publish(O,"subagent.action.stationarity",{subagentSessionId:$,phase:x.phase,toolName:x.toolName,runLength:x.runLength,nudgeThreshold:x.nudgeThreshold,haltThreshold:x.haltThreshold,progressAware:x.progressAware});break;case"mcp_catalog_changed":R.publish(O,"subagent.mcp.catalog.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_content_changed":R.publish(O,"subagent.mcp.content.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,contentKind:x.contentKind,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_resource_updated":R.publish(O,"subagent.mcp.resource.updated",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,uri:x.uri});break;case"mcp_connection_changed":R.publish(O,"subagent.mcp.connection.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,phase:x.phase,reason:x.reason,attempt:x.attempt,maxAttempts:x.maxAttempts,nextRetryAt:x.nextRetryAt,error:x.error});break;case"mcp_log":R.publish(O,"subagent.mcp.log",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,level:x.level,logger:x.logger,message:x.message,projectedBytes:x.projectedBytes,dataSha256:x.dataSha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted,timestamp:x.timestamp,synthetic:x.synthetic});break;case"mcp_instructions_changed":R.publish(O,"subagent.mcp.instructions.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,action:x.action,reason:x.reason,text:x.text,sourceBytes:x.sourceBytes,projectedBytes:x.projectedBytes,sha256:x.sha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted});break;case"mcp_task_changed":R.publish(O,"subagent.mcp.task.changed",{subagentSessionId:$,revision:x.revision,taskId:x.taskId,serverName:x.serverName,toolName:x.toolName,status:x.status,statusMessage:x.statusMessage,createdAt:x.createdAt,updatedAt:x.updatedAt,completedAt:x.completedAt,hasResult:x.hasResult,error:x.error});break;case"project_rules_loaded":R.publish(O,"subagent.project.rules.loaded",{subagentSessionId:$,files:x.files,triggerPaths:x.triggerPaths,blockedWrite:x.blockedWrite});break;default:break}}function TO(O,$="projectPath"){if(!K1.isAbsolute(O))throw new H(`${$} must be absolute`);return K1.resolve(O)}function U$(O){try{uO(O)}catch($){throw new H($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function z0(O){return{sessionId:O.id,projectPath:O.projectPath}}function CO(O,$,x){return{id:O.sessionId,projectPath:O.projectPath,title:O.title??`Session ${O.sessionId.slice(0,6)}`,createdAt:new Date(O.firstMessageTime),updatedAt:new Date(O.lastMessageTime),rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,taskStatus:O.taskStatus,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,pendingInteraction:O.pendingInteraction,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:O.taskQueuePosition,taskQueueDepth:O.taskQueueDepth,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,taskWorktree:x,messages:$}}function Y$(O){return O.flatMap(($)=>{if(!j1($)||$.role==="system"||$.role==="tool"&&$.name===ZO)return[];let x=$.tool_calls?.filter((z)=>!("function"in z)||z.function.name!==ZO),J=typeof $.content==="string"?$.content.trim():"";if($.role==="assistant"&&$.tool_calls?.length&&!x?.length&&!J&&!$.reasoningContent&&!$.metadata)return[];let Q={...$,...$.tool_calls?{tool_calls:x&&x.length>0?x:void 0}:{}};if($.role==="tool"){let z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0,F=$.name??(typeof z?.toolName==="string"?z.toolName:"unknown");if(z!==void 0&&(Object.hasOwn(z,"output")||Object.hasOwn(z,"error"))){let B=D$(z),C=qO(kO(F,B),EO);return[{...Q,name:F,content:IO(C),metadata:RO(F,{...B.metadata,status:B.success?"completed":"failed"})}]}return[{...Q,name:F,metadata:RO(F,z)}]}let G=C1($.metadata);return[G?{...Q,content:T1(G)}:Q]})}function zO(O,$){O.title=$.title??O.title,O.taskStatus=$.taskStatus,O.taskStatusReason=$.taskStatusReason,O.taskFailure=$.taskFailure,O.taskStartedAt=$.taskStartedAt,O.taskCompletedAt=$.taskCompletedAt,O.taskPromptSummary=$.taskPromptSummary,O.taskPriority=$.taskPriority,O.taskKind=$.taskKind,O.taskDueAt=$.taskDueAt,O.taskModelId=$.taskModelId,O.selectedModelId=$.selectedModelId,O.permissionMode=$.permissionMode,O.reasoningEffort=$.reasoningEffort,O.serviceTier=$.serviceTier,O.responseVerbosity=$.responseVerbosity,O.communicationStyle=$.communicationStyle,O.communicationStyleDigest=$.communicationStyleDigest,O.projectInstructionsDigest=$.projectInstructionsDigest,O.pendingInteraction=$.pendingInteraction,O.taskRetryAvailable=$.taskRetryAvailable,O.taskRetriedFrom=$.taskRetriedFrom,O.taskDelivery=$.taskDelivery,O.taskIsolation=$.taskIsolation,O.taskSourceProjectPath=$.taskSourceProjectPath,O.taskWorktreePath=$.taskWorktreePath,O.taskWorktreeBranch=$.taskWorktreeBranch,O.taskBaseCommit=$.taskBaseCommit,O.taskDiffStat=$.taskDiffStat,O.taskQueuePosition=$.taskQueuePosition,O.taskQueueDepth=$.taskQueueDepth,O.taskConcurrencyLimit=$.taskConcurrencyLimit,O.archivedAt=$.archivedAt,O.archivedBySessionId=$.archivedBySessionId,O.updatedAt=new Date($.lastMessageTime)}async function n0(O){let $=await E.findSessionMetadata(O.id,O.projectPath);if($)zO(O,$)}function i0(O){let $=D0(O.currentRunId),x=$?.status==="waiting_permission"?"running":$?.status??O.taskStatus;return{sessionId:O.id,projectPath:O.projectPath,title:O.title,rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,status:void 0,taskStatus:x,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:x==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:x==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:$?.pendingPermission?{type:$.pendingPermission.details.type==="askUserQuestion"?"question":$.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:$.pendingPermission.permissionId}:O.pendingInteraction,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function N0(O,$){if(U$(O),$!==void 0){let J=m0({sessionId:O,projectPath:TO($)});if(t.has(v(J)))return J;let Q=await E.findSessionMetadata(J.sessionId,J.projectPath);if(!Q)throw new y("Session",O);return m0({sessionId:Q.sessionId,projectPath:Q.projectPath})}let x=new Map;for(let J of t.values()){if(J.id!==O)continue;let Q=z0(J);x.set(v(Q),Q)}for(let J of await E.listSessions()){if(J.sessionId!==O)continue;let Q=m0({sessionId:J.sessionId,projectPath:J.projectPath});x.set(v(Q),Q)}if(x.size===0)try{let J=await E.findSessionMetadata(O);if(!J)throw new y("Session",O);return m0({sessionId:J.sessionId,projectPath:J.projectPath})}catch(J){if(J instanceof y)throw J;if(J instanceof Error&&J.message.startsWith("Ambiguous session ID:"))throw new B0;throw J}if(x.size>1)throw new B0;return x.values().next().value}function _$(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
7
+ `)}function F1(O,$){let x=($??[]).filter((Q)=>Q.type==="image"&&typeof Q.content==="string").map((Q)=>({type:"image_url",image_url:{url:Q.content}}));if(x.length===0)return O;let J=[];if(O.trim())J.push({type:"text",text:O});return J.push(...x),J}var p1=()=>{P2();let O=new M2;O.onError((Z,V)=>{if(Z instanceof JO){let Y=new k0("Session runtime capacity is full",{resource:Z.resource,limit:Z.limit});return V.json(Y.toObject(),429)}if(Z instanceof Q0)return V.json(Z.toObject(),Z.statusCode);return m.error("[SessionRoutes] Unhandled route error:",Z),V.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,x=new Map,J=new Map,Q=new Map,G=new z$,z=new z$,F=x0(),T=new v1({maxResident:F?.maxResidentSessionRuntimes??D1,idleMs:F?.sessionRuntimeIdleMs??H1}),B=new q1,C=setInterval(()=>{T.sweepIdle().catch((Z)=>{m.warn("[SessionRoutes] Session Runtime idle sweep failed:",Z)})},B1);C.unref?.();let w,W=async(Z)=>{let V;try{V=B.enter()}catch{throw new l0}try{return await Z()}finally{V.release()}};O.use("*",async(Z,V)=>{if(Z.req.method==="GET"||Z.req.method==="HEAD")return V();return W(V)});let I=(Z,V)=>G.runExclusive(v(Z),V),J0=(Z,V)=>z.runExclusive(v(Z),V),p=(Z)=>[...b0.values()].some((V)=>V.sessionId===Z.sessionId&&V.projectPath===Z.projectPath&&_0(V)),b=async(Z,V,Y)=>{let X=J.get(V);if(!X)X=(async()=>{if($.get(V)===Y)$.delete(V);for(let[D,_]of $)if(_===Y)$.delete(D);let K=z0(Z);if(t.get(V)===Z&&!p(K)&&!I0.has(V)&&!C0.has(V))t.delete(V);if(await Y.dispose(),$.size===0)await U0.getInstance().disconnectAll()})().finally(()=>{if(J.get(V)===X)J.delete(V)}),J.set(V,X);await X},e=async(Z,V={})=>{let Y=z0(Z),X=v(Y);await J.get(X);let K=T.acquire(X);if(K){if($.get(X)!==K.value)throw K.release(),Error("Session Runtime residency identity is inconsistent");return K}if(T.owns(X))throw new JO(T.getStats().maxResident);let D=x.get(X);if(!D){let _=V.communicationStyle??Z.communicationStyle;D=(async()=>{let L=await T.reserve(X,{surface:"web",allowEviction:!0});try{let M=await jO.create({sessionId:Z.id,workspaceRoot:Z.projectPath,...Z.selectedModelId??Z.taskModelId?{modelId:Z.selectedModelId??Z.taskModelId}:{},permissionMode:V.permissionMode??Z.permissionMode??"default",...Z.reasoningEffort?{reasoningEffort:Z.reasoningEffort}:{},...Z.serviceTier?{serviceTier:Z.serviceTier}:{},...Z.responseVerbosity?{responseVerbosity:Z.responseVerbosity}:{},..._?{communicationStyle:_}:{},..._===Z.communicationStyle&&Z.communicationStyleDigest?{communicationStyleDigest:Z.communicationStyleDigest}:{},...Z.projectInstructionsDigest?{projectInstructionsDigest:Z.projectInstructionsDigest}:{},...Z.taskWorktree?{taskWorktree:Z.taskWorktree}:{},...Z.taskIsolation?{taskIsolation:Z.taskIsolation}:{},...Z.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:Z.id}}:{}}),A=L.commit({key:X,surface:"web",value:M,canEvict:()=>!p(Y)&&!I0.has(X)&&!C0.has(X)&&!x.has(X)&&!J.has(X)&&M.isIdleForResidency(),dispose:()=>b(Z,X,M)});return $.set(X,M),{runtime:M,claimLease:()=>{if(A){let k=A;return A=void 0,k}let j=T.acquire(X);if(!j||j.value!==M)throw Error("Initialized Session Runtime lost residency");return j}}}catch(M){throw L.cancel(),M}})(),x.set(X,D)}try{return(await D).claimLease()}finally{if(x.get(X)===D)x.delete(X)}},h=async(Z,V,Y={})=>{let X=await e(Z,Y);try{return await V(X.value)}finally{X.release()}},Z0=async(Z,V)=>{let Y=v(z0(Z)),X=x.get(Y);if(X)await X.catch(()=>{return});x.delete(Y);let K=V??$.get(Y);if(!K)return;if(!await T.remove(Y,K))throw Error(`Session Runtime is pinned and cannot be disposed: ${Y}`)},i=async(Z)=>{let V=v(Z),Y=t.get(V);if(Y)return Y;let X=Q.get(V);if(!X)X=(async()=>{let K=await E.findSessionMetadata(Z.sessionId,Z.projectPath);if(!K)throw new y("Session",Z.sessionId);let[D,_]=await Promise.all([E.loadSession(Z.sessionId,Z.projectPath),E.findSessionTaskWorktree(Z.sessionId,Z.projectPath)]),L=CO(K,D,_);return t.set(V,L),L})(),Q.set(V,X);try{return await X}finally{if(Q.get(V)===X)Q.delete(V)}},$0=async(Z,V)=>{let Y=await N0(Z,V);try{await E.assertSessionWritable(Y.sessionId,Y.projectPath)}catch(X){if(X instanceof V$)throw new q(X.message);throw X}return i(Y)},S0=async(Z,V)=>{if(Z.permissionMode===V)return;let Y=await E.setSessionPermissionMode(Z.id,Z.projectPath,V);Z.permissionMode=Y.permissionMode,Z.updatedAt=new Date(Y.lastMessageTime),R.publish(z0(Z),"session.updated",{permissionMode:V})},o=(Z,V,Y,X={})=>{if(!B.stats().accepting)throw new l0;let K=QO(12),D={id:K,sessionId:Z.id,projectPath:Z.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:Z.taskIsolation!==void 0&&X.runtimeLease!==void 0,createdAt:new Date};if(Z.taskIsolation&&X.runtimeLease){let _=X.runtimeLease.value,L=f0.admit({key:`${Z.projectPath}\x00${Z.id}`,..._.getTaskAdmissionLimits(),pendingBytes:k1({content:V,outputSchema:X.outputSchema,pendingMessages:_.getPendingSteeringMessages()}),signal:D.abortController.signal,onUpdate:(A)=>{D.status=A.state,Z.taskStatus=A.state,Z.taskQueuePosition=A.queuePosition,Z.taskQueueDepth=A.queueDepth,Z.taskConcurrencyLimit=A.maxConcurrent,D.taskAdmissionUpdate=(D.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await _.setTaskAdmission(A)}).catch((j)=>{m.warn(`[SessionRoutes] Failed to persist admission for ${Z.id}:`,j)})}});D.taskAdmission=L;let M=L.getSnapshot();D.status=M.state,Z.taskStatus=M.state,Z.taskQueuePosition=M.queuePosition,Z.taskQueueDepth=M.queueDepth,Z.taskConcurrencyLimit=M.maxConcurrent}return b0.set(K,D),Z.currentRunId=K,D.completion=h2(D,Z,V,Y,e,{pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:D.taskAdmission,runtimeLease:X.runtimeLease,disposeRuntime:Z0}).catch((_)=>{m.error(`[SessionRoutes] Run ${K} failed:`,_)}),D},p0=async(Z)=>{let V;if(Z.outputSchema)try{V=X$(Z.outputSchema).schema}catch(u){throw new H(u instanceof Error?u.message:"Invalid output schema")}let Y=G$("task",12),X=TO(Z.sourceProjectPath),K=Z.modelId?.trim(),D=x0();if(!D)throw new H("Config not initialized");let[_,L]=await Promise.all([lO(X,D),T0(X)]);if(K&&!_.config.models.some((u)=>u.id===K))throw new H(`Task model not found: ${K}`);let M=K||_.config.models.find((u)=>u.id===_.config.currentModelId)?.id||_.config.models[0]?.id;if(!M)throw new H("No model is configured. Add or select a model before dispatching a task.");let A=_.config.models.find((u)=>u.id===M);if(!A)throw new H(`Task model not found: ${M}`);let j=Z.reasoningEffort??"off",k=Z.serviceTier??"auto",K0=Z.responseVerbosity??"auto",P0=Z.communicationStyle??"auto",j0,G0=L.projectRules?.staticRules(X),O0=G0&&G0.files.length>0?G0.provenanceSha256:void 0;try{let u=_.catalog.resolveConfig(A);L1(u,j),_1(u,k),U1(u,K0);let l=w1(P0,L.communicationStyles);j0=l.source==="built-in"?void 0:l.contentSha256}catch(u){throw new H(u instanceof Error?u.message:"Invalid reasoning effort")}let r0={version:1,prompt:Z.prompt,...Z.title?{title:Z.title}:{},...Z.taskPriority?{taskPriority:Z.taskPriority}:{},...Z.taskKind?{taskKind:Z.taskKind}:{},...Z.taskDueAt?{taskDueAt:Z.taskDueAt}:{},sourceProjectPath:X,isolation:Z.isolation,permissionMode:Z.permissionMode,modelId:M,reasoningEffort:j,serviceTier:k,responseVerbosity:K0,communicationStyle:P0,...j0?{communicationStyleDigest:j0}:{},...O0?{projectInstructionsDigest:O0}:{},...Z.attachments?{attachments:Z.attachments.map((u)=>({...u}))}:{},...V?{outputSchema:V}:{}},g,P,S;try{let u=await S1.createSessionTask({sessionId:Y,prompt:Z.prompt,title:Z.title,taskPriority:Z.taskPriority,taskKind:Z.taskKind,taskDueAt:Z.taskDueAt,sourceProjectPath:X,isolation:Z.isolation,dispatch:r0,retriedFrom:Z.retriedFrom}),{metadata:l}=u;g=u.taskWorktree,P=CO(l,[],g);let d=z0(P);t.set(v(d),P),R.publish(d,"task.status",{taskStatus:l.taskStatus,updatedAt:l.lastMessageTime});let s=F1(Z.prompt,Z.attachments);S=await e(P);let UO=S.value,n=V?await UO.prepareInputTurn(s,{outputSchema:V}):await UO.prepareInputTurn(s);if(!n.accepted)throw new q(`Task prompt was not accepted: ${n.reason}`);let Y0=o(P,s,Z.permissionMode,{preparedInputTurn:n,runtimeLease:S,outputSchema:V});return S=void 0,await Y0.taskAdmissionUpdate,{session:i0(P),runId:Y0.id,messageId:n.messageId,status:Y0.status==="queued"?"queued":"running",queuePosition:P.taskQueuePosition,queueDepth:P.taskQueueDepth,maxConcurrentTasks:P.taskConcurrencyLimit}}catch(u){if(S?.release(),S=void 0,(u instanceof F$||u instanceof JO)&&P){let l=z0(P),d=v(l);if(g)await E0.exit({sessionId:P.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await Z0(P).catch(()=>{return}),await E.deleteSession(P.id,P.projectPath).catch(()=>{return}),t.delete(d),new k0(u instanceof JO?"Session runtime capacity is full":"Task admission capacity is full",{resource:u.resource,limit:u.limit})}if(P){let l=await E.findSessionMetadata(P.id,P.projectPath).catch(()=>{return});if(!l||l.taskStatus==="queued"){let d=iO(u),s=await E.updateSessionMetadata(P.id,P.projectPath,{taskStatus:"failed",taskStatusReason:d.message,taskFailure:d,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});P.taskStatus=s?.taskStatus??"failed",P.taskStatusReason=s?.taskStatusReason??d.message,P.taskFailure=s?.taskFailure??d,P.taskCompletedAt=s?.taskCompletedAt}else P.taskStatus=l.taskStatus,P.taskStatusReason=l.taskStatusReason,P.taskFailure=l.taskFailure,P.taskCompletedAt=l.taskCompletedAt}throw u}},w0=(Z)=>W(()=>p0(Z)),N=async(Z,V)=>{let Y=await N0(Z,V),X=await E.findSessionMetadata(Y.sessionId,Y.projectPath);if(!X)throw new y("Session",Y.sessionId);if(!["failed","interrupted","cancelled"].includes(X.taskStatus))throw new q(`Task cannot be retried while status is ${X.taskStatus}`);let K=await E.findSessionTaskDispatch(Y.sessionId,Y.projectPath);if(!K)throw new q("Task retry payload is unavailable");return w0({prompt:K.prompt,title:X.title??K.title,taskPriority:X.taskPriority??K.taskPriority,taskKind:X.taskKind??K.taskKind,taskDueAt:X.taskDueAt,sourceProjectPath:K.sourceProjectPath,isolation:K.isolation,permissionMode:K.permissionMode,modelId:K.modelId,reasoningEffort:K.reasoningEffort,serviceTier:K.serviceTier,responseVerbosity:K.responseVerbosity,communicationStyle:K.communicationStyle,attachments:K.attachments,outputSchema:K.outputSchema,retriedFrom:Y})},V0=(Z,V)=>W(()=>N(Z,V)),S$=(Z,V,Y)=>W(async()=>{let X=await N0(Z,Y);if(!await E.findSessionMetadata(X.sessionId,X.projectPath))throw new y("Session",X.sessionId);let D=await E.updateSessionMetadata(X.sessionId,X.projectPath,V),_=t.get(v(X));if(_)zO(_,D);return R.publish(X,"session.updated",{...D.title?{title:D.title}:{},...D.taskPriority?{taskPriority:D.taskPriority}:{},...D.taskKind?{taskKind:D.taskKind}:{},taskDueAt:D.taskDueAt??null}),_?i0(_):{...D,isActive:!1}}),rO=async(Z,V)=>{let Y=await $0(Z,V);if(!Y.taskWorktree)throw new H("Session does not have a task worktree");try{await E0.restoreSession(Y.taskWorktree);let X=await E0.getDiffArtifact(Y.id);if(!X)throw new q("Task diff artifact is unavailable");return{sessionId:Y.id,projectPath:Y.projectPath,...X}}catch(X){if(X instanceof q)throw X;throw m.error("[SessionRoutes] Failed to load task diff artifact:",X),new q("Task diff artifact is unavailable")}},FO=async(Z,V,Y)=>{let X=await N0(Z,Y);return J0(X,async()=>{let K=await $0(X.sessionId,X.projectPath);if(["queued","running"].includes(K.taskStatus))throw new q(`Task artifacts cannot be delivered while status is ${K.taskStatus}`);if(K.taskDelivery?.status==="applied")throw new q("Task changes have already been applied");if(K.taskDelivery?.status==="discarded")throw new q("Task changes have already been discarded");if(!K.taskWorktree)throw new q("Task worktree is unavailable");let D=async(_,L=!1)=>{let M=await E.updateSessionMetadata(K.id,K.projectPath,{taskDelivery:_,...L?{taskWorktree:null}:{}});if(zO(K,M),L)K.taskWorktree=void 0;return R.publish(X,"task.delivery",{taskDelivery:_,...L?{taskWorktreeRemoved:!0}:{},updatedAt:M.lastMessageTime}),i0(K)};try{if(V==="discard"){try{await E0.restoreSession(K.taskWorktree)}catch(M){return m.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${K.id}:`,M),D({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:K.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let L=await E0.exit({sessionId:K.id,action:"remove",discardChanges:!0});return D({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:L.discardedFiles??0,message:"Task worktree removed"},!0)}try{await E0.restoreSession(K.taskWorktree)}catch(L){throw m.warn(`[SessionRoutes] Task worktree is unavailable for ${K.id}:`,L),new W$("artifact_unavailable","Task worktree is unavailable")}let _=await E0.apply(K.id);return D({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:_.sourceCommit,changedFiles:_.changedFiles,message:"Task changes applied to the source workspace"})}catch(_){if(_ instanceof W$)throw await D({status:"conflicted",updatedAt:new Date().toISOString(),message:_.message}),new q(_.message);throw _}})},yO=(Z,V,Y)=>W(()=>FO(Z,V,Y)),mO=async(Z)=>{let V=D0(Z.currentRunId);if(_0(V))return;if(Z.taskIsolation&&Z.taskStatus!=="queued"&&Z.taskStatus!=="running")return;let Y=await jO.hasPendingInbox(Z.projectPath,Z.id),X=!Y&&await jO.hasActiveGoal(Z.projectPath,Z.id);if(!Y&&!X)return;let K=await e(Z),D=!1;try{let _=K.value,L=D0(Z.currentRunId);if(_0(L))return;if(Y&&_.getPendingSteeringCount()===0)await _.reloadPendingInbox();let M=_.getPendingSteeringCount()>0,A=M?null:await _.getGoal(),j=A?.status==="active"||A?.status==="verifying";if(!M&&!j||_.hasTurnOwner())return;o(Z,"",Z.permissionMode??"default",{pendingInputOnly:M,goalContinuationOnly:j,runtimeLease:K}),D=!0}finally{if(!D)K.release()}},q0=async(Z)=>{let V;try{V=B.enter()}catch{return}try{await mO(Z)}finally{V.release()}};YO=q0;let eO=async()=>{let Z={scheduled:0,failed:0,deferred:0};if(!B.stats().accepting)return Z;let V=(await E.listSessions({taskStatus:"queued"})).filter((Y)=>Y.taskIsolation!==void 0).sort((Y,X)=>Y.firstMessageTime.localeCompare(X.firstMessageTime)||Y.projectPath.localeCompare(X.projectPath)||Y.sessionId.localeCompare(X.sessionId));for(let[Y,X]of V.entries()){let K={sessionId:X.sessionId,projectPath:X.projectPath};try{if(!await jO.hasPendingInbox(X.projectPath,X.sessionId)){let _=iO("Queued task input is missing");await E.updateSessionMetadata(X.sessionId,X.projectPath,{taskStatus:"failed",taskStatusReason:_.message,taskFailure:_,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Z.failed++;continue}let D=await i(K);if(await q0(D),D.currentRunId)Z.scheduled++}catch(D){if(D instanceof F$||D instanceof JO){Z.deferred+=V.length-Y;break}m.warn(`[SessionRoutes] Failed to recover queued task ${X.sessionId}:`,D),Z.deferred++}}return Z};return O.get("/",async(Z)=>{try{let V=await E.listSessions(),Y=new Set(V.filter((A)=>A.relationType==="subagent").map((A)=>v({sessionId:A.sessionId,projectPath:A.projectPath}))),X=Array.from(t.values()).filter((A)=>!Y.has(v(z0(A)))&&A.relationType!=="subagent").map((A)=>i0(A)),K=new Set(X.map((A)=>v({sessionId:A.sessionId,projectPath:A.projectPath}))),D=V.filter((A)=>{if(A.relationType==="subagent")return!1;return!K.has(v({sessionId:A.sessionId,projectPath:A.projectPath}))}),_=new Set(K),L=D.filter((A)=>{let j=v({sessionId:A.sessionId,projectPath:A.projectPath});if(_.has(j))return!1;return _.add(j),!0}),M=[...X,...L];return Z.json(M)}catch(V){throw m.error("[SessionRoutes] Failed to list sessions:",V),new r("Failed to list sessions")}}),O.get("/catalog",async(Z)=>{try{let V=Z.req.query("limit"),Y=V===void 0?void 0:Number(V),X=Z.req.query("cursor"),K=Z.req.query("projectPath"),D=Z.req.query("archived");if(D!==void 0&&D!=="true"&&D!=="false")throw new H("archived must be true or false");let _=D==="true",L=await E.listSessionPage({...K?{cwd:TO(K)}:{},...X?{cursor:X}:{},...Y===void 0?{}:{limit:Y},includeSubagents:!1,archived:_}),M=new Map((_?[]:Array.from(t.values())).filter((A)=>A.relationType!=="subagent").map((A)=>[v(z0(A)),i0(A)]));return Z.json({sessions:L.sessions.map((A)=>M.get(v({sessionId:A.sessionId,projectPath:A.projectPath}))??A),...L.nextCursor?{nextCursor:L.nextCursor}:{}})}catch(V){if(V instanceof H)throw V;if(V instanceof Error&&(V.message.startsWith("Invalid session cursor")||V.message.startsWith("Session cursor scope")||V.message.startsWith("Session catalog")))throw new H(V.message);throw m.error("[SessionRoutes] Failed to list session catalog:",V),new r("Failed to list session catalog")}}),O.post("/",async(Z)=>{try{let V=await Z.req.json(),Y=f(T2,V);if(!Y.success)throw new H("Invalid request body");let{title:X,projectPath:K}=Y.data,D=G$("web",12),_=TO(K||Z.get("directory")||c(),K?"projectPath":"directory"),L=await E.createSessionMetadata(D,_,{title:X,taskStatus:"completed"}),M=CO(L,[]),A=z0(M);return t.set(v(A),M),R.publish(A,"session.created",{}),Z.json({...i0(M),status:void 0,agentType:void 0,model:void 0})}catch(V){if(m.error("[SessionRoutes] Failed to create session:",V),V instanceof H)throw V;throw new r("Failed to create session")}}),O.get("/:sessionId/export",async(Z)=>{let V=Z.req.param("sessionId");try{let Y=Z.req.query("includeReasoning");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new H("includeReasoning must be true or false");let X=await N0(V,Z.req.query("projectPath")),K=await E.exportSessionMarkdown(X.sessionId,X.projectPath,{includeReasoning:Y==="true"});return Z.body(K.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${K.filename}"`,"Content-Length":String(Buffer.byteLength(K.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":K.contentSha256,"X-Blade-Export-Activities":String(K.activityCount),"X-Blade-Export-Messages":String(K.messageCount),"X-Blade-Export-Redactions":String(K.redactionCount)})}catch(Y){if(Y instanceof H||Y instanceof y||Y instanceof B0)throw Y;if(Y instanceof Error&&Y.message==="No conversation content to export")throw new q(Y.message);throw m.error("[SessionRoutes] Failed to export session:",Y),new r("Failed to export session")}}),O.post("/:sessionId/fork",async(Z)=>{let V=Z.req.param("sessionId");try{U$(V);let Y=await Z.req.json(),X=f(R2,Y);if(!X.success)throw new H("Invalid request body");let K=TO(X.data.projectPath),D=await E.findSessionMetadata(V,K);if(!D)throw new y("Session",V);let _=await E.forkSession(V,{sourceProjectPath:D.projectPath,targetProjectPath:D.projectPath}),L=CO(_.metadata,_.messages),M=z0(L);return t.set(v(M),L),R.publish(M,"task.status",{taskStatus:_.metadata.taskStatus,..._.metadata.taskCompletedAt?{taskCompletedAt:_.metadata.taskCompletedAt}:{},updatedAt:_.metadata.lastMessageTime}),Z.json({session:_.metadata,messages:Y$(_.messages)},201)}catch(Y){if(Y instanceof H||Y instanceof y||Y instanceof q)throw Y;if(Y instanceof b1)throw new q("Session has no durable creation record");throw m.error("[SessionRoutes] Failed to fork session:",Y),new r("Failed to fork session")}}),O.get("/:sessionId",async(Z)=>{let V=Z.req.param("sessionId");try{let Y=await N0(V,Z.req.query("projectPath")),X=t.get(v(Y));if(X)return Z.json(i0(X));let K=await E.findSessionMetadata(Y.sessionId,Y.projectPath);if(!K)throw new y("Session",V);return Z.json(K)}catch(Y){if(Y instanceof H||Y instanceof y||Y instanceof B0)throw Y;throw m.error("[SessionRoutes] Failed to get session:",Y),new r("Failed to get session")}}),O.patch("/:sessionId",async(Z)=>{let V=Z.req.param("sessionId");try{let Y=await Z.req.json(),X=f(b2,Y);if(!X.success)throw new H("Invalid request body");if(X.data.title===void 0)throw new H("title is required");let K=await N0(V,X.data.projectPath),D=await E.updateSessionMetadata(K.sessionId,K.projectPath,{title:X.data.title}),_=t.get(v(K));if(_)_.title=D.title??_.title,_.updatedAt=new Date(D.lastMessageTime);if(D.title)R.publish(K,"session.updated",{title:D.title});return Z.json({success:!0,title:D.title})}catch(Y){if(m.error("[SessionRoutes] Failed to update session:",Y),Y instanceof H||Y instanceof y||Y instanceof B0)throw Y;throw new r("Failed to update session")}}),O.get("/:sessionId/rewind",async(Z)=>{let V=await $0(Z.req.param("sessionId"),Z.req.query("projectPath"));return h(V,async(Y)=>Z.json({checkpoints:await Y.listRewindCheckpoints()}))}),O.post("/:sessionId/rewind",async(Z)=>{let V=f(P1,await Z.req.json());if(!V.success)throw new H("Invalid rewind request");let Y=await $0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(Y);return I(X,async()=>{let K=D0(Y.currentRunId);if(_0(K))throw new q("Cannot rewind while a run is active");return h(Y,async(D)=>{let _;try{_=await D.rewindSession(V.data)}catch(M){if(M instanceof Error&&M.message.startsWith("Cannot rewind while"))throw new q(M.message);throw M}Y.messages=[..._.messages],Y.updatedAt=new Date;let L=Y$(_.messages);return R.publish(X,"session.rewound",{targetMessageId:_.checkpoint.messageId,mode:_.mode,removedTurns:_.removedTurns,restoredFiles:_.restoredFiles,messages:L}),Z.json({..._,messages:L})})})}),O.get("/:sessionId/review",async(Z)=>{let V=Z.req.param("sessionId"),Y=await N0(V,Z.req.query("projectPath")),X=await a0.list(Y.projectPath,Y.sessionId);return Z.json({reviews:X.map((K)=>({...K,content:K.completion?A1(K.start,K.completion):void 0}))})}),O.post("/:sessionId/review",async(Z)=>{let V=Z.req.param("sessionId"),Y=f(g1,await Z.req.json());if(!Y.success)throw new H("Invalid code review request");let X=await $0(V,Y.data.projectPath),K=z0(X),D=v(K);return I(K,async()=>{if(_0(D0(X.currentRunId)))throw new q("Cannot start a review during an active turn");if(C0.has(D))throw new q("Session already has an active review");return h(X,async(_)=>{if(await a0.recoverInterrupted(K.projectPath,K.sessionId,_),Y.data.modelId&&!_.getModelById(Y.data.modelId))throw new H(`Model not found: ${Y.data.modelId}`);if(Y.data.modelId&&_.getCurrentModelId()!==Y.data.modelId)await _.refresh({modelId:Y.data.modelId});if(Y.data.modelId&&X.selectedModelId!==Y.data.modelId){let j=await E.updateSessionMetadata(X.id,X.projectPath,{selectedModelId:Y.data.modelId});zO(X,j)}let L=new AbortController,M;try{M=await a0.start({sessionId:K.sessionId,projectPath:K.projectPath,runtime:_,request:{kind:Y.data.kind,...Y.data.ref?{ref:Y.data.ref}:{},...Y.data.instructions?{instructions:Y.data.instructions}:{}},signal:L.signal,onEvent:(j)=>{if(j.kind==="tool_start")R.publish(K,"review.tool.started",{reviewId:M?.reviewId,toolCallId:j.toolCall.id,toolName:j.toolCall.function.name});else if(j.kind==="tool_progress")R.publish(K,"review.tool.progress",{reviewId:M?.reviewId,toolCallId:j.toolCall.id,message:j.update.message.slice(0,1000)});else if(j.kind==="tool_result")R.publish(K,"review.tool.completed",{reviewId:M?.reviewId,toolCallId:j.toolCall.id,success:j.result.success})}})}catch(j){if(j instanceof Error&&(j.message.includes("active review")||j.message.includes("interrupted review")||j.message.includes("active turn")))throw new q(j.message);if(j instanceof Error&&(j.message.includes("review")||j.message.includes("Git")||j.message.includes("changes")||j.message.includes("ref")))throw new H(j.message);throw j}if(!M)throw new r("Code review failed to start");await n0(X),R.publish(K,"review.started",{reviewId:M.reviewId,kind:Y.data.kind}),R.publish(K,"task.status",{taskStatus:X.taskStatus,...X.taskStatusReason?{taskStatusReason:X.taskStatusReason}:{},...X.taskStartedAt?{taskStartedAt:X.taskStartedAt}:{},...X.taskPromptSummary?{taskPromptSummary:X.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let A=M.completion.then(async(j)=>{X.messages=await E.loadSession(K.sessionId,K.projectPath),await n0(X),R.publish(K,"task.status",{taskStatus:X.taskStatus,...X.taskStatusReason?{taskStatusReason:X.taskStatusReason}:{},...X.taskFailure?{taskFailure:X.taskFailure}:{},...X.taskStartedAt?{taskStartedAt:X.taskStartedAt}:{},...X.taskCompletedAt?{taskCompletedAt:X.taskCompletedAt}:{},...X.taskPromptSummary?{taskPromptSummary:X.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),R.publish(K,"review.completed",{reviewId:M.reviewId,status:j.status,findings:j.findings.length})}).catch((j)=>{m.error(`[SessionRoutes] Code review ${M.reviewId} failed:`,j)}).finally(()=>{if(C0.get(D)?.reviewId===M.reviewId)C0.delete(D)});return C0.set(D,{reviewId:M.reviewId,controller:L,completion:A}),Z.json({reviewId:M.reviewId,status:"running"},202)})})}),O.get("/:sessionId/subagents",async(Z)=>{let V=await $0(Z.req.param("sessionId"),Z.req.query("projectPath"));return h(V,(Y)=>Z.json({subagents:Y.listSubagents().map(cO)}))}),O.post("/:sessionId/subagents/:agentId/resume",async(Z)=>{U$(Z.req.param("agentId"));let V=f1.safeParse(await Z.req.json());if(!V.success)throw new H("Invalid subagent resume request");let Y=await $0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(Y);return I(X,async()=>{let K=D0(Y.currentRunId);if(_0(K))throw new q("Cannot resume a subagent while a parent run is active");return h(Y,async(D)=>{let _=!1,L,M=(j)=>{R.publish(X,"subagent.complete",{subagentSessionId:j.id,success:j.status==="completed",status:j.status,summary:j.result?.message?.slice(0,500),type:j.subagentType,verificationVerdict:j.result?.verificationVerdict,resumedFrom:j.resumedFrom,rootAgentId:j.rootAgentId,resumeDepth:j.resumeDepth})},A;try{A=D.resumeSubagent({agentId:Z.req.param("agentId"),prompt:V.data.prompt,onEvent:(j,k)=>{m2(X,k,j)},onCompleted:(j)=>{if(_)M(j);else L=j}})}catch(j){if(j instanceof Error&&(j.message.startsWith("Cannot resume")||j.message.startsWith("Subagent cannot")))throw new q(j.message);if(j instanceof Error&&j.message.startsWith("Subagent not found"))throw new y(j.message);throw j}if(R.publish(X,"subagent.start",{subagentSessionId:A.session.id,type:A.session.subagentType,description:A.session.description,resumedFrom:A.source.id,rootAgentId:A.session.rootAgentId,resumeDepth:A.session.resumeDepth}),_=!0,L)M(L);return Z.json({source:cO(A.source),session:cO(A.session)})})})}),O.get("/:sessionId/goal",async(Z)=>{let V=await $0(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json({goal:await new R1(V.projectPath,V.id).get()})}),O.put("/:sessionId/goal",async(Z)=>{let V=f(E2,await Z.req.json());if(!V.success)throw new H("Invalid goal request");let Y=await $0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(Y);return I(X,async()=>{let K=D0(Y.currentRunId);if(_0(K))return Z.json({status:"rejected",reason:"run_active"},409);let _=V.data.permissionMode??Y.permissionMode??"default";if(Y.permissionMode!==_)await S0(Y,_);let L=await e(Y),M=!1;try{let A=await L.value.createGoal(V.data);R.publish(X,"goal.updated",{goal:A});let j=o(Y,"",_,{goalContinuationOnly:!0,runtimeLease:L});return M=!0,await j.taskAdmissionUpdate,Z.json({status:j.status==="queued"?"queued":"running",runId:j.id,goal:A,queuePosition:Y.taskQueuePosition,queueDepth:Y.taskQueueDepth,maxConcurrentTasks:Y.taskConcurrencyLimit},202)}finally{if(!M)L.release()}})}),O.patch("/:sessionId/goal",async(Z)=>{let V=f(q2,await Z.req.json());if(!V.success)throw new H("Invalid goal update");let Y=await $0(Z.req.param("sessionId"),Z.req.query("projectPath")),X=z0(Y);return I(X,async()=>{let K=await e(Y),D=!1;try{let _=K.value,L;if(V.data.action==="pause")L=await _.pauseGoal();else if(V.data.action==="edit")L=await _.editGoal(V.data.objective);else L=await _.resumeGoal();if(R.publish(X,"goal.updated",{goal:L}),L.status==="active"&&!_0(D0(Y.currentRunId))){let M=o(Y,"","default",{goalContinuationOnly:!0,runtimeLease:K});return D=!0,await M.taskAdmissionUpdate,Z.json({status:M.status==="queued"?"queued":"running",runId:M.id,goal:L,queuePosition:Y.taskQueuePosition,queueDepth:Y.taskQueueDepth,maxConcurrentTasks:Y.taskConcurrencyLimit},202)}return Z.json({status:L.status,goal:L})}finally{if(!D)K.release()}})}),O.delete("/:sessionId/goal",async(Z)=>{let V=await $0(Z.req.param("sessionId"),Z.req.query("projectPath")),Y=z0(V);return h(V,async(X)=>{let K=await X.clearGoal();if(K)R.publish(Y,"goal.cleared",{});return Z.json({cleared:K})})}),O.post("/:sessionId/archive",async(Z)=>{let V=Z.req.param("sessionId");try{let Y=await N0(V,Z.req.query("projectPath")),X=await E.listSessionArchiveMembers(Y.sessionId,Y.projectPath);for(let D of X){let _=m0({sessionId:D.sessionId,projectPath:D.projectPath}),L=t.get(v(_));if(_0(D0(L?.currentRunId)))throw new q(`Stop session ${D.sessionId} before archiving this session tree`)}for(let D of X){let _=m0({sessionId:D.sessionId,projectPath:D.projectPath}),L=t.get(v(_));if(L)await Z0(L)}let K=await E.archiveSession(Y.sessionId,Y.projectPath);for(let D of X){let _=m0({sessionId:D.sessionId,projectPath:D.projectPath}),L=v(_);t.delete(L),Q.delete(L),x.delete(L),R.publish(_,"session.archived",{archiveRootId:Y.sessionId,archivedAt:K.archivedAt})}if($.size===0)await U0.getInstance().disconnectAll();return Z.json({session:K,archivedSessionIds:X.map((D)=>D.sessionId)})}catch(Y){if(Y instanceof H||Y instanceof y||Y instanceof B0||Y instanceof q)throw Y;if(Y instanceof N$)throw new q(Y.message);throw m.error("[SessionRoutes] Failed to archive session:",Y),new r("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Z)=>{let V=Z.req.param("sessionId");try{let Y=await N0(V,Z.req.query("projectPath")),X=await E.listSessionArchiveMembers(Y.sessionId,Y.projectPath),K=await E.unarchiveSession(Y.sessionId,Y.projectPath),D=X.filter((_)=>_.sessionId===Y.sessionId||_.archivedBySessionId===Y.sessionId).map((_)=>_.sessionId);for(let _ of D)R.publish({sessionId:_,projectPath:Y.projectPath},"session.unarchived",{archiveRootId:Y.sessionId});return Z.json({session:K,restoredSessionIds:D})}catch(Y){if(Y instanceof H||Y instanceof y||Y instanceof B0)throw Y;if(Y instanceof N$)throw new q(Y.message);throw m.error("[SessionRoutes] Failed to unarchive session:",Y),new r("Failed to unarchive session")}}),O.delete("/:sessionId",async(Z)=>{let V=Z.req.param("sessionId"),Y=Z.req.query("projectPath");try{let X=await N0(V,Y),K=v(X),D=t.get(K),_=$.get(K),L=D?.taskWorktree??await E.findSessionTaskWorktree(X.sessionId,X.projectPath),M;if(D?.currentRunId){let k=D0(D.currentRunId);if(k)bO(k),await k.completion,M=k.id}let A=C0.get(K);if(A)A.controller.abort("session-delete"),await A.completion;if(_)await _.clearGoal().catch((k)=>{m.warn("[SessionRoutes] Failed to clear session goal:",k)});if(await E.deleteSession(X.sessionId,X.projectPath),R.publish(X,"session.deleted",{}),M)I2(M);t.delete(K),Q.delete(K),x.delete(K);let j=$.get(K);if(j){if(!await T.remove(K,j))throw new q("Session Runtime is still active and cannot be deleted")}if(L)try{await E0.restoreSession(L),await E0.exit({sessionId:X.sessionId,action:"remove",discardChanges:!0})}catch(k){m.warn(`[SessionRoutes] Failed to remove deleted task worktree ${X.sessionId}:`,k)}return Z.json({success:!0})}catch(X){if(m.error("[SessionRoutes] Failed to delete session:",X),X instanceof H||X instanceof y||X instanceof B0)throw X;throw new r("Failed to delete session")}}),O.get("/:sessionId/message",async(Z)=>{let V=Z.req.param("sessionId");try{let Y=await N0(V,Z.req.query("projectPath")),X=t.get(v(Y)),K=X?.messages?X.messages:await E.loadSession(Y.sessionId,Y.projectPath);return Z.json(Y$(K))}catch(Y){if(m.error("[SessionRoutes] Failed to get messages:",Y),Y instanceof H||Y instanceof y||Y instanceof B0)throw Y;throw new r("Failed to get messages")}}),O.get("/:sessionId/events",async(Z)=>{let V=Z.req.param("sessionId"),Y=await N0(V,Z.req.query("projectPath"));try{await E.assertSessionWritable(Y.sessionId,Y.projectPath)}catch(L){if(L instanceof V$)throw new q(L.message);throw L}let X=await i(Y),K=Z.req.header("Last-Event-ID")??Z.req.query("lastEventId"),D=K?Number.parseInt(K,10):Number.NaN,_=Number.isInteger(D)?D+1:void 0;return A2(Z,async(L)=>{let A,j,k=!1,K0,P0,j0=new Promise((g)=>{P0=g}),G0=()=>{if(j!==void 0)clearInterval(j),j=void 0;A?.(),A=void 0},O0=(g)=>{if(k)return;k=!0,G0(),K0?.close(g),P0()},r0=new Set;L.onAbort(O0),K0=new HO({write:async(g)=>{await L.writeSSE(g)},onFailure:(g)=>{m.warn(`[SessionRoutes] SSE egress closed for ${Y.sessionId}: kind=${g.kind} pendingItems=${g.pendingItems??0} pendingBytes=${g.pendingBytes??0}`),O0(g)}}),A=R.subscribe((g)=>{if(g.sessionId!==Y.sessionId||g.projectPath!==Y.projectPath)return;let P=g.properties.requestId;if((g.type==="permission.asked"||g.type==="question.required"||g.type==="elicitation.required")&&typeof P==="string"){if(r0.has(P))return;r0.add(P)}if(g.type==="subagent.completion.queued")I(Y,()=>q0(X)).catch((S)=>{m.error(`[SessionRoutes] Failed to wake background completion for ${X.id}:`,S)});K0?.observe(S2(g),g.seq)});try{if(L.aborted||k)return;let g=D0(X.currentRunId),P=_0(g)?await e(X):void 0;try{let l=P?.value,d=l?.getPendingSteeringCount()??0;await K0.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:Y.sessionId,projectPath:Y.projectPath,timestamp:Date.now(),status:_0(g)?g.status:"idle",runId:_0(g)?g.id:void 0,queued:d,pendingInputDelivery:d>0?l?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:l?.getRecoveredSteeringCount()??0}})})}finally{P?.release()}if(L.aborted||k)return;if(_!==void 0){if(await E1.for(Y.sessionId,Y.projectPath).replay({onCommitted:async(d)=>{if(L.aborted||k)return;let s=y2(d);if(s.seq===void 0)return;await K0.writeReplay({...typeof d.seq==="number"?{id:String(d.seq)}:{},data:JSON.stringify({type:s.type,...s.seq!==void 0?{seq:s.seq}:{},properties:{...s.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})},s.seq)}},_),L.aborted||k)return}if(K0.finishInitialization({replayed:_!==void 0}),L.aborted||k)return;if(!g&&!C0.has(v(Y))){let d=(await a0.list(Y.projectPath,Y.sessionId)).some((s)=>s.completion===void 0)?await h(X,(s)=>a0.recoverInterrupted(Y.projectPath,Y.sessionId,s)):void 0;if(d)X.messages=await E.loadSession(Y.sessionId,Y.projectPath),await n0(X),R.publish(Y,"review.completed",{reviewId:d.reviewId,status:d.status,findings:0,recovered:!0})}if(L.aborted||k)return;if(!g)await o0.recoverResponded(Y.projectPath,Y.sessionId);if(L.aborted||k)return;let S=g?void 0:await o0.findPending(Y.projectPath,Y.sessionId),u=g?.pendingPermission??(S?{permissionId:S.request.requestId,details:o0.confirmationDetails(S),resolve:()=>{return}}:void 0);if(u){r0.add(u.permissionId);let l=u1(u,!0);K0.observe({data:JSON.stringify({type:l.type,properties:{...l.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})})}if(L.aborted||k)return;if(q0(X).catch((l)=>{m.error(`[SessionRoutes] Failed to resume pending input for ${V}:`,l)}),L.aborted||k)return;j=setInterval(()=>{if(L.aborted||k)return;K0?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await j0}finally{O0()}})}),O.post("/:sessionId/message",async(Z)=>{let V=Z.req.param("sessionId"),Y=await Z.req.json(),X=f(C2,Y);if(!X.success)throw new H("Invalid message format");let{content:K,attachments:D,modelId:_,reasoningEffort:L,serviceTier:M,responseVerbosity:A,communicationStyle:j,permissionMode:k,projectPath:K0,outputSchema:P0}=X.data,j0;if(P0)try{j0=X$(P0).schema}catch(d){throw new H(d instanceof Error?d.message:"Invalid output schema")}let G0=j,O0=_?.trim();if((D??[]).reduce((d,s)=>d+(typeof s.content==="string"?Buffer.byteLength(s.content):0),0)>aO)throw new H("Message attachments exceed the 5 MiB limit");let g=k,P=F1(K,D),S=await $0(V,K0??Z.req.query("projectPath")),u=g??S.permissionMode??"default",l=z0(S);return I(l,async()=>{let d=D0(S.currentRunId);if(_0(d)){if(j0)throw new q("Wait for the active turn to finish before setting an output schema");return h(S,async(n)=>{if(O0&&!n.getModelById(O0))throw new H(`Model not found: ${O0}`);if(O0&&n.getCurrentModelId()!==O0)throw new q("Wait for the active turn to finish before switching models");if(L&&n.getReasoningConfiguration().selection!==L)throw new q("Wait for the active turn to finish before switching reasoning effort");if(M&&n.getServiceTierConfiguration().selection!==M)throw new q("Wait for the active turn to finish before switching service tier");if(A&&n.getResponseVerbosityConfiguration().selection!==A)throw new q("Wait for the active turn to finish before switching response verbosity");if(G0&&n.getCommunicationStyleConfiguration().selection!==G0)throw new q("Wait for the active turn to finish before switching communication style");if(g&&S.permissionMode!==g)throw new q("Wait for the active turn to finish before switching permission mode");let Y0=await n.enqueueSteering(P,{allowBeforeTurn:!0});if(!Y0.accepted)return Z.json({status:"rejected",reason:Y0.reason??"turn_unavailable"},409);let d0=Y0.messageId??QO(12),_O=Y0.queued;R.publish(l,"message.created",{messageId:d0,role:"user",content:_$(P)});let hO=Y0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(R.publish(l,hO,{runId:d.id,messageId:d0,queued:_O}),Y0.delivery==="next_turn"&&d.status!=="running"&&d.status!=="waiting_permission")q0(S).catch((gO)=>{m.error(`[SessionRoutes] Failed to wake queued follow-up for ${V}:`,gO)});if(Y0.delivery==="next_turn")d.pendingFollowUpRequested=!0;return Z.json({runId:d.id,messageId:d0,status:Y0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:_O},202)})}if(S.permissionMode!==u)await S0(S,u);let s=await e(S,{permissionMode:u,...G0&&!G0.includes(":")?{communicationStyle:G0}:{}}),UO=!1;try{let n=s.value;if(O0&&!n.getModelById(O0))throw new H(`Model not found: ${O0}`);if(L)try{n.resolveReasoningConfiguration(L,O0)}catch(X0){throw new H(X0 instanceof Error?X0.message:"Invalid reasoning effort")}if(M)try{n.resolveServiceTierConfiguration(M,O0)}catch(X0){throw new H(X0 instanceof Error?X0.message:"Invalid service tier")}if(A)try{n.resolveResponseVerbosityConfiguration(A,O0)}catch(X0){throw new H(X0 instanceof Error?X0.message:"Invalid response verbosity")}let Y0=G0?n.resolveCommunicationStyleConfiguration(G0):void 0;if(Y0?.source!==void 0&&Y0.source!=="built-in"&&!Y0.contentSha256)throw new H("Custom communication style has no provenance");let d0=n.getCurrentModelId(),_O=n.getReasoningConfiguration(),hO=n.getServiceTierConfiguration(),gO=n.getResponseVerbosityConfiguration(),f$=n.getCommunicationStyleConfiguration(),y$=Boolean(O0)&&d0!==O0,m$=Boolean(L)&&_O.selection!==L,h$=Boolean(M)&&hO.selection!==M,g$=Boolean(A)&&gO.selection!==A,v$=Boolean(G0)&&f$.selection!==G0;if(y$||m$||h$||g$||v$)await n.refresh({...O0?{modelId:O0}:{},...L?{reasoningEffort:L}:{},...M?{serviceTier:M}:{},...A?{responseVerbosity:A}:{},...G0?{communicationStyle:G0}:{}});let O$={...O0&&S.selectedModelId!==O0?{selectedModelId:O0}:{},...L&&S.reasoningEffort!==L?{reasoningEffort:L}:{},...M&&S.serviceTier!==M?{serviceTier:M}:{},...A&&S.responseVerbosity!==A?{responseVerbosity:A}:{},...Y0&&(S.communicationStyle!==G0||S.communicationStyleDigest!==Y0.contentSha256)?{communicationStyle:G0,communicationStyleDigest:Y0.source==="built-in"?null:Y0.contentSha256}:{}};if(Object.keys(O$).length>0)try{let X0=await E.updateSessionMetadata(S.id,S.projectPath,O$);S.permissionMode=X0.permissionMode,S.selectedModelId=X0.selectedModelId,S.reasoningEffort=X0.reasoningEffort,S.serviceTier=X0.serviceTier,S.responseVerbosity=X0.responseVerbosity,S.communicationStyle=X0.communicationStyle,S.communicationStyleDigest=X0.communicationStyleDigest,S.updatedAt=new Date(X0.lastMessageTime),R.publish(l,"session.updated",O$)}catch(X0){if(y$||m$||h$||g$||v$)await n.refresh({...d0?{modelId:d0}:{},reasoningEffort:_O.selection,serviceTier:hO.selection,responseVerbosity:gO.selection,communicationStyle:f$.selection}).catch((a4)=>m.error("[SessionRoutes] Failed to roll back non-durable model settings:",a4));throw X0}let DO=j0?await n.prepareInputTurn(P,{outputSchema:j0}):await n.prepareInputTurn(P);if(!DO.accepted)return Z.json({status:"rejected",reason:DO.reason},DO.reason==="queue_full"?429:409);let $$=o(S,P,u,{preparedInputTurn:DO,outputSchema:j0,runtimeLease:s});return UO=!0,await $$.taskAdmissionUpdate,Z.json({runId:$$.id,messageId:DO.messageId,status:$$.status==="queued"?"queued":"running",queuePosition:S.taskQueuePosition,queueDepth:S.taskQueueDepth,maxConcurrentTasks:S.taskConcurrencyLimit},202)}finally{if(!UO)s.release()}})}),O.post("/:sessionId/side-question",async(Z)=>{let V=Z.req.param("sessionId"),Y=f(h1,await Z.req.json());if(!Y.success)throw new H("Invalid side conversation request");let X=await $0(V,Y.data.projectPath??Z.req.query("projectPath"));return h(X,async(K)=>{let D=await K.askSideQuestion(Y.data.question,{signal:Z.req.raw.signal});return Z.json({...D,...K.getCurrentModelId()?{modelId:K.getCurrentModelId()}:{}})})}),O.post("/:sessionId/shell",async(Z)=>{let V=Z.req.param("sessionId"),Y=f(m1,await Z.req.json());if(!Y.success)throw new H("Invalid user shell command");let X=await $0(V,Y.data.projectPath??Z.req.query("projectPath")),K=z0(X),D=v(K);return I(K,async()=>{if(I0.has(D))throw new q("A user shell command is already running in this Session");let _=await e(X),L=_.value,M=new AbortController,A,j=new Promise((k)=>{A=k});I0.set(D,{controller:M,completion:j});try{let k=await L.executeUserShellCommand(Y.data.command,{signal:M.signal});X.messages=await E.loadSession(X.id,X.projectPath),X.updatedAt=new Date;let K0=D0(X.currentRunId);if(k.delivery==="next_turn"&&_0(K0))K0.pendingFollowUpRequested=!0;return Z.json({executionId:k.executionId,messageId:k.messageId,record:k.record,auxiliary:k.auxiliary,...k.delivery?{delivery:k.delivery}:{},...k.queued!==void 0?{queued:k.queued}:{}})}finally{I0.delete(D),A(),_.release()}})}),O.post("/:sessionId/abort",async(Z)=>{let V=Z.req.param("sessionId"),Y=await N0(V,Z.req.query("projectPath")),X=t.get(v(Y));if(X?.currentRunId){let _=D0(X.currentRunId);if(_)bO(_),await _.completion}let K=I0.get(v(Y));if(K)K.controller.abort("user-cancel"),await K.completion;let D=C0.get(v(Y));if(D)D.controller.abort("user-cancel"),await D.completion;return Z.json({success:!0})}),O.get("/:sessionId/status",async(Z)=>{let V=Z.req.param("sessionId"),Y=await N0(V,Z.req.query("projectPath")),X=t.get(v(Y)),K=C0.get(v(Y));if(K)return Z.json({sessionId:V,projectPath:Y.projectPath,reviewId:K.reviewId,status:"reviewing"});if(!X?.currentRunId)return Z.json({sessionId:V,projectPath:Y.projectPath,status:"idle"});let D=D0(X.currentRunId);return Z.json({sessionId:V,projectPath:Y.projectPath,runId:X.currentRunId,status:D?.status||"idle"})}),{app:O,dispatchTask:w0,retryTask:V0,updateTask:S$,getTaskDiff:rO,deliverTask:yO,recoverQueuedTasks:eO,getRuntimeResidencyStats:()=>T.getStats(),getCoordinationStats:()=>({messageSubmissions:G.getStats(),taskDeliveries:z.getStats()}),shutdown:(Z="server-shutdown")=>{if(w)return w;return B.close(Z),clearInterval(C),w=(async()=>{let V,Y=async(L)=>{let M=await Promise.allSettled(L);for(let A of M)if(A.status==="rejected")V??=A.reason},X=new Set,K=()=>{for(let L of b0.values()){if(L.completion)X.add(L.completion);if(_0(L))bO(L,Z)}for(let L of I0.values())L.controller.abort(Z),X.add(L.completion);for(let L of C0.values())L.controller.abort(Z),X.add(L.completion)},D=B.waitForIdle(),_=!1;D.then(()=>{_=!0});while(!_)K(),await Promise.race([D,new Promise((L)=>setImmediate(L))]);if(await D,K(),await Y([...X]),await Y([...x.values()]),K(),await Y([...X]),await Y([T.disposeAll()]),$.clear(),await Y([...J.values()]),await Y([U0.getInstance().disconnectAll()]),x.clear(),J.clear(),Q.clear(),t.clear(),YO===q0)YO=void 0;if(V!==void 0)throw V})(),w}}};async function h2(O,$,x,J,Q,G={}){let{abortController:z,sessionId:F,id:T}=O,B=G.preparedInputTurn?.messageId??QO(12),w=G.pendingInputOnly===!0||G.preparedInputTurn?.mode==="pending"||G.goalContinuationOnly===!0?void 0:QO(12),W=G.runtimeLease,I,J0,p=z0($),b=(h,Z0)=>{R.publish(p,h,Z0)},e=async()=>{let h=String(z.signal.reason||"Task run cancelled");if($.taskIsolation){if(!W)W=await Q($).catch(()=>{return});let Z0=I??W?.value;if(h==="user-cancel")await Z0?.discardPendingInput().catch(($0)=>{m.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,$0)});let i=await Z0?.setTaskStatus("cancelled",h).catch(()=>{return});if(i)zO($,i);else await n0($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=h,$.taskCompletedAt??=new Date().toISOString()};try{if(G.taskAdmission){if(await G.taskAdmission.ready,await O.taskAdmissionUpdate,z.signal.aborted)throw Error(String(z.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!G.pendingInputOnly&&!G.goalContinuationOnly)b("message.created",{messageId:B,role:"user",content:_$(x)});if(b("session.status",{status:"running"}),w)b("message.created",{messageId:w,role:"assistant",content:""});W??=await Q($),I=W.value;let h=I,Z0=Boolean(G.outputSchema??h.getPendingSteeringMessages().find((N)=>N.outputSchema)?.outputSchema);J0=await I1.createWithRuntime(h,{sessionId:F,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let i=async(N)=>{let V0=N.interactionRequestId??QO(12),S$=300000;O.status="waiting_permission";let rO=new Promise((q0)=>{let eO=setTimeout(()=>{m.warn(`[SessionRoutes] Permission ${V0} timed out after 300000ms`),b("permission.timeout",{requestId:V0}),q0({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:V0,resolve:(P$)=>{clearTimeout(eO),q0(P$)},details:N}}),FO=O.pendingPermission;if(!FO)throw Error("Permission request was not registered");let yO=u1(FO);b(yO.type,yO.properties),m.info(`[SessionRoutes] Permission request created: ${V0}, runId: ${T}`);let mO=await rO;if(m.info(`[SessionRoutes] Permission response received: ${V0}, approved: ${mO.approved}`),!z.signal.aborted)O.status="running";if(O.pendingPermission===FO)O.pendingPermission=void 0;return b("interaction.resolved",{requestId:V0}),mO},S0={messages:await E.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:F,workspaceRoot:$.projectPath,signal:z.signal,permissionMode:J,onPermissionModeChange:async(N)=>{$.permissionMode=N,$.updatedAt=new Date,b("session.updated",{permissionMode:N})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:i}},o=()=>{if(!w)w=QO(12),b("message.created",{messageId:w,role:"assistant",content:""});return w},p0=async(N)=>{switch(N.kind){case"content_delta":if(Z0)break;b("message.delta",{messageId:o(),delta:N.delta});break;case"structured_output":b("structured.output",{messageId:o(),output:N.output,schemaDigest:N.schemaDigest});break;case"thinking_delta":b("thinking.delta",{messageId:o(),delta:N.delta});break;case"tool_start":if("function"in N.toolCall){if(N.toolCall.function.name===ZO)break;b("tool.start",{messageId:o(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,arguments:N.toolCall.function.arguments,toolKind:N.toolKind})}break;case"tool_result":if("function"in N.toolCall){if(N.toolCall.function.name===ZO)break;b("tool.result",{messageId:o(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,success:N.result.success,summary:N.result.metadata?.summary,output:IO(qO(kO(N.toolCall.function.name,N.result),EO)),metadata:RO(N.toolCall.function.name,N.result.metadata)})}break;case"tool_progress":if("function"in N.toolCall){if(N.toolCall.function.name===ZO)break;b("tool.progress",{messageId:o(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,...N.update})}break;case"token_usage":b("token.usage",{...N.usage});break;case"turn_start":b("turn.started",{turn:N.turn,maxTurns:N.maxTurns});break;case"provider_admission":b("provider.admission",{phase:N.phase,requestClass:N.requestClass,resource:N.resource,scope:N.scope,reason:N.reason,queuePosition:N.queuePosition,queueDepth:N.queueDepth,inFlight:N.inFlight,limit:N.limit,waitMs:N.waitMs,maxWaitMs:N.maxWaitMs,recoveryRemainingMs:N.recoveryRemainingMs});break;case"provider_circuit":b("provider.circuit",{phase:N.phase,reason:N.reason,statusCode:N.statusCode,retryAfterMs:N.retryAfterMs,nextProbeAt:N.nextProbeAt,openDurationMs:N.openDurationMs,sampleCount:N.sampleCount,failureCount:N.failureCount,recoveryRemainingMs:N.recoveryRemainingMs});break;case"provider_retry":b("provider.retry",{phase:N.phase,attempt:N.attempt,maxRetries:N.maxRetries,reason:N.reason,statusCode:N.statusCode,delayMs:N.delayMs,nextRetryAt:N.nextRetryAt,mode:N.mode,recoveryBudgetMs:N.recoveryBudgetMs,recoveryElapsedMs:N.recoveryElapsedMs,recoveryRemainingMs:N.recoveryRemainingMs,exhaustedBy:N.exhaustedBy});break;case"provider_stall":b("provider.stall",{phase:N.phase,stallCount:N.stallCount,durationMs:N.durationMs,warningAfterMs:N.warningAfterMs,timeoutMs:N.timeoutMs,outputStarted:N.outputStarted});break;case"action_stationarity":b("action.stationarity",{phase:N.phase,toolName:N.toolName,runLength:N.runLength,nudgeThreshold:N.nudgeThreshold,haltThreshold:N.haltThreshold,progressAware:N.progressAware});break;case"mcp_catalog_changed":b("mcp.catalog.changed",{messageId:o(),revision:N.revision,serverName:N.serverName,added:N.added,removed:N.removed,updated:N.updated});break;case"mcp_content_changed":b("mcp.content.changed",{messageId:o(),revision:N.revision,serverName:N.serverName,contentKind:N.contentKind,added:N.added,removed:N.removed,updated:N.updated});break;case"mcp_resource_updated":b("mcp.resource.updated",{messageId:o(),revision:N.revision,serverName:N.serverName,uri:N.uri});break;case"mcp_connection_changed":b("mcp.connection.changed",{messageId:o(),revision:N.revision,serverName:N.serverName,phase:N.phase,reason:N.reason,attempt:N.attempt,maxAttempts:N.maxAttempts,nextRetryAt:N.nextRetryAt,error:N.error});break;case"mcp_log":b("mcp.log",{messageId:o(),revision:N.revision,serverName:N.serverName,level:N.level,logger:N.logger,message:N.message,projectedBytes:N.projectedBytes,dataSha256:N.dataSha256,truncated:N.truncated,detailsOmitted:N.detailsOmitted,timestamp:N.timestamp,synthetic:N.synthetic});break;case"mcp_instructions_changed":b("mcp.instructions.changed",{messageId:o(),revision:N.revision,serverName:N.serverName,action:N.action,reason:N.reason,text:N.text,sourceBytes:N.sourceBytes,projectedBytes:N.projectedBytes,sha256:N.sha256,truncated:N.truncated,detailsOmitted:N.detailsOmitted});break;case"mcp_task_changed":b("mcp.task.changed",{messageId:o(),revision:N.revision,taskId:N.taskId,serverName:N.serverName,toolName:N.toolName,status:N.status,statusMessage:N.statusMessage,createdAt:N.createdAt,updatedAt:N.updatedAt,completedAt:N.completedAt,hasResult:N.hasResult,error:N.error});break;case"project_rules_loaded":b("project.rules.loaded",{messageId:o(),files:N.files,triggerPaths:N.triggerPaths,blockedWrite:N.blockedWrite});break;case"steering_applied":b("steering.applied",{runId:T,messageIds:N.messageIds,count:N.count,recovered:N.recovered,delivery:N.delivery,queued:h.getPendingSteeringCount()});break;case"follow_up_started":{if(w)b("message.complete",{messageId:w}),w=void 0;for(let V0 of N.messages){if(!V0.recovered||V0.persisted)continue;b("message.created",{messageId:V0.id,role:"user",content:_$(V0.content),recovered:!0})}b("follow_up.started",{runId:T,queued:N.queued,recovered:N.recovered}),o();break}case"goal_updated":b("goal.updated",{goal:N.goal});break;case"goal_continuation_started":b("goal.continuation.started",{goal:N.goal,continuation:N.continuation}),o();break;case"compaction":b(N.phase==="start"?"compaction.started":"compaction.completed",{...N.reason?{reason:N.reason}:{},...N.strategy?{strategy:N.strategy}:{},...N.outcome?{outcome:N.outcome}:{},...N.preTokens!==void 0?{preTokens:N.preTokens}:{},...N.postTokens!==void 0?{postTokens:N.postTokens}:{}});break;case"model_fallback":b("model.fallback",{});break;case"task_update":b("task.updated",{tasks:N.tasks});break;default:break}},w0=await K$(J0.chatStream(x,S0,{stream:!0,pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly,outputSchema:G.outputSchema,taskAdmission:G.taskAdmission}),p0);if(!w0.success)throw Error(w0.error?.message??"Agent run failed");for(let N=0;N<20;N++){let V0=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,h.getPendingSteeringCount()===0){if(!V0)break;continue}if(z.signal.aborted)break;if(w0=await K$(J0.chatStream("",S0,{stream:!0,pendingInputOnly:!0,taskAdmission:G.taskAdmission}),p0),!w0.success)throw Error(w0.error?.message??"Agent follow-up failed")}if($.messages=await E.loadSession($.id,$.projectPath),$.updatedAt=new Date,await n0($),z.signal.aborted||O.status==="cancelled"){await e(),b("session.status",{status:"idle"});return}if(w)b("message.complete",{messageId:w});b("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),b("session.completed",{runId:T,outputTruncated:w0.metadata?.outputTruncated??!1}),b("session.status",{status:"idle"})}catch(h){if(I&&G.preparedInputTurn)await I.finishTurn(G.preparedInputTurn.handle).catch(()=>{return});if(z.signal.aborted||O.status==="cancelled"){bO(O,"runtime-abort"),await e(),b("session.status",{status:"idle"});return}await n0($).catch(()=>{return}),m.error("[SessionRoutes] Agent execution error:",h),O.status="failed",$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let Z0=iO(h);if(!$.taskFailure){let i=I?await I.setTaskStatus("failed",h).catch(()=>{return}):await E.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:Z0.message,taskFailure:Z0,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(i)zO($,i)}$.taskStatusReason??=Z0.message,$.taskFailure??=Z0,b("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),b("session.status",{status:"error"})}finally{if(G.taskAdmission?.release(),G.taskAdmission){let h=f0.getStats();b("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:h.queued,taskConcurrencyLimit:h.maxConcurrent,taskInFlight:h.inFlight,taskAdmissionPaused:h.paused,updatedAt:new Date().toISOString()})}if(await J0?.destroy().catch(()=>{return}),W?.release(),O.disposeRuntimeOnSettle&&G.disposeRuntime)await G.disposeRuntime($,I).catch((h)=>{m.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,h)});k2(O)}}async function d1(O,$,x){m.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),m.info(`[SessionRoutes] Active runs: ${b0.size}`);for(let[G,z]of b0.entries())if(m.info(`[SessionRoutes] Checking run ${G}: sessionId=${z.sessionId}, projectPath=${z.projectPath}, pendingPermission=${z.pendingPermission?.permissionId}`),z.sessionId===O.sessionId&&z.projectPath===O.projectPath&&z.pendingPermission?.permissionId===$){if(z.pendingPermission.details.interactionRequestId)await o0.respond(O.projectPath,O.sessionId,$,x);return z.pendingPermission.resolve(x),m.info(`[SessionRoutes] Permission ${$} responded, runId: ${z.id}`),!0}let J=await o0.findPending(O.projectPath,O.sessionId);if(!J||J.request.requestId!==$)return m.error(`[SessionRoutes] Permission not found: ${$}`),!1;await o0.respondAndRecover(O.projectPath,O.sessionId,$,x);let Q=t.get(v(O));if(!Q){let G=await E.findSessionMetadata(O.sessionId,O.projectPath);if(!G)return!1;let[z,F]=await Promise.all([E.loadSession(O.sessionId,O.projectPath),E.findSessionTaskWorktree(O.sessionId,O.projectPath)]);Q=CO(G,z,F),t.set(v(O),Q)}else await n0(Q);if(R.publish(O,"interaction.resolved",{requestId:$}),YO)YO(Q).catch((G)=>{m.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,G)});return!0}var H$=a("Service"),v2=U.Object({approved:U.Boolean(),remember:U.Optional(U.Boolean()),scope:U.Optional(F0(["once","session","project"])),targetMode:U.Optional(F0(["default","autoEdit","plan","yolo"])),feedback:U.Optional(U.String({maxLength:4000})),answers:U.Optional(U.Record(U.String({maxLength:80}),U.Union([U.String({maxLength:4000}),U.Array(U.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:U.Optional(U.Object({action:F0(["accept","decline","cancel"]),content:U.Optional(U.Record(U.String(),U.Union([U.String({maxLength:4000}),U.Number(),U.Boolean(),U.Array(U.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),l1=()=>{let O=new g2;return O.post("/:permissionId",async($)=>{let x=$.req.param("permissionId"),J=$.req.query("sessionId"),Q=$.req.query("projectPath");H$.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${J}`);try{let G=await $.req.json(),z=f(v2,G);if(!z.success)throw new H("Invalid permission response format");let{approved:F,remember:T,scope:B,targetMode:C,feedback:w,answers:W,elicitation:I}=z.data;if(!J)throw new H("sessionId query parameter is required");let J0=await N0(J,Q);if(!await d1(J0,x,{approved:F,reason:w,scope:B,targetMode:C,feedback:w,answers:W,elicitation:I}))throw new y("Permission request",x);return H$.info(`[PermissionRoutes] Permission ${x} ${F?"approved":"denied"}`),$.json({success:!0,approved:F,remember:T})}catch(G){if(H$.error("[PermissionRoutes] Failed to respond to permission:",G),G instanceof H||G instanceof B0||G instanceof y||G instanceof Q0)throw G;throw G}}),O};import c1 from"node:path";import{Hono as u2}from"hono";var p2=U.Object({projectPath:U.String({minLength:1}),enabled:U.Boolean(),scope:U.Optional(F0(["local","project","global"]))}),d2=U.Object({projectPath:U.String({minLength:1})}),l2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),trust:U.Literal(!0),ref:U.Optional(U.String({minLength:1}))}),c2=U.Object({projectPath:U.String({minLength:1}),trust:U.Literal(!0)}),i2=U.Object({projectPath:U.String({minLength:1}),confirm:U.Literal(!0)}),a2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),ref:U.Optional(U.String({minLength:1}))}),i1=U.Object({projectPath:U.String({minLength:1}),confirm:U.Optional(U.Literal(!0))}),o2=U.Object({projectPath:U.String({minLength:1}),scope:U.Optional(F0(["local","project","global"])),policy:U.Object({restrictToAllowedSources:U.Boolean(),requireGitCommitSha:U.Boolean(),allowedGitHosts:U.Array(U.String()),allowedMarketplaces:U.Array(U.String()),allowedLocalRoots:U.Array(U.String())})});function M0(O){if(!O||!c1.isAbsolute(O))throw new H("projectPath must be absolute");return c1.resolve(O)}async function a1(O){let[$,x]=await Promise.all([T0(O),LO.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((J)=>({name:J.manifest.name,description:J.manifest.description,version:J.manifest.version,source:J.source,enabled:J.status==="active",status:J.status,commands:J.commands.length,skills:J.skills.length,agents:J.agents.length,hooks:J.hooks?Object.values(J.hooks).reduce((Q,G)=>Q+(Array.isArray(G)?G.length:0),0):0,mcpServers:Object.keys(J.mcpServers??{}).length,configurable:J.source!=="cli",managed:J.installation!==void 0,marketplace:J.installation?.source.type==="marketplace"?J.installation.source.marketplace:void 0,revision:J.installation?.revision,installedAt:J.installation?.installedAt,updatedAt:J.installation?.updatedAt,compatibilityIssues:J.compatibilityIssues??[],effectiveScope:J.source==="cli"?"invocation":x.settings[J.manifest.name]?.effectiveScope??"default",settingLayers:J.source==="cli"?{invocation:!0}:x.settings[J.manifest.name]?.layers??{}}))}async function n2(){let O=o1(),[$,x]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),J=new Map(x.map((Q)=>[Q.name,Q]));return $.map(({marketplace:Q,manifest:G})=>({name:Q.name,description:G.description??G.metadata?.description??"",sourceType:Q.source.type,revision:Q.revision,updatedAt:Q.updatedAt,plugins:G.plugins.map((z)=>{let F=J.get(z.name);return{name:z.name,description:z.description??"",version:z.version,category:z.category,tags:z.tags??[],installed:F!==void 0,installedVersion:F?.version}})}))}function GO(O,$){if(!O.success)throw new H(O.error??$)}var Q4=()=>{let O=new u2;return O.get("/",async($)=>{let x=M0($.req.query("projectPath"));return $.json(await a1(x))}),O.post("/refresh",async($)=>{let x=f(d2,await $.req.json());if(!x.success)throw new H("Invalid plugin refresh request");let J=M0(x.data.projectPath),Q=await t1(J);return $.json({plugins:await a1(J),errors:Q.discovery.errors.map((G)=>({code:G.code??"LOAD_ERROR",error:G.error}))})}),O.get("/catalog",async($)=>{return M0($.req.query("projectPath")),$.json(await n2())}),O.get("/policy",async($)=>{let x=M0($.req.query("projectPath")),J=await LO.getInstance().loadWorkspacePluginSourcePolicy(x);return $.json({policy:J,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let x=f(o2,await $.req.json());if(!x.success)throw new H("Invalid plugin source policy request");let J=M0(x.data.projectPath),Q=await s1(J,x.data.policy,x.data.scope??"global");return $.json({policy:Q})}),O.post("/install",async($)=>{let x=f(l2,await $.req.json());if(!x.success)throw new H("Invalid plugin install request; explicit source trust is required");let J=M0(x.data.projectPath),{result:Q}=await r1(J,x.data.source,{trusted:x.data.trust,ref:x.data.ref});return GO(Q,"Plugin installation failed"),$.json({name:Q.pluginName,version:Q.manifest?.version,revision:Q.installation?.revision,changed:Q.changed,installedDependencies:Q.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let x=f(a2,await $.req.json());if(!x.success)throw new H("Invalid marketplace add request");let J=M0(x.data.projectPath),Q=await $4(J,x.data.source,x.data.ref);return GO(Q,"Marketplace installation failed"),$.json({name:Q.marketplace?.name,plugins:Q.manifest?.plugins.length??0,revision:Q.marketplace?.revision,changed:Q.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let x=f(i1,await $.req.json());if(!x.success)throw new H("Invalid marketplace refresh request");let J=await x4(M0(x.data.projectPath),$.req.param("name"));return GO(J,"Marketplace refresh failed"),$.json({name:J.marketplace?.name,plugins:J.manifest?.plugins.length??0,revision:J.marketplace?.revision,changed:J.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let x=f(i1,await $.req.json());if(!x.success||x.data.confirm!==!0)throw new H("Invalid marketplace removal request; explicit confirmation is required");M0(x.data.projectPath);let J=await J4($.req.param("name"),!0);return GO(J,"Marketplace removal failed"),$.json({name:J.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let x=f(c2,await $.req.json());if(!x.success)throw new H("Invalid plugin update request; explicit source trust is required");let J=M0(x.data.projectPath),{result:Q}=await e1(J,$.req.param("name"),{trusted:x.data.trust});return GO(Q,"Plugin update failed"),$.json({name:Q.pluginName,version:Q.manifest?.version,revision:Q.installation?.revision,changed:Q.changed,updatedDependencies:Q.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let x=f(i2,await $.req.json());if(!x.success)throw new H("Invalid plugin uninstall request; explicit confirmation is required");let J=M0(x.data.projectPath),{result:Q}=await O4(J,$.req.param("name"),x.data.confirm);return GO(Q,"Plugin uninstall failed"),$.json({name:Q.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let x=f(p2,await $.req.json());if(!x.success)throw new H("Invalid plugin state request");let J=M0(x.data.projectPath),Q=$.req.param("name"),z=(await T0(J)).plugins.get(Q);if(!z)throw new y("Plugin",Q);if(z.source==="cli")throw new H(`Plugin "${Q}" was loaded with --plugin-dir and is invocation-scoped`);let F=await n1(J,Q,x.data.enabled,x.data.scope??"local");return $.json(F)}),O};import{Hono as O5}from"hono";import{execFile as t2}from"node:child_process";import s2 from"node:path";var w$="__BLADE_DIRECTORY_PICKER_CANCELLED__",r2=900000;function e2(O,$){return new Promise((x)=>{t2(O,[...$],{timeout:r2,maxBuffer:65536,windowsHide:!0},(J,Q,G)=>{let z=J?.code;x({stdout:Q,stderr:G,exitCode:typeof z==="number"?z:J?1:0,...typeof z==="string"?{errorCode:z}:{}})})})}function B$(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===w$)return{cancelled:!0};if(!s2.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function L$(O){return O.exitCode!==0||Boolean(O.errorCode)}class Z4{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??e2}pick(){if(this.activeSelection)return this.activeSelection;let O=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=O,O}async pickForPlatform(){switch(this.platform){case"darwin":return this.pickOnMac();case"win32":return this.pickOnWindows();case"linux":return this.pickOnLinux();default:throw Error("Native folder selection is unavailable on this system")}}async pickOnMac(){let O=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${w$}"`,"end try"].join(`
8
+ `),$=await this.runCommand("osascript",["-e",O]);if(L$($))throw Error("Unable to open the macOS folder picker");return B$($.stdout)}async pickOnWindows(){let O=["Add-Type -AssemblyName System.Windows.Forms","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog",'$dialog.Description = "Choose a project folder"',"$dialog.ShowNewFolderButton = $true","if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {"," [Console]::Out.Write($dialog.SelectedPath)","} else {",` [Console]::Out.Write("${w$}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(L$($))throw Error("Unable to open the Windows folder picker");return B$($.stdout)}async pickOnLinux(){let O=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let $ of O){let x=await this.runCommand($.command,$.args);if(x.errorCode==="ENOENT")continue;if(x.exitCode===1&&!x.stdout.trim()&&!x.stderr.trim())return{cancelled:!0};if(L$(x))throw Error("Unable to open the Linux folder picker");return B$(x.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var Y4=new Z4;var $5=U.Object({path:U.String({minLength:1})});function x5(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let $=new URL(O).hostname;return $==="localhost"||$==="127.0.0.1"||$==="::1"||$==="[::1]"}catch{return!1}}var z4=(O={})=>{let $=new O5,x=O.pickDirectory??(()=>Y4.pick()),J=O.allowDirectoryPickerRequest??x5;return $.get("/",async(Q)=>{return Q.json(await nO.list(c()))}),$.post("/",async(Q)=>{let G;try{G=await Q.req.json()}catch{throw new H("A valid JSON body is required")}let z=f($5,G);if(!z.success)throw new H("A project path is required");try{let F=await nO.bind(z.data.path,c());return Q.json(F,201)}catch(F){throw new H(F instanceof Error?F.message:"Failed to bind project")}}),$.post("/pick",async(Q)=>{if(!J(Q.req.header("Origin")))throw new Q0("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Q.json(await x())}catch(G){throw new H(G instanceof Error?G.message:"Failed to select a folder")}}),$.delete("/",async(Q)=>{let G=Q.req.query("path");if(!G)throw new H("A project path is required");try{let z=await nO.unbind(G);return Q.json({success:!0,removed:z})}catch(z){throw new H(z instanceof Error?z.message:"Failed to unbind project")}}),$};import{Hono as J5}from"hono";var G4=a("Service"),K4=()=>{let O=new J5;return O.get("/",async($)=>{try{let x=await V4();return $.json(x)}catch(x){return G4.error("[ProviderRoutes] Failed to list providers:",x),$.json([])}}),O.get("/:provider/models",async($)=>{let x=$.req.param("provider");try{let J=await N4(x);return $.json(J)}catch(J){return G4.error("[ProviderRoutes] Failed to list models:",J),$.json([])}}),O.put("/:provider/credential",async($)=>{let x=$.req.param("provider"),J=await $.req.json();if(!J.apiKey?.trim())throw new H("apiKey is required");return await c0().setApiKey(x,J.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await c0().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let x=$.req.param("provider"),J=x0(),Q=J?.modelProviders[x];if(!J||!Q)throw new y("Model provider",x);let G=await $.req.json();if(!G.name||!G.baseUrl||!G.wireApi)throw new H("name, baseUrl and wireApi are required");let z="apiKeyEnv"in G?G.apiKeyEnv?.trim():Q.apiKeyEnv,F={name:G.name,baseUrl:G.baseUrl,wireApi:G.wireApi,...z?{apiKeyEnv:z}:{}},T=c0(),B=G.apiKey?.trim()?await T.credentials.read(x):void 0;if(G.apiKey?.trim())await T.setApiKey(x,G.apiKey.trim());try{return await L0().updateModelProvider(x,F),$.json({success:!0})}catch(C){if(G.apiKey?.trim())if(B)await T.credentials.modify(x,async()=>B);else await T.credentials.delete(x);if(C instanceof Error&&(C.message.includes("modelProviders.")||C.message.includes("built-in provider")))throw new H(C.message);throw C}}),O.delete("/:provider",async($)=>{let x=$.req.param("provider");if(!x0()?.modelProviders[x])throw new y("Model provider",x);let Q=$.req.query("removeModels");if(Q!==void 0&&Q!=="true"&&Q!=="false")throw new H("removeModels must be true or false");try{let G=await L0().removeModelProvider(x,{removeModels:Q==="true"});return $.json({success:!0,...G})}catch(G){if(G instanceof Error&&(G.message.includes("still referenced")||G.message.includes("owns the only model")))throw new q(G.message);throw G}}),O.post("/:provider/probe",async($)=>{let x=$.req.param("provider"),J=x0();if(!J?.modelProviders[x])throw new y("Model provider",x);let Q=await $.req.json().catch(()=>({})),G=J.models.filter((F)=>F.provider===x),z=Q.modelId?G.find((F)=>F.id===Q.modelId):G[0];if(!z)throw new H(Q.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return $.json(await X4(z,J))}),O};import{Hono as Q5}from"hono";var Z5=a("Service"),_4=(O,$)=>{let x=new Q5;return x.onError((J,Q)=>{if(J instanceof Q0)return Q.json(J.toObject(),J.statusCode);return Z5.error("[ScheduleRoutes] Unhandled route error:",J),Q.json(new r("Schedule request failed").toObject(),500)}),x.get("/",async(J)=>{let Q=await O.list();return J.json(U4.parse({schedules:Q}))}),x.post("/",async(J)=>{let Q;try{Q=await J.req.json()}catch{throw new H("Invalid request body")}let G=f(W4,Q);if(!G.success)throw new H("Invalid schedule request");let z=G.data.projectPath||J.get("directory")||c();try{let F=await O.create({...G.data,projectPath:z});return J.json(t0.parse(F),201)}catch(F){throw new H(F instanceof Error?F.message:"Failed to create schedule")}}),x.get("/:id",async(J)=>{let Q=await O.get(J.req.param("id"));if(!Q)throw new y("Schedule not found");return J.json(t0.parse(Q))}),x.patch("/:id",async(J)=>{let Q;try{Q=await J.req.json()}catch{throw new H("Invalid request body")}let G=f(F4,Q);if(!G.success)throw new H("Invalid schedule update");let{modelId:z,reasoningEffort:F,serviceTier:T,responseVerbosity:B,communicationStyle:C,isolation:w,permissionMode:W,...I}=G.data,J0={...z!==void 0?{modelId:z}:{},...F!==void 0?{reasoningEffort:F}:{},...T!==void 0?{serviceTier:T}:{},...B!==void 0?{responseVerbosity:B}:{},...C!==void 0?{communicationStyle:C}:{},...w!==void 0?{isolation:w}:{},...W!==void 0?{permissionMode:W}:{}};try{let p=await O.update(J.req.param("id"),{...I,...Object.keys(J0).length>0?{dispatch:J0}:{}});if(!p)throw new y("Schedule not found");return J.json(t0.parse(p))}catch(p){if(p instanceof Q0)throw p;throw new H(p instanceof Error?p.message:"Failed to update schedule")}}),x.delete("/:id",async(J)=>{if(!await O.remove(J.req.param("id")))throw new y("Schedule not found");return J.json({ok:!0})}),x.post("/:id/enable",async(J)=>{let Q=await O.setEnabled(J.req.param("id"),!0);if(!Q)throw new y("Schedule not found");return J.json(t0.parse(Q))}),x.post("/:id/disable",async(J)=>{let Q=await O.setEnabled(J.req.param("id"),!1);if(!Q)throw new y("Schedule not found");return J.json(t0.parse(Q))}),x.post("/:id/run",async(J)=>{let Q=await O.get(J.req.param("id"));if(!Q)throw new y("Schedule not found");if(!$)throw new r("Scheduler is not running in this process");await $.fire(Q,new Date,{manual:!0});let G=await O.get(Q.id);return J.json(t0.parse(G??Q),202)}),x};import*as g0 from"node:fs/promises";import{homedir as B4}from"node:os";import*as A0 from"node:path";import{Hono as Y5}from"hono";var s0=a("Service"),D4=A0.join(B4(),".blade","skills"),M$=A0.join(B4(),".blade","skills-config.json");async function L4(){try{let O=await g0.readFile(M$,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function z5(O){await g0.mkdir(A0.dirname(M$),{recursive:!0}),await g0.writeFile(M$,JSON.stringify(O,null,2))}async function G5(O,$){let x=await L4();if($)x.disabled=x.disabled.filter((J)=>J!==O);else if(!x.disabled.includes(O))x.disabled.push(O);await z5(x)}var h0=null,X5=300000,V5=6;async function N5(){if(h0&&Date.now()-h0.timestamp<X5)return h0.data;try{let O=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!O.ok){if(s0.warn(`GitHub API returned ${O.status}`),h0)return h0.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let x=(await O.json()).filter((z)=>z.type==="dir"),J=Array(x.length),Q=0,G=Math.min(V5,x.length);return await Promise.all(Array.from({length:G},async()=>{while(Q<x.length){let z=Q++,F=x[z];if(!F)continue;let T=`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 w=(await B.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(w)T=w[1].trim().slice(0,100)}}catch{}J[z]={name:F.name,description:T,tag:"Official",author:"Anthropic"}}})),h0={data:J,timestamp:Date.now()},J}catch(O){if(s0.warn("Failed to fetch skills catalog from GitHub:",O),h0)return h0.data;throw O}}var w4=()=>{let O=new Y5;return O.get("/",async($)=>{try{let x=$.get("directory")||c(),Q=(await T0(x)).skills.getAll(),G=await L4(),z=Q.map((F)=>({id:F.name,name:F.name,enabled:!G.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"&&A0.dirname(A0.resolve(F.basePath))===A0.resolve(D4),capabilities:["prompts"],allowedTools:F.allowedTools||[]}));return $.json(z)}catch(x){return s0.error("[SkillsRoutes] Failed to get skills:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async($)=>{try{let x=$.req.param("name"),J=await $.req.json();return await G5(x,J.enabled),$.json({success:!0,enabled:J.enabled})}catch(x){return s0.error("[SkillsRoutes] Failed to toggle skill:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name"),J=$.get("directory")||c();return AO(J,async(Q)=>{let G=Q.skills,z=G.get(x);if(!z)return $.json({success:!1,error:"Skill not found"},404);let F=A0.resolve(z.basePath),T=A0.resolve(D4);if(z.source!=="user"||A0.dirname(F)!==T)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await g0.rm(F,{recursive:!0,force:!0}),await G.refresh(),MO(J),await wO(J),$.json({success:!0})})}catch(x){return s0.error("[SkillsRoutes] Failed to uninstall skill:",x),$.json({success:!1,error:x.message},500)}}),O.post("/install",async($)=>{try{let x=await $.req.json(),J=H4(),Q=$.get("directory")||c();return AO(Q,async(G)=>{let z=G.skills,F=!1;if(x.source==="catalog"&&x.name){if(F=await J.installOfficialSkill(x.name),!F)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(F=await J.installFromRepo(x.url,x.name),!F)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(x.source==="local"&&x.path){if(F=await J.installFromLocal(x.path,x.name),!F)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await z.refresh(),MO(Q),await wO(Q),$.json({success:!0})})}catch(x){return s0.error("[SkillsRoutes] Failed to install skill:",x),$.json({success:!1,error:x.message},500)}}),O.get("/catalog",async($)=>{try{let x=await N5();return $.json(x)}catch(x){return s0.error("[SkillsRoutes] Failed to get catalog:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills catalog"},502)}}),O};import{execSync as K5}from"node:child_process";import{readdir as W5}from"node:fs/promises";import tO from"node:path";import F5 from"fast-glob";import{Hono as U5}from"hono";var SO=a("Service"),_5=(O)=>{try{return K5("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},D5=[...XO.map((O)=>`${O}/**`),...XO,...XO.map((O)=>`**/${O}/**`),...XO.map((O)=>`**/${O}`),...A$.map((O)=>`**/${O}`)],H5=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),j4=()=>{let O=new U5;return O.get("/commands",async($)=>{try{let x=$.req.query("q")||"",J=$.get("directory")||c(),Q=await T0(J),G=A4(x,J,Q).filter((z)=>!H5.has(z.command));return $.json(G)}catch(x){return SO.error("[SuggestionsRoutes] Failed to get command suggestions:",x),$.json([])}}),O.get("/files",async($)=>{try{let x=$.req.query("q")||"",J=$.get("directory")||c(),Q=Math.min(Number($.req.query("limit"))||100,1000),G=$.req.query("type")==="file",F=(await F5("**/*",{cwd:J,dot:!1,followSymbolicLinks:!1,onlyFiles:G,markDirectories:!0,unique:!0,ignore:D5})).map((C)=>C.replace(/\\/g,"/"));if(!x)return $.json(F.slice(0,Q));let T=x.toLowerCase(),B=F.filter((C)=>C.toLowerCase().includes(T)).slice(0,Q);return $.json(B)}catch(x){return SO.error("[SuggestionsRoutes] Failed to get file suggestions:",x),$.json([])}}),O.get("/files/tree",async($)=>{try{let x=$.get("directory")||c(),J=$.req.query("path")||"",Q=J?tO.join(x,J):x,z=(await W5(Q,{withFileTypes:!0})).map((B)=>({name:B.name,path:J?`${J}/${B.name}`:B.name,type:B.isDirectory()?"dir":"file"}));z.sort((B,C)=>{if(B.type!==C.type)return B.type==="dir"?-1:1;return B.name.localeCompare(C.name)});let F=new Set(XO),T=z.filter((B)=>{let C=B.name;if(C.startsWith("."))return!1;if(F.has(C))return!1;for(let w of A$)if(C.match(new RegExp(w.replace("*",".*"))))return!1;return!0});return $.json(T)}catch(x){return SO.error("[SuggestionsRoutes] Failed to get file tree:",x),$.json([])}}),O.get("/files/content",async($)=>{try{let x=$.req.query("path");if(!x)return $.json({error:"Missing file path"},400);let J=$.get("directory")||c(),Q=tO.resolve(J,x),G=tO.relative(J,Q);if(G.startsWith("..")||tO.isAbsolute(G))return $.json({error:"Invalid file path"},400);let z=M4(),F=await z.stat(Q);if(!F?.isFile)return $.json({error:"File not found"},404);let T=200000,B=await z.readTextFile(Q),C=B.length>T;return $.json({path:x,content:C?B.slice(0,T):B,truncated:C,size:F.size})}catch(x){return SO.error("[SuggestionsRoutes] Failed to get file content:",x),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{try{let x=$.get("directory")||c(),J=_5(x);return $.json({branch:J})}catch(x){return SO.error("[SuggestionsRoutes] Failed to get git info:",x),$.json({branch:null})}}),O};import{Hono as B5}from"hono";var VO=a("Service"),E4=(O)=>{let $=new B5;return $.onError((x,J)=>{if(x instanceof Q0)return J.json(x.toObject(),x.statusCode);return VO.error("[TaskRoutes] Unhandled route error:",x),J.json(new r("Failed to dispatch task").toObject(),500)}),$.post("/",async(x)=>{let J;try{J=await x.req.json()}catch{throw new H("Invalid request body")}let Q=f(C4,J);if(!Q.success)throw new H("Invalid task request");if((Q.data.attachments??[]).reduce((z,F)=>z+(typeof F.content==="string"?Buffer.byteLength(F.content):0),0)>aO)throw new H("Task attachments exceed the 5 MiB limit");if(Q.data.taskDueAt&&!Number.isFinite(Date.parse(Q.data.taskDueAt)))throw new H("Invalid task due date");try{let z=await O.dispatchTask({prompt:Q.data.prompt,title:Q.data.title,taskPriority:Q.data.taskPriority,taskKind:Q.data.taskKind,taskDueAt:Q.data.taskDueAt?new Date(Q.data.taskDueAt).toISOString():void 0,sourceProjectPath:Q.data.projectPath||x.get("directory")||c(),isolation:Q.data.isolation,permissionMode:Q.data.permissionMode,modelId:Q.data.modelId,reasoningEffort:Q.data.reasoningEffort,serviceTier:Q.data.serviceTier,responseVerbosity:Q.data.responseVerbosity,communicationStyle:Q.data.communicationStyle,attachments:Q.data.attachments,outputSchema:Q.data.outputSchema});return x.json(T$.parse(z),202)}catch(z){if(z instanceof H||z instanceof q||z instanceof l0||z instanceof k0)throw z;throw VO.error("[TaskRoutes] Failed to dispatch task:",z),new r("Failed to dispatch task")}}),$.patch("/:sessionId",async(x)=>{let J;try{J=await x.req.json()}catch{throw new H("Invalid request body")}let Q=f(b4,J);if(!Q.success)throw new H("Invalid task update");if(Q.data.title===void 0&&Q.data.taskPriority===void 0&&Q.data.taskKind===void 0&&Q.data.taskDueAt===void 0)throw new H("Task update must include at least one field");if(typeof Q.data.taskDueAt==="string"&&!Number.isFinite(Date.parse(Q.data.taskDueAt)))throw new H("Invalid task due date");try{let G=await O.updateTask(x.req.param("sessionId"),{...Q.data,...typeof Q.data.taskDueAt==="string"?{taskDueAt:new Date(Q.data.taskDueAt).toISOString()}:{}},x.req.query("projectPath"));return x.json(j$.parse(G))}catch(G){if(G instanceof H||G instanceof y||G instanceof q)throw G;throw VO.error("[TaskRoutes] Failed to update task:",G),new r("Failed to update task")}}),$.post("/:sessionId/retry",async(x)=>{try{let J=await O.retryTask(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(T$.parse(J),202)}catch(J){if(J instanceof H||J instanceof y||J instanceof q||J instanceof l0||J instanceof k0)throw J;throw VO.error("[TaskRoutes] Failed to retry task:",J),new r("Failed to retry task")}}),$.get("/:sessionId/diff",async(x)=>{try{let J=await O.getTaskDiff(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(T4.parse(J))}catch(J){if(J instanceof H||J instanceof y||J instanceof q)throw J;throw VO.error("[TaskRoutes] Failed to load task diff:",J),new r("Failed to load task diff")}}),$.post("/:sessionId/delivery",async(x)=>{let J;try{J=await x.req.json()}catch{throw new H("Invalid request body")}let Q=f(R4,J);if(!Q.success)throw new H("Invalid task delivery request");try{let G=await O.deliverTask(x.req.param("sessionId"),Q.data.action,x.req.query("projectPath"));return x.json(j$.parse(G))}catch(G){if(G instanceof H||G instanceof y||G instanceof q)throw G;throw VO.error("[TaskRoutes] Failed to deliver task:",G),new r("Failed to deliver task")}}),$};import{Hono as L5}from"hono";var v0=a("Service"),NO=new Map,q4=2097152,k4=65536;function I4(){return typeof globalThis.Bun<"u"}async function w5(O,$,x){if(I4()){let{spawn:G}=await import("bun-pty"),z=G(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:z.pid,write:(F)=>z.write(F),resize:(F,T)=>z.resize(F,T),kill:()=>z.kill(),onData:(F)=>z.onData(F),onExit:(F)=>z.onExit(F)}}let Q=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:Q.pid,write:(G)=>Q.write(G),resize:(G,z)=>Q.resize(G,z),kill:()=>Q.kill(),onData:(G)=>{Q.onData(G)},onExit:(G)=>{Q.onExit(G)}}}var R$=void 0,b$;if(I4())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();b$=$.upgradeWebSocket,R$=$.websocket}catch(O){v0.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function S4(O,$){let x=`term-${Date.now()}`;v0.info(`[Terminal] New connection: ${x}, cwd: ${O}`);let J=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Q=J.endsWith("sh")?["-l"]:[],G=await w5(J,Q,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),z={id:x,process:G,cwd:O,buffer:"",subscribers:new Set};if(NO.set(x,z),z.subscribers.add($),G.onData((F)=>{let T=!1;for(let B of z.subscribers)try{B.send(F),T=!0}catch{z.subscribers.delete(B)}if(T)return;if(z.buffer+=F,z.buffer.length>q4)z.buffer=z.buffer.slice(-q4)}),G.onExit(({exitCode:F})=>{v0.info(`[Terminal] Process exited: ${x}, code: ${F}`);for(let T of z.subscribers)try{T.close()}catch{}NO.delete(x)}),z.buffer){let F=z.buffer;z.buffer="";for(let T=0;T<F.length;T+=k4)$.send(F.slice(T,T+k4))}return{session:z,cleanup:()=>{if(v0.info(`[Terminal] Connection closed: ${x}`),z.subscribers.delete($),z.subscribers.size===0){try{z.process.kill()}catch{}NO.delete(x)}}}}function P4(O,$){O.on("connection",async(x,J)=>{let Q=new URL(J.url||"/",`http://${J.headers.host}`);if(!Q.pathname.endsWith("/terminal/ws")){x.close();return}let G=Q.searchParams.get("cwd")||$()||c();try{let{session:z,cleanup:F}=await S4(G,{send:(T)=>x.send(T),close:()=>x.close()});x.on("message",(T)=>{try{z.process.write(String(T))}catch(B){v0.error("[Terminal] Failed to write to PTY:",B)}}),x.on("close",F),x.on("error",F)}catch(z){v0.error("[Terminal] Failed to spawn PTY:",z),x.close()}})}var f4=()=>{let O=new L5;if(O.get("/status",($)=>{let x=Array.from(NO.values()).map((J)=>({id:J.id,cwd:J.cwd}));return $.json({active:x.length,terminals:x})}),O.post("/kill/:terminalId",($)=>{let x=$.req.param("terminalId"),J=NO.get(x);if(J){try{J.process.kill()}catch{}for(let Q of J.subscribers)Q.close();return NO.delete(x),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),b$)O.get("/ws",b$(($)=>{let x=$.req.query("cwd")||$.get("directory")||c(),J;return{async onOpen(Q,G){try{J=await S4(x,{send:(z)=>G.send(z),close:()=>G.close()})}catch(z){v0.error("[Terminal] Failed to spawn PTY:",z),G.close()}},onMessage(Q){if(!J)return;try{J.session.process.write(String(Q.data))}catch(G){v0.error("[Terminal] Failed to write to PTY:",G)}},onClose(){J?.cleanup()}}}));else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import M5 from"node:path";import{Hono as A5}from"hono";var j5=U.Object({projectPath:U.String({minLength:1}),action:F0(["trust","revoke"])});function y4(O){if(!M5.isAbsolute(O))throw new H("projectPath must be absolute")}var h4=()=>{let O=new A5;return O.get("/",async($)=>{let x=$.req.query("projectPath");if(!x)throw new H("projectPath query parameter is required");return y4(x),$.json(await E$.getInstance().getStatus(x))}),O.post("/",async($)=>{let x=f(j5,await $.req.json());if(!x.success)throw new H("Invalid workspace trust request");let{projectPath:J,action:Q}=x.data;y4(J);let G=E$.getInstance(),z=Q==="trust"?await G.trust(J):await G.revoke(J);return await m4(),$.json({...z,reloadRequired:z.sensitiveSources>0})}),O};var W0=a("Service"),I$=[],sO,KO,WO,PO,g4=new Map,v4=new Map,y5=new Set([".css",".html",".js",".json",".svg"]),m5=1024,h5=3600000;function g5(O,$){if(!O)return 0;let x=O.split(",").map((J)=>{let[Q,...G]=J.trim().toLowerCase().split(";"),z=G.find((T)=>T.trim().startsWith("q=")),F=z?Number(z.trim().slice(2)):1;return{name:Q,quality:Number.isFinite(F)?Math.max(0,Math.min(1,F)):0}});return x.find((J)=>J.name===$)?.quality??x.find((J)=>J.name==="*")?.quality??0}function u4(){if(WO)return;let O=()=>{E.collectStaleEmptySessions().then(($)=>{if($>0)W0.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{W0.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),WO=setInterval(O,h5),WO.unref?.()}function v5(){if(!WO)return;clearInterval(WO),WO=void 0}function u5(O){return["br","gzip"].map((x)=>({encoding:x,quality:g5(O,x)})).filter((x)=>x.quality>0).sort((x,J)=>J.quality-x.quality||(x.encoding==="br"?-1:1))[0]?.encoding}function p5(O){let $=g4.get(O);if($)return $;let x=fO(O);return g4.set(O,x),x}function d5(O,$,x){let J=`${x}:${O}`,Q=v4.get(J);if(Q)return Q;let G=x==="br"?q5($,{params:{[I5.BROTLI_PARAM_QUALITY]:5}}):k5($,{level:6});return v4.set(J,G),G}function l5(){let O=b5(E5(import.meta.url)),$=[u0(O,"web"),u0(c(),"dist/web"),u0(c(),"packages/cli/dist/web")];for(let x of $){let J=u0(x,"index.html");if(k$(J)){if(fO(J,"utf-8").includes("/assets/"))return W0.debug(`[Server] Found web dist at: ${x}`),x}}return null}function c5(){let O=new S5;O.onError((J,Q)=>{if(W0.error("[Server] Request error:",J),J instanceof l4){let z=new k0(J.message,{resource:"workspace_agent_resources",limit:J.capacity});return Q.json(z.toObject(),429)}if(J instanceof Q0)return Q.json(J.toObject(),J.statusCode);let G=J instanceof Error?J.message:String(J);return Q.json({error:{code:"INTERNAL_ERROR",message:G}},500)}),O.use(async(J,Q)=>{let G=process.env.BLADE_SERVER_PASSWORD;if(!G)return Q();let z=J.req.path;if(z==="/"||z==="/favicon.svg"||z.startsWith("/assets/")||z.endsWith(".html")||z.endsWith(".js")||z.endsWith(".css"))return Q();let F=J.req.header("Authorization");if(!F?.startsWith("Basic "))return J.header("WWW-Authenticate",'Basic realm="Blade Server"'),J.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let T=Buffer.from(F.slice(6),"base64").toString(),[B,C]=T.split(":"),w=process.env.BLADE_SERVER_USERNAME??"blade";if(B!==w||C!==G)return J.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Q()}),O.use(async(J,Q)=>{let G=J.req.path==="/health"||J.req.path==="/global/health"||J.req.path.startsWith("/assets/");if(!G)W0.debug(`[Server] ${J.req.method} ${J.req.path}`);let z=Date.now();if(await Q(),!G){let F=Date.now()-z;W0.debug(`[Server] ${J.req.method} ${J.req.path} - ${J.res.status} (${F}ms)`)}}),O.use(P5({origin(J){if(!J)return;if(J.startsWith("http://localhost:"))return J;if(J.startsWith("http://127.0.0.1:"))return J;if(J==="tauri://localhost"||J==="http://tauri.localhost")return J;if(I$.includes(J))return J;return}})),O.use(async(J,Q)=>{let G=J.req.query("directory")||J.req.header("x-blade-directory")||c();try{G=decodeURIComponent(G)}catch{}return J.set("directory",G),Q()});let $=p1();PO=$,sO=$.recoverQueuedTasks,KO=new J$({dispatch:(J)=>$.dispatchTask(J),store:q$}),O.route("/global",t$()),O.route("/events",o$()),O.route("/sessions",$.app),O.route("/tasks",E4($)),O.route("/schedules",_4(q$,KO)),O.route("/configs",p$()),O.route("/permissions",l1()),O.route("/plugins",Q4()),O.route("/hooks",x1()),O.route("/workspace-trust",h4()),O.route("/providers",K4()),O.route("/models",N1()),O.route("/projects",z4()),O.route("/suggestions",j4()),O.route("/terminal",f4()),O.route("/mcp",Z1()),O.route("/skills",w4()),O.get("/health",(J)=>{return J.json({healthy:!0,version:$O()})});let x=l5();if(x)W0.info(`[Server] Serving static files from ${x}`),O.get("/favicon.svg",()=>{let J=u0(x,"favicon.svg");if(!k$(J))return new Response(null,{status:404});return new Response(fO(J),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(J)=>{let Q=u0(x,J.req.path);if(!k$(Q))return J.json({error:{code:"NOT_FOUND",message:`File not found: ${J.req.path}`}},404);let G=p5(Q),z=R5(Q).toLowerCase(),T={".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"}[z]||"application/octet-stream",B=y5.has(z)&&G.byteLength>=m5?u5(J.req.header("Accept-Encoding")):void 0,C=B?d5(Q,G,B):G;return new Response(new Uint8Array(C),{headers:{"Content-Type":T,"Content-Length":String(C.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...B?{"Content-Encoding":B}:{}}})}),O.get("/",(J)=>{let Q=u0(x,"index.html"),G=fO(Q,"utf-8");return J.html(G,200,{"Cache-Control":"no-cache"})}),O.get("*",(J)=>{let Q=J.req.path;if(Q.includes("."))return J.json({error:{code:"NOT_FOUND",message:`File not found: ${Q}`}},404);let G=u0(x,"index.html"),z=fO(G,"utf-8");return J.html(z,200,{"Cache-Control":"no-cache"})});else W0.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(J)=>{return J.json({message:"Blade API Server",version:$O(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),O.all("*",(J)=>{return J.json({error:{code:"NOT_FOUND",message:`Route not found: ${J.req.path}`}},404)});return O}function i5(){let O=C5(),$=[];for(let x of Object.keys(O)){let J=O[x];if(!J)continue;for(let Q of J){if(Q.internal||Q.family!=="IPv4")continue;if(Q.address.startsWith("172."))continue;$.push(Q.address)}}return $}function p4(){return typeof globalThis.Bun<"u"}function d4(O,$){let x=globalThis.Bun,J=(G)=>{try{return x.serve({hostname:$.hostname,port:G,fetch:O.fetch,idleTimeout:0,websocket:R$})}catch(z){W0.error("Failed to start Bun server:",z);return}},Q=$.port===0?J(4096)??J(0):J($.port);if(!Q)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{Q.stop(!0)}}}function a5(O,$){return new Promise((x,J)=>{let Q=T5(async(B,C)=>{let w=new URL(B.url||"/",`http://${B.headers.host}`),W=new Headers;for(let[p,b]of Object.entries(B.headers))if(b)if(Array.isArray(b))for(let e of b)W.append(p,e);else W.set(p,b);let I;if(B.method!=="GET"&&B.method!=="HEAD")I=(await new Promise((b)=>{let e=[];B.on("data",(h)=>e.push(h)),B.on("end",()=>b(Buffer.concat(e)))})).toString();let J0=new Request(w.toString(),{method:B.method,headers:W,body:I});try{let p=await O.fetch(J0);if(C.statusCode=p.status,p.headers.forEach((b,e)=>{C.setHeader(e,b)}),p.body){let b=p.body.getReader(),e=async()=>{let{done:h,value:Z0}=await b.read();if(h){C.end();return}return C.write(Z0),e()};await e()}else{let b=await p.text();C.end(b)}}catch(p){W0.error("[Server] Node request error:",p),C.statusCode=500,C.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),G=new f5({noServer:!0}),z=c();P4(G,()=>z),Q.on("upgrade",(B,C,w)=>{if(new URL(B.url||"/",`http://${B.headers.host}`).pathname==="/terminal/ws")G.handleUpgrade(B,C,w,(I)=>{G.emit("connection",I,B)});else C.destroy()});let F=(B)=>{return new Promise((C,w)=>{Q.once("error",(W)=>{if(W.code==="EADDRINUSE")w(W);else w(W)}),Q.listen(B,$.hostname,()=>{let W=Q.address();if(W&&typeof W==="object")C(W.port);else C(B)})})};(async()=>{let B;if($.port===0)try{B=await F(4096)}catch{B=await F(0)}else B=await F($.port);let C=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${B}`);x({url:C,port:B,hostname:$.hostname,stop:async()=>{return new Promise((w)=>{G.close(()=>{Q.close(()=>w())})})}})})().catch(J)})}var i4;((N6)=>{let O,$,x,J=(B,C)=>{if(O!==B)return Promise.resolve();if(x)return x;let w=C?.shutdown("server-shutdown");return KO?.stop(),v5(),x=(async()=>{let W,I=async(J0)=>{if(!J0)return;try{await J0()}catch(p){W??=p}};if(await I(()=>B.stop()),await I(w?()=>w:void 0),c4(),O===B)O=void 0,$=void 0,PO=void 0,sO=void 0,KO=void 0;if(W0.info("[Server] Blade server stopped"),W!==void 0)throw W})(),x};function Q(){if(!$)$=c5();return $}N6.getApp=Q;function G(B){I$=B.cors??[];let C=Q();if(p4())O=d4(C,B),x=void 0,W0.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let w=O,W=PO;return sO?.().catch((I)=>{W0.warn("[Server] Failed to recover queued tasks:",I)}),KO?.start(),u4(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>J(w,W)}}N6.listen=G;async function z(B){I$=B.cors??[];let C=Q();if(p4())O=d4(C,B),W0.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await a5(C,B),W0.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);x=void 0;let w=O,W=PO;try{await sO?.()}catch(I){W0.warn("[Server] Failed to recover queued tasks:",I)}return KO?.start(),u4(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>J(w,W)}}N6.listenAsync=z;function F(){return O!==void 0}N6.isRunning=F;function T(){return PO?.getCoordinationStats()}N6.getSessionCoordinationStatsForTests=T})(i4||={});export{o5 as f,n5 as g,i5 as h,i4 as i};