blade-code 0.10.151 → 0.10.152

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 (43) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-67qs02fy.js → chunk-069ffeb6.js} +1 -1
  3. package/dist/{chunk-5t34fb09.js → chunk-0y8bxjwj.js} +1 -1
  4. package/dist/{chunk-xzyer86q.js → chunk-5jabe6fh.js} +1 -1
  5. package/dist/{chunk-04vgt8dm.js → chunk-68y9kcyz.js} +1 -1
  6. package/dist/{chunk-6dbw10rs.js → chunk-7mexgpjc.js} +1 -1
  7. package/dist/chunk-8g3dph9d.js +14 -0
  8. package/dist/{chunk-w42hqe61.js → chunk-9daqcc7x.js} +1 -1
  9. package/dist/{chunk-bcg6xser.js → chunk-ae8966n2.js} +1 -1
  10. package/dist/{chunk-92641trz.js → chunk-azc480af.js} +1 -1
  11. package/dist/{chunk-hje6nbwf.js → chunk-c0n0fxkt.js} +1 -1
  12. package/dist/{chunk-46g5y6rx.js → chunk-ce7e73tx.js} +1 -1
  13. package/dist/{chunk-hc610zyv.js → chunk-cvazye0h.js} +1 -1
  14. package/dist/{chunk-j2rqnazv.js → chunk-d0q5n5ea.js} +3 -3
  15. package/dist/{chunk-7pmp2exr.js → chunk-d5wbm0qg.js} +1 -1
  16. package/dist/{chunk-y8yzy5hm.js → chunk-dzeh2tx3.js} +1 -1
  17. package/dist/{chunk-znn0tmmd.js → chunk-e1j1gsr5.js} +1 -1
  18. package/dist/{chunk-7ra6t995.js → chunk-e8gmfajx.js} +1 -1
  19. package/dist/{chunk-9gq1zfyn.js → chunk-fswy6tg3.js} +1 -1
  20. package/dist/{chunk-fhzabp5e.js → chunk-fxhjbst1.js} +1 -1
  21. package/dist/chunk-g3h54s6h.js +1 -0
  22. package/dist/{chunk-cyvak7w2.js → chunk-genqngnt.js} +1 -1
  23. package/dist/{chunk-s86r4dvg.js → chunk-gtajytct.js} +1 -1
  24. package/dist/{chunk-e737c7xj.js → chunk-h1pw492p.js} +1 -1
  25. package/dist/{chunk-ren2c4ne.js → chunk-jgqk2tmr.js} +1 -1
  26. package/dist/chunk-nv1e4f05.js +1 -0
  27. package/dist/{chunk-anqqrsmh.js → chunk-p9vtz642.js} +1 -1
  28. package/dist/{chunk-ydxxmm5k.js → chunk-qmveehgt.js} +1 -1
  29. package/dist/{chunk-1xnekfd9.js → chunk-qv6s1q20.js} +1 -1
  30. package/dist/{chunk-bp81vf6p.js → chunk-sgy87nrv.js} +1 -1
  31. package/dist/{chunk-4mbv95b1.js → chunk-sj578593.js} +2 -2
  32. package/dist/{chunk-4g24tps2.js → chunk-sja01scc.js} +1 -1
  33. package/dist/{chunk-2r71jda0.js → chunk-sncepfa3.js} +1 -1
  34. package/dist/{chunk-v62dnty4.js → chunk-tq99wv62.js} +1 -1
  35. package/dist/{chunk-4pz9j7vd.js → chunk-w1e6gagm.js} +1 -1
  36. package/dist/{chunk-kg8h8wpx.js → chunk-wfynmt9r.js} +1 -1
  37. package/dist/{chunk-56m3sdrp.js → chunk-wpa74vxq.js} +1 -1
  38. package/dist/{chunk-cbsmzk4x.js → chunk-y5dbpqzw.js} +1 -1
  39. package/dist/{chunk-cw77p0s5.js → chunk-yvccs002.js} +1 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-gsq0crsx.js +0 -1
  42. package/dist/chunk-ng174ysm.js +0 -1
  43. package/dist/chunk-npjs625f.js +0 -14
@@ -1,14 +0,0 @@
1
- import{e as Z3,f as J3,g as H3,h as n0,i as B3}from"./chunk-v62dnty4.js";import{j as l1}from"./chunk-pv6cgfv1.js";import{v as c0,w as I2}from"./chunk-2r71jda0.js";import{A as f0,x as R2,y as q2,z as E2}from"./chunk-6dbw10rs.js";import{B as L2,C as Y$,D as X$,E as V$,F as V0,G as z$}from"./chunk-4pz9j7vd.js";import{$ as H2,Da as S3,J as V2,K as g1,L as E3,O as z2,P as t0,Q as y4,R as u1,S as E$,T as L4,U as W2,V as W0,W as N2,X as K2,Y as W$,Z as K1,aa as x4,ba as x0,ca as A0,fa as I1,ga as R1,ha as d3,ia as B2,ja as D2,ka as v2,la as u2,ma as d2,na as c2,oa as i2,pa as l2,qa as a2,ra as n2,sa as o2,va as Q3,ya as e3}from"./chunk-j2rqnazv.js";import{Ka as L$,Qa as pO}from"./chunk-e737c7xj.js";import{Ta as _2,Va as U2,Wa as w2,Xa as F2,bb as J4,eb as f3,fb as h4,gb as x2,hb as M2,ib as P3,jb as k3,kb as g4,lb as m3,mb as y0,nb as X3,ob as V3,pb as z3,qb as A2,rb as T2,sb as b2,tb as j2,ub as $$,vb as l4}from"./chunk-ht8epjz2.js";import{Jb as vO,Kb as o,Mb as P,Nb as G2,Yb as D4,gc as m0}from"./chunk-56m3sdrp.js";import{rc as M4}from"./chunk-wm896gnx.js";import{$c as H1,Bd as Q2,Ld as x1,Md as k0,Rc as s$,Td as b1,Ud as A4,Vd as j1,Xd as l0,Yc as r$,Zc as w4,_c as e$,_d as F4,ad as O2,dd as N4,de as X2,ee as H4,fe as B4,ge as v,qd as $2}from"./chunk-ydxxmm5k.js";import{Ee as Z2,Le as J2,Me as Y2}from"./chunk-q1rnvn85.js";import{ff as W3,jf as N3,kf as K3,lf as _3,mf as U3,nf as P4,of as w3,pf as F3}from"./chunk-fx9vm1n5.js";import{Of as v3,Sf as xO,Wf as T$,bg as aO}from"./chunk-04vgt8dm.js";import{cg as v1}from"./chunk-7xhw74hk.js";import{vg as o$}from"./chunk-7wcxjbyg.js";import{xg as h1}from"./chunk-cbsmzk4x.js";import{$g as i4,Gg as u3,Kg as p2,Og as U1,Pg as w1,Tg as V5,Wg as Q0,Xg as F1}from"./chunk-hc610zyv.js";import{sh as b$,th as t$}from"./chunk-hv8nt7wj.js";import{xh as F$,yh as d0}from"./chunk-ren2c4ne.js";import{Li as H$,Qh as D$,Qi as _1,ei as u$,hi as d$,ji as c$,ki as i$,li as R$,mi as q$,ni as Q$,ti as l$,wi as a$,yi as n$}from"./chunk-kg8h8wpx.js";import{Ti as _4}from"./chunk-sd9bze9x.js";import{Vi as c1,Yi as U4}from"./chunk-514va7ce.js";import{aj as XO}from"./chunk-jsv3e4k6.js";import{Cj as $O,Ej as h,Gj as G,Hj as nO,Jj as YO}from"./chunk-5q4z0sfr.js";import{Oj as E0}from"./chunk-0b67y4j1.js";import{Qj as M$,Rj as p$,Tj as A$,Uj as v$}from"./chunk-9kj19a8t.js";import{Wj as u0}from"./chunk-znn0tmmd.js";import{bk as c4}from"./chunk-gm2yfq3r.js";import{Ak as k1,Ik as K$,ek as d1,yk as _O}from"./chunk-7xtxvrh8.js";import{Lk as v4}from"./chunk-sdapqhj0.js";var Q8={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 Z8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as a4,readFileSync as S1}from"node:fs";import{createServer as S6}from"node:http";import{networkInterfaces as C6}from"node:os";import{dirname as f6,extname as P6,join as I0}from"node:path";import{fileURLToPath as k6}from"node:url";import{brotliCompressSync as m6,gzipSync as y6,constants as h6}from"node:zlib";import{Hono as g6}from"hono";import{cors as p6}from"hono/cors";import{WebSocketServer as v6}from"ws";var v0=$O("Service"),M5=30000,A5=new Set(["completed","failed","cancelled","interrupted"]);class Y4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??$$.getInstance(),this.tickMs=O.tickMs??M5}start(){if(this.timer)return;v0.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"||!A5.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,v0.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($){v0.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}),v0.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??T5(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:J4(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}),v0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);v0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:J4(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 T5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class WO 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 l extends WO{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends WO{constructor(O){super("BAD_REQUEST",O,400)}}class c extends WO{constructor(O){super("CONFLICT",O,409)}}class rO extends WO{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends WO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class f1 extends WO{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class gO extends WO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class JO extends WO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var N8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as b5}from"hono";var X4=$O("Service"),j5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(YO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function I5(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 Z$=()=>{let O=new b5;return O.get("/",async($)=>{try{let Q=xO();return $.json(Q?I5(Q):{})}catch(Q){return X4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=h(j5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await aO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof Q$)throw new F(Q.message);throw X4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=xO();return $.json(Q?.permissions||{})}catch(Q){return X4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as R5}from"hono";import{streamSSE as q5}from"hono/streaming";function J$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
- `;if(O.event!==void 0)$+=`event: ${O.event}
3
- `;for(let Q of O.data.split(/\r\n|\r|\n/))$+=`data: ${Q}
4
- `;if(O.retry!==void 0)$+=`retry: ${O.retry}
5
- `;return $+=`
6
- `,Buffer.byteLength($)}class W1{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??Y$,this.maxPendingBytes=O.maxPendingBytes??X$,this.serial=new z$({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??V$,sizeOf:J$,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 V0("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=J$(O),Z=this.serial.stats();if(Q>this.maxPendingBytes){this.fail(new V0("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 V0("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 V0("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 V0("closed","SSE egress is closed")}}var E5=15000,S5=$O("Service"),C5=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"]),f5=new Set(["queued","running","completed","failed","cancelled","interrupted"]),P5=new Set(["high","medium","low"]),k5=new Set(["feature","bug","maintenance","research"]);function m5(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 N1(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function y5(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}:{},...N1($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}function G$(O,$){return $&&O instanceof V0&&(O.kind==="closed"||O.kind==="aborted")}var N$=()=>{let O=new R5,$=new K1;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 W$)throw new LO;throw X}let J=!1;try{let X=q5(Q,async(V)=>{let _,B,w=!1,I,b,x=new Promise((D)=>{b=D}),R,A=()=>{if(B!==void 0)clearInterval(B),B=void 0;_?.(),_=void 0},S=(D)=>{if(R)return R;return w=!0,R=(async()=>{try{A(),I?.close(D),V.close()}finally{b()}})(),R},y=()=>{S(Z.signal.reason)};if(Z.signal.addEventListener("abort",y,{once:!0}),V.onAbort(()=>{S()}),Z.signal.aborted){await S(Z.signal.reason),Z.signal.removeEventListener("abort",y),Z.release();return}I=new W1({write:async(D)=>{await V.writeSSE(D)},onFailure:(D)=>{if(G$(D,w))return;S5.warn(`[EventRoutes] SSE egress closed: kind=${D.kind} pendingItems=${D.pendingItems??0} pendingBytes=${D.pendingBytes??0}`),S(D)}});let m=(D,r)=>{I?.observe({data:JSON.stringify({type:D,properties:r})})};_=P.subscribe((D)=>{if(!C5.has(D.type))return;if(D.type==="permission.asked"||D.type==="question.required"||D.type==="elicitation.required"){let s=D.properties.requestId;if(typeof s!=="string"||!s)return;m("interaction.pending",{sessionId:D.sessionId,projectPath:D.projectPath,interactionType:D.type==="question.required"?"question":D.type==="elicitation.required"?"elicitation":"permission",requestId:s});return}if(D.type==="interaction.resolved"){let s=D.properties.requestId;if(typeof s!=="string"||!s)return;m(D.type,{sessionId:D.sessionId,projectPath:D.projectPath,requestId:s});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 s=D.properties.title,wO=D.properties.taskPriority,bO=D.properties.taskKind,SO=D.properties.taskDueAt,VO=typeof s==="string"&&Boolean(s.trim()),O0=P5.has(String(wO)),tO=k5.has(String(bO)),hO=SO===null||typeof SO==="string"&&Number.isFinite(Date.parse(SO));if(!VO&&!O0&&!tO&&!hO)return;m(D.type,{sessionId:D.sessionId,projectPath:D.projectPath,...VO?{title:s}:{},...O0?{taskPriority:wO}:{},...tO?{taskKind:bO}:{},...hO?{taskDueAt:SO}:{}});return}if(D.type==="task.delivery"){let s=y5(D.properties.taskDelivery);if(!s)return;m(D.type,{sessionId:D.sessionId,projectPath:D.projectPath,taskDelivery:s,...D.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof D.properties.updatedAt==="string"?{updatedAt:D.properties.updatedAt}:{}});return}if(D.type==="schedule.fired"){let s=D.properties.scheduleId,wO=D.properties.firedAt;if(typeof s!=="string"||typeof wO!=="string")return;m(D.type,{scheduleId:s,firedAt:wO,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 r=D.properties.taskStatus;if(typeof r!=="string"||!f5.has(r))return;let u=m5(D.properties.taskDiffStat),UO=N1(D.properties.taskQueuePosition,1),CO=N1(D.properties.taskQueueDepth,0),f=N1(D.properties.taskConcurrencyLimit,1),ZO=N1(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:r,...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}:{},...UO!==void 0?{taskQueuePosition:UO}:{},...CO!==void 0?{taskQueueDepth:CO}:{},...f!==void 0?{taskConcurrencyLimit:f}:{},...ZO!==void 0?{taskInFlight:ZO}:{},...d!==void 0?{taskAdmissionPaused:d}:{}})});try{if(V.aborted||w)return;if(await I.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),V.aborted||w)return;if(I.finishInitialization({replayed:!1}),V.aborted||w)return;B=setInterval(()=>{if(V.aborted||w)return;I?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},E5),await x}catch(D){if(G$(D,w))return;throw D}finally{await S(),Z.signal.removeEventListener("abort",y),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 h5}from"hono";var g5=G.Object({paused:G.Boolean()}),_$=()=>{let O=new h5;return O.get("/health",($)=>{return $.json({healthy:!0,version:u0()})}),O.get("/info",($)=>{let Q=XO(),Z=xO();if(Z)x0.configure(Z.maxConcurrentTasks,Z.maxQueuedTasks,Z.maxQueuedTaskBytes);let J=x0.getStats();return $.json({version:u0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:Q,gitBranch:K$(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=h(g5,Q);if(!Z.success)throw new F("Invalid task admission control request");x0.setPaused(Z.data.paused);let J=x0.getStats();return $.json({inFlight:J.inFlight,queued:J.queued,maxConcurrent:J.maxConcurrent,maxQueued:J.maxQueued,paused:J.paused})}),O};import{Hono as p5}from"hono";var v5=G.Object({projectPath:G.String({minLength:1}),action:YO(["trust","revoke"]),expectedDigest:G.Optional(G.String())}),u5=G.Object({projectPath:G.String({minLength:1}),sessionId:G.String({minLength:1}),enabled:G.Boolean()});function V4(O){if(!O)throw new F("projectPath must be absolute");try{return _O(O)}catch{throw new F("projectPath must reference a local workspace")}}function U$(O){if(!O)throw new F("sessionId is required");try{k1(O)}catch($){throw new F($ instanceof Error?$.message:"sessionId is invalid")}return O}async function P1(O){let $=V4(O),Q=xO()?.hooks??H$.hooks,Z=await _1.getInstance().loadWorkspaceHooks($,Q,{includeBaseForCurrentWorkspace:!1});return F1($,async()=>{w1($);let J=d0.getInstance();return J.loadConfig(Z,$),await U1($),J.getConfig($)})}function w$(O,$){let Q=d0.getInstance(),Z=Q.getConfig($).enabled,J=Q.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:Q.isSessionEnabled(O,$),paused:J,configEnabled:Z}}var B$=()=>{let O=new p5;return O.get("/trust",async($)=>{let Q=$.req.query("projectPath");if(!Q)throw new F("projectPath query parameter is required");return await P1(Q),$.json(await d0.getInstance().getTrustStatus(Q))}),O.post("/trust",async($)=>{let Q=h(v5,await $.req.json());if(!Q.success)throw new F("Invalid hook trust request");let{projectPath:Z,action:J,expectedDigest:X}=Q.data;await P1(Z);let V=d0.getInstance(),_;try{_=J==="trust"?await V.trustProject(Z,X):await V.revokeProjectTrust(Z)}catch(B){if(B instanceof F$)throw new c(B.message);throw B}return $.json(_)}),O.get("/session",async($)=>{let Q=V4($.req.query("projectPath")),Z=U$($.req.query("sessionId"));return await P1(Q),$.json(w$(Z,Q))}),O.post("/session",async($)=>{let Q=h(u5,await $.req.json());if(!Q.success)throw new F("Invalid hook session request");let Z=V4(Q.data.projectPath),J=U$(Q.data.sessionId);await P1(Z);let X=d0.getInstance();if(Q.data.enabled)X.enableSession(J,Z);else X.disableSession(J,Z);return $.json(w$(J,Z))}),O};import{Hono as d5}from"hono";var z0=$O("Service");function c5(O){try{return L$(O)}catch{return[]}}function i5(O){if(!m1(O)||!m1(O.reference)||!m1(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(!m1(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 m1(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function M0(O,$){let Q=xO()?.mcpServers??{};for(let[Z,J]of Object.entries(Q)){if($&&Z!==$)continue;if(!O.getServerStatus(Z))await O.registerServer(Z,J,{connect:!1})}}var x$=()=>{let O=new d5;return O.get("/",async($)=>{try{let Q=pO.getInstance();await M0(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((_)=>_.name),completionSupported:V.client.completionSupported,tasks:V.client.tasks,resources:V.contentCatalog.resources,resourceTemplates:V.contentCatalog.resourceTemplates.map((_)=>({..._,variables:c5(_.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 z0.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=pO.getInstance();return await M0(Z,Q),await Z.connectServer(Q),$.json({success:!0})}catch(Q){return z0.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=pO.getInstance();return await M0(Z,Q),await Z.disconnectServer(Q),$.json({success:!0})}catch(Q){return z0.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=pO.getInstance();return await M0(X,Q),$.json(X.getLogSnapshot(Q,{limit:Z,afterRevision:J}))}catch(Q){return z0.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(!D$(Z.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let J=pO.getInstance();return await M0(J,Q),await J.setServerLoggingLevel(Q,Z.level),$.json({success:!0,level:Z.level})}catch(Q){return z0.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=i5(await $.req.json()),J=pO.getInstance();await M0(J,Q);let X=await J.complete(Q,Z);return $.json(X)}catch(Q){return z0.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=pO.getInstance();await M0(Z,Q);let J=await Z.beginOAuthLogin(Q);return $.json({success:!0,flowId:J.flowId,authorizationUrl:J.authorizationUrl},202)}catch(Q){return z0.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=pO.getInstance();return await M0(Z,Q),await Z.logoutOAuth(Q),$.json({success:!0})}catch(Q){return z0.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 pO.getInstance().unregisterServer(Q);let J=xO();if(J?.mcpServers){let{[Q]:X,...V}=J.mcpServers;await aO().updateConfig({mcpServers:V})}return $.json({success:!0})}catch(Q){return z0.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 pO.getInstance().registerServer(Z,J);let V=xO();return await aO().updateConfig({mcpServers:{...V?.mcpServers,[Z]:J}}),$.json({success:!0})}catch(Q){return z0.error("[McpRoutes] Failed to add MCP server:",Q),$.json({success:!1,error:Q.message},500)}}),O};import{getSupportedThinkingLevels as l5}from"@earendil-works/pi-ai";import{Hono as a5}from"hono";var y1=$O("Service");function n5(O){let $=O||XO();try{return _O($,O?"directory":"cwd")}catch(Q){throw new F(Q instanceof Error?Q.message:"directory is invalid")}}function o5(O,$,Q=b$.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:l5($),supportedServiceTiers:A$($),supportedResponseVerbosities:M$($),communicationStyles:Q,input:$.input}}function t5(O){j$(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function j$(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new F("streamIdleTimeout must be at least 1000ms")}var I$=()=>{let O=new a5;return O.get("/",async($)=>{try{let Q=xO();if(!Q)throw Error("Config not initialized");let Z=n5($.get("directory")),[J,X]=await Promise.all([h1(Z,Q),Q0(Z)]),V=J.config.models,_=V.find((b)=>b.id===J.config.currentModelId)??V[0],B=J.catalog,w=X.communicationStyles.list(),I=(b)=>o5(b,B.resolveConfig(b),w);return $.json({configured:V.map(I),current:_?I(_):null})}catch(Q){if(Q instanceof F)throw Q;y1.error("[ModelsRoutes] Failed to get models:",Q);let Z=new JO("Failed to get models");return $.json(Z.toObject(),500)}}),O.post("/",async($)=>{let Q=E0(),Z,J;try{let X=await $.req.json(),{provider:V,displayName:_,model:B,overrides:w,apiKey:I,modelProvider:b}=X;if(!V||!B)throw new F("provider and model are required");j$(w);let x;if(b){if(b.id!==V)throw new F("modelProvider.id must match the model provider");if(xO()?.modelProviders[V])throw new F(`model provider already exists: ${V}`);x={name:b.name,baseUrl:b.baseUrl,wireApi:b.wireApi,...b.apiKeyEnv?{apiKeyEnv:b.apiKeyEnv}:{}};try{Q.registerModelProvider(V,x,[B]),J=V}catch(S){throw new F(S instanceof Error?S.message:"Invalid model provider")}}else Q.getModel(V,B);if(I?.trim()){if(await Q.setApiKey(V,I.trim()),x)Z=V}let R={provider:V,displayName:_||void 0,model:B,overrides:w||void 0},A=x?await aO().addModelWithProvider(R,x):await aO().addModel(R);return $.json({success:!0,model:A})}catch(X){if(Z)await Q.credentials.delete(Z);if(J){let V=xO();Q.configureModelProviders(V?.modelProviders??{},V?.models??[])}throw y1.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,_=T$(Q);if(!_)throw new F("model config not found");if(V)E0().getModel(_.provider,V);return await aO().updateModel(Q,t5({displayName:J,overrides:X,model:V})),$.json({success:!0})}catch(Q){throw y1.error("[ModelsRoutes] Failed to update model:",Q),Q}}),O.delete("/:modelId",async($)=>{try{let Q=$.req.param("modelId");return await aO().removeModel(Q),$.json({success:!0})}catch(Q){throw y1.error("[ModelsRoutes] Failed to delete model:",Q),Q}}),O};import{Hono as A9}from"hono";import{Mutex as Q9}from"async-mutex";import{Hono as Z9}from"hono";import{streamSSE as J9}from"hono/streaming";import{LRUCache as Y9}from"lru-cache";import{nanoid as i0}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 S0 extends Error{reason;constructor(O="Session projection residency is closed"){super(O);this.reason=O;this.name="SessionProjectionResidencyClosedError"}}class G0 extends Error{key;constructor(O,$=`Session projection residency already owns key: ${O}`){super($);this.key=O;this.name="SessionProjectionResidencyConflictError"}}class z4 extends Error{deadlineAt;constructor(O){super(`Session projection close wait timed out at ${O}`);this.deadlineAt=O;this.name="SessionProjectionResidencyCloseTimeoutError"}}function s5(O,$){if(O.size!==$.size)return!1;for(let[Q,Z]of O)if(!$.has(Q)||$.get(Q)!==Z)return!1;return!0}class G4{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(!R$(O.maxResident))throw Error("Invalid max resident Session projection limit");if(!q$(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 G0(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((A,S)=>A.localeCompare(S));for(let A of Q)if(this.closings.has(A))throw new G0(A,`Session projection residency is already closing key: ${A}`);let Z=new Map,J=new Map,X=new Map,V=new Set;for(let A of Q){let S=this.reservations.get(A);if(S)this.reservations.delete(A);let y=this.residents.get(A);if(y){if(this.residents.delete(A),y.phase="closing",X.set(A,y),this.closings.set(A,y),Z.set(A,y.generation),V.add(A),y.value!==void 0){let D=this.projectSnapshot(y.value);if(D!==void 0)J.set(A,D)}continue}let m={key:A,generation:S?.generation??this.allocateGeneration(),value:void 0,pins:0,lastUsedAt:this.now(),phase:"closing"};X.set(A,m),this.closings.set(A,m),Z.set(A,m.generation)}let _={keys:Q,generations:Z,snapshots:J,entries:X,originalResidentKeys:V,waiters:new Set,state:"open"};this.closeStates.add(_),this.notifyCapacityAvailableIf(!0);let B=()=>{if(_.state==="committed")throw new S0("Session projection close set is already committed");if(_.state==="rolled_back")throw new S0("Session projection close set is already rolled back")},w=()=>{for(let A of _.entries.values())if(A.pins>0)return!1;return!0},I=()=>{if(!w())return;for(let A of _.waiters){if(A.timer!==void 0)clearTimeout(A.timer);A.removeAbortListener?.(),A.resolve()}_.waiters.clear()},b=({signal:A,deadlineAt:S}={})=>{if(_.state!=="open"||w())return Promise.resolve();if(S!==void 0&&S<=this.now())return Promise.reject(new z4(S));return new Promise((y,m)=>{let D={resolve:()=>y(),reject:m,timer:void 0,removeAbortListener:void 0};if(_.waiters.add(D),S!==void 0){let r=Math.max(0,S-this.now());D.timer=setTimeout(()=>{_.waiters.delete(D),D.removeAbortListener?.(),m(new z4(S))},r)}if(A){let r=()=>{if(_.waiters.delete(D),D.timer!==void 0)clearTimeout(D.timer);A.removeEventListener("abort",r),m(A.reason instanceof Error?A.reason:Error(String(A.reason??"AbortError")))};if(A.addEventListener("abort",r,{once:!0}),D.removeAbortListener=()=>{A.removeEventListener("abort",r)},A.aborted)r()}})},x=()=>{if(_.state==="committed")return;if(B(),!w())throw new G0(_.keys[0]??"","Session projection close set still has active pins");let A=!1;for(let S of _.keys){let y=_.entries.get(S);if(!y)continue;if(this.closings.get(S)===y){if(this.closings.delete(S),y.value!==void 0)A=!0}}_.state="committed",this.closeStates.delete(_),I(),this.notifyCapacityAvailableIf(A)},R=(A)=>{if(this.closed)throw new S0(this.closedReason);if(_.state==="committed")throw new S0("Session projection close set is already committed");if(_.state==="rolled_back"){if(!_.rollbackReplacements)return;if(!s5(_.rollbackReplacements,A))throw new G0(_.keys[0]??"","Session projection close set rollback replacements changed");return}if(!w())throw new G0(_.keys[0]??"","Session projection close set still has active pins");for(let D of _.originalResidentKeys)if(!A.has(D))throw new G0(D,`Session projection close rollback requires replacement for key: ${D}`);let S=!1,y=!1,m=this.now();for(let D of _.keys){let r=_.entries.get(D);if(!r)continue;if(this.closings.get(D)===r)this.closings.delete(D);if(!_.originalResidentKeys.has(D)){S||=r.value!==void 0;continue}let u=A.get(D);if(u===void 0){S||=r.value!==void 0;continue}if(r.value=u,r.phase="resident",r.lastUsedAt=m,this.residents.set(D,r),r.pins===0)y=!0}_.rollbackReplacements=new Map(A),_.state="rolled_back",this.closeStates.delete(_),I(),this.notifyCapacityAvailableIf(S||y)};return{keys:_.keys,generations:_.generations,snapshots:_.snapshots,waitForIdle:b,commit:x,rollback:R}}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 S0(this.closedReason)}assertKeyOpen(O){if(this.residents.has(O)||this.reservations.has(O)||this.closings.has(O))throw new G0(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 G0(O.key);if(this.closed)throw this.reservations.delete(O.key),$=!0,new S0(this.closedReason);if(this.reservations.get(O.key)!==O)throw $=!0,new G0(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 E$($.projectPath,`web-browser:${$.sessionId}`,{exposeArtifactPaths:!1}))}get(O){let $=o(O),Q=this.runtimes.get($);if(Q?.state==="live")return Q.runtime;if(Q)throw new g1("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(o(O));if($?.state==="live")await $.runtime.page({action:{kind:"reset"}})}dispose(O){let $=o(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 e5}from"hono";var S$=G.Object({action:YO(["accept","dismiss"])},{additionalProperties:!1}),r5=nO(G.Union([G.Object({kind:G.Literal("click"),dialog:G.Optional(S$)},{additionalProperties:!1}),G.Object({kind:G.Literal("click_at"),screenshotId:G.String({minLength:1,maxLength:H1}),x:G.Integer({minimum:0,maximum:N4}),y:G.Integer({minimum:0,maximum:N4}),dialog:G.Optional(S$)},{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:YO(["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:YO(["up","down","left","right"]),amount:G.Integer()},{additionalProperties:!1})])),C$=nO(G.Object({action:G.Optional(YO(["goto","back","forward","reload"])),url:G.Optional(G.String()),pageId:G.Optional(G.String()),expectedOrigin:G.Optional(G.String()),waitUntil:G.Optional(YO(["commit","domcontentloaded","load"])),timeoutMs:G.Optional(G.Integer())},{additionalProperties:!1})),f$=nO(G.Object({pageId:G.String(),snapshotId:G.String(),ref:G.Optional(G.String()),expectedOrigin:G.String(),action:r5,timeoutMs:G.Optional(G.Integer())},{additionalProperties:!1}));function P$(O,$){if(O===void 0)return;let Q=Number(O);if(!Number.isSafeInteger(Q))throw new F(`${$} must be an integer`);return Q}function O9(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 WO(O.code.toUpperCase(),O.message,$,O.details)}function k$(O){let $=new e5;$.use("*",(Z,J)=>O.withAdmission(J)),$.onError((Z,J)=>{let X=Z instanceof g1?$9(Z):Z instanceof WO?Z:new JO;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=h(C$,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=h(f$,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=P$(Z.req.query("depth"),"depth"),V=O9(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"),_=Z.req.query("expectedOrigin");if(X==="screenshot"){let I=Z.req.query("source")??"user";if(I!=="user"&&I!=="agent")throw new F("Unsupported browser screenshot source");if(I==="agent"&&(!V||!_))throw new F("Agent browser screenshots require pageId and expectedOrigin");let b={...V?{pageId:V}:{},..._?{expectedOrigin:_}:{}},x=I==="agent"?await O.captureAgentScreenshot(J,b):await O.getRuntime(J).screenshot(b);return new Response(new Uint8Array(x),{headers:{"Content-Type":"image/png","Content-Length":String(x.length),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}let B=P$(Z.req.query("limit"),"limit"),w={...V?{pageId:V}:{},..._?{expectedOrigin:_}:{}};if(X==="find"){let I=Z.req.query("text");if(!I)throw new F("text is required for browser find");return Z.json(await O.getRuntime(J).inspect({...w,target:{kind:"find",text:I,...B===void 0?{}:{limit:B}}}))}if(X!=="console"&&X!=="page-errors"&&X!=="network")throw new F("Unsupported browser inspection target");return Z.json(await O.getRuntime(J).inspect({...w,target:{kind:X,...B===void 0?{}:{limit:B}}}))}),$.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 a=$O("Service"),p1="web-pending-resume-recovery-budget-exhausted";class D1 extends Error{evidence;constructor(O){super(O.taskFailure.message);this.evidence=O;this.name="WebAgentRunFailure"}}var X9=G.Object({title:G.Optional(G.String()),projectPath:G.Optional(G.String())}),V9=A2,z9=nO(G.Object({projectPath:G.Optional(G.String()),expectedVersion:U2,operation:F2},{additionalProperties:!1})),G9=new Set(["revision_conflict","already_claimed","immutable_origin","immutable_boundary","not_found","runtime_unavailable","invalid_mutation","storage_unavailable"]);function W9(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"&&G9.has($.code)&&h(w2,$.snapshot).success}var N9=G.Object({title:G.Optional(G.String()),projectPath:G.Optional(G.String())}),K9=G.Object({projectPath:G.String()}),_9=G.Object({objective:G.String({minLength:1}),tokenBudget:G.Optional(G.Integer({minimum:1})),permissionMode:G.Optional(YO(["default","autoEdit","plan","yolo"]))}),U9=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})})]),N0,M1,Y0=new Map,U0=new Map,J0=new Map,i1=new Y9({max:100,ttl:1800000});function w9(O){let $=structuredClone({...O,createdAt:O.createdAt.toISOString(),updatedAt:O.updatedAt.toISOString()});return{...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)}}function m$(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function kO(O){if(!O)return;return Y0.get(O)??i1.get(O)}function F9(O){if(Y0.get(O.id)!==O)return;Y0.delete(O.id),i1.set(O.id,O)}function H9(O){Y0.delete(O),i1.delete(O)}function PO(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function A1(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:M4}),Q)P.publish(m$(O),"interaction.resolved",{requestId:Q.permissionId});return O.abortController.abort($),O.status="cancelled",P.publish(m$(O),"run.cancelled",{runId:O.id}),!0}function S2(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 B9(O){if(O.type.startsWith("committed.")){let $=O.properties.event;if(!$||typeof $!=="object"||Array.isArray($))return;let Q=C2($);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 D9(){let O=N0;if(O)O.accepting=!1,O.invalidateAll("route-reset");N0=void 0;for(let $ of Y0.values())A1($,"route-reset");Y0.clear();for(let $ of U0.values())$.controller.abort("route-reset");U0.clear(),i1.clear(),M1?.(),M1=void 0}function L9(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=L9(Q.tool_admission);if(Z)Q.tool_admission=Z;else delete Q.tool_admission;if(V2(O)){let V=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},_={},B=(w,I,b)=>{let x=V[w];if(typeof x==="string"&&Buffer.byteLength(x)<=I&&(!b||b.test(x)))_[w]=x};if(B("action",64),B("status",16,/^(?:ok|warning|error)$/),B("pageId",H1,/^browser_page_[a-f0-9-]+$/),B("snapshotId",H1,/^browser_snapshot_[a-f0-9-]+$/),B("origin",w4),B("candidateOrigin",w4),B("url",r$),B("title",e$),B("errorCode",64,/^browser_[a-z_]+$/),typeof V.truncated==="boolean")_.truncated=V.truncated;if(typeof V.actionApplied==="boolean"||V.actionApplied==="unknown")_.actionApplied=V.actionApplied;if(typeof V.sideEffectsUncertain==="boolean")_.sideEffectsUncertain=V.sideEffectsUncertain;if(typeof V.diagnosticCount==="number"&&Number.isSafeInteger(V.diagnosticCount)&&V.diagnosticCount>=0&&V.diagnosticCount<=s$)_.diagnosticCount=V.diagnosticCount;if(V.interaction&&typeof V.interaction==="object"&&!Array.isArray(V.interaction)){let w=V.interaction,I=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof w.action==="string"&&I.has(w.action)){let b={action:w.action};if(typeof w.ref==="string"&&Buffer.byteLength(w.ref)<=O2&&/^[a-z][a-z0-9]*$/.test(w.ref))b.ref=w.ref;let x=(R,A,S)=>typeof R==="number"&&Number.isFinite(R)&&R>=A&&R<=S;if(w.viewport&&typeof w.viewport==="object"&&!Array.isArray(w.viewport)){let R=w.viewport;if(x(R.width,1,16384)&&x(R.height,1,16384))b.viewport={width:R.width,height:R.height}}if(w.targetBox&&typeof w.targetBox==="object"&&!Array.isArray(w.targetBox)){let R=w.targetBox;if(x(R.x,-16384,32768)&&x(R.y,-16384,32768)&&x(R.width,0,16384)&&x(R.height,0,16384))b.targetBox={x:R.x,y:R.y,width:R.width,height:R.height}}_.interaction=b}}if(V.artifact&&typeof V.artifact==="object"&&!Array.isArray(V.artifact)){let w=V.artifact;if(typeof w.id==="string"&&/^[a-f0-9]{64}$/.test(w.id)&&w.sha256===w.id&&w.kind==="image"&&w.mimeType==="image/png"&&typeof w.size==="number"&&Number.isSafeInteger(w.size)&&w.size>=0&&w.size<=$2&&w.persisted===!0)_.artifact={id:w.id,sha256:w.sha256,kind:w.kind,mimeType:w.mimeType,size:w.size,persisted:!0,...typeof w.path==="string"&&Buffer.byteLength(w.path)<=8192?{path:w.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:_,...Z?{tool_admission:Z}:{}}}if(O==="Bash"){let V={},_=["message","signal","status","summary"],B=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],w=["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 b of _){let x=Q[b];if(typeof x==="string")V[b]=x.slice(0,8192)}for(let b of B){let x=Q[b];if(typeof x==="boolean")V[b]=x}for(let b of w){let x=Q[b];if(typeof x==="number"&&Number.isSafeInteger(x)&&x>=0)V[b]=x}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 b of["bash_id","shell_id"]){let x=Q[b];if(typeof x==="string"&&x.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(x))V[b]=x}if(Z)V.tool_admission=Z;let I=Q.background_shell_admission;if(I&&typeof I==="object"&&!Array.isArray(I)){let b=I;if(b.code==="background_shell_busy"&&(b.scope==="session"||b.scope==="global")&&b.retryable===!0&&Number.isSafeInteger(b.limit)&&b.limit>0)V.background_shell_admission={code:b.code,scope:b.scope,retryable:b.retryable,limit:b.limit}}return V}let J=200000,X=(V,_)=>typeof V==="number"&&Number.isSafeInteger(V)&&V>=0&&V<=_?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,_=Array.isArray(V.artifacts)?V.artifacts.slice(0,64).flatMap((B)=>{if(!B||typeof B!=="object"||Array.isArray(B))return[];let w=B,I=new Set(["text","image","audio","resource"]);if(typeof w.id!=="string"||!/^[a-f0-9]{64}$/.test(w.id)||typeof w.sha256!=="string"||w.sha256!==w.id||typeof w.kind!=="string"||!I.has(w.kind)||X(w.size,67108864)!==w.size||typeof w.persisted!=="boolean")return[];return[{id:w.id.slice(0,128),sha256:w.sha256.slice(0,128),kind:w.kind,size:w.size,persisted:w.persisted,...typeof w.mimeType==="string"?{mimeType:w.mimeType.slice(0,256)}:{},...typeof w.sourceUri==="string"?{sourceUri:w.sourceUri.slice(0,8192)}:{},...typeof w.path==="string"?{path:w.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:_}}else delete Q.mcpResult;return Q};function C2(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=A4(Q),X=j1(I1(Z,J),b1);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:R1(X),metadata:T1(Z,J.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function x9(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:R1(j1(I1(Q.toolCall.function.name,Q.result),b1)),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 P0(O,$="projectPath"){try{return _O(O,$)}catch(Q){throw new F(Q instanceof Error?Q.message:`${$} is invalid`)}}function L1(O){try{k1(O)}catch($){throw new F($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function zO(O){return{sessionId:O.id,projectPath:O.projectPath}}function B1(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 K4(O){return O.flatMap(($)=>{if(!Z2($)||$.role==="system"||$.role==="tool"&&$.name===l0)return[];let Q=$.tool_calls?.filter((V)=>!("function"in V)||V.function.name!==l0),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,_=$.name??(typeof V?.toolName==="string"?V.toolName:"unknown");if(V!==void 0&&(Object.hasOwn(V,"output")||Object.hasOwn(V,"error"))){let w=A4(V),I=j1(I1(_,w),b1);return[{...J,name:_,content:R1(I),metadata:T1(_,{...w.metadata,status:w.success?"completed":"failed"})}]}return[{...J,name:_,metadata:T1(_,V)}]}let X=Y2($.metadata);return[X?{...J,content:J2(X)}:J]})}function K0(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 w0(O){let $=await v.findSessionMetadata(O.id,O.projectPath);if($)K0(O,$)}function C0(O){let $=kO(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 mO(O,$){let Q=N0;if(Q?.accepting)return Q.resolveSessionRef(O,$);if(L1(O),$!==void 0){let J=vO({sessionId:O,projectPath:P0($)}),X=await v.findSessionMetadata(J.sessionId,J.projectPath);if(!X)throw new l("Session",O);return vO({sessionId:X.sessionId,projectPath:X.projectPath})}let Z=new Map;for(let J of await v.listSessions()){if(J.sessionId!==O)continue;let X=vO({sessionId:J.sessionId,projectPath:J.projectPath});Z.set(o(X),X)}if(Z.size===0)try{let J=await v.findSessionMetadata(O);if(!J)throw new l("Session",O);return vO({sessionId:J.sessionId,projectPath:J.projectPath})}catch(J){if(J instanceof l)throw J;if(J instanceof Error&&J.message.startsWith("Ambiguous session ID:"))throw new gO;throw J}if(Z.size>1)throw new gO;return Z.values().next().value}function y$(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
7
- `)}function h$(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 g$(O,$){return $&&O instanceof V0&&(O.kind==="closed"||O.kind==="aborted")}var f2=()=>{D9();let O=new Z9;O.onError((Y,N)=>{if(Y instanceof c0){let z=new rO("Session runtime capacity is full",{resource:Y.resource,limit:Y.limit});return N.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 N.json(z.toObject(),429)}if(Y instanceof WO)return N.json(Y.toObject(),Y.statusCode);return a.error("[SessionRoutes] Unhandled route error:",Y),N.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,_=new _4,B=new _4,w=new Q9,I=xO(),b=new I2({maxResident:I?.maxResidentSessionRuntimes??l$,idleMs:I?.sessionRuntimeIdleMs??a$}),x=new G4({maxResident:I?.maxResidentSessionProjections??u$,idleMs:I?.sessionProjectionIdleMs??d$,toSnapshot:w9}),R=new K1,A=new K1,S=setInterval(()=>{b.sweepIdle().catch((Y)=>{a.warn("[SessionRoutes] Session Runtime idle sweep failed:",Y)})},n$);S.unref?.();let y=setInterval(()=>{try{x.sweepIdle()}catch(Y){a.warn("[SessionRoutes] Session projection idle sweep failed:",Y)}},c$);y.unref?.();let m,D=new Map,r=1,u,UO=(Y)=>{let N=Y.projectionLease;Y.projectionLease=void 0,N?.release()},CO=()=>{for(let Y of D.values()){if(Y.timer)clearTimeout(Y.timer);UO(Y)}D.clear()};M1=CO;let f=async(Y)=>{let N;try{N=R.enter()}catch{throw new LO}try{return await Y()}finally{N.release()}};O.use("*",async(Y,N)=>{if(Y.req.method==="GET"||Y.req.method==="HEAD")return N();return f(N)});let ZO=(Y,N)=>_.runExclusive(o(Y),N),d=(Y,N)=>{let z=o(Y),W=D.get(z);if(!W||N!==void 0&&W.generation!==N)return;if(W.timer)clearTimeout(W.timer);UO(W),D.delete(z)},s=(Y,N)=>{let z=D.get(o(zO(Y)));return z?.generation===N.generation&&z.attempt===N.attempt&&z.inFlight&&!z.terminal},wO=(Y,N)=>{let z=o(zO(Y)),W=D.get(z);if(W){if(N?.release(),W.inFlight||W.timer||W.terminal)return}else{if(!N)throw new LO;W={attempt:0,generation:r++,inFlight:!1,projectedInputIds:new Set,projectionLease:N,startedAt:Date.now(),terminal:!1,timer:void 0},D.set(z,W)}return W.inFlight=!0,W.attempt++,{attempt:W.attempt,deadlineAt:W.startedAt+q2,generation:W.generation,projectedInputIds:W.projectedInputIds}},bO=(Y,N,z,W,K)=>{P.publish(Y,"pending.resume",{phase:N,kind:"pending_input",attempt:z,maxAttempts:R2,...K===void 0?{}:{delayMs:K,nextRetryAt:Date.now()+K},...W?{failure:{code:W.code,retryable:W.retryable,...W.resource?{resource:W.resource}:{}}}:{}})},SO=(Y,N,z,W,K,L)=>{let H=zO(Y),T=o(H),j=D.get(T);if(!j||j.generation!==N.generation)return!1;if(L)return j.inFlight=!1,j.terminal=!0,UO(j),bO(H,"exhausted",N.attempt,z.taskFailure),!1;let M=E2({sessionIdentity:T,failedAttempt:N.attempt,recoveryStartedAt:j.startedAt,workStillPending:W,evidence:z});if(M.phase!=="retry_scheduled")return j.inFlight=!1,j.terminal=!0,UO(j),bO(H,M.phase,N.attempt,z.taskFailure),!1;if(!j.projectionLease)return!1;let E=setTimeout(()=>{(async()=>{if(await K.completion,D.get(T)!==j||j.timer!==E)return;await ZO(H,async()=>{if(D.get(T)!==j||j.timer!==E)return;j.timer=void 0,j.inFlight=!1;let q=wO(Y);if(!q)return;try{await u(Y,q)}catch(C){if(D.get(T)!==j)return;let g=k0(C);j.inFlight=!1,j.terminal=!0;try{let KO=new Date().toISOString(),GO;try{GO=await v.updateSessionMetadata(Y.id,Y.projectPath,{taskStatus:"failed",taskStatusReason:g.message,taskFailure:g,taskCompletedAt:KO,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null})}catch{a.error(`[SessionRoutes] Failed to persist terminal pending input state for ${Y.id}`)}if(D.get(T)!==j||!j.terminal)return;if(Y.taskStatus="failed",Y.taskStatusReason=g.message,Y.taskFailure=g,Y.taskCompletedAt=KO,GO)K0(Y,GO);bO(H,"failed",q.attempt,g),P.publish(H,"session.error",{error:g.message,taskFailure:g}),P.publish(H,"session.status",{status:"error"})}finally{UO(j)}}})})().catch((q)=>{a.error(`[SessionRoutes] Failed to retry pending input for ${Y.id}:`,q)})},M.delayMs);return E.unref?.(),j.timer=E,j.inFlight=!1,bO(H,"retry_scheduled",N.attempt+1,z.taskFailure,M.delayMs),!0},VO=(Y,N)=>{let z=zO(Y),W=D.get(o(z));if(!W||W.generation!==N.generation)return!1;if(N.attempt>1)bO(z,"recovered",N.attempt);return d(z,N.generation),!0},O0=(Y,N)=>B.runExclusive(o(Y),N),tO=(Y)=>[...Y0.values()].some((N)=>N.sessionId===Y.sessionId&&N.projectPath===Y.projectPath&&PO(N)),hO=async(Y,N,z)=>{let W=J.get(N);if(!W)W=(async()=>{if($.get(N)===z)$.delete(N);for(let[L,H]of $)if(H===z)$.delete(L);let K=zO(Y);if(sO(K)?.id===Y.id&&!tO(K)&&!U0.has(N)&&!J0.has(N))await e1(K,"route-reset").catch(()=>{return});if(await z.dispose(),$.size===0)await pO.getInstance().disconnectAll()})().finally(()=>{if(J.get(N)===W)J.delete(N)}),J.set(N,W);await W},U=async(Y,N={})=>{let z=zO(Y),W=o(z);await J.get(W);let K=b.acquire(W);if(K){if($.get(W)!==K.value)throw K.release(),Error("Session Runtime residency identity is inconsistent");return K}if(b.owns(W))throw new c0(b.getStats().maxResident);let L=Z.get(W);if(!L){let H=N.communicationStyle??Y.communicationStyle;L=(async()=>{let T=await b.reserve(W,{surface:"web",allowEviction:!0}),j;try{j=await A0.create({sessionId:Y.id,workspaceRoot:Y.projectPath,permissionMode:N.permissionMode??Y.permissionMode??"default",...Y.reasoningEffort?{reasoningEffort:Y.reasoningEffort}:{},...Y.serviceTier?{serviceTier:Y.serviceTier}:{},...Y.responseVerbosity?{responseVerbosity:Y.responseVerbosity}:{},...H?{communicationStyle:H}:{},...H===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}}:{}});let M=j.getCurrentModelId();if(M&&(Y.selectedModelId||Y.taskModelId)&&M!==Y.selectedModelId){let C=await v.updateSessionMetadata(Y.id,Y.projectPath,{selectedModelId:M}).catch((g)=>{a.warn(`[SessionRoutes] Failed to migrate restored model for ${Y.id}:`,g);return});if(C)Y.selectedModelId=C.selectedModelId,Y.updatedAt=new Date(C.lastMessageTime)}let E=j,q=T.commit({key:W,surface:"web",value:E,canEvict:()=>!tO(z)&&!U0.has(W)&&!J0.has(W)&&!Z.has(W)&&!J.has(W)&&E.isIdleForResidency(),dispose:()=>hO(Y,W,E)});return j=void 0,$.set(W,E),{runtime:E,claimLease:()=>{if(q){let g=q;return q=void 0,g}let C=b.acquire(W);if(!C||C.value!==E)throw Error("Initialized Session Runtime lost residency");return C}}}catch(M){if(T.cancel(),j)await j.dispose().catch((E)=>{a.warn(`[SessionRoutes] Failed to dispose uncommitted Runtime for ${Y.id}:`,E)});if(M instanceof W2)throw new f1(M.reason);throw M}})(),Z.set(W,L)}try{return(await L).claimLease()}finally{if(Z.get(W)===L)Z.delete(W)}},e=async(Y,N,z={})=>{let W=await U(Y,z);try{return await N(W.value)}finally{W.release()}},r1=async(Y)=>{let N=o(zO(Y));if(!$.has(N)&&!Z.has(N)&&!await A0.hasDurableFollowUpInbox(Y.projectPath,Y.id))return H2();return e(Y,(z)=>z.getFollowUpQueueSnapshot())},J1=async(Y,N)=>{let z=o(zO(Y)),W=Z.get(z);if(W)await W.catch(()=>{return});Z.delete(z);let K=N??$.get(z);if(!K)return;if(!await b.remove(z,K))throw Error(`Session Runtime is pinned and cannot be disposed: ${z}`)},Y1=(Y,N)=>{if(N==="delete")throw new l("Session",Y.sessionId);if(N==="archive")throw new c("Session is archived");throw new LO},R0=(Y,N,z)=>{if(z.invalidatedBy)Y1(Y,z.invalidatedBy);if(X.get(N)!==z)throw new LO},g0=(Y,N)=>{let z=o(Y),W=X.get(z);if(!W)return;if(W.invalidatedBy??=N,W.cancelReservation?.(),W.cancelReservation=void 0,X.get(z)===W)X.delete(z)},X1=(Y)=>{for(let N of V)N.invalidatedBy??=Y,N.cancelReservation?.(),N.cancelReservation=void 0;X.clear()},sO=(Y)=>x.snapshot(o(Y)),p0=()=>x.snapshotAll(),e1=async(Y,N)=>{g0(Y,N);let z=o(Y);if(!sO(Y))return;let W=x.beginCloseMany([z],N);await W.waitForIdle({deadlineAt:Date.now()+i$}),W.commit()},W5=async(Y,N)=>{if(N!==void 0)return L1(Y),vO({sessionId:Y,projectPath:P0(N)});return O4(Y,N)},O4=async(Y,N)=>{if(L1(Y),N!==void 0){let W=vO({sessionId:Y,projectPath:P0(N)});if(sO(W))return W;let K=await v.findSessionMetadata(W.sessionId,W.projectPath);if(!K)throw new l("Session",Y);return vO({sessionId:K.sessionId,projectPath:K.projectPath})}let z=new Map;for(let W of p0()){if(W.id!==Y)continue;let K=zO(W);z.set(o(K),K)}for(let W of await v.listSessions()){if(W.sessionId!==Y)continue;let K=vO({sessionId:W.sessionId,projectPath:W.projectPath});z.set(o(K),K)}if(z.size===0)try{let W=await v.findSessionMetadata(Y);if(!W)throw new l("Session",Y);return vO({sessionId:W.sessionId,projectPath:W.projectPath})}catch(W){if(W instanceof l)throw W;if(W instanceof Error&&W.message.startsWith("Ambiguous session ID:"))throw new gO;throw W}if(z.size>1)throw new gO;return z.values().next().value},L0=async(Y)=>{let N=N0;if(!N?.accepting||N.acquireOrHydrateSession!==L0)throw new LO;let z=o(Y),W=x.acquire(z);if(W)return W;let K=X.get(z);if(!K){let H;H={promise:Promise.resolve().then(async()=>{let j=x.acquire(z);if(j){j.release();return}R0(Y,z,H);let M=x.reserve(z);H.cancelReservation=()=>M.cancel();try{let E=await v.findSessionMetadata(Y.sessionId,Y.projectPath);if(R0(Y,z,H),!E)throw new l("Session",Y.sessionId);let q=await v.findSessionTaskWorktree(Y.sessionId,Y.projectPath);R0(Y,z,H);let C=B1(E,q);R0(Y,z,H);let g=M.commit(C);H.cancelReservation=void 0,g.release()}catch(E){throw H.cancelReservation?.(),H.cancelReservation=void 0,E}})},K=H,X.set(z,K),V.add(K)}try{await K.promise}finally{if(V.delete(K),X.get(z)===K)X.delete(z)}let L=x.acquire(z);if(!L)throw new LO;return L},N5=async(Y,N)=>{let z=await L0(Y);try{return await N(z.value)}finally{z.release()}},C1=async(Y,N)=>{let z=await O4(Y,N);try{await v.assertSessionWritable(z.sessionId,z.projectPath)}catch(W){if(W instanceof H4)throw new c(W.message);throw W}return L0(z)},q0=(Y)=>{let N=x.acquire(Y.key);if(!N||N.generation!==Y.generation)throw N?.release(),new LO;return N},o4=async(Y)=>{let N=await L0(Y);try{return q0(N)}finally{N.release()}},iO=async(Y,N,z)=>{let W=await C1(Y,N);try{let K=W.value;return await z(K,zO(K),W)}finally{W.release()}},K5=async(Y,N)=>{let z=await C1(Y.sessionId,Y.projectPath);try{return await N(z.value,z)}finally{z.release()}},t4=async(Y,N)=>{if(Y.permissionMode===N)return;let z=await v.setSessionPermissionMode(Y.id,Y.projectPath,N);Y.permissionMode=z.permissionMode,Y.updatedAt=new Date(z.lastMessageTime),P.publish(zO(Y),"session.updated",{permissionMode:N})},V1=(Y,N,z,W)=>{if(!R.stats().accepting)throw new LO;let K=i0(12),L={id:K,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 H=W.runtimeLease.value,T=x0.admit({key:`${Y.projectPath}\x00${Y.id}`,...H.getTaskAdmissionLimits(),pendingBytes:B2({content:N,outputSchema:W.outputSchema,pendingMessages:H.getPendingSteeringMessages()}),signal:L.abortController.signal,onUpdate:(M)=>{L.status=M.state,Y.taskStatus=M.state,Y.taskQueuePosition=M.queuePosition,Y.taskQueueDepth=M.queueDepth,Y.taskConcurrencyLimit=M.maxConcurrent,L.taskAdmissionUpdate=(L.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await H.setTaskAdmission(M)}).catch((E)=>{a.warn(`[SessionRoutes] Failed to persist admission for ${Y.id}:`,E)})}});L.taskAdmission=T;let j=T.getSnapshot();L.status=j.state,Y.taskStatus=j.state,Y.taskQueuePosition=j.queuePosition,Y.taskQueueDepth=j.queueDepth,Y.taskConcurrencyLimit=j.maxConcurrent}return Y0.set(K,L),Y.currentRunId=K,L.completion=M9(L,Y,N,z,U,{pendingInputOnly:W.pendingInputOnly,preparedInputTurn:W.preparedInputTurn,goalContinuationOnly:W.goalContinuationOnly,outputSchema:W.outputSchema,taskAdmission:L.taskAdmission,runtimeLease:W.runtimeLease,projectionLease:W.projectionLease,disposeRuntime:J1,pendingResume:W.pendingResume,onPendingResumeFailure:(H,T,j,M)=>SO(Y,H,T,j,L,M),onPendingResumeSuccess:(H)=>VO(Y,H),onPendingResumeCancelled:(H)=>d(zO(Y),H.generation)}).catch((H)=>{a.error(`[SessionRoutes] Run ${K} failed:`,H)}),L},_5=async(Y)=>{let N;if(Y.outputSchema)try{N=F4(Y.outputSchema).schema}catch(p){throw new F(p instanceof Error?p.message:"Invalid output schema")}let z=v1("task",12),W=P0(Y.sourceProjectPath),K=Y.modelId?.trim(),L=xO();if(!L)throw new F("Config not initialized");let[H,T]=await Promise.all([h1(W,L),Q0(W)]);if(K&&!H.config.models.some((p)=>p.id===K))throw new F(`Task model not found: ${K}`);let j=K||H.config.models.find((p)=>p.id===H.config.currentModelId)?.id||H.config.models[0]?.id;if(!j)throw new F("No model is configured. Add or select a model before dispatching a task.");let M=H.config.models.find((p)=>p.id===j);if(!M)throw new F(`Task model not found: ${j}`);let E=Y.reasoningEffort??"off",q=Y.serviceTier??"auto",C=Y.responseVerbosity??"auto",g=Y.communicationStyle??"auto",KO,GO=T.projectRules?.staticRules(W),n=GO&&GO.files.length>0?GO.provenanceSha256:void 0;try{let p=H.catalog.resolveConfig(M);o$(p,E),v$(p,q),p$(p,C);let BO=t$(g,T.communicationStyles);KO=BO.source==="built-in"?void 0:BO.contentSha256}catch(p){throw new F(p instanceof Error?p.message:"Invalid reasoning effort")}let uO={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:j,reasoningEffort:E,serviceTier:q,responseVerbosity:C,communicationStyle:g,...KO?{communicationStyleDigest:KO}:{},...n?{projectInstructionsDigest:n}:{},...Y.attachments?{attachments:Y.attachments.map((p)=>({...p}))}:{},...N?{outputSchema:N}:{}},dO,t,FO,i,HO,lO;try{let p=await w.runExclusive(async()=>{lO=o(vO({sessionId:z,projectPath:W})),HO=x.reserve(lO);try{return await L2.createSessionTask({sessionId:z,prompt:Y.prompt,title:Y.title,taskPriority:Y.taskPriority,taskKind:Y.taskKind,taskDueAt:Y.taskDueAt,sourceProjectPath:W,isolation:Y.isolation,dispatch:uO,retriedFrom:Y.retriedFrom})}catch($0){throw HO?.cancel(),HO=void 0,$0}}),{metadata:BO}=p;if(dO=p.taskWorktree,t=B1(BO,dO),!HO)throw new LO;let cO=o(zO(t));if(lO!==cO)HO.cancel(),HO=x.reserve(cO),lO=cO;i=HO.commit(t),HO=void 0,lO=void 0;let k=zO(t);P.publish(k,"task.status",{taskStatus:BO.taskStatus,updatedAt:BO.lastMessageTime});let OO=h$(Y.prompt,Y.attachments);FO=await U(t);let NO=FO.value,jO=N?await NO.prepareInputTurn(OO,{outputSchema:N}):await NO.prepareInputTurn(OO);if(!jO.accepted)throw new c(`Task prompt was not accepted: ${jO.reason}`);if(!i)throw new LO;let qO=V1(t,OO,Y.permissionMode,{preparedInputTurn:jO,runtimeLease:FO,projectionLease:i,outputSchema:N});return i=void 0,FO=void 0,await qO.taskAdmissionUpdate,{session:C0(t),runId:qO.id,messageId:jO.messageId,status:qO.status==="queued"?"queued":"running",queuePosition:t.taskQueuePosition,queueDepth:t.taskQueueDepth,maxConcurrentTasks:t.taskConcurrencyLimit}}catch(p){if(HO?.cancel(),HO=void 0,lO=void 0,i?.release(),i=void 0,FO?.release(),FO=void 0,p instanceof Z0&&!t)throw new rO("Session projection capacity is full",{resource:p.resource,limit:p.limit,retryable:p.retryable});if((p instanceof x4||p instanceof c0||p instanceof Z0)&&t){if(dO)await W0.exit({sessionId:t.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await J1(t).catch(()=>{return}),await v.deleteSession(t.id,t.projectPath).catch(()=>{return}),new rO(p instanceof Z0?"Session projection capacity is full":p instanceof c0?"Session runtime capacity is full":"Task admission capacity is full",{resource:p.resource,limit:p.limit,...p instanceof Z0?{retryable:p.retryable}:{}})}if(t){let BO=await v.findSessionMetadata(t.id,t.projectPath).catch(()=>{return});if(!BO||BO.taskStatus==="queued"){let cO=k0(p),k=await v.updateSessionMetadata(t.id,t.projectPath,{taskStatus:"failed",taskStatusReason:cO.message,taskFailure:cO,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});t.taskStatus=k?.taskStatus??"failed",t.taskStatusReason=k?.taskStatusReason??cO.message,t.taskFailure=k?.taskFailure??cO,t.taskCompletedAt=k?.taskCompletedAt}else t.taskStatus=BO.taskStatus,t.taskStatusReason=BO.taskStatusReason,t.taskFailure=BO.taskFailure,t.taskCompletedAt=BO.taskCompletedAt}throw p}},s4=(Y)=>f(()=>_5(Y)),U5=async(Y,N)=>{let z=await mO(Y,N),W=await v.findSessionMetadata(z.sessionId,z.projectPath);if(!W)throw new l("Session",z.sessionId);if(!["failed","interrupted","cancelled"].includes(W.taskStatus))throw new c(`Task cannot be retried while status is ${W.taskStatus}`);let K=await v.findSessionTaskDispatch(z.sessionId,z.projectPath);if(!K)throw new c("Task retry payload is unavailable");return s4({prompt:K.prompt,title:W.title??K.title,taskPriority:W.taskPriority??K.taskPriority,taskKind:W.taskKind??K.taskKind,taskDueAt:W.taskDueAt,sourceProjectPath:K.sourceProjectPath,isolation:K.isolation,permissionMode:K.permissionMode,modelId:K.modelId,reasoningEffort:K.reasoningEffort,serviceTier:K.serviceTier,responseVerbosity:K.responseVerbosity,communicationStyle:K.communicationStyle,attachments:K.attachments,outputSchema:K.outputSchema,retriedFrom:z})},w5=(Y,N)=>f(()=>U5(Y,N)),F5=(Y,N,z)=>f(async()=>{let W=await mO(Y,z);if(!await v.findSessionMetadata(W.sessionId,W.projectPath))throw new l("Session",W.sessionId);let L=await v.updateSessionMetadata(W.sessionId,W.projectPath,N),H=sO(W);if(H)K0(H,L);return P.publish(W,"session.updated",{...L.title?{title:L.title}:{},...L.taskPriority?{taskPriority:L.taskPriority}:{},...L.taskKind?{taskKind:L.taskKind}:{},taskDueAt:L.taskDueAt??null}),H?C0(H):{...L,isActive:!1}}),H5=async(Y,N)=>{return iO(Y,N,async(z)=>{if(!z.taskWorktree)throw new F("Session does not have a task worktree");try{await W0.restoreSession(z.taskWorktree);let W=await W0.getDiffArtifact(z.id);if(!W)throw new c("Task diff artifact is unavailable");return{sessionId:z.id,projectPath:z.projectPath,...W}}catch(W){if(W instanceof c)throw W;throw a.error("[SessionRoutes] Failed to load task diff artifact:",W),new c("Task diff artifact is unavailable")}})},B5=async(Y,N,z)=>{let W=await mO(Y,z);return O0(W,async()=>{return K5(W,async(K)=>{if(["queued","running"].includes(K.taskStatus))throw new c(`Task artifacts cannot be delivered while status is ${K.taskStatus}`);if(K.taskDelivery?.status==="applied")throw new c("Task changes have already been applied");if(K.taskDelivery?.status==="discarded")throw new c("Task changes have already been discarded");if(!K.taskWorktree)throw new c("Task worktree is unavailable");let L=async(H,T=!1)=>{let j=await v.updateSessionMetadata(K.id,K.projectPath,{taskDelivery:H,...T?{taskWorktree:null}:{}});if(K0(K,j),T)K.taskWorktree=void 0;return P.publish(W,"task.delivery",{taskDelivery:H,...T?{taskWorktreeRemoved:!0}:{},updatedAt:j.lastMessageTime}),C0(K)};try{if(N==="discard"){try{await W0.restoreSession(K.taskWorktree)}catch(j){return a.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${K.id}:`,j),L({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:K.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let T=await W0.exit({sessionId:K.id,action:"remove",discardChanges:!0});return L({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:T.discardedFiles??0,message:"Task worktree removed"},!0)}try{await W0.restoreSession(K.taskWorktree)}catch(T){throw a.warn(`[SessionRoutes] Task worktree is unavailable for ${K.id}:`,T),new L4("artifact_unavailable","Task worktree is unavailable")}let H=await W0.apply(K.id);return L({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:H.sourceCommit,changedFiles:H.changedFiles,message:"Task changes applied to the source workspace"})}catch(H){if(H instanceof L4)throw await L({status:"conflicted",updatedAt:new Date().toISOString(),message:H.message}),new c(H.message);throw H}})})},D5=(Y,N,z)=>f(()=>B5(Y,N,z)),r4=async(Y,N)=>{let z=zO(Y),W=o(z),K=D.get(W);if(!N&&K?.terminal)return;let L=kO(Y.currentRunId);if(PO(L)){if(N)d(zO(Y),N.generation);return}let H=Y.taskIsolation&&Y.taskStatus!=="queued"&&Y.taskStatus!=="running",T=H?await A0.hasRecoverableTurn(Y.projectPath,Y.id):!1;if(H&&!T){if(N)d(zO(Y),N.generation);return}let j=await A0.hasPendingInbox(Y.projectPath,Y.id),M=!j&&await A0.hasActiveGoal(Y.projectPath,Y.id);if(!j&&!M&&!T)T=await A0.hasRecoverableTurn(Y.projectPath,Y.id);if(!j&&!M&&!T){d(zO(Y));return}if(N&&!j){d(zO(Y),N.generation);return}let E=await U(Y),q=!1,C,g;try{let KO=E.value,GO=kO(Y.currentRunId);if(PO(GO)){if(N)d(zO(Y),N.generation);return}if(j&&KO.getPendingSteeringCount()===0)await KO.reloadPendingInbox();let n=KO.getPendingSteeringCount()>0,uO=n?null:await KO.getGoal(),dO=uO?.status==="active"||uO?.status==="verifying",t=KO.getTurnRecoveryAssessment();if(t.state!=="none"&&(t.state==="requires_attention"||!n&&!dO))P.publish({sessionId:Y.id,projectPath:Y.projectPath},"turn.recovery",{assessment:t});if(t.state==="requires_attention"||H||!n&&!dO||KO.hasTurnOwner()){if(N||!n)d(zO(Y),N?.generation);return}let FO=N;if(n&&!Y.taskIsolation&&!FO){let i=await o4(z);try{FO=wO(Y,i);let HO=D.get(W);if(FO&&HO?.generation===FO.generation&&HO.projectionLease===i)g=FO,i=void 0}finally{i?.release()}}if(n&&!Y.taskIsolation&&!FO)return;if(N&&!s(Y,N))return;C=N?(()=>{let i=K?.projectionLease;if(!i)throw new LO;return q0(i)})():await o4(zO(Y)),V1(Y,"",Y.permissionMode??"default",{pendingInputOnly:n,goalContinuationOnly:dO,runtimeLease:E,projectionLease:C,pendingResume:n?FO:void 0}),C=void 0,g=void 0,q=!0}finally{if(C?.release(),g)d(z,g.generation);if(!q)E.release()}};u=async(Y,N)=>{let z;try{z=R.enter()}catch{return}try{let W=kO(Y.currentRunId);if(PO(W)){if(N)d(zO(Y),N.generation);return}if(Y.taskIsolation){await r4(Y);return}await r4(Y,N)}finally{z.release()}};let $4={accepting:!0,resolveSessionRef:O4,getProjectionSnapshot:sO,snapshotAll:p0,acquireOrHydrateSession:L0,invalidateAll:X1,resumeRecoveredInteraction:u};N0=$4;let L5=async()=>{let Y={scheduled:0,failed:0,deferred:0};if(!R.stats().accepting)return Y;let N=(await v.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 N.entries()){let K={sessionId:W.sessionId,projectPath:W.projectPath};try{if(!await A0.hasPendingInbox(W.projectPath,W.sessionId)){let T=k0("Queued task input is missing");await v.updateSessionMetadata(W.sessionId,W.projectPath,{taskStatus:"failed",taskStatusReason:T.message,taskFailure:T,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Y.failed++;continue}let L=await L0(K),H=L.value;if(L.release(),await u(H),H.currentRunId)Y.scheduled++}catch(L){if(L instanceof x4||L instanceof c0){Y.deferred+=N.length-z;break}a.warn(`[SessionRoutes] Failed to recover queued task ${W.sessionId}:`,L),Y.deferred++}}return Y};return O.route("/",k$({withAdmission:f,resolveSessionRef:async(Y,N)=>{try{let z=await W5(Y,N);return(await L0(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,N)=>{return N5(Y,(z)=>e(z,(W)=>W.captureBrowserScreenshot(N)))},resetRuntime:(Y)=>Q.reset(Y)})),O.get("/",async(Y)=>{try{let N=await v.listSessions(),z=new Set(N.filter((M)=>M.relationType==="subagent").map((M)=>o({sessionId:M.sessionId,projectPath:M.projectPath}))),W=p0().filter((M)=>!z.has(o(zO(M)))&&M.relationType!=="subagent").map((M)=>C0(M)),K=new Set(W.map((M)=>o({sessionId:M.sessionId,projectPath:M.projectPath}))),L=N.filter((M)=>{if(M.relationType==="subagent")return!1;return!K.has(o({sessionId:M.sessionId,projectPath:M.projectPath}))}),H=new Set(K),T=L.filter((M)=>{let E=o({sessionId:M.sessionId,projectPath:M.projectPath});if(H.has(E))return!1;return H.add(E),!0}),j=[...W,...T.map((M)=>({...M,isActive:!1}))];return Y.json(j)}catch(N){throw a.error("[SessionRoutes] Failed to list sessions:",N),new JO("Failed to list sessions")}}),O.get("/catalog",async(Y)=>{try{let N=Y.req.query("limit"),z=N===void 0?void 0:Number(N),W=Y.req.query("cursor"),K=Y.req.query("projectPath"),L=Y.req.query("archived");if(L!==void 0&&L!=="true"&&L!=="false")throw new F("archived must be true or false");let H=L==="true",T=await v.listSessionPage({...K?{cwd:P0(K)}:{},...W?{cursor:W}:{},...z===void 0?{}:{limit:z},includeSubagents:!1,archived:H}),j=new Map((H?[]:p0()).filter((M)=>M.relationType!=="subagent").map((M)=>[o(zO(M)),C0(M)]));return Y.json({sessions:T.sessions.map((M)=>j.get(o({sessionId:M.sessionId,projectPath:M.projectPath}))??M),...T.nextCursor?{nextCursor:T.nextCursor}:{}})}catch(N){if(N instanceof F)throw N;if(N instanceof Error&&(N.message.startsWith("Invalid session cursor")||N.message.startsWith("Session cursor scope")||N.message.startsWith("Session catalog")))throw new F(N.message);throw a.error("[SessionRoutes] Failed to list session catalog:",N),new JO("Failed to list session catalog")}}),O.post("/",async(Y)=>{try{let N=await Y.req.json(),z=h(X9,N);if(!z.success)throw new F("Invalid request body");let{title:W,projectPath:K}=z.data,L=v1("web",12),H=P0(K||Y.get("directory")||XO(),K?"projectPath":"directory"),T=vO({sessionId:L,projectPath:H}),j=await w.runExclusive(async()=>{let E=x.reserve(o(T));try{let q=await v.createSessionMetadata(L,H,{title:W,taskStatus:"completed"}),C=B1(q);return E.commit(C)}catch(q){throw E.cancel(),q}}),M=j.value;return j.release(),P.publish(T,"session.created",{}),Y.json({...C0(M),status:void 0,agentType:void 0,model:void 0})}catch(N){if(a.error("[SessionRoutes] Failed to create session:",N),N instanceof F||N instanceof WO||N instanceof Z0)throw N;throw new JO("Failed to create session")}}),O.get("/:sessionId/export",async(Y)=>{let N=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 mO(N,Y.req.query("projectPath")),K=await v.exportSessionMarkdown(W.sessionId,W.projectPath,{includeReasoning:z==="true"});return Y.body(K.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${K.filename}"`,"Content-Length":String(Buffer.byteLength(K.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":K.contentSha256,"X-Blade-Export-Activities":String(K.activityCount),"X-Blade-Export-Messages":String(K.messageCount),"X-Blade-Export-Redactions":String(K.redactionCount)})}catch(z){if(z instanceof F||z instanceof l||z instanceof gO)throw z;if(z instanceof Error&&z.message==="No conversation content to export")throw new c(z.message);throw a.error("[SessionRoutes] Failed to export session:",z),new JO("Failed to export session")}}),O.post("/:sessionId/fork",async(Y)=>{let N=Y.req.param("sessionId");try{L1(N);let z=await Y.req.json(),W=h(K9,z);if(!W.success)throw new F("Invalid request body");let K=P0(W.data.projectPath),L=v1("fork"),H,T=await w.runExclusive(async()=>{let E=await v.findSessionMetadata(N,K);if(!E)throw new l("Session",N);let q;try{q=x.reserve(o({sessionId:L,projectPath:E.projectPath}))}catch(C){if(!(C instanceof Z0))throw C}try{let C=await v.forkSession(N,{newSessionId:L,sourceProjectPath:E.projectPath,targetProjectPath:E.projectPath});if(q){let g=B1(C.metadata);H=q.commit(g)}return C}catch(C){throw q?.cancel(),C}}),j=B1(T.metadata),M=zO(j);return H?.release(),P.publish(M,"task.status",{taskStatus:T.metadata.taskStatus,...T.metadata.taskCompletedAt?{taskCompletedAt:T.metadata.taskCompletedAt}:{},updatedAt:T.metadata.lastMessageTime}),Y.json({session:T.metadata,messages:K4(T.messages)},201)}catch(z){if(z instanceof F||z instanceof l||z instanceof c)throw z;if(z instanceof X2)throw new c("Session has no durable creation record");throw a.error("[SessionRoutes] Failed to fork session:",z),new JO("Failed to fork session")}}),O.get("/:sessionId",async(Y)=>{let N=Y.req.param("sessionId");try{let z=await mO(N,Y.req.query("projectPath")),W=sO(z);if(W)return Y.json(C0(W));let K=await v.findSessionMetadata(z.sessionId,z.projectPath);if(!K)throw new l("Session",N);return Y.json(K)}catch(z){if(z instanceof F||z instanceof l||z instanceof gO)throw z;throw a.error("[SessionRoutes] Failed to get session:",z),new JO("Failed to get session")}}),O.patch("/:sessionId",async(Y)=>{let N=Y.req.param("sessionId");try{let z=await Y.req.json(),W=h(N9,z);if(!W.success)throw new F("Invalid request body");if(W.data.title===void 0)throw new F("title is required");let K=await mO(N,W.data.projectPath),L=await v.updateSessionMetadata(K.sessionId,K.projectPath,{title:W.data.title}),H=x.acquire(o(K));try{let T=H?.value;if(T)T.title=L.title??T.title,T.updatedAt=new Date(L.lastMessageTime)}finally{H?.release()}if(L.title)P.publish(K,"session.updated",{title:L.title});return Y.json({success:!0,title:L.title})}catch(z){if(a.error("[SessionRoutes] Failed to update session:",z),z instanceof F||z instanceof l||z instanceof gO)throw z;throw new JO("Failed to update session")}}),O.get("/:sessionId/rewind",async(Y)=>{return iO(Y.req.param("sessionId"),Y.req.query("projectPath"),(N)=>e(N,async(z)=>Y.json({checkpoints:await z.listRewindCheckpoints()})))}),O.post("/:sessionId/rewind",async(Y)=>{let N=h(x2,await Y.req.json());if(!N.success)throw new F("Invalid rewind request");return iO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,K)=>ZO(W,async()=>{let L=kO(z.currentRunId);if(PO(L))throw new c("Cannot rewind while a run is active");return e(z,async(H)=>{let T;try{T=await H.rewindSession(N.data)}catch(M){if(M instanceof Error&&M.message.startsWith("Cannot rewind while"))throw new c(M.message);throw M}await w0(z);let j=K4(T.messages);return P.publish(W,"session.rewound",{targetMessageId:T.checkpoint.messageId,mode:T.mode,removedTurns:T.removedTurns,restoredFiles:T.restoredFiles,messages:j}),Y.json({...T,messages:j})})}))}),O.get("/:sessionId/review",async(Y)=>{let N=Y.req.param("sessionId"),z=await mO(N,Y.req.query("projectPath")),W=await f0.list(z.projectPath,z.sessionId);return Y.json({reviews:W.map((K)=>({...K,content:K.completion?Q2(K.start,K.completion):void 0}))})}),O.post("/:sessionId/review",async(Y)=>{let N=Y.req.param("sessionId"),z=h(j2,await Y.req.json());if(!z.success)throw new F("Invalid code review request");let W=await C1(N,z.data.projectPath),K=W.value,L=zO(K),H=o(L);try{return await ZO(L,async()=>{if(PO(kO(K.currentRunId)))throw new c("Cannot start a review during an active turn");if(J0.has(H))throw new c("Session already has an active review");return e(K,async(T)=>{if(await f0.recoverInterrupted(L.projectPath,L.sessionId,T),z.data.modelId&&!T.getModelById(z.data.modelId))throw new F(`Model not found: ${z.data.modelId}`);if(z.data.modelId&&T.getCurrentModelId()!==z.data.modelId)await T.refresh({modelId:z.data.modelId});if(z.data.modelId&&K.selectedModelId!==z.data.modelId){let C=await v.updateSessionMetadata(K.id,K.projectPath,{selectedModelId:z.data.modelId});K0(K,C)}let j=new AbortController,M,E;try{M=q0(W),E=await f0.start({sessionId:L.sessionId,projectPath:L.projectPath,runtime:T,request:{kind:z.data.kind,...z.data.ref?{ref:z.data.ref}:{},...z.data.instructions?{instructions:z.data.instructions}:{}},signal:j.signal,onEvent:(C)=>{if(C.kind==="tool_start")P.publish(L,"review.tool.started",{reviewId:E?.reviewId,toolCallId:C.toolCall.id,toolName:C.toolCall.function.name});else if(C.kind==="tool_progress")P.publish(L,"review.tool.progress",{reviewId:E?.reviewId,toolCallId:C.toolCall.id,message:C.update.message.slice(0,1000)});else if(C.kind==="tool_result")P.publish(L,"review.tool.completed",{reviewId:E?.reviewId,toolCallId:C.toolCall.id,success:C.result.success})}})}catch(C){if(M?.release(),C instanceof Error&&(C.message.includes("active review")||C.message.includes("interrupted review")||C.message.includes("active turn")))throw new c(C.message);if(C instanceof Error&&(C.message.includes("review")||C.message.includes("Git")||C.message.includes("changes")||C.message.includes("ref")))throw new F(C.message);throw C}if(!E)throw new JO("Code review failed to start");await w0(K),P.publish(L,"review.started",{reviewId:E.reviewId,kind:z.data.kind}),P.publish(L,"task.status",{taskStatus:K.taskStatus,...K.taskStatusReason?{taskStatusReason:K.taskStatusReason}:{},...K.taskStartedAt?{taskStartedAt:K.taskStartedAt}:{},...K.taskPromptSummary?{taskPromptSummary:K.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let q=E.completion.then(async(C)=>{await w0(K),P.publish(L,"task.status",{taskStatus:K.taskStatus,...K.taskStatusReason?{taskStatusReason:K.taskStatusReason}:{},...K.taskFailure?{taskFailure:K.taskFailure}:{},...K.taskStartedAt?{taskStartedAt:K.taskStartedAt}:{},...K.taskCompletedAt?{taskCompletedAt:K.taskCompletedAt}:{},...K.taskPromptSummary?{taskPromptSummary:K.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),P.publish(L,"review.completed",{reviewId:E.reviewId,status:C.status,findings:C.findings.length})}).catch((C)=>{a.error(`[SessionRoutes] Code review ${E.reviewId} failed:`,C)}).finally(()=>{if(J0.get(H)?.reviewId===E.reviewId)J0.delete(H);M?.release()});return J0.set(H,{reviewId:E.reviewId,controller:j,completion:q,projectionLease:M}),Y.json({reviewId:E.reviewId,status:"running"},202)})})}finally{W.release()}}),O.get("/:sessionId/subagents",async(Y)=>{return iO(Y.req.param("sessionId"),Y.req.query("projectPath"),(N)=>e(N,(z)=>Y.json({subagents:z.listSubagents().map(u1)})))}),O.post("/:sessionId/subagents/:agentId/resume",async(Y)=>{L1(Y.req.param("agentId"));let N=M2.safeParse(await Y.req.json());if(!N.success)throw new F("Invalid subagent resume request");return iO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,K)=>ZO(W,async()=>{let L=kO(z.currentRunId);if(PO(L))throw new c("Cannot resume a subagent while a parent run is active");return e(z,async(H)=>{let T=!1,j,M=(q)=>{P.publish(W,"subagent.complete",{subagentSessionId:q.id,success:q.status==="completed",status:q.status,summary:q.result?.message?.slice(0,500),type:q.subagentType,verificationVerdict:q.result?.verificationVerdict,resumedFrom:q.resumedFrom,rootAgentId:q.rootAgentId,resumeDepth:q.resumeDepth})},E;try{E=H.resumeSubagent({agentId:Y.req.param("agentId"),prompt:N.data.prompt,onEvent:(q,C)=>{x9(W,C,q)},onCompleted:(q)=>{if(T)M(q);else j=q}})}catch(q){if(q instanceof Error&&(q.message.startsWith("Cannot resume")||q.message.startsWith("Subagent cannot")))throw new c(q.message);if(q instanceof Error&&q.message.startsWith("Subagent not found"))throw new l(q.message);throw q}if(P.publish(W,"subagent.start",{subagentSessionId:E.session.id,type:E.session.subagentType,description:E.session.description,resumedFrom:E.source.id,rootAgentId:E.session.rootAgentId,resumeDepth:E.session.resumeDepth}),T=!0,j)M(j);return Y.json({source:u1(E.source),session:u1(E.session)})})}))}),O.get("/:sessionId/goal",async(Y)=>{return iO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(N)=>Y.json({goal:await new z2(N.projectPath,N.id).get()}))}),O.put("/:sessionId/goal",async(Y)=>{let N=h(_9,await Y.req.json());if(!N.success)throw new F("Invalid goal request");return iO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,K)=>ZO(W,async()=>{let L=kO(z.currentRunId);if(PO(L))return Y.json({status:"rejected",reason:"run_active"},409);let T=N.data.permissionMode??z.permissionMode??"default";if(z.permissionMode!==T)await t4(z,T);let j=await U(z),M=!1,E;try{let q=await j.value.createGoal(N.data);P.publish(W,"goal.updated",{goal:q}),E=q0(K);let C=V1(z,"",T,{goalContinuationOnly:!0,runtimeLease:j,projectionLease:E});return M=!0,E=void 0,await C.taskAdmissionUpdate,Y.json({status:C.status==="queued"?"queued":"running",runId:C.id,goal:q,queuePosition:z.taskQueuePosition,queueDepth:z.taskQueueDepth,maxConcurrentTasks:z.taskConcurrencyLimit},202)}finally{if(E?.release(),!M)j.release()}}))}),O.patch("/:sessionId/goal",async(Y)=>{let N=h(U9,await Y.req.json());if(!N.success)throw new F("Invalid goal update");return iO(Y.req.param("sessionId"),Y.req.query("projectPath"),async(z,W,K)=>ZO(W,async()=>{let L=await U(z),H=!1,T;try{let j=L.value,M;if(N.data.action==="pause")M=await j.pauseGoal();else if(N.data.action==="edit")M=await j.editGoal(N.data.objective);else M=await j.resumeGoal();if(P.publish(W,"goal.updated",{goal:M}),M.status==="active"&&!PO(kO(z.currentRunId))){T=q0(K);let E=V1(z,"","default",{goalContinuationOnly:!0,runtimeLease:L,projectionLease:T});return H=!0,T=void 0,await E.taskAdmissionUpdate,Y.json({status:E.status==="queued"?"queued":"running",runId:E.id,goal:M,queuePosition:z.taskQueuePosition,queueDepth:z.taskQueueDepth,maxConcurrentTasks:z.taskConcurrencyLimit},202)}return Y.json({status:M.status,goal:M})}finally{if(T?.release(),!H)L.release()}}))}),O.delete("/:sessionId/goal",async(Y)=>{return iO(Y.req.param("sessionId"),Y.req.query("projectPath"),(N,z)=>e(N,async(W)=>{let K=await W.clearGoal();if(K)P.publish(z,"goal.cleared",{});return Y.json({cleared:K})}))}),O.post("/:sessionId/archive",async(Y)=>{let N=Y.req.param("sessionId");try{let z=await mO(N,Y.req.query("projectPath")),W=await v.listSessionArchiveMembers(z.sessionId,z.projectPath);for(let L of W){let H=vO({sessionId:L.sessionId,projectPath:L.projectPath}),T=sO(H);if(PO(kO(T?.currentRunId)))throw new c(`Stop session ${L.sessionId} before archiving this session tree`)}for(let L of W){let H=vO({sessionId:L.sessionId,projectPath:L.projectPath}),T=sO(H);if(T)await J1(T)}let K=await v.archiveSession(z.sessionId,z.projectPath);for(let L of W){let H=vO({sessionId:L.sessionId,projectPath:L.projectPath}),T=o(H);g0(H,"archive"),await e1(H,"archive").catch(()=>{return}),Z.delete(T),P.publish(H,"session.archived",{archiveRootId:z.sessionId,archivedAt:K.archivedAt})}if($.size===0)await pO.getInstance().disconnectAll();return Y.json({session:K,archivedSessionIds:W.map((L)=>L.sessionId)})}catch(z){if(z instanceof F||z instanceof l||z instanceof gO||z instanceof c)throw z;if(z instanceof B4)throw new c(z.message);throw a.error("[SessionRoutes] Failed to archive session:",z),new JO("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Y)=>{let N=Y.req.param("sessionId");try{let z=await mO(N,Y.req.query("projectPath")),W=await v.listSessionArchiveMembers(z.sessionId,z.projectPath),K=await v.unarchiveSession(z.sessionId,z.projectPath),L=W.filter((H)=>H.sessionId===z.sessionId||H.archivedBySessionId===z.sessionId).map((H)=>H.sessionId);for(let H of L)P.publish({sessionId:H,projectPath:z.projectPath},"session.unarchived",{archiveRootId:z.sessionId});return Y.json({session:K,restoredSessionIds:L})}catch(z){if(z instanceof F||z instanceof l||z instanceof gO)throw z;if(z instanceof B4)throw new c(z.message);throw a.error("[SessionRoutes] Failed to unarchive session:",z),new JO("Failed to unarchive session")}}),O.delete("/:sessionId",async(Y)=>{let N=Y.req.param("sessionId"),z=Y.req.query("projectPath");try{let W=await mO(N,z);d(W);let K=o(W),L=x.acquire(K),H=L?.value,T=H?.currentRunId,j=$.get(K),M=H?.taskWorktree??await v.findSessionTaskWorktree(W.sessionId,W.projectPath);L?.release();let E;if(T){let g=kO(T);if(g)A1(g),await g.completion,E=g.id}let q=J0.get(K);if(q)q.controller.abort("session-delete"),await q.completion;if(j)await j.clearGoal().catch((g)=>{a.warn("[SessionRoutes] Failed to clear session goal:",g)});if(await Q.dispose(W),await v.deleteSession(W.sessionId,W.projectPath),g0(W,"delete"),E)H9(E);await e1(W,"delete").catch(()=>{return}),Z.delete(K),P.publish(W,"session.deleted",{});let C=$.get(K);if(C){if(!await b.remove(K,C))throw new c("Session Runtime is still active and cannot be deleted")}if(M)try{await W0.restoreSession(M),await W0.exit({sessionId:W.sessionId,action:"remove",discardChanges:!0})}catch(g){a.warn(`[SessionRoutes] Failed to remove deleted task worktree ${W.sessionId}:`,g)}return Y.json({success:!0})}catch(W){if(a.error("[SessionRoutes] Failed to delete session:",W),W instanceof F||W instanceof l||W instanceof gO)throw W;throw new JO("Failed to delete session")}}),O.get("/:sessionId/message",async(Y)=>{let N=Y.req.param("sessionId");try{let z=await mO(N,Y.req.query("projectPath")),W=await v.loadSession(z.sessionId,z.projectPath);return Y.json(K4(W))}catch(z){if(a.error("[SessionRoutes] Failed to get messages:",z),z instanceof F||z instanceof l||z instanceof gO)throw z;throw new JO("Failed to get messages")}}),O.get("/:sessionId/follow-ups",async(Y)=>{return iO(Y.req.param("sessionId"),Y.req.query("projectPath"),(N,z)=>ZO(z,async()=>Y.json(await r1(N))))}),O.post("/:sessionId/follow-ups/mutate",async(Y)=>{let N=z9.safeParse(await Y.req.json());if(!N.success)throw new F("Invalid follow-up queue mutation");return iO(Y.req.param("sessionId"),N.data.projectPath??Y.req.query("projectPath"),(z,W)=>ZO(W,async()=>{try{return await e(z,async(K)=>{let L={expectedVersion:N.data.expectedVersion,operation:N.data.operation},H=await K.mutateFollowUpQueue(L);if(H.snapshot.version!==L.expectedVersion)P.publish(W,"follow_up.queue.changed",{queue:H.snapshot});return Y.json(H)})}catch(K){if(!W9(K))throw K;let L=K.code==="not_found"?404:K.code==="invalid_mutation"?400:K.code==="storage_unavailable"||K.code==="runtime_unavailable"?503:409;return Y.json({error:{code:K.code,message:K.message},snapshot:K.snapshot},L)}}))}),O.get("/:sessionId/events",async(Y)=>{let N=Y.req.param("sessionId"),z;try{z=A.enter(Y.req.raw.signal)}catch{throw new LO}let W=!1;try{let K=await mO(N,Y.req.query("projectPath"));try{await v.assertSessionWritable(K.sessionId,K.projectPath)}catch(q){if(q instanceof H4)throw new c(q.message);throw q}let L=await L0(K),H=L.value,T=Y.req.header("Last-Event-ID")??Y.req.query("lastEventId"),j=T?Number.parseInt(T,10):Number.NaN,M=Number.isInteger(j)?j+1:void 0,E=J9(Y,async(q)=>{let g=new Set,KO,GO,n=!1,uO,dO,t=new Promise((k)=>{dO=k}),FO,i=new Set,HO=(k)=>{let OO=k;return g.add(OO),k.finally(()=>{g.delete(OO)})},lO=()=>{if(KO?.(),KO=void 0,GO!==void 0)clearInterval(GO),GO=void 0},p=(k)=>{if(FO)return FO;return n=!0,FO=(async()=>{try{lO(),uO?.close(k),q.close()}finally{dO()}})(),FO},BO=()=>{p(z.signal.reason)},cO=async(k)=>{await p(k),await Promise.allSettled([...g]),z.signal.removeEventListener("abort",BO),z.release()};if(z.signal.addEventListener("abort",BO,{once:!0}),q.onAbort(()=>{p()}),z.signal.aborted){await cO(z.signal.reason);return}uO=new W1({write:async(k)=>{await q.writeSSE(k)},onFailure:(k)=>{if(g$(k,n))return;a.warn(`[SessionRoutes] SSE egress closed for ${K.sessionId}: kind=${k.kind} pendingItems=${k.pendingItems??0} pendingBytes=${k.pendingBytes??0}`),p(k)}}),KO=P.subscribe((k)=>{if(n)return;if(k.sessionId!==K.sessionId||k.projectPath!==K.projectPath)return;let OO=k.properties.requestId;if((k.type==="permission.asked"||k.type==="question.required"||k.type==="elicitation.required")&&typeof OO==="string"){if(i.has(OO))return;i.add(OO)}if(k.type==="subagent.completion.queued"){let jO=ZO(K,()=>u(H)).catch((qO)=>{a.error(`[SessionRoutes] Failed to wake background completion for ${H.id}:`,qO)});HO(jO)}if(k.type==="team.message.received"&&typeof k.properties.teamName==="string"&&typeof k.properties.messageId==="string"&&typeof k.properties.content==="string"&&K2(k.properties.metadata,{messageId:k.properties.messageId,teamName:k.properties.teamName})){let jO=k.properties.teamName,qO=k.properties.messageId,$0=k.properties.content,AO=k.properties.metadata,DO=ZO(K,async()=>{let IO=await U(H),z1=!1;try{let X0=await IO.value.enqueueSteering($0,{allowBeforeTurn:!0,messageId:qO,origin:"team_message",metadata:AO});if(!X0.accepted)return;if(X0.queue&&!X0.duplicate)P.publish(K,"follow_up.queue.changed",{queue:X0.queue});await new N2(jO,d1()).markDelivered([qO]),z1=X0.delivery==="next_turn"}finally{IO.release()}if(!z1)return;await u(H).catch((X0)=>{a.error(`[SessionRoutes] Failed to wake teammate delivery for ${H.id}:`,X0)})}).catch((IO)=>{a.error(`[SessionRoutes] Failed to deliver teammate message for ${H.id}:`,IO)});HO(DO)}if(k.type==="subagent.completion.queued"||k.type==="team.message.received")return;let NO=B9(k);if(NO)uO?.observe(NO,k.seq)});try{if(q.aborted||n)return;let k=kO(H.currentRunId),OO=await ZO(K,()=>r1(H)),NO=PO(k)?await U(H):void 0;try{let AO=NO?.value,DO=AO?.getPendingSteeringCount()??0;await uO.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:K.sessionId,projectPath:K.projectPath,timestamp:Date.now(),status:PO(k)?k.status:"idle",runId:PO(k)?k.id:void 0,queued:DO,pendingInputDelivery:DO>0?AO?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:AO?.getRecoveredSteeringCount()??0,followUpQueue:OO,providerRecovery:AO?.getProviderRecoveryProjection()??null,turnActivity:AO?.getTurnActivityProjection()??null}})})}finally{NO?.release()}if(q.aborted||n)return;if(M!==void 0){if(await G2.for(K.sessionId,K.projectPath).replay({onCommitted:async(DO)=>{if(q.aborted||n)return;let IO=C2(DO);if(!IO||IO.seq===void 0)return;await uO.writeReplay({...typeof DO.seq==="number"?{id:String(DO.seq)}:{},data:JSON.stringify({type:IO.type,...IO.seq!==void 0?{seq:IO.seq}:{},properties:{...IO.properties,sessionId:K.sessionId,projectPath:K.projectPath}})},IO.seq)}},M),q.aborted||n)return}if(uO.finishInitialization({replayed:M!==void 0}),q.aborted||n)return;if(!k&&!J0.has(o(K))){let DO=(await f0.list(K.projectPath,K.sessionId)).some((IO)=>IO.completion===void 0)?await e(H,(IO)=>f0.recoverInterrupted(K.projectPath,K.sessionId,IO)):void 0;if(DO)await w0(H),P.publish(K,"review.completed",{reviewId:DO.reviewId,status:DO.status,findings:0,recovered:!0})}if(q.aborted||n)return;if(!k)await m0.recoverResponded(K.projectPath,K.sessionId);if(q.aborted||n)return;let jO=k?void 0:await m0.findPending(K.projectPath,K.sessionId),qO=k?.pendingPermission??(jO?{permissionId:jO.request.requestId,details:m0.confirmationDetails(jO),resolve:()=>{return}}:void 0);if(qO){i.add(qO.permissionId);let AO=S2(qO,!0);uO.observe({data:JSON.stringify({type:AO.type,properties:{...AO.properties,sessionId:K.sessionId,projectPath:K.projectPath}})})}if(q.aborted||n)return;let $0=u(H).catch(async(AO)=>{if(AO instanceof f1){await w0(H).catch(()=>{return});let DO=H.taskFailure?.code==="workspace_unavailable"?H.taskFailure:x1("workspace_unavailable");H.taskStatus="failed",H.taskStatusReason=DO.message,H.taskFailure=DO,P.publish(K,"session.error",{error:DO.message,taskFailure:DO}),P.publish(K,"session.status",{status:"error"})}a.error(`[SessionRoutes] Failed to resume pending input for ${N}:`,AO)});if(HO($0),q.aborted||n)return;GO=setInterval(()=>{if(q.aborted||n)return;uO?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await t}catch(k){if(g$(k,n))return;throw k}finally{await cO()}});return W=!0,L.release(),E}catch(K){if(!W)z.release();throw K}}),O.post("/:sessionId/message",async(Y)=>{let N=Y.req.param("sessionId"),z=await Y.req.json(),W=h(V9,z);if(!W.success)throw new F("Invalid message format");let{content:K,attachments:L,modelId:H,reasoningEffort:T,serviceTier:j,responseVerbosity:M,communicationStyle:E,permissionMode:q,projectPath:C,outputSchema:g}=W.data,KO;if(g)try{KO=F4(g).schema}catch(p){throw new F(p instanceof Error?p.message:"Invalid output schema")}let GO=E;if(Buffer.byteLength(K,"utf8")>U4)throw new F(`Message text exceeds the ${U4}-byte limit`);let n=H?.trim();if((L??[]).reduce((p,BO)=>p+(typeof BO.content==="string"?Buffer.byteLength(BO.content):0),0)>c1)throw new F("Message attachments exceed the 5 MiB limit");let dO=q,t=h$(K,L),FO=await C1(N,C??Y.req.query("projectPath")),i=FO.value,HO=zO(i),lO=dO??i.permissionMode??"default";try{return await ZO(HO,async()=>{let p=kO(i.currentRunId);if(PO(p)){if(KO)throw new c("Wait for the active turn to finish before setting an output schema");return e(i,async(OO)=>{if(n&&!OO.getModelById(n))throw new F(`Model not found: ${n}`);if(n&&OO.getCurrentModelId()!==n)throw new c("Wait for the active turn to finish before switching models");if(T&&OO.getReasoningConfiguration().selection!==T)throw new c("Wait for the active turn to finish before switching reasoning effort");if(j&&OO.getServiceTierConfiguration().selection!==j)throw new c("Wait for the active turn to finish before switching service tier");if(M&&OO.getResponseVerbosityConfiguration().selection!==M)throw new c("Wait for the active turn to finish before switching response verbosity");if(GO&&OO.getCommunicationStyleConfiguration().selection!==GO)throw new c("Wait for the active turn to finish before switching communication style");if(dO&&i.permissionMode!==dO)throw new c("Wait for the active turn to finish before switching permission mode");let NO=await OO.enqueueSteering(t,{allowBeforeTurn:!0});if(!NO.accepted)return Y.json({status:"rejected",reason:NO.reason??"turn_unavailable"},409);let jO=NO.messageId??i0(12),qO=NO.queued,$0=NO.queue??await OO.getFollowUpQueueSnapshot(),AO=NO.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(P.publish(HO,AO,{runId:p.id,messageId:jO,queued:qO}),!NO.duplicate)P.publish(HO,"follow_up.queue.changed",{queue:$0});if(NO.delivery==="next_turn"&&p.status!=="running"&&p.status!=="waiting_permission")u(i).catch((DO)=>{a.error(`[SessionRoutes] Failed to wake queued follow-up for ${N}:`,DO)});if(NO.delivery==="next_turn")p.pendingFollowUpRequested=!0;return Y.json({runId:p.id,messageId:jO,status:NO.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:qO,followUpQueue:$0},202)})}if(d(HO),i.permissionMode!==lO)await t4(i,lO);let BO=await U(i,{permissionMode:lO,...GO&&!GO.includes(":")?{communicationStyle:GO}:{}}),cO=!1,k;try{let OO=BO.value;if(n&&!OO.getModelById(n))throw new F(`Model not found: ${n}`);if(T)try{OO.resolveReasoningConfiguration(T,n)}catch(RO){throw new F(RO instanceof Error?RO.message:"Invalid reasoning effort")}if(j)try{OO.resolveServiceTierConfiguration(j,n)}catch(RO){throw new F(RO instanceof Error?RO.message:"Invalid service tier")}if(M)try{OO.resolveResponseVerbosityConfiguration(M,n)}catch(RO){throw new F(RO instanceof Error?RO.message:"Invalid response verbosity")}let NO=GO?OO.resolveCommunicationStyleConfiguration(GO):void 0;if(NO?.source!==void 0&&NO.source!=="built-in"&&!NO.contentSha256)throw new F("Custom communication style has no provenance");let jO=OO.getCurrentModelId(),qO=OO.getReasoningConfiguration(),$0=OO.getServiceTierConfiguration(),AO=OO.getResponseVerbosityConfiguration(),DO=OO.getCommunicationStyleConfiguration(),IO=Boolean(n)&&jO!==n,z1=Boolean(T)&&qO.selection!==T,X0=Boolean(j)&&$0.selection!==j,e4=Boolean(M)&&AO.selection!==M,O$=Boolean(GO)&&DO.selection!==GO;if(IO||z1||X0||e4||O$)await OO.refresh({...n?{modelId:n}:{},...T?{reasoningEffort:T}:{},...j?{serviceTier:j}:{},...M?{responseVerbosity:M}:{},...GO?{communicationStyle:GO}:{}});let Q4={...n&&i.selectedModelId!==n?{selectedModelId:n}:{},...T&&i.reasoningEffort!==T?{reasoningEffort:T}:{},...j&&i.serviceTier!==j?{serviceTier:j}:{},...M&&i.responseVerbosity!==M?{responseVerbosity:M}:{},...NO&&(i.communicationStyle!==GO||i.communicationStyleDigest!==NO.contentSha256)?{communicationStyle:GO,communicationStyleDigest:NO.source==="built-in"?null:NO.contentSha256}:{}};if(Object.keys(Q4).length>0)try{let RO=await v.updateSessionMetadata(i.id,i.projectPath,Q4);i.permissionMode=RO.permissionMode,i.selectedModelId=RO.selectedModelId,i.reasoningEffort=RO.reasoningEffort,i.serviceTier=RO.serviceTier,i.responseVerbosity=RO.responseVerbosity,i.communicationStyle=RO.communicationStyle,i.communicationStyleDigest=RO.communicationStyleDigest,i.updatedAt=new Date(RO.lastMessageTime),P.publish(HO,"session.updated",Q4)}catch(RO){if(IO||z1||X0||e4||O$)await OO.refresh({...jO?{modelId:jO}:{},reasoningEffort:qO.selection,serviceTier:$0.selection,responseVerbosity:AO.selection,communicationStyle:DO.selection}).catch((x5)=>a.error("[SessionRoutes] Failed to roll back non-durable model settings:",x5));throw RO}let G1=KO?await OO.prepareInputTurn(t,{outputSchema:KO}):await OO.prepareInputTurn(t);if(!G1.accepted)return Y.json({status:"rejected",reason:G1.reason},G1.reason==="queue_full"?429:409);k=q0(FO);let Z4=V1(i,t,lO,{preparedInputTurn:G1,outputSchema:KO,runtimeLease:BO,projectionLease:k});return cO=!0,k=void 0,await Z4.taskAdmissionUpdate,Y.json({runId:Z4.id,messageId:G1.messageId,status:Z4.status==="queued"?"queued":"running",queuePosition:i.taskQueuePosition,queueDepth:i.taskQueueDepth,maxConcurrentTasks:i.taskConcurrencyLimit},202)}finally{if(k?.release(),!cO)BO.release()}})}finally{FO.release()}}),O.post("/:sessionId/side-question",async(Y)=>{let N=Y.req.param("sessionId"),z=h(b2,await Y.req.json());if(!z.success)throw new F("Invalid side conversation request");return iO(N,z.data.projectPath??Y.req.query("projectPath"),(W)=>e(W,async(K)=>{let L=await K.askSideQuestion(z.data.question,{signal:Y.req.raw.signal});return Y.json({...L,...K.getCurrentModelId()?{modelId:K.getCurrentModelId()}:{}})}))}),O.post("/:sessionId/shell",async(Y)=>{let N=Y.req.param("sessionId"),z=h(T2,await Y.req.json());if(!z.success)throw new F("Invalid user shell command");return iO(N,z.data.projectPath??Y.req.query("projectPath"),(W,K,L)=>{let H=o(K);return ZO(K,async()=>{if(U0.has(H))throw new c("A user shell command is already running in this Session");let T=await U(W),j=q0(L),M=T.value,E=new AbortController,q,C=new Promise((g)=>{q=g});U0.set(H,{controller:E,completion:C,projectionLease:j});try{let g=await M.executeUserShellCommand(z.data.command,{signal:E.signal});await w0(W);let KO=kO(W.currentRunId);if(g.delivery==="next_turn"&&PO(KO))KO.pendingFollowUpRequested=!0;if(g.queue)P.publish(K,"follow_up.queue.changed",{queue:g.queue});return Y.json({executionId:g.executionId,messageId:g.messageId,record:g.record,auxiliary:g.auxiliary,...g.delivery?{delivery:g.delivery}:{},...g.queued!==void 0?{queued:g.queued}:{}})}finally{U0.delete(H),q(),T.release(),j.release()}})})}),O.post("/:sessionId/abort",async(Y)=>{let N=Y.req.param("sessionId"),z=await mO(N,Y.req.query("projectPath"));d(z);let W=sO(z);if(W?.currentRunId){let H=kO(W.currentRunId);if(H)A1(H),await H.completion}let K=U0.get(o(z));if(K)K.controller.abort("user-cancel"),await K.completion;let L=J0.get(o(z));if(L)L.controller.abort("user-cancel"),await L.completion;return Y.json({success:!0})}),O.get("/:sessionId/status",async(Y)=>{let N=Y.req.param("sessionId"),z=await mO(N,Y.req.query("projectPath")),W=sO(z),K=J0.get(o(z));if(K)return Y.json({sessionId:N,projectPath:z.projectPath,reviewId:K.reviewId,status:"reviewing"});if(!W?.currentRunId)return Y.json({sessionId:N,projectPath:z.projectPath,status:"idle"});let L=kO(W.currentRunId);return Y.json({sessionId:N,projectPath:z.projectPath,runId:W.currentRunId,status:L?.status==="attention_required"?"idle":L?.status??"idle"})}),{app:O,dispatchTask:s4,retryTask:w5,updateTask:F5,getTaskDiff:H5,deliverTask:D5,recoverQueuedTasks:L5,getRuntimeResidencyStats:()=>b.getStats(),getProjectionResidencyStats:()=>x.getStats(),getCoordinationStats:()=>({messageSubmissions:_.getStats(),taskDeliveries:B.getStats()}),getSseConnectionStats:()=>A.stats(),shutdown:(Y="server-shutdown")=>{if(m)return m;R.close(Y);let N=A.shutdown(Y);$4.accepting=!1,X1("server-shutdown");let z=Promise.allSettled([...V].map((W)=>W.promise));return clearInterval(S),clearInterval(y),CO(),m=(async()=>{let W,K=async(M)=>{let E=await Promise.allSettled(M);for(let q of E)if(q.status==="rejected")W??=q.reason},L=new Set,H=()=>{for(let M of Y0.values()){if(M.completion)L.add(M.completion);if(PO(M))A1(M,Y)}for(let M of U0.values())M.controller.abort(Y),L.add(M.completion);for(let M of J0.values())M.controller.abort(Y),L.add(M.completion)},T=R.waitForIdle(),j=!1;T.then(()=>{j=!0});while(!j)H(),await Promise.race([T,new Promise((M)=>setImmediate(M))]);if(await T,H(),await K([...L]),await z,await K([...Z.values()]),H(),await K([...L]),await K([N]),await K([...Z.values()]),await K([b.disposeAll()]),$.clear(),await K([...J.values()]),await K([Q.disposeAll()]),await K([pO.getInstance().disconnectAll()]),Z.clear(),J.clear(),X.clear(),V.clear(),N0===$4)N0=void 0;if(M1===CO)M1=void 0;if(W!==void 0)throw W})(),m}}};async function M9(O,$,Q,Z,J,X={}){let{abortController:V,sessionId:_,id:B}=O,w=X.preparedInputTurn?.messageId??i0(12),b=X.pendingInputOnly===!0||X.preparedInputTurn?.mode==="pending"||X.goalContinuationOnly===!0?void 0:i0(12),x=X.runtimeLease,R=X.projectionLease,A,S,y=!1,m=!1,D,r=zO($),u=X.pendingResume?.projectedInputIds??new Set,UO=(d)=>{if(u.has(d))return;if(u.size>=_2){let s=u.values().next().value;if(s!==void 0)u.delete(s)}u.add(d)},CO=async(d)=>{let s=d.metadata?.recoveryAttention;if(!s||!A)return!1;if(X.preparedInputTurn)await A.finishTurn(X.preparedInputTurn.handle,{preserveStartupRecovery:!0,outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}}).catch(()=>{return});let wO=`Turn recovery requires attention: ${s.reason}`,bO=await A.setTaskStatus("interrupted",wO).catch(()=>{return});if(bO)K0($,bO);else $.taskStatus="interrupted",$.taskStatusReason=wO,$.taskCompletedAt=void 0;return O.status="attention_required",f("session.status",{status:"idle"}),!0},f=(d,s)=>{P.publish(r,d,s)},ZO=async()=>{let d=String(V.signal.reason||"Task run cancelled");if($.taskIsolation){if(!x)x=await J($).catch(()=>{return});let s=A??x?.value;if(d==="user-cancel")await s?.discardPendingInput().catch((bO)=>{a.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,bO)});let wO=await s?.setTaskStatus("cancelled",d).catch(()=>{return});if(wO)K0($,wO);else await w0($).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(p1),new D1({taskFailure:x1("timeout"),outputStarted:!1,toolExecutionStarted:!1,toolCallsCount:0});else D=setTimeout(()=>{V.abort(p1);let e=O.pendingPermission;if(O.pendingPermission=void 0,e?.resolve({approved:!1,reason:M4}),e)f("interaction.resolved",{requestId:e.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)f("message.created",{messageId:w,role:"user",content:y$(Q)});if(f("session.status",{status:"running"}),b)f("message.created",{messageId:b,role:"assistant",content:""});x??=await J($),A=x.value;let d=A,s=Boolean(X.outputSchema??d.getPendingSteeringMessages().find((U)=>U.outputSchema)?.outputSchema);S=await D2.createWithRuntime(d,{sessionId:_,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let wO=async(U)=>{let e=U.interactionRequestId??i0(12),r1=300000;O.status="waiting_permission";let J1=new Promise((X1)=>{let sO=setTimeout(()=>{a.warn(`[SessionRoutes] Permission ${e} timed out after 300000ms`),f("permission.timeout",{requestId:e}),X1({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:e,resolve:(p0)=>{clearTimeout(sO),X1(p0)},details:U}}),Y1=O.pendingPermission;if(!Y1)throw Error("Permission request was not registered");let R0=S2(Y1);f(R0.type,R0.properties),a.info(`[SessionRoutes] Permission request created: ${e}, runId: ${B}`);let g0=await J1;if(a.info(`[SessionRoutes] Permission response received: ${e}, approved: ${g0.approved}`),!V.signal.aborted)O.status="running";if(O.pendingPermission===Y1)O.pendingPermission=void 0;return f("interaction.resolved",{requestId:e}),g0},SO={messages:await v.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:_,workspaceRoot:$.projectPath,signal:V.signal,permissionMode:Z,onPermissionModeChange:async(U)=>{$.permissionMode=U,$.updatedAt=new Date,f("session.updated",{permissionMode:U})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:wO}},VO=()=>{if(!b)b=i0(12),f("message.created",{messageId:b,role:"assistant",content:""});return b},O0=async(U)=>{switch(U.kind){case"content_delta":if(U.delta.length>0)y=!0;if(s)break;f("message.delta",{messageId:VO(),delta:U.delta});break;case"structured_output":y=!0,f("structured.output",{messageId:VO(),output:U.output,schemaDigest:U.schemaDigest});break;case"thinking_delta":if(U.delta.length>0)y=!0;f("thinking.delta",{messageId:VO(),delta:U.delta});break;case"tool_start":if(m=!0,"function"in U.toolCall){if(U.toolCall.function.name===l0)break;f("tool.start",{messageId:VO(),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===l0)break;f("tool.result",{messageId:VO(),toolName:U.toolCall.function.name,toolCallId:U.toolCall.id,success:U.result.success,summary:U.result.metadata?.summary,output:R1(j1(I1(U.toolCall.function.name,U.result),b1)),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===l0)break;f("tool.progress",{messageId:VO(),toolName:U.toolCall.function.name,toolCallId:U.toolCall.id,...U.update})}break;case"token_usage":f("token.usage",{...U.usage});break;case"turn_start":f("turn.started",{turn:U.turn,maxTurns:U.maxTurns});break;case"turn_recovery":f("turn.recovery",{assessment:U.assessment});break;case"provider_admission":f("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":f("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":f("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":f("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":f("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":f("mcp.catalog.changed",{messageId:VO(),revision:U.revision,serverName:U.serverName,added:U.added,removed:U.removed,updated:U.updated});break;case"mcp_content_changed":f("mcp.content.changed",{messageId:VO(),revision:U.revision,serverName:U.serverName,contentKind:U.contentKind,added:U.added,removed:U.removed,updated:U.updated});break;case"mcp_resource_updated":f("mcp.resource.updated",{messageId:VO(),revision:U.revision,serverName:U.serverName,uri:U.uri});break;case"mcp_connection_changed":f("mcp.connection.changed",{messageId:VO(),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":f("mcp.log",{messageId:VO(),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":f("mcp.instructions.changed",{messageId:VO(),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":f("mcp.task.changed",{messageId:VO(),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":f("project.rules.loaded",{messageId:VO(),files:U.files,triggerPaths:U.triggerPaths,blockedWrite:U.blockedWrite});break;case"steering_applied":for(let e of U.messages){if((e.origin??"user")!=="user")continue;if(e.persisted)continue;if(u.has(e.id))continue;f("message.created",{messageId:e.id,role:"user",content:y$(e.content),...e.recovered?{recovered:!0}:{}}),UO(e.id)}f("steering.applied",{runId:B,messageIds:U.messageIds,count:U.count,recovered:U.recovered,delivery:U.delivery,queued:d.getPendingSteeringCount()}),f("follow_up.queue.changed",{queue:U.queue});break;case"follow_up_started":{if(b)f("message.complete",{messageId:b}),b=void 0;f("follow_up.started",{runId:B,queued:U.queued,recovered:U.recovered}),f("follow_up.queue.changed",{queue:U.queue}),VO();break}case"follow_up_queue_changed":f("follow_up.queue.changed",{queue:U.queue});break;case"goal_updated":f("goal.updated",{goal:U.goal});break;case"goal_continuation_started":f("goal.continuation.started",{goal:U.goal,continuation:U.continuation,...U.prematureStopPattern?{prematureStopPattern:U.prematureStopPattern}:{},...U.prematureStopCount!==void 0?{prematureStopCount:U.prematureStopCount}:{}}),VO();break;case"compaction":f(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":f("model.fallback",{from:U.from,to:U.to,candidate:U.candidate,candidateCount:U.candidateCount,trigger:U.trigger});break;case"task_update":f("task.updated",{tasks:U.tasks});break;case"goal_frontier_updated":f("goal.frontier.updated",{goalId:U.goal.goalId,goalStatus:U.goal.status,frontier:U.frontier,stall:U.goal.frontierStall});break;default:break}},tO=(U)=>{let e=U.metadata?.toolCallsCount;return new D1({taskFailure:k0(U.error?.details??U.error?.message??"Agent run failed"),outputStarted:y,toolExecutionStarted:m,toolCallsCount:typeof e==="number"&&Number.isInteger(e)?e:-1})},hO=await D4(S.chatStream(Q,SO,{stream:!0,pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:X.taskAdmission}),O0);if(await CO(hO))return;if(!hO.success)throw tO(hO);for(let U=0;U<20;U++){let e=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,d.getPendingSteeringCount()===0){if(!e)break;continue}if(V.signal.aborted)break;if(hO=await D4(S.chatStream("",SO,{stream:!0,pendingInputOnly:!0,taskAdmission:X.taskAdmission}),O0),await CO(hO))return;if(!hO.success)throw tO(hO)}if(await w0($),X.pendingResume&&V.signal.aborted&&V.signal.reason===p1)throw new D1({taskFailure:x1("timeout"),outputStarted:y,toolExecutionStarted:m,toolCallsCount:Number.isInteger(hO.metadata?.toolCallsCount)?hO.metadata?.toolCallsCount??-1:-1});if(V.signal.aborted||O.status==="cancelled"){await ZO(),f("session.status",{status:"idle"});return}if(X.pendingResume)X.onPendingResumeSuccess?.(X.pendingResume);if(b)f("message.complete",{messageId:b});f("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),f("session.completed",{runId:B,outputTruncated:hO.metadata?.outputTruncated??!1}),f("session.status",{status:"idle"})}catch(d){if(A&&X.preparedInputTurn)await(A.getTurnRecoveryAssessment().state==="requires_attention"?A.finishTurn(X.preparedInputTurn.handle,{preserveStartupRecovery:!0}):A.finishTurn(X.preparedInputTurn.handle)).catch(()=>{return});let s=X.pendingResume!==void 0&&V.signal.aborted&&V.signal.reason===p1;if(V.signal.aborted&&!s||O.status==="cancelled"){if(X.pendingResume)X.onPendingResumeCancelled?.(X.pendingResume);A1(O,"runtime-abort"),await ZO(),f("session.status",{status:"idle"});return}let wO=d instanceof D1?d.evidence:s?{taskFailure:x1("timeout"),outputStarted:y,toolExecutionStarted:m,toolCallsCount:-1}:X.pendingResume?{taskFailure:k0(d),outputStarted:!0,toolExecutionStarted:!0,toolCallsCount:-1}:void 0,bO=X.pendingResume!==void 0&&wO!==void 0&&X.onPendingResumeFailure?.(X.pendingResume,wO,s||(A?.getPendingSteeringCount()??0)>0,s)===!0;if(O.status="failed",bO){let VO=await A?.setTaskStatus("running").catch(()=>{return});if(VO)K0($,VO);$.taskStatus="running",$.taskStatusReason=void 0,$.taskFailure=void 0,$.taskCompletedAt=void 0,f("session.status",{status:"running"});return}await w0($).catch(()=>{return}),a.error("[SessionRoutes] Agent execution error:",d),$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let SO=wO?.taskFailure??k0(d);if(!$.taskFailure){let VO=A?await A.setTaskStatus("failed",d).catch(()=>{return}):await v.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:SO.message,taskFailure:SO,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(VO)K0($,VO)}$.taskStatusReason??=SO.message,$.taskFailure??=SO,f("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),f("session.status",{status:"error"})}finally{if(D)clearTimeout(D);if(X.taskAdmission?.release(),X.taskAdmission){let d=x0.getStats();f("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 S?.destroy().catch(()=>{return}),x?.release(),R?.release(),O.disposeRuntimeOnSettle&&X.disposeRuntime)await X.disposeRuntime($,A).catch((d)=>{a.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,d)});F9(O)}}async function P2(O,$,Q){a.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),a.info(`[SessionRoutes] Active runs: ${Y0.size}`);for(let[V,_]of Y0.entries())if(a.info(`[SessionRoutes] Checking run ${V}: sessionId=${_.sessionId}, projectPath=${_.projectPath}, pendingPermission=${_.pendingPermission?.permissionId}`),_.sessionId===O.sessionId&&_.projectPath===O.projectPath&&_.pendingPermission?.permissionId===$){if(_.pendingPermission.details.interactionRequestId)await m0.respond(O.projectPath,O.sessionId,$,Q);return _.pendingPermission.resolve(Q),a.info(`[SessionRoutes] Permission ${$} responded, runId: ${_.id}`),!0}let Z=await m0.findPending(O.projectPath,O.sessionId);if(!Z||Z.request.requestId!==$)return a.error(`[SessionRoutes] Permission not found: ${$}`),!1;await m0.respondAndRecover(O.projectPath,O.sessionId,$,Q),P.publish(O,"interaction.resolved",{requestId:$});let J=N0;if(!J?.accepting)return!0;let X;try{X=await J.acquireOrHydrateSession(O);let V=X.value,_=await v.findSessionMetadata(O.sessionId,O.projectPath);if(N0!==J||!J.accepting||!X.isCurrent())return!0;if(_)K0(V,_);J.resumeRecoveredInteraction(V).catch((B)=>{a.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,B)})}catch(V){if(N0!==J||!J.accepting)return!0;throw V}finally{X?.release()}return!0}var T4=$O("Service"),T9=G.Object({approved:G.Boolean(),remember:G.Optional(G.Boolean()),scope:G.Optional(YO(["once","session","project"])),targetMode:G.Optional(YO(["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:YO(["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}))}))}),k2=()=>{let O=new A9;return O.post("/:permissionId",async($)=>{let Q=$.req.param("permissionId"),Z=$.req.query("sessionId"),J=$.req.query("projectPath");T4.info(`[PermissionRoutes] Received permission response: permissionId=${Q}, sessionId=${Z}`);try{let X=await $.req.json(),V=h(T9,X);if(!V.success)throw new F("Invalid permission response format");let{approved:_,remember:B,scope:w,targetMode:I,feedback:b,answers:x,elicitation:R}=V.data;if(!Z)throw new F("sessionId query parameter is required");let A=await mO(Z,J);if(!await P2(A,Q,{approved:_,reason:b,scope:w,targetMode:I,feedback:b,answers:x,elicitation:R}))throw new l("Permission request",Q);return T4.info(`[PermissionRoutes] Permission ${Q} ${_?"approved":"denied"}`),$.json({success:!0,approved:_,remember:B})}catch(X){if(T4.error("[PermissionRoutes] Failed to respond to permission:",X),X instanceof F||X instanceof gO||X instanceof l||X instanceof WO)throw X;throw X}}),O};import{homedir as m2}from"node:os";import b4 from"node:path";import{Hono as b9}from"hono";var j9=G.Object({projectPath:G.String({minLength:1}),enabled:G.Boolean(),scope:G.Optional(YO(["local","project","global"]))}),I9=G.Object({projectPath:G.String({minLength:1})}),R9=G.Object({projectPath:G.String({minLength:1}),source:G.String({minLength:1}),trust:G.Literal(!0),ref:G.Optional(G.String({minLength:1}))}),q9=G.Object({projectPath:G.String({minLength:1}),trust:G.Literal(!0)}),E9=G.Object({projectPath:G.String({minLength:1}),confirm:G.Literal(!0)}),S9=G.Object({projectPath:G.String({minLength:1}),source:G.String({minLength:1}),ref:G.Optional(G.String({minLength:1}))}),y2=G.Object({projectPath:G.String({minLength:1}),confirm:G.Optional(G.Literal(!0))}),C9=G.Object({projectPath:G.String({minLength:1}),scope:G.Optional(YO(["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 eO(O){if(!O)throw new F("projectPath must be absolute");try{return _O(O)}catch{throw new F("projectPath must reference a local workspace")}}function f9(O){return b4.isAbsolute(O)||O.startsWith("./")||O.startsWith("../")||O==="~"||O.startsWith("~/")}function h2(O,$){if(!f9(O))return;let Q=O==="~"?m2():O.startsWith("~/")?b4.join(m2(),O.slice(2)):O;try{_O(b4.resolve($,Q))}catch{throw new F("Plugin source must reference a local workspace")}}async function g2(O){let[$,Q]=await Promise.all([Q0(O),_1.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 P9(){let O=p2(),[$,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 _=Z.get(V.name);return{name:V.name,description:V.description??"",version:V.version,category:V.category,tags:V.tags??[],installed:_!==void 0,installedVersion:_?.version}})}))}function a0(O,$){if(!O.success)throw new F(O.error??$)}var t2=()=>{let O=new b9;return O.get("/",async($)=>{let Q=eO($.req.query("projectPath"));return $.json(await g2(Q))}),O.post("/refresh",async($)=>{let Q=h(I9,await $.req.json());if(!Q.success)throw new F("Invalid plugin refresh request");let Z=eO(Q.data.projectPath),J=await u2(Z);return $.json({plugins:await g2(Z),errors:J.discovery.errors.map((X)=>({code:X.code??"LOAD_ERROR",error:X.error}))})}),O.get("/catalog",async($)=>{return eO($.req.query("projectPath")),$.json(await P9())}),O.get("/policy",async($)=>{let Q=eO($.req.query("projectPath")),Z=await _1.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=h(C9,await $.req.json());if(!Q.success)throw new F("Invalid plugin source policy request");let Z=eO(Q.data.projectPath),J=await d2(Z,Q.data.policy,Q.data.scope??"global");return $.json({policy:J})}),O.post("/install",async($)=>{let Q=h(R9,await $.req.json());if(!Q.success)throw new F("Invalid plugin install request; explicit source trust is required");let Z=eO(Q.data.projectPath);h2(Q.data.source,Z);let{result:J}=await c2(Z,Q.data.source,{trusted:Q.data.trust,ref:Q.data.ref});return a0(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=h(S9,await $.req.json());if(!Q.success)throw new F("Invalid marketplace add request");let Z=eO(Q.data.projectPath);h2(Q.data.source,Z);let J=await a2(Z,Q.data.source,Q.data.ref);return a0(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=h(y2,await $.req.json());if(!Q.success)throw new F("Invalid marketplace refresh request");let Z=await n2(eO(Q.data.projectPath),$.req.param("name"));return a0(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=h(y2,await $.req.json());if(!Q.success||Q.data.confirm!==!0)throw new F("Invalid marketplace removal request; explicit confirmation is required");eO(Q.data.projectPath);let Z=await o2($.req.param("name"),!0);return a0(Z,"Marketplace removal failed"),$.json({name:Z.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let Q=h(q9,await $.req.json());if(!Q.success)throw new F("Invalid plugin update request; explicit source trust is required");let Z=eO(Q.data.projectPath),{result:J}=await i2(Z,$.req.param("name"),{trusted:Q.data.trust});return a0(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=h(E9,await $.req.json());if(!Q.success)throw new F("Invalid plugin uninstall request; explicit confirmation is required");let Z=eO(Q.data.projectPath),{result:J}=await l2(Z,$.req.param("name"),Q.data.confirm);return a0(J,"Plugin uninstall failed"),$.json({name:J.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let Q=h(j9,await $.req.json());if(!Q.success)throw new F("Invalid plugin state request");let Z=eO(Q.data.projectPath),J=$.req.param("name"),V=(await Q0(Z)).plugins.get(J);if(!V)throw new l("Plugin",J);if(V.source==="cli")throw new F(`Plugin "${J}" was loaded with --plugin-dir and is invocation-scoped`);let _=await v2(Z,J,Q.data.enabled,Q.data.scope??"local");return $.json(_)}),O};import{Hono as g9}from"hono";import{execFile as k9}from"node:child_process";import m9 from"node:path";var R4="__BLADE_DIRECTORY_PICKER_CANCELLED__",y9=900000;function h9(O,$){return new Promise((Q)=>{k9(O,[...$],{timeout:y9,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 j4(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===R4)return{cancelled:!0};if(!m9.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function I4(O){return O.exitCode!==0||Boolean(O.errorCode)}class s2{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??h9}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 "${R4}"`,"end try"].join(`
8
- `),$=await this.runCommand("osascript",["-e",O]);if(I4($))throw Error("Unable to open the macOS folder picker");return j4($.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("${R4}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(I4($))throw Error("Unable to open the Windows folder picker");return j4($.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(I4(Q))throw Error("Unable to open the Linux folder picker");return j4(Q.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var r2=new s2;var p9=G.Object({path:G.String({minLength:1})});function e2(O){try{return _O(O)}catch($){throw new F($ instanceof Error?$.message:"Project path is invalid")}}function v9(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 O3=(O={})=>{let $=new g9,Q=O.pickDirectory??(()=>r2.pick()),Z=O.allowDirectoryPickerRequest??v9;return $.get("/",async(J)=>{return J.json(await l1.list(XO()))}),$.post("/",async(J)=>{let X;try{X=await J.req.json()}catch{throw new F("A valid JSON body is required")}let V=h(p9,X);if(!V.success)throw new F("A project path is required");try{let _=e2(V.data.path),B=await l1.bind(_,XO());return J.json(B,201)}catch(_){throw new F(_ instanceof Error?_.message:"Failed to bind project")}}),$.post("/pick",async(J)=>{if(!Z(J.req.header("Origin")))throw new WO("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 l1.unbind(e2(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 u9}from"hono";var $3=$O("Service"),Y3=()=>{let O=new u9;return O.get("/",async($)=>{try{let Q=await Z3();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 J3(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 E0().setApiKey(Q,Z.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await E0().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let Q=$.req.param("provider"),Z=xO(),J=Z?.modelProviders[Q];if(!Z||!J)throw new l("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,_={name:X.name,baseUrl:X.baseUrl,wireApi:X.wireApi,...V?{apiKeyEnv:V}:{}},B=E0(),w=X.apiKey?.trim()?await B.credentials.read(Q):void 0;if(X.apiKey?.trim())await B.setApiKey(Q,X.apiKey.trim());try{return await aO().updateModelProvider(Q,_),$.json({success:!0})}catch(I){if(X.apiKey?.trim())if(w)await B.credentials.modify(Q,async()=>w);else await B.credentials.delete(Q);if(I instanceof Error&&(I.message.includes("modelProviders.")||I.message.includes("built-in provider")))throw new F(I.message);throw I}}),O.delete("/:provider",async($)=>{let Q=$.req.param("provider");if(!xO()?.modelProviders[Q])throw new l("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 aO().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 c(X.message);throw X}}),O.post("/:provider/probe",async($)=>{let Q=$.req.param("provider"),Z=xO();if(!Z?.modelProviders[Q])throw new l("Model provider",Q);let J=await $.req.json().catch(()=>({})),X=Z.models.filter((_)=>_.provider===Q),V=J.modelId?X.find((_)=>_.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 Q3(V,Z))}),O};import{Hono as d9}from"hono";var c9=$O("Service"),G3=(O,$)=>{let Q=new d9;return Q.onError((Z,J)=>{if(Z instanceof WO)return J.json(Z.toObject(),Z.statusCode);return c9.error("[ScheduleRoutes] Unhandled route error:",Z),J.json(new JO("Schedule request failed").toObject(),500)}),Q.get("/",async(Z)=>{let J=await O.list();return Z.json(z3.parse({schedules:J}))}),Q.post("/",async(Z)=>{let J;try{J=await Z.req.json()}catch{throw new F("Invalid request body")}let X=h(X3,J);if(!X.success)throw new F("Invalid schedule request");let V;try{V=_O(X.data.projectPath||Z.get("directory")||XO())}catch{throw new F("projectPath must reference a local workspace")}try{let _=await O.create({...X.data,projectPath:V});return Z.json(y0.parse(_),201)}catch(_){throw new F(_ instanceof Error?_.message:"Failed to create schedule")}}),Q.get("/:id",async(Z)=>{let J=await O.get(Z.req.param("id"));if(!J)throw new l("Schedule not found");return Z.json(y0.parse(J))}),Q.patch("/:id",async(Z)=>{let J;try{J=await Z.req.json()}catch{throw new F("Invalid request body")}let X=h(V3,J);if(!X.success)throw new F("Invalid schedule update");let{modelId:V,reasoningEffort:_,serviceTier:B,responseVerbosity:w,communicationStyle:I,isolation:b,permissionMode:x,...R}=X.data,A={...V!==void 0?{modelId:V}:{},..._!==void 0?{reasoningEffort:_}:{},...B!==void 0?{serviceTier:B}:{},...w!==void 0?{responseVerbosity:w}:{},...I!==void 0?{communicationStyle:I}:{},...b!==void 0?{isolation:b}:{},...x!==void 0?{permissionMode:x}:{}};try{let S=await O.update(Z.req.param("id"),{...R,...Object.keys(A).length>0?{dispatch:A}:{}});if(!S)throw new l("Schedule not found");return Z.json(y0.parse(S))}catch(S){if(S instanceof WO)throw S;throw new F(S instanceof Error?S.message:"Failed to update schedule")}}),Q.delete("/:id",async(Z)=>{if(!await O.remove(Z.req.param("id")))throw new l("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 l("Schedule not found");return Z.json(y0.parse(J))}),Q.post("/:id/disable",async(Z)=>{let J=await O.setEnabled(Z.req.param("id"),!1);if(!J)throw new l("Schedule not found");return Z.json(y0.parse(J))}),Q.post("/:id/run",async(Z)=>{let J=await O.get(Z.req.param("id"));if(!J)throw new l("Schedule not found");if(!$)throw new JO("Scheduler is not running in this process");await $.fire(J,new Date,{manual:!0});let X=await O.get(J.id);return Z.json(y0.parse(X??J),202)}),Q};import{createHash as i9}from"node:crypto";import{Hono as l9}from"hono";var q4={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},a9=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(YO(["true","false"])),workspaceKind:G.Optional(YO(["local","acp-remote"]))},{additionalProperties:!1}),a1=65536,n9=new Set(["cursor","limit","archived","workspaceKind"]),o9=new Set(["locator","limit"]),t9=new Set(["locator","cursor","expectedSnapshot","limit"]),s9=new Set(["locator"]),r9=new Set(["version","sessionId","workspace"]),e9=new Set(["kind","projectPath","workspaceRef"]),O6=$O("Service");function D3(O={}){let $=O.service?void 0:new H3(O.cursorRegistryOptions),Q=O.service??new B3({database:O.database,cursorRegistry:$}),Z=O.logger??O6,J=new l9,X=!0,V=0,_,B=new Set,w=()=>new n0("session_surface_unavailable"),I=()=>{if(V===0)return Promise.resolve();return new Promise((x)=>B.add(x))};return J.onError((x,R)=>{let A=Z6(x);return Z.warn(`[SessionSurfaceRoutes] method=${R.req.method} path=${R.req.path} code=${A.error.code} kind=${R.get("surfaceKind")??"unknown"} locator=${R.get("surfaceLocatorDigest")??"none"}`),R.json(A,q4[A.error.code])}),J.use("*",async(x,R)=>{if(x.set("surfaceKind","unknown"),x.set("surfaceLocatorDigest","none"),!X){let A=n1(w());return x.json(A,q4[A.error.code])}V+=1;try{if(await R(),!X){let A=n1(w());x.res=x.json(A,q4[A.error.code])}return x.res}finally{if(V-=1,V===0){for(let A of B)A();B.clear()}}}),J.get("/catalog",async(x)=>{let R=$6(x.req.url),A=await Q.listPage(R);return x.json(K3.parse(A))}),J.post("/open",async(x)=>{E4(x.req.url);let R=await f4(x.req.raw);q1(R,o9,yO());let A=S4(R);C4(x,A);let S=h(U3,R);if(!S.success)throw yO();let y=await Q.open(A,{limit:S.data.limit});return x.json(P4.parse(y))}),J.post("/history",async(x)=>{E4(x.req.url);let R=await f4(x.req.raw);q1(R,t9,yO());let A=S4(R);C4(x,A);let S=h(w3,R);if(!S.success)throw yO();let y=await Q.historyPage(A,{cursor:S.data.cursor,expectedSnapshot:S.data.expectedSnapshot,limit:S.data.limit});return x.json(_3.parse(y))}),J.post("/fork",async(x)=>{E4(x.req.url);let R=await f4(x.req.raw);q1(R,s9,yO());let A=S4(R);if(C4(x,A),!h(F3,R).success)throw yO();let y=await Q.fork(A);return x.json(P4.parse(y))}),{app:J,getStats:()=>({accepting:X,active:V,cursors:$?.stats().entryCount??0}),shutdown:(x="server-shutdown")=>{if(_)return _;return X=!1,_=(async()=>{let A=(await Promise.allSettled([Promise.resolve().then(()=>Q.close(x)),I()])).find((S)=>S.status==="rejected");if(A)throw A.reason})(),_}}}function yO(){return new n0("invalid_session_surface_request")}function $6(O){let $=new URL(O).searchParams,Q={},Z=new Set;for(let[X,V]of $){if(!n9.has(X)||Z.has(X))throw yO();Z.add(X),Q[X]=V}let J=h(a9,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 E4(O){if(new URL(O).searchParams.size>0)throw yO()}function q1(O,$,Q){if(!O||typeof O!=="object"||Array.isArray(O))throw Q;if(Object.keys(O).some((Z)=>!$.has(Z)))throw Q}function S4(O){if(!O||typeof O!=="object"||Array.isArray(O))throw yO();let $=Reflect.get(O,"locator");if($===void 0)throw yO();let Q=new n0("invalid_session_locator");q1($,r9,Q),q1(Reflect.get($,"workspace"),e9,Q);let Z=h(W3,$);if(!Z.success)throw Q;return Z.data}function C4(O,$){O.set("surfaceKind",$.workspace.kind),O.set("surfaceLocatorDigest",J6($))}async function f4(O){let $=O.headers.get("content-length");if($!==null&&(!/^\d+$/.test($)||Number($)>a1))throw yO();let Q=O.body?.getReader();if(!Q)throw yO();let Z=[],J=0;try{while(!0){let{done:B,value:w}=await Q.read();if(B)break;if(J+=w.byteLength,J>a1){try{await Q.cancel()}catch{}throw yO()}Z.push(w)}}finally{Q.releaseLock()}let X=new Uint8Array(J),V=0;for(let B of Z)X.set(B,V),V+=B.byteLength;let _=new TextDecoder().decode(X);if(!_)throw yO();try{return Q6(_),JSON.parse(_)}catch{throw yO()}}function Q6(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 _=new Set;if(O[$]==="}"){$+=1;return}while($<O.length){Q();let B=Z();if(_.has(B))throw Error("duplicate key");if(_.add(B),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 Z6(O){if(O instanceof n0)return n1(O);return n1(new n0("session_surface_state_invalid"))}function n1(O){return N3.parse({error:{code:O.code,message:O.message,retryable:O.retryable}})}function J6(O){if(!O)return"none";return i9("sha256").update("session-surface-route-locator-v2\x00").update(JSON.stringify(O)).digest("hex").slice(0,16)}import*as b0 from"node:fs/promises";import{homedir as T3}from"node:os";import*as oO from"node:path";import{Hono as z6}from"hono";import{exec as Y6}from"node:child_process";import*as QO from"node:fs/promises";import{homedir as X6}from"node:os";import*as TO from"node:path";import{promisify as V6}from"node:util";var o1=V6(Y6),MO=$O("General"),L3={url:"https://github.com/anthropics/skills.git",branch:"main"};class x3{skillsDir;constructor(O){this.skillsDir=O||TO.join(X6(),".blade","skills")}async isGitAvailable(){try{return await o1("git --version"),!0}catch{return!1}}async installOfficialSkill(O){let{url:$,branch:Q}=L3,Z=TO.join(this.skillsDir,O),J=TO.join(this.skillsDir,`.tmp-${O}-${Date.now()}`);try{if(!await this.isGitAvailable())return MO.warn("Git not available, skipping skill installation"),!1;MO.info(`Installing official skill: ${O}...`),await QO.mkdir(this.skillsDir,{recursive:!0,mode:493}),await o1(`git clone --depth 1 --branch ${Q} --single-branch ${$} "${J}"`,{timeout:30000});let X=TO.join(J,"skills",O);try{await QO.access(X)}catch{return MO.warn(`Skill ${O} not found in official repository`),await QO.rm(J,{recursive:!0,force:!0}),!1}try{await QO.rm(Z,{recursive:!0,force:!0})}catch{}return await QO.cp(X,Z,{recursive:!0}),await QO.rm(J,{recursive:!0,force:!0}),MO.info(`Successfully installed: ${O}`),!0}catch(X){try{await QO.rm(J,{recursive:!0,force:!0})}catch{}return MO.warn(`Failed to install ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installFromRepo(O,$){let Q=$||this.extractRepoName(O),Z=TO.join(this.skillsDir,Q),J=TO.join(this.skillsDir,`.tmp-repo-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return MO.warn("Git not available, cannot install from repo"),!1;MO.info(`Installing skill from repo: ${O}...`),await QO.mkdir(this.skillsDir,{recursive:!0,mode:493}),await o1(`git clone --depth 1 "${O}" "${J}"`,{timeout:60000});let X=TO.join(J,"SKILL.md");try{await QO.access(X)}catch{return MO.warn(`No SKILL.md found in repository ${O}`),await QO.rm(J,{recursive:!0,force:!0}),!1}await QO.rm(Z,{recursive:!0,force:!0}),await QO.rename(J,Z);try{await QO.rm(TO.join(Z,".git"),{recursive:!0,force:!0})}catch{}return MO.info(`Successfully installed skill from repo: ${Q}`),!0}catch(X){try{await QO.rm(J,{recursive:!0,force:!0})}catch{}return MO.warn(`Failed to install from repo ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installFromLocal(O,$,Q=!0){let Z=$||TO.basename(O),J=TO.join(this.skillsDir,Z);try{let X=TO.resolve(O);try{await QO.access(X)}catch{return MO.warn(`Local path does not exist: ${X}`),!1}let V=TO.join(X,"SKILL.md");try{await QO.access(V)}catch{return MO.warn(`No SKILL.md found in local path: ${X}`),!1}if(MO.info(`Installing skill from local path: ${X}...`),await QO.mkdir(this.skillsDir,{recursive:!0,mode:493}),await QO.rm(J,{recursive:!0,force:!0}),Q)await QO.symlink(X,J,"dir"),MO.info(`Created symlink for skill: ${Z}`);else await QO.cp(X,J,{recursive:!0}),MO.info(`Copied skill to: ${Z}`);return!0}catch(X){return MO.warn(`Failed to install from local path ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}extractRepoName(O){return O.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:O,branch:$}=L3,Q=TO.join(this.skillsDir,`.tmp-all-${Date.now()}`),Z=[],J=[];try{if(!await this.isGitAvailable())return MO.warn("Git not available, skipping skill installation"),{installed:Z,failed:J};await QO.mkdir(this.skillsDir,{recursive:!0,mode:493}),MO.info("Cloning official skills repository..."),await o1(`git clone --depth 1 --branch ${$} --single-branch ${O} "${Q}"`,{timeout:60000});let X=TO.join(Q,"skills"),V=await QO.readdir(X,{withFileTypes:!0});for(let _ of V){if(!_.isDirectory())continue;let B=_.name,w=TO.join(X,B),I=TO.join(this.skillsDir,B);try{await QO.access(TO.join(w,"SKILL.md")),await QO.rm(I,{recursive:!0,force:!0}),await QO.cp(w,I,{recursive:!0}),MO.info(`Installed: ${B}`),Z.push(B)}catch(b){MO.warn(`Failed to install ${B}`),J.push(B)}}await QO.rm(Q,{recursive:!0,force:!0})}catch(X){try{await QO.rm(Q,{recursive:!0,force:!0})}catch{}MO.warn(`Failed to install skills: ${X instanceof Error?X.message:"Unknown error"}`)}return{installed:Z,failed:J}}}var k4=null;function M3(O){if(!k4)k4=new x3(O);return k4}var h0=$O("Service"),A3=oO.join(T3(),".blade","skills"),m4=oO.join(T3(),".blade","skills-config.json");function t1(O){try{return _O(O,"directory")}catch{throw new F("directory must reference a local workspace")}}async function b3(){try{let O=await b0.readFile(m4,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function G6(O){await b0.mkdir(oO.dirname(m4),{recursive:!0}),await b0.writeFile(m4,JSON.stringify(O,null,2))}async function W6(O,$){let Q=await b3();if($)Q.disabled=Q.disabled.filter((Z)=>Z!==O);else if(!Q.disabled.includes(O))Q.disabled.push(O);await G6(Q)}var T0=null,N6=300000,K6=6;async function _6(){if(T0&&Date.now()-T0.timestamp<N6)return T0.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(h0.warn(`GitHub API returned ${O.status}`),T0)return T0.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(K6,Q.length);return await Promise.all(Array.from({length:X},async()=>{while(J<Q.length){let V=J++,_=Q[V];if(!_)continue;let B=`Official ${_.name} skill`;try{let w=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${_.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(w.ok){let b=(await w.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(b)B=b[1].trim().slice(0,100)}}catch{}Z[V]={name:_.name,description:B,tag:"Official",author:"Anthropic"}}})),T0={data:Z,timestamp:Date.now()},Z}catch(O){if(h0.warn("Failed to fetch skills catalog from GitHub:",O),T0)return T0.data;throw O}}var j3=()=>{let O=new z6;return O.get("/",async($)=>{try{let Q=t1($.get("directory")||XO()),J=(await Q0(Q)).skills.getAll(),X=await b3(),V=J.map((_)=>({id:_.name,name:_.name,enabled:!X.disabled.includes(_.name),description:_.description||"",version:_.version||"1.0.0",provider:"Local",location:_.source==="builtin"?"Built-in":_.basePath,removable:_.source==="user"&&oO.dirname(oO.resolve(_.basePath))===oO.resolve(A3),capabilities:["prompts"],allowedTools:_.allowedTools||[]}));return $.json(V)}catch(Q){if(Q instanceof F)throw Q;return h0.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 W6(Q,Z.enabled),$.json({success:!0,enabled:Z.enabled})}catch(Q){return h0.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=t1($.get("directory")||XO());return F1(Z,async(J)=>{let X=J.skills,V=X.get(Q);if(!V)return $.json({success:!1,error:"Skill not found"},404);let _=oO.resolve(V.basePath),B=oO.resolve(A3);if(V.source!=="user"||oO.dirname(_)!==B)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await b0.rm(_,{recursive:!0,force:!0}),await X.refresh(),w1(Z),await U1(Z),$.json({success:!0})})}catch(Q){if(Q instanceof F)throw Q;return h0.error("[SkillsRoutes] Failed to uninstall skill:",Q),$.json({success:!1,error:Q.message},500)}}),O.post("/install",async($)=>{try{let Q=await $.req.json(),Z=M3(),J=t1($.get("directory")||XO());return F1(J,async(X)=>{let V=X.skills,_=!1;if(Q.source==="catalog"&&Q.name){if(_=await Z.installOfficialSkill(Q.name),!_)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(Q.source==="repo"&&Q.url){if(_=await Z.installFromRepo(Q.url,Q.name),!_)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(Q.source==="local"&&Q.path){let B=t1(oO.resolve(Q.path));if(_=await Z.installFromLocal(B,Q.name),!_)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 V.refresh(),w1(J),await U1(J),$.json({success:!0})})}catch(Q){if(Q instanceof F)throw Q;return h0.error("[SkillsRoutes] Failed to install skill:",Q),$.json({success:!1,error:Q.message},500)}}),O.get("/catalog",async($)=>{try{let Q=await _6();return $.json(Q)}catch(Q){return h0.error("[SkillsRoutes] Failed to get catalog:",Q),$.json({error:Q instanceof Error?Q.message:"Failed to get skills catalog"},502)}}),O};import{execSync as U6}from"node:child_process";import{readdir as w6,realpath as F6}from"node:fs/promises";import F0 from"node:path";import H6 from"fast-glob";import{Hono as B6}from"hono";var E1=$O("Service"),D6=(O)=>{try{return U6("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},L6=[...t0.map((O)=>`${O}/**`),...t0,...t0.map((O)=>`**/${O}/**`),...t0.map((O)=>`**/${O}`),...y4.map((O)=>`**/${O}`)],x6=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]);function o0(O){try{return _O(O,"directory")}catch($){throw new F($ instanceof Error?$.message:"directory is invalid")}}function I3(O,$){let Q=F0.relative(O,$);return Q===""||Q!==".."&&!Q.startsWith(`..${F0.sep}`)&&!F0.isAbsolute(Q)}async function R3(O){let $=F0.resolve(O),Q=[];while(!0)try{return F0.resolve(await F6($),...Q.reverse())}catch(Z){let J=Z.code;if(J!=="ENOENT"&&J!=="ENOTDIR")throw Z;let X=F0.dirname($);if(X===$)return F0.resolve(O);Q.push(F0.basename($)),$=X}}async function q3(O,$){let Q=F0.resolve(O,$);if(!I3(O,Q))return null;let Z=await R3(O),J=await R3(Q);if(!I3(Z,J))return null;try{o0(J)}catch{return null}return J}var C3=()=>{let O=new B6;return O.get("/commands",async($)=>{let Q=o0($.get("directory")||XO());try{let Z=$.req.query("q")||"",J=await Q0(Q),X=S3(Z,Q,J).filter((V)=>!x6.has(V.command));return $.json(X)}catch(Z){return E1.error("[SuggestionsRoutes] Failed to get command suggestions:",Z),$.json([])}}),O.get("/files",async($)=>{let Q=o0($.get("directory")||XO());try{let Z=$.req.query("q")||"",J=Math.min(Number($.req.query("limit"))||100,1000),X=$.req.query("type")==="file",_=(await H6("**/*",{cwd:Q,dot:!1,followSymbolicLinks:!1,onlyFiles:X,markDirectories:!0,unique:!0,ignore:L6})).map((I)=>I.replace(/\\/g,"/"));if(!Z)return $.json(_.slice(0,J));let B=Z.toLowerCase(),w=_.filter((I)=>I.toLowerCase().includes(B)).slice(0,J);return $.json(w)}catch(Z){return E1.error("[SuggestionsRoutes] Failed to get file suggestions:",Z),$.json([])}}),O.get("/files/tree",async($)=>{let Q=o0($.get("directory")||XO());try{let Z=$.req.query("path")||"",J=await q3(Q,Z);if(!J)return $.json({error:"Invalid file path"},400);let V=(await w6(J,{withFileTypes:!0})).map((w)=>({name:w.name,path:Z?`${Z}/${w.name}`:w.name,type:w.isDirectory()?"dir":"file"}));V.sort((w,I)=>{if(w.type!==I.type)return w.type==="dir"?-1:1;return w.name.localeCompare(I.name)});let _=new Set(t0),B=V.filter((w)=>{let I=w.name;if(I.startsWith("."))return!1;if(_.has(I))return!1;for(let b of y4)if(I.match(new RegExp(b.replace("*",".*"))))return!1;return!0});return $.json(B)}catch(Z){return E1.error("[SuggestionsRoutes] Failed to get file tree:",Z),$.json([])}}),O.get("/files/content",async($)=>{let Q=o0($.get("directory")||XO());try{let Z=$.req.query("path");if(!Z)return $.json({error:"Missing file path"},400);let J=await q3(Q,Z);if(!J)return $.json({error:"Invalid file path"},400);let X=E3(),V=await X.stat(J);if(!V?.isFile)return $.json({error:"File not found"},404);let _=200000,B=await X.readTextFile(J),w=B.length>_;return $.json({path:Z,content:w?B.slice(0,_):B,truncated:w,size:V.size})}catch(Z){return E1.error("[SuggestionsRoutes] Failed to get file content:",Z),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{let Q=o0($.get("directory")||XO());try{let Z=D6(Q);return $.json({branch:Z})}catch(Z){return E1.error("[SuggestionsRoutes] Failed to get git info:",Z),$.json({branch:null})}}),O};import{Hono as M6}from"hono";var s0=$O("Service"),y3=(O)=>{let $=new M6;return $.onError((Q,Z)=>{if(Q instanceof WO)return Z.json(Q.toObject(),Q.statusCode);return s0.error("[TaskRoutes] Unhandled route error:",Q),Z.json(new JO("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=h(P3,Z);if(!J.success)throw new F("Invalid task request");if((J.data.attachments??[]).reduce((V,_)=>V+(typeof _.content==="string"?Buffer.byteLength(_.content):0),0)>c1)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")||XO(),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(g4.parse(V),202)}catch(V){if(V instanceof F||V instanceof c||V instanceof LO||V instanceof rO)throw V;throw s0.error("[TaskRoutes] Failed to dispatch task:",V),new JO("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=h(k3,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(h4.parse(X))}catch(X){if(X instanceof F||X instanceof l||X instanceof c)throw X;throw s0.error("[TaskRoutes] Failed to update task:",X),new JO("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(g4.parse(Z),202)}catch(Z){if(Z instanceof F||Z instanceof l||Z instanceof c||Z instanceof LO||Z instanceof rO)throw Z;throw s0.error("[TaskRoutes] Failed to retry task:",Z),new JO("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(f3.parse(Z))}catch(Z){if(Z instanceof F||Z instanceof l||Z instanceof c)throw Z;throw s0.error("[TaskRoutes] Failed to load task diff:",Z),new JO("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=h(m3,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(h4.parse(X))}catch(X){if(X instanceof F||X instanceof l||X instanceof c)throw X;throw s0.error("[TaskRoutes] Failed to deliver task:",X),new JO("Failed to deliver task")}}),$};import{Hono as b6}from"hono";var A6=nO(G.Object({id:G.String(),name:G.String(),subagentType:G.String(),description:G.String(),agentId:G.Optional(G.String()),status:YO(["leader","running","completed","failed","cancelled","unknown"]),result:G.Optional(G.Unknown()),stats:G.Optional(G.Unknown()),worktreePath:G.Optional(G.String())})),T6=nO(G.Object({id:G.String(),subject:G.String(),description:G.String(),status:YO(["pending","blocked","running","completed"]),owner:G.Optional(G.String()),priority:YO(["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())})),jJ=nO(G.Object({name:G.String(),description:G.Optional(G.String()),status:YO(["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(A6),tasks:G.Array(T6)})),h3=nO(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(YO(["high","medium","low"]))}),{maxItems:256}))})),g3=nO(G.Object({sessionId:G.String({minLength:1}),projectPath:G.String({minLength:1}),to:G.String({minLength:1}),message:G.String({minLength:1,maxLength:32768})})),p3=nO(G.Object({sessionId:G.String({minLength:1}),projectPath:G.String({minLength:1}),memberId:G.String({minLength:1})}));var j6=$O("Service"),c3=()=>{let O=new b6;return O.onError(($,Q)=>{if($ instanceof WO)return Q.json($.toObject(),$.statusCode);return j6.error("[TeamRoutes] Unhandled route error:",$),Q.json(new JO("Team operation failed").toObject(),500)}),O.get("/",async($)=>{e0();let Q=await O1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await r0(Q.projectPath).list(Q))}),O.post("/",async($)=>{e0();let Q=h(h3,await p4($.req));if(!Q.success)throw new F("Invalid team request");let Z=await O1(Q.data.sessionId,Q.data.projectPath),J=await v.findSessionMetadata(Z.sessionId,Z.projectPath);return $.json(await r0(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($)=>{e0();let Q=await O1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await r0(Q.projectPath).getSnapshot($.req.param("teamName"),Q))}),O.post("/:teamName/messages",async($)=>{e0();let Q=h(g3,await p4($.req));if(!Q.success)throw new F("Invalid team message");let Z=await O1(Q.data.sessionId,Q.data.projectPath),J=await r0(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($)=>{e0();let Q=h(p3,await p4($.req));if(!Q.success)throw new F("Invalid team task claim");let Z=await O1(Q.data.sessionId,Q.data.projectPath);return $.json({task:await r0(Z.projectPath).claimTask($.req.param("teamName"),Q.data.memberId,Z)})}),O.delete("/:teamName",async($)=>{e0();let Q=await O1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await r0(Q.projectPath).delete($.req.param("teamName"),{owner:Q,killRunning:!0}))}),O};function r0(O){return new d3({configDir:d1(),subagentRegistry:u3(O)})}function e0(){if(v3().config.config?.agentTeamsEnabled!==!0)throw new LO("Agent Teams are disabled")}async function O1(O,$){if(!O||!$)throw new F("sessionId and absolute projectPath are required");let Q;try{Q=_O($)}catch{throw new F("sessionId and local projectPath are required")}if(!await v.findSessionMetadata(O,Q))throw new l(`Session not found: ${O}`);return{sessionId:O,projectPath:Q}}async function p4(O){try{return await O.json()}catch{throw new F("Invalid request body")}}import{Hono as I6}from"hono";var j0=$O("Service"),$1=new Map,i3=2097152,l3=65536;function a3(){return typeof globalThis.Bun<"u"}function n3(O,$){return _O(O||$||XO(),"cwd")}async function R6(O,$,Q){if(a3()){let{spawn:X}=await import("bun-pty"),V=X(O,$,{name:"xterm-256color",cwd:Q.cwd,env:Q.env});return{pid:V.pid,write:(_)=>V.write(_),resize:(_,B)=>V.resize(_,B),kill:()=>V.kill(),onData:(_)=>V.onData(_),onExit:(_)=>V.onExit(_)}}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 d4=void 0,u4;if(a3())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();u4=$.upgradeWebSocket,d4=$.websocket}catch(O){j0.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function o3(O,$){let Q=`term-${Date.now()}`;j0.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 R6(Z,J,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),V={id:Q,process:X,cwd:O,buffer:"",subscribers:new Set};if($1.set(Q,V),V.subscribers.add($),X.onData((_)=>{let B=!1;for(let w of V.subscribers)try{w.send(_),B=!0}catch{V.subscribers.delete(w)}if(B)return;if(V.buffer+=_,V.buffer.length>i3)V.buffer=V.buffer.slice(-i3)}),X.onExit(({exitCode:_})=>{j0.info(`[Terminal] Process exited: ${Q}, code: ${_}`);for(let B of V.subscribers)try{B.close()}catch{}$1.delete(Q)}),V.buffer){let _=V.buffer;V.buffer="";for(let B=0;B<_.length;B+=l3)$.send(_.slice(B,B+l3))}return{session:V,cleanup:()=>{if(j0.info(`[Terminal] Connection closed: ${Q}`),V.subscribers.delete($),V.subscribers.size===0){try{V.process.kill()}catch{}$1.delete(Q)}}}}function t3(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=n3(J.searchParams.get("cwd")??void 0,$()),{session:V,cleanup:_}=await o3(X,{send:(B)=>Q.send(B),close:()=>Q.close()});Q.on("message",(B)=>{try{V.process.write(String(B))}catch(w){j0.error("[Terminal] Failed to write to PTY:",w)}}),Q.on("close",_),Q.on("error",_)}catch(J){j0.error("[Terminal] Failed to spawn PTY:",J),Q.close()}})}var s3=()=>{let O=new I6;if(O.get("/status",($)=>{let Q=Array.from($1.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=$1.get(Q);if(Z){try{Z.process.kill()}catch{}for(let J of Z.subscribers)J.close();return $1.delete(Q),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),u4)O.get("/ws",async($,Q)=>{let Z=$.req.query("cwd")??void 0,J;try{J=n3(Z,$.get("directory"))}catch(_){let B=_ instanceof Error?_.message:"cwd must reference a local workspace";return $.text(B,400)}let X;return u4(()=>{return{async onOpen(_,B){try{X=await o3(J,{send:(w)=>B.send(w),close:()=>B.close()})}catch(w){j0.error("[Terminal] Failed to spawn PTY:",w),B.close()}},onMessage(_){if(!X)return;try{X.session.process.write(String(_.data))}catch(B){j0.error("[Terminal] Failed to write to PTY:",B)}},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 q6}from"hono";var E6=G.Object({projectPath:G.String({minLength:1}),action:YO(["trust","revoke"])});function r3(O){try{return _O(O)}catch{throw new F("projectPath must reference a local workspace")}}var O5=()=>{let O=new q6;return O.get("/",async($)=>{let Q=$.req.query("projectPath");if(!Q)throw new F("projectPath query parameter is required");let Z=r3(Q);return $.json(await c4.getInstance().getStatus(Z))}),O.post("/",async($)=>{let Q=h(E6,await $.req.json());if(!Q.success)throw new F("Invalid workspace trust request");let{action:Z}=Q.data,J=r3(Q.data.projectPath),X=c4.getInstance(),V=Z==="trust"?await X.trust(J):await X.revoke(J);return await e3(),$.json({...V,reloadRequired:V.sensitiveSources>0})}),O};var EO=$O("Service"),n4=[],Q1,D0,Z1,_0,H0,B0,$5=new Map,Q5=new Map,u6=new Set([".css",".html",".js",".json",".svg"]),d6=1024,c6=3600000;class s1 extends Error{}function i6(O){return O==="/sessions/v2"||O.startsWith("/sessions/v2/")}function l6(O,$,Q){return new Promise((Z,J)=>{let X=[],V=0,_=()=>{O.off("data",B),O.off("end",w),O.off("error",I),$.removeEventListener("abort",b)},B=(R)=>{if(V+=R.byteLength,Q!==void 0&&V>Q){_(),O.resume(),J(new s1);return}X.push(R)},w=()=>{_(),Z(Buffer.concat(X,V))},I=(R)=>{_(),J(R)},b=()=>{_(),J($.reason)},x=O.headers["content-length"];if(Q!==void 0&&x!==void 0&&(!/^\d+$/.test(x)||Number(x)>Q)){O.resume(),J(new s1);return}if(O.on("data",B),O.once("end",w),O.once("error",I),$.addEventListener("abort",b,{once:!0}),$.aborted)b()})}function a6(O,$){if(!O)return 0;let Q=O.split(",").map((Z)=>{let[J,...X]=Z.trim().toLowerCase().split(";"),V=X.find((B)=>B.trim().startsWith("q=")),_=V?Number(V.trim().slice(2)):1;return{name:J,quality:Number.isFinite(_)?Math.max(0,Math.min(1,_)):0}});return Q.find((Z)=>Z.name===$)?.quality??Q.find((Z)=>Z.name==="*")?.quality??0}function Z5(){if(Z1)return;let O=()=>{v.collectStaleEmptySessions().then(($)=>{if($>0)EO.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{EO.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),Z1=setInterval(O,c6),Z1.unref?.()}function J5(){if(!Z1)return;clearInterval(Z1),Z1=void 0}function n6(O){return["br","gzip"].map((Q)=>({encoding:Q,quality:a6(O,Q)})).filter((Q)=>Q.quality>0).sort((Q,Z)=>Z.quality-Q.quality||(Q.encoding==="br"?-1:1))[0]?.encoding}function o6(O){let $=$5.get(O);if($)return $;let Q=S1(O);return $5.set(O,Q),Q}function t6(O,$,Q){let Z=`${Q}:${O}`,J=Q5.get(Z);if(J)return J;let X=Q==="br"?m6($,{params:{[h6.BROTLI_PARAM_QUALITY]:5}}):y6($,{level:6});return Q5.set(Z,X),X}function s6(){let O=f6(k6(import.meta.url)),$=[I0(O,"web"),I0(XO(),"dist/web"),I0(XO(),"packages/cli/dist/web")];for(let Q of $){let Z=I0(Q,"index.html");if(a4(Z)){if(S1(Z,"utf-8").includes("/assets/"))return EO.debug(`[Server] Found web dist at: ${Q}`),Q}}return null}function r6(){let O=new g6;O.onError((X,V)=>{if(EO.error("[Server] Request error:",X),X instanceof V5){let B=new rO(X.message,{resource:"workspace_agent_resources",limit:X.capacity});return V.json(B.toObject(),429)}if(X instanceof WO)return V.json(X.toObject(),X.statusCode);let _=X instanceof Error?X.message:String(X);return V.json({error:{code:"INTERNAL_ERROR",message:_}},500)}),O.use(async(X,V)=>{let _=process.env.BLADE_SERVER_PASSWORD;if(!_)return V();let B=X.req.path;if(B==="/"||B==="/favicon.svg"||B.startsWith("/assets/")||B.endsWith(".html")||B.endsWith(".js")||B.endsWith(".css"))return V();let w=X.req.header("Authorization");if(!w?.startsWith("Basic "))return X.header("WWW-Authenticate",'Basic realm="Blade Server"'),X.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let I=Buffer.from(w.slice(6),"base64").toString(),[b,x]=I.split(":"),R=process.env.BLADE_SERVER_USERNAME??"blade";if(b!==R||x!==_)return X.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return V()}),O.use(async(X,V)=>{let _=X.req.path==="/health"||X.req.path==="/global/health"||X.req.path.startsWith("/assets/");if(!_)EO.debug(`[Server] ${X.req.method} ${X.req.path}`);let B=Date.now();if(await V(),!_){let w=Date.now()-B;EO.debug(`[Server] ${X.req.method} ${X.req.path} - ${X.res.status} (${w}ms)`)}}),O.use(p6({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(n4.includes(X))return X;return}})),O.use(async(X,V)=>{let _=X.req.query("directory")||X.req.header("x-blade-directory")||XO();try{_=decodeURIComponent(_)}catch{}return X.set("directory",_),V()});let $,Q,Z;try{$=f2(),Q=D3(),Z=N$(),_0=$,H0=Q,B0=Z,Q1=$.recoverQueuedTasks,D0=new Y4({dispatch:(X)=>$.dispatchTask(X),store:l4}),O.route("/global",_$()),O.route("/events",Z.app),O.route("/sessions/v2",Q.app),O.route("/sessions",$.app),O.route("/tasks",y3($)),O.route("/teams",c3()),O.route("/schedules",G3(l4,D0)),O.route("/configs",Z$()),O.route("/permissions",k2()),O.route("/plugins",t2()),O.route("/hooks",B$()),O.route("/workspace-trust",O5()),O.route("/providers",Y3()),O.route("/models",I$()),O.route("/projects",O3()),O.route("/suggestions",C3()),O.route("/terminal",s3()),O.route("/mcp",x$()),O.route("/skills",j3())}catch(X){throw z5($,Q,Z,"server-startup-failure").catch((V)=>{EO.error("[Server] Failed to clean up route controllers:",V)}),_0=void 0,H0=void 0,B0=void 0,Q1=void 0,D0=void 0,X}O.get("/health",(X)=>{return X.json({healthy:!0,version:u0()})});let J=s6();if(J)EO.info(`[Server] Serving static files from ${J}`),O.get("/favicon.svg",()=>{let X=I0(J,"favicon.svg");if(!a4(X))return new Response(null,{status:404});return new Response(S1(X),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(X)=>{let V=I0(J,X.req.path);if(!a4(V))return X.json({error:{code:"NOT_FOUND",message:`File not found: ${X.req.path}`}},404);let _=o6(V),B=P6(V).toLowerCase(),I={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[B]||"application/octet-stream",b=u6.has(B)&&_.byteLength>=d6?n6(X.req.header("Accept-Encoding")):void 0,x=b?t6(V,_,b):_;return new Response(new Uint8Array(x),{headers:{"Content-Type":I,"Content-Length":String(x.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...b?{"Content-Encoding":b}:{}}})}),O.get("/",(X)=>{let V=I0(J,"index.html"),_=S1(V,"utf-8");return X.html(_,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 _=I0(J,"index.html"),B=S1(_,"utf-8");return X.html(B,200,{"Cache-Control":"no-cache"})});else EO.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:u0(),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 z5(O,$,Q,Z){let J=[],X;for(let B of[O,$,Q])try{J.push(B?.shutdown(Z)??Promise.resolve())}catch(w){X??=w}let _=(await Promise.allSettled(J)).find((B)=>B.status==="rejected");if(X!==void 0)throw X;if(_)throw _.reason}function e6(){let O=C6(),$=[];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 Y5(){return typeof globalThis.Bun<"u"}function X5(O,$){let Q=globalThis.Bun,Z=(X)=>{try{return Q.serve({hostname:$.hostname,port:X,fetch:O.fetch,idleTimeout:0,websocket:d4})}catch(V){EO.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 O8(O,$){return new Promise((Q,Z)=>{let J=S6(async(w,I)=>{let b=new AbortController,x=()=>{if(!b.signal.aborted)b.abort("client-disconnected")},R=()=>x(),A=()=>{if(!I.writableEnded)x()};if(w.once("aborted",R),I.once("close",A),w.aborted||I.destroyed)x();try{let S=new URL(w.url||"/",`http://${w.headers.host}`),y=new Headers;for(let[u,UO]of Object.entries(w.headers))if(UO)if(Array.isArray(UO))for(let CO of UO)y.append(u,CO);else y.set(u,UO);let m;if(w.method!=="GET"&&w.method!=="HEAD")m=(await l6(w,b.signal,i6(S.pathname)?a1:void 0)).toString();let D=new Request(S.toString(),{method:w.method,headers:y,body:m,signal:b.signal}),r=await O.fetch(D);if(I.statusCode=r.status,r.headers.forEach((u,UO)=>{I.setHeader(UO,u)}),r.body){let u=r.body.getReader(),UO=async()=>{let{done:CO,value:f}=await u.read();if(CO){I.end();return}return I.write(f),UO()};await UO()}else{let u=await r.text();I.end(u)}}catch(S){if(b.signal.aborted)return;if(S instanceof s1){I.statusCode=400,I.setHeader("content-type","application/json; charset=UTF-8"),I.setHeader("connection","close"),I.end(JSON.stringify({error:{code:"invalid_session_surface_request",message:"Session surface request is invalid",retryable:!1}}));return}EO.error("[Server] Node request error:",S),I.statusCode=500,I.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}finally{w.off("aborted",R),I.off("close",A)}}),X=new v6({noServer:!0}),V=XO();t3(X,()=>V),J.on("upgrade",(w,I,b)=>{let x;try{x=new URL(w.url||"/",`http://${w.headers.host}`)}catch{I.end(`HTTP/1.1 400 Bad Request\r
9
- Connection: close\r
10
- \r
11
- `);return}if(x.pathname==="/terminal/ws"){try{_O(x.searchParams.get("cwd")||V,"cwd")}catch{I.end(`HTTP/1.1 400 Bad Request\r
12
- Connection: close\r
13
- \r
14
- `);return}X.handleUpgrade(w,I,b,(R)=>{X.emit("connection",R,w)})}else I.destroy()});let _=(w)=>{return new Promise((I,b)=>{J.once("error",(x)=>{if(x.code==="EADDRINUSE")b(x);else b(x)}),J.listen(w,$.hostname,()=>{let x=J.address();if(x&&typeof x==="object")I(x.port);else I(w)})})};(async()=>{let w;if($.port===0)try{w=await _(4096)}catch{w=await _(0)}else w=await _($.port);let I=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${w}`);Q({url:I,port:w,hostname:$.hostname,stop:async()=>{return new Promise((b)=>{X.close(()=>{J.close(()=>b())})})}})})().catch(Z)})}var G5;((kY)=>{let O,$,Q,Z=async(x,R,A,S)=>{let y=[],m=D0,D=[];if($=void 0,_0===x)_0=void 0;if(H0===R)H0=void 0;if(B0===A)B0=void 0;if(Q1=void 0,D0=void 0,S&&O===S)O=void 0,Q=void 0;try{D.push(z5(x,R,A,"server-startup-failure"))}catch(u){y.push(u)}try{m?.stop()}catch(u){y.push(u)}try{J5()}catch(u){y.push(u)}try{i4()}catch(u){y.push(u)}if(S)try{D.push(S.stop())}catch(u){y.push(u)}let r=await Promise.allSettled(D);for(let u of r)if(u.status==="rejected")y.push(u.reason);for(let u of y)EO.error("[Server] Startup cleanup failed:",u)},J=(x,R,A,S)=>{if(O!==x)return Promise.resolve();if(Q)return Q;let y,m,D,r,u,UO,CO,f;try{UO=R?.shutdown("server-shutdown")}catch(ZO){y=ZO}try{CO=A?.shutdown("server-shutdown")}catch(ZO){m=ZO}try{f=S?.shutdown("server-shutdown")}catch(ZO){D=ZO}try{D0?.stop()}catch(ZO){r=ZO}try{J5()}catch(ZO){u=ZO}return Q=(async()=>{let ZO=Promise.resolve().then(()=>x.stop()),[d,s,wO,bO]=await Promise.allSettled([UO??Promise.resolve(),CO??Promise.resolve(),f??Promise.resolve(),ZO]),SO;try{i4()}catch(tO){SO=tO}let O0=[y,d.status==="rejected"?d.reason:void 0,m,s.status==="rejected"?s.reason:void 0,D,wO.status==="rejected"?wO.reason:void 0,r,u,bO.status==="rejected"?bO.reason:void 0,SO].find((tO)=>tO!==void 0);if(O0!==void 0){if(O===x)Q=void 0;throw O0}if(O===x){if(O=void 0,$=void 0,_0===R)_0=void 0;if(H0===A)H0=void 0;if(B0===S)B0=void 0;Q1=void 0,D0=void 0}EO.info("[Server] Blade server stopped")})(),Q};function X(){if(!$)$=r6();return $}kY.getApp=X;function V(x){n4=x.cors??[];let R=X(),A=_0,S=H0,y=B0,m;try{if(Y5())m=X5(R,x),O=m,Q=void 0,EO.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");Q1?.().catch((D)=>{EO.warn("[Server] Failed to recover queued tasks:",D)}),D0?.start(),Z5()}catch(D){throw Z(A,S,y,m),D}if(!m)throw Error("Server transport failed to initialize");return{url:m.url,port:m.port,hostname:m.hostname,stop:()=>J(m,A,S,y)}}kY.listen=V;async function _(x){n4=x.cors??[];let R=X(),A=_0,S=H0,y=B0,m;try{if(Y5())m=X5(R,x),O=m,EO.info(`[Server] Blade server listening on ${m.url} (Bun runtime)`);else m=await O8(R,x),O=m,EO.info(`[Server] Blade server listening on ${m.url} (Node.js runtime)`);Q=void 0;try{await Q1?.()}catch(D){EO.warn("[Server] Failed to recover queued tasks:",D)}D0?.start(),Z5()}catch(D){throw await Z(A,S,y,m),D}if(!m)throw Error("Server transport failed to initialize");return{url:m.url,port:m.port,hostname:m.hostname,stop:()=>J(m,A,S,y)}}kY.listenAsync=_;function B(){return O!==void 0}kY.isRunning=B;function w(){return _0?.getCoordinationStats()}kY.getSessionCoordinationStatsForTests=w;function I(){return H0?.getStats()}kY.getSessionSurfaceStatsForTests=I;function b(){return{global:B0?.getSseConnectionStats(),session:_0?.getSseConnectionStats()}}kY.getSseConnectionStatsForTests=b})(G5||={});export{Q8 as a,Z8 as b,e6 as c,G5 as d};