blade-code 0.10.150 → 0.10.151

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