blade-code 0.10.162 → 0.10.164

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 (42) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-6c5z2b5s.js → chunk-09gn2ah5.js} +1 -1
  3. package/dist/{chunk-sspk1ah8.js → chunk-12b8berg.js} +1 -1
  4. package/dist/{chunk-56ma2n3p.js → chunk-1x1j96rx.js} +1 -1
  5. package/dist/{chunk-9f6nyfcs.js → chunk-20aw21g5.js} +1 -1
  6. package/dist/{chunk-mg03ydep.js → chunk-3b0z6rt5.js} +1 -1
  7. package/dist/{chunk-wbr9fc4k.js → chunk-3b38pf4n.js} +1 -1
  8. package/dist/{chunk-4k7gvnth.js → chunk-3yb1qns4.js} +1 -1
  9. package/dist/{chunk-rjbneaq0.js → chunk-4f6qkmst.js} +1 -1
  10. package/dist/{chunk-cvwcrr4h.js → chunk-550ht3zq.js} +3 -3
  11. package/dist/{chunk-sz1jw89z.js → chunk-5t26nec1.js} +1 -1
  12. package/dist/{chunk-3xffezpc.js → chunk-61m3bxvx.js} +1 -1
  13. package/dist/{chunk-9cb1hv2z.js → chunk-6hgshp48.js} +1 -1
  14. package/dist/{chunk-0aya8d61.js → chunk-89316rjt.js} +2 -2
  15. package/dist/{chunk-syq7j5b0.js → chunk-9fvptk89.js} +1 -1
  16. package/dist/{chunk-za0frk62.js → chunk-at33x380.js} +1 -1
  17. package/dist/chunk-azgqxeg1.js +1 -0
  18. package/dist/{chunk-zb6mn0dz.js → chunk-b6b8dt4v.js} +1 -1
  19. package/dist/{chunk-y54mge74.js → chunk-cawqz33k.js} +1 -1
  20. package/dist/{chunk-msx7ecb2.js → chunk-ctfanxj1.js} +2 -2
  21. package/dist/{chunk-46t79ek8.js → chunk-d4d8k3fs.js} +1 -1
  22. package/dist/chunk-g8ppb5hy.js +1 -0
  23. package/dist/{chunk-t89f4way.js → chunk-gbssjm9p.js} +1 -1
  24. package/dist/{chunk-hs0fatm3.js → chunk-gjw6emhv.js} +1 -1
  25. package/dist/{chunk-j9fdpvq0.js → chunk-jn1c83cw.js} +1 -1
  26. package/dist/{chunk-6sedqj8r.js → chunk-k89nms05.js} +1 -1
  27. package/dist/{chunk-psm2d7pr.js → chunk-kmm2jddj.js} +1 -1
  28. package/dist/{chunk-abc5bzqn.js → chunk-m25gsyt7.js} +1 -1
  29. package/dist/{chunk-hjrc4jdm.js → chunk-mag420dh.js} +1 -1
  30. package/dist/{chunk-f194ct93.js → chunk-qrs39qym.js} +1 -1
  31. package/dist/{chunk-qjbn97e2.js → chunk-r3wf3h15.js} +1 -1
  32. package/dist/{chunk-qq8h5eag.js → chunk-sb4z34ky.js} +1 -1
  33. package/dist/{chunk-ajtwwg2b.js → chunk-tn0x2xrg.js} +1 -1
  34. package/dist/{chunk-yk62xvqm.js → chunk-tt5x15k4.js} +1 -1
  35. package/dist/{chunk-vh5hxd2w.js → chunk-tyz7g60b.js} +1 -1
  36. package/dist/{chunk-nj2bggcj.js → chunk-w4b72q18.js} +1 -1
  37. package/dist/{chunk-3aavhxe8.js → chunk-wvx38688.js} +1 -1
  38. package/dist/{chunk-n7kwrvvw.js → chunk-xbzya00g.js} +1 -1
  39. package/dist/{chunk-92ck72sg.js → chunk-y5ezcp90.js} +1 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-azn3qphf.js +0 -1
  42. package/dist/chunk-e6tz8qrg.js +0 -1
@@ -1,10 +1,10 @@
1
- import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-wbr9fc4k.js";import{j as o1}from"./chunk-zj1g4nbq.js";import{v as a0,w as y2}from"./chunk-hjrc4jdm.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-9cb1hv2z.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-ajtwwg2b.js";import{$ as I2,Ea as u3,J as B2,K as u1,L as v3,O as D2,P as e0,Q as d4,R as i1,S as g$,T as A4,U as j4,V as K0,W as L2,X as M2,Y as D$,Z as w1,aa as R2,ba as b4,ca as j0,da as H0,ga as q1,ha as E1,ia as O5,ja as q2,ka as E2,la as r2,ma as e2,na as O3,oa as $3,pa as Q3,qa as Z3,ra as J3,sa as Y3,ta as X3,wa as w3,za as W5}from"./chunk-cvwcrr4h.js";import{La as q$,Ra as uO}from"./chunk-nj2bggcj.js";import{Ua as A2,Wa as j2,Xa as b2,Ya as T2,cb as V4,fb as c3,gb as c4,hb as S2,ib as f2,jb as i3,kb as l3,lb as i4,mb as a3,nb as g0,ob as N3,pb as B3,qb as D3,rb as P2,sb as k2,tb as m2,ub as h2,vb as W$,wb as r4}from"./chunk-30x3mcsb.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,hc as y0}from"./chunk-y54mge74.js";import{sc as T4}from"./chunk-zzvs471p.js";import{$c as W2,$d as D4,Cd as w2,Ic as V2,Md as A1,Nd as h0,Sc as z2,Ud as I1,Vd as I4,Wd as R1,Yd as o0,Zc as G2,_c as B4,ad as D1,bd as K2,ed as U4,ee as N2,fe as x4,ge as L4,he as g,rd as _2}from"./chunk-za0frk62.js";import{Fe as U2,Me as H2,Ne as F2}from"./chunk-y5wngtz0.js";import{gf as L3,kf as M3,lf as A3,mf as j3,nf as b3,of as y4,pf as T3,qf as I3}from"./chunk-w33zjw8m.js";import{Pf as r3,Tf as MO,Xf as f$,cg as nO}from"./chunk-syq7j5b0.js";import{dg as c1}from"./chunk-t0gm0pn1.js";import{wg as J2}from"./chunk-50vwafn5.js";import{yg as B1}from"./chunk-t89f4way.js";import{Hg as e3,Lg as s2,Pg as H1,Qg as F1,Ug as B5,Xg as eO,Yg as N1,_g as X2,ah as s4}from"./chunk-mg03ydep.js";import{th as P$,uh as Y2}from"./chunk-vbjgcn49.js";import{yh as b$,zh as l0}from"./chunk-sspk1ah8.js";import{Mi as T$,Rh as R$,Ri as U1,fi as s$,ii as r$,ki as e$,li as O2,mi as h$,ni as y$,oi as K$,ui as $2,xi as Q2,zi as Z2}from"./chunk-f194ct93.js";import{Ui as F4}from"./chunk-kv458q06.js";import{Wi as a1,Zi as N4}from"./chunk-5v0jcyea.js";import{bj as GO}from"./chunk-2f8d0km4.js";import{Dj as ZO,Fj as y,Hj as G,Ij as oO,Kj as zO}from"./chunk-2mk914vk.js";import{Pj as f0}from"./chunk-j8hbddjp.js";import{Rj as C$,Sj as o$,Uj as S$,Vj as t$}from"./chunk-4cdk4mds.js";import{Xj as i0}from"./chunk-rjbneaq0.js";import{ck as t4}from"./chunk-rvs364rz.js";import{Bk as g1,Jk as L$,fk as l1,zk as wO}from"./chunk-4wx5sya5.js";import{Mk as a4}from"./chunk-eg3ms291.js";var H8={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 F8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as e4,readFileSync as f1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as i6}from"node:os";import{dirname as l6,extname as a6,join as E0}from"node:path";import{fileURLToPath as n6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var c0=ZO("Service"),f5=30000,P5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??W$.getInstance(),this.tickMs=O.tickMs??f5}start(){if(this.timer)return;c0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!P5.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,c0.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 Q of $)await this.evaluate(Q,O)}catch($){c0.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}),c0.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,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??k5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),c0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);c0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:V?V.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function k5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class _O extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class i extends _O{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends _O{constructor(O){super("BAD_REQUEST",O,400)}}class v extends _O{constructor(O){super("CONFLICT",O,409)}}class rO extends _O{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends _O{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class A0 extends _O{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class vO extends _O{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class VO extends _O{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as m5}from"hono";var G4=ZO("Service"),h5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(zO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function y5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var _$=()=>{let O=new m5;return O.get("/",async($)=>{try{let Q=MO();return $.json(Q?y5(Q):{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(h5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await nO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof K$)throw new F(Q.message);throw G4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=MO();return $.json(Q?.permissions||{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as g5}from"hono";import{streamSSE as p5}from"hono/streaming";function w$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
1
+ import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-3b38pf4n.js";import{j as o1}from"./chunk-zj1g4nbq.js";import{v as a0,w as y2}from"./chunk-mag420dh.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-6hgshp48.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-tn0x2xrg.js";import{$ as I2,Ea as u3,J as B2,K as u1,L as v3,O as D2,P as e0,Q as d4,R as i1,S as g$,T as A4,U as j4,V as K0,W as L2,X as M2,Y as D$,Z as w1,aa as R2,ba as b4,ca as j0,da as H0,ga as q1,ha as E1,ia as O5,ja as q2,ka as E2,la as r2,ma as e2,na as O3,oa as $3,pa as Q3,qa as Z3,ra as J3,sa as Y3,ta as X3,wa as w3,za as W5}from"./chunk-550ht3zq.js";import{La as q$,Ra as uO}from"./chunk-w4b72q18.js";import{Ua as A2,Wa as j2,Xa as b2,Ya as T2,cb as V4,fb as c3,gb as c4,hb as S2,ib as f2,jb as i3,kb as l3,lb as i4,mb as a3,nb as g0,ob as N3,pb as B3,qb as D3,rb as P2,sb as k2,tb as m2,ub as h2,vb as W$,wb as r4}from"./chunk-30x3mcsb.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,hc as y0}from"./chunk-cawqz33k.js";import{sc as T4}from"./chunk-zzvs471p.js";import{$c as W2,$d as D4,Cd as w2,Ic as V2,Md as A1,Nd as h0,Sc as z2,Ud as I1,Vd as I4,Wd as R1,Yd as o0,Zc as G2,_c as B4,ad as D1,bd as K2,ed as U4,ee as N2,fe as x4,ge as L4,he as g,rd as _2}from"./chunk-at33x380.js";import{Fe as U2,Me as H2,Ne as F2}from"./chunk-y5wngtz0.js";import{gf as L3,kf as M3,lf as A3,mf as j3,nf as b3,of as y4,pf as T3,qf as I3}from"./chunk-w33zjw8m.js";import{Pf as r3,Tf as MO,Xf as f$,cg as nO}from"./chunk-9fvptk89.js";import{dg as c1}from"./chunk-t0gm0pn1.js";import{wg as J2}from"./chunk-50vwafn5.js";import{yg as B1}from"./chunk-gbssjm9p.js";import{Hg as e3,Lg as s2,Pg as H1,Qg as F1,Ug as B5,Xg as eO,Yg as N1,_g as X2,ah as s4}from"./chunk-3b0z6rt5.js";import{th as P$,uh as Y2}from"./chunk-vbjgcn49.js";import{yh as b$,zh as l0}from"./chunk-12b8berg.js";import{Mi as T$,Rh as R$,Ri as U1,fi as s$,ii as r$,ki as e$,li as O2,mi as h$,ni as y$,oi as K$,ui as $2,xi as Q2,zi as Z2}from"./chunk-qrs39qym.js";import{Ui as F4}from"./chunk-kv458q06.js";import{Wi as a1,Zi as N4}from"./chunk-5v0jcyea.js";import{bj as GO}from"./chunk-2f8d0km4.js";import{Dj as ZO,Fj as y,Hj as G,Ij as oO,Kj as zO}from"./chunk-2mk914vk.js";import{Pj as f0}from"./chunk-j8hbddjp.js";import{Rj as C$,Sj as o$,Uj as S$,Vj as t$}from"./chunk-4cdk4mds.js";import{Xj as i0}from"./chunk-4f6qkmst.js";import{ck as t4}from"./chunk-rvs364rz.js";import{Bk as g1,Jk as L$,fk as l1,zk as wO}from"./chunk-4wx5sya5.js";import{Mk as a4}from"./chunk-eg3ms291.js";var H8={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 F8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as e4,readFileSync as f1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as i6}from"node:os";import{dirname as l6,extname as a6,join as E0}from"node:path";import{fileURLToPath as n6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var c0=ZO("Service"),f5=30000,P5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??W$.getInstance(),this.tickMs=O.tickMs??f5}start(){if(this.timer)return;c0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!P5.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,c0.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 Q of $)await this.evaluate(Q,O)}catch($){c0.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}),c0.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,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??k5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),c0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);c0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:V?V.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function k5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class _O extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class i extends _O{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends _O{constructor(O){super("BAD_REQUEST",O,400)}}class v extends _O{constructor(O){super("CONFLICT",O,409)}}class rO extends _O{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends _O{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class A0 extends _O{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class vO extends _O{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class VO extends _O{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as m5}from"hono";var G4=ZO("Service"),h5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(zO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function y5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var _$=()=>{let O=new m5;return O.get("/",async($)=>{try{let Q=MO();return $.json(Q?y5(Q):{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(h5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await nO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof K$)throw new F(Q.message);throw G4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=MO();return $.json(Q?.permissions||{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as g5}from"hono";import{streamSSE as p5}from"hono/streaming";function w$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)$+=`event: ${O.event}
3
3
  `;for(let Q of O.data.split(/\r\n|\r|\n/))$+=`data: ${Q}
4
4
  `;if(O.retry!==void 0)$+=`retry: ${O.retry}
5
5
  `;return $+=`
6
6
  `,Buffer.byteLength($)}class K1{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??U$,this.maxPendingBytes=O.maxPendingBytes??H$,this.serial=new N$({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??F$,sizeOf:w$,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 z0("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 Q=O.replayed?$.filter((J)=>J.sequence!==void 0&&J.sequence>this.highestReplaySequence).sort((J,X)=>J.sequence-X.sequence||J.order-X.order):$.sort((J,X)=>J.order-X.order),Z;for(let J of Q){if(O.replayed&&J.sequence!==void 0&&J.sequence===Z)continue;if(this.offerLive(J.message,J.sequence),this.serial.stats().closed)return;Z=J.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 Q=w$(O),Z=this.serial.stats();if(Q>this.maxPendingBytes){this.fail(new z0("oversized",`SSE frame requires ${Q} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:Z.pendingItems+this.buffered.length,pendingBytes:Z.pendingBytes+this.bufferedBytes}));return}if(Z.pendingItems+this.buffered.length>=this.maxPendingItems||Z.pendingBytes+this.bufferedBytes+Q>this.maxPendingBytes){this.fail(new z0("overflow","SSE initialization buffer limit exceeded",{pendingItems:Z.pendingItems+this.buffered.length,pendingBytes:Z.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:Q,sequence:$,order:this.nextOrder}),this.bufferedBytes+=Q}offerLive(O,$){if($!==void 0){if($<=this.highestReplaySequence)return;if($<=this.highestDeliveredSequence){this.fail(new z0("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 z0("closed","SSE egress is closed")}}var v5=15000,u5=ZO("Service"),d5=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","session.archived","session.unarchived","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),c5=new Set(["queued","running","completed","failed","cancelled","interrupted"]),i5=new Set(["high","medium","low"]),l5=new Set(["feature","bug","maintenance","research"]);function a5(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,Q=["changedFiles","additions","deletions","commits"];if(Q.some((Z)=>typeof $[Z]!=="number"||!Number.isInteger($[Z])||$[Z]<0))return;return Object.fromEntries(Q.map((Z)=>[Z,$[Z]]))}function _1(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function n5(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}:{},..._1($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}function B$(O,$){return $&&O instanceof z0&&(O.kind==="closed"||O.kind==="aborted")}var x$=()=>{let O=new g5,$=new w1;return O.onError((Q,Z)=>{if(Q instanceof LO)return Z.json(Q.toObject(),503);throw Q}),O.get("/",async(Q)=>{let Z;try{Z=$.enter(Q.req.raw.signal)}catch(X){if(X instanceof D$)throw new LO;throw X}let J=!1;try{let X=p5(Q,async(V)=>{let w,N,H=!1,j,T,L=new Promise((D)=>{T=D}),q,b=()=>{if(N!==void 0)clearInterval(N),N=void 0;w?.(),w=void 0},E=(D)=>{if(q)return q;return H=!0,q=(async()=>{try{b(),j?.close(D),V.close()}finally{T()}})(),q},h=()=>{E(Z.signal.reason)};if(Z.signal.addEventListener("abort",h,{once:!0}),V.onAbort(()=>{E()}),Z.signal.aborted){await E(Z.signal.reason),Z.signal.removeEventListener("abort",h),Z.release();return}j=new K1({write:async(D)=>{await V.writeSSE(D)},onFailure:(D)=>{if(B$(D,H))return;u5.warn(`[EventRoutes] SSE egress closed: kind=${D.kind} pendingItems=${D.pendingItems??0} pendingBytes=${D.pendingBytes??0}`),E(D)}});let m=(D,e)=>{j?.observe({data:JSON.stringify({type:D,properties:e})})};w=P.subscribe((D)=>{if(!d5.has(D.type))return;if(D.type==="permission.asked"||D.type==="question.required"||D.type==="elicitation.required"){let n=D.properties.requestId;if(typeof n!=="string"||!n)return;m("interaction.pending",{sessionId:D.sessionId,projectPath:D.projectPath,interactionType:D.type==="question.required"?"question":D.type==="elicitation.required"?"elicitation":"permission",requestId:n});return}if(D.type==="interaction.resolved"){let n=D.properties.requestId;if(typeof n!=="string"||!n)return;m(D.type,{sessionId:D.sessionId,projectPath:D.projectPath,requestId:n});return}if(D.type==="session.created"||D.type==="session.deleted"||D.type==="session.archived"||D.type==="session.unarchived"){m(D.type,{sessionId:D.sessionId,projectPath:D.projectPath});return}if(D.type==="session.updated"){let n=D.properties.title,NO=D.properties.taskPriority,qO=D.properties.taskKind,SO=D.properties.taskDueAt,KO=typeof n==="string"&&Boolean(n.trim()),$0=i5.has(String(NO)),tO=l5.has(String(qO)),gO=SO===null||typeof SO==="string"&&Number.isFinite(Date.parse(SO));if(!KO&&!$0&&!tO&&!gO)return;m(D.type,{sessionId:D.sessionId,projectPath:D.projectPath,...KO?{title:n}:{},...$0?{taskPriority:NO}:{},...tO?{taskKind:qO}:{},...gO?{taskDueAt:SO}:{}});return}if(D.type==="task.delivery"){let n=n5(D.properties.taskDelivery);if(!n)return;m(D.type,{sessionId:D.sessionId,projectPath:D.projectPath,taskDelivery:n,...D.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof D.properties.updatedAt==="string"?{updatedAt:D.properties.updatedAt}:{}});return}if(D.type==="schedule.fired"){let n=D.properties.scheduleId,NO=D.properties.firedAt;if(typeof n!=="string"||typeof NO!=="string")return;m(D.type,{scheduleId:n,firedAt:NO,sessionId:D.sessionId,projectPath:D.projectPath,...typeof D.properties.runId==="string"?{runId:D.properties.runId}:{},...typeof D.properties.status==="string"?{status:D.properties.status}:{}});return}let e=D.properties.taskStatus;if(typeof e!=="string"||!c5.has(e))return;let u=a5(D.properties.taskDiffStat),FO=_1(D.properties.taskQueuePosition,1),fO=_1(D.properties.taskQueueDepth,0),S=_1(D.properties.taskConcurrencyLimit,1),YO=_1(D.properties.taskInFlight,0),d=typeof D.properties.taskAdmissionPaused==="boolean"?D.properties.taskAdmissionPaused:void 0;m(D.type,{sessionId:D.sessionId,projectPath:D.projectPath,taskStatus:e,...typeof D.properties.taskStatusReason==="string"?{taskStatusReason:D.properties.taskStatusReason}:{},...D.properties.taskFailure&&typeof D.properties.taskFailure==="object"?{taskFailure:D.properties.taskFailure}:{},...typeof D.properties.taskStartedAt==="string"?{taskStartedAt:D.properties.taskStartedAt}:{},...typeof D.properties.taskCompletedAt==="string"?{taskCompletedAt:D.properties.taskCompletedAt}:{},...typeof D.properties.updatedAt==="string"?{updatedAt:D.properties.updatedAt}:{},...u?{taskDiffStat:u}:{},...FO!==void 0?{taskQueuePosition:FO}:{},...fO!==void 0?{taskQueueDepth:fO}:{},...S!==void 0?{taskConcurrencyLimit:S}:{},...YO!==void 0?{taskInFlight:YO}:{},...d!==void 0?{taskAdmissionPaused:d}:{}})});try{if(V.aborted||H)return;if(await j.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),V.aborted||H)return;if(j.finishInitialization({replayed:!1}),V.aborted||H)return;N=setInterval(()=>{if(V.aborted||H)return;j?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},v5),await L}catch(D){if(B$(D,H))return;throw D}finally{await E(),Z.signal.removeEventListener("abort",h),Z.release()}});return J=!0,X}catch(X){if(!J)Z.release();throw X}}),{app:O,shutdown:(Q)=>$.shutdown(Q),getSseConnectionStats:()=>$.stats()}};import{Hono as o5}from"hono";var t5=G.Object({paused:G.Boolean()}),M$=()=>{let O=new o5;return O.get("/health",($)=>{return $.json({healthy:!0,version:i0()})}),O.get("/info",($)=>{let Q=GO(),Z=MO();if(Z)j0.configure(Z.maxConcurrentTasks,Z.maxQueuedTasks,Z.maxQueuedTaskBytes);let J=j0.getStats();return $.json({version:i0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:Q,gitBranch:L$(Q),taskAdmission:{inFlight:J.inFlight,queued:J.queued,maxConcurrent:J.maxConcurrent,maxQueued:J.maxQueued,paused:J.paused}})}),O.put("/task-admission",async($)=>{let Q;try{Q=await $.req.json()}catch{throw new F("Invalid request body")}let Z=y(t5,Q);if(!Z.success)throw new F("Invalid task admission control request");j0.setPaused(Z.data.paused);let J=j0.getStats();return $.json({inFlight:J.inFlight,queued:J.queued,maxConcurrent:J.maxConcurrent,maxQueued:J.maxQueued,paused:J.paused})}),O};import{Hono as s5}from"hono";var r5=G.Object({projectPath:G.String({minLength:1}),action:zO(["trust","revoke"]),expectedDigest:G.Optional(G.String())}),e5=G.Object({projectPath:G.String({minLength:1}),sessionId:G.String({minLength:1}),enabled:G.Boolean()});function W4(O){if(!O)throw new F("projectPath must be absolute");try{return wO(O)}catch{throw new F("projectPath must reference a local workspace")}}function A$(O){if(!O)throw new F("sessionId is required");try{g1(O)}catch($){throw new F($ instanceof Error?$.message:"sessionId is invalid")}return O}async function y1(O){let $=W4(O),Q=MO()?.hooks??T$.hooks,Z=await U1.getInstance().loadWorkspaceHooks($,Q,{includeBaseForCurrentWorkspace:!1});return N1($,async()=>{F1($);let J=l0.getInstance();return J.loadConfig(Z,$),await H1($),J.getConfig($)})}function j$(O,$){let Q=l0.getInstance(),Z=Q.getConfig($).enabled,J=Q.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:Q.isSessionEnabled(O,$),paused:J,configEnabled:Z}}var I$=()=>{let O=new s5;return O.get("/trust",async($)=>{let Q=$.req.query("projectPath");if(!Q)throw new F("projectPath query parameter is required");return await y1(Q),$.json(await l0.getInstance().getTrustStatus(Q))}),O.post("/trust",async($)=>{let Q=y(r5,await $.req.json());if(!Q.success)throw new F("Invalid hook trust request");let{projectPath:Z,action:J,expectedDigest:X}=Q.data;await y1(Z);let V=l0.getInstance(),w;try{w=J==="trust"?await V.trustProject(Z,X):await V.revokeProjectTrust(Z)}catch(N){if(N instanceof b$)throw new v(N.message);throw N}return $.json(w)}),O.get("/session",async($)=>{let Q=W4($.req.query("projectPath")),Z=A$($.req.query("sessionId"));return await y1(Q),$.json(j$(Z,Q))}),O.post("/session",async($)=>{let Q=y(e5,await $.req.json());if(!Q.success)throw new F("Invalid hook session request");let Z=W4(Q.data.projectPath),J=A$(Q.data.sessionId);await y1(Z);let X=l0.getInstance();if(Q.data.enabled)X.enableSession(J,Z);else X.disableSession(J,Z);return $.json(j$(J,Z))}),O};import{Hono as O9}from"hono";var G0=ZO("Service");function $9(O){try{return q$(O)}catch{return[]}}function Q9(O){if(!p1(O)||!p1(O.reference)||!p1(O.argument))throw Error("Invalid MCP completion request");let $=O.reference.type,Q=$==="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(!Q||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let Z;if(O.context!==void 0){if(!p1(O.context))throw Error("Invalid MCP completion context");Z=Object.create(null);for(let[J,X]of Object.entries(O.context)){if(typeof X!=="string")throw Error("Invalid MCP completion context");Z[J]=X}}return{reference:Q,argument:{name:O.argument.name,value:O.argument.value},...Z?{context:Z}:{}}}function p1(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function b0(O,$){let Q=MO()?.mcpServers??{};for(let[Z,J]of Object.entries(Q)){if($&&Z!==$)continue;if(!O.getServerStatus(Z))await O.registerServer(Z,J,{connect:!1})}}var E$=()=>{let O=new O9;return O.get("/",async($)=>{try{let Q=uO.getInstance();await b0(Q);let Z=Q.getAllServers(),J=await Promise.all(Array.from(Z.entries()).map(async([X,V])=>({id:X,name:X,status:V.status==="connected"?"connected":V.status==="reconnecting"?"reconnecting":V.status==="connecting"?"connecting":V.lastError?"error":"offline",endpoint:V.config.command?`${V.config.command} ${(V.config.args||[]).join(" ")}`.trim():V.config.url||"Unknown",description:`MCP server: ${X}`,tools:V.tools.map((w)=>w.name),completionSupported:V.client.completionSupported,tasks:V.client.tasks,resources:V.contentCatalog.resources,resourceTemplates:V.contentCatalog.resourceTemplates.map((w)=>({...w,variables:$9(w.uriTemplate)})),prompts:V.contentCatalog.prompts,connectedAt:V.connectedAt?.toISOString(),error:V.lastError?.message,recovery:V.recovery,logging:V.logging,instructions:V.instructions,oauthEnabled:V.client.oauthEnabled,oauthStatus:await V.client.getOAuthStatus()})));return $.json(J)}catch(Q){return G0.error("[McpRoutes] Failed to get MCP servers:",Q),$.json({error:Q instanceof Error?Q.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async($)=>{try{let Q=$.req.param("name"),Z=uO.getInstance();return await b0(Z,Q),await Z.connectServer(Q),$.json({success:!0})}catch(Q){return G0.error("[McpRoutes] Failed to connect MCP server:",Q),$.json({success:!1,error:Q.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let Q=$.req.param("name"),Z=uO.getInstance();return await b0(Z,Q),await Z.disconnectServer(Q),$.json({success:!0})}catch(Q){return G0.error("[McpRoutes] Failed to disconnect MCP server:",Q),$.json({success:!1,error:Q.message},500)}}),O.get("/:name/logs",async($)=>{try{let Q=$.req.param("name"),Z=Number($.req.query("limit")??20),J=Number($.req.query("afterRevision")??0);if(!Number.isSafeInteger(Z)||Z<1||Z>100||!Number.isSafeInteger(J)||J<0)return $.json({error:"Invalid MCP log pagination"},400);let X=uO.getInstance();return await b0(X,Q),$.json(X.getLogSnapshot(Q,{limit:Z,afterRevision:J}))}catch(Q){return G0.error("[McpRoutes] Failed to get MCP logs:",Q),$.json({error:Q.message},500)}}),O.post("/:name/logging-level",async($)=>{try{let Q=$.req.param("name"),Z=await $.req.json();if(!R$(Z.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let J=uO.getInstance();return await b0(J,Q),await J.setServerLoggingLevel(Q,Z.level),$.json({success:!0,level:Z.level})}catch(Q){return G0.error("[McpRoutes] Failed to set MCP logging level:",Q),$.json({success:!1,error:Q.message},400)}}),O.post("/:name/complete",async($)=>{try{let Q=$.req.param("name"),Z=Q9(await $.req.json()),J=uO.getInstance();await b0(J,Q);let X=await J.complete(Q,Z);return $.json(X)}catch(Q){return G0.error("[McpRoutes] Failed to complete MCP argument:",Q),$.json({error:Q.message},400)}}),O.post("/:name/oauth/login",async($)=>{try{let Q=$.req.param("name"),Z=uO.getInstance();await b0(Z,Q);let J=await Z.beginOAuthLogin(Q);return $.json({success:!0,flowId:J.flowId,authorizationUrl:J.authorizationUrl},202)}catch(Q){return G0.error("[McpRoutes] Failed to start MCP OAuth login:",Q),$.json({success:!1,error:Q.message},400)}}),O.post("/:name/oauth/logout",async($)=>{try{let Q=$.req.param("name"),Z=uO.getInstance();return await b0(Z,Q),await Z.logoutOAuth(Q),$.json({success:!0})}catch(Q){return G0.error("[McpRoutes] Failed to log out MCP OAuth:",Q),$.json({success:!1,error:Q.message},400)}}),O.delete("/:name",async($)=>{try{let Q=$.req.param("name");await uO.getInstance().unregisterServer(Q);let J=MO();if(J?.mcpServers){let{[Q]:X,...V}=J.mcpServers;await nO().updateConfig({mcpServers:V})}return $.json({success:!0})}catch(Q){return G0.error("[McpRoutes] Failed to delete MCP server:",Q),$.json({success:!1,error:Q.message},500)}}),O.post("/",async($)=>{try{let Q=await $.req.json(),{name:Z,config:J}=Q;if(!Z||!J)return $.json({success:!1,error:"Missing name or config"},400);await uO.getInstance().registerServer(Z,J);let V=MO();return await nO().updateConfig({mcpServers:{...V?.mcpServers,[Z]:J}}),$.json({success:!0})}catch(Q){return G0.error("[McpRoutes] Failed to add MCP server:",Q),$.json({success:!1,error:Q.message},500)}}),O};import{getSupportedThinkingLevels as Z9}from"@earendil-works/pi-ai";import{Hono as J9}from"hono";var v1=ZO("Service");function Y9(O){let $=O||GO();try{return wO($,O?"directory":"cwd")}catch(Q){throw new F(Q instanceof Error?Q.message:"directory is invalid")}}function X9(O,$,Q=P$.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:Z9($),supportedServiceTiers:S$($),supportedResponseVerbosities:C$($),communicationStyles:Q,input:$.input}}function V9(O){k$(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function k$(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new F("streamIdleTimeout must be at least 1000ms")}var m$=()=>{let O=new J9;return O.get("/",async($)=>{try{let Q=MO();if(!Q)throw Error("Config not initialized");let Z=Y9($.get("directory")),[J,X]=await Promise.all([B1(Z,Q),eO(Z)]),V=J.config.models,w=V.find((T)=>T.id===J.config.currentModelId)??V[0],N=J.catalog,H=X.communicationStyles.list(),j=(T)=>X9(T,N.resolveConfig(T),H);return $.json({configured:V.map(j),current:w?j(w):null})}catch(Q){if(Q instanceof F)throw Q;v1.error("[ModelsRoutes] Failed to get models:",Q);let Z=new VO("Failed to get models");return $.json(Z.toObject(),500)}}),O.post("/",async($)=>{let Q=f0(),Z,J;try{let X=await $.req.json(),{provider:V,displayName:w,model:N,overrides:H,apiKey:j,modelProvider:T}=X;if(!V||!N)throw new F("provider and model are required");k$(H);let L;if(T){if(T.id!==V)throw new F("modelProvider.id must match the model provider");if(MO()?.modelProviders[V])throw new F(`model provider already exists: ${V}`);L={name:T.name,baseUrl:T.baseUrl,wireApi:T.wireApi,...T.apiKeyEnv?{apiKeyEnv:T.apiKeyEnv}:{}};try{Q.registerModelProvider(V,L,[N]),J=V}catch(E){throw new F(E instanceof Error?E.message:"Invalid model provider")}}else Q.getModel(V,N);if(j?.trim()){if(await Q.setApiKey(V,j.trim()),L)Z=V}let q={provider:V,displayName:w||void 0,model:N,overrides:H||void 0},b=L?await nO().addModelWithProvider(q,L):await nO().addModel(q);return $.json({success:!0,model:b})}catch(X){if(Z)await Q.credentials.delete(Z);if(J){let V=MO();Q.configureModelProviders(V?.modelProviders??{},V?.models??[])}throw v1.error("[ModelsRoutes] Failed to add model:",X),X}}),O.put("/:modelId",async($)=>{try{let Q=$.req.param("modelId"),Z=await $.req.json(),{displayName:J,overrides:X,model:V}=Z,w=f$(Q);if(!w)throw new F("model config not found");if(V)f0().getModel(w.provider,V);return await nO().updateModel(Q,V9({displayName:J,overrides:X,model:V})),$.json({success:!0})}catch(Q){throw v1.error("[ModelsRoutes] Failed to update model:",Q),Q}}),O.delete("/:modelId",async($)=>{try{let Q=$.req.param("modelId");return await nO().removeModel(Q),$.json({success:!0})}catch(Q){throw v1.error("[ModelsRoutes] Failed to delete model:",Q),Q}}),O};import{Hono as P9}from"hono";import{Mutex as w9}from"async-mutex";import{Hono as U9}from"hono";import{streamSSE as H9}from"hono/streaming";import{LRUCache as F9}from"lru-cache";import{nanoid as n0}from"nanoid";class Z0 extends Error{limit;resource="resident_session_projections";retryable=!0;constructor(O){super("Session projection capacity is full");this.limit=O;this.name="SessionProjectionCapacityError"}}class P0 extends Error{reason;constructor(O="Session projection residency is closed"){super(O);this.reason=O;this.name="SessionProjectionResidencyClosedError"}}class W0 extends Error{key;constructor(O,$=`Session projection residency already owns key: ${O}`){super($);this.key=O;this.name="SessionProjectionResidencyConflictError"}}class K4 extends Error{deadlineAt;constructor(O){super(`Session projection close wait timed out at ${O}`);this.deadlineAt=O;this.name="SessionProjectionResidencyCloseTimeoutError"}}function z9(O,$){if(O.size!==$.size)return!1;for(let[Q,Z]of O)if(!$.has(Q)||$.get(Q)!==Z)return!1;return!0}class _4{maxResident;idleMs;toSnapshot;now;residents=new Map;reservations=new Map;closings=new Map;closeStates=new Set;capacityListeners=new Set;nextGeneration=1;closed=!1;closedReason="Session projection residency is closed";invalidationPromise;resolveInvalidation;constructor(O){if(!h$(O.maxResident))throw Error("Invalid max resident Session projection limit");if(!y$(O.idleMs))throw Error("Invalid Session projection idle timeout");this.maxResident=O.maxResident,this.idleMs=O.idleMs,this.toSnapshot=O.toSnapshot,this.now=O.now??Date.now}acquire(O){if(this.assertNotClosed(),this.closings.has(O))throw new W0(O);let $=this.residents.get(O);if(!$||$.value===void 0)return;return $.pins++,this.createLease($)}reserve(O){this.assertNotClosed(),this.assertKeyOpen(O),this.makeCapacityForReservation();let $={key:O,generation:this.allocateGeneration()};return this.reservations.set(O,$),this.createReservation($)}snapshot(O){let $=this.residents.get(O);if(!$||$.value===void 0)return;return this.projectSnapshot($.value)}snapshotAll(){let O=[];for(let $ of this.residents.values()){if($.value===void 0)continue;let Q=this.projectSnapshot($.value);if(Q!==void 0)O.push(Q)}return O}beginCloseMany(O,$){this.assertNotClosed();let Q=[...new Set(O)].sort((b,E)=>b.localeCompare(E));for(let b of Q)if(this.closings.has(b))throw new W0(b,`Session projection residency is already closing key: ${b}`);let Z=new Map,J=new Map,X=new Map,V=new Set;for(let b of Q){let E=this.reservations.get(b);if(E)this.reservations.delete(b);let h=this.residents.get(b);if(h){if(this.residents.delete(b),h.phase="closing",X.set(b,h),this.closings.set(b,h),Z.set(b,h.generation),V.add(b),h.value!==void 0){let D=this.projectSnapshot(h.value);if(D!==void 0)J.set(b,D)}continue}let m={key:b,generation:E?.generation??this.allocateGeneration(),value:void 0,pins:0,lastUsedAt:this.now(),phase:"closing"};X.set(b,m),this.closings.set(b,m),Z.set(b,m.generation)}let w={keys:Q,generations:Z,snapshots:J,entries:X,originalResidentKeys:V,waiters:new Set,state:"open"};this.closeStates.add(w),this.notifyCapacityAvailableIf(!0);let N=()=>{if(w.state==="committed")throw new P0("Session projection close set is already committed");if(w.state==="rolled_back")throw new P0("Session projection close set is already rolled back")},H=()=>{for(let b of w.entries.values())if(b.pins>0)return!1;return!0},j=()=>{if(!H())return;for(let b of w.waiters){if(b.timer!==void 0)clearTimeout(b.timer);b.removeAbortListener?.(),b.resolve()}w.waiters.clear()},T=({signal:b,deadlineAt:E}={})=>{if(w.state!=="open"||H())return Promise.resolve();if(E!==void 0&&E<=this.now())return Promise.reject(new K4(E));return new Promise((h,m)=>{let D={resolve:()=>h(),reject:m,timer:void 0,removeAbortListener:void 0};if(w.waiters.add(D),E!==void 0){let e=Math.max(0,E-this.now());D.timer=setTimeout(()=>{w.waiters.delete(D),D.removeAbortListener?.(),m(new K4(E))},e)}if(b){let e=()=>{if(w.waiters.delete(D),D.timer!==void 0)clearTimeout(D.timer);b.removeEventListener("abort",e),m(b.reason instanceof Error?b.reason:Error(String(b.reason??"AbortError")))};if(b.addEventListener("abort",e,{once:!0}),D.removeAbortListener=()=>{b.removeEventListener("abort",e)},b.aborted)e()}})},L=()=>{if(w.state==="committed")return;if(N(),!H())throw new W0(w.keys[0]??"","Session projection close set still has active pins");let b=!1;for(let E of w.keys){let h=w.entries.get(E);if(!h)continue;if(this.closings.get(E)===h){if(this.closings.delete(E),h.value!==void 0)b=!0}}w.state="committed",this.closeStates.delete(w),j(),this.notifyCapacityAvailableIf(b)},q=(b)=>{if(this.closed)throw new P0(this.closedReason);if(w.state==="committed")throw new P0("Session projection close set is already committed");if(w.state==="rolled_back"){if(!w.rollbackReplacements)return;if(!z9(w.rollbackReplacements,b))throw new W0(w.keys[0]??"","Session projection close set rollback replacements changed");return}if(!H())throw new W0(w.keys[0]??"","Session projection close set still has active pins");for(let D of w.originalResidentKeys)if(!b.has(D))throw new W0(D,`Session projection close rollback requires replacement for key: ${D}`);let E=!1,h=!1,m=this.now();for(let D of w.keys){let e=w.entries.get(D);if(!e)continue;if(this.closings.get(D)===e)this.closings.delete(D);if(!w.originalResidentKeys.has(D)){E||=e.value!==void 0;continue}let u=b.get(D);if(u===void 0){E||=e.value!==void 0;continue}if(e.value=u,e.phase="resident",e.lastUsedAt=m,this.residents.set(D,e),e.pins===0)h=!0}w.rollbackReplacements=new Map(b),w.state="rolled_back",this.closeStates.delete(w),j(),this.notifyCapacityAvailableIf(E||h)};return{keys:w.keys,generations:w.generations,snapshots:w.snapshots,waitForIdle:T,commit:L,rollback:q}}invalidateAll(O){if(this.closed&&this.invalidationPromise)return this.invalidationPromise;this.closed=!0,this.closedReason=O;for(let $ of[...this.reservations.keys()])this.reservations.delete($);for(let[$,Q]of[...this.residents.entries()])this.residents.delete($),Q.phase="closing",this.closings.set($,Q);return this.invalidationPromise=new Promise(($)=>{this.resolveInvalidation=$}),this.maybeFinishInvalidation(),this.invalidationPromise}sweepIdle(){if(this.closed)return 0;let O=this.now(),$=0;while(!0){let Q=[...this.residents.values()].filter((Z)=>Z.pins===0).sort((Z,J)=>Z.lastUsedAt-J.lastUsedAt||Z.generation-J.generation).find((Z)=>O-Z.lastUsedAt>=this.idleMs);if(!Q)return $;this.residents.delete(Q.key),$++,this.notifyCapacityAvailableIf(!0)}}onCapacityAvailable(O){return this.capacityListeners.add(O),()=>{this.capacityListeners.delete(O)}}getStats(){let O=0,$=0,Q=this.reservations.size,Z=0;for(let J of this.residents.values())if(O++,J.pins>0)Z++;for(let J of this.closings.values())if($++,J.pins>0)Z++;return{resident:O,closing:$,reserved:Q,pinned:Z,retained:O+Q+this.countClosingWithValue(),maxResident:this.maxResident,idleMs:this.idleMs}}getDebugStats(){let O=0,$=0;for(let Q of this.closings.values())if(Q.value===void 0)O++;for(let Q of this.closeStates)$+=Q.waiters.size;return{tombstones:O,waiters:$,listeners:this.capacityListeners.size}}assertNotClosed(){if(this.closed)throw new P0(this.closedReason)}assertKeyOpen(O){if(this.residents.has(O)||this.reservations.has(O)||this.closings.has(O))throw new W0(O)}retainedCount(){return this.residents.size+this.reservations.size+this.countClosingWithValue()}countClosingWithValue(){let O=0;for(let $ of this.closings.values())if($.value!==void 0)O++;return O}allocateGeneration(){let O=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,O}createReservation(O){let $=!1;return{key:O.key,generation:O.generation,commit:(Q)=>{if($)throw new W0(O.key);if(this.closed)throw this.reservations.delete(O.key),$=!0,new P0(this.closedReason);if(this.reservations.get(O.key)!==O)throw $=!0,new W0(O.key);this.reservations.delete(O.key);let Z={key:O.key,generation:O.generation,value:Q,pins:1,lastUsedAt:this.now(),phase:"resident"};return this.residents.set(O.key,Z),$=!0,this.createLease(Z)},cancel:()=>{if($)return;if(this.reservations.get(O.key)===O)this.reservations.delete(O.key),this.notifyCapacityAvailableIf(!0);$=!0}}}createLease(O){let $=!1;return{key:O.key,generation:O.generation,get value(){return O.value},isCurrent:()=>{let Q=this.residents.get(O.key);if(Q===O&&Q.generation===O.generation)return!0;let Z=this.closings.get(O.key);return Z===O&&Z.generation===O.generation},release:()=>{if($)return;$=!0;let Q=this.residents.get(O.key),Z=this.closings.get(O.key),J=Q===O&&Q.generation===O.generation?Q:Z===O&&Z.generation===O.generation?Z:void 0;if(!J)return;J.pins=Math.max(0,J.pins-1),J.lastUsedAt=this.now(),this.notifyCapacityAvailableIf(!0),this.resolveIdleWaitersForEntry(J),this.maybeFinishInvalidation()}}}makeCapacityForReservation(){while(this.retainedCount()>=this.maxResident){let O=[...this.residents.values()].filter(($)=>$.pins===0).sort(($,Q)=>$.lastUsedAt-Q.lastUsedAt||$.generation-Q.generation)[0];if(!O)throw new Z0(this.maxResident);this.residents.delete(O.key)}}projectSnapshot(O){try{return this.toSnapshot(O)}catch{return}}resolveIdleWaitersForEntry(O){if(O.pins>0)return;for(let $ of this.closeStates){if(!$.entries.has(O.key))continue;let Q=!0;for(let Z of $.entries.values())if(Z.pins>0){Q=!1;break}if(!Q)continue;for(let Z of $.waiters){if(Z.timer!==void 0)clearTimeout(Z.timer);Z.removeAbortListener?.(),Z.resolve()}$.waiters.clear()}}maybeFinishInvalidation(){if(!this.closed||!this.resolveInvalidation)return;for(let $ of this.closings.values())if($.pins>0)return;this.closings.clear();let O=this.resolveInvalidation;this.resolveInvalidation=void 0,O()}notifyCapacityAvailableIf(O){if(!O)return;for(let $ of[...this.capacityListeners])try{$()}catch{}}}class w4{runtimes=new Map;createRuntime;constructor(O={}){this.createRuntime=O.createRuntime??(($)=>new g$($.projectPath,`web-browser:${$.sessionId}`,{exposeArtifactPaths:!1}))}get(O){let $=a(O),Q=this.runtimes.get($);if(Q?.state==="live")return Q.runtime;if(Q)throw new u1("browser_disposed","Browser Session Runtime is closed",{retryable:!0});let Z=this.createRuntime(O);return this.runtimes.set($,{state:"live",runtime:Z}),Z}async reset(O){let $=this.runtimes.get(a(O));if($?.state==="live")await $.runtime.page({action:{kind:"reset"}})}dispose(O){let $=a(O),Q=this.runtimes.get($);if(!Q)return Promise.resolve();if(Q.state==="disposing")return Q.disposePromise;return this.disposeKey($,Q.runtime)}async disposeAll(){let $=(await Promise.allSettled([...this.runtimes.keys()].map((Q)=>{let Z=this.runtimes.get(Q);if(!Z)return Promise.resolve();if(Z.state==="disposing")return Z.disposePromise;return this.disposeKey(Q,Z.runtime)}))).find((Q)=>Q.status==="rejected");if($)throw $.reason}stats(){let O=0,$=0,Q=0;for(let Z of this.runtimes.values()){if(Z.state==="live")O++;if(Z.state==="disposing")$++;if(Z.state==="failed")Q++}return{sessions:this.runtimes.size,live:O,disposing:$,failed:Q}}disposeKey(O,$){let Q=$.dispose().then(()=>{if(this.runtimes.get(O)?.runtime===$)this.runtimes.delete(O)},(Z)=>{if(this.runtimes.get(O)?.runtime===$)this.runtimes.set(O,{state:"failed",runtime:$,error:Z});throw Z});return this.runtimes.set(O,{state:"disposing",runtime:$,disposePromise:Q}),Q}}import{Hono as W9}from"hono";var p$=G.Object({action:zO(["accept","dismiss"])},{additionalProperties:!1}),G9=oO(G.Union([G.Object({kind:G.Literal("click"),dialog:G.Optional(p$)},{additionalProperties:!1}),G.Object({kind:G.Literal("click_at"),screenshotId:G.String({minLength:1,maxLength:D1}),x:G.Integer({minimum:0,maximum:U4}),y:G.Integer({minimum:0,maximum:U4}),dialog:G.Optional(p$)},{additionalProperties:!1}),G.Object({kind:G.Literal("hover")},{additionalProperties:!1}),G.Object({kind:G.Literal("fill"),value:G.String()},{additionalProperties:!1}),G.Object({kind:G.Literal("type"),value:G.String()},{additionalProperties:!1}),G.Object({kind:G.Literal("press"),key:zO(["Enter","Tab","Escape","Backspace","Delete","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown","Space"])},{additionalProperties:!1}),G.Object({kind:G.Literal("select"),values:G.Array(G.String())},{additionalProperties:!1}),G.Object({kind:G.Literal("check")},{additionalProperties:!1}),G.Object({kind:G.Literal("uncheck")},{additionalProperties:!1}),G.Object({kind:G.Literal("scroll"),direction:zO(["up","down","left","right"]),amount:G.Integer()},{additionalProperties:!1})])),v$=oO(G.Object({action:G.Optional(zO(["goto","back","forward","reload"])),url:G.Optional(G.String()),pageId:G.Optional(G.String()),expectedOrigin:G.Optional(G.String()),waitUntil:G.Optional(zO(["commit","domcontentloaded","load"])),timeoutMs:G.Optional(G.Integer())},{additionalProperties:!1})),u$=oO(G.Object({pageId:G.String(),snapshotId:G.String(),ref:G.Optional(G.String()),expectedOrigin:G.String(),action:G9,timeoutMs:G.Optional(G.Integer())},{additionalProperties:!1}));function d$(O,$){if(O===void 0)return;let Q=Number(O);if(!Number.isSafeInteger(Q))throw new F(`${$} must be an integer`);return Q}function K9(O,$){if(O===void 0)return;if(O==="true")return!0;if(O==="false")return!1;throw new F(`${$} must be true or false`)}function _9(O){let $=O.code==="browser_not_installed"||O.code==="browser_disconnected"||O.code==="browser_disposed"?503:O.code==="browser_capacity"?429:O.code==="browser_unsupported"?400:409;return new _O(O.code.toUpperCase(),O.message,$,O.details)}function c$(O){let $=new W9;$.use("*",(Z,J)=>O.withAdmission(J)),$.onError((Z,J)=>{let X=Z instanceof u1?_9(Z):Z instanceof _O?Z:new VO;return J.json(X.toObject(),X.statusCode)});let Q=(Z,J)=>O.resolveSessionRef(Z,J);return $.post("/:sessionId/browser/navigate",async(Z)=>{let J=await Z.req.json().catch(()=>{return}),X=y(v$,J);if(!X.success)throw new F("Invalid browser navigation request");let V=await Q(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json(await O.getRuntime(V).navigate(X.data))}),$.post("/:sessionId/browser/interact",async(Z)=>{let J=await Z.req.json().catch(()=>{return}),X=y(u$,J);if(!X.success)throw new F("Invalid browser interaction request");let V=await Q(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json(await O.getRuntime(V).interact(X.data))}),$.get("/:sessionId/browser/snapshot",async(Z)=>{let J=await Q(Z.req.param("sessionId"),Z.req.query("projectPath")),X=d$(Z.req.query("depth"),"depth"),V=K9(Z.req.query("includeBoxes"),"includeBoxes");return Z.json(await O.getRuntime(J).snapshot({...Z.req.query("pageId")?{pageId:Z.req.query("pageId")}:{},...X===void 0?{}:{depth:X},...V===void 0?{}:{includeBoxes:V}}))}),$.get("/:sessionId/browser/inspect",async(Z)=>{let J=await Q(Z.req.param("sessionId"),Z.req.query("projectPath")),X=Z.req.query("target"),V=Z.req.query("pageId"),w=Z.req.query("expectedOrigin");if(X==="screenshot"){let j=Z.req.query("source")??"user";if(j!=="user"&&j!=="agent")throw new F("Unsupported browser screenshot source");if(j==="agent"&&(!V||!w))throw new F("Agent browser screenshots require pageId and expectedOrigin");let T={...V?{pageId:V}:{},...w?{expectedOrigin:w}:{}},L=j==="agent"?await O.captureAgentScreenshot(J,T):await O.getRuntime(J).screenshot(T);return new Response(new Uint8Array(L),{headers:{"Content-Type":"image/png","Content-Length":String(L.length),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}let N=d$(Z.req.query("limit"),"limit"),H={...V?{pageId:V}:{},...w?{expectedOrigin:w}:{}};if(X==="find"){let j=Z.req.query("text");if(!j)throw new F("text is required for browser find");return Z.json(await O.getRuntime(J).inspect({...H,target:{kind:"find",text:j,...N===void 0?{}:{limit:N}}}))}if(X!=="console"&&X!=="page-errors"&&X!=="network")throw new F("Unsupported browser inspection target");return Z.json(await O.getRuntime(J).inspect({...H,target:{kind:X,...N===void 0?{}:{limit:N}}}))}),$.post("/:sessionId/browser/reset",async(Z)=>{let J=await Q(Z.req.param("sessionId"),Z.req.query("projectPath"));return await O.resetRuntime(J),Z.json({success:!0})}),$}var l=ZO("Service"),d1="web-pending-resume-recovery-budget-exhausted";class L1 extends Error{evidence;constructor(O){super(O.taskFailure.message);this.evidence=O;this.name="WebAgentRunFailure"}}var N9=G.Object({title:G.Optional(G.String()),projectPath:G.Optional(G.String())}),B9=P2,D9=oO(G.Object({projectPath:G.Optional(G.String()),expectedVersion:j2,operation:T2},{additionalProperties:!1})),x9=new Set(["revision_conflict","already_claimed","immutable_origin","immutable_boundary","not_found","runtime_unavailable","invalid_mutation","storage_unavailable"]);function L9(O){if(!(O instanceof Error)||O.name!=="FollowUpQueueMutationError")return!1;if(!("code"in O)||!("snapshot"in O))return!1;let $=O;return typeof $.code==="string"&&x9.has($.code)&&y(b2,$.snapshot).success}var M9=G.Object({title:G.Optional(G.String()),projectPath:G.Optional(G.String())}),A9=G.Object({projectPath:G.String()}),j9=G.Object({objective:G.String({minLength:1}),tokenBudget:G.Optional(G.Integer({minimum:1})),permissionMode:G.Optional(zO(["default","autoEdit","plan","yolo"]))}),b9=G.Union([G.Object({action:G.Literal("pause")}),G.Object({action:G.Literal("resume")}),G.Object({action:G.Literal("edit"),objective:G.String({minLength:1})})]),_0,j1,Y0=new Map,F0=new Map,J0=new Map,n1=new F9({max:100,ttl:1800000});function T9(O){let $=structuredClone({...O,createdAt:O.createdAt.toISOString(),updatedAt:O.updatedAt.toISOString()});return{...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)}}function i$(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function mO(O){if(!O)return;return Y0.get(O)??n1.get(O)}function I9(O){if(Y0.get(O.id)!==O)return;Y0.delete(O.id),n1.set(O.id,O)}function R9(O){Y0.delete(O),n1.delete(O)}function kO(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function b1(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed"||O.status==="attention_required")return!1;let Q=O.pendingPermission;if(O.pendingPermission=void 0,Q?.resolve({approved:!1,reason:T4}),Q)P.publish(i$(O),"interaction.resolved",{requestId:Q.permissionId});return O.abortController.abort($),O.status="cancelled",P.publish(i$(O),"run.cancelled",{runId:O.id}),!0}function u2(O,$=!1){let{permissionId:Q,details:Z}=O;if(Z.type==="askUserQuestion"&&Z.questions)return{type:"question.required",properties:{requestId:Q,toolCallId:Z.toolCallId??Q,questions:Z.questions,details:Z,...$?{replayed:!0}:{}}};if(Z.type==="mcpElicitation"&&Z.mcpElicitation)return{type:"elicitation.required",properties:{requestId:Q,toolCallId:Z.toolCallId??Q,elicitation:Z.mcpElicitation,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:Q,toolName:Z.toolName,description:Z.message,args:Z.args,details:Z,...$?{replayed:!0}:{}}}}function q9(O){if(O.type.startsWith("committed.")){let $=O.properties.event;if(!$||typeof $!=="object"||Array.isArray($))return;let Q=d2($);if(!Q)return;return{...Q.seq!==void 0?{id:String(Q.seq)}:{},data:JSON.stringify({type:Q.type,...Q.seq!==void 0?{seq:Q.seq}:{},properties:{...Q.properties,sessionId:O.sessionId,projectPath:O.projectPath}})}}return{...typeof O.seq==="number"?{id:String(O.seq)}:{},data:JSON.stringify({type:O.type,...typeof O.seq==="number"?{seq:O.seq}:{},properties:{...O.properties,sessionId:O.sessionId,projectPath:O.projectPath}})}}function E9(){let O=_0;if(O)O.accepting=!1,O.invalidateAll("route-reset");_0=void 0;for(let $ of Y0.values())b1($,"route-reset");Y0.clear();for(let $ of F0.values())$.controller.abort("route-reset");F0.clear(),n1.clear(),j1?.(),j1=void 0}function C9(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,Q=$.code,Z=$.reason,J=$.scope,X=$.kind,V=$.limit;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||Z!=="queue_full"&&Z!=="wait_timeout"&&Z!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(V)||V<=0||X!==void 0&&X!=="readonly"&&X!=="write"&&X!=="execute")return;return{code:Q,reason:Z,scope:J,retryable:$.retryable,...X===void 0?{}:{kind:X},limit:V}}var T1=(O,$)=>{if(!$||typeof $!=="object")return $;let Q={...$},Z=C9(Q.tool_admission);if(Z)Q.tool_admission=Z;else delete Q.tool_admission;if(B2(O)){let V=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},w={},N=(H,j,T)=>{let L=V[H];if(typeof L==="string"&&Buffer.byteLength(L)<=j&&(!T||T.test(L)))w[H]=L};if(N("action",64),N("status",16,/^(?:ok|warning|error)$/),N("pageId",D1,/^browser_page_[a-f0-9-]+$/),N("snapshotId",D1,/^browser_snapshot_[a-f0-9-]+$/),N("origin",B4),N("candidateOrigin",B4),N("url",G2),N("title",W2),N("errorCode",64,/^browser_[a-z_]+$/),typeof V.truncated==="boolean")w.truncated=V.truncated;if(typeof V.actionApplied==="boolean"||V.actionApplied==="unknown")w.actionApplied=V.actionApplied;if(typeof V.sideEffectsUncertain==="boolean")w.sideEffectsUncertain=V.sideEffectsUncertain;if(typeof V.diagnosticCount==="number"&&Number.isSafeInteger(V.diagnosticCount)&&V.diagnosticCount>=0&&V.diagnosticCount<=z2)w.diagnosticCount=V.diagnosticCount;if(V.interaction&&typeof V.interaction==="object"&&!Array.isArray(V.interaction)){let H=V.interaction,j=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof H.action==="string"&&j.has(H.action)){let T={action:H.action};if(typeof H.ref==="string"&&Buffer.byteLength(H.ref)<=K2&&/^[a-z][a-z0-9]*$/.test(H.ref))T.ref=H.ref;let L=(q,b,E)=>typeof q==="number"&&Number.isFinite(q)&&q>=b&&q<=E;if(H.viewport&&typeof H.viewport==="object"&&!Array.isArray(H.viewport)){let q=H.viewport;if(L(q.width,1,16384)&&L(q.height,1,16384))T.viewport={width:q.width,height:q.height}}if(H.targetBox&&typeof H.targetBox==="object"&&!Array.isArray(H.targetBox)){let q=H.targetBox;if(L(q.x,-16384,32768)&&L(q.y,-16384,32768)&&L(q.width,0,16384)&&L(q.height,0,16384))T.targetBox={x:q.x,y:q.y,width:q.width,height:q.height}}w.interaction=T}}if(V.artifact&&typeof V.artifact==="object"&&!Array.isArray(V.artifact)){let H=V.artifact;if(typeof H.id==="string"&&/^[a-f0-9]{64}$/.test(H.id)&&H.sha256===H.id&&H.kind==="image"&&H.mimeType==="image/png"&&typeof H.size==="number"&&Number.isSafeInteger(H.size)&&H.size>=0&&H.size<=_2&&H.persisted===!0)w.artifact={id:H.id,sha256:H.sha256,kind:H.kind,mimeType:H.mimeType,size:H.size,persisted:!0,...typeof H.path==="string"&&Buffer.byteLength(H.path)<=8192?{path:H.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:w,...Z?{tool_admission:Z}:{}}}if(O==="Bash"){let V={},w=["message","signal","status","summary"],N=["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"],H=["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 T of w){let L=Q[T];if(typeof L==="string")V[T]=L.slice(0,8192)}for(let T of N){let L=Q[T];if(typeof L==="boolean")V[T]=L}for(let T of H){let L=Q[T];if(typeof L==="number"&&Number.isSafeInteger(L)&&L>=0)V[T]=L}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))V.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")V.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")V.background_reason=Q.background_reason;for(let T of["bash_id","shell_id"]){let L=Q[T];if(typeof L==="string"&&L.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(L))V[T]=L}if(Z)V.tool_admission=Z;let j=Q.background_shell_admission;if(j&&typeof j==="object"&&!Array.isArray(j)){let T=j;if(T.code==="background_shell_busy"&&(T.scope==="session"||T.scope==="global")&&T.retryable===!0&&Number.isSafeInteger(T.limit)&&T.limit>0)V.background_shell_admission={code:T.code,scope:T.scope,retryable:T.retryable,limit:T.limit}}return V}let J=200000,X=(V,w)=>typeof V==="number"&&Number.isSafeInteger(V)&&V>=0&&V<=w?V:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>J)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>J)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let V=Q.mcpResult,w=Array.isArray(V.artifacts)?V.artifacts.slice(0,64).flatMap((N)=>{if(!N||typeof N!=="object"||Array.isArray(N))return[];let H=N,j=new Set(["text","image","audio","resource"]);if(typeof H.id!=="string"||!/^[a-f0-9]{64}$/.test(H.id)||typeof H.sha256!=="string"||H.sha256!==H.id||typeof H.kind!=="string"||!j.has(H.kind)||X(H.size,67108864)!==H.size||typeof H.persisted!=="boolean")return[];return[{id:H.id.slice(0,128),sha256:H.sha256.slice(0,128),kind:H.kind,size:H.size,persisted:H.persisted,...typeof H.mimeType==="string"?{mimeType:H.mimeType.slice(0,256)}:{},...typeof H.sourceUri==="string"?{sourceUri:H.sourceUri.slice(0,8192)}:{},...typeof H.path==="string"?{path:H.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:V.isError===!0,contentCount:X(V.contentCount,64),textBytes:X(V.textBytes,4194304),structuredBytes:X(V.structuredBytes,4194304),artifactCount:X(V.artifactCount,64),truncated:V.truncated===!0,binaryOmitted:V.binaryOmitted===!0,artifacts:w}}else delete Q.mcpResult;return Q};function d2(O){let $=typeof O.seq==="number"?{seq:O.seq}:{};if(O.type==="message_created"&&O.data.metadata!==null&&typeof O.data.metadata==="object"&&!Array.isArray(O.data.metadata)&&O.data.metadata.clientVisible===!1)return;if((O.type==="part_created"||O.type==="part_updated")&&O.data.partType!=="tool_call"&&O.data.partType!=="tool_result")return;if(O.type==="part_created"&&O.data.partType==="tool_call"){let Q=O.data.payload;return{type:"tool.start",...$,properties:{messageId:O.data.messageId,toolCallId:Q.toolCallId??O.data.partId,toolName:Q.toolName??"unknown",arguments:JSON.stringify(Q.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let Q=O.data.payload,Z=Q.toolName??"unknown",J=I4(Q),X=R1(q1(Z,J),I1);return{type:"tool.result",...$,properties:{messageId:O.data.messageId,toolCallId:Q.toolCallId??O.data.partId,toolName:Z,success:J.success,status:J.success?"completed":"failed",summary:J.metadata?.summary,output:E1(X),metadata:T1(Z,J.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function S9(O,$,Q){switch(Q.kind){case"tool_start":if("function"in Q.toolCall)P.publish(O,"subagent.update",{subagentSessionId:$,toolName:Q.toolCall.function.name}),P.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:Q.toolCall.id,toolName:Q.toolCall.function.name,arguments:Q.toolCall.function.arguments,toolKind:Q.toolKind});break;case"tool_result":if("function"in Q.toolCall)P.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:Q.toolCall.id,toolName:Q.toolCall.function.name,success:Q.result.success,summary:Q.result.metadata?.summary,output:E1(R1(q1(Q.toolCall.function.name,Q.result),I1)),metadata:T1(Q.toolCall.function.name,Q.result.metadata)});break;case"tool_progress":if("function"in Q.toolCall)P.publish(O,"subagent.tool.progress",{subagentSessionId:$,toolCallId:Q.toolCall.id,toolName:Q.toolCall.function.name,...Q.update});break;case"content_delta":P.publish(O,"subagent.delta",{subagentSessionId:$,delta:Q.delta});break;case"thinking_delta":P.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:Q.delta});break;case"stream_end":P.publish(O,"subagent.stream.end",{subagentSessionId:$});break;case"provider_admission":P.publish(O,"subagent.provider.admission",{subagentSessionId:$,phase:Q.phase,requestClass:Q.requestClass,resource:Q.resource,scope:Q.scope,reason:Q.reason,queuePosition:Q.queuePosition,queueDepth:Q.queueDepth,inFlight:Q.inFlight,limit:Q.limit,waitMs:Q.waitMs,maxWaitMs:Q.maxWaitMs,recoveryRemainingMs:Q.recoveryRemainingMs});break;case"provider_circuit":P.publish(O,"subagent.provider.circuit",{subagentSessionId:$,phase:Q.phase,reason:Q.reason,statusCode:Q.statusCode,retryAfterMs:Q.retryAfterMs,nextProbeAt:Q.nextProbeAt,openDurationMs:Q.openDurationMs,sampleCount:Q.sampleCount,failureCount:Q.failureCount,recoveryRemainingMs:Q.recoveryRemainingMs});break;case"provider_retry":P.publish(O,"subagent.provider.retry",{subagentSessionId:$,phase:Q.phase,attempt:Q.attempt,maxRetries:Q.maxRetries,reason:Q.reason,statusCode:Q.statusCode,delayMs:Q.delayMs,nextRetryAt:Q.nextRetryAt,mode:Q.mode,recoveryBudgetMs:Q.recoveryBudgetMs,recoveryElapsedMs:Q.recoveryElapsedMs,recoveryRemainingMs:Q.recoveryRemainingMs,exhaustedBy:Q.exhaustedBy});break;case"provider_stall":P.publish(O,"subagent.provider.stall",{subagentSessionId:$,phase:Q.phase,stallCount:Q.stallCount,durationMs:Q.durationMs,warningAfterMs:Q.warningAfterMs,timeoutMs:Q.timeoutMs,outputStarted:Q.outputStarted});break;case"action_stationarity":P.publish(O,"subagent.action.stationarity",{subagentSessionId:$,phase:Q.phase,toolName:Q.toolName,runLength:Q.runLength,nudgeThreshold:Q.nudgeThreshold,haltThreshold:Q.haltThreshold,progressAware:Q.progressAware});break;case"mcp_catalog_changed":P.publish(O,"subagent.mcp.catalog.changed",{subagentSessionId:$,revision:Q.revision,serverName:Q.serverName,added:Q.added,removed:Q.removed,updated:Q.updated});break;case"mcp_content_changed":P.publish(O,"subagent.mcp.content.changed",{subagentSessionId:$,revision:Q.revision,serverName:Q.serverName,contentKind:Q.contentKind,added:Q.added,removed:Q.removed,updated:Q.updated});break;case"mcp_resource_updated":P.publish(O,"subagent.mcp.resource.updated",{subagentSessionId:$,revision:Q.revision,serverName:Q.serverName,uri:Q.uri});break;case"mcp_connection_changed":P.publish(O,"subagent.mcp.connection.changed",{subagentSessionId:$,revision:Q.revision,serverName:Q.serverName,phase:Q.phase,reason:Q.reason,attempt:Q.attempt,maxAttempts:Q.maxAttempts,nextRetryAt:Q.nextRetryAt,error:Q.error});break;case"mcp_log":P.publish(O,"subagent.mcp.log",{subagentSessionId:$,revision:Q.revision,serverName:Q.serverName,level:Q.level,logger:Q.logger,message:Q.message,projectedBytes:Q.projectedBytes,dataSha256:Q.dataSha256,truncated:Q.truncated,detailsOmitted:Q.detailsOmitted,timestamp:Q.timestamp,synthetic:Q.synthetic});break;case"mcp_instructions_changed":P.publish(O,"subagent.mcp.instructions.changed",{subagentSessionId:$,revision:Q.revision,serverName:Q.serverName,action:Q.action,reason:Q.reason,text:Q.text,sourceBytes:Q.sourceBytes,projectedBytes:Q.projectedBytes,sha256:Q.sha256,truncated:Q.truncated,detailsOmitted:Q.detailsOmitted});break;case"mcp_task_changed":P.publish(O,"subagent.mcp.task.changed",{subagentSessionId:$,revision:Q.revision,taskId:Q.taskId,serverName:Q.serverName,toolName:Q.toolName,status:Q.status,statusMessage:Q.statusMessage,createdAt:Q.createdAt,updatedAt:Q.updatedAt,completedAt:Q.completedAt,hasResult:Q.hasResult,error:Q.error});break;case"project_rules_loaded":P.publish(O,"subagent.project.rules.loaded",{subagentSessionId:$,files:Q.files,triggerPaths:Q.triggerPaths,blockedWrite:Q.blockedWrite});break;default:break}}function T0(O,$="projectPath"){try{return wO(O,$)}catch(Q){throw new F(Q instanceof Error?Q.message:`${$} is invalid`)}}function M1(O){try{g1(O)}catch($){throw new F($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function WO(O){return{sessionId:O.id,projectPath:O.projectPath}}function x1(O,$){return{id:O.sessionId,projectPath:O.projectPath,title:O.title??`Session ${O.sessionId.slice(0,6)}`,createdAt:new Date(O.firstMessageTime),updatedAt:new Date(O.lastMessageTime),rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,taskStatus:O.taskStatus,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,pendingInteraction:O.pendingInteraction,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:O.taskQueuePosition,taskQueueDepth:O.taskQueueDepth,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,taskWorktree:$,messageCount:O.messageCount}}function H4(O){return O.flatMap(($)=>{if(!U2($)||$.role==="system"||$.role==="tool"&&$.name===o0)return[];let Q=$.tool_calls?.filter((V)=>!("function"in V)||V.function.name!==o0),Z=typeof $.content==="string"?$.content.trim():"";if($.role==="assistant"&&$.tool_calls?.length&&!Q?.length&&!Z&&!$.reasoningContent&&!$.metadata)return[];let J={...$,...$.tool_calls?{tool_calls:Q&&Q.length>0?Q:void 0}:{}};if($.role==="tool"){let V=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0,w=$.name??(typeof V?.toolName==="string"?V.toolName:"unknown");if(V!==void 0&&(Object.hasOwn(V,"output")||Object.hasOwn(V,"error"))){let H=I4(V),j=R1(q1(w,H),I1);return[{...J,name:w,content:E1(j),metadata:T1(w,{...H.metadata,status:H.success?"completed":"failed"})}]}return[{...J,name:w,metadata:T1(w,V)}]}let X=F2($.metadata);return[X?{...J,content:H2(X)}:J]})}function w0(O,$){O.title=$.title??O.title,O.taskStatus=$.taskStatus,O.taskStatusReason=$.taskStatusReason,O.taskFailure=$.taskFailure,O.taskStartedAt=$.taskStartedAt,O.taskCompletedAt=$.taskCompletedAt,O.taskPromptSummary=$.taskPromptSummary,O.taskPriority=$.taskPriority,O.taskKind=$.taskKind,O.taskDueAt=$.taskDueAt,O.taskModelId=$.taskModelId,O.selectedModelId=$.selectedModelId,O.permissionMode=$.permissionMode,O.reasoningEffort=$.reasoningEffort,O.serviceTier=$.serviceTier,O.responseVerbosity=$.responseVerbosity,O.communicationStyle=$.communicationStyle,O.communicationStyleDigest=$.communicationStyleDigest,O.projectInstructionsDigest=$.projectInstructionsDigest,O.pendingInteraction=$.pendingInteraction,O.taskRetryAvailable=$.taskRetryAvailable,O.taskRetriedFrom=$.taskRetriedFrom,O.taskDelivery=$.taskDelivery,O.taskIsolation=$.taskIsolation,O.taskSourceProjectPath=$.taskSourceProjectPath,O.taskWorktreePath=$.taskWorktreePath,O.taskWorktreeBranch=$.taskWorktreeBranch,O.taskBaseCommit=$.taskBaseCommit,O.taskDiffStat=$.taskDiffStat,O.taskQueuePosition=$.taskQueuePosition,O.taskQueueDepth=$.taskQueueDepth,O.taskConcurrencyLimit=$.taskConcurrencyLimit,O.archivedAt=$.archivedAt,O.archivedBySessionId=$.archivedBySessionId,O.messageCount=$.messageCount,O.updatedAt=new Date($.lastMessageTime)}async function N0(O){let $=await g.findSessionMetadata(O.id,O.projectPath);if($)w0(O,$)}function k0(O){let $=mO(O.currentRunId),Q=$?.status==="waiting_permission"?"running":$?.status==="attention_required"?"interrupted":$?.status??O.taskStatus;return{sessionId:O.id,projectPath:O.projectPath,title:O.title,rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,status:void 0,taskStatus:Q,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:Q==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:Q==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:$?.pendingPermission?{type:$.pendingPermission.details.type==="askUserQuestion"?"question":$.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:$.pendingPermission.permissionId}:O.pendingInteraction,agentType:void 0,model:void 0,messageCount:O.messageCount,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function hO(O,$){let Q=_0;if(Q?.accepting)return Q.resolveSessionRef(O,$);if(M1(O),$!==void 0){let J=dO({sessionId:O,projectPath:T0($)}),X=await g.findSessionMetadata(J.sessionId,J.projectPath);if(!X)throw new i("Session",O);return dO({sessionId:X.sessionId,projectPath:X.projectPath})}let Z=new Map;for(let J of await g.listSessions()){if(J.sessionId!==O)continue;let X=dO({sessionId:J.sessionId,projectPath:J.projectPath});Z.set(a(X),X)}if(Z.size===0)try{let J=await g.findSessionMetadata(O);if(!J)throw new i("Session",O);return dO({sessionId:J.sessionId,projectPath:J.projectPath})}catch(J){if(J instanceof i)throw J;if(J instanceof Error&&J.message.startsWith("Ambiguous session ID:"))throw new vO;throw J}if(Z.size>1)throw new vO;return Z.values().next().value}function l$(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
7
- `)}function a$(O,$){let Q=($??[]).filter((J)=>J.type==="image"&&typeof J.content==="string").map((J)=>({type:"image_url",image_url:{url:J.content}}));if(Q.length===0)return O;let Z=[];if(O.trim())Z.push({type:"text",text:O});return Z.push(...Q),Z}function n$(O,$){return $&&O instanceof z0&&(O.kind==="closed"||O.kind==="aborted")}var c2=()=>{E9();let O=new U9;O.onError((Y,K)=>{if(Y instanceof a0){let z=new rO("Session runtime capacity is full",{resource:Y.resource,limit:Y.limit});return K.json(z.toObject(),429)}if(Y instanceof Z0){let z=new rO("Session projection capacity is full",{resource:Y.resource,limit:Y.limit,retryable:Y.retryable});return K.json(z.toObject(),429)}if(Y instanceof _O)return K.json(Y.toObject(),Y.statusCode);return l.error("[SessionRoutes] Unhandled route error:",Y),K.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,Q=new w4,Z=new Map,J=new Map,X=new Map,V=new Set,w=new F4,N=new F4,H=new w9,j=MO(),T=new y2({maxResident:j?.maxResidentSessionRuntimes??$2,idleMs:j?.sessionRuntimeIdleMs??Q2}),L=new _4({maxResident:j?.maxResidentSessionProjections??s$,idleMs:j?.sessionProjectionIdleMs??r$,toSnapshot:T9}),q=new w1,b=new w1,E=setInterval(()=>{T.sweepIdle().catch((Y)=>{l.warn("[SessionRoutes] Session Runtime idle sweep failed:",Y)})},Z2);E.unref?.();let h=setInterval(()=>{try{L.sweepIdle()}catch(Y){l.warn("[SessionRoutes] Session projection idle sweep failed:",Y)}},e$);h.unref?.();let m,D=new Map,e=1,u,FO=(Y)=>{let K=Y.projectionLease;Y.projectionLease=void 0,K?.release()},fO=()=>{for(let Y of D.values()){if(Y.timer)clearTimeout(Y.timer);FO(Y)}D.clear()};j1=fO;let S=async(Y)=>{let K;try{K=q.enter()}catch{throw new LO}try{return await Y()}finally{K.release()}};O.use("*",async(Y,K)=>{if(Y.req.method==="GET"||Y.req.method==="HEAD")return K();return S(K)});let YO=(Y,K)=>w.runExclusive(a(Y),K),d=(Y,K)=>{let z=a(Y),W=D.get(z);if(!W||K!==void 0&&W.generation!==K)return;if(W.timer)clearTimeout(W.timer);FO(W),D.delete(z)},n=(Y,K)=>{let z=D.get(a(WO(Y)));return z?.generation===K.generation&&z.attempt===K.attempt&&z.inFlight&&!z.terminal},NO=(Y,K)=>{let z=a(WO(Y)),W=D.get(z);if(W){if(K?.release(),W.inFlight||W.timer||W.terminal)return}else{if(!K)throw new LO;W={attempt:0,generation:e++,inFlight:!1,projectedInputIds:new Set,projectionLease:K,startedAt:Date.now(),terminal:!1,timer:void 0},D.set(z,W)}return W.inFlight=!0,W.attempt++,{attempt:W.attempt,deadlineAt:W.startedAt+p2,generation:W.generation,projectedInputIds:W.projectedInputIds}},qO=(Y,K,z,W,_)=>{P.publish(Y,"pending.resume",{phase:K,kind:"pending_input",attempt:z,maxAttempts:g2,..._===void 0?{}:{delayMs:_,nextRetryAt:Date.now()+_},...W?{failure:{code:W.code,retryable:W.retryable,...W.resource?{resource:W.resource}:{}}}:{}})},SO=(Y,K,z,W,_,x)=>{let B=WO(Y),A=a(B),I=D.get(A);if(!I||I.generation!==K.generation)return!1;if(x)return I.inFlight=!1,I.terminal=!0,FO(I),qO(B,"exhausted",K.attempt,z.taskFailure),!1;let M=v2({sessionIdentity:A,failedAttempt:K.attempt,recoveryStartedAt:I.startedAt,workStillPending:W,evidence:z});if(M.phase!=="retry_scheduled")return I.inFlight=!1,I.terminal=!0,FO(I),qO(B,M.phase,K.attempt,z.taskFailure),!1;if(!I.projectionLease)return!1;let C=setTimeout(()=>{(async()=>{if(await _.completion,D.get(A)!==I||I.timer!==C)return;await YO(B,async()=>{if(D.get(A)!==I||I.timer!==C)return;I.timer=void 0,I.inFlight=!1;let R=NO(Y);if(!R)return;try{await u(Y,R)}catch(f){if(D.get(A)!==I)return;let p=h0(f);I.inFlight=!1,I.terminal=!0;try{let BO=new Date().toISOString(),AO;try{AO=await g.updateSessionMetadata(Y.id,Y.projectPath,{taskStatus:"failed",taskStatusReason:p.message,taskFailure:p,taskCompletedAt:BO,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null})}catch{l.error(`[SessionRoutes] Failed to persist terminal pending input state for ${Y.id}`)}if(D.get(A)!==I||!I.terminal)return;if(Y.taskStatus="failed",Y.taskStatusReason=p.message,Y.taskFailure=p,Y.taskCompletedAt=BO,AO)w0(Y,AO);qO(B,"failed",R.attempt,p),P.publish(B,"session.error",{error:p.message,taskFailure:p}),P.publish(B,"session.status",{status:"error"})}finally{FO(I)}}})})().catch((R)=>{l.error(`[SessionRoutes] Failed to retry pending input for ${Y.id}:`,R)})},M.delayMs);return C.unref?.(),I.timer=C,I.inFlight=!1,qO(B,"retry_scheduled",K.attempt+1,z.taskFailure,M.delayMs),!0},KO=(Y,K)=>{let z=WO(Y),W=D.get(a(z));if(!W||W.generation!==K.generation)return!1;if(K.attempt>1)qO(z,"recovered",K.attempt);return d(z,K.generation),!0},$0=(Y,K)=>N.runExclusive(a(Y),K),tO=(Y)=>[...Y0.values()].some((K)=>K.sessionId===Y.sessionId&&K.projectPath===Y.projectPath&&kO(K)),gO=async(Y,K,z)=>{let W=J.get(K);if(!W)W=(async()=>{if($.get(K)===z)$.delete(K);for(let[x,B]of $)if(B===z)$.delete(x);let _=WO(Y);if(X0(_)?.id===Y.id&&!tO(_)&&!F0.has(K)&&!J0.has(K))await Q4(_,"route-reset").catch(()=>{return});if(await z.dispose(),$.size===0)await uO.getInstance().disconnectAll()})().finally(()=>{if(J.get(K)===W)J.delete(K)}),J.set(K,W);await W},U=(Y,K={})=>{let z=K.communicationStyle??Y.communicationStyle;return{sessionId:Y.id,workspaceRoot:Y.projectPath,permissionMode:K.permissionMode??Y.permissionMode??"default",...Y.reasoningEffort?{reasoningEffort:Y.reasoningEffort}:{},...Y.serviceTier?{serviceTier:Y.serviceTier}:{},...Y.responseVerbosity?{responseVerbosity:Y.responseVerbosity}:{},...z?{communicationStyle:z}:{},...z===Y.communicationStyle&&Y.communicationStyleDigest?{communicationStyleDigest:Y.communicationStyleDigest}:{},...Y.projectInstructionsDigest?{projectInstructionsDigest:Y.projectInstructionsDigest}:{},...Y.taskWorktree?{taskWorktree:Y.taskWorktree}:{},...Y.taskIsolation?{taskIsolation:Y.taskIsolation}:{},...Y.messageCount>0?{sessionStart:{isResume:!0,resumeSessionId:Y.id}}:{}}},OO=async(Y,K={})=>{let z=WO(Y),W=a(z);await J.get(W);let _=T.acquire(W);if(_){if($.get(W)!==_.value)throw _.release(),Error("Session Runtime residency identity is inconsistent");return _}if(T.owns(W))throw new a0(T.getStats().maxResident);let x=Z.get(W);if(!x)x=(async()=>{let B=await T.reserve(W,{surface:"web",allowEviction:!0}),A;try{A=await H0.create(U(Y,K));let I=A.getCurrentModelId();if(I&&(Y.selectedModelId||Y.taskModelId)&&I!==Y.selectedModelId){let R=await g.updateSessionMetadata(Y.id,Y.projectPath,{selectedModelId:I}).catch((f)=>{l.warn(`[SessionRoutes] Failed to migrate restored model for ${Y.id}:`,f);return});if(R)Y.selectedModelId=R.selectedModelId,Y.updatedAt=new Date(R.lastMessageTime)}let M=A,C=B.commit({key:W,surface:"web",value:M,canEvict:()=>!tO(z)&&!F0.has(W)&&!J0.has(W)&&!Z.has(W)&&!J.has(W)&&M.isIdleForResidency(),dispose:()=>gO(Y,W,M)});return A=void 0,$.set(W,M),{runtime:M,claimLease:()=>{if(C){let f=C;return C=void 0,f}let R=T.acquire(W);if(!R||R.value!==M)throw Error("Initialized Session Runtime lost residency");return R}}}catch(I){if(B.cancel(),A)await A.dispose().catch((M)=>{l.warn(`[SessionRoutes] Failed to dispose uncommitted Runtime for ${Y.id}:`,M)});if(I instanceof j4)throw new A0(I.reason);throw I}})(),Z.set(W,x);try{return(await x).claimLease()}finally{if(Z.get(W)===x)Z.delete(W)}},iO=async(Y,K,z={})=>{let W=await OO(Y,z);try{return await K(W.value)}finally{W.release()}},P1=(Y)=>{if(Y instanceof A0||Y instanceof _O)return Y;if(Y instanceof j4)return new A0(Y.reason);if(Y instanceof V2)return new v(Y.message);if(Y instanceof Error&&"code"in Y&&(Y.code==="ENOENT"||Y.code==="ENOTDIR"))return new A0("workspace_missing");return Y instanceof Error?Y:Error(String(Y))},V1=(Y)=>{if(Y.taskIsolation!=="worktree"||Y.taskWorktree)return;if(!Y.taskSourceProjectPath)throw new A0("task_source_project_missing");return T0(Y.taskSourceProjectPath)},k1=async(Y,K)=>{let z=WO(Y),W=a(z),_=V1(Y);if(!_||$.has(W)||Z.has(W))try{return await iO(Y,K)}catch(A){throw P1(A)}let x=MO();if(!x)throw new LO("Configuration is not initialized");let B;try{let[A,I]=await Promise.all([B1(_,x),eO(_)]);return B=await H0.create({...U(Y),workspace:R2(_),modelResources:A,agentResources:X2(I),lspResources:{projectRoot:_,servers:{}},auxiliaryReadOnly:!0}),await K(B)}catch(A){throw P1(A)}finally{await B?.dispose()}},z1=async(Y)=>{let K=a(WO(Y));if(!$.has(K)&&!Z.has(K)&&!await H0.hasDurableFollowUpInbox(Y.projectPath,Y.id))return I2();return iO(Y,(z)=>z.getFollowUpQueueSnapshot())},u0=async(Y,K)=>{let z=a(WO(Y)),W=Z.get(z);if(W)await W.catch(()=>{return});Z.delete(z);let _=K??$.get(z);if(!_)return;if(!await T.remove(z,_))throw Error(`Session Runtime is pinned and cannot be disposed: ${z}`)},O4=(Y,K)=>{if(K==="delete")throw new i("Session",Y.sessionId);if(K==="archive")throw new v("Session is archived");throw new LO},d0=(Y,K,z)=>{if(z.invalidatedBy)O4(Y,z.invalidatedBy);if(X.get(K)!==z)throw new LO},$4=(Y,K)=>{let z=a(Y),W=X.get(z);if(!W)return;if(W.invalidatedBy??=K,W.cancelReservation?.(),W.cancelReservation=void 0,X.get(z)===W)X.delete(z)},$$=(Y)=>{for(let K of V)K.invalidatedBy??=Y,K.cancelReservation?.(),K.cancelReservation=void 0;X.clear()},X0=(Y)=>L.snapshot(a(Y)),m1=()=>L.snapshotAll(),Q4=async(Y,K)=>{$4(Y,K);let z=a(Y);if(!X0(Y))return;let W=L.beginCloseMany([z],K);await W.waitForIdle({deadlineAt:Date.now()+O2}),W.commit()},L5=async(Y,K)=>{if(K!==void 0)return M1(Y),dO({sessionId:Y,projectPath:T0(K)});return Z4(Y,K)},Z4=async(Y,K)=>{if(M1(Y),K!==void 0){let W=dO({sessionId:Y,projectPath:T0(K)});if(X0(W))return W;let _=await g.findSessionMetadata(W.sessionId,W.projectPath);if(!_)throw new i("Session",Y);return dO({sessionId:_.sessionId,projectPath:_.projectPath})}let z=new Map;for(let W of m1()){if(W.id!==Y)continue;let _=WO(W);z.set(a(_),_)}for(let W of await g.listSessions()){if(W.sessionId!==Y)continue;let _=dO({sessionId:W.sessionId,projectPath:W.projectPath});z.set(a(_),_)}if(z.size===0)try{let W=await g.findSessionMetadata(Y);if(!W)throw new i("Session",Y);return dO({sessionId:W.sessionId,projectPath:W.projectPath})}catch(W){if(W instanceof i)throw W;if(W instanceof Error&&W.message.startsWith("Ambiguous session ID:"))throw new vO;throw W}if(z.size>1)throw new vO;return z.values().next().value},M0=async(Y)=>{let K=_0;if(!K?.accepting||K.acquireOrHydrateSession!==M0)throw new LO;let z=a(Y),W=L.acquire(z);if(W)return W;let _=X.get(z);if(!_){let B;B={promise:Promise.resolve().then(async()=>{let I=L.acquire(z);if(I){I.release();return}d0(Y,z,B);let M=L.reserve(z);B.cancelReservation=()=>M.cancel();try{let C=await g.findSessionMetadata(Y.sessionId,Y.projectPath);if(d0(Y,z,B),!C)throw new i("Session",Y.sessionId);let R=await g.findSessionTaskWorktree(Y.sessionId,Y.projectPath);d0(Y,z,B);let f=x1(C,R);d0(Y,z,B);let p=M.commit(f);B.cancelReservation=void 0,p.release()}catch(C){throw B.cancelReservation?.(),B.cancelReservation=void 0,C}})},_=B,X.set(z,_),V.add(_)}try{await _.promise}finally{if(V.delete(_),X.get(z)===_)X.delete(z)}let x=L.acquire(z);if(!x)throw new LO;return x},M5=async(Y,K)=>{let z=await M0(Y);try{return await K(z.value)}finally{z.release()}},h1=async(Y,K)=>{let z=await Z4(Y,K);try{await g.assertSessionWritable(z.sessionId,z.projectPath)}catch(W){if(W instanceof x4)throw new v(W.message);throw W}return M0(z)},C0=(Y)=>{let K=L.acquire(Y.key);if(!K||K.generation!==Y.generation)throw K?.release(),new LO;return K},Q$=async(Y)=>{let K=await M0(Y);try{return C0(K)}finally{K.release()}},lO=async(Y,K,z)=>{let W=await h1(Y,K);try{let _=W.value;return await z(_,WO(_),W)}finally{W.release()}},A5=async(Y,K)=>{let z=await h1(Y.sessionId,Y.projectPath);try{return await K(z.value,z)}finally{z.release()}},Z$=async(Y,K)=>{if(Y.permissionMode===K)return;let z=await g.setSessionPermissionMode(Y.id,Y.projectPath,K);Y.permissionMode=z.permissionMode,Y.updatedAt=new Date(z.lastMessageTime),P.publish(WO(Y),"session.updated",{permissionMode:K})},G1=(Y,K,z,W)=>{if(!q.stats().accepting)throw new LO;let _=n0(12),x={id:_,sessionId:Y.id,projectPath:Y.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:Y.taskIsolation!==void 0&&W.runtimeLease!==void 0,pendingResume:W.pendingResume,projectionLease:W.projectionLease,createdAt:new Date};if(Y.taskIsolation&&W.runtimeLease){let B=W.runtimeLease.value,A=j0.admit({key:`${Y.projectPath}\x00${Y.id}`,...B.getTaskAdmissionLimits(),pendingBytes:q2({content:K,outputSchema:W.outputSchema,pendingMessages:B.getPendingSteeringMessages()}),signal:x.abortController.signal,onUpdate:(M)=>{x.status=M.state,Y.taskStatus=M.state,Y.taskQueuePosition=M.queuePosition,Y.taskQueueDepth=M.queueDepth,Y.taskConcurrencyLimit=M.maxConcurrent,x.taskAdmissionUpdate=(x.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await B.setTaskAdmission(M)}).catch((C)=>{l.warn(`[SessionRoutes] Failed to persist admission for ${Y.id}:`,C)})}});x.taskAdmission=A;let I=A.getSnapshot();x.status=I.state,Y.taskStatus=I.state,Y.taskQueuePosition=I.queuePosition,Y.taskQueueDepth=I.queueDepth,Y.taskConcurrencyLimit=I.maxConcurrent}return Y0.set(_,x),Y.currentRunId=_,x.completion=f9(x,Y,K,z,OO,{pendingInputOnly:W.pendingInputOnly,preparedInputTurn:W.preparedInputTurn,goalContinuationOnly:W.goalContinuationOnly,outputSchema:W.outputSchema,taskAdmission:x.taskAdmission,runtimeLease:W.runtimeLease,projectionLease:W.projectionLease,disposeRuntime:u0,pendingResume:W.pendingResume,onPendingResumeFailure:(B,A,I,M)=>SO(Y,B,A,I,x,M),onPendingResumeSuccess:(B)=>KO(Y,B),onPendingResumeCancelled:(B)=>d(WO(Y),B.generation)}).catch((B)=>{l.error(`[SessionRoutes] Run ${_} failed:`,B)}),x},j5=async(Y)=>{let K;if(Y.outputSchema)try{K=D4(Y.outputSchema).schema}catch(c){throw new F(c instanceof Error?c.message:"Invalid output schema")}let z=c1("task",12),W=T0(Y.sourceProjectPath),_=Y.modelId?.trim(),x=MO();if(!x)throw new F("Config not initialized");let[B,A]=await Promise.all([B1(W,x),eO(W)]);if(_&&!B.config.models.some((c)=>c.id===_))throw new F(`Task model not found: ${_}`);let I=_||B.config.models.find((c)=>c.id===B.config.currentModelId)?.id||B.config.models[0]?.id;if(!I)throw new F("No model is configured. Add or select a model before dispatching a task.");let M=B.config.models.find((c)=>c.id===I);if(!M)throw new F(`Task model not found: ${I}`);let C=Y.reasoningEffort??"off",R=Y.serviceTier??"auto",f=Y.responseVerbosity??"auto",p=Y.communicationStyle??"auto",BO,AO=A.projectRules?.staticRules(W),o=AO&&AO.files.length>0?AO.provenanceSha256:void 0;try{let c=B.catalog.resolveConfig(M);J2(c,C),t$(c,R),o$(c,f);let bO=Y2(p,A.communicationStyles);BO=bO.source==="built-in"?void 0:bO.contentSha256}catch(c){throw new F(c instanceof Error?c.message:"Invalid reasoning effort")}let JO={version:1,prompt:Y.prompt,...Y.title?{title:Y.title}:{},...Y.taskPriority?{taskPriority:Y.taskPriority}:{},...Y.taskKind?{taskKind:Y.taskKind}:{},...Y.taskDueAt?{taskDueAt:Y.taskDueAt}:{},sourceProjectPath:W,isolation:Y.isolation,permissionMode:Y.permissionMode,modelId:I,reasoningEffort:C,serviceTier:R,responseVerbosity:f,communicationStyle:p,...BO?{communicationStyleDigest:BO}:{},...o?{projectInstructionsDigest:o}:{},...Y.attachments?{attachments:Y.attachments.map((c)=>({...c}))}:{},...K?{outputSchema:K}:{}},Q0,t,UO,HO,jO,r;try{let c=await H.runExclusive(async()=>{r=a(dO({sessionId:z,projectPath:W})),jO=L.reserve(r);try{return await C2.createSessionTask({sessionId:z,prompt:Y.prompt,title:Y.title,taskPriority:Y.taskPriority,taskKind:Y.taskKind,taskDueAt:Y.taskDueAt,sourceProjectPath:W,isolation:Y.isolation,dispatch:JO,retriedFrom:Y.retriedFrom})}catch(sO){throw jO?.cancel(),jO=void 0,sO}}),{metadata:bO}=c;if(Q0=c.taskWorktree,t=x1(bO,Q0),!jO)throw new LO;let DO=a(WO(t));if(r!==DO)jO.cancel(),jO=L.reserve(DO),r=DO;HO=jO.commit(t),jO=void 0,r=void 0;let k=WO(t);P.publish(k,"task.status",{taskStatus:bO.taskStatus,updatedAt:bO.lastMessageTime});let pO=a$(Y.prompt,Y.attachments);UO=await OO(t);let aO=UO.value,$O=K?await aO.prepareInputTurn(pO,{outputSchema:K}):await aO.prepareInputTurn(pO);if(!$O.accepted)throw new v(`Task prompt was not accepted: ${$O.reason}`);if(!HO)throw new LO;let XO=G1(t,pO,Y.permissionMode,{preparedInputTurn:$O,runtimeLease:UO,projectionLease:HO,outputSchema:K});return HO=void 0,UO=void 0,await XO.taskAdmissionUpdate,{session:k0(t),runId:XO.id,messageId:$O.messageId,status:XO.status==="queued"?"queued":"running",queuePosition:t.taskQueuePosition,queueDepth:t.taskQueueDepth,maxConcurrentTasks:t.taskConcurrencyLimit}}catch(c){if(jO?.cancel(),jO=void 0,r=void 0,HO?.release(),HO=void 0,UO?.release(),UO=void 0,c instanceof Z0&&!t)throw new rO("Session projection capacity is full",{resource:c.resource,limit:c.limit,retryable:c.retryable});if((c instanceof b4||c instanceof a0||c instanceof Z0)&&t){if(Q0)await K0.exit({sessionId:t.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await u0(t).catch(()=>{return}),await g.deleteSession(t.id,t.projectPath).catch(()=>{return}),new rO(c instanceof Z0?"Session projection capacity is full":c instanceof a0?"Session runtime capacity is full":"Task admission capacity is full",{resource:c.resource,limit:c.limit,...c instanceof Z0?{retryable:c.retryable}:{}})}if(t){let bO=await g.findSessionMetadata(t.id,t.projectPath).catch(()=>{return});if(!bO||bO.taskStatus==="queued"){let DO=h0(c),k=await g.updateSessionMetadata(t.id,t.projectPath,{taskStatus:"failed",taskStatusReason:DO.message,taskFailure:DO,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});t.taskStatus=k?.taskStatus??"failed",t.taskStatusReason=k?.taskStatusReason??DO.message,t.taskFailure=k?.taskFailure??DO,t.taskCompletedAt=k?.taskCompletedAt}else t.taskStatus=bO.taskStatus,t.taskStatusReason=bO.taskStatusReason,t.taskFailure=bO.taskFailure,t.taskCompletedAt=bO.taskCompletedAt}throw c}},J$=(Y)=>S(()=>j5(Y)),b5=async(Y,K)=>{let z=await hO(Y,K),W=await g.findSessionMetadata(z.sessionId,z.projectPath);if(!W)throw new i("Session",z.sessionId);if(!["failed","interrupted","cancelled"].includes(W.taskStatus))throw new v(`Task cannot be retried while status is ${W.taskStatus}`);let _=await g.findSessionTaskDispatch(z.sessionId,z.projectPath);if(!_)throw new v("Task retry payload is unavailable");return J$({prompt:_.prompt,title:W.title??_.title,taskPriority:W.taskPriority??_.taskPriority,taskKind:W.taskKind??_.taskKind,taskDueAt:W.taskDueAt,sourceProjectPath:_.sourceProjectPath,isolation:_.isolation,permissionMode:_.permissionMode,modelId:_.modelId,reasoningEffort:_.reasoningEffort,serviceTier:_.serviceTier,responseVerbosity:_.responseVerbosity,communicationStyle:_.communicationStyle,attachments:_.attachments,outputSchema:_.outputSchema,retriedFrom:z})},T5=(Y,K)=>S(()=>b5(Y,K)),I5=(Y,K,z)=>S(async()=>{let W=await hO(Y,z);if(!await g.findSessionMetadata(W.sessionId,W.projectPath))throw new i("Session",W.sessionId);let x=await g.updateSessionMetadata(W.sessionId,W.projectPath,K),B=X0(W);if(B)w0(B,x);return P.publish(W,"session.updated",{...x.title?{title:x.title}:{},...x.taskPriority?{taskPriority:x.taskPriority}:{},...x.taskKind?{taskKind:x.taskKind}:{},taskDueAt:x.taskDueAt??null}),B?k0(B):{...x,isActive:!1}}),R5=async(Y,K)=>{return lO(Y,K,async(z)=>{if(!z.taskWorktree)throw new F("Session does not have a task worktree");try{await K0.restoreSession(z.taskWorktree);let W=await K0.getDiffArtifact(z.id);if(!W)throw new v("Task diff artifact is unavailable");return{sessionId:z.id,projectPath:z.projectPath,...W}}catch(W){if(W instanceof v)throw W;throw l.error("[SessionRoutes] Failed to load task diff artifact:",W),new v("Task diff artifact is unavailable")}})},q5=async(Y,K,z)=>{let W=await hO(Y,z);return $0(W,async()=>{return A5(W,async(_)=>{if(["queued","running"].includes(_.taskStatus))throw new v(`Task artifacts cannot be delivered while status is ${_.taskStatus}`);if(_.taskDelivery?.status==="applied")throw new v("Task changes have already been applied");if(_.taskDelivery?.status==="discarded")throw new v("Task changes have already been discarded");if(!_.taskWorktree)throw new v("Task worktree is unavailable");let x=async(B,A=!1)=>{let I=await g.updateSessionMetadata(_.id,_.projectPath,{taskDelivery:B,...A?{taskWorktree:null}:{}});if(w0(_,I),A)_.taskWorktree=void 0;return P.publish(W,"task.delivery",{taskDelivery:B,...A?{taskWorktreeRemoved:!0}:{},updatedAt:I.lastMessageTime}),k0(_)};try{if(K==="discard"){try{await K0.restoreSession(_.taskWorktree)}catch(I){return l.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${_.id}:`,I),x({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:_.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let A=await K0.exit({sessionId:_.id,action:"remove",discardChanges:!0});return x({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:A.discardedFiles??0,message:"Task worktree removed"},!0)}try{await K0.restoreSession(_.taskWorktree)}catch(A){throw l.warn(`[SessionRoutes] Task worktree is unavailable for ${_.id}:`,A),new A4("artifact_unavailable","Task worktree is unavailable")}let B=await K0.apply(_.id);return x({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:B.sourceCommit,changedFiles:B.changedFiles,message:"Task changes applied to the source workspace"})}catch(B){if(B instanceof A4)throw await x({status:"conflicted",updatedAt:new Date().toISOString(),message:B.message}),new v(B.message);throw B}})})},E5=(Y,K,z)=>S(()=>q5(Y,K,z)),Y$=async(Y,K)=>{let z=WO(Y),W=a(z),_=D.get(W);if(!K&&_?.terminal)return;let x=mO(Y.currentRunId);if(kO(x)){if(K)d(WO(Y),K.generation);return}let B=Y.taskIsolation&&Y.taskStatus!=="queued"&&Y.taskStatus!=="running",A=B?await H0.hasRecoverableTurn(Y.projectPath,Y.id):!1;if(B&&!A){if(K)d(WO(Y),K.generation);return}let I=await H0.hasPendingInbox(Y.projectPath,Y.id),M=!I&&await H0.hasActiveGoal(Y.projectPath,Y.id);if(!I&&!M&&!A)A=await H0.hasRecoverableTurn(Y.projectPath,Y.id);if(!I&&!M&&!A){d(WO(Y));return}if(K&&!I){d(WO(Y),K.generation);return}let C=await OO(Y),R=!1,f,p;try{let BO=C.value,AO=mO(Y.currentRunId);if(kO(AO)){if(K)d(WO(Y),K.generation);return}if(I&&BO.getPendingSteeringCount()===0)await BO.reloadPendingInbox();let o=BO.getPendingSteeringCount()>0,JO=o?null:await BO.getGoal(),Q0=JO?.status==="active"||JO?.status==="verifying",t=BO.getTurnRecoveryAssessment();if(t.state!=="none"&&(t.state==="requires_attention"||!o&&!Q0))P.publish({sessionId:Y.id,projectPath:Y.projectPath},"turn.recovery",{assessment:t});if(t.state==="requires_attention"||B||!o&&!Q0||BO.hasTurnOwner()){if(K||!o)d(WO(Y),K?.generation);return}let UO=K;if(o&&!Y.taskIsolation&&!UO){let HO=await Q$(z);try{UO=NO(Y,HO);let jO=D.get(W);if(UO&&jO?.generation===UO.generation&&jO.projectionLease===HO)p=UO,HO=void 0}finally{HO?.release()}}if(o&&!Y.taskIsolation&&!UO)return;if(K&&!n(Y,K))return;f=K?(()=>{let HO=_?.projectionLease;if(!HO)throw new LO;return C0(HO)})():await Q$(WO(Y)),G1(Y,"",Y.permissionMode??"default",{pendingInputOnly:o,goalContinuationOnly:Q0,runtimeLease:C,projectionLease:f,pendingResume:o?UO:void 0}),f=void 0,p=void 0,R=!0}finally{if(f?.release(),p)d(z,p.generation);if(!R)C.release()}};u=async(Y,K)=>{let z;try{z=q.enter()}catch{return}try{let W=mO(Y.currentRunId);if(kO(W)){if(K)d(WO(Y),K.generation);return}if(Y.taskIsolation){await Y$(Y);return}await Y$(Y,K)}finally{z.release()}};let J4={accepting:!0,resolveSessionRef:Z4,getProjectionSnapshot:X0,snapshotAll:m1,acquireOrHydrateSession:M0,invalidateAll:$$,resumeRecoveredInteraction:u};_0=J4;let C5=async()=>{let Y={scheduled:0,failed:0,deferred:0};if(!q.stats().accepting)return Y;let K=(await g.listSessions({taskStatus:"queued"})).filter((z)=>z.taskIsolation!==void 0).sort((z,W)=>z.firstMessageTime.localeCompare(W.firstMessageTime)||z.projectPath.localeCompare(W.projectPath)||z.sessionId.localeCompare(W.sessionId));for(let[z,W]of K.entries()){let _={sessionId:W.sessionId,projectPath:W.projectPath};try{if(!await H0.hasPendingInbox(W.projectPath,W.sessionId)){let A=h0("Queued task input is missing");await g.updateSessionMetadata(W.sessionId,W.projectPath,{taskStatus:"failed",taskStatusReason:A.message,taskFailure:A,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Y.failed++;continue}let x=await M0(_),B=x.value;if(x.release(),await u(B),B.currentRunId)Y.scheduled++}catch(x){if(x instanceof b4||x instanceof a0){Y.deferred+=K.length-z;break}l.warn(`[SessionRoutes] Failed to recover queued task ${W.sessionId}:`,x),Y.deferred++}}return Y};return O.route("/",c$({withAdmission:S,resolveSessionRef:async(Y,K)=>{try{let z=await L5(Y,K);return(await M0(z)).release(),z}catch(z){if(z instanceof Z0)throw new rO("Session projection capacity is full",{resource:z.resource,limit:z.limit,retryable:z.retryable});throw z}},getRuntime:(Y)=>Q.get(Y),captureAgentScreenshot:async(Y,K)=>{return M5(Y,(z)=>iO(z,(W)=>W.captureBrowserScreenshot(K)))},resetRuntime:(Y)=>Q.reset(Y)})),O.get("/",async(Y)=>{try{let K=await g.listSessions(),z=new Set(K.filter((M)=>M.relationType==="subagent").map((M)=>a({sessionId:M.sessionId,projectPath:M.projectPath}))),W=m1().filter((M)=>!z.has(a(WO(M)))&&M.relationType!=="subagent").map((M)=>k0(M)),_=new Set(W.map((M)=>a({sessionId:M.sessionId,projectPath:M.projectPath}))),x=K.filter((M)=>{if(M.relationType==="subagent")return!1;return!_.has(a({sessionId:M.sessionId,projectPath:M.projectPath}))}),B=new Set(_),A=x.filter((M)=>{let C=a({sessionId:M.sessionId,projectPath:M.projectPath});if(B.has(C))return!1;return B.add(C),!0}),I=[...W,...A.map((M)=>({...M,isActive:!1}))];return Y.json(I)}catch(K){throw l.error("[SessionRoutes] Failed to list sessions:",K),new VO("Failed to list sessions")}}),O.get("/catalog",async(Y)=>{try{let K=Y.req.query("limit"),z=K===void 0?void 0:Number(K),W=Y.req.query("cursor"),_=Y.req.query("projectPath"),x=Y.req.query("archived");if(x!==void 0&&x!=="true"&&x!=="false")throw new F("archived must be true or false");let B=x==="true",A=await g.listSessionPage({..._?{cwd:T0(_)}:{},...W?{cursor:W}:{},...z===void 0?{}:{limit:z},includeSubagents:!1,archived:B}),I=new Map((B?[]:m1()).filter((M)=>M.relationType!=="subagent").map((M)=>[a(WO(M)),k0(M)]));return Y.json({sessions:A.sessions.map((M)=>I.get(a({sessionId:M.sessionId,projectPath:M.projectPath}))??M),...A.nextCursor?{nextCursor:A.nextCursor}:{}})}catch(K){if(K instanceof F)throw K;if(K instanceof Error&&(K.message.startsWith("Invalid session cursor")||K.message.startsWith("Session cursor scope")||K.message.startsWith("Session catalog")))throw new F(K.message);throw l.error("[SessionRoutes] Failed to list session catalog:",K),new VO("Failed to list session catalog")}}),O.post("/",async(Y)=>{try{let K=await Y.req.json(),z=y(N9,K);if(!z.success)throw new F("Invalid request body");let{title:W,projectPath:_}=z.data,x=c1("web",12),B=T0(_||Y.get("directory")||GO(),_?"projectPath":"directory"),A=dO({sessionId:x,projectPath:B}),I=await H.runExclusive(async()=>{let C=L.reserve(a(A));try{let R=await g.createSessionMetadata(x,B,{title:W,taskStatus:"completed"}),f=x1(R);return C.commit(f)}catch(R){throw C.cancel(),R}}),M=I.value;return I.release(),P.publish(A,"session.created",{}),Y.json({...k0(M),status:void 0,agentType:void 0,model:void 0})}catch(K){if(l.error("[SessionRoutes] Failed to create session:",K),K instanceof F||K instanceof _O||K instanceof Z0)throw K;throw new VO("Failed to create session")}}),O.get("/:sessionId/export",async(Y)=>{let K=Y.req.param("sessionId");try{let z=Y.req.query("includeReasoning");if(z!==void 0&&z!=="true"&&z!=="false")throw new F("includeReasoning must be true or false");let W=await hO(K,Y.req.query("projectPath")),_=await g.exportSessionMarkdown(W.sessionId,W.projectPath,{includeReasoning:z==="true"});return Y.body(_.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${_.filename}"`,"Content-Length":String(Buffer.byteLength(_.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":_.contentSha256,"X-Blade-Export-Activities":String(_.activityCount),"X-Blade-Export-Messages":String(_.messageCount),"X-Blade-Export-Redactions":String(_.redactionCount)})}catch(z){if(z instanceof F||z instanceof i||z instanceof vO)throw z;if(z instanceof Error&&z.message==="No conversation content to export")throw new v(z.message);throw l.error("[SessionRoutes] Failed to export session:",z),new VO("Failed to export session")}}),O.post("/:sessionId/fork",async(Y)=>{let K=Y.req.param("sessionId");try{M1(K);let z=await Y.req.json(),W=y(A9,z);if(!W.success)throw new F("Invalid request body");let _=T0(W.data.projectPath),x=c1("fork"),B,A=await H.runExclusive(async()=>{let C=await g.findSessionMetadata(K,_);if(!C)throw new i("Session",K);let R;try{R=L.reserve(a({sessionId:x,projectPath:C.projectPath}))}catch(f){if(!(f instanceof Z0))throw f}try{let f=await g.forkSession(K,{newSessionId:x,sourceProjectPath:C.projectPath,targetProjectPath:C.projectPath});if(R){let p=x1(f.metadata);B=R.commit(p)}return f}catch(f){throw R?.cancel(),f}}),I=x1(A.metadata),M=WO(I);return B?.release(),P.publish(M,"task.status",{taskStatus:A.metadata.taskStatus,...A.metadata.taskCompletedAt?{taskCompletedAt:A.metadata.taskCompletedAt}:{},updatedAt:A.metadata.lastMessageTime}),Y.json({session:A.metadata,messages:H4(A.messages)},201)}catch(z){if(z instanceof F||z instanceof i||z instanceof v)throw z;if(z instanceof N2)throw new v("Session has no durable creation record");throw l.error("[SessionRoutes] Failed to fork session:",z),new VO("Failed to fork session")}}),O.get("/:sessionId",async(Y)=>{let K=Y.req.param("sessionId");try{let z=await hO(K,Y.req.query("projectPath")),W=X0(z);if(W)return Y.json(k0(W));let _=await g.findSessionMetadata(z.sessionId,z.projectPath);if(!_)throw new i("Session",K);return Y.json(_)}catch(z){if(z instanceof F||z instanceof i||z instanceof vO)throw z;throw l.error("[SessionRoutes] Failed to get session:",z),new VO("Failed to get session")}}),O.patch("/:sessionId",async(Y)=>{let K=Y.req.param("sessionId");try{let z=await Y.req.json(),W=y(M9,z);if(!W.success)throw new F("Invalid request body");if(W.data.title===void 0)throw new F("title is required");let _=await hO(K,W.data.projectPath),x=await g.updateSessionMetadata(_.sessionId,_.projectPath,{title:W.data.title}),B=L.acquire(a(_));try{let A=B?.value;if(A)A.title=x.title??A.title,A.updatedAt=new Date(x.lastMessageTime)}finally{B?.release()}if(x.title)P.publish(_,"session.updated",{title:x.title});return Y.json({success:!0,title:x.title})}catch(z){if(l.error("[SessionRoutes] Failed to update session:",z),z instanceof F||z instanceof i||z instanceof vO)throw z;throw new VO("Failed to update session")}}),O.get("/:sessionId/rewind",async(Y)=>{return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),(K)=>iO(K,async(z)=>Y.json({checkpoints:await z.listRewindCheckpoints()})))}),O.post("/:sessionId/rewind",async(Y)=>{let K=y(S2,await Y.req.json());if(!K.success)throw new F("Invalid rewind request");return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,_)=>YO(W,async()=>{let x=mO(z.currentRunId);if(kO(x))throw new v("Cannot rewind while a run is active");return iO(z,async(B)=>{let A;try{A=await B.rewindSession(K.data)}catch(M){if(M instanceof Error&&M.message.startsWith("Cannot rewind while"))throw new v(M.message);throw M}await N0(z);let I=H4(A.messages);return P.publish(W,"session.rewound",{targetMessageId:A.checkpoint.messageId,mode:A.mode,removedTurns:A.removedTurns,restoredFiles:A.restoredFiles,messages:I}),Y.json({...A,messages:I})})}))}),O.get("/:sessionId/review",async(Y)=>{let K=Y.req.param("sessionId"),z=await hO(K,Y.req.query("projectPath")),W=await m0.list(z.projectPath,z.sessionId);return Y.json({reviews:W.map((_)=>({..._,content:_.completion?w2(_.start,_.completion):void 0}))})}),O.post("/:sessionId/review",async(Y)=>{let K=Y.req.param("sessionId"),z=y(h2,await Y.req.json());if(!z.success)throw new F("Invalid code review request");let W=await h1(K,z.data.projectPath),_=W.value,x=WO(_),B=a(x);try{return await YO(x,async()=>{if(kO(mO(_.currentRunId)))throw new v("Cannot start a review during an active turn");if(J0.has(B))throw new v("Session already has an active review");return iO(_,async(A)=>{if(await m0.recoverInterrupted(x.projectPath,x.sessionId,A),z.data.modelId&&!A.getModelById(z.data.modelId))throw new F(`Model not found: ${z.data.modelId}`);if(z.data.modelId&&A.getCurrentModelId()!==z.data.modelId)await A.refresh({modelId:z.data.modelId});if(z.data.modelId&&_.selectedModelId!==z.data.modelId){let f=await g.updateSessionMetadata(_.id,_.projectPath,{selectedModelId:z.data.modelId});w0(_,f)}let I=new AbortController,M,C;try{M=C0(W),C=await m0.start({sessionId:x.sessionId,projectPath:x.projectPath,runtime:A,request:{kind:z.data.kind,...z.data.ref?{ref:z.data.ref}:{},...z.data.instructions?{instructions:z.data.instructions}:{}},signal:I.signal,onEvent:(f)=>{if(f.kind==="tool_start")P.publish(x,"review.tool.started",{reviewId:C?.reviewId,toolCallId:f.toolCall.id,toolName:f.toolCall.function.name});else if(f.kind==="tool_progress")P.publish(x,"review.tool.progress",{reviewId:C?.reviewId,toolCallId:f.toolCall.id,message:f.update.message.slice(0,1000)});else if(f.kind==="tool_result")P.publish(x,"review.tool.completed",{reviewId:C?.reviewId,toolCallId:f.toolCall.id,success:f.result.success})}})}catch(f){if(M?.release(),f instanceof Error&&(f.message.includes("active review")||f.message.includes("interrupted review")||f.message.includes("active turn")))throw new v(f.message);if(f instanceof Error&&(f.message.includes("review")||f.message.includes("Git")||f.message.includes("changes")||f.message.includes("ref")))throw new F(f.message);throw f}if(!C)throw new VO("Code review failed to start");await N0(_),P.publish(x,"review.started",{reviewId:C.reviewId,kind:z.data.kind}),P.publish(x,"task.status",{taskStatus:_.taskStatus,..._.taskStatusReason?{taskStatusReason:_.taskStatusReason}:{},..._.taskStartedAt?{taskStartedAt:_.taskStartedAt}:{},..._.taskPromptSummary?{taskPromptSummary:_.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let R=C.completion.then(async(f)=>{await N0(_),P.publish(x,"task.status",{taskStatus:_.taskStatus,..._.taskStatusReason?{taskStatusReason:_.taskStatusReason}:{},..._.taskFailure?{taskFailure:_.taskFailure}:{},..._.taskStartedAt?{taskStartedAt:_.taskStartedAt}:{},..._.taskCompletedAt?{taskCompletedAt:_.taskCompletedAt}:{},..._.taskPromptSummary?{taskPromptSummary:_.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),P.publish(x,"review.completed",{reviewId:C.reviewId,status:f.status,findings:f.findings.length})}).catch((f)=>{l.error(`[SessionRoutes] Code review ${C.reviewId} failed:`,f)}).finally(()=>{if(J0.get(B)?.reviewId===C.reviewId)J0.delete(B);M?.release()});return J0.set(B,{reviewId:C.reviewId,controller:I,completion:R,projectionLease:M}),Y.json({reviewId:C.reviewId,status:"running"},202)})})}finally{W.release()}}),O.get("/:sessionId/subagents",async(Y)=>{return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),(K)=>iO(K,(z)=>Y.json({subagents:z.listSubagents().map(i1)})))}),O.post("/:sessionId/subagents/:agentId/resume",async(Y)=>{M1(Y.req.param("agentId"));let K=f2.safeParse(await Y.req.json());if(!K.success)throw new F("Invalid subagent resume request");return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,_)=>YO(W,async()=>{let x=mO(z.currentRunId);if(kO(x))throw new v("Cannot resume a subagent while a parent run is active");return iO(z,async(B)=>{let A=!1,I,M=(R)=>{P.publish(W,"subagent.complete",{subagentSessionId:R.id,success:R.status==="completed",status:R.status,summary:R.result?.message?.slice(0,500),type:R.subagentType,verificationVerdict:R.result?.verificationVerdict,resumedFrom:R.resumedFrom,rootAgentId:R.rootAgentId,resumeDepth:R.resumeDepth})},C;try{C=B.resumeSubagent({agentId:Y.req.param("agentId"),prompt:K.data.prompt,onEvent:(R,f)=>{S9(W,f,R)},onCompleted:(R)=>{if(A)M(R);else I=R}})}catch(R){if(R instanceof Error&&(R.message.startsWith("Cannot resume")||R.message.startsWith("Subagent cannot")))throw new v(R.message);if(R instanceof Error&&R.message.startsWith("Subagent not found"))throw new i(R.message);throw R}if(P.publish(W,"subagent.start",{subagentSessionId:C.session.id,type:C.session.subagentType,description:C.session.description,resumedFrom:C.source.id,rootAgentId:C.session.rootAgentId,resumeDepth:C.session.resumeDepth}),A=!0,I)M(I);return Y.json({source:i1(C.source),session:i1(C.session)})})}))}),O.get("/:sessionId/goal",async(Y)=>{return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(K)=>Y.json({goal:await new D2(K.projectPath,K.id).get()}))}),O.put("/:sessionId/goal",async(Y)=>{let K=y(j9,await Y.req.json());if(!K.success)throw new F("Invalid goal request");return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,_)=>YO(W,async()=>{let x=mO(z.currentRunId);if(kO(x))return Y.json({status:"rejected",reason:"run_active"},409);let A=K.data.permissionMode??z.permissionMode??"default";if(z.permissionMode!==A)await Z$(z,A);let I=await OO(z),M=!1,C;try{let R=await I.value.createGoal(K.data);P.publish(W,"goal.updated",{goal:R}),C=C0(_);let f=G1(z,"",A,{goalContinuationOnly:!0,runtimeLease:I,projectionLease:C});return M=!0,C=void 0,await f.taskAdmissionUpdate,Y.json({status:f.status==="queued"?"queued":"running",runId:f.id,goal:R,queuePosition:z.taskQueuePosition,queueDepth:z.taskQueueDepth,maxConcurrentTasks:z.taskConcurrencyLimit},202)}finally{if(C?.release(),!M)I.release()}}))}),O.patch("/:sessionId/goal",async(Y)=>{let K=y(b9,await Y.req.json());if(!K.success)throw new F("Invalid goal update");return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,_)=>YO(W,async()=>{let x=await OO(z),B=!1,A;try{let I=x.value,M;if(K.data.action==="pause")M=await I.pauseGoal();else if(K.data.action==="edit")M=await I.editGoal(K.data.objective);else M=await I.resumeGoal();if(P.publish(W,"goal.updated",{goal:M}),M.status==="active"&&!kO(mO(z.currentRunId))){A=C0(_);let C=G1(z,"","default",{goalContinuationOnly:!0,runtimeLease:x,projectionLease:A});return B=!0,A=void 0,await C.taskAdmissionUpdate,Y.json({status:C.status==="queued"?"queued":"running",runId:C.id,goal:M,queuePosition:z.taskQueuePosition,queueDepth:z.taskQueueDepth,maxConcurrentTasks:z.taskConcurrencyLimit},202)}return Y.json({status:M.status,goal:M})}finally{if(A?.release(),!B)x.release()}}))}),O.delete("/:sessionId/goal",async(Y)=>{return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),(K,z)=>iO(K,async(W)=>{let _=await W.clearGoal();if(_)P.publish(z,"goal.cleared",{});return Y.json({cleared:_})}))}),O.post("/:sessionId/archive",async(Y)=>{let K=Y.req.param("sessionId");try{let z=await hO(K,Y.req.query("projectPath")),W=await g.listSessionArchiveMembers(z.sessionId,z.projectPath);for(let x of W){let B=dO({sessionId:x.sessionId,projectPath:x.projectPath}),A=X0(B);if(kO(mO(A?.currentRunId)))throw new v(`Stop session ${x.sessionId} before archiving this session tree`)}for(let x of W){let B=dO({sessionId:x.sessionId,projectPath:x.projectPath}),A=X0(B);if(A)await u0(A)}let _=await g.archiveSession(z.sessionId,z.projectPath);for(let x of W){let B=dO({sessionId:x.sessionId,projectPath:x.projectPath}),A=a(B);$4(B,"archive"),await Q4(B,"archive").catch(()=>{return}),Z.delete(A),P.publish(B,"session.archived",{archiveRootId:z.sessionId,archivedAt:_.archivedAt})}if($.size===0)await uO.getInstance().disconnectAll();return Y.json({session:_,archivedSessionIds:W.map((x)=>x.sessionId)})}catch(z){if(z instanceof F||z instanceof i||z instanceof vO||z instanceof v)throw z;if(z instanceof L4)throw new v(z.message);throw l.error("[SessionRoutes] Failed to archive session:",z),new VO("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Y)=>{let K=Y.req.param("sessionId");try{let z=await hO(K,Y.req.query("projectPath")),W=await g.listSessionArchiveMembers(z.sessionId,z.projectPath),_=await g.unarchiveSession(z.sessionId,z.projectPath),x=W.filter((B)=>B.sessionId===z.sessionId||B.archivedBySessionId===z.sessionId).map((B)=>B.sessionId);for(let B of x)P.publish({sessionId:B,projectPath:z.projectPath},"session.unarchived",{archiveRootId:z.sessionId});return Y.json({session:_,restoredSessionIds:x})}catch(z){if(z instanceof F||z instanceof i||z instanceof vO)throw z;if(z instanceof L4)throw new v(z.message);throw l.error("[SessionRoutes] Failed to unarchive session:",z),new VO("Failed to unarchive session")}}),O.delete("/:sessionId",async(Y)=>{let K=Y.req.param("sessionId"),z=Y.req.query("projectPath");try{let W=await hO(K,z);d(W);let _=a(W),x=L.acquire(_),B=x?.value,A=B?.currentRunId,I=$.get(_),M=B?.taskWorktree??await g.findSessionTaskWorktree(W.sessionId,W.projectPath);x?.release();let C;if(A){let p=mO(A);if(p)b1(p),await p.completion,C=p.id}let R=J0.get(_);if(R)R.controller.abort("session-delete"),await R.completion;if(I)await I.clearGoal().catch((p)=>{l.warn("[SessionRoutes] Failed to clear session goal:",p)});if(await Q.dispose(W),await g.deleteSession(W.sessionId,W.projectPath),$4(W,"delete"),C)R9(C);await Q4(W,"delete").catch(()=>{return}),Z.delete(_),P.publish(W,"session.deleted",{});let f=$.get(_);if(f){if(!await T.remove(_,f))throw new v("Session Runtime is still active and cannot be deleted")}if(M)try{await K0.restoreSession(M),await K0.exit({sessionId:W.sessionId,action:"remove",discardChanges:!0})}catch(p){l.warn(`[SessionRoutes] Failed to remove deleted task worktree ${W.sessionId}:`,p)}return Y.json({success:!0})}catch(W){if(l.error("[SessionRoutes] Failed to delete session:",W),W instanceof F||W instanceof i||W instanceof vO)throw W;throw new VO("Failed to delete session")}}),O.get("/:sessionId/message",async(Y)=>{let K=Y.req.param("sessionId");try{let z=await hO(K,Y.req.query("projectPath")),W=await g.loadSession(z.sessionId,z.projectPath);return Y.json(H4(W))}catch(z){if(l.error("[SessionRoutes] Failed to get messages:",z),z instanceof F||z instanceof i||z instanceof vO)throw z;throw new VO("Failed to get messages")}}),O.get("/:sessionId/follow-ups",async(Y)=>{return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),(K,z)=>YO(z,async()=>Y.json(await z1(K))))}),O.post("/:sessionId/follow-ups/mutate",async(Y)=>{let K=D9.safeParse(await Y.req.json());if(!K.success)throw new F("Invalid follow-up queue mutation");return lO(Y.req.param("sessionId"),K.data.projectPath??Y.req.query("projectPath"),(z,W)=>YO(W,async()=>{try{return await iO(z,async(_)=>{let x={expectedVersion:K.data.expectedVersion,operation:K.data.operation},B=await _.mutateFollowUpQueue(x);if(B.snapshot.version!==x.expectedVersion)P.publish(W,"follow_up.queue.changed",{queue:B.snapshot});return Y.json(B)})}catch(_){if(!L9(_))throw _;let x=_.code==="not_found"?404:_.code==="invalid_mutation"?400:_.code==="storage_unavailable"||_.code==="runtime_unavailable"?503:409;return Y.json({error:{code:_.code,message:_.message},snapshot:_.snapshot},x)}}))}),O.get("/:sessionId/events",async(Y)=>{let K=Y.req.param("sessionId"),z;try{z=b.enter(Y.req.raw.signal)}catch{throw new LO}let W=!1;try{let _=await hO(K,Y.req.query("projectPath"));try{await g.assertSessionWritable(_.sessionId,_.projectPath)}catch(R){if(R instanceof x4)throw new v(R.message);throw R}let x=await M0(_),B=x.value,A=Y.req.header("Last-Event-ID")??Y.req.query("lastEventId"),I=A?Number.parseInt(A,10):Number.NaN,M=Number.isInteger(I)?I+1:void 0,C=H9(Y,async(R)=>{let p=new Set,BO,AO,o=!1,JO,Q0,t=new Promise((k)=>{Q0=k}),UO,HO=new Set,jO=(k)=>{let pO=k;return p.add(pO),k.finally(()=>{p.delete(pO)})},r=()=>{if(BO?.(),BO=void 0,AO!==void 0)clearInterval(AO),AO=void 0},c=(k)=>{if(UO)return UO;return o=!0,UO=(async()=>{try{r(),JO?.close(k),R.close()}finally{Q0()}})(),UO},bO=()=>{c(z.signal.reason)},DO=async(k)=>{await c(k),await Promise.allSettled([...p]),z.signal.removeEventListener("abort",bO),z.release()};if(z.signal.addEventListener("abort",bO,{once:!0}),R.onAbort(()=>{c()}),z.signal.aborted){await DO(z.signal.reason);return}JO=new K1({write:async(k)=>{await R.writeSSE(k)},onFailure:(k)=>{if(n$(k,o))return;l.warn(`[SessionRoutes] SSE egress closed for ${_.sessionId}: kind=${k.kind} pendingItems=${k.pendingItems??0} pendingBytes=${k.pendingBytes??0}`),c(k)}}),BO=P.subscribe((k)=>{if(o)return;if(k.sessionId!==_.sessionId||k.projectPath!==_.projectPath)return;let pO=k.properties.requestId;if((k.type==="permission.asked"||k.type==="question.required"||k.type==="elicitation.required")&&typeof pO==="string"){if(HO.has(pO))return;HO.add(pO)}if(k.type==="subagent.completion.queued"){let $O=YO(_,()=>u(B)).catch((XO)=>{l.error(`[SessionRoutes] Failed to wake background completion for ${B.id}:`,XO)});jO($O)}if(k.type==="team.message.received"&&typeof k.properties.teamName==="string"&&typeof k.properties.messageId==="string"&&typeof k.properties.content==="string"&&M2(k.properties.metadata,{messageId:k.properties.messageId,teamName:k.properties.teamName})){let $O=k.properties.teamName,XO=k.properties.messageId,sO=k.properties.content,TO=k.properties.metadata,xO=YO(_,async()=>{let IO=await OO(B),S0=!1;try{let V0=await IO.value.enqueueSteering(sO,{allowBeforeTurn:!0,messageId:XO,origin:"team_message",metadata:TO});if(!V0.accepted)return;if(V0.queue&&!V0.duplicate)P.publish(_,"follow_up.queue.changed",{queue:V0.queue});await new L2($O,l1()).markDelivered([XO]),S0=V0.delivery==="next_turn"}finally{IO.release()}if(!S0)return;await u(B).catch((V0)=>{l.error(`[SessionRoutes] Failed to wake teammate delivery for ${B.id}:`,V0)})}).catch((IO)=>{l.error(`[SessionRoutes] Failed to deliver teammate message for ${B.id}:`,IO)});jO(xO)}if(k.type==="subagent.completion.queued"||k.type==="team.message.received")return;let aO=q9(k);if(aO)JO?.observe(aO,k.seq)});try{if(R.aborted||o)return;let k=mO(B.currentRunId),pO=await YO(_,()=>z1(B)),aO=kO(k)?await OO(B):void 0;try{let TO=aO?.value,xO=TO?.getPendingSteeringCount()??0;await JO.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:_.sessionId,projectPath:_.projectPath,timestamp:Date.now(),status:kO(k)?k.status:"idle",runId:kO(k)?k.id:void 0,queued:xO,pendingInputDelivery:xO>0?TO?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:TO?.getRecoveredSteeringCount()??0,followUpQueue:pO,providerRecovery:TO?.getProviderRecoveryProjection()??null,turnActivity:TO?.getTurnActivityProjection()??null}})})}finally{aO?.release()}if(R.aborted||o)return;if(M!==void 0){if(await x2.for(_.sessionId,_.projectPath).replay({onCommitted:async(xO)=>{if(R.aborted||o)return;let IO=d2(xO);if(!IO||IO.seq===void 0)return;await JO.writeReplay({...typeof xO.seq==="number"?{id:String(xO.seq)}:{},data:JSON.stringify({type:IO.type,...IO.seq!==void 0?{seq:IO.seq}:{},properties:{...IO.properties,sessionId:_.sessionId,projectPath:_.projectPath}})},IO.seq)}},M),R.aborted||o)return}if(JO.finishInitialization({replayed:M!==void 0}),R.aborted||o)return;if(!k&&!J0.has(a(_))){let xO=(await m0.list(_.projectPath,_.sessionId)).some((IO)=>IO.completion===void 0)?await iO(B,(IO)=>m0.recoverInterrupted(_.projectPath,_.sessionId,IO)):void 0;if(xO)await N0(B),P.publish(_,"review.completed",{reviewId:xO.reviewId,status:xO.status,findings:0,recovered:!0})}if(R.aborted||o)return;if(!k)await y0.recoverResponded(_.projectPath,_.sessionId);if(R.aborted||o)return;let $O=k?void 0:await y0.findPending(_.projectPath,_.sessionId),XO=k?.pendingPermission??($O?{permissionId:$O.request.requestId,details:y0.confirmationDetails($O),resolve:()=>{return}}:void 0);if(XO){HO.add(XO.permissionId);let TO=u2(XO,!0);JO.observe({data:JSON.stringify({type:TO.type,properties:{...TO.properties,sessionId:_.sessionId,projectPath:_.projectPath}})})}if(R.aborted||o)return;let sO=u(B).catch(async(TO)=>{if(TO instanceof A0){await N0(B).catch(()=>{return});let xO=B.taskFailure?.code==="workspace_unavailable"?B.taskFailure:A1("workspace_unavailable");B.taskStatus="failed",B.taskStatusReason=xO.message,B.taskFailure=xO,P.publish(_,"session.error",{error:xO.message,taskFailure:xO}),P.publish(_,"session.status",{status:"error"})}l.error(`[SessionRoutes] Failed to resume pending input for ${K}:`,TO)});if(jO(sO),R.aborted||o)return;AO=setInterval(()=>{if(R.aborted||o)return;JO?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await t}catch(k){if(n$(k,o))return;throw k}finally{await DO()}});return W=!0,x.release(),C}catch(_){if(!W)z.release();throw _}}),O.post("/:sessionId/message",async(Y)=>{let K=Y.req.param("sessionId"),z=await Y.req.json(),W=y(B9,z);if(!W.success)throw new F("Invalid message format");let{content:_,attachments:x,modelId:B,reasoningEffort:A,serviceTier:I,responseVerbosity:M,communicationStyle:C,permissionMode:R,projectPath:f,annotations:p,outputSchema:BO}=W.data,AO;if(BO)try{AO=D4(BO).schema}catch(DO){throw new F(DO instanceof Error?DO.message:"Invalid output schema")}let o=C;if(Buffer.byteLength(_,"utf8")>N4)throw new F(`Message text exceeds the ${N4}-byte limit`);let JO=B?.trim();if((x??[]).reduce((DO,k)=>DO+(typeof k.content==="string"?Buffer.byteLength(k.content):0),0)>a1)throw new F("Message attachments exceed the 5 MiB limit");let t=R,UO=a$(_,x),HO=p&&p.length>0?{selectedConversationAnnotations:p}:void 0,jO=await h1(K,f??Y.req.query("projectPath")),r=jO.value,c=WO(r),bO=t??r.permissionMode??"default";try{return await YO(c,async()=>{let DO=mO(r.currentRunId);if(kO(DO)){if(AO)throw new v("Wait for the active turn to finish before setting an output schema");return iO(r,async($O)=>{if(JO&&!$O.getModelById(JO))throw new F(`Model not found: ${JO}`);if(JO&&$O.getCurrentModelId()!==JO)throw new v("Wait for the active turn to finish before switching models");if(A&&$O.getReasoningConfiguration().selection!==A)throw new v("Wait for the active turn to finish before switching reasoning effort");if(I&&$O.getServiceTierConfiguration().selection!==I)throw new v("Wait for the active turn to finish before switching service tier");if(M&&$O.getResponseVerbosityConfiguration().selection!==M)throw new v("Wait for the active turn to finish before switching response verbosity");if(o&&$O.getCommunicationStyleConfiguration().selection!==o)throw new v("Wait for the active turn to finish before switching communication style");if(t&&r.permissionMode!==t)throw new v("Wait for the active turn to finish before switching permission mode");let XO=await $O.enqueueSteering(UO,{allowBeforeTurn:!0,...HO?{metadata:HO}:{}});if(!XO.accepted)return Y.json({status:"rejected",reason:XO.reason??"turn_unavailable"},409);let sO=XO.messageId??n0(12),TO=XO.queued,xO=XO.queue??await $O.getFollowUpQueueSnapshot(),IO=XO.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(P.publish(c,IO,{runId:DO.id,messageId:sO,queued:TO}),!XO.duplicate)P.publish(c,"follow_up.queue.changed",{queue:xO});if(XO.delivery==="next_turn"&&DO.status!=="running"&&DO.status!=="waiting_permission")u(r).catch((S0)=>{l.error(`[SessionRoutes] Failed to wake queued follow-up for ${K}:`,S0)});if(XO.delivery==="next_turn")DO.pendingFollowUpRequested=!0;return Y.json({runId:DO.id,messageId:sO,status:XO.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:TO,followUpQueue:xO},202)})}if(d(c),r.permissionMode!==bO)await Z$(r,bO);let k=await OO(r,{permissionMode:bO,...o&&!o.includes(":")?{communicationStyle:o}:{}}),pO=!1,aO;try{let $O=k.value;if(JO&&!$O.getModelById(JO))throw new F(`Model not found: ${JO}`);if(A)try{$O.resolveReasoningConfiguration(A,JO)}catch(EO){throw new F(EO instanceof Error?EO.message:"Invalid reasoning effort")}if(I)try{$O.resolveServiceTierConfiguration(I,JO)}catch(EO){throw new F(EO instanceof Error?EO.message:"Invalid service tier")}if(M)try{$O.resolveResponseVerbosityConfiguration(M,JO)}catch(EO){throw new F(EO instanceof Error?EO.message:"Invalid response verbosity")}let XO=o?$O.resolveCommunicationStyleConfiguration(o):void 0;if(XO?.source!==void 0&&XO.source!=="built-in"&&!XO.contentSha256)throw new F("Custom communication style has no provenance");let sO=$O.getCurrentModelId(),TO=$O.getReasoningConfiguration(),xO=$O.getServiceTierConfiguration(),IO=$O.getResponseVerbosityConfiguration(),S0=$O.getCommunicationStyleConfiguration(),V0=Boolean(JO)&&sO!==JO,X$=Boolean(A)&&TO.selection!==A,V$=Boolean(I)&&xO.selection!==I,z$=Boolean(M)&&IO.selection!==M,G$=Boolean(o)&&S0.selection!==o;if(V0||X$||V$||z$||G$)await $O.refresh({...JO?{modelId:JO}:{},...A?{reasoningEffort:A}:{},...I?{serviceTier:I}:{},...M?{responseVerbosity:M}:{},...o?{communicationStyle:o}:{}});let Y4={...JO&&r.selectedModelId!==JO?{selectedModelId:JO}:{},...A&&r.reasoningEffort!==A?{reasoningEffort:A}:{},...I&&r.serviceTier!==I?{serviceTier:I}:{},...M&&r.responseVerbosity!==M?{responseVerbosity:M}:{},...XO&&(r.communicationStyle!==o||r.communicationStyleDigest!==XO.contentSha256)?{communicationStyle:o,communicationStyleDigest:XO.source==="built-in"?null:XO.contentSha256}:{}};if(Object.keys(Y4).length>0)try{let EO=await g.updateSessionMetadata(r.id,r.projectPath,Y4);r.permissionMode=EO.permissionMode,r.selectedModelId=EO.selectedModelId,r.reasoningEffort=EO.reasoningEffort,r.serviceTier=EO.serviceTier,r.responseVerbosity=EO.responseVerbosity,r.communicationStyle=EO.communicationStyle,r.communicationStyleDigest=EO.communicationStyleDigest,r.updatedAt=new Date(EO.lastMessageTime),P.publish(c,"session.updated",Y4)}catch(EO){if(V0||X$||V$||z$||G$)await $O.refresh({...sO?{modelId:sO}:{},reasoningEffort:TO.selection,serviceTier:xO.selection,responseVerbosity:IO.selection,communicationStyle:S0.selection}).catch((S5)=>l.error("[SessionRoutes] Failed to roll back non-durable model settings:",S5));throw EO}let W1=AO||HO?await $O.prepareInputTurn(UO,{...AO?{outputSchema:AO}:{},...HO?{metadata:HO}:{}}):await $O.prepareInputTurn(UO);if(!W1.accepted)return Y.json({status:"rejected",reason:W1.reason},W1.reason==="queue_full"?429:409);aO=C0(jO);let X4=G1(r,UO,bO,{preparedInputTurn:W1,outputSchema:AO,runtimeLease:k,projectionLease:aO});return pO=!0,aO=void 0,await X4.taskAdmissionUpdate,Y.json({runId:X4.id,messageId:W1.messageId,status:X4.status==="queued"?"queued":"running",queuePosition:r.taskQueuePosition,queueDepth:r.taskQueueDepth,maxConcurrentTasks:r.taskConcurrencyLimit},202)}finally{if(aO?.release(),!pO)k.release()}})}finally{jO.release()}}),O.post("/:sessionId/side-question",async(Y)=>{let K=Y.req.param("sessionId"),z=y(m2,await Y.req.json());if(!z.success)throw new F("Invalid side conversation request");return lO(K,z.data.projectPath??Y.req.query("projectPath"),(W)=>k1(W,async(_)=>{let x=await _.askSideQuestion(z.data.question,{signal:Y.req.raw.signal});return Y.json({...x,..._.getCurrentModelId()?{modelId:_.getCurrentModelId()}:{}})}))}),O.post("/:sessionId/shell",async(Y)=>{let K=Y.req.param("sessionId"),z=y(k2,await Y.req.json());if(!z.success)throw new F("Invalid user shell command");return lO(K,z.data.projectPath??Y.req.query("projectPath"),(W,_,x)=>{let B=a(_);return YO(_,async()=>{if(F0.has(B))throw new v("A user shell command is already running in this Session");let A=await OO(W),I=C0(x),M=A.value,C=new AbortController,R,f=new Promise((p)=>{R=p});F0.set(B,{controller:C,completion:f,projectionLease:I});try{let p=await M.executeUserShellCommand(z.data.command,{signal:C.signal});await N0(W);let BO=mO(W.currentRunId);if(p.delivery==="next_turn"&&kO(BO))BO.pendingFollowUpRequested=!0;if(p.queue)P.publish(_,"follow_up.queue.changed",{queue:p.queue});return Y.json({executionId:p.executionId,messageId:p.messageId,record:p.record,auxiliary:p.auxiliary,...p.delivery?{delivery:p.delivery}:{},...p.queued!==void 0?{queued:p.queued}:{}})}finally{F0.delete(B),R(),A.release(),I.release()}})})}),O.post("/:sessionId/abort",async(Y)=>{let K=Y.req.param("sessionId"),z=await hO(K,Y.req.query("projectPath"));d(z);let W=X0(z);if(W?.currentRunId){let B=mO(W.currentRunId);if(B)b1(B),await B.completion}let _=F0.get(a(z));if(_)_.controller.abort("user-cancel"),await _.completion;let x=J0.get(a(z));if(x)x.controller.abort("user-cancel"),await x.completion;return Y.json({success:!0})}),O.get("/:sessionId/status",async(Y)=>{let K=Y.req.param("sessionId"),z=await hO(K,Y.req.query("projectPath")),W=X0(z),_=J0.get(a(z));if(_)return Y.json({sessionId:K,projectPath:z.projectPath,reviewId:_.reviewId,status:"reviewing"});if(!W?.currentRunId)return Y.json({sessionId:K,projectPath:z.projectPath,status:"idle"});let x=mO(W.currentRunId);return Y.json({sessionId:K,projectPath:z.projectPath,runId:W.currentRunId,status:x?.status==="attention_required"?"idle":x?.status??"idle"})}),{app:O,dispatchTask:J$,retryTask:T5,updateTask:I5,getTaskDiff:R5,deliverTask:E5,recoverQueuedTasks:C5,getRuntimeResidencyStats:()=>T.getStats(),getProjectionResidencyStats:()=>L.getStats(),getCoordinationStats:()=>({messageSubmissions:w.getStats(),taskDeliveries:N.getStats()}),getSseConnectionStats:()=>b.stats(),shutdown:(Y="server-shutdown")=>{if(m)return m;q.close(Y);let K=b.shutdown(Y);J4.accepting=!1,$$("server-shutdown");let z=Promise.allSettled([...V].map((W)=>W.promise));return clearInterval(E),clearInterval(h),fO(),m=(async()=>{let W,_=async(M)=>{let C=await Promise.allSettled(M);for(let R of C)if(R.status==="rejected")W??=R.reason},x=new Set,B=()=>{for(let M of Y0.values()){if(M.completion)x.add(M.completion);if(kO(M))b1(M,Y)}for(let M of F0.values())M.controller.abort(Y),x.add(M.completion);for(let M of J0.values())M.controller.abort(Y),x.add(M.completion)},A=q.waitForIdle(),I=!1;A.then(()=>{I=!0});while(!I)B(),await Promise.race([A,new Promise((M)=>setImmediate(M))]);if(await A,B(),await _([...x]),await z,await _([...Z.values()]),B(),await _([...x]),await _([K]),await _([...Z.values()]),await _([T.disposeAll()]),$.clear(),await _([...J.values()]),await _([Q.disposeAll()]),await _([uO.getInstance().disconnectAll()]),Z.clear(),J.clear(),X.clear(),V.clear(),_0===J4)_0=void 0;if(j1===fO)j1=void 0;if(W!==void 0)throw W})(),m}}};async function f9(O,$,Q,Z,J,X={}){let{abortController:V,sessionId:w,id:N}=O,H=X.preparedInputTurn?.messageId??n0(12),T=X.pendingInputOnly===!0||X.preparedInputTurn?.mode==="pending"||X.goalContinuationOnly===!0?void 0:n0(12),L=X.runtimeLease,q=X.projectionLease,b,E,h=!1,m=!1,D,e=WO($),u=X.pendingResume?.projectedInputIds??new Set,FO=(d)=>{if(u.has(d))return;if(u.size>=A2){let n=u.values().next().value;if(n!==void 0)u.delete(n)}u.add(d)},fO=async(d)=>{let n=d.metadata?.recoveryAttention;if(!n||!b)return!1;if(X.preparedInputTurn)await b.finishTurn(X.preparedInputTurn.handle,{preserveStartupRecovery:!0,outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}}).catch(()=>{return});let NO=`Turn recovery requires attention: ${n.reason}`,qO=await b.setTaskStatus("interrupted",NO).catch(()=>{return});if(qO)w0($,qO);else $.taskStatus="interrupted",$.taskStatusReason=NO,$.taskCompletedAt=void 0;return O.status="attention_required",S("session.status",{status:"idle"}),!0},S=(d,n)=>{P.publish(e,d,n)},YO=async()=>{let d=String(V.signal.reason||"Task run cancelled");if($.taskIsolation){if(!L)L=await J($).catch(()=>{return});let n=b??L?.value;if(d==="user-cancel")await n?.discardPendingInput().catch((qO)=>{l.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,qO)});let NO=await n?.setTaskStatus("cancelled",d).catch(()=>{return});if(NO)w0($,NO);else await N0($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=d,$.taskCompletedAt??=new Date().toISOString()};try{if(X.pendingResume){let U=X.pendingResume.deadlineAt-Date.now();if(U<=0)throw V.abort(d1),new L1({taskFailure:A1("timeout"),outputStarted:!1,toolExecutionStarted:!1,toolCallsCount:0});else D=setTimeout(()=>{V.abort(d1);let OO=O.pendingPermission;if(O.pendingPermission=void 0,OO?.resolve({approved:!1,reason:T4}),OO)S("interaction.resolved",{requestId:OO.permissionId})},U),D.unref?.()}if(X.taskAdmission){if(await X.taskAdmission.ready,await O.taskAdmissionUpdate,V.signal.aborted)throw Error(String(V.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!X.pendingInputOnly&&!X.goalContinuationOnly)S("message.created",{messageId:H,role:"user",content:l$(Q),...X.preparedInputTurn?.metadata?{metadata:X.preparedInputTurn.metadata}:{}});if(S("session.status",{status:"running"}),T)S("message.created",{messageId:T,role:"assistant",content:""});L??=await J($),b=L.value;let d=b,n=Boolean(X.outputSchema??d.getPendingSteeringMessages().find((U)=>U.outputSchema)?.outputSchema);E=await E2.createWithRuntime(d,{sessionId:w,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let NO=async(U)=>{let OO=U.interactionRequestId??n0(12),iO=300000;O.status="waiting_permission";let P1=new Promise((u0)=>{let O4=setTimeout(()=>{l.warn(`[SessionRoutes] Permission ${OO} timed out after 300000ms`),S("permission.timeout",{requestId:OO}),u0({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:OO,resolve:(d0)=>{clearTimeout(O4),u0(d0)},details:U}}),V1=O.pendingPermission;if(!V1)throw Error("Permission request was not registered");let k1=u2(V1);S(k1.type,k1.properties),l.info(`[SessionRoutes] Permission request created: ${OO}, runId: ${N}`);let z1=await P1;if(l.info(`[SessionRoutes] Permission response received: ${OO}, approved: ${z1.approved}`),!V.signal.aborted)O.status="running";if(O.pendingPermission===V1)O.pendingPermission=void 0;return S("interaction.resolved",{requestId:OO}),z1},SO={messages:await g.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:w,workspaceRoot:$.projectPath,signal:V.signal,permissionMode:Z,onPermissionModeChange:async(U)=>{$.permissionMode=U,$.updatedAt=new Date,S("session.updated",{permissionMode:U})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:NO}},KO=()=>{if(!T)T=n0(12),S("message.created",{messageId:T,role:"assistant",content:""});return T},$0=async(U)=>{switch(U.kind){case"content_delta":if(U.delta.length>0)h=!0;if(n)break;S("message.delta",{messageId:KO(),delta:U.delta});break;case"structured_output":h=!0,S("structured.output",{messageId:KO(),output:U.output,schemaDigest:U.schemaDigest});break;case"thinking_delta":if(U.delta.length>0)h=!0;S("thinking.delta",{messageId:KO(),delta:U.delta});break;case"tool_start":if(m=!0,"function"in U.toolCall){if(U.toolCall.function.name===o0)break;S("tool.start",{messageId:KO(),toolName:U.toolCall.function.name,toolCallId:U.toolCall.id,arguments:U.toolCall.function.arguments,toolKind:U.toolKind})}break;case"tool_result":if(m=!0,"function"in U.toolCall){if(U.toolCall.function.name===o0)break;S("tool.result",{messageId:KO(),toolName:U.toolCall.function.name,toolCallId:U.toolCall.id,success:U.result.success,summary:U.result.metadata?.summary,output:E1(R1(q1(U.toolCall.function.name,U.result),I1)),metadata:T1(U.toolCall.function.name,U.result.metadata)})}break;case"tool_progress":if(m=!0,"function"in U.toolCall){if(U.toolCall.function.name===o0)break;S("tool.progress",{messageId:KO(),toolName:U.toolCall.function.name,toolCallId:U.toolCall.id,...U.update})}break;case"token_usage":S("token.usage",{...U.usage});break;case"turn_start":S("turn.started",{turn:U.turn,maxTurns:U.maxTurns});break;case"turn_recovery":S("turn.recovery",{assessment:U.assessment});break;case"provider_admission":S("provider.admission",{phase:U.phase,requestClass:U.requestClass,resource:U.resource,scope:U.scope,reason:U.reason,queuePosition:U.queuePosition,queueDepth:U.queueDepth,inFlight:U.inFlight,limit:U.limit,waitMs:U.waitMs,maxWaitMs:U.maxWaitMs,recoveryRemainingMs:U.recoveryRemainingMs});break;case"provider_circuit":S("provider.circuit",{phase:U.phase,reason:U.reason,statusCode:U.statusCode,retryAfterMs:U.retryAfterMs,nextProbeAt:U.nextProbeAt,openDurationMs:U.openDurationMs,sampleCount:U.sampleCount,failureCount:U.failureCount,recoveryRemainingMs:U.recoveryRemainingMs});break;case"provider_retry":S("provider.retry",{phase:U.phase,attempt:U.attempt,maxRetries:U.maxRetries,reason:U.reason,statusCode:U.statusCode,delayMs:U.delayMs,nextRetryAt:U.nextRetryAt,mode:U.mode,recoveryBudgetMs:U.recoveryBudgetMs,recoveryElapsedMs:U.recoveryElapsedMs,recoveryRemainingMs:U.recoveryRemainingMs,exhaustedBy:U.exhaustedBy});break;case"provider_stall":S("provider.stall",{phase:U.phase,stallCount:U.stallCount,durationMs:U.durationMs,warningAfterMs:U.warningAfterMs,timeoutMs:U.timeoutMs,outputStarted:U.outputStarted});break;case"provider_recovery":break;case"turn_activity":break;case"action_stationarity":S("action.stationarity",{phase:U.phase,toolName:U.toolName,runLength:U.runLength,nudgeThreshold:U.nudgeThreshold,haltThreshold:U.haltThreshold,progressAware:U.progressAware});break;case"mcp_catalog_changed":S("mcp.catalog.changed",{messageId:KO(),revision:U.revision,serverName:U.serverName,added:U.added,removed:U.removed,updated:U.updated});break;case"mcp_content_changed":S("mcp.content.changed",{messageId:KO(),revision:U.revision,serverName:U.serverName,contentKind:U.contentKind,added:U.added,removed:U.removed,updated:U.updated});break;case"mcp_resource_updated":S("mcp.resource.updated",{messageId:KO(),revision:U.revision,serverName:U.serverName,uri:U.uri});break;case"mcp_connection_changed":S("mcp.connection.changed",{messageId:KO(),revision:U.revision,serverName:U.serverName,phase:U.phase,reason:U.reason,attempt:U.attempt,maxAttempts:U.maxAttempts,nextRetryAt:U.nextRetryAt,error:U.error});break;case"mcp_log":S("mcp.log",{messageId:KO(),revision:U.revision,serverName:U.serverName,level:U.level,logger:U.logger,message:U.message,projectedBytes:U.projectedBytes,dataSha256:U.dataSha256,truncated:U.truncated,detailsOmitted:U.detailsOmitted,timestamp:U.timestamp,synthetic:U.synthetic});break;case"mcp_instructions_changed":S("mcp.instructions.changed",{messageId:KO(),revision:U.revision,serverName:U.serverName,action:U.action,reason:U.reason,text:U.text,sourceBytes:U.sourceBytes,projectedBytes:U.projectedBytes,sha256:U.sha256,truncated:U.truncated,detailsOmitted:U.detailsOmitted});break;case"mcp_task_changed":S("mcp.task.changed",{messageId:KO(),revision:U.revision,taskId:U.taskId,serverName:U.serverName,toolName:U.toolName,status:U.status,statusMessage:U.statusMessage,createdAt:U.createdAt,updatedAt:U.updatedAt,completedAt:U.completedAt,hasResult:U.hasResult,error:U.error});break;case"project_rules_loaded":S("project.rules.loaded",{messageId:KO(),files:U.files,triggerPaths:U.triggerPaths,blockedWrite:U.blockedWrite});break;case"steering_applied":for(let OO of U.messages){if((OO.origin??"user")!=="user")continue;if(OO.persisted)continue;if(u.has(OO.id))continue;S("message.created",{messageId:OO.id,role:"user",content:l$(OO.content),...OO.metadata?{metadata:OO.metadata}:{},...OO.recovered?{recovered:!0}:{}}),FO(OO.id)}S("steering.applied",{runId:N,messageIds:U.messageIds,count:U.count,recovered:U.recovered,delivery:U.delivery,queued:d.getPendingSteeringCount()}),S("follow_up.queue.changed",{queue:U.queue});break;case"follow_up_started":{if(T)S("message.complete",{messageId:T}),T=void 0;S("follow_up.started",{runId:N,queued:U.queued,recovered:U.recovered}),S("follow_up.queue.changed",{queue:U.queue}),KO();break}case"follow_up_queue_changed":S("follow_up.queue.changed",{queue:U.queue});break;case"goal_updated":S("goal.updated",{goal:U.goal});break;case"goal_continuation_started":S("goal.continuation.started",{goal:U.goal,continuation:U.continuation,...U.prematureStopPattern?{prematureStopPattern:U.prematureStopPattern}:{},...U.prematureStopCount!==void 0?{prematureStopCount:U.prematureStopCount}:{}}),KO();break;case"compaction":S(U.phase==="start"?"compaction.started":"compaction.completed",{...U.reason?{reason:U.reason}:{},...U.strategy?{strategy:U.strategy}:{},...U.outcome?{outcome:U.outcome}:{},...U.preTokens!==void 0?{preTokens:U.preTokens}:{},...U.preTokenSource?{preTokenSource:U.preTokenSource}:{},...U.estimatedPendingTokens!==void 0?{estimatedPendingTokens:U.estimatedPendingTokens}:{},...U.postTokens!==void 0?{postTokens:U.postTokens}:{},...U.sampleAttempts!==void 0?{sampleAttempts:U.sampleAttempts}:{},...U.inputReductions!==void 0?{inputReductions:U.inputReductions}:{},...U.messagesOmitted!==void 0?{messagesOmitted:U.messagesOmitted}:{},...U.filesOmitted!==void 0?{filesOmitted:U.filesOmitted}:{},...U.imagesOmitted!==void 0?{imagesOmitted:U.imagesOmitted}:{},...U.fallbackTargetTokens!==void 0?{fallbackTargetTokens:U.fallbackTargetTokens}:{},...U.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:U.fallbackMessagesOmitted}:{},...U.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:U.fallbackMessagesTruncated}:{},...U.failureReason?{failureReason:U.failureReason}:{},...U.memory?{memory:U.memory}:{}});break;case"model_fallback":S("model.fallback",{from:U.from,to:U.to,candidate:U.candidate,candidateCount:U.candidateCount,trigger:U.trigger});break;case"task_update":S("task.updated",{tasks:U.tasks});break;case"goal_frontier_updated":S("goal.frontier.updated",{goalId:U.goal.goalId,goalStatus:U.goal.status,frontier:U.frontier,stall:U.goal.frontierStall});break;default:break}},tO=(U)=>{let OO=U.metadata?.toolCallsCount;return new L1({taskFailure:h0(U.error?.details??U.error?.message??"Agent run failed"),outputStarted:h,toolExecutionStarted:m,toolCallsCount:typeof OO==="number"&&Number.isInteger(OO)?OO:-1})},gO=await M4(E.chatStream(Q,SO,{stream:!0,pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:X.taskAdmission}),$0);if(await fO(gO))return;if(!gO.success)throw tO(gO);for(let U=0;U<20;U++){let OO=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,d.getPendingSteeringCount()===0){if(!OO)break;continue}if(V.signal.aborted)break;if(gO=await M4(E.chatStream("",SO,{stream:!0,pendingInputOnly:!0,taskAdmission:X.taskAdmission}),$0),await fO(gO))return;if(!gO.success)throw tO(gO)}if(await N0($),X.pendingResume&&V.signal.aborted&&V.signal.reason===d1)throw new L1({taskFailure:A1("timeout"),outputStarted:h,toolExecutionStarted:m,toolCallsCount:Number.isInteger(gO.metadata?.toolCallsCount)?gO.metadata?.toolCallsCount??-1:-1});if(V.signal.aborted||O.status==="cancelled"){await YO(),S("session.status",{status:"idle"});return}if(X.pendingResume)X.onPendingResumeSuccess?.(X.pendingResume);if(T)S("message.complete",{messageId:T});S("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),S("session.completed",{runId:N,outputTruncated:gO.metadata?.outputTruncated??!1}),S("session.status",{status:"idle"})}catch(d){if(b&&X.preparedInputTurn)await(b.getTurnRecoveryAssessment().state==="requires_attention"?b.finishTurn(X.preparedInputTurn.handle,{preserveStartupRecovery:!0}):b.finishTurn(X.preparedInputTurn.handle)).catch(()=>{return});let n=X.pendingResume!==void 0&&V.signal.aborted&&V.signal.reason===d1;if(V.signal.aborted&&!n||O.status==="cancelled"){if(X.pendingResume)X.onPendingResumeCancelled?.(X.pendingResume);b1(O,"runtime-abort"),await YO(),S("session.status",{status:"idle"});return}let NO=d instanceof L1?d.evidence:n?{taskFailure:A1("timeout"),outputStarted:h,toolExecutionStarted:m,toolCallsCount:-1}:X.pendingResume?{taskFailure:h0(d),outputStarted:!0,toolExecutionStarted:!0,toolCallsCount:-1}:void 0,qO=X.pendingResume!==void 0&&NO!==void 0&&X.onPendingResumeFailure?.(X.pendingResume,NO,n||(b?.getPendingSteeringCount()??0)>0,n)===!0;if(O.status="failed",qO){let KO=await b?.setTaskStatus("running").catch(()=>{return});if(KO)w0($,KO);$.taskStatus="running",$.taskStatusReason=void 0,$.taskFailure=void 0,$.taskCompletedAt=void 0,S("session.status",{status:"running"});return}await N0($).catch(()=>{return}),l.error("[SessionRoutes] Agent execution error:",d),$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let SO=NO?.taskFailure??h0(d);if(!$.taskFailure){let KO=b?await b.setTaskStatus("failed",d).catch(()=>{return}):await g.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:SO.message,taskFailure:SO,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(KO)w0($,KO)}$.taskStatusReason??=SO.message,$.taskFailure??=SO,S("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),S("session.status",{status:"error"})}finally{if(D)clearTimeout(D);if(X.taskAdmission?.release(),X.taskAdmission){let d=j0.getStats();S("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:d.queued,taskConcurrencyLimit:d.maxConcurrent,taskInFlight:d.inFlight,taskAdmissionPaused:d.paused,updatedAt:new Date().toISOString()})}if(await E?.destroy().catch(()=>{return}),L?.release(),q?.release(),O.disposeRuntimeOnSettle&&X.disposeRuntime)await X.disposeRuntime($,b).catch((d)=>{l.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,d)});I9(O)}}async function i2(O,$,Q){l.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),l.info(`[SessionRoutes] Active runs: ${Y0.size}`);for(let[V,w]of Y0.entries())if(l.info(`[SessionRoutes] Checking run ${V}: sessionId=${w.sessionId}, projectPath=${w.projectPath}, pendingPermission=${w.pendingPermission?.permissionId}`),w.sessionId===O.sessionId&&w.projectPath===O.projectPath&&w.pendingPermission?.permissionId===$){if(w.pendingPermission.details.interactionRequestId)await y0.respond(O.projectPath,O.sessionId,$,Q);return w.pendingPermission.resolve(Q),l.info(`[SessionRoutes] Permission ${$} responded, runId: ${w.id}`),!0}let Z=await y0.findPending(O.projectPath,O.sessionId);if(!Z||Z.request.requestId!==$)return l.error(`[SessionRoutes] Permission not found: ${$}`),!1;await y0.respondAndRecover(O.projectPath,O.sessionId,$,Q),P.publish(O,"interaction.resolved",{requestId:$});let J=_0;if(!J?.accepting)return!0;let X;try{X=await J.acquireOrHydrateSession(O);let V=X.value,w=await g.findSessionMetadata(O.sessionId,O.projectPath);if(_0!==J||!J.accepting||!X.isCurrent())return!0;if(w)w0(V,w);J.resumeRecoveredInteraction(V).catch((N)=>{l.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,N)})}catch(V){if(_0!==J||!J.accepting)return!0;throw V}finally{X?.release()}return!0}var R4=ZO("Service"),k9=G.Object({approved:G.Boolean(),remember:G.Optional(G.Boolean()),scope:G.Optional(zO(["once","session","project"])),targetMode:G.Optional(zO(["default","autoEdit","plan","yolo"])),feedback:G.Optional(G.String({maxLength:4000})),answers:G.Optional(G.Record(G.String({maxLength:80}),G.Union([G.String({maxLength:4000}),G.Array(G.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:G.Optional(G.Object({action:zO(["accept","decline","cancel"]),content:G.Optional(G.Record(G.String(),G.Union([G.String({maxLength:4000}),G.Number(),G.Boolean(),G.Array(G.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),l2=()=>{let O=new P9;return O.post("/:permissionId",async($)=>{let Q=$.req.param("permissionId"),Z=$.req.query("sessionId"),J=$.req.query("projectPath");R4.info(`[PermissionRoutes] Received permission response: permissionId=${Q}, sessionId=${Z}`);try{let X=await $.req.json(),V=y(k9,X);if(!V.success)throw new F("Invalid permission response format");let{approved:w,remember:N,scope:H,targetMode:j,feedback:T,answers:L,elicitation:q}=V.data;if(!Z)throw new F("sessionId query parameter is required");let b=await hO(Z,J);if(!await i2(b,Q,{approved:w,reason:T,scope:H,targetMode:j,feedback:T,answers:L,elicitation:q}))throw new i("Permission request",Q);return R4.info(`[PermissionRoutes] Permission ${Q} ${w?"approved":"denied"}`),$.json({success:!0,approved:w,remember:N})}catch(X){if(R4.error("[PermissionRoutes] Failed to respond to permission:",X),X instanceof F||X instanceof vO||X instanceof i||X instanceof _O)throw X;throw X}}),O};import{homedir as a2}from"node:os";import q4 from"node:path";import{Hono as m9}from"hono";var h9=G.Object({projectPath:G.String({minLength:1}),enabled:G.Boolean(),scope:G.Optional(zO(["local","project","global"]))}),y9=G.Object({projectPath:G.String({minLength:1})}),g9=G.Object({projectPath:G.String({minLength:1}),source:G.String({minLength:1}),trust:G.Literal(!0),ref:G.Optional(G.String({minLength:1}))}),p9=G.Object({projectPath:G.String({minLength:1}),trust:G.Literal(!0)}),v9=G.Object({projectPath:G.String({minLength:1}),confirm:G.Literal(!0)}),u9=G.Object({projectPath:G.String({minLength:1}),source:G.String({minLength:1}),ref:G.Optional(G.String({minLength:1}))}),n2=G.Object({projectPath:G.String({minLength:1}),confirm:G.Optional(G.Literal(!0))}),d9=G.Object({projectPath:G.String({minLength:1}),scope:G.Optional(zO(["local","project","global"])),policy:G.Object({restrictToAllowedSources:G.Boolean(),requireGitCommitSha:G.Boolean(),allowedGitHosts:G.Array(G.String()),allowedMarketplaces:G.Array(G.String()),allowedLocalRoots:G.Array(G.String())})});function O0(O){if(!O)throw new F("projectPath must be absolute");try{return wO(O)}catch{throw new F("projectPath must reference a local workspace")}}function c9(O){return q4.isAbsolute(O)||O.startsWith("./")||O.startsWith("../")||O==="~"||O.startsWith("~/")}function o2(O,$){if(!c9(O))return;let Q=O==="~"?a2():O.startsWith("~/")?q4.join(a2(),O.slice(2)):O;try{wO(q4.resolve($,Q))}catch{throw new F("Plugin source must reference a local workspace")}}async function t2(O){let[$,Q]=await Promise.all([eO(O),U1.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((Z)=>({name:Z.manifest.name,description:Z.manifest.description,version:Z.manifest.version,source:Z.source,enabled:Z.status==="active",status:Z.status,commands:Z.commands.length,skills:Z.skills.length,agents:Z.agents.length,hooks:Z.hooks?Object.values(Z.hooks).reduce((J,X)=>J+(Array.isArray(X)?X.length:0),0):0,mcpServers:Object.keys(Z.mcpServers??{}).length,configurable:Z.source!=="cli",managed:Z.installation!==void 0,marketplace:Z.installation?.source.type==="marketplace"?Z.installation.source.marketplace:void 0,revision:Z.installation?.revision,installedAt:Z.installation?.installedAt,updatedAt:Z.installation?.updatedAt,compatibilityIssues:Z.compatibilityIssues??[],effectiveScope:Z.source==="cli"?"invocation":Q.settings[Z.manifest.name]?.effectiveScope??"default",settingLayers:Z.source==="cli"?{invocation:!0}:Q.settings[Z.manifest.name]?.layers??{}}))}async function i9(){let O=s2(),[$,Q]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),Z=new Map(Q.map((J)=>[J.name,J]));return $.map(({marketplace:J,manifest:X})=>({name:J.name,description:X.description??X.metadata?.description??"",sourceType:J.source.type,revision:J.revision,updatedAt:J.updatedAt,plugins:X.plugins.map((V)=>{let w=Z.get(V.name);return{name:V.name,description:V.description??"",version:V.version,category:V.category,tags:V.tags??[],installed:w!==void 0,installedVersion:w?.version}})}))}function t0(O,$){if(!O.success)throw new F(O.error??$)}var V3=()=>{let O=new m9;return O.get("/",async($)=>{let Q=O0($.req.query("projectPath"));return $.json(await t2(Q))}),O.post("/refresh",async($)=>{let Q=y(y9,await $.req.json());if(!Q.success)throw new F("Invalid plugin refresh request");let Z=O0(Q.data.projectPath),J=await e2(Z);return $.json({plugins:await t2(Z),errors:J.discovery.errors.map((X)=>({code:X.code??"LOAD_ERROR",error:X.error}))})}),O.get("/catalog",async($)=>{return O0($.req.query("projectPath")),$.json(await i9())}),O.get("/policy",async($)=>{let Q=O0($.req.query("projectPath")),Z=await U1.getInstance().loadWorkspacePluginSourcePolicy(Q);return $.json({policy:Z,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let Q=y(d9,await $.req.json());if(!Q.success)throw new F("Invalid plugin source policy request");let Z=O0(Q.data.projectPath),J=await O3(Z,Q.data.policy,Q.data.scope??"global");return $.json({policy:J})}),O.post("/install",async($)=>{let Q=y(g9,await $.req.json());if(!Q.success)throw new F("Invalid plugin install request; explicit source trust is required");let Z=O0(Q.data.projectPath);o2(Q.data.source,Z);let{result:J}=await $3(Z,Q.data.source,{trusted:Q.data.trust,ref:Q.data.ref});return t0(J,"Plugin installation failed"),$.json({name:J.pluginName,version:J.manifest?.version,revision:J.installation?.revision,changed:J.changed,installedDependencies:J.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let Q=y(u9,await $.req.json());if(!Q.success)throw new F("Invalid marketplace add request");let Z=O0(Q.data.projectPath);o2(Q.data.source,Z);let J=await J3(Z,Q.data.source,Q.data.ref);return t0(J,"Marketplace installation failed"),$.json({name:J.marketplace?.name,plugins:J.manifest?.plugins.length??0,revision:J.marketplace?.revision,changed:J.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let Q=y(n2,await $.req.json());if(!Q.success)throw new F("Invalid marketplace refresh request");let Z=await Y3(O0(Q.data.projectPath),$.req.param("name"));return t0(Z,"Marketplace refresh failed"),$.json({name:Z.marketplace?.name,plugins:Z.manifest?.plugins.length??0,revision:Z.marketplace?.revision,changed:Z.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let Q=y(n2,await $.req.json());if(!Q.success||Q.data.confirm!==!0)throw new F("Invalid marketplace removal request; explicit confirmation is required");O0(Q.data.projectPath);let Z=await X3($.req.param("name"),!0);return t0(Z,"Marketplace removal failed"),$.json({name:Z.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let Q=y(p9,await $.req.json());if(!Q.success)throw new F("Invalid plugin update request; explicit source trust is required");let Z=O0(Q.data.projectPath),{result:J}=await Q3(Z,$.req.param("name"),{trusted:Q.data.trust});return t0(J,"Plugin update failed"),$.json({name:J.pluginName,version:J.manifest?.version,revision:J.installation?.revision,changed:J.changed,updatedDependencies:J.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let Q=y(v9,await $.req.json());if(!Q.success)throw new F("Invalid plugin uninstall request; explicit confirmation is required");let Z=O0(Q.data.projectPath),{result:J}=await Z3(Z,$.req.param("name"),Q.data.confirm);return t0(J,"Plugin uninstall failed"),$.json({name:J.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let Q=y(h9,await $.req.json());if(!Q.success)throw new F("Invalid plugin state request");let Z=O0(Q.data.projectPath),J=$.req.param("name"),V=(await eO(Z)).plugins.get(J);if(!V)throw new i("Plugin",J);if(V.source==="cli")throw new F(`Plugin "${J}" was loaded with --plugin-dir and is invocation-scoped`);let w=await r2(Z,J,Q.data.enabled,Q.data.scope??"local");return $.json(w)}),O};import{Hono as t9}from"hono";import{execFile as l9}from"node:child_process";import a9 from"node:path";var S4="__BLADE_DIRECTORY_PICKER_CANCELLED__",n9=900000;function o9(O,$){return new Promise((Q)=>{l9(O,[...$],{timeout:n9,maxBuffer:65536,windowsHide:!0},(Z,J,X)=>{let V=Z?.code;Q({stdout:J,stderr:X,exitCode:typeof V==="number"?V:Z?1:0,...typeof V==="string"?{errorCode:V}:{}})})})}function E4(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===S4)return{cancelled:!0};if(!a9.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function C4(O){return O.exitCode!==0||Boolean(O.errorCode)}class z3{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??o9}pick(){if(this.activeSelection)return this.activeSelection;let O=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=O,O}async pickForPlatform(){switch(this.platform){case"darwin":return this.pickOnMac();case"win32":return this.pickOnWindows();case"linux":return this.pickOnLinux();default:throw Error("Native folder selection is unavailable on this system")}}async pickOnMac(){let O=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${S4}"`,"end try"].join(`
7
+ `)}function a$(O,$){let Q=($??[]).filter((J)=>J.type==="image"&&typeof J.content==="string").map((J)=>({type:"image_url",image_url:{url:J.content}}));if(Q.length===0)return O;let Z=[];if(O.trim())Z.push({type:"text",text:O});return Z.push(...Q),Z}function n$(O,$){return $&&O instanceof z0&&(O.kind==="closed"||O.kind==="aborted")}var c2=()=>{E9();let O=new U9;O.onError((Y,K)=>{if(Y instanceof a0){let z=new rO("Session runtime capacity is full",{resource:Y.resource,limit:Y.limit});return K.json(z.toObject(),429)}if(Y instanceof Z0){let z=new rO("Session projection capacity is full",{resource:Y.resource,limit:Y.limit,retryable:Y.retryable});return K.json(z.toObject(),429)}if(Y instanceof _O)return K.json(Y.toObject(),Y.statusCode);return l.error("[SessionRoutes] Unhandled route error:",Y),K.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,Q=new w4,Z=new Map,J=new Map,X=new Map,V=new Set,w=new F4,N=new F4,H=new w9,j=MO(),T=new y2({maxResident:j?.maxResidentSessionRuntimes??$2,idleMs:j?.sessionRuntimeIdleMs??Q2}),L=new _4({maxResident:j?.maxResidentSessionProjections??s$,idleMs:j?.sessionProjectionIdleMs??r$,toSnapshot:T9}),q=new w1,b=new w1,E=setInterval(()=>{T.sweepIdle().catch((Y)=>{l.warn("[SessionRoutes] Session Runtime idle sweep failed:",Y)})},Z2);E.unref?.();let h=setInterval(()=>{try{L.sweepIdle()}catch(Y){l.warn("[SessionRoutes] Session projection idle sweep failed:",Y)}},e$);h.unref?.();let m,D=new Map,e=1,u,FO=(Y)=>{let K=Y.projectionLease;Y.projectionLease=void 0,K?.release()},fO=()=>{for(let Y of D.values()){if(Y.timer)clearTimeout(Y.timer);FO(Y)}D.clear()};j1=fO;let S=async(Y,K)=>{let z;try{z=q.enter(K)}catch{throw new LO}try{return await Y(z.signal)}finally{z.release()}};O.use("*",async(Y,K)=>{if(Y.req.method==="GET"||Y.req.method==="HEAD")return K();return S((z)=>{return Y.set("requestSignal",z),K()},Y.req.raw.signal)});let YO=(Y,K)=>w.runExclusive(a(Y),K),d=(Y,K)=>{let z=a(Y),W=D.get(z);if(!W||K!==void 0&&W.generation!==K)return;if(W.timer)clearTimeout(W.timer);FO(W),D.delete(z)},n=(Y,K)=>{let z=D.get(a(WO(Y)));return z?.generation===K.generation&&z.attempt===K.attempt&&z.inFlight&&!z.terminal},NO=(Y,K)=>{let z=a(WO(Y)),W=D.get(z);if(W){if(K?.release(),W.inFlight||W.timer||W.terminal)return}else{if(!K)throw new LO;W={attempt:0,generation:e++,inFlight:!1,projectedInputIds:new Set,projectionLease:K,startedAt:Date.now(),terminal:!1,timer:void 0},D.set(z,W)}return W.inFlight=!0,W.attempt++,{attempt:W.attempt,deadlineAt:W.startedAt+p2,generation:W.generation,projectedInputIds:W.projectedInputIds}},qO=(Y,K,z,W,_)=>{P.publish(Y,"pending.resume",{phase:K,kind:"pending_input",attempt:z,maxAttempts:g2,..._===void 0?{}:{delayMs:_,nextRetryAt:Date.now()+_},...W?{failure:{code:W.code,retryable:W.retryable,...W.resource?{resource:W.resource}:{}}}:{}})},SO=(Y,K,z,W,_,x)=>{let B=WO(Y),A=a(B),I=D.get(A);if(!I||I.generation!==K.generation)return!1;if(x)return I.inFlight=!1,I.terminal=!0,FO(I),qO(B,"exhausted",K.attempt,z.taskFailure),!1;let M=v2({sessionIdentity:A,failedAttempt:K.attempt,recoveryStartedAt:I.startedAt,workStillPending:W,evidence:z});if(M.phase!=="retry_scheduled")return I.inFlight=!1,I.terminal=!0,FO(I),qO(B,M.phase,K.attempt,z.taskFailure),!1;if(!I.projectionLease)return!1;let C=setTimeout(()=>{(async()=>{if(await _.completion,D.get(A)!==I||I.timer!==C)return;await YO(B,async()=>{if(D.get(A)!==I||I.timer!==C)return;I.timer=void 0,I.inFlight=!1;let R=NO(Y);if(!R)return;try{await u(Y,R)}catch(f){if(D.get(A)!==I)return;let p=h0(f);I.inFlight=!1,I.terminal=!0;try{let BO=new Date().toISOString(),AO;try{AO=await g.updateSessionMetadata(Y.id,Y.projectPath,{taskStatus:"failed",taskStatusReason:p.message,taskFailure:p,taskCompletedAt:BO,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null})}catch{l.error(`[SessionRoutes] Failed to persist terminal pending input state for ${Y.id}`)}if(D.get(A)!==I||!I.terminal)return;if(Y.taskStatus="failed",Y.taskStatusReason=p.message,Y.taskFailure=p,Y.taskCompletedAt=BO,AO)w0(Y,AO);qO(B,"failed",R.attempt,p),P.publish(B,"session.error",{error:p.message,taskFailure:p}),P.publish(B,"session.status",{status:"error"})}finally{FO(I)}}})})().catch((R)=>{l.error(`[SessionRoutes] Failed to retry pending input for ${Y.id}:`,R)})},M.delayMs);return C.unref?.(),I.timer=C,I.inFlight=!1,qO(B,"retry_scheduled",K.attempt+1,z.taskFailure,M.delayMs),!0},KO=(Y,K)=>{let z=WO(Y),W=D.get(a(z));if(!W||W.generation!==K.generation)return!1;if(K.attempt>1)qO(z,"recovered",K.attempt);return d(z,K.generation),!0},$0=(Y,K)=>N.runExclusive(a(Y),K),tO=(Y)=>[...Y0.values()].some((K)=>K.sessionId===Y.sessionId&&K.projectPath===Y.projectPath&&kO(K)),gO=async(Y,K,z)=>{let W=J.get(K);if(!W)W=(async()=>{if($.get(K)===z)$.delete(K);for(let[x,B]of $)if(B===z)$.delete(x);let _=WO(Y);if(X0(_)?.id===Y.id&&!tO(_)&&!F0.has(K)&&!J0.has(K))await Q4(_,"route-reset").catch(()=>{return});if(await z.dispose(),$.size===0)await uO.getInstance().disconnectAll()})().finally(()=>{if(J.get(K)===W)J.delete(K)}),J.set(K,W);await W},U=(Y,K={})=>{let z=K.communicationStyle??Y.communicationStyle;return{sessionId:Y.id,workspaceRoot:Y.projectPath,permissionMode:K.permissionMode??Y.permissionMode??"default",...Y.reasoningEffort?{reasoningEffort:Y.reasoningEffort}:{},...Y.serviceTier?{serviceTier:Y.serviceTier}:{},...Y.responseVerbosity?{responseVerbosity:Y.responseVerbosity}:{},...z?{communicationStyle:z}:{},...z===Y.communicationStyle&&Y.communicationStyleDigest?{communicationStyleDigest:Y.communicationStyleDigest}:{},...Y.projectInstructionsDigest?{projectInstructionsDigest:Y.projectInstructionsDigest}:{},...Y.taskWorktree?{taskWorktree:Y.taskWorktree}:{},...Y.taskIsolation?{taskIsolation:Y.taskIsolation}:{},...Y.messageCount>0?{sessionStart:{isResume:!0,resumeSessionId:Y.id}}:{}}},OO=async(Y,K={})=>{let z=WO(Y),W=a(z);await J.get(W);let _=T.acquire(W);if(_){if($.get(W)!==_.value)throw _.release(),Error("Session Runtime residency identity is inconsistent");return _}if(T.owns(W))throw new a0(T.getStats().maxResident);let x=Z.get(W);if(!x)x=(async()=>{let B=await T.reserve(W,{surface:"web",allowEviction:!0}),A;try{A=await H0.create(U(Y,K));let I=A.getCurrentModelId();if(I&&(Y.selectedModelId||Y.taskModelId)&&I!==Y.selectedModelId){let R=await g.updateSessionMetadata(Y.id,Y.projectPath,{selectedModelId:I}).catch((f)=>{l.warn(`[SessionRoutes] Failed to migrate restored model for ${Y.id}:`,f);return});if(R)Y.selectedModelId=R.selectedModelId,Y.updatedAt=new Date(R.lastMessageTime)}let M=A,C=B.commit({key:W,surface:"web",value:M,canEvict:()=>!tO(z)&&!F0.has(W)&&!J0.has(W)&&!Z.has(W)&&!J.has(W)&&M.isIdleForResidency(),dispose:()=>gO(Y,W,M)});return A=void 0,$.set(W,M),{runtime:M,claimLease:()=>{if(C){let f=C;return C=void 0,f}let R=T.acquire(W);if(!R||R.value!==M)throw Error("Initialized Session Runtime lost residency");return R}}}catch(I){if(B.cancel(),A)await A.dispose().catch((M)=>{l.warn(`[SessionRoutes] Failed to dispose uncommitted Runtime for ${Y.id}:`,M)});if(I instanceof j4)throw new A0(I.reason);throw I}})(),Z.set(W,x);try{return(await x).claimLease()}finally{if(Z.get(W)===x)Z.delete(W)}},iO=async(Y,K,z={})=>{let W=await OO(Y,z);try{return await K(W.value)}finally{W.release()}},P1=(Y)=>{if(Y instanceof A0||Y instanceof _O)return Y;if(Y instanceof j4)return new A0(Y.reason);if(Y instanceof V2)return new v(Y.message);if(Y instanceof Error&&"code"in Y&&(Y.code==="ENOENT"||Y.code==="ENOTDIR"))return new A0("workspace_missing");return Y instanceof Error?Y:Error(String(Y))},V1=(Y)=>{if(Y.taskIsolation!=="worktree"||Y.taskWorktree)return;if(!Y.taskSourceProjectPath)throw new A0("task_source_project_missing");return T0(Y.taskSourceProjectPath)},k1=async(Y,K)=>{let z=WO(Y),W=a(z),_=V1(Y);if(!_||$.has(W)||Z.has(W))try{return await iO(Y,K)}catch(A){throw P1(A)}let x=MO();if(!x)throw new LO("Configuration is not initialized");let B;try{let[A,I]=await Promise.all([B1(_,x),eO(_)]);return B=await H0.create({...U(Y),workspace:R2(_),modelResources:A,agentResources:X2(I),lspResources:{projectRoot:_,servers:{}},auxiliaryReadOnly:!0}),await K(B)}catch(A){throw P1(A)}finally{await B?.dispose()}},z1=async(Y)=>{let K=a(WO(Y));if(!$.has(K)&&!Z.has(K)&&!await H0.hasDurableFollowUpInbox(Y.projectPath,Y.id))return I2();return iO(Y,(z)=>z.getFollowUpQueueSnapshot())},u0=async(Y,K)=>{let z=a(WO(Y)),W=Z.get(z);if(W)await W.catch(()=>{return});Z.delete(z);let _=K??$.get(z);if(!_)return;if(!await T.remove(z,_))throw Error(`Session Runtime is pinned and cannot be disposed: ${z}`)},O4=(Y,K)=>{if(K==="delete")throw new i("Session",Y.sessionId);if(K==="archive")throw new v("Session is archived");throw new LO},d0=(Y,K,z)=>{if(z.invalidatedBy)O4(Y,z.invalidatedBy);if(X.get(K)!==z)throw new LO},$4=(Y,K)=>{let z=a(Y),W=X.get(z);if(!W)return;if(W.invalidatedBy??=K,W.cancelReservation?.(),W.cancelReservation=void 0,X.get(z)===W)X.delete(z)},$$=(Y)=>{for(let K of V)K.invalidatedBy??=Y,K.cancelReservation?.(),K.cancelReservation=void 0;X.clear()},X0=(Y)=>L.snapshot(a(Y)),m1=()=>L.snapshotAll(),Q4=async(Y,K)=>{$4(Y,K);let z=a(Y);if(!X0(Y))return;let W=L.beginCloseMany([z],K);await W.waitForIdle({deadlineAt:Date.now()+O2}),W.commit()},L5=async(Y,K)=>{if(K!==void 0)return M1(Y),dO({sessionId:Y,projectPath:T0(K)});return Z4(Y,K)},Z4=async(Y,K)=>{if(M1(Y),K!==void 0){let W=dO({sessionId:Y,projectPath:T0(K)});if(X0(W))return W;let _=await g.findSessionMetadata(W.sessionId,W.projectPath);if(!_)throw new i("Session",Y);return dO({sessionId:_.sessionId,projectPath:_.projectPath})}let z=new Map;for(let W of m1()){if(W.id!==Y)continue;let _=WO(W);z.set(a(_),_)}for(let W of await g.listSessions()){if(W.sessionId!==Y)continue;let _=dO({sessionId:W.sessionId,projectPath:W.projectPath});z.set(a(_),_)}if(z.size===0)try{let W=await g.findSessionMetadata(Y);if(!W)throw new i("Session",Y);return dO({sessionId:W.sessionId,projectPath:W.projectPath})}catch(W){if(W instanceof i)throw W;if(W instanceof Error&&W.message.startsWith("Ambiguous session ID:"))throw new vO;throw W}if(z.size>1)throw new vO;return z.values().next().value},M0=async(Y)=>{let K=_0;if(!K?.accepting||K.acquireOrHydrateSession!==M0)throw new LO;let z=a(Y),W=L.acquire(z);if(W)return W;let _=X.get(z);if(!_){let B;B={promise:Promise.resolve().then(async()=>{let I=L.acquire(z);if(I){I.release();return}d0(Y,z,B);let M=L.reserve(z);B.cancelReservation=()=>M.cancel();try{let C=await g.findSessionMetadata(Y.sessionId,Y.projectPath);if(d0(Y,z,B),!C)throw new i("Session",Y.sessionId);let R=await g.findSessionTaskWorktree(Y.sessionId,Y.projectPath);d0(Y,z,B);let f=x1(C,R);d0(Y,z,B);let p=M.commit(f);B.cancelReservation=void 0,p.release()}catch(C){throw B.cancelReservation?.(),B.cancelReservation=void 0,C}})},_=B,X.set(z,_),V.add(_)}try{await _.promise}finally{if(V.delete(_),X.get(z)===_)X.delete(z)}let x=L.acquire(z);if(!x)throw new LO;return x},M5=async(Y,K)=>{let z=await M0(Y);try{return await K(z.value)}finally{z.release()}},h1=async(Y,K)=>{let z=await Z4(Y,K);try{await g.assertSessionWritable(z.sessionId,z.projectPath)}catch(W){if(W instanceof x4)throw new v(W.message);throw W}return M0(z)},C0=(Y)=>{let K=L.acquire(Y.key);if(!K||K.generation!==Y.generation)throw K?.release(),new LO;return K},Q$=async(Y)=>{let K=await M0(Y);try{return C0(K)}finally{K.release()}},lO=async(Y,K,z)=>{let W=await h1(Y,K);try{let _=W.value;return await z(_,WO(_),W)}finally{W.release()}},A5=async(Y,K)=>{let z=await h1(Y.sessionId,Y.projectPath);try{return await K(z.value,z)}finally{z.release()}},Z$=async(Y,K)=>{if(Y.permissionMode===K)return;let z=await g.setSessionPermissionMode(Y.id,Y.projectPath,K);Y.permissionMode=z.permissionMode,Y.updatedAt=new Date(z.lastMessageTime),P.publish(WO(Y),"session.updated",{permissionMode:K})},G1=(Y,K,z,W)=>{if(!q.stats().accepting)throw new LO;let _=n0(12),x={id:_,sessionId:Y.id,projectPath:Y.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:Y.taskIsolation!==void 0&&W.runtimeLease!==void 0,pendingResume:W.pendingResume,projectionLease:W.projectionLease,createdAt:new Date};if(Y.taskIsolation&&W.runtimeLease){let B=W.runtimeLease.value,A=j0.admit({key:`${Y.projectPath}\x00${Y.id}`,...B.getTaskAdmissionLimits(),pendingBytes:q2({content:K,outputSchema:W.outputSchema,pendingMessages:B.getPendingSteeringMessages()}),signal:x.abortController.signal,onUpdate:(M)=>{x.status=M.state,Y.taskStatus=M.state,Y.taskQueuePosition=M.queuePosition,Y.taskQueueDepth=M.queueDepth,Y.taskConcurrencyLimit=M.maxConcurrent,x.taskAdmissionUpdate=(x.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await B.setTaskAdmission(M)}).catch((C)=>{l.warn(`[SessionRoutes] Failed to persist admission for ${Y.id}:`,C)})}});x.taskAdmission=A;let I=A.getSnapshot();x.status=I.state,Y.taskStatus=I.state,Y.taskQueuePosition=I.queuePosition,Y.taskQueueDepth=I.queueDepth,Y.taskConcurrencyLimit=I.maxConcurrent}return Y0.set(_,x),Y.currentRunId=_,x.completion=f9(x,Y,K,z,OO,{pendingInputOnly:W.pendingInputOnly,preparedInputTurn:W.preparedInputTurn,goalContinuationOnly:W.goalContinuationOnly,outputSchema:W.outputSchema,taskAdmission:x.taskAdmission,runtimeLease:W.runtimeLease,projectionLease:W.projectionLease,disposeRuntime:u0,pendingResume:W.pendingResume,onPendingResumeFailure:(B,A,I,M)=>SO(Y,B,A,I,x,M),onPendingResumeSuccess:(B)=>KO(Y,B),onPendingResumeCancelled:(B)=>d(WO(Y),B.generation)}).catch((B)=>{l.error(`[SessionRoutes] Run ${_} failed:`,B)}),x},j5=async(Y)=>{let K;if(Y.outputSchema)try{K=D4(Y.outputSchema).schema}catch(c){throw new F(c instanceof Error?c.message:"Invalid output schema")}let z=c1("task",12),W=T0(Y.sourceProjectPath),_=Y.modelId?.trim(),x=MO();if(!x)throw new F("Config not initialized");let[B,A]=await Promise.all([B1(W,x),eO(W)]);if(_&&!B.config.models.some((c)=>c.id===_))throw new F(`Task model not found: ${_}`);let I=_||B.config.models.find((c)=>c.id===B.config.currentModelId)?.id||B.config.models[0]?.id;if(!I)throw new F("No model is configured. Add or select a model before dispatching a task.");let M=B.config.models.find((c)=>c.id===I);if(!M)throw new F(`Task model not found: ${I}`);let C=Y.reasoningEffort??"off",R=Y.serviceTier??"auto",f=Y.responseVerbosity??"auto",p=Y.communicationStyle??"auto",BO,AO=A.projectRules?.staticRules(W),o=AO&&AO.files.length>0?AO.provenanceSha256:void 0;try{let c=B.catalog.resolveConfig(M);J2(c,C),t$(c,R),o$(c,f);let bO=Y2(p,A.communicationStyles);BO=bO.source==="built-in"?void 0:bO.contentSha256}catch(c){throw new F(c instanceof Error?c.message:"Invalid reasoning effort")}let JO={version:1,prompt:Y.prompt,...Y.title?{title:Y.title}:{},...Y.taskPriority?{taskPriority:Y.taskPriority}:{},...Y.taskKind?{taskKind:Y.taskKind}:{},...Y.taskDueAt?{taskDueAt:Y.taskDueAt}:{},sourceProjectPath:W,isolation:Y.isolation,permissionMode:Y.permissionMode,modelId:I,reasoningEffort:C,serviceTier:R,responseVerbosity:f,communicationStyle:p,...BO?{communicationStyleDigest:BO}:{},...o?{projectInstructionsDigest:o}:{},...Y.attachments?{attachments:Y.attachments.map((c)=>({...c}))}:{},...K?{outputSchema:K}:{}},Q0,t,UO,HO,jO,r;try{let c=await H.runExclusive(async()=>{r=a(dO({sessionId:z,projectPath:W})),jO=L.reserve(r);try{return await C2.createSessionTask({sessionId:z,prompt:Y.prompt,title:Y.title,taskPriority:Y.taskPriority,taskKind:Y.taskKind,taskDueAt:Y.taskDueAt,sourceProjectPath:W,isolation:Y.isolation,dispatch:JO,retriedFrom:Y.retriedFrom})}catch(sO){throw jO?.cancel(),jO=void 0,sO}}),{metadata:bO}=c;if(Q0=c.taskWorktree,t=x1(bO,Q0),!jO)throw new LO;let DO=a(WO(t));if(r!==DO)jO.cancel(),jO=L.reserve(DO),r=DO;HO=jO.commit(t),jO=void 0,r=void 0;let k=WO(t);P.publish(k,"task.status",{taskStatus:bO.taskStatus,updatedAt:bO.lastMessageTime});let pO=a$(Y.prompt,Y.attachments);UO=await OO(t);let aO=UO.value,$O=K?await aO.prepareInputTurn(pO,{outputSchema:K}):await aO.prepareInputTurn(pO);if(!$O.accepted)throw new v(`Task prompt was not accepted: ${$O.reason}`);if(!HO)throw new LO;let XO=G1(t,pO,Y.permissionMode,{preparedInputTurn:$O,runtimeLease:UO,projectionLease:HO,outputSchema:K});return HO=void 0,UO=void 0,await XO.taskAdmissionUpdate,{session:k0(t),runId:XO.id,messageId:$O.messageId,status:XO.status==="queued"?"queued":"running",queuePosition:t.taskQueuePosition,queueDepth:t.taskQueueDepth,maxConcurrentTasks:t.taskConcurrencyLimit}}catch(c){if(jO?.cancel(),jO=void 0,r=void 0,HO?.release(),HO=void 0,UO?.release(),UO=void 0,c instanceof Z0&&!t)throw new rO("Session projection capacity is full",{resource:c.resource,limit:c.limit,retryable:c.retryable});if((c instanceof b4||c instanceof a0||c instanceof Z0)&&t){if(Q0)await K0.exit({sessionId:t.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await u0(t).catch(()=>{return}),await g.deleteSession(t.id,t.projectPath).catch(()=>{return}),new rO(c instanceof Z0?"Session projection capacity is full":c instanceof a0?"Session runtime capacity is full":"Task admission capacity is full",{resource:c.resource,limit:c.limit,...c instanceof Z0?{retryable:c.retryable}:{}})}if(t){let bO=await g.findSessionMetadata(t.id,t.projectPath).catch(()=>{return});if(!bO||bO.taskStatus==="queued"){let DO=h0(c),k=await g.updateSessionMetadata(t.id,t.projectPath,{taskStatus:"failed",taskStatusReason:DO.message,taskFailure:DO,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});t.taskStatus=k?.taskStatus??"failed",t.taskStatusReason=k?.taskStatusReason??DO.message,t.taskFailure=k?.taskFailure??DO,t.taskCompletedAt=k?.taskCompletedAt}else t.taskStatus=bO.taskStatus,t.taskStatusReason=bO.taskStatusReason,t.taskFailure=bO.taskFailure,t.taskCompletedAt=bO.taskCompletedAt}throw c}},J$=(Y)=>S(()=>j5(Y)),b5=async(Y,K)=>{let z=await hO(Y,K),W=await g.findSessionMetadata(z.sessionId,z.projectPath);if(!W)throw new i("Session",z.sessionId);if(!["failed","interrupted","cancelled"].includes(W.taskStatus))throw new v(`Task cannot be retried while status is ${W.taskStatus}`);let _=await g.findSessionTaskDispatch(z.sessionId,z.projectPath);if(!_)throw new v("Task retry payload is unavailable");return J$({prompt:_.prompt,title:W.title??_.title,taskPriority:W.taskPriority??_.taskPriority,taskKind:W.taskKind??_.taskKind,taskDueAt:W.taskDueAt,sourceProjectPath:_.sourceProjectPath,isolation:_.isolation,permissionMode:_.permissionMode,modelId:_.modelId,reasoningEffort:_.reasoningEffort,serviceTier:_.serviceTier,responseVerbosity:_.responseVerbosity,communicationStyle:_.communicationStyle,attachments:_.attachments,outputSchema:_.outputSchema,retriedFrom:z})},T5=(Y,K)=>S(()=>b5(Y,K)),I5=(Y,K,z)=>S(async()=>{let W=await hO(Y,z);if(!await g.findSessionMetadata(W.sessionId,W.projectPath))throw new i("Session",W.sessionId);let x=await g.updateSessionMetadata(W.sessionId,W.projectPath,K),B=X0(W);if(B)w0(B,x);return P.publish(W,"session.updated",{...x.title?{title:x.title}:{},...x.taskPriority?{taskPriority:x.taskPriority}:{},...x.taskKind?{taskKind:x.taskKind}:{},taskDueAt:x.taskDueAt??null}),B?k0(B):{...x,isActive:!1}}),R5=async(Y,K)=>{return lO(Y,K,async(z)=>{if(!z.taskWorktree)throw new F("Session does not have a task worktree");try{await K0.restoreSession(z.taskWorktree);let W=await K0.getDiffArtifact(z.id);if(!W)throw new v("Task diff artifact is unavailable");return{sessionId:z.id,projectPath:z.projectPath,...W}}catch(W){if(W instanceof v)throw W;throw l.error("[SessionRoutes] Failed to load task diff artifact:",W),new v("Task diff artifact is unavailable")}})},q5=async(Y,K,z)=>{let W=await hO(Y,z);return $0(W,async()=>{return A5(W,async(_)=>{if(["queued","running"].includes(_.taskStatus))throw new v(`Task artifacts cannot be delivered while status is ${_.taskStatus}`);if(_.taskDelivery?.status==="applied")throw new v("Task changes have already been applied");if(_.taskDelivery?.status==="discarded")throw new v("Task changes have already been discarded");if(!_.taskWorktree)throw new v("Task worktree is unavailable");let x=async(B,A=!1)=>{let I=await g.updateSessionMetadata(_.id,_.projectPath,{taskDelivery:B,...A?{taskWorktree:null}:{}});if(w0(_,I),A)_.taskWorktree=void 0;return P.publish(W,"task.delivery",{taskDelivery:B,...A?{taskWorktreeRemoved:!0}:{},updatedAt:I.lastMessageTime}),k0(_)};try{if(K==="discard"){try{await K0.restoreSession(_.taskWorktree)}catch(I){return l.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${_.id}:`,I),x({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:_.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let A=await K0.exit({sessionId:_.id,action:"remove",discardChanges:!0});return x({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:A.discardedFiles??0,message:"Task worktree removed"},!0)}try{await K0.restoreSession(_.taskWorktree)}catch(A){throw l.warn(`[SessionRoutes] Task worktree is unavailable for ${_.id}:`,A),new A4("artifact_unavailable","Task worktree is unavailable")}let B=await K0.apply(_.id);return x({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:B.sourceCommit,changedFiles:B.changedFiles,message:"Task changes applied to the source workspace"})}catch(B){if(B instanceof A4)throw await x({status:"conflicted",updatedAt:new Date().toISOString(),message:B.message}),new v(B.message);throw B}})})},E5=(Y,K,z)=>S(()=>q5(Y,K,z)),Y$=async(Y,K)=>{let z=WO(Y),W=a(z),_=D.get(W);if(!K&&_?.terminal)return;let x=mO(Y.currentRunId);if(kO(x)){if(K)d(WO(Y),K.generation);return}let B=Y.taskIsolation&&Y.taskStatus!=="queued"&&Y.taskStatus!=="running",A=B?await H0.hasRecoverableTurn(Y.projectPath,Y.id):!1;if(B&&!A){if(K)d(WO(Y),K.generation);return}let I=await H0.hasPendingInbox(Y.projectPath,Y.id),M=!I&&await H0.hasActiveGoal(Y.projectPath,Y.id);if(!I&&!M&&!A)A=await H0.hasRecoverableTurn(Y.projectPath,Y.id);if(!I&&!M&&!A){d(WO(Y));return}if(K&&!I){d(WO(Y),K.generation);return}let C=await OO(Y),R=!1,f,p;try{let BO=C.value,AO=mO(Y.currentRunId);if(kO(AO)){if(K)d(WO(Y),K.generation);return}if(I&&BO.getPendingSteeringCount()===0)await BO.reloadPendingInbox();let o=BO.getPendingSteeringCount()>0,JO=o?null:await BO.getGoal(),Q0=JO?.status==="active"||JO?.status==="verifying",t=BO.getTurnRecoveryAssessment();if(t.state!=="none"&&(t.state==="requires_attention"||!o&&!Q0))P.publish({sessionId:Y.id,projectPath:Y.projectPath},"turn.recovery",{assessment:t});if(t.state==="requires_attention"||B||!o&&!Q0||BO.hasTurnOwner()){if(K||!o)d(WO(Y),K?.generation);return}let UO=K;if(o&&!Y.taskIsolation&&!UO){let HO=await Q$(z);try{UO=NO(Y,HO);let jO=D.get(W);if(UO&&jO?.generation===UO.generation&&jO.projectionLease===HO)p=UO,HO=void 0}finally{HO?.release()}}if(o&&!Y.taskIsolation&&!UO)return;if(K&&!n(Y,K))return;f=K?(()=>{let HO=_?.projectionLease;if(!HO)throw new LO;return C0(HO)})():await Q$(WO(Y)),G1(Y,"",Y.permissionMode??"default",{pendingInputOnly:o,goalContinuationOnly:Q0,runtimeLease:C,projectionLease:f,pendingResume:o?UO:void 0}),f=void 0,p=void 0,R=!0}finally{if(f?.release(),p)d(z,p.generation);if(!R)C.release()}};u=async(Y,K)=>{let z;try{z=q.enter()}catch{return}try{let W=mO(Y.currentRunId);if(kO(W)){if(K)d(WO(Y),K.generation);return}if(Y.taskIsolation){await Y$(Y);return}await Y$(Y,K)}finally{z.release()}};let J4={accepting:!0,resolveSessionRef:Z4,getProjectionSnapshot:X0,snapshotAll:m1,acquireOrHydrateSession:M0,invalidateAll:$$,resumeRecoveredInteraction:u};_0=J4;let C5=async()=>{let Y={scheduled:0,failed:0,deferred:0};if(!q.stats().accepting)return Y;let K=(await g.listSessions({taskStatus:"queued"})).filter((z)=>z.taskIsolation!==void 0).sort((z,W)=>z.firstMessageTime.localeCompare(W.firstMessageTime)||z.projectPath.localeCompare(W.projectPath)||z.sessionId.localeCompare(W.sessionId));for(let[z,W]of K.entries()){let _={sessionId:W.sessionId,projectPath:W.projectPath};try{if(!await H0.hasPendingInbox(W.projectPath,W.sessionId)){let A=h0("Queued task input is missing");await g.updateSessionMetadata(W.sessionId,W.projectPath,{taskStatus:"failed",taskStatusReason:A.message,taskFailure:A,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Y.failed++;continue}let x=await M0(_),B=x.value;if(x.release(),await u(B),B.currentRunId)Y.scheduled++}catch(x){if(x instanceof b4||x instanceof a0){Y.deferred+=K.length-z;break}l.warn(`[SessionRoutes] Failed to recover queued task ${W.sessionId}:`,x),Y.deferred++}}return Y};return O.route("/",c$({withAdmission:S,resolveSessionRef:async(Y,K)=>{try{let z=await L5(Y,K);return(await M0(z)).release(),z}catch(z){if(z instanceof Z0)throw new rO("Session projection capacity is full",{resource:z.resource,limit:z.limit,retryable:z.retryable});throw z}},getRuntime:(Y)=>Q.get(Y),captureAgentScreenshot:async(Y,K)=>{return M5(Y,(z)=>iO(z,(W)=>W.captureBrowserScreenshot(K)))},resetRuntime:(Y)=>Q.reset(Y)})),O.get("/",async(Y)=>{try{let K=await g.listSessions(),z=new Set(K.filter((M)=>M.relationType==="subagent").map((M)=>a({sessionId:M.sessionId,projectPath:M.projectPath}))),W=m1().filter((M)=>!z.has(a(WO(M)))&&M.relationType!=="subagent").map((M)=>k0(M)),_=new Set(W.map((M)=>a({sessionId:M.sessionId,projectPath:M.projectPath}))),x=K.filter((M)=>{if(M.relationType==="subagent")return!1;return!_.has(a({sessionId:M.sessionId,projectPath:M.projectPath}))}),B=new Set(_),A=x.filter((M)=>{let C=a({sessionId:M.sessionId,projectPath:M.projectPath});if(B.has(C))return!1;return B.add(C),!0}),I=[...W,...A.map((M)=>({...M,isActive:!1}))];return Y.json(I)}catch(K){throw l.error("[SessionRoutes] Failed to list sessions:",K),new VO("Failed to list sessions")}}),O.get("/catalog",async(Y)=>{try{let K=Y.req.query("limit"),z=K===void 0?void 0:Number(K),W=Y.req.query("cursor"),_=Y.req.query("projectPath"),x=Y.req.query("archived");if(x!==void 0&&x!=="true"&&x!=="false")throw new F("archived must be true or false");let B=x==="true",A=await g.listSessionPage({..._?{cwd:T0(_)}:{},...W?{cursor:W}:{},...z===void 0?{}:{limit:z},includeSubagents:!1,archived:B}),I=new Map((B?[]:m1()).filter((M)=>M.relationType!=="subagent").map((M)=>[a(WO(M)),k0(M)]));return Y.json({sessions:A.sessions.map((M)=>I.get(a({sessionId:M.sessionId,projectPath:M.projectPath}))??M),...A.nextCursor?{nextCursor:A.nextCursor}:{}})}catch(K){if(K instanceof F)throw K;if(K instanceof Error&&(K.message.startsWith("Invalid session cursor")||K.message.startsWith("Session cursor scope")||K.message.startsWith("Session catalog")))throw new F(K.message);throw l.error("[SessionRoutes] Failed to list session catalog:",K),new VO("Failed to list session catalog")}}),O.post("/",async(Y)=>{try{let K=await Y.req.json(),z=y(N9,K);if(!z.success)throw new F("Invalid request body");let{title:W,projectPath:_}=z.data,x=c1("web",12),B=T0(_||Y.get("directory")||GO(),_?"projectPath":"directory"),A=dO({sessionId:x,projectPath:B}),I=await H.runExclusive(async()=>{let C=L.reserve(a(A));try{let R=await g.createSessionMetadata(x,B,{title:W,taskStatus:"completed"}),f=x1(R);return C.commit(f)}catch(R){throw C.cancel(),R}}),M=I.value;return I.release(),P.publish(A,"session.created",{}),Y.json({...k0(M),status:void 0,agentType:void 0,model:void 0})}catch(K){if(l.error("[SessionRoutes] Failed to create session:",K),K instanceof F||K instanceof _O||K instanceof Z0)throw K;throw new VO("Failed to create session")}}),O.get("/:sessionId/export",async(Y)=>{let K=Y.req.param("sessionId");try{let z=Y.req.query("includeReasoning");if(z!==void 0&&z!=="true"&&z!=="false")throw new F("includeReasoning must be true or false");let W=await hO(K,Y.req.query("projectPath")),_=await g.exportSessionMarkdown(W.sessionId,W.projectPath,{includeReasoning:z==="true"});return Y.body(_.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${_.filename}"`,"Content-Length":String(Buffer.byteLength(_.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":_.contentSha256,"X-Blade-Export-Activities":String(_.activityCount),"X-Blade-Export-Messages":String(_.messageCount),"X-Blade-Export-Redactions":String(_.redactionCount)})}catch(z){if(z instanceof F||z instanceof i||z instanceof vO)throw z;if(z instanceof Error&&z.message==="No conversation content to export")throw new v(z.message);throw l.error("[SessionRoutes] Failed to export session:",z),new VO("Failed to export session")}}),O.post("/:sessionId/fork",async(Y)=>{let K=Y.req.param("sessionId");try{M1(K);let z=await Y.req.json(),W=y(A9,z);if(!W.success)throw new F("Invalid request body");let _=T0(W.data.projectPath),x=c1("fork"),B,A=await H.runExclusive(async()=>{let C=await g.findSessionMetadata(K,_);if(!C)throw new i("Session",K);let R;try{R=L.reserve(a({sessionId:x,projectPath:C.projectPath}))}catch(f){if(!(f instanceof Z0))throw f}try{let f=await g.forkSession(K,{newSessionId:x,sourceProjectPath:C.projectPath,targetProjectPath:C.projectPath});if(R){let p=x1(f.metadata);B=R.commit(p)}return f}catch(f){throw R?.cancel(),f}}),I=x1(A.metadata),M=WO(I);return B?.release(),P.publish(M,"task.status",{taskStatus:A.metadata.taskStatus,...A.metadata.taskCompletedAt?{taskCompletedAt:A.metadata.taskCompletedAt}:{},updatedAt:A.metadata.lastMessageTime}),Y.json({session:A.metadata,messages:H4(A.messages)},201)}catch(z){if(z instanceof F||z instanceof i||z instanceof v)throw z;if(z instanceof N2)throw new v("Session has no durable creation record");throw l.error("[SessionRoutes] Failed to fork session:",z),new VO("Failed to fork session")}}),O.get("/:sessionId",async(Y)=>{let K=Y.req.param("sessionId");try{let z=await hO(K,Y.req.query("projectPath")),W=X0(z);if(W)return Y.json(k0(W));let _=await g.findSessionMetadata(z.sessionId,z.projectPath);if(!_)throw new i("Session",K);return Y.json(_)}catch(z){if(z instanceof F||z instanceof i||z instanceof vO)throw z;throw l.error("[SessionRoutes] Failed to get session:",z),new VO("Failed to get session")}}),O.patch("/:sessionId",async(Y)=>{let K=Y.req.param("sessionId");try{let z=await Y.req.json(),W=y(M9,z);if(!W.success)throw new F("Invalid request body");if(W.data.title===void 0)throw new F("title is required");let _=await hO(K,W.data.projectPath),x=await g.updateSessionMetadata(_.sessionId,_.projectPath,{title:W.data.title}),B=L.acquire(a(_));try{let A=B?.value;if(A)A.title=x.title??A.title,A.updatedAt=new Date(x.lastMessageTime)}finally{B?.release()}if(x.title)P.publish(_,"session.updated",{title:x.title});return Y.json({success:!0,title:x.title})}catch(z){if(l.error("[SessionRoutes] Failed to update session:",z),z instanceof F||z instanceof i||z instanceof vO)throw z;throw new VO("Failed to update session")}}),O.get("/:sessionId/rewind",async(Y)=>{return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),(K)=>iO(K,async(z)=>Y.json({checkpoints:await z.listRewindCheckpoints()})))}),O.post("/:sessionId/rewind",async(Y)=>{let K=y(S2,await Y.req.json());if(!K.success)throw new F("Invalid rewind request");return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,_)=>YO(W,async()=>{let x=mO(z.currentRunId);if(kO(x))throw new v("Cannot rewind while a run is active");return iO(z,async(B)=>{let A;try{A=await B.rewindSession(K.data)}catch(M){if(M instanceof Error&&M.message.startsWith("Cannot rewind while"))throw new v(M.message);throw M}await N0(z);let I=H4(A.messages);return P.publish(W,"session.rewound",{targetMessageId:A.checkpoint.messageId,mode:A.mode,removedTurns:A.removedTurns,restoredFiles:A.restoredFiles,messages:I}),Y.json({...A,messages:I})})}))}),O.get("/:sessionId/review",async(Y)=>{let K=Y.req.param("sessionId"),z=await hO(K,Y.req.query("projectPath")),W=await m0.list(z.projectPath,z.sessionId);return Y.json({reviews:W.map((_)=>({..._,content:_.completion?w2(_.start,_.completion):void 0}))})}),O.post("/:sessionId/review",async(Y)=>{let K=Y.req.param("sessionId"),z=y(h2,await Y.req.json());if(!z.success)throw new F("Invalid code review request");let W=await h1(K,z.data.projectPath),_=W.value,x=WO(_),B=a(x);try{return await YO(x,async()=>{if(kO(mO(_.currentRunId)))throw new v("Cannot start a review during an active turn");if(J0.has(B))throw new v("Session already has an active review");return iO(_,async(A)=>{if(await m0.recoverInterrupted(x.projectPath,x.sessionId,A),z.data.modelId&&!A.getModelById(z.data.modelId))throw new F(`Model not found: ${z.data.modelId}`);if(z.data.modelId&&A.getCurrentModelId()!==z.data.modelId)await A.refresh({modelId:z.data.modelId});if(z.data.modelId&&_.selectedModelId!==z.data.modelId){let f=await g.updateSessionMetadata(_.id,_.projectPath,{selectedModelId:z.data.modelId});w0(_,f)}let I=new AbortController,M,C;try{M=C0(W),C=await m0.start({sessionId:x.sessionId,projectPath:x.projectPath,runtime:A,request:{kind:z.data.kind,...z.data.ref?{ref:z.data.ref}:{},...z.data.instructions?{instructions:z.data.instructions}:{}},signal:I.signal,onEvent:(f)=>{if(f.kind==="tool_start")P.publish(x,"review.tool.started",{reviewId:C?.reviewId,toolCallId:f.toolCall.id,toolName:f.toolCall.function.name});else if(f.kind==="tool_progress")P.publish(x,"review.tool.progress",{reviewId:C?.reviewId,toolCallId:f.toolCall.id,message:f.update.message.slice(0,1000)});else if(f.kind==="tool_result")P.publish(x,"review.tool.completed",{reviewId:C?.reviewId,toolCallId:f.toolCall.id,success:f.result.success})}})}catch(f){if(M?.release(),f instanceof Error&&(f.message.includes("active review")||f.message.includes("interrupted review")||f.message.includes("active turn")))throw new v(f.message);if(f instanceof Error&&(f.message.includes("review")||f.message.includes("Git")||f.message.includes("changes")||f.message.includes("ref")))throw new F(f.message);throw f}if(!C)throw new VO("Code review failed to start");await N0(_),P.publish(x,"review.started",{reviewId:C.reviewId,kind:z.data.kind}),P.publish(x,"task.status",{taskStatus:_.taskStatus,..._.taskStatusReason?{taskStatusReason:_.taskStatusReason}:{},..._.taskStartedAt?{taskStartedAt:_.taskStartedAt}:{},..._.taskPromptSummary?{taskPromptSummary:_.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let R=C.completion.then(async(f)=>{await N0(_),P.publish(x,"task.status",{taskStatus:_.taskStatus,..._.taskStatusReason?{taskStatusReason:_.taskStatusReason}:{},..._.taskFailure?{taskFailure:_.taskFailure}:{},..._.taskStartedAt?{taskStartedAt:_.taskStartedAt}:{},..._.taskCompletedAt?{taskCompletedAt:_.taskCompletedAt}:{},..._.taskPromptSummary?{taskPromptSummary:_.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),P.publish(x,"review.completed",{reviewId:C.reviewId,status:f.status,findings:f.findings.length})}).catch((f)=>{l.error(`[SessionRoutes] Code review ${C.reviewId} failed:`,f)}).finally(()=>{if(J0.get(B)?.reviewId===C.reviewId)J0.delete(B);M?.release()});return J0.set(B,{reviewId:C.reviewId,controller:I,completion:R,projectionLease:M}),Y.json({reviewId:C.reviewId,status:"running"},202)})})}finally{W.release()}}),O.get("/:sessionId/subagents",async(Y)=>{return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),(K)=>iO(K,(z)=>Y.json({subagents:z.listSubagents().map(i1)})))}),O.post("/:sessionId/subagents/:agentId/resume",async(Y)=>{M1(Y.req.param("agentId"));let K=f2.safeParse(await Y.req.json());if(!K.success)throw new F("Invalid subagent resume request");return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,_)=>YO(W,async()=>{let x=mO(z.currentRunId);if(kO(x))throw new v("Cannot resume a subagent while a parent run is active");return iO(z,async(B)=>{let A=!1,I,M=(R)=>{P.publish(W,"subagent.complete",{subagentSessionId:R.id,success:R.status==="completed",status:R.status,summary:R.result?.message?.slice(0,500),type:R.subagentType,verificationVerdict:R.result?.verificationVerdict,resumedFrom:R.resumedFrom,rootAgentId:R.rootAgentId,resumeDepth:R.resumeDepth})},C;try{C=B.resumeSubagent({agentId:Y.req.param("agentId"),prompt:K.data.prompt,onEvent:(R,f)=>{S9(W,f,R)},onCompleted:(R)=>{if(A)M(R);else I=R}})}catch(R){if(R instanceof Error&&(R.message.startsWith("Cannot resume")||R.message.startsWith("Subagent cannot")))throw new v(R.message);if(R instanceof Error&&R.message.startsWith("Subagent not found"))throw new i(R.message);throw R}if(P.publish(W,"subagent.start",{subagentSessionId:C.session.id,type:C.session.subagentType,description:C.session.description,resumedFrom:C.source.id,rootAgentId:C.session.rootAgentId,resumeDepth:C.session.resumeDepth}),A=!0,I)M(I);return Y.json({source:i1(C.source),session:i1(C.session)})})}))}),O.get("/:sessionId/goal",async(Y)=>{return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(K)=>Y.json({goal:await new D2(K.projectPath,K.id).get()}))}),O.put("/:sessionId/goal",async(Y)=>{let K=y(j9,await Y.req.json());if(!K.success)throw new F("Invalid goal request");return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,_)=>YO(W,async()=>{let x=mO(z.currentRunId);if(kO(x))return Y.json({status:"rejected",reason:"run_active"},409);let A=K.data.permissionMode??z.permissionMode??"default";if(z.permissionMode!==A)await Z$(z,A);let I=await OO(z),M=!1,C;try{let R=await I.value.createGoal(K.data);P.publish(W,"goal.updated",{goal:R}),C=C0(_);let f=G1(z,"",A,{goalContinuationOnly:!0,runtimeLease:I,projectionLease:C});return M=!0,C=void 0,await f.taskAdmissionUpdate,Y.json({status:f.status==="queued"?"queued":"running",runId:f.id,goal:R,queuePosition:z.taskQueuePosition,queueDepth:z.taskQueueDepth,maxConcurrentTasks:z.taskConcurrencyLimit},202)}finally{if(C?.release(),!M)I.release()}}))}),O.patch("/:sessionId/goal",async(Y)=>{let K=y(b9,await Y.req.json());if(!K.success)throw new F("Invalid goal update");return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,_)=>YO(W,async()=>{let x=await OO(z),B=!1,A;try{let I=x.value,M;if(K.data.action==="pause")M=await I.pauseGoal();else if(K.data.action==="edit")M=await I.editGoal(K.data.objective);else M=await I.resumeGoal();if(P.publish(W,"goal.updated",{goal:M}),M.status==="active"&&!kO(mO(z.currentRunId))){A=C0(_);let C=G1(z,"","default",{goalContinuationOnly:!0,runtimeLease:x,projectionLease:A});return B=!0,A=void 0,await C.taskAdmissionUpdate,Y.json({status:C.status==="queued"?"queued":"running",runId:C.id,goal:M,queuePosition:z.taskQueuePosition,queueDepth:z.taskQueueDepth,maxConcurrentTasks:z.taskConcurrencyLimit},202)}return Y.json({status:M.status,goal:M})}finally{if(A?.release(),!B)x.release()}}))}),O.delete("/:sessionId/goal",async(Y)=>{return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),(K,z)=>iO(K,async(W)=>{let _=await W.clearGoal();if(_)P.publish(z,"goal.cleared",{});return Y.json({cleared:_})}))}),O.post("/:sessionId/archive",async(Y)=>{let K=Y.req.param("sessionId");try{let z=await hO(K,Y.req.query("projectPath")),W=await g.listSessionArchiveMembers(z.sessionId,z.projectPath);for(let x of W){let B=dO({sessionId:x.sessionId,projectPath:x.projectPath}),A=X0(B);if(kO(mO(A?.currentRunId)))throw new v(`Stop session ${x.sessionId} before archiving this session tree`)}for(let x of W){let B=dO({sessionId:x.sessionId,projectPath:x.projectPath}),A=X0(B);if(A)await u0(A)}let _=await g.archiveSession(z.sessionId,z.projectPath);for(let x of W){let B=dO({sessionId:x.sessionId,projectPath:x.projectPath}),A=a(B);$4(B,"archive"),await Q4(B,"archive").catch(()=>{return}),Z.delete(A),P.publish(B,"session.archived",{archiveRootId:z.sessionId,archivedAt:_.archivedAt})}if($.size===0)await uO.getInstance().disconnectAll();return Y.json({session:_,archivedSessionIds:W.map((x)=>x.sessionId)})}catch(z){if(z instanceof F||z instanceof i||z instanceof vO||z instanceof v)throw z;if(z instanceof L4)throw new v(z.message);throw l.error("[SessionRoutes] Failed to archive session:",z),new VO("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Y)=>{let K=Y.req.param("sessionId");try{let z=await hO(K,Y.req.query("projectPath")),W=await g.listSessionArchiveMembers(z.sessionId,z.projectPath),_=await g.unarchiveSession(z.sessionId,z.projectPath),x=W.filter((B)=>B.sessionId===z.sessionId||B.archivedBySessionId===z.sessionId).map((B)=>B.sessionId);for(let B of x)P.publish({sessionId:B,projectPath:z.projectPath},"session.unarchived",{archiveRootId:z.sessionId});return Y.json({session:_,restoredSessionIds:x})}catch(z){if(z instanceof F||z instanceof i||z instanceof vO)throw z;if(z instanceof L4)throw new v(z.message);throw l.error("[SessionRoutes] Failed to unarchive session:",z),new VO("Failed to unarchive session")}}),O.delete("/:sessionId",async(Y)=>{let K=Y.req.param("sessionId"),z=Y.req.query("projectPath");try{let W=await hO(K,z);d(W);let _=a(W),x=L.acquire(_),B=x?.value,A=B?.currentRunId,I=$.get(_),M=B?.taskWorktree??await g.findSessionTaskWorktree(W.sessionId,W.projectPath);x?.release();let C;if(A){let p=mO(A);if(p)b1(p),await p.completion,C=p.id}let R=J0.get(_);if(R)R.controller.abort("session-delete"),await R.completion;if(I)await I.clearGoal().catch((p)=>{l.warn("[SessionRoutes] Failed to clear session goal:",p)});if(await Q.dispose(W),await g.deleteSession(W.sessionId,W.projectPath),$4(W,"delete"),C)R9(C);await Q4(W,"delete").catch(()=>{return}),Z.delete(_),P.publish(W,"session.deleted",{});let f=$.get(_);if(f){if(!await T.remove(_,f))throw new v("Session Runtime is still active and cannot be deleted")}if(M)try{await K0.restoreSession(M),await K0.exit({sessionId:W.sessionId,action:"remove",discardChanges:!0})}catch(p){l.warn(`[SessionRoutes] Failed to remove deleted task worktree ${W.sessionId}:`,p)}return Y.json({success:!0})}catch(W){if(l.error("[SessionRoutes] Failed to delete session:",W),W instanceof F||W instanceof i||W instanceof vO)throw W;throw new VO("Failed to delete session")}}),O.get("/:sessionId/message",async(Y)=>{let K=Y.req.param("sessionId");try{let z=await hO(K,Y.req.query("projectPath")),W=await g.loadSession(z.sessionId,z.projectPath);return Y.json(H4(W))}catch(z){if(l.error("[SessionRoutes] Failed to get messages:",z),z instanceof F||z instanceof i||z instanceof vO)throw z;throw new VO("Failed to get messages")}}),O.get("/:sessionId/follow-ups",async(Y)=>{return lO(Y.req.param("sessionId"),Y.req.query("projectPath"),(K,z)=>YO(z,async()=>Y.json(await z1(K))))}),O.post("/:sessionId/follow-ups/mutate",async(Y)=>{let K=D9.safeParse(await Y.req.json());if(!K.success)throw new F("Invalid follow-up queue mutation");return lO(Y.req.param("sessionId"),K.data.projectPath??Y.req.query("projectPath"),(z,W)=>YO(W,async()=>{try{return await iO(z,async(_)=>{let x={expectedVersion:K.data.expectedVersion,operation:K.data.operation},B=await _.mutateFollowUpQueue(x);if(B.snapshot.version!==x.expectedVersion)P.publish(W,"follow_up.queue.changed",{queue:B.snapshot});return Y.json(B)})}catch(_){if(!L9(_))throw _;let x=_.code==="not_found"?404:_.code==="invalid_mutation"?400:_.code==="storage_unavailable"||_.code==="runtime_unavailable"?503:409;return Y.json({error:{code:_.code,message:_.message},snapshot:_.snapshot},x)}}))}),O.get("/:sessionId/events",async(Y)=>{let K=Y.req.param("sessionId"),z;try{z=b.enter(Y.req.raw.signal)}catch{throw new LO}let W=!1;try{let _=await hO(K,Y.req.query("projectPath"));try{await g.assertSessionWritable(_.sessionId,_.projectPath)}catch(R){if(R instanceof x4)throw new v(R.message);throw R}let x=await M0(_),B=x.value,A=Y.req.header("Last-Event-ID")??Y.req.query("lastEventId"),I=A?Number.parseInt(A,10):Number.NaN,M=Number.isInteger(I)?I+1:void 0,C=H9(Y,async(R)=>{let p=new Set,BO,AO,o=!1,JO,Q0,t=new Promise((k)=>{Q0=k}),UO,HO=new Set,jO=(k)=>{let pO=k;return p.add(pO),k.finally(()=>{p.delete(pO)})},r=()=>{if(BO?.(),BO=void 0,AO!==void 0)clearInterval(AO),AO=void 0},c=(k)=>{if(UO)return UO;return o=!0,UO=(async()=>{try{r(),JO?.close(k),R.close()}finally{Q0()}})(),UO},bO=()=>{c(z.signal.reason)},DO=async(k)=>{await c(k),await Promise.allSettled([...p]),z.signal.removeEventListener("abort",bO),z.release()};if(z.signal.addEventListener("abort",bO,{once:!0}),R.onAbort(()=>{c()}),z.signal.aborted){await DO(z.signal.reason);return}JO=new K1({write:async(k)=>{await R.writeSSE(k)},onFailure:(k)=>{if(n$(k,o))return;l.warn(`[SessionRoutes] SSE egress closed for ${_.sessionId}: kind=${k.kind} pendingItems=${k.pendingItems??0} pendingBytes=${k.pendingBytes??0}`),c(k)}}),BO=P.subscribe((k)=>{if(o)return;if(k.sessionId!==_.sessionId||k.projectPath!==_.projectPath)return;let pO=k.properties.requestId;if((k.type==="permission.asked"||k.type==="question.required"||k.type==="elicitation.required")&&typeof pO==="string"){if(HO.has(pO))return;HO.add(pO)}if(k.type==="subagent.completion.queued"){let $O=YO(_,()=>u(B)).catch((XO)=>{l.error(`[SessionRoutes] Failed to wake background completion for ${B.id}:`,XO)});jO($O)}if(k.type==="team.message.received"&&typeof k.properties.teamName==="string"&&typeof k.properties.messageId==="string"&&typeof k.properties.content==="string"&&M2(k.properties.metadata,{messageId:k.properties.messageId,teamName:k.properties.teamName})){let $O=k.properties.teamName,XO=k.properties.messageId,sO=k.properties.content,TO=k.properties.metadata,xO=YO(_,async()=>{let IO=await OO(B),S0=!1;try{let V0=await IO.value.enqueueSteering(sO,{allowBeforeTurn:!0,messageId:XO,origin:"team_message",metadata:TO});if(!V0.accepted)return;if(V0.queue&&!V0.duplicate)P.publish(_,"follow_up.queue.changed",{queue:V0.queue});await new L2($O,l1()).markDelivered([XO]),S0=V0.delivery==="next_turn"}finally{IO.release()}if(!S0)return;await u(B).catch((V0)=>{l.error(`[SessionRoutes] Failed to wake teammate delivery for ${B.id}:`,V0)})}).catch((IO)=>{l.error(`[SessionRoutes] Failed to deliver teammate message for ${B.id}:`,IO)});jO(xO)}if(k.type==="subagent.completion.queued"||k.type==="team.message.received")return;let aO=q9(k);if(aO)JO?.observe(aO,k.seq)});try{if(R.aborted||o)return;let k=mO(B.currentRunId),pO=await YO(_,()=>z1(B)),aO=kO(k)?await OO(B):void 0;try{let TO=aO?.value,xO=TO?.getPendingSteeringCount()??0;await JO.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:_.sessionId,projectPath:_.projectPath,timestamp:Date.now(),status:kO(k)?k.status:"idle",runId:kO(k)?k.id:void 0,queued:xO,pendingInputDelivery:xO>0?TO?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:TO?.getRecoveredSteeringCount()??0,followUpQueue:pO,providerRecovery:TO?.getProviderRecoveryProjection()??null,turnActivity:TO?.getTurnActivityProjection()??null}})})}finally{aO?.release()}if(R.aborted||o)return;if(M!==void 0){if(await x2.for(_.sessionId,_.projectPath).replay({onCommitted:async(xO)=>{if(R.aborted||o)return;let IO=d2(xO);if(!IO||IO.seq===void 0)return;await JO.writeReplay({...typeof xO.seq==="number"?{id:String(xO.seq)}:{},data:JSON.stringify({type:IO.type,...IO.seq!==void 0?{seq:IO.seq}:{},properties:{...IO.properties,sessionId:_.sessionId,projectPath:_.projectPath}})},IO.seq)}},M),R.aborted||o)return}if(JO.finishInitialization({replayed:M!==void 0}),R.aborted||o)return;if(!k&&!J0.has(a(_))){let xO=(await m0.list(_.projectPath,_.sessionId)).some((IO)=>IO.completion===void 0)?await iO(B,(IO)=>m0.recoverInterrupted(_.projectPath,_.sessionId,IO)):void 0;if(xO)await N0(B),P.publish(_,"review.completed",{reviewId:xO.reviewId,status:xO.status,findings:0,recovered:!0})}if(R.aborted||o)return;if(!k)await y0.recoverResponded(_.projectPath,_.sessionId);if(R.aborted||o)return;let $O=k?void 0:await y0.findPending(_.projectPath,_.sessionId),XO=k?.pendingPermission??($O?{permissionId:$O.request.requestId,details:y0.confirmationDetails($O),resolve:()=>{return}}:void 0);if(XO){HO.add(XO.permissionId);let TO=u2(XO,!0);JO.observe({data:JSON.stringify({type:TO.type,properties:{...TO.properties,sessionId:_.sessionId,projectPath:_.projectPath}})})}if(R.aborted||o)return;let sO=u(B).catch(async(TO)=>{if(TO instanceof A0){await N0(B).catch(()=>{return});let xO=B.taskFailure?.code==="workspace_unavailable"?B.taskFailure:A1("workspace_unavailable");B.taskStatus="failed",B.taskStatusReason=xO.message,B.taskFailure=xO,P.publish(_,"session.error",{error:xO.message,taskFailure:xO}),P.publish(_,"session.status",{status:"error"})}l.error(`[SessionRoutes] Failed to resume pending input for ${K}:`,TO)});if(jO(sO),R.aborted||o)return;AO=setInterval(()=>{if(R.aborted||o)return;JO?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await t}catch(k){if(n$(k,o))return;throw k}finally{await DO()}});return W=!0,x.release(),C}catch(_){if(!W)z.release();throw _}}),O.post("/:sessionId/message",async(Y)=>{let K=Y.req.param("sessionId"),z=await Y.req.json(),W=y(B9,z);if(!W.success)throw new F("Invalid message format");let{content:_,attachments:x,modelId:B,reasoningEffort:A,serviceTier:I,responseVerbosity:M,communicationStyle:C,permissionMode:R,projectPath:f,annotations:p,outputSchema:BO}=W.data,AO;if(BO)try{AO=D4(BO).schema}catch(DO){throw new F(DO instanceof Error?DO.message:"Invalid output schema")}let o=C;if(Buffer.byteLength(_,"utf8")>N4)throw new F(`Message text exceeds the ${N4}-byte limit`);let JO=B?.trim();if((x??[]).reduce((DO,k)=>DO+(typeof k.content==="string"?Buffer.byteLength(k.content):0),0)>a1)throw new F("Message attachments exceed the 5 MiB limit");let t=R,UO=a$(_,x),HO=p&&p.length>0?{selectedConversationAnnotations:p}:void 0,jO=await h1(K,f??Y.req.query("projectPath")),r=jO.value,c=WO(r),bO=t??r.permissionMode??"default";try{return await YO(c,async()=>{let DO=mO(r.currentRunId);if(kO(DO)){if(AO)throw new v("Wait for the active turn to finish before setting an output schema");return iO(r,async($O)=>{if(JO&&!$O.getModelById(JO))throw new F(`Model not found: ${JO}`);if(JO&&$O.getCurrentModelId()!==JO)throw new v("Wait for the active turn to finish before switching models");if(A&&$O.getReasoningConfiguration().selection!==A)throw new v("Wait for the active turn to finish before switching reasoning effort");if(I&&$O.getServiceTierConfiguration().selection!==I)throw new v("Wait for the active turn to finish before switching service tier");if(M&&$O.getResponseVerbosityConfiguration().selection!==M)throw new v("Wait for the active turn to finish before switching response verbosity");if(o&&$O.getCommunicationStyleConfiguration().selection!==o)throw new v("Wait for the active turn to finish before switching communication style");if(t&&r.permissionMode!==t)throw new v("Wait for the active turn to finish before switching permission mode");let XO=await $O.enqueueSteering(UO,{allowBeforeTurn:!0,...HO?{metadata:HO}:{}});if(!XO.accepted)return Y.json({status:"rejected",reason:XO.reason??"turn_unavailable"},409);let sO=XO.messageId??n0(12),TO=XO.queued,xO=XO.queue??await $O.getFollowUpQueueSnapshot(),IO=XO.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(P.publish(c,IO,{runId:DO.id,messageId:sO,queued:TO}),!XO.duplicate)P.publish(c,"follow_up.queue.changed",{queue:xO});if(XO.delivery==="next_turn"&&DO.status!=="running"&&DO.status!=="waiting_permission")u(r).catch((S0)=>{l.error(`[SessionRoutes] Failed to wake queued follow-up for ${K}:`,S0)});if(XO.delivery==="next_turn")DO.pendingFollowUpRequested=!0;return Y.json({runId:DO.id,messageId:sO,status:XO.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:TO,followUpQueue:xO},202)})}if(d(c),r.permissionMode!==bO)await Z$(r,bO);let k=await OO(r,{permissionMode:bO,...o&&!o.includes(":")?{communicationStyle:o}:{}}),pO=!1,aO;try{let $O=k.value;if(JO&&!$O.getModelById(JO))throw new F(`Model not found: ${JO}`);if(A)try{$O.resolveReasoningConfiguration(A,JO)}catch(EO){throw new F(EO instanceof Error?EO.message:"Invalid reasoning effort")}if(I)try{$O.resolveServiceTierConfiguration(I,JO)}catch(EO){throw new F(EO instanceof Error?EO.message:"Invalid service tier")}if(M)try{$O.resolveResponseVerbosityConfiguration(M,JO)}catch(EO){throw new F(EO instanceof Error?EO.message:"Invalid response verbosity")}let XO=o?$O.resolveCommunicationStyleConfiguration(o):void 0;if(XO?.source!==void 0&&XO.source!=="built-in"&&!XO.contentSha256)throw new F("Custom communication style has no provenance");let sO=$O.getCurrentModelId(),TO=$O.getReasoningConfiguration(),xO=$O.getServiceTierConfiguration(),IO=$O.getResponseVerbosityConfiguration(),S0=$O.getCommunicationStyleConfiguration(),V0=Boolean(JO)&&sO!==JO,X$=Boolean(A)&&TO.selection!==A,V$=Boolean(I)&&xO.selection!==I,z$=Boolean(M)&&IO.selection!==M,G$=Boolean(o)&&S0.selection!==o;if(V0||X$||V$||z$||G$)await $O.refresh({...JO?{modelId:JO}:{},...A?{reasoningEffort:A}:{},...I?{serviceTier:I}:{},...M?{responseVerbosity:M}:{},...o?{communicationStyle:o}:{}});let Y4={...JO&&r.selectedModelId!==JO?{selectedModelId:JO}:{},...A&&r.reasoningEffort!==A?{reasoningEffort:A}:{},...I&&r.serviceTier!==I?{serviceTier:I}:{},...M&&r.responseVerbosity!==M?{responseVerbosity:M}:{},...XO&&(r.communicationStyle!==o||r.communicationStyleDigest!==XO.contentSha256)?{communicationStyle:o,communicationStyleDigest:XO.source==="built-in"?null:XO.contentSha256}:{}};if(Object.keys(Y4).length>0)try{let EO=await g.updateSessionMetadata(r.id,r.projectPath,Y4);r.permissionMode=EO.permissionMode,r.selectedModelId=EO.selectedModelId,r.reasoningEffort=EO.reasoningEffort,r.serviceTier=EO.serviceTier,r.responseVerbosity=EO.responseVerbosity,r.communicationStyle=EO.communicationStyle,r.communicationStyleDigest=EO.communicationStyleDigest,r.updatedAt=new Date(EO.lastMessageTime),P.publish(c,"session.updated",Y4)}catch(EO){if(V0||X$||V$||z$||G$)await $O.refresh({...sO?{modelId:sO}:{},reasoningEffort:TO.selection,serviceTier:xO.selection,responseVerbosity:IO.selection,communicationStyle:S0.selection}).catch((S5)=>l.error("[SessionRoutes] Failed to roll back non-durable model settings:",S5));throw EO}let W1=AO||HO?await $O.prepareInputTurn(UO,{...AO?{outputSchema:AO}:{},...HO?{metadata:HO}:{}}):await $O.prepareInputTurn(UO);if(!W1.accepted)return Y.json({status:"rejected",reason:W1.reason},W1.reason==="queue_full"?429:409);aO=C0(jO);let X4=G1(r,UO,bO,{preparedInputTurn:W1,outputSchema:AO,runtimeLease:k,projectionLease:aO});return pO=!0,aO=void 0,await X4.taskAdmissionUpdate,Y.json({runId:X4.id,messageId:W1.messageId,status:X4.status==="queued"?"queued":"running",queuePosition:r.taskQueuePosition,queueDepth:r.taskQueueDepth,maxConcurrentTasks:r.taskConcurrencyLimit},202)}finally{if(aO?.release(),!pO)k.release()}})}finally{jO.release()}}),O.post("/:sessionId/side-question",async(Y)=>{let K=Y.req.param("sessionId"),z=y(m2,await Y.req.json());if(!z.success)throw new F("Invalid side conversation request");return lO(K,z.data.projectPath??Y.req.query("projectPath"),(W)=>k1(W,async(_)=>{let x=await _.askSideQuestion(z.data.question,{signal:Y.get("requestSignal")});return Y.json({...x,..._.getCurrentModelId()?{modelId:_.getCurrentModelId()}:{}})}))}),O.post("/:sessionId/shell",async(Y)=>{let K=Y.req.param("sessionId"),z=y(k2,await Y.req.json());if(!z.success)throw new F("Invalid user shell command");return lO(K,z.data.projectPath??Y.req.query("projectPath"),(W,_,x)=>{let B=a(_);return YO(_,async()=>{if(F0.has(B))throw new v("A user shell command is already running in this Session");let A=await OO(W),I=C0(x),M=A.value,C=new AbortController,R,f=new Promise((p)=>{R=p});F0.set(B,{controller:C,completion:f,projectionLease:I});try{let p=await M.executeUserShellCommand(z.data.command,{signal:C.signal});await N0(W);let BO=mO(W.currentRunId);if(p.delivery==="next_turn"&&kO(BO))BO.pendingFollowUpRequested=!0;if(p.queue)P.publish(_,"follow_up.queue.changed",{queue:p.queue});return Y.json({executionId:p.executionId,messageId:p.messageId,record:p.record,auxiliary:p.auxiliary,...p.delivery?{delivery:p.delivery}:{},...p.queued!==void 0?{queued:p.queued}:{}})}finally{F0.delete(B),R(),A.release(),I.release()}})})}),O.post("/:sessionId/abort",async(Y)=>{let K=Y.req.param("sessionId"),z=await hO(K,Y.req.query("projectPath"));d(z);let W=X0(z);if(W?.currentRunId){let B=mO(W.currentRunId);if(B)b1(B),await B.completion}let _=F0.get(a(z));if(_)_.controller.abort("user-cancel"),await _.completion;let x=J0.get(a(z));if(x)x.controller.abort("user-cancel"),await x.completion;return Y.json({success:!0})}),O.get("/:sessionId/status",async(Y)=>{let K=Y.req.param("sessionId"),z=await hO(K,Y.req.query("projectPath")),W=X0(z),_=J0.get(a(z));if(_)return Y.json({sessionId:K,projectPath:z.projectPath,reviewId:_.reviewId,status:"reviewing"});if(!W?.currentRunId)return Y.json({sessionId:K,projectPath:z.projectPath,status:"idle"});let x=mO(W.currentRunId);return Y.json({sessionId:K,projectPath:z.projectPath,runId:W.currentRunId,status:x?.status==="attention_required"?"idle":x?.status??"idle"})}),{app:O,dispatchTask:J$,retryTask:T5,updateTask:I5,getTaskDiff:R5,deliverTask:E5,recoverQueuedTasks:C5,getRuntimeResidencyStats:()=>T.getStats(),getProjectionResidencyStats:()=>L.getStats(),getCoordinationStats:()=>({messageSubmissions:w.getStats(),taskDeliveries:N.getStats()}),getSseConnectionStats:()=>b.stats(),shutdown:(Y="server-shutdown")=>{if(m)return m;q.close(Y);let K=b.shutdown(Y);J4.accepting=!1,$$("server-shutdown");let z=Promise.allSettled([...V].map((W)=>W.promise));return clearInterval(E),clearInterval(h),fO(),m=(async()=>{let W,_=async(M)=>{let C=await Promise.allSettled(M);for(let R of C)if(R.status==="rejected")W??=R.reason},x=new Set,B=()=>{for(let M of Y0.values()){if(M.completion)x.add(M.completion);if(kO(M))b1(M,Y)}for(let M of F0.values())M.controller.abort(Y),x.add(M.completion);for(let M of J0.values())M.controller.abort(Y),x.add(M.completion)},A=q.waitForIdle(),I=!1;A.then(()=>{I=!0});while(!I)B(),await Promise.race([A,new Promise((M)=>setImmediate(M))]);if(await A,B(),await _([...x]),await z,await _([...Z.values()]),B(),await _([...x]),await _([K]),await _([...Z.values()]),await _([T.disposeAll()]),$.clear(),await _([...J.values()]),await _([Q.disposeAll()]),await _([uO.getInstance().disconnectAll()]),Z.clear(),J.clear(),X.clear(),V.clear(),_0===J4)_0=void 0;if(j1===fO)j1=void 0;if(W!==void 0)throw W})(),m}}};async function f9(O,$,Q,Z,J,X={}){let{abortController:V,sessionId:w,id:N}=O,H=X.preparedInputTurn?.messageId??n0(12),T=X.pendingInputOnly===!0||X.preparedInputTurn?.mode==="pending"||X.goalContinuationOnly===!0?void 0:n0(12),L=X.runtimeLease,q=X.projectionLease,b,E,h=!1,m=!1,D,e=WO($),u=X.pendingResume?.projectedInputIds??new Set,FO=(d)=>{if(u.has(d))return;if(u.size>=A2){let n=u.values().next().value;if(n!==void 0)u.delete(n)}u.add(d)},fO=async(d)=>{let n=d.metadata?.recoveryAttention;if(!n||!b)return!1;if(X.preparedInputTurn)await b.finishTurn(X.preparedInputTurn.handle,{preserveStartupRecovery:!0,outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}}).catch(()=>{return});let NO=`Turn recovery requires attention: ${n.reason}`,qO=await b.setTaskStatus("interrupted",NO).catch(()=>{return});if(qO)w0($,qO);else $.taskStatus="interrupted",$.taskStatusReason=NO,$.taskCompletedAt=void 0;return O.status="attention_required",S("session.status",{status:"idle"}),!0},S=(d,n)=>{P.publish(e,d,n)},YO=async()=>{let d=String(V.signal.reason||"Task run cancelled");if($.taskIsolation){if(!L)L=await J($).catch(()=>{return});let n=b??L?.value;if(d==="user-cancel")await n?.discardPendingInput().catch((qO)=>{l.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,qO)});let NO=await n?.setTaskStatus("cancelled",d).catch(()=>{return});if(NO)w0($,NO);else await N0($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=d,$.taskCompletedAt??=new Date().toISOString()};try{if(X.pendingResume){let U=X.pendingResume.deadlineAt-Date.now();if(U<=0)throw V.abort(d1),new L1({taskFailure:A1("timeout"),outputStarted:!1,toolExecutionStarted:!1,toolCallsCount:0});else D=setTimeout(()=>{V.abort(d1);let OO=O.pendingPermission;if(O.pendingPermission=void 0,OO?.resolve({approved:!1,reason:T4}),OO)S("interaction.resolved",{requestId:OO.permissionId})},U),D.unref?.()}if(X.taskAdmission){if(await X.taskAdmission.ready,await O.taskAdmissionUpdate,V.signal.aborted)throw Error(String(V.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!X.pendingInputOnly&&!X.goalContinuationOnly)S("message.created",{messageId:H,role:"user",content:l$(Q),...X.preparedInputTurn?.metadata?{metadata:X.preparedInputTurn.metadata}:{}});if(S("session.status",{status:"running"}),T)S("message.created",{messageId:T,role:"assistant",content:""});L??=await J($),b=L.value;let d=b,n=Boolean(X.outputSchema??d.getPendingSteeringMessages().find((U)=>U.outputSchema)?.outputSchema);E=await E2.createWithRuntime(d,{sessionId:w,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let NO=async(U)=>{let OO=U.interactionRequestId??n0(12),iO=300000;O.status="waiting_permission";let P1=new Promise((u0)=>{let O4=setTimeout(()=>{l.warn(`[SessionRoutes] Permission ${OO} timed out after 300000ms`),S("permission.timeout",{requestId:OO}),u0({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:OO,resolve:(d0)=>{clearTimeout(O4),u0(d0)},details:U}}),V1=O.pendingPermission;if(!V1)throw Error("Permission request was not registered");let k1=u2(V1);S(k1.type,k1.properties),l.info(`[SessionRoutes] Permission request created: ${OO}, runId: ${N}`);let z1=await P1;if(l.info(`[SessionRoutes] Permission response received: ${OO}, approved: ${z1.approved}`),!V.signal.aborted)O.status="running";if(O.pendingPermission===V1)O.pendingPermission=void 0;return S("interaction.resolved",{requestId:OO}),z1},SO={messages:await g.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:w,workspaceRoot:$.projectPath,signal:V.signal,permissionMode:Z,onPermissionModeChange:async(U)=>{$.permissionMode=U,$.updatedAt=new Date,S("session.updated",{permissionMode:U})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:NO}},KO=()=>{if(!T)T=n0(12),S("message.created",{messageId:T,role:"assistant",content:""});return T},$0=async(U)=>{switch(U.kind){case"content_delta":if(U.delta.length>0)h=!0;if(n)break;S("message.delta",{messageId:KO(),delta:U.delta});break;case"structured_output":h=!0,S("structured.output",{messageId:KO(),output:U.output,schemaDigest:U.schemaDigest});break;case"thinking_delta":if(U.delta.length>0)h=!0;S("thinking.delta",{messageId:KO(),delta:U.delta});break;case"tool_start":if(m=!0,"function"in U.toolCall){if(U.toolCall.function.name===o0)break;S("tool.start",{messageId:KO(),toolName:U.toolCall.function.name,toolCallId:U.toolCall.id,arguments:U.toolCall.function.arguments,toolKind:U.toolKind})}break;case"tool_result":if(m=!0,"function"in U.toolCall){if(U.toolCall.function.name===o0)break;S("tool.result",{messageId:KO(),toolName:U.toolCall.function.name,toolCallId:U.toolCall.id,success:U.result.success,summary:U.result.metadata?.summary,output:E1(R1(q1(U.toolCall.function.name,U.result),I1)),metadata:T1(U.toolCall.function.name,U.result.metadata)})}break;case"tool_progress":if(m=!0,"function"in U.toolCall){if(U.toolCall.function.name===o0)break;S("tool.progress",{messageId:KO(),toolName:U.toolCall.function.name,toolCallId:U.toolCall.id,...U.update})}break;case"token_usage":S("token.usage",{...U.usage});break;case"turn_start":S("turn.started",{turn:U.turn,maxTurns:U.maxTurns});break;case"turn_recovery":S("turn.recovery",{assessment:U.assessment});break;case"provider_admission":S("provider.admission",{phase:U.phase,requestClass:U.requestClass,resource:U.resource,scope:U.scope,reason:U.reason,queuePosition:U.queuePosition,queueDepth:U.queueDepth,inFlight:U.inFlight,limit:U.limit,waitMs:U.waitMs,maxWaitMs:U.maxWaitMs,recoveryRemainingMs:U.recoveryRemainingMs});break;case"provider_circuit":S("provider.circuit",{phase:U.phase,reason:U.reason,statusCode:U.statusCode,retryAfterMs:U.retryAfterMs,nextProbeAt:U.nextProbeAt,openDurationMs:U.openDurationMs,sampleCount:U.sampleCount,failureCount:U.failureCount,recoveryRemainingMs:U.recoveryRemainingMs});break;case"provider_retry":S("provider.retry",{phase:U.phase,attempt:U.attempt,maxRetries:U.maxRetries,reason:U.reason,statusCode:U.statusCode,delayMs:U.delayMs,nextRetryAt:U.nextRetryAt,mode:U.mode,recoveryBudgetMs:U.recoveryBudgetMs,recoveryElapsedMs:U.recoveryElapsedMs,recoveryRemainingMs:U.recoveryRemainingMs,exhaustedBy:U.exhaustedBy});break;case"provider_stall":S("provider.stall",{phase:U.phase,stallCount:U.stallCount,durationMs:U.durationMs,warningAfterMs:U.warningAfterMs,timeoutMs:U.timeoutMs,outputStarted:U.outputStarted});break;case"provider_recovery":break;case"turn_activity":break;case"action_stationarity":S("action.stationarity",{phase:U.phase,toolName:U.toolName,runLength:U.runLength,nudgeThreshold:U.nudgeThreshold,haltThreshold:U.haltThreshold,progressAware:U.progressAware});break;case"mcp_catalog_changed":S("mcp.catalog.changed",{messageId:KO(),revision:U.revision,serverName:U.serverName,added:U.added,removed:U.removed,updated:U.updated});break;case"mcp_content_changed":S("mcp.content.changed",{messageId:KO(),revision:U.revision,serverName:U.serverName,contentKind:U.contentKind,added:U.added,removed:U.removed,updated:U.updated});break;case"mcp_resource_updated":S("mcp.resource.updated",{messageId:KO(),revision:U.revision,serverName:U.serverName,uri:U.uri});break;case"mcp_connection_changed":S("mcp.connection.changed",{messageId:KO(),revision:U.revision,serverName:U.serverName,phase:U.phase,reason:U.reason,attempt:U.attempt,maxAttempts:U.maxAttempts,nextRetryAt:U.nextRetryAt,error:U.error});break;case"mcp_log":S("mcp.log",{messageId:KO(),revision:U.revision,serverName:U.serverName,level:U.level,logger:U.logger,message:U.message,projectedBytes:U.projectedBytes,dataSha256:U.dataSha256,truncated:U.truncated,detailsOmitted:U.detailsOmitted,timestamp:U.timestamp,synthetic:U.synthetic});break;case"mcp_instructions_changed":S("mcp.instructions.changed",{messageId:KO(),revision:U.revision,serverName:U.serverName,action:U.action,reason:U.reason,text:U.text,sourceBytes:U.sourceBytes,projectedBytes:U.projectedBytes,sha256:U.sha256,truncated:U.truncated,detailsOmitted:U.detailsOmitted});break;case"mcp_task_changed":S("mcp.task.changed",{messageId:KO(),revision:U.revision,taskId:U.taskId,serverName:U.serverName,toolName:U.toolName,status:U.status,statusMessage:U.statusMessage,createdAt:U.createdAt,updatedAt:U.updatedAt,completedAt:U.completedAt,hasResult:U.hasResult,error:U.error});break;case"project_rules_loaded":S("project.rules.loaded",{messageId:KO(),files:U.files,triggerPaths:U.triggerPaths,blockedWrite:U.blockedWrite});break;case"steering_applied":for(let OO of U.messages){if((OO.origin??"user")!=="user")continue;if(OO.persisted)continue;if(u.has(OO.id))continue;S("message.created",{messageId:OO.id,role:"user",content:l$(OO.content),...OO.metadata?{metadata:OO.metadata}:{},...OO.recovered?{recovered:!0}:{}}),FO(OO.id)}S("steering.applied",{runId:N,messageIds:U.messageIds,count:U.count,recovered:U.recovered,delivery:U.delivery,queued:d.getPendingSteeringCount()}),S("follow_up.queue.changed",{queue:U.queue});break;case"follow_up_started":{if(T)S("message.complete",{messageId:T}),T=void 0;S("follow_up.started",{runId:N,queued:U.queued,recovered:U.recovered}),S("follow_up.queue.changed",{queue:U.queue}),KO();break}case"follow_up_queue_changed":S("follow_up.queue.changed",{queue:U.queue});break;case"goal_updated":S("goal.updated",{goal:U.goal});break;case"goal_continuation_started":S("goal.continuation.started",{goal:U.goal,continuation:U.continuation,...U.prematureStopPattern?{prematureStopPattern:U.prematureStopPattern}:{},...U.prematureStopCount!==void 0?{prematureStopCount:U.prematureStopCount}:{}}),KO();break;case"compaction":S(U.phase==="start"?"compaction.started":"compaction.completed",{...U.reason?{reason:U.reason}:{},...U.strategy?{strategy:U.strategy}:{},...U.outcome?{outcome:U.outcome}:{},...U.preTokens!==void 0?{preTokens:U.preTokens}:{},...U.preTokenSource?{preTokenSource:U.preTokenSource}:{},...U.estimatedPendingTokens!==void 0?{estimatedPendingTokens:U.estimatedPendingTokens}:{},...U.postTokens!==void 0?{postTokens:U.postTokens}:{},...U.sampleAttempts!==void 0?{sampleAttempts:U.sampleAttempts}:{},...U.inputReductions!==void 0?{inputReductions:U.inputReductions}:{},...U.messagesOmitted!==void 0?{messagesOmitted:U.messagesOmitted}:{},...U.filesOmitted!==void 0?{filesOmitted:U.filesOmitted}:{},...U.imagesOmitted!==void 0?{imagesOmitted:U.imagesOmitted}:{},...U.fallbackTargetTokens!==void 0?{fallbackTargetTokens:U.fallbackTargetTokens}:{},...U.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:U.fallbackMessagesOmitted}:{},...U.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:U.fallbackMessagesTruncated}:{},...U.failureReason?{failureReason:U.failureReason}:{},...U.memory?{memory:U.memory}:{}});break;case"model_fallback":S("model.fallback",{from:U.from,to:U.to,candidate:U.candidate,candidateCount:U.candidateCount,trigger:U.trigger});break;case"task_update":S("task.updated",{tasks:U.tasks});break;case"goal_frontier_updated":S("goal.frontier.updated",{goalId:U.goal.goalId,goalStatus:U.goal.status,frontier:U.frontier,stall:U.goal.frontierStall});break;default:break}},tO=(U)=>{let OO=U.metadata?.toolCallsCount;return new L1({taskFailure:h0(U.error?.details??U.error?.message??"Agent run failed"),outputStarted:h,toolExecutionStarted:m,toolCallsCount:typeof OO==="number"&&Number.isInteger(OO)?OO:-1})},gO=await M4(E.chatStream(Q,SO,{stream:!0,pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:X.taskAdmission}),$0);if(await fO(gO))return;if(!gO.success)throw tO(gO);for(let U=0;U<20;U++){let OO=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,d.getPendingSteeringCount()===0){if(!OO)break;continue}if(V.signal.aborted)break;if(gO=await M4(E.chatStream("",SO,{stream:!0,pendingInputOnly:!0,taskAdmission:X.taskAdmission}),$0),await fO(gO))return;if(!gO.success)throw tO(gO)}if(await N0($),X.pendingResume&&V.signal.aborted&&V.signal.reason===d1)throw new L1({taskFailure:A1("timeout"),outputStarted:h,toolExecutionStarted:m,toolCallsCount:Number.isInteger(gO.metadata?.toolCallsCount)?gO.metadata?.toolCallsCount??-1:-1});if(V.signal.aborted||O.status==="cancelled"){await YO(),S("session.status",{status:"idle"});return}if(X.pendingResume)X.onPendingResumeSuccess?.(X.pendingResume);if(T)S("message.complete",{messageId:T});S("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),S("session.completed",{runId:N,outputTruncated:gO.metadata?.outputTruncated??!1}),S("session.status",{status:"idle"})}catch(d){if(b&&X.preparedInputTurn)await(b.getTurnRecoveryAssessment().state==="requires_attention"?b.finishTurn(X.preparedInputTurn.handle,{preserveStartupRecovery:!0}):b.finishTurn(X.preparedInputTurn.handle)).catch(()=>{return});let n=X.pendingResume!==void 0&&V.signal.aborted&&V.signal.reason===d1;if(V.signal.aborted&&!n||O.status==="cancelled"){if(X.pendingResume)X.onPendingResumeCancelled?.(X.pendingResume);b1(O,"runtime-abort"),await YO(),S("session.status",{status:"idle"});return}let NO=d instanceof L1?d.evidence:n?{taskFailure:A1("timeout"),outputStarted:h,toolExecutionStarted:m,toolCallsCount:-1}:X.pendingResume?{taskFailure:h0(d),outputStarted:!0,toolExecutionStarted:!0,toolCallsCount:-1}:void 0,qO=X.pendingResume!==void 0&&NO!==void 0&&X.onPendingResumeFailure?.(X.pendingResume,NO,n||(b?.getPendingSteeringCount()??0)>0,n)===!0;if(O.status="failed",qO){let KO=await b?.setTaskStatus("running").catch(()=>{return});if(KO)w0($,KO);$.taskStatus="running",$.taskStatusReason=void 0,$.taskFailure=void 0,$.taskCompletedAt=void 0,S("session.status",{status:"running"});return}await N0($).catch(()=>{return}),l.error("[SessionRoutes] Agent execution error:",d),$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let SO=NO?.taskFailure??h0(d);if(!$.taskFailure){let KO=b?await b.setTaskStatus("failed",d).catch(()=>{return}):await g.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:SO.message,taskFailure:SO,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(KO)w0($,KO)}$.taskStatusReason??=SO.message,$.taskFailure??=SO,S("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),S("session.status",{status:"error"})}finally{if(D)clearTimeout(D);if(X.taskAdmission?.release(),X.taskAdmission){let d=j0.getStats();S("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:d.queued,taskConcurrencyLimit:d.maxConcurrent,taskInFlight:d.inFlight,taskAdmissionPaused:d.paused,updatedAt:new Date().toISOString()})}if(await E?.destroy().catch(()=>{return}),L?.release(),q?.release(),O.disposeRuntimeOnSettle&&X.disposeRuntime)await X.disposeRuntime($,b).catch((d)=>{l.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,d)});I9(O)}}async function i2(O,$,Q){l.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),l.info(`[SessionRoutes] Active runs: ${Y0.size}`);for(let[V,w]of Y0.entries())if(l.info(`[SessionRoutes] Checking run ${V}: sessionId=${w.sessionId}, projectPath=${w.projectPath}, pendingPermission=${w.pendingPermission?.permissionId}`),w.sessionId===O.sessionId&&w.projectPath===O.projectPath&&w.pendingPermission?.permissionId===$){if(w.pendingPermission.details.interactionRequestId)await y0.respond(O.projectPath,O.sessionId,$,Q);return w.pendingPermission.resolve(Q),l.info(`[SessionRoutes] Permission ${$} responded, runId: ${w.id}`),!0}let Z=await y0.findPending(O.projectPath,O.sessionId);if(!Z||Z.request.requestId!==$)return l.error(`[SessionRoutes] Permission not found: ${$}`),!1;await y0.respondAndRecover(O.projectPath,O.sessionId,$,Q),P.publish(O,"interaction.resolved",{requestId:$});let J=_0;if(!J?.accepting)return!0;let X;try{X=await J.acquireOrHydrateSession(O);let V=X.value,w=await g.findSessionMetadata(O.sessionId,O.projectPath);if(_0!==J||!J.accepting||!X.isCurrent())return!0;if(w)w0(V,w);J.resumeRecoveredInteraction(V).catch((N)=>{l.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,N)})}catch(V){if(_0!==J||!J.accepting)return!0;throw V}finally{X?.release()}return!0}var R4=ZO("Service"),k9=G.Object({approved:G.Boolean(),remember:G.Optional(G.Boolean()),scope:G.Optional(zO(["once","session","project"])),targetMode:G.Optional(zO(["default","autoEdit","plan","yolo"])),feedback:G.Optional(G.String({maxLength:4000})),answers:G.Optional(G.Record(G.String({maxLength:80}),G.Union([G.String({maxLength:4000}),G.Array(G.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:G.Optional(G.Object({action:zO(["accept","decline","cancel"]),content:G.Optional(G.Record(G.String(),G.Union([G.String({maxLength:4000}),G.Number(),G.Boolean(),G.Array(G.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),l2=()=>{let O=new P9;return O.post("/:permissionId",async($)=>{let Q=$.req.param("permissionId"),Z=$.req.query("sessionId"),J=$.req.query("projectPath");R4.info(`[PermissionRoutes] Received permission response: permissionId=${Q}, sessionId=${Z}`);try{let X=await $.req.json(),V=y(k9,X);if(!V.success)throw new F("Invalid permission response format");let{approved:w,remember:N,scope:H,targetMode:j,feedback:T,answers:L,elicitation:q}=V.data;if(!Z)throw new F("sessionId query parameter is required");let b=await hO(Z,J);if(!await i2(b,Q,{approved:w,reason:T,scope:H,targetMode:j,feedback:T,answers:L,elicitation:q}))throw new i("Permission request",Q);return R4.info(`[PermissionRoutes] Permission ${Q} ${w?"approved":"denied"}`),$.json({success:!0,approved:w,remember:N})}catch(X){if(R4.error("[PermissionRoutes] Failed to respond to permission:",X),X instanceof F||X instanceof vO||X instanceof i||X instanceof _O)throw X;throw X}}),O};import{homedir as a2}from"node:os";import q4 from"node:path";import{Hono as m9}from"hono";var h9=G.Object({projectPath:G.String({minLength:1}),enabled:G.Boolean(),scope:G.Optional(zO(["local","project","global"]))}),y9=G.Object({projectPath:G.String({minLength:1})}),g9=G.Object({projectPath:G.String({minLength:1}),source:G.String({minLength:1}),trust:G.Literal(!0),ref:G.Optional(G.String({minLength:1}))}),p9=G.Object({projectPath:G.String({minLength:1}),trust:G.Literal(!0)}),v9=G.Object({projectPath:G.String({minLength:1}),confirm:G.Literal(!0)}),u9=G.Object({projectPath:G.String({minLength:1}),source:G.String({minLength:1}),ref:G.Optional(G.String({minLength:1}))}),n2=G.Object({projectPath:G.String({minLength:1}),confirm:G.Optional(G.Literal(!0))}),d9=G.Object({projectPath:G.String({minLength:1}),scope:G.Optional(zO(["local","project","global"])),policy:G.Object({restrictToAllowedSources:G.Boolean(),requireGitCommitSha:G.Boolean(),allowedGitHosts:G.Array(G.String()),allowedMarketplaces:G.Array(G.String()),allowedLocalRoots:G.Array(G.String())})});function O0(O){if(!O)throw new F("projectPath must be absolute");try{return wO(O)}catch{throw new F("projectPath must reference a local workspace")}}function c9(O){return q4.isAbsolute(O)||O.startsWith("./")||O.startsWith("../")||O==="~"||O.startsWith("~/")}function o2(O,$){if(!c9(O))return;let Q=O==="~"?a2():O.startsWith("~/")?q4.join(a2(),O.slice(2)):O;try{wO(q4.resolve($,Q))}catch{throw new F("Plugin source must reference a local workspace")}}async function t2(O){let[$,Q]=await Promise.all([eO(O),U1.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((Z)=>({name:Z.manifest.name,description:Z.manifest.description,version:Z.manifest.version,source:Z.source,enabled:Z.status==="active",status:Z.status,commands:Z.commands.length,skills:Z.skills.length,agents:Z.agents.length,hooks:Z.hooks?Object.values(Z.hooks).reduce((J,X)=>J+(Array.isArray(X)?X.length:0),0):0,mcpServers:Object.keys(Z.mcpServers??{}).length,configurable:Z.source!=="cli",managed:Z.installation!==void 0,marketplace:Z.installation?.source.type==="marketplace"?Z.installation.source.marketplace:void 0,revision:Z.installation?.revision,installedAt:Z.installation?.installedAt,updatedAt:Z.installation?.updatedAt,compatibilityIssues:Z.compatibilityIssues??[],effectiveScope:Z.source==="cli"?"invocation":Q.settings[Z.manifest.name]?.effectiveScope??"default",settingLayers:Z.source==="cli"?{invocation:!0}:Q.settings[Z.manifest.name]?.layers??{}}))}async function i9(){let O=s2(),[$,Q]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),Z=new Map(Q.map((J)=>[J.name,J]));return $.map(({marketplace:J,manifest:X})=>({name:J.name,description:X.description??X.metadata?.description??"",sourceType:J.source.type,revision:J.revision,updatedAt:J.updatedAt,plugins:X.plugins.map((V)=>{let w=Z.get(V.name);return{name:V.name,description:V.description??"",version:V.version,category:V.category,tags:V.tags??[],installed:w!==void 0,installedVersion:w?.version}})}))}function t0(O,$){if(!O.success)throw new F(O.error??$)}var V3=()=>{let O=new m9;return O.get("/",async($)=>{let Q=O0($.req.query("projectPath"));return $.json(await t2(Q))}),O.post("/refresh",async($)=>{let Q=y(y9,await $.req.json());if(!Q.success)throw new F("Invalid plugin refresh request");let Z=O0(Q.data.projectPath),J=await e2(Z);return $.json({plugins:await t2(Z),errors:J.discovery.errors.map((X)=>({code:X.code??"LOAD_ERROR",error:X.error}))})}),O.get("/catalog",async($)=>{return O0($.req.query("projectPath")),$.json(await i9())}),O.get("/policy",async($)=>{let Q=O0($.req.query("projectPath")),Z=await U1.getInstance().loadWorkspacePluginSourcePolicy(Q);return $.json({policy:Z,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let Q=y(d9,await $.req.json());if(!Q.success)throw new F("Invalid plugin source policy request");let Z=O0(Q.data.projectPath),J=await O3(Z,Q.data.policy,Q.data.scope??"global");return $.json({policy:J})}),O.post("/install",async($)=>{let Q=y(g9,await $.req.json());if(!Q.success)throw new F("Invalid plugin install request; explicit source trust is required");let Z=O0(Q.data.projectPath);o2(Q.data.source,Z);let{result:J}=await $3(Z,Q.data.source,{trusted:Q.data.trust,ref:Q.data.ref});return t0(J,"Plugin installation failed"),$.json({name:J.pluginName,version:J.manifest?.version,revision:J.installation?.revision,changed:J.changed,installedDependencies:J.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let Q=y(u9,await $.req.json());if(!Q.success)throw new F("Invalid marketplace add request");let Z=O0(Q.data.projectPath);o2(Q.data.source,Z);let J=await J3(Z,Q.data.source,Q.data.ref);return t0(J,"Marketplace installation failed"),$.json({name:J.marketplace?.name,plugins:J.manifest?.plugins.length??0,revision:J.marketplace?.revision,changed:J.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let Q=y(n2,await $.req.json());if(!Q.success)throw new F("Invalid marketplace refresh request");let Z=await Y3(O0(Q.data.projectPath),$.req.param("name"));return t0(Z,"Marketplace refresh failed"),$.json({name:Z.marketplace?.name,plugins:Z.manifest?.plugins.length??0,revision:Z.marketplace?.revision,changed:Z.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let Q=y(n2,await $.req.json());if(!Q.success||Q.data.confirm!==!0)throw new F("Invalid marketplace removal request; explicit confirmation is required");O0(Q.data.projectPath);let Z=await X3($.req.param("name"),!0);return t0(Z,"Marketplace removal failed"),$.json({name:Z.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let Q=y(p9,await $.req.json());if(!Q.success)throw new F("Invalid plugin update request; explicit source trust is required");let Z=O0(Q.data.projectPath),{result:J}=await Q3(Z,$.req.param("name"),{trusted:Q.data.trust});return t0(J,"Plugin update failed"),$.json({name:J.pluginName,version:J.manifest?.version,revision:J.installation?.revision,changed:J.changed,updatedDependencies:J.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let Q=y(v9,await $.req.json());if(!Q.success)throw new F("Invalid plugin uninstall request; explicit confirmation is required");let Z=O0(Q.data.projectPath),{result:J}=await Z3(Z,$.req.param("name"),Q.data.confirm);return t0(J,"Plugin uninstall failed"),$.json({name:J.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let Q=y(h9,await $.req.json());if(!Q.success)throw new F("Invalid plugin state request");let Z=O0(Q.data.projectPath),J=$.req.param("name"),V=(await eO(Z)).plugins.get(J);if(!V)throw new i("Plugin",J);if(V.source==="cli")throw new F(`Plugin "${J}" was loaded with --plugin-dir and is invocation-scoped`);let w=await r2(Z,J,Q.data.enabled,Q.data.scope??"local");return $.json(w)}),O};import{Hono as t9}from"hono";import{execFile as l9}from"node:child_process";import a9 from"node:path";var S4="__BLADE_DIRECTORY_PICKER_CANCELLED__",n9=900000;function o9(O,$){return new Promise((Q)=>{l9(O,[...$],{timeout:n9,maxBuffer:65536,windowsHide:!0},(Z,J,X)=>{let V=Z?.code;Q({stdout:J,stderr:X,exitCode:typeof V==="number"?V:Z?1:0,...typeof V==="string"?{errorCode:V}:{}})})})}function E4(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===S4)return{cancelled:!0};if(!a9.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function C4(O){return O.exitCode!==0||Boolean(O.errorCode)}class z3{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??o9}pick(){if(this.activeSelection)return this.activeSelection;let O=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=O,O}async pickForPlatform(){switch(this.platform){case"darwin":return this.pickOnMac();case"win32":return this.pickOnWindows();case"linux":return this.pickOnLinux();default:throw Error("Native folder selection is unavailable on this system")}}async pickOnMac(){let O=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${S4}"`,"end try"].join(`
8
8
  `),$=await this.runCommand("osascript",["-e",O]);if(C4($))throw Error("Unable to open the macOS folder picker");return E4($.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("${S4}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(C4($))throw Error("Unable to open the Windows folder picker");return E4($.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 Q=await this.runCommand($.command,$.args);if(Q.errorCode==="ENOENT")continue;if(Q.exitCode===1&&!Q.stdout.trim()&&!Q.stderr.trim())return{cancelled:!0};if(C4(Q))throw Error("Unable to open the Linux folder picker");return E4(Q.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var G3=new z3;var s9=G.Object({path:G.String({minLength:1})});function W3(O){try{return wO(O)}catch($){throw new F($ instanceof Error?$.message:"Project path is invalid")}}function r9(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let $=new URL(O).hostname;return $==="localhost"||$==="127.0.0.1"||$==="::1"||$==="[::1]"}catch{return!1}}var K3=(O={})=>{let $=new t9,Q=O.pickDirectory??(()=>G3.pick()),Z=O.allowDirectoryPickerRequest??r9;return $.get("/",async(J)=>{return J.json(await o1.list(GO()))}),$.post("/",async(J)=>{let X;try{X=await J.req.json()}catch{throw new F("A valid JSON body is required")}let V=y(s9,X);if(!V.success)throw new F("A project path is required");try{let w=W3(V.data.path),N=await o1.bind(w,GO());return J.json(N,201)}catch(w){throw new F(w instanceof Error?w.message:"Failed to bind project")}}),$.post("/pick",async(J)=>{if(!Z(J.req.header("Origin")))throw new _O("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return J.json(await Q())}catch(X){throw new F(X instanceof Error?X.message:"Failed to select a folder")}}),$.delete("/",async(J)=>{let X=J.req.query("path");if(!X)throw new F("A project path is required");try{let V=await o1.unbind(W3(X));return J.json({success:!0,removed:V})}catch(V){throw new F(V instanceof Error?V.message:"Failed to unbind project")}}),$};import{Hono as e9}from"hono";var _3=ZO("Service"),F3=()=>{let O=new e9;return O.get("/",async($)=>{try{let Q=await U3();return $.json(Q)}catch(Q){return _3.error("[ProviderRoutes] Failed to list providers:",Q),$.json([])}}),O.get("/:provider/models",async($)=>{let Q=$.req.param("provider");try{let Z=await H3(Q);return $.json(Z)}catch(Z){return _3.error("[ProviderRoutes] Failed to list models:",Z),$.json([])}}),O.put("/:provider/credential",async($)=>{let Q=$.req.param("provider"),Z=await $.req.json();if(!Z.apiKey?.trim())throw new F("apiKey is required");return await f0().setApiKey(Q,Z.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await f0().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let Q=$.req.param("provider"),Z=MO(),J=Z?.modelProviders[Q];if(!Z||!J)throw new i("Model provider",Q);let X=await $.req.json();if(!X.name||!X.baseUrl||!X.wireApi)throw new F("name, baseUrl and wireApi are required");let V="apiKeyEnv"in X?X.apiKeyEnv?.trim():J.apiKeyEnv,w={name:X.name,baseUrl:X.baseUrl,wireApi:X.wireApi,...V?{apiKeyEnv:V}:{}},N=f0(),H=X.apiKey?.trim()?await N.credentials.read(Q):void 0;if(X.apiKey?.trim())await N.setApiKey(Q,X.apiKey.trim());try{return await nO().updateModelProvider(Q,w),$.json({success:!0})}catch(j){if(X.apiKey?.trim())if(H)await N.credentials.modify(Q,async()=>H);else await N.credentials.delete(Q);if(j instanceof Error&&(j.message.includes("modelProviders.")||j.message.includes("built-in provider")))throw new F(j.message);throw j}}),O.delete("/:provider",async($)=>{let Q=$.req.param("provider");if(!MO()?.modelProviders[Q])throw new i("Model provider",Q);let J=$.req.query("removeModels");if(J!==void 0&&J!=="true"&&J!=="false")throw new F("removeModels must be true or false");try{let X=await nO().removeModelProvider(Q,{removeModels:J==="true"});return $.json({success:!0,...X})}catch(X){if(X instanceof Error&&(X.message.includes("still referenced")||X.message.includes("owns the only model")))throw new v(X.message);throw X}}),O.post("/:provider/probe",async($)=>{let Q=$.req.param("provider"),Z=MO();if(!Z?.modelProviders[Q])throw new i("Model provider",Q);let J=await $.req.json().catch(()=>({})),X=Z.models.filter((w)=>w.provider===Q),V=J.modelId?X.find((w)=>w.id===J.modelId):X[0];if(!V)throw new F(J.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return $.json(await w3(V,Z))}),O};import{Hono as O6}from"hono";var $6=ZO("Service"),x3=(O,$)=>{let Q=new O6;return Q.onError((Z,J)=>{if(Z instanceof _O)return J.json(Z.toObject(),Z.statusCode);return $6.error("[ScheduleRoutes] Unhandled route error:",Z),J.json(new VO("Schedule request failed").toObject(),500)}),Q.get("/",async(Z)=>{let J=await O.list();return Z.json(D3.parse({schedules:J}))}),Q.post("/",async(Z)=>{let J;try{J=await Z.req.json()}catch{throw new F("Invalid request body")}let X=y(N3,J);if(!X.success)throw new F("Invalid schedule request");let V;try{V=wO(X.data.projectPath||Z.get("directory")||GO())}catch{throw new F("projectPath must reference a local workspace")}try{let w=await O.create({...X.data,projectPath:V});return Z.json(g0.parse(w),201)}catch(w){throw new F(w instanceof Error?w.message:"Failed to create schedule")}}),Q.get("/:id",async(Z)=>{let J=await O.get(Z.req.param("id"));if(!J)throw new i("Schedule not found");return Z.json(g0.parse(J))}),Q.patch("/:id",async(Z)=>{let J;try{J=await Z.req.json()}catch{throw new F("Invalid request body")}let X=y(B3,J);if(!X.success)throw new F("Invalid schedule update");let{modelId:V,reasoningEffort:w,serviceTier:N,responseVerbosity:H,communicationStyle:j,isolation:T,permissionMode:L,...q}=X.data,b={...V!==void 0?{modelId:V}:{},...w!==void 0?{reasoningEffort:w}:{},...N!==void 0?{serviceTier:N}:{},...H!==void 0?{responseVerbosity:H}:{},...j!==void 0?{communicationStyle:j}:{},...T!==void 0?{isolation:T}:{},...L!==void 0?{permissionMode:L}:{}};try{let E=await O.update(Z.req.param("id"),{...q,...Object.keys(b).length>0?{dispatch:b}:{}});if(!E)throw new i("Schedule not found");return Z.json(g0.parse(E))}catch(E){if(E instanceof _O)throw E;throw new F(E instanceof Error?E.message:"Failed to update schedule")}}),Q.delete("/:id",async(Z)=>{if(!await O.remove(Z.req.param("id")))throw new i("Schedule not found");return Z.json({ok:!0})}),Q.post("/:id/enable",async(Z)=>{let J=await O.setEnabled(Z.req.param("id"),!0);if(!J)throw new i("Schedule not found");return Z.json(g0.parse(J))}),Q.post("/:id/disable",async(Z)=>{let J=await O.setEnabled(Z.req.param("id"),!1);if(!J)throw new i("Schedule not found");return Z.json(g0.parse(J))}),Q.post("/:id/run",async(Z)=>{let J=await O.get(Z.req.param("id"));if(!J)throw new i("Schedule not found");if(!$)throw new VO("Scheduler is not running in this process");await $.fire(J,new Date,{manual:!0});let X=await O.get(J.id);return Z.json(g0.parse(X??J),202)}),Q};import{createHash as Q6}from"node:crypto";import{Hono as Z6}from"hono";var f4={invalid_session_surface_request:400,invalid_session_locator:400,session_surface_not_found:404,workspace_binding_mismatch:409,session_surface_cursor_invalid:400,session_surface_snapshot_changed:409,session_surface_read_only:409,session_surface_capability_unavailable:403,session_surface_capacity:429,session_surface_unavailable:503,session_surface_state_invalid:500},J6=G.Object({cursor:G.Optional(G.String({minLength:1})),limit:G.Optional(G.String({pattern:"^(?:[1-9]|[1-9][0-9]|100)$"})),archived:G.Optional(zO(["true","false"])),workspaceKind:G.Optional(zO(["local","acp-remote"]))},{additionalProperties:!1}),t1=65536,Y6=new Set(["cursor","limit","archived","workspaceKind"]),X6=new Set(["locator","limit"]),V6=new Set(["locator","cursor","expectedSnapshot","limit"]),z6=new Set(["locator"]),G6=new Set(["version","sessionId","workspace"]),W6=new Set(["kind","projectPath","workspaceRef"]),K6=ZO("Service");function E3(O={}){let $=O.service?void 0:new R3(O.cursorRegistryOptions),Q=O.service??new q3({database:O.database,cursorRegistry:$}),Z=O.logger??K6,J=new Z6,X=!0,V=0,w,N=new Set,H=()=>new s0("session_surface_unavailable"),j=()=>{if(V===0)return Promise.resolve();return new Promise((L)=>N.add(L))};return J.onError((L,q)=>{let b=U6(L);return Z.warn(`[SessionSurfaceRoutes] method=${q.req.method} path=${q.req.path} code=${b.error.code} kind=${q.get("surfaceKind")??"unknown"} locator=${q.get("surfaceLocatorDigest")??"none"}`),q.json(b,f4[b.error.code])}),J.use("*",async(L,q)=>{if(L.set("surfaceKind","unknown"),L.set("surfaceLocatorDigest","none"),!X){let b=s1(H());return L.json(b,f4[b.error.code])}V+=1;try{if(await q(),!X){let b=s1(H());L.res=L.json(b,f4[b.error.code])}return L.res}finally{if(V-=1,V===0){for(let b of N)b();N.clear()}}}),J.get("/catalog",async(L)=>{let q=_6(L.req.url),b=await Q.listPage(q);return L.json(A3.parse(b))}),J.post("/open",async(L)=>{P4(L.req.url);let q=await h4(L.req.raw);C1(q,X6,yO());let b=k4(q);m4(L,b);let E=y(b3,q);if(!E.success)throw yO();let h=await Q.open(b,{limit:E.data.limit});return L.json(y4.parse(h))}),J.post("/history",async(L)=>{P4(L.req.url);let q=await h4(L.req.raw);C1(q,V6,yO());let b=k4(q);m4(L,b);let E=y(T3,q);if(!E.success)throw yO();let h=await Q.historyPage(b,{cursor:E.data.cursor,expectedSnapshot:E.data.expectedSnapshot,limit:E.data.limit});return L.json(j3.parse(h))}),J.post("/fork",async(L)=>{P4(L.req.url);let q=await h4(L.req.raw);C1(q,z6,yO());let b=k4(q);if(m4(L,b),!y(I3,q).success)throw yO();let h=await Q.fork(b);return L.json(y4.parse(h))}),{app:J,getStats:()=>({accepting:X,active:V,cursors:$?.stats().entryCount??0}),shutdown:(L="server-shutdown")=>{if(w)return w;return X=!1,w=(async()=>{let b=(await Promise.allSettled([Promise.resolve().then(()=>Q.close(L)),j()])).find((E)=>E.status==="rejected");if(b)throw b.reason})(),w}}}function yO(){return new s0("invalid_session_surface_request")}function _6(O){let $=new URL(O).searchParams,Q={},Z=new Set;for(let[X,V]of $){if(!Y6.has(X)||Z.has(X))throw yO();Z.add(X),Q[X]=V}let J=y(J6,Q);if(!J.success)throw yO();return{...J.data.archived!==void 0?{archived:J.data.archived==="true"}:{},...J.data.cursor!==void 0?{cursor:J.data.cursor}:{},...J.data.limit!==void 0?{limit:Number(J.data.limit)}:{},...J.data.workspaceKind!==void 0?{workspaceKind:J.data.workspaceKind}:{}}}function P4(O){if(new URL(O).searchParams.size>0)throw yO()}function C1(O,$,Q){if(!O||typeof O!=="object"||Array.isArray(O))throw Q;if(Object.keys(O).some((Z)=>!$.has(Z)))throw Q}function k4(O){if(!O||typeof O!=="object"||Array.isArray(O))throw yO();let $=Reflect.get(O,"locator");if($===void 0)throw yO();let Q=new s0("invalid_session_locator");C1($,G6,Q),C1(Reflect.get($,"workspace"),W6,Q);let Z=y(L3,$);if(!Z.success)throw Q;return Z.data}function m4(O,$){O.set("surfaceKind",$.workspace.kind),O.set("surfaceLocatorDigest",H6($))}async function h4(O){let $=O.headers.get("content-length");if($!==null&&(!/^\d+$/.test($)||Number($)>t1))throw yO();let Q=O.body?.getReader();if(!Q)throw yO();let Z=[],J=0;try{while(!0){let{done:N,value:H}=await Q.read();if(N)break;if(J+=H.byteLength,J>t1){try{await Q.cancel()}catch{}throw yO()}Z.push(H)}}finally{Q.releaseLock()}let X=new Uint8Array(J),V=0;for(let N of Z)X.set(N,V),V+=N.byteLength;let w=new TextDecoder().decode(X);if(!w)throw yO();try{return w6(w),JSON.parse(w)}catch{throw yO()}}function w6(O){let $=0,Q=()=>{while(/\s/.test(O[$]??""))$+=1},Z=()=>{let X=$;if(O[$]!=='"')throw Error("expected string");$+=1;while($<O.length){let V=O[$];if(V==="\\"){$+=2;continue}if($+=1,V==='"')return JSON.parse(O.slice(X,$))}throw Error("unterminated string")},J=()=>{Q();let X=O[$];if(X==="{"){$+=1,Q();let w=new Set;if(O[$]==="}"){$+=1;return}while($<O.length){Q();let N=Z();if(w.has(N))throw Error("duplicate key");if(w.add(N),Q(),O[$]!==":")throw Error("expected colon");if($+=1,J(),Q(),O[$]==="}"){$+=1;return}if(O[$]!==",")throw Error("expected comma");$+=1}throw Error("unterminated object")}if(X==="["){if($+=1,Q(),O[$]==="]"){$+=1;return}while($<O.length){if(J(),Q(),O[$]==="]"){$+=1;return}if(O[$]!==",")throw Error("expected comma");$+=1}throw Error("unterminated array")}if(X==='"'){Z();return}let V=/^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(O.slice($))?.[0];if(!V)throw Error("invalid primitive");$+=V.length};if(J(),Q(),$!==O.length)throw Error("trailing JSON")}function U6(O){if(O instanceof s0)return s1(O);return s1(new s0("session_surface_state_invalid"))}function s1(O){return M3.parse({error:{code:O.code,message:O.message,retryable:O.retryable}})}function H6(O){if(!O)return"none";return Q6("sha256").update("session-surface-route-locator-v2\x00").update(JSON.stringify(O)).digest("hex").slice(0,16)}import*as R0 from"node:fs/promises";import{homedir as k3}from"node:os";import*as cO from"node:path";import{Hono as x6}from"hono";import{execFile as F6}from"node:child_process";import*as s from"node:fs/promises";import{homedir as N6}from"node:os";import*as QO from"node:path";import{promisify as B6}from"node:util";var D6=B6(F6),RO=ZO("General");function p0(O){return typeof O==="string"&&O===O.trim()&&/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/.test(O)}function p4(O){if(typeof O!=="string"||!O||/\s/.test(O))return!1;if([...O].some(($)=>$.charCodeAt(0)<32||$.charCodeAt(0)===127))return!1;if(O.startsWith("git@"))return/^git@[A-Za-z0-9][A-Za-z0-9.-]*:[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+$/.test(O);if(!/^(https|ssh):\/\//.test(O))return!1;try{let $=new URL(O);return($.protocol==="https:"||$.protocol==="ssh:")&&Boolean($.hostname)&&!$.hostname.startsWith("-")&&!$.password&&!($.protocol==="https:"&&$.username)&&!($.username&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test($.username))&&!$.search&&!$.hash&&$.pathname!=="/"}catch{return!1}}function v4(O){let $=O.startsWith("git@")?O.slice(O.indexOf(":")+1):new URL(O).pathname;return QO.posix.basename($.replace(/\/+$/,"")).replace(/\.git$/,"")}var C3={url:"https://github.com/anthropics/skills.git",branch:"main"};class S3{skillsDir;constructor(O){this.skillsDir=O||QO.join(N6(),".blade","skills")}async isGitAvailable(){try{return await this.runGit(["--version"],5000),!0}catch{return!1}}async runGit(O,$){await D6("git",O,{shell:!1,timeout:$,maxBuffer:4194304,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}async installOfficialSkill(O){if(!p0(O))return!1;let{url:$,branch:Q}=C3,Z=QO.join(this.skillsDir,O),J=QO.join(this.skillsDir,`.tmp-${O}-${Date.now()}`);try{if(!await this.isGitAvailable())return RO.warn("Git not available, skipping skill installation"),!1;RO.info(`Installing official skill: ${O}...`),await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),await this.runGit(["clone","--depth","1","--branch",Q,"--single-branch","--",$,J],30000);let X=QO.join(J,"skills",O);try{await s.access(X)}catch{return RO.warn(`Skill ${O} not found in official repository`),await s.rm(J,{recursive:!0,force:!0}),!1}try{await s.rm(Z,{recursive:!0,force:!0})}catch{}return await s.cp(X,Z,{recursive:!0}),await s.rm(J,{recursive:!0,force:!0}),RO.info(`Successfully installed: ${O}`),!0}catch(X){try{await s.rm(J,{recursive:!0,force:!0})}catch{}return RO.warn(`Failed to install ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installFromRepo(O,$){if(!p4(O))return!1;let Q=$??v4(O);if(!p0(Q))return!1;let Z=QO.join(this.skillsDir,Q),J=QO.join(this.skillsDir,`.tmp-repo-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return RO.warn("Git not available, cannot install from repo"),!1;RO.info(`Installing skill from repo: ${O}...`),await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),await this.runGit(["clone","--depth","1","--",O,J],60000);let X=QO.join(J,"SKILL.md");try{await s.access(X)}catch{return RO.warn(`No SKILL.md found in repository ${O}`),await s.rm(J,{recursive:!0,force:!0}),!1}await s.rm(Z,{recursive:!0,force:!0}),await s.rename(J,Z);try{await s.rm(QO.join(Z,".git"),{recursive:!0,force:!0})}catch{}return RO.info(`Successfully installed skill from repo: ${Q}`),!0}catch(X){try{await s.rm(J,{recursive:!0,force:!0})}catch{}return RO.warn(`Failed to install from repo ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installFromLocal(O,$,Q=!0){if(typeof O!=="string"||!O.trim()||O.includes("\x00"))return!1;let Z=$??QO.basename(O);if(!p0(Z))return!1;let J=QO.resolve(this.skillsDir,Z);try{let X=await s.realpath(QO.resolve(O)),V=QO.dirname(J),w=[];while(!0)try{V=QO.join(await s.realpath(V),...w);break}catch(j){if(j.code!=="ENOENT")throw j;w.unshift(QO.basename(V)),V=QO.dirname(V)}let N=QO.join(V,Z);try{if(!(await s.lstat(N)).isSymbolicLink())N=await s.realpath(N)}catch(j){if(j.code!=="ENOENT")throw j}if([QO.relative(N,X),QO.relative(X,N)].some((j)=>j===""||!j.startsWith(`..${QO.sep}`)&&j!==".."&&!QO.isAbsolute(j)))return!1;let H=QO.join(X,"SKILL.md");try{await s.access(H)}catch{return RO.warn(`No SKILL.md found in local path: ${X}`),!1}if(RO.info(`Installing skill from local path: ${X}...`),await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),await s.rm(J,{recursive:!0,force:!0}),Q)await s.symlink(X,J,"dir"),RO.info(`Created symlink for skill: ${Z}`);else await s.cp(X,J,{recursive:!0}),RO.info(`Copied skill to: ${Z}`);return!0}catch(X){return RO.warn(`Failed to install from local path ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installAllOfficialSkills(){let{url:O,branch:$}=C3,Q=QO.join(this.skillsDir,`.tmp-all-${Date.now()}`),Z=[],J=[];try{if(!await this.isGitAvailable())return RO.warn("Git not available, skipping skill installation"),{installed:Z,failed:J};await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),RO.info("Cloning official skills repository..."),await this.runGit(["clone","--depth","1","--branch",$,"--single-branch","--",O,Q],60000);let X=QO.join(Q,"skills"),V=await s.readdir(X,{withFileTypes:!0});for(let w of V){if(!w.isDirectory())continue;let N=w.name;if(!p0(N)){J.push(N);continue}let H=QO.join(X,N),j=QO.join(this.skillsDir,N);try{await s.access(QO.join(H,"SKILL.md")),await s.rm(j,{recursive:!0,force:!0}),await s.cp(H,j,{recursive:!0}),RO.info(`Installed: ${N}`),Z.push(N)}catch(T){RO.warn(`Failed to install ${N}`),J.push(N)}}await s.rm(Q,{recursive:!0,force:!0})}catch(X){try{await s.rm(Q,{recursive:!0,force:!0})}catch{}RO.warn(`Failed to install skills: ${X instanceof Error?X.message:"Unknown error"}`)}return{installed:Z,failed:J}}}var g4=null;function f3(O){if(!g4)g4=new S3(O);return g4}var v0=ZO("Service"),P3=cO.join(k3(),".blade","skills"),u4=cO.join(k3(),".blade","skills-config.json"),L6=G.Union([G.Object({source:G.Literal("catalog"),name:G.String({minLength:1,maxLength:64})}),G.Object({source:G.Literal("repo"),url:G.String({minLength:1,maxLength:4096}),name:G.Optional(G.String({minLength:1,maxLength:64}))}),G.Object({source:G.Literal("local"),path:G.String({minLength:1,maxLength:4096}),name:G.Optional(G.String({minLength:1,maxLength:64}))})]);function r1(O){try{return wO(O,"directory")}catch{throw new F("directory must reference a local workspace")}}async function m3(){try{let O=await R0.readFile(u4,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function M6(O){await R0.mkdir(cO.dirname(u4),{recursive:!0}),await R0.writeFile(u4,JSON.stringify(O,null,2))}async function A6(O,$){let Q=await m3();if($)Q.disabled=Q.disabled.filter((Z)=>Z!==O);else if(!Q.disabled.includes(O))Q.disabled.push(O);await M6(Q)}var I0=null,j6=300000,b6=6;async function T6(){if(I0&&Date.now()-I0.timestamp<j6)return I0.data;try{let O=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!O.ok){if(v0.warn(`GitHub API returned ${O.status}`),I0)return I0.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let Q=(await O.json()).filter((V)=>V.type==="dir"),Z=Array(Q.length),J=0,X=Math.min(b6,Q.length);return await Promise.all(Array.from({length:X},async()=>{while(J<Q.length){let V=J++,w=Q[V];if(!w)continue;let N=`Official ${w.name} skill`;try{let H=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${w.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(H.ok){let T=(await H.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(T)N=T[1].trim().slice(0,100)}}catch{}Z[V]={name:w.name,description:N,tag:"Official",author:"Anthropic"}}})),I0={data:Z,timestamp:Date.now()},Z}catch(O){if(v0.warn("Failed to fetch skills catalog from GitHub:",O),I0)return I0.data;throw O}}var h3=()=>{let O=new x6;return O.get("/",async($)=>{try{let Q=r1($.get("directory")||GO()),J=(await eO(Q)).skills.getAll(),X=await m3(),V=J.map((w)=>({id:w.name,name:w.name,enabled:!X.disabled.includes(w.name),description:w.description||"",version:w.version||"1.0.0",provider:"Local",location:w.source==="builtin"?"Built-in":w.basePath,removable:w.source==="user"&&cO.dirname(cO.resolve(w.basePath))===cO.resolve(P3),capabilities:["prompts"],allowedTools:w.allowedTools||[]}));return $.json(V)}catch(Q){if(Q instanceof F)throw Q;return v0.error("[SkillsRoutes] Failed to get skills:",Q),$.json({error:Q instanceof Error?Q.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async($)=>{try{let Q=$.req.param("name"),Z=await $.req.json();return await A6(Q,Z.enabled),$.json({success:!0,enabled:Z.enabled})}catch(Q){return v0.error("[SkillsRoutes] Failed to toggle skill:",Q),$.json({success:!1,error:Q.message},500)}}),O.delete("/:name",async($)=>{try{let Q=$.req.param("name"),Z=r1($.get("directory")||GO());return N1(Z,async(J)=>{let X=J.skills,V=X.get(Q);if(!V)return $.json({success:!1,error:"Skill not found"},404);let w=cO.resolve(V.basePath),N=cO.resolve(P3);if(V.source!=="user"||cO.dirname(w)!==N)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await R0.rm(w,{recursive:!0,force:!0}),await X.refresh(),F1(Z),await H1(Z),$.json({success:!0})})}catch(Q){if(Q instanceof F)throw Q;return v0.error("[SkillsRoutes] Failed to uninstall skill:",Q),$.json({success:!1,error:Q.message},500)}}),O.post("/install",async($)=>{try{let Q=y(L6,await $.req.json().catch(()=>null));if(!Q.success)throw new F("Invalid skill install request");let Z=Q.data;if(Z.name!==void 0&&!p0(Z.name))throw new F("Invalid skill name");if(Z.source==="repo"&&!p4(Z.url))throw new F("Skill repositories must use HTTPS or SSH without embedded credentials");if(Z.source==="local"&&(!Z.path.trim()||Z.path.includes("\x00")))throw new F("Invalid local skill path");let J=Z.name??(Z.source==="repo"?v4(Z.url):Z.source==="local"?cO.basename(Z.path):void 0);if(!p0(J))throw new F("Invalid skill name");let X=f3(),V=r1($.get("directory")||GO());return N1(V,async(w)=>{let N=w.skills,H=!1;if(Z.source==="catalog"&&Z.name){if(H=await X.installOfficialSkill(Z.name),!H)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(Z.source==="repo"&&Z.url){if(H=await X.installFromRepo(Z.url,Z.name),!H)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(Z.source==="local"&&Z.path){let j=r1(cO.resolve(Z.path));if(H=await X.installFromLocal(j,Z.name),!H)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 N.refresh(),F1(V),await H1(V),$.json({success:!0})})}catch(Q){if(Q instanceof F)throw Q;return v0.error("[SkillsRoutes] Failed to install skill:",Q),$.json({success:!1,error:Q.message},500)}}),O.get("/catalog",async($)=>{try{let Q=await T6();return $.json(Q)}catch(Q){return v0.error("[SkillsRoutes] Failed to get catalog:",Q),$.json({error:Q instanceof Error?Q.message:"Failed to get skills catalog"},502)}}),O};import{execSync as I6}from"node:child_process";import{readdir as R6,realpath as q6}from"node:fs/promises";import B0 from"node:path";import E6 from"fast-glob";import{Hono as C6}from"hono";var S1=ZO("Service"),S6=(O)=>{try{return I6("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},f6=[...e0.map((O)=>`${O}/**`),...e0,...e0.map((O)=>`**/${O}/**`),...e0.map((O)=>`**/${O}`),...d4.map((O)=>`**/${O}`)],P6=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]);function r0(O){try{return wO(O,"directory")}catch($){throw new F($ instanceof Error?$.message:"directory is invalid")}}function y3(O,$){let Q=B0.relative(O,$);return Q===""||Q!==".."&&!Q.startsWith(`..${B0.sep}`)&&!B0.isAbsolute(Q)}async function g3(O){let $=B0.resolve(O),Q=[];while(!0)try{return B0.resolve(await q6($),...Q.reverse())}catch(Z){let J=Z.code;if(J!=="ENOENT"&&J!=="ENOTDIR")throw Z;let X=B0.dirname($);if(X===$)return B0.resolve(O);Q.push(B0.basename($)),$=X}}async function p3(O,$){let Q=B0.resolve(O,$);if(!y3(O,Q))return null;let Z=await g3(O),J=await g3(Q);if(!y3(Z,J))return null;try{r0(J)}catch{return null}return J}var d3=()=>{let O=new C6;return O.get("/commands",async($)=>{let Q=r0($.get("directory")||GO());try{let Z=$.req.query("q")||"",J=await eO(Q),X=u3(Z,Q,J).filter((V)=>!P6.has(V.command));return $.json(X)}catch(Z){return S1.error("[SuggestionsRoutes] Failed to get command suggestions:",Z),$.json([])}}),O.get("/files",async($)=>{let Q=r0($.get("directory")||GO());try{let Z=$.req.query("q")||"",J=Math.min(Number($.req.query("limit"))||100,1000),X=$.req.query("type")==="file",w=(await E6("**/*",{cwd:Q,dot:!1,followSymbolicLinks:!1,onlyFiles:X,markDirectories:!0,unique:!0,ignore:f6})).map((j)=>j.replace(/\\/g,"/"));if(!Z)return $.json(w.slice(0,J));let N=Z.toLowerCase(),H=w.filter((j)=>j.toLowerCase().includes(N)).slice(0,J);return $.json(H)}catch(Z){return S1.error("[SuggestionsRoutes] Failed to get file suggestions:",Z),$.json([])}}),O.get("/files/tree",async($)=>{let Q=r0($.get("directory")||GO());try{let Z=$.req.query("path")||"",J=await p3(Q,Z);if(!J)return $.json({error:"Invalid file path"},400);let V=(await R6(J,{withFileTypes:!0})).map((H)=>({name:H.name,path:Z?`${Z}/${H.name}`:H.name,type:H.isDirectory()?"dir":"file"}));V.sort((H,j)=>{if(H.type!==j.type)return H.type==="dir"?-1:1;return H.name.localeCompare(j.name)});let w=new Set(e0),N=V.filter((H)=>{let j=H.name;if(j.startsWith("."))return!1;if(w.has(j))return!1;for(let T of d4)if(j.match(new RegExp(T.replace("*",".*"))))return!1;return!0});return $.json(N)}catch(Z){return S1.error("[SuggestionsRoutes] Failed to get file tree:",Z),$.json([])}}),O.get("/files/content",async($)=>{let Q=r0($.get("directory")||GO());try{let Z=$.req.query("path");if(!Z)return $.json({error:"Missing file path"},400);let J=await p3(Q,Z);if(!J)return $.json({error:"Invalid file path"},400);let X=v3(),V=await X.stat(J);if(!V?.isFile)return $.json({error:"File not found"},404);let w=200000,N=await X.readTextFile(J),H=N.length>w;return $.json({path:Z,content:H?N.slice(0,w):N,truncated:H,size:V.size})}catch(Z){return S1.error("[SuggestionsRoutes] Failed to get file content:",Z),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{let Q=r0($.get("directory")||GO());try{let Z=S6(Q);return $.json({branch:Z})}catch(Z){return S1.error("[SuggestionsRoutes] Failed to get git info:",Z),$.json({branch:null})}}),O};import{Hono as k6}from"hono";var O1=ZO("Service"),n3=(O)=>{let $=new k6;return $.onError((Q,Z)=>{if(Q instanceof _O)return Z.json(Q.toObject(),Q.statusCode);return O1.error("[TaskRoutes] Unhandled route error:",Q),Z.json(new VO("Failed to dispatch task").toObject(),500)}),$.post("/",async(Q)=>{let Z;try{Z=await Q.req.json()}catch{throw new F("Invalid request body")}let J=y(i3,Z);if(!J.success)throw new F("Invalid task request");if((J.data.attachments??[]).reduce((V,w)=>V+(typeof w.content==="string"?Buffer.byteLength(w.content):0),0)>a1)throw new F("Task attachments exceed the 5 MiB limit");if(J.data.taskDueAt&&!Number.isFinite(Date.parse(J.data.taskDueAt)))throw new F("Invalid task due date");try{let V=await O.dispatchTask({prompt:J.data.prompt,title:J.data.title,taskPriority:J.data.taskPriority,taskKind:J.data.taskKind,taskDueAt:J.data.taskDueAt?new Date(J.data.taskDueAt).toISOString():void 0,sourceProjectPath:J.data.projectPath||Q.get("directory")||GO(),isolation:J.data.isolation,permissionMode:J.data.permissionMode,modelId:J.data.modelId,reasoningEffort:J.data.reasoningEffort,serviceTier:J.data.serviceTier,responseVerbosity:J.data.responseVerbosity,communicationStyle:J.data.communicationStyle,attachments:J.data.attachments,outputSchema:J.data.outputSchema});return Q.json(i4.parse(V),202)}catch(V){if(V instanceof F||V instanceof v||V instanceof LO||V instanceof rO)throw V;throw O1.error("[TaskRoutes] Failed to dispatch task:",V),new VO("Failed to dispatch task")}}),$.patch("/:sessionId",async(Q)=>{let Z;try{Z=await Q.req.json()}catch{throw new F("Invalid request body")}let J=y(l3,Z);if(!J.success)throw new F("Invalid task update");if(J.data.title===void 0&&J.data.taskPriority===void 0&&J.data.taskKind===void 0&&J.data.taskDueAt===void 0)throw new F("Task update must include at least one field");if(typeof J.data.taskDueAt==="string"&&!Number.isFinite(Date.parse(J.data.taskDueAt)))throw new F("Invalid task due date");try{let X=await O.updateTask(Q.req.param("sessionId"),{...J.data,...typeof J.data.taskDueAt==="string"?{taskDueAt:new Date(J.data.taskDueAt).toISOString()}:{}},Q.req.query("projectPath"));return Q.json(c4.parse(X))}catch(X){if(X instanceof F||X instanceof i||X instanceof v)throw X;throw O1.error("[TaskRoutes] Failed to update task:",X),new VO("Failed to update task")}}),$.post("/:sessionId/retry",async(Q)=>{try{let Z=await O.retryTask(Q.req.param("sessionId"),Q.req.query("projectPath"));return Q.json(i4.parse(Z),202)}catch(Z){if(Z instanceof F||Z instanceof i||Z instanceof v||Z instanceof LO||Z instanceof rO)throw Z;throw O1.error("[TaskRoutes] Failed to retry task:",Z),new VO("Failed to retry task")}}),$.get("/:sessionId/diff",async(Q)=>{try{let Z=await O.getTaskDiff(Q.req.param("sessionId"),Q.req.query("projectPath"));return Q.json(c3.parse(Z))}catch(Z){if(Z instanceof F||Z instanceof i||Z instanceof v)throw Z;throw O1.error("[TaskRoutes] Failed to load task diff:",Z),new VO("Failed to load task diff")}}),$.post("/:sessionId/delivery",async(Q)=>{let Z;try{Z=await Q.req.json()}catch{throw new F("Invalid request body")}let J=y(a3,Z);if(!J.success)throw new F("Invalid task delivery request");try{let X=await O.deliverTask(Q.req.param("sessionId"),J.data.action,Q.req.query("projectPath"));return Q.json(c4.parse(X))}catch(X){if(X instanceof F||X instanceof i||X instanceof v)throw X;throw O1.error("[TaskRoutes] Failed to deliver task:",X),new VO("Failed to deliver task")}}),$};import{Hono as y6}from"hono";var m6=oO(G.Object({id:G.String(),name:G.String(),subagentType:G.String(),description:G.String(),agentId:G.Optional(G.String()),status:zO(["leader","running","completed","failed","cancelled","unknown"]),result:G.Optional(G.Unknown()),stats:G.Optional(G.Unknown()),worktreePath:G.Optional(G.String())})),h6=oO(G.Object({id:G.String(),subject:G.String(),description:G.String(),status:zO(["pending","blocked","running","completed"]),owner:G.Optional(G.String()),priority:zO(["high","medium","low"]),dependsOn:G.Array(G.String()),blocks:G.Array(G.String()),result:G.Optional(G.String()),createdAt:G.String(),startedAt:G.Optional(G.String()),completedAt:G.Optional(G.String())})),uJ=oO(G.Object({name:G.String(),description:G.Optional(G.String()),status:zO(["idle","running","completed","failed","deleted"]),leadAgentId:G.String(),leadSessionId:G.Optional(G.String()),workspaceRoot:G.Optional(G.String()),peerMessagingEnabled:G.Boolean(),createdAt:G.Number(),updatedAt:G.Number(),deletedAt:G.Optional(G.Number()),members:G.Array(m6),tasks:G.Array(h6)})),o3=oO(G.Object({sessionId:G.String({minLength:1}),projectPath:G.String({minLength:1}),name:G.String({minLength:1}),description:G.Optional(G.String()),leadAgentType:G.Optional(G.String()),peerMessagingEnabled:G.Optional(G.Boolean()),members:G.Array(G.Object({name:G.String({minLength:1}),subagentType:G.String({minLength:1}),description:G.Optional(G.String()),prompt:G.String({minLength:10,maxLength:32768})}),{maxItems:32}),tasks:G.Optional(G.Array(G.Object({subject:G.String({minLength:1}),description:G.String({minLength:1}),dependsOn:G.Optional(G.Array(G.String())),assignedTo:G.Optional(G.String()),priority:G.Optional(zO(["high","medium","low"]))}),{maxItems:256}))})),t3=oO(G.Object({sessionId:G.String({minLength:1}),projectPath:G.String({minLength:1}),to:G.String({minLength:1}),message:G.String({minLength:1,maxLength:32768})})),s3=oO(G.Object({sessionId:G.String({minLength:1}),projectPath:G.String({minLength:1}),memberId:G.String({minLength:1})}));var g6=ZO("Service"),$5=()=>{let O=new y6;return O.onError(($,Q)=>{if($ instanceof _O)return Q.json($.toObject(),$.statusCode);return g6.error("[TeamRoutes] Unhandled route error:",$),Q.json(new VO("Team operation failed").toObject(),500)}),O.get("/",async($)=>{Q1();let Q=await Z1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await $1(Q.projectPath).list(Q))}),O.post("/",async($)=>{Q1();let Q=y(o3,await l4($.req));if(!Q.success)throw new F("Invalid team request");let Z=await Z1(Q.data.sessionId,Q.data.projectPath),J=await g.findSessionMetadata(Z.sessionId,Z.projectPath);return $.json(await $1(Z.projectPath).create({name:Q.data.name,description:Q.data.description,leadAgentType:Q.data.leadAgentType,owner:Z,modelId:J?.selectedModelId,peerMessagingEnabled:Q.data.peerMessagingEnabled,members:Q.data.members,tasks:Q.data.tasks}),201)}),O.get("/:teamName",async($)=>{Q1();let Q=await Z1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await $1(Q.projectPath).getSnapshot($.req.param("teamName"),Q))}),O.post("/:teamName/messages",async($)=>{Q1();let Q=y(t3,await l4($.req));if(!Q.success)throw new F("Invalid team message");let Z=await Z1(Q.data.sessionId,Q.data.projectPath),J=await $1(Z.projectPath).sendMessage({name:$.req.param("teamName"),to:Q.data.to,body:Q.data.message,owner:Z});return $.json({messages:J})}),O.post("/:teamName/tasks/claim",async($)=>{Q1();let Q=y(s3,await l4($.req));if(!Q.success)throw new F("Invalid team task claim");let Z=await Z1(Q.data.sessionId,Q.data.projectPath);return $.json({task:await $1(Z.projectPath).claimTask($.req.param("teamName"),Q.data.memberId,Z)})}),O.delete("/:teamName",async($)=>{Q1();let Q=await Z1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await $1(Q.projectPath).delete($.req.param("teamName"),{owner:Q,killRunning:!0}))}),O};function $1(O){return new O5({configDir:l1(),subagentRegistry:e3(O)})}function Q1(){if(r3().config.config?.agentTeamsEnabled!==!0)throw new LO("Agent Teams are disabled")}async function Z1(O,$){if(!O||!$)throw new F("sessionId and absolute projectPath are required");let Q;try{Q=wO($)}catch{throw new F("sessionId and local projectPath are required")}if(!await g.findSessionMetadata(O,Q))throw new i(`Session not found: ${O}`);return{sessionId:O,projectPath:Q}}async function l4(O){try{return await O.json()}catch{throw new F("Invalid request body")}}import{Hono as p6}from"hono";var q0=ZO("Service"),J1=new Map,Q5=2097152,Z5=65536;function J5(){return typeof globalThis.Bun<"u"}function Y5(O,$){return wO(O||$||GO(),"cwd")}async function v6(O,$,Q){if(J5()){let{spawn:X}=await import("bun-pty"),V=X(O,$,{name:"xterm-256color",cwd:Q.cwd,env:Q.env});return{pid:V.pid,write:(w)=>V.write(w),resize:(w,N)=>V.resize(w,N),kill:()=>V.kill(),onData:(w)=>V.onData(w),onExit:(w)=>V.onExit(w)}}let J=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:Q.cwd,env:Q.env,cols:80,rows:24});return{pid:J.pid,write:(X)=>J.write(X),resize:(X,V)=>J.resize(X,V),kill:()=>J.kill(),onData:(X)=>{J.onData(X)},onExit:(X)=>{J.onExit(X)}}}var o4=void 0,n4;if(J5())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();n4=$.upgradeWebSocket,o4=$.websocket}catch(O){q0.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function X5(O,$){let Q=`term-${Date.now()}`;q0.info(`[Terminal] New connection: ${Q}, cwd: ${O}`);let Z=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",J=Z.endsWith("sh")?["-l"]:[],X=await v6(Z,J,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),V={id:Q,process:X,cwd:O,buffer:"",subscribers:new Set};if(J1.set(Q,V),V.subscribers.add($),X.onData((w)=>{let N=!1;for(let H of V.subscribers)try{H.send(w),N=!0}catch{V.subscribers.delete(H)}if(N)return;if(V.buffer+=w,V.buffer.length>Q5)V.buffer=V.buffer.slice(-Q5)}),X.onExit(({exitCode:w})=>{q0.info(`[Terminal] Process exited: ${Q}, code: ${w}`);for(let N of V.subscribers)try{N.close()}catch{}J1.delete(Q)}),V.buffer){let w=V.buffer;V.buffer="";for(let N=0;N<w.length;N+=Z5)$.send(w.slice(N,N+Z5))}return{session:V,cleanup:()=>{if(q0.info(`[Terminal] Connection closed: ${Q}`),V.subscribers.delete($),V.subscribers.size===0){try{V.process.kill()}catch{}J1.delete(Q)}}}}function V5(O,$){O.on("connection",async(Q,Z)=>{try{let J=new URL(Z.url||"/",`http://${Z.headers.host}`);if(!J.pathname.endsWith("/terminal/ws")){Q.close();return}let X=Y5(J.searchParams.get("cwd")??void 0,$()),{session:V,cleanup:w}=await X5(X,{send:(N)=>Q.send(N),close:()=>Q.close()});Q.on("message",(N)=>{try{V.process.write(String(N))}catch(H){q0.error("[Terminal] Failed to write to PTY:",H)}}),Q.on("close",w),Q.on("error",w)}catch(J){q0.error("[Terminal] Failed to spawn PTY:",J),Q.close()}})}var z5=()=>{let O=new p6;if(O.get("/status",($)=>{let Q=Array.from(J1.values()).map((Z)=>({id:Z.id,cwd:Z.cwd}));return $.json({active:Q.length,terminals:Q})}),O.post("/kill/:terminalId",($)=>{let Q=$.req.param("terminalId"),Z=J1.get(Q);if(Z){try{Z.process.kill()}catch{}for(let J of Z.subscribers)J.close();return J1.delete(Q),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),n4)O.get("/ws",async($,Q)=>{let Z=$.req.query("cwd")??void 0,J;try{J=Y5(Z,$.get("directory"))}catch(w){let N=w instanceof Error?w.message:"cwd must reference a local workspace";return $.text(N,400)}let X;return n4(()=>{return{async onOpen(w,N){try{X=await X5(J,{send:(H)=>N.send(H),close:()=>N.close()})}catch(H){q0.error("[Terminal] Failed to spawn PTY:",H),N.close()}},onMessage(w){if(!X)return;try{X.session.process.write(String(w.data))}catch(N){q0.error("[Terminal] Failed to write to PTY:",N)}},onClose(){X?.cleanup()}}})($,Q)});else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import{Hono as u6}from"hono";var d6=G.Object({projectPath:G.String({minLength:1}),action:zO(["trust","revoke"])});function G5(O){try{return wO(O)}catch{throw new F("projectPath must reference a local workspace")}}var K5=()=>{let O=new u6;return O.get("/",async($)=>{let Q=$.req.query("projectPath");if(!Q)throw new F("projectPath query parameter is required");let Z=G5(Q);return $.json(await t4.getInstance().getStatus(Z))}),O.post("/",async($)=>{let Q=y(d6,await $.req.json());if(!Q.success)throw new F("Invalid workspace trust request");let{action:Z}=Q.data,J=G5(Q.data.projectPath),X=t4.getInstance(),V=Z==="trust"?await X.trust(J):await X.revoke(J);return await W5(),$.json({...V,reloadRequired:V.sensitiveSources>0})}),O};var CO=ZO("Service"),O$=[],Y1,L0,X1,U0,D0,x0,_5=new Map,w5=new Map,$8=new Set([".css",".html",".js",".json",".svg"]),Q8=1024,Z8=3600000;class e1 extends Error{}function J8(O){return O==="/sessions/v2"||O.startsWith("/sessions/v2/")}function Y8(O,$,Q){return new Promise((Z,J)=>{let X=[],V=0,w=()=>{O.off("data",N),O.off("end",H),O.off("error",j),$.removeEventListener("abort",T)},N=(q)=>{if(V+=q.byteLength,Q!==void 0&&V>Q){w(),O.resume(),J(new e1);return}X.push(q)},H=()=>{w(),Z(Buffer.concat(X,V))},j=(q)=>{w(),J(q)},T=()=>{w(),J($.reason)},L=O.headers["content-length"];if(Q!==void 0&&L!==void 0&&(!/^\d+$/.test(L)||Number(L)>Q)){O.resume(),J(new e1);return}if(O.on("data",N),O.once("end",H),O.once("error",j),$.addEventListener("abort",T,{once:!0}),$.aborted)T()})}function X8(O,$){if(!O)return 0;let Q=O.split(",").map((Z)=>{let[J,...X]=Z.trim().toLowerCase().split(";"),V=X.find((N)=>N.trim().startsWith("q=")),w=V?Number(V.trim().slice(2)):1;return{name:J,quality:Number.isFinite(w)?Math.max(0,Math.min(1,w)):0}});return Q.find((Z)=>Z.name===$)?.quality??Q.find((Z)=>Z.name==="*")?.quality??0}function U5(){if(X1)return;let O=()=>{g.collectStaleEmptySessions().then(($)=>{if($>0)CO.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{CO.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),X1=setInterval(O,Z8),X1.unref?.()}function H5(){if(!X1)return;clearInterval(X1),X1=void 0}function V8(O){return["br","gzip"].map((Q)=>({encoding:Q,quality:X8(O,Q)})).filter((Q)=>Q.quality>0).sort((Q,Z)=>Z.quality-Q.quality||(Q.encoding==="br"?-1:1))[0]?.encoding}function z8(O){let $=_5.get(O);if($)return $;let Q=f1(O);return _5.set(O,Q),Q}function G8(O,$,Q){let Z=`${Q}:${O}`,J=w5.get(Z);if(J)return J;let X=Q==="br"?o6($,{params:{[s6.BROTLI_PARAM_QUALITY]:5}}):t6($,{level:6});return w5.set(Z,X),X}function W8(){let O=l6(n6(import.meta.url)),$=[E0(O,"web"),E0(GO(),"dist/web"),E0(GO(),"packages/cli/dist/web")];for(let Q of $){let Z=E0(Q,"index.html");if(e4(Z)){if(f1(Z,"utf-8").includes("/assets/"))return CO.debug(`[Server] Found web dist at: ${Q}`),Q}}return null}function K8(){let O=new r6;O.onError((X,V)=>{if(CO.error("[Server] Request error:",X),X instanceof B5){let N=new rO(X.message,{resource:"workspace_agent_resources",limit:X.capacity});return V.json(N.toObject(),429)}if(X instanceof _O)return V.json(X.toObject(),X.statusCode);let w=X instanceof Error?X.message:String(X);return V.json({error:{code:"INTERNAL_ERROR",message:w}},500)}),O.use(async(X,V)=>{let w=process.env.BLADE_SERVER_PASSWORD;if(!w)return V();let N=X.req.path;if(N==="/"||N==="/favicon.svg"||N.startsWith("/assets/")||N.endsWith(".html")||N.endsWith(".js")||N.endsWith(".css"))return V();let H=X.req.header("Authorization");if(!H?.startsWith("Basic "))return X.header("WWW-Authenticate",'Basic realm="Blade Server"'),X.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let j=Buffer.from(H.slice(6),"base64").toString(),[T,L]=j.split(":"),q=process.env.BLADE_SERVER_USERNAME??"blade";if(T!==q||L!==w)return X.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return V()}),O.use(async(X,V)=>{let w=X.req.path==="/health"||X.req.path==="/global/health"||X.req.path.startsWith("/assets/");if(!w)CO.debug(`[Server] ${X.req.method} ${X.req.path}`);let N=Date.now();if(await V(),!w){let H=Date.now()-N;CO.debug(`[Server] ${X.req.method} ${X.req.path} - ${X.res.status} (${H}ms)`)}}),O.use(e6({origin(X){if(!X)return;if(X.startsWith("http://localhost:"))return X;if(X.startsWith("http://127.0.0.1:"))return X;if(X==="tauri://localhost"||X==="http://tauri.localhost")return X;if(O$.includes(X))return X;return}})),O.use(async(X,V)=>{let w=X.req.query("directory")||X.req.header("x-blade-directory")||GO();try{w=decodeURIComponent(w)}catch{}return X.set("directory",w),V()});let $,Q,Z;try{$=c2(),Q=E3(),Z=x$(),U0=$,D0=Q,x0=Z,Y1=$.recoverQueuedTasks,L0=new z4({dispatch:(X)=>$.dispatchTask(X),store:r4}),O.route("/global",M$()),O.route("/events",Z.app),O.route("/sessions/v2",Q.app),O.route("/sessions",$.app),O.route("/tasks",n3($)),O.route("/teams",$5()),O.route("/schedules",x3(r4,L0)),O.route("/configs",_$()),O.route("/permissions",l2()),O.route("/plugins",V3()),O.route("/hooks",I$()),O.route("/workspace-trust",K5()),O.route("/providers",F3()),O.route("/models",m$()),O.route("/projects",K3()),O.route("/suggestions",d3()),O.route("/terminal",z5()),O.route("/mcp",E$()),O.route("/skills",h3())}catch(X){throw D5($,Q,Z,"server-startup-failure").catch((V)=>{CO.error("[Server] Failed to clean up route controllers:",V)}),U0=void 0,D0=void 0,x0=void 0,Y1=void 0,L0=void 0,X}O.get("/health",(X)=>{return X.json({healthy:!0,version:i0()})});let J=W8();if(J)CO.info(`[Server] Serving static files from ${J}`),O.get("/favicon.svg",()=>{let X=E0(J,"favicon.svg");if(!e4(X))return new Response(null,{status:404});return new Response(f1(X),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(X)=>{let V=E0(J,X.req.path);if(!e4(V))return X.json({error:{code:"NOT_FOUND",message:`File not found: ${X.req.path}`}},404);let w=z8(V),N=a6(V).toLowerCase(),j={".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"}[N]||"application/octet-stream",T=$8.has(N)&&w.byteLength>=Q8?V8(X.req.header("Accept-Encoding")):void 0,L=T?G8(V,w,T):w;return new Response(new Uint8Array(L),{headers:{"Content-Type":j,"Content-Length":String(L.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...T?{"Content-Encoding":T}:{}}})}),O.get("/",(X)=>{let V=E0(J,"index.html"),w=f1(V,"utf-8");return X.html(w,200,{"Cache-Control":"no-cache"})}),O.get("*",(X)=>{let V=X.req.path;if(V.includes("."))return X.json({error:{code:"NOT_FOUND",message:`File not found: ${V}`}},404);let w=E0(J,"index.html"),N=f1(w,"utf-8");return X.html(N,200,{"Cache-Control":"no-cache"})});else CO.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(X)=>{return X.json({message:"Blade API Server",version:i0(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),O.all("*",(X)=>{return X.json({error:{code:"NOT_FOUND",message:`Route not found: ${X.req.path}`}},404)});return O}async function D5(O,$,Q,Z){let J=[],X;for(let N of[O,$,Q])try{J.push(N?.shutdown(Z)??Promise.resolve())}catch(H){X??=H}let w=(await Promise.allSettled(J)).find((N)=>N.status==="rejected");if(X!==void 0)throw X;if(w)throw w.reason}function _8(){let O=i6(),$=[];for(let Q of Object.keys(O)){let Z=O[Q];if(!Z)continue;for(let J of Z){if(J.internal||J.family!=="IPv4")continue;if(J.address.startsWith("172."))continue;$.push(J.address)}}return $}function F5(){return typeof globalThis.Bun<"u"}function N5(O,$){let Q=globalThis.Bun,Z=(X)=>{try{return Q.serve({hostname:$.hostname,port:X,fetch:O.fetch,idleTimeout:0,websocket:o4})}catch(V){CO.error("Failed to start Bun server:",V);return}},J=$.port===0?Z(4096)??Z(0):Z($.port);if(!J)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:J.url,port:J.port,hostname:J.hostname,stop:async()=>{J.stop(!0)}}}function w8(O,$){return new Promise((Q,Z)=>{let J=c6(async(H,j)=>{let T=new AbortController,L=()=>{if(!T.signal.aborted)T.abort("client-disconnected")},q=()=>L(),b=()=>{if(!j.writableEnded)L()};if(H.once("aborted",q),j.once("close",b),H.aborted||j.destroyed)L();try{let E=new URL(H.url||"/",`http://${H.headers.host}`),h=new Headers;for(let[u,FO]of Object.entries(H.headers))if(FO)if(Array.isArray(FO))for(let fO of FO)h.append(u,fO);else h.set(u,FO);let m;if(H.method!=="GET"&&H.method!=="HEAD")m=(await Y8(H,T.signal,J8(E.pathname)?t1:void 0)).toString();let D=new Request(E.toString(),{method:H.method,headers:h,body:m,signal:T.signal}),e=await O.fetch(D);if(j.statusCode=e.status,e.headers.forEach((u,FO)=>{j.setHeader(FO,u)}),e.body){let u=e.body.getReader(),FO=async()=>{let{done:fO,value:S}=await u.read();if(fO){j.end();return}return j.write(S),FO()};await FO()}else{let u=await e.text();j.end(u)}}catch(E){if(T.signal.aborted)return;if(E instanceof e1){j.statusCode=400,j.setHeader("content-type","application/json; charset=UTF-8"),j.setHeader("connection","close"),j.end(JSON.stringify({error:{code:"invalid_session_surface_request",message:"Session surface request is invalid",retryable:!1}}));return}CO.error("[Server] Node request error:",E),j.statusCode=500,j.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}finally{H.off("aborted",q),j.off("close",b)}}),X=new O8({noServer:!0}),V=GO();V5(X,()=>V),J.on("upgrade",(H,j,T)=>{let L;try{L=new URL(H.url||"/",`http://${H.headers.host}`)}catch{j.end(`HTTP/1.1 400 Bad Request\r
9
9
  Connection: close\r
10
10
  \r