blade-code 0.10.205 → 0.11.1
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.
- package/dist/blade.js +2 -2
- package/dist/{chunk-7ajvrtb3.js → chunk-06hkf59s.js} +1 -1
- package/dist/{chunk-p0wyhp5a.js → chunk-0b83mt1c.js} +2 -2
- package/dist/{chunk-qtwgm95z.js → chunk-0wcnkxe8.js} +3 -3
- package/dist/{chunk-b8ast0cp.js → chunk-1beqtjsw.js} +1 -1
- package/dist/chunk-1kxpnt9q.js +1 -0
- package/dist/chunk-25s0c8km.js +1726 -0
- package/dist/{chunk-ak5xvsxr.js → chunk-27bjk35b.js} +1 -1
- package/dist/{chunk-515yj7mt.js → chunk-2ftyzk83.js} +1 -1
- package/dist/chunk-2g3v9qpz.js +1 -0
- package/dist/{chunk-5zmp7p0n.js → chunk-2vrsfb8p.js} +59 -59
- package/dist/{chunk-17d4m89n.js → chunk-30p7aff1.js} +2 -2
- package/dist/{chunk-kehgewqh.js → chunk-3kszepm6.js} +1 -1
- package/dist/{chunk-ys8gysg8.js → chunk-3y2x6fb6.js} +1 -1
- package/dist/chunk-43gg1wdc.js +1 -0
- package/dist/{chunk-xbs91jd8.js → chunk-447ps2te.js} +2 -2
- package/dist/{chunk-0eajnhrj.js → chunk-4cdk4mds.js} +1 -1
- package/dist/{chunk-8pd1hp4r.js → chunk-5034apfz.js} +2 -2
- package/dist/{chunk-ynd1v33f.js → chunk-5bc4hwt9.js} +1 -1
- package/dist/chunk-72wn385d.js +1 -0
- package/dist/chunk-7eset766.js +25 -0
- package/dist/chunk-7vzz3rsx.js +332 -0
- package/dist/{chunk-xxbxc31z.js → chunk-80946c9a.js} +1 -1
- package/dist/chunk-8emp6ysb.js +1 -0
- package/dist/chunk-8evyh5t0.js +1 -0
- package/dist/chunk-8hdtssvs.js +1 -0
- package/dist/chunk-8n3jythp.js +733 -0
- package/dist/{chunk-zj1g4nbq.js → chunk-8sth12hd.js} +1 -1
- package/dist/{chunk-fdr4fcrf.js → chunk-9qxch6sy.js} +1 -1
- package/dist/chunk-9ydrwcpy.js +3 -0
- package/dist/chunk-9yn01a90.js +12 -0
- package/dist/chunk-a1tt14a2.js +2 -0
- package/dist/{chunk-egss0m1x.js → chunk-a731hdwa.js} +1 -1
- package/dist/{chunk-gn9er641.js → chunk-a74ynw4t.js} +1 -1
- package/dist/chunk-b36egepz.js +1 -0
- package/dist/chunk-dxq7462e.js +352 -0
- package/dist/{chunk-eg3ms291.js → chunk-f552hzcx.js} +1 -1
- package/dist/{chunk-g01mth5d.js → chunk-f6hc7t65.js} +2 -2
- package/dist/{chunk-qq5y7b2r.js → chunk-fqxzzsgr.js} +1 -1
- package/dist/{chunk-xyypxrad.js → chunk-g0hhqxpg.js} +1 -1
- package/dist/{chunk-4wx5sya5.js → chunk-gzbb747a.js} +1 -1
- package/dist/{chunk-w42j9p3t.js → chunk-h8w3ahnk.js} +1 -1
- package/dist/chunk-hmw99nm1.js +94 -0
- package/dist/chunk-hrtf7dba.js +2 -0
- package/dist/chunk-j7dx054r.js +1 -0
- package/dist/chunk-j9ppeg6v.js +1 -0
- package/dist/chunk-jemb0vwa.js +1 -0
- package/dist/{chunk-qdbbke8f.js → chunk-m30qwpe9.js} +1 -1
- package/dist/{chunk-kvp523gt.js → chunk-m70cnaeg.js} +1 -1
- package/dist/{chunk-rtwd35gd.js → chunk-m8te4s8f.js} +2 -2
- package/dist/chunk-ms0wve9g.js +14 -0
- package/dist/{chunk-wezr6wfq.js → chunk-n8qg68y2.js} +1 -1
- package/dist/chunk-pm5ssr7m.js +25 -0
- package/dist/chunk-r9m3b170.js +1 -0
- package/dist/chunk-rt3f4xjz.js +23 -0
- package/dist/{chunk-430b319j.js → chunk-s1cch8tt.js} +1 -1
- package/dist/chunk-sa9fxss4.js +2 -0
- package/dist/{chunk-xmymx75h.js → chunk-ta99scbr.js} +1 -1
- package/dist/chunk-tf1qz4q6.js +1 -0
- package/dist/{chunk-efjjkha8.js → chunk-tqt5c2f5.js} +2 -2
- package/dist/{chunk-9jz1q7bk.js → chunk-ts5xzefm.js} +2 -2
- package/dist/chunk-v17q4bsd.js +6 -0
- package/dist/{chunk-qp2qc4p2.js → chunk-v1k6nvth.js} +2 -2
- package/dist/{chunk-1cy4ab77.js → chunk-vbjgcn49.js} +1 -1
- package/dist/{chunk-kkzznz4w.js → chunk-wcps5gjm.js} +1 -1
- package/dist/{chunk-vz88tqtd.js → chunk-xcj23spc.js} +2 -2
- package/dist/chunk-xcy45yxx.js +8 -0
- package/dist/chunk-xseh3f4m.js +2 -0
- package/dist/chunk-xz7dddaj.js +4 -0
- package/dist/{chunk-c51wwnh2.js → chunk-xzva8y4e.js} +5 -6
- package/dist/chunk-y0wc0hef.js +10 -0
- package/dist/chunk-yrr9mdjn.js +44 -0
- package/dist/{chunk-f8kjdxz7.js → chunk-zjezws85.js} +2 -2
- package/dist/web/assets/ChatView-BA3kB_z1.js +17 -0
- package/dist/web/assets/CodeBlockHighlighter-B5kcdVCA.js +8 -0
- package/dist/web/assets/FilePreview-BQid6G2-.js +8 -0
- package/dist/web/assets/KanbanBoard-CTR7bMLa.js +1 -0
- package/dist/web/assets/MarkdownRenderer-d7DdyYdx.js +30 -0
- package/dist/web/assets/ScrollArea-D1tPWHKZ.js +1 -0
- package/dist/web/assets/SessionHistorySurface-Cv_jRoJr.js +1 -0
- package/dist/web/assets/SettingsModal-CFa2uCzI.js +5 -0
- package/dist/web/assets/Sidebar-DrRNJOgU.js +1 -0
- package/dist/web/assets/TaskSwitcher-C9AKJrl-.js +1 -0
- package/dist/web/assets/TerminalPanel-BxBGcuB9.js +1 -0
- package/dist/web/assets/archive-DNa9b1YE.js +1 -0
- package/dist/web/assets/arrow-left-BQh8jlfT.js +1 -0
- package/dist/web/assets/calendar-clock-CC7FeYTg.js +1 -0
- package/dist/web/assets/chevron-right-6ZTOJE0p.js +1 -0
- package/dist/web/assets/clock-3-P2q6i6vm.js +1 -0
- package/dist/web/assets/copy-C-KvzjCC.js +1 -0
- package/dist/web/assets/dist-DiQNoDMg.js +11 -0
- package/dist/web/assets/download-CJHn20x1.js +1 -0
- package/dist/web/assets/folder-DmyFehXD.js +1 -0
- package/dist/web/assets/index-BVEiHNFk.css +1 -0
- package/dist/web/assets/index-D-oma3Je.js +11 -0
- package/dist/web/assets/message-square-plus-CKu9bFq3.js +1 -0
- package/dist/web/assets/pause-D2FxNG-w.js +1 -0
- package/dist/web/assets/pencil-D6HI7KC8.js +1 -0
- package/dist/web/assets/play-4jKCDYR-.js +1 -0
- package/dist/web/assets/plus-C4p8E1Nk.js +1 -0
- package/dist/web/assets/preload-helper-BC9Zf9qO.js +1 -0
- package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
- package/dist/web/assets/session-events-CvFfHkFA.js +23 -0
- package/dist/web/assets/settings-fWlqCZ-U.js +1 -0
- package/dist/web/assets/team-qGS2kixH.js +1 -0
- package/dist/web/assets/teamService-DfIvlI2_.js +1 -0
- package/dist/web/assets/terminal-DZkEoiSb.js +1 -0
- package/dist/web/assets/triangle-alert-Detl9fRQ.js +1 -0
- package/dist/web/assets/vendor-radix-CHeA_3Pt.js +41 -0
- package/dist/web/assets/vendor-react-hNfZDUf2.js +9 -0
- package/dist/web/assets/vendor-xterm-CANZO_wP.js +16 -0
- package/dist/web/assets/vendor-xterm-CHOd7Rch.css +1 -0
- package/dist/web/index.html +6 -4
- package/package.json +11 -10
- package/dist/chunk-18swytk4.js +0 -25
- package/dist/chunk-3297ghav.js +0 -1
- package/dist/chunk-33ck9ryb.js +0 -1
- package/dist/chunk-4fa11h6f.js +0 -94
- package/dist/chunk-535s1mm8.js +0 -1
- package/dist/chunk-57939tb3.js +0 -8
- package/dist/chunk-6169xxb4.js +0 -2
- package/dist/chunk-6v0cdqkw.js +0 -1
- package/dist/chunk-8kwj6px8.js +0 -1
- package/dist/chunk-a8z11yd2.js +0 -3
- package/dist/chunk-aatfjx15.js +0 -2
- package/dist/chunk-b2ek44t5.js +0 -12
- package/dist/chunk-b9d0ex8n.js +0 -4
- package/dist/chunk-bwe49m6n.js +0 -1719
- package/dist/chunk-ccgtbzrz.js +0 -14
- package/dist/chunk-jgxfhk9k.js +0 -733
- package/dist/chunk-jhpwwwjt.js +0 -1
- package/dist/chunk-jjj86dej.js +0 -1
- package/dist/chunk-kejvty9z.js +0 -23
- package/dist/chunk-kf9gj2gn.js +0 -2
- package/dist/chunk-mhe1zppc.js +0 -1
- package/dist/chunk-pb1q26gw.js +0 -181
- package/dist/chunk-pc5f77qh.js +0 -1
- package/dist/chunk-pkx6kfy6.js +0 -1
- package/dist/chunk-qjptyj18.js +0 -1
- package/dist/chunk-shgxzmdw.js +0 -1
- package/dist/chunk-thytjs86.js +0 -44
- package/dist/chunk-tm3789m3.js +0 -2
- package/dist/chunk-tnmcrvk2.js +0 -25
- package/dist/chunk-wejthch2.js +0 -1
- package/dist/chunk-xv6ejk2z.js +0 -353
- package/dist/chunk-yvgef7rp.js +0 -10
- package/dist/chunk-zj48897e.js +0 -6
- package/dist/web/assets/ChatView-BF6HUrBw.js +0 -70
- package/dist/web/assets/CodeBlockHighlighter-C4CgCiRf.js +0 -8
- package/dist/web/assets/FilePreview-BS4PgFKb.js +0 -55
- package/dist/web/assets/KanbanBoard-DDXB-yq1.js +0 -16
- package/dist/web/assets/MarkdownRenderer-DS7RznBE.js +0 -30
- package/dist/web/assets/ScrollArea-BM9NzGZM.js +0 -1
- package/dist/web/assets/SessionHistorySurface-DnRySeLE.js +0 -6
- package/dist/web/assets/SettingsModal-D5YLUtIo.js +0 -20
- package/dist/web/assets/Sidebar-BZC6OkDJ.js +0 -31
- package/dist/web/assets/TaskSwitcher-WewOkw5m.js +0 -26
- package/dist/web/assets/TerminalPanel-C5SGdRNr.js +0 -6
- package/dist/web/assets/archive-DkczUU08.js +0 -6
- package/dist/web/assets/arrow-left-9pBiQwu7.js +0 -6
- package/dist/web/assets/calendar-clock-BFnUlxrU.js +0 -6
- package/dist/web/assets/chevron-right-yCVkAEcj.js +0 -6
- package/dist/web/assets/clock-3-CcoWoRQs.js +0 -6
- package/dist/web/assets/copy-HJF0oQBS.js +0 -6
- package/dist/web/assets/download-DSBCIqk3.js +0 -6
- package/dist/web/assets/external-link-zIgEO0KB.js +0 -11
- package/dist/web/assets/folder-BdRo64o3.js +0 -11
- package/dist/web/assets/index-B5mUEr6D.js +0 -11
- package/dist/web/assets/index-BVDkKudh.js +0 -211
- package/dist/web/assets/index-CaCifsSK.css +0 -1
- package/dist/web/assets/message-square-plus-3klTXO0S.js +0 -21
- package/dist/web/assets/pause-B9Q5JWvH.js +0 -6
- package/dist/web/assets/pencil-CbYIz1b1.js +0 -6
- package/dist/web/assets/play-CZMTj43e.js +0 -6
- package/dist/web/assets/plus-Cc7I8fhb.js +0 -6
- package/dist/web/assets/session-events-NEjosinC.js +0 -31
- package/dist/web/assets/settings-DSF3exX2.js +0 -6
- package/dist/web/assets/team-qfeJHL9s.js +0 -6
- package/dist/web/assets/teamService-Bs9qBKI8.js +0 -1
- package/dist/web/assets/terminal-DQLqe-Ed.js +0 -6
- package/dist/web/assets/vendor-radix-D6QrtXqd.js +0 -45
- package/dist/web/assets/vendor-react-DofNRwfy.js +0 -49
- package/dist/web/assets/vendor-xterm-9CEnUXvW.css +0 -32
- package/dist/web/assets/vendor-xterm-DuYZoU4T.js +0 -49
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import{e as B3,f as x3,g as f3,h as r0,i as S3}from"./chunk-1beqtjsw.js";import{j as o1}from"./chunk-8sth12hd.js";import{w as t0,x as d2,y as T1,z as c1}from"./chunk-sa9fxss4.js";import{A as c2,B as l2,C as i2,D as m0}from"./chunk-v1k6nvth.js";import{E as h2,F as _$,G as N$,H as B$,I as G0,J as x$}from"./chunk-30p7aff1.js";import{$ as C2,Aa as N3,Da as U5,Ia as i3,N as m1,O as l3,R as T2,S as O1,T as i4,V as i1,W as p$,X as A4,Y as j4,Z as W0,_ as I2,aa as M$,ba as F1,da as S2,ea as P2,fa as b4,ga as N0,ha as B0,ka as C4,la as R4,ma as Q5,na as k2,oa as J2,pa as Z3,qa as J3,ra as Q3,sa as Y3,ta as X3,ua as V3,va as z3,wa as G3,xa as K3}from"./chunk-25s0c8km.js";import{Pa as E$,Va as iO}from"./chunk-pm5ssr7m.js";import{$a as E2,Ab as $$,Ya as Z2,_a as R2,ab as f2,gb as V4,jb as a3,kb as n4,lb as y2,mb as m2,nb as o3,ob as t3,pb as a4,qb as s3,rb as v0,sb as M3,tb as L3,ub as A3,vb as g2,wb as v2,xb as p2,yb as u2,zb as H$}from"./chunk-xseh3f4m.js";import{Ob as nO,Pb as i,Rb as m,Sb as q2,bc as _4,mc as g0}from"./chunk-7vzz3rsx.js";import{xc as g1}from"./chunk-9qxch6sy.js";import{$d as I4,Hd as M2,Nc as D2,Rd as o0,Sd as q0,Zd as T4,_d as q4,be as L1,ee as D4,fd as d$,jd as U4,je as b2,ke as M4,le as L4,me as g}from"./chunk-hmw99nm1.js";import{Ke as L2,Re as A2,Se as j2}from"./chunk-dxq7462e.js";import{lf as b3,pf as T3,qf as q3,rf as I3,sf as C3,tf as p4,uf as R3,vf as E3}from"./chunk-tqt5c2f5.js";import{Uf as Z5,Yf as LO,ag as k$,dg as tO}from"./chunk-7eset766.js";import{eg as l1}from"./chunk-5yyp6njq.js";import{xg as N2}from"./chunk-zfxcef0z.js";import{zg as D1}from"./chunk-g0hhqxpg.js";import{Ig as J5,Lg as $3,Pg as N1,Qg as B1,Ug as L5,Xg as O0,Yg as x1,_g as x2,ah as O$}from"./chunk-8n3jythp.js";import{th as h$,uh as B2}from"./chunk-vbjgcn49.js";import{yh as q$,zh as n0}from"./chunk-xzva8y4e.js";import{Bi as _2,Hh as B4,Oi as I$,Th as R$,Ti as _1,hi as K2,ki as w2,mi as H2,ni as W2,oi as g$,pi as v$,qi as W$,wi as U2,zi as F2}from"./chunk-yrr9mdjn.js";import{Yi as KO}from"./chunk-m30qwpe9.js";import{wj as a1,zj as x4}from"./chunk-hrtf7dba.js";import{Dj as OO,Fj as h,Hj as z,Ij as sO,Kj as GO}from"./chunk-9ydrwcpy.js";import{Pj as P0}from"./chunk-0wcnkxe8.js";import{Rj as S$,Sj as z2,Uj as P$,Vj as G2}from"./chunk-4cdk4mds.js";import{Xj as i0}from"./chunk-a1tt14a2.js";import{dk as e4}from"./chunk-zjezws85.js";import{Ak as k1,Ik as A$,ek as n1,yk as WO}from"./chunk-gzbb747a.js";import{Kk as t4}from"./chunk-f552hzcx.js";var F8={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 _8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as Z$,readFileSync as C1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as l6}from"node:os";import{dirname as i6,extname as n6,join as f0}from"node:path";import{fileURLToPath as a6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var l0=OO("Service"),y5=30000,m5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??H$.getInstance(),this.tickMs=O.tickMs??y5}start(){if(this.timer)return;l0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=m.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!m5.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,l0.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 Z of $)await this.evaluate(Z,O)}catch($){l0.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}),l0.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,Z={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Y=await this.dispatch({prompt:O.prompt,title:O.title??g5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Z.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Y.session.sessionId,lastStatus:Y.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),m.publish({sessionId:Y.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Y.session.sessionId,runId:Y.runId,status:Y.status}),l0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Y.session.sessionId} (${Y.status})`)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);l0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Y);let G=O.trigger.kind==="once"?null:Z.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:X,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Z){let Y=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!Y)return;await this.store.update(Y.id,{lastStatus:$,...Z?{lastError:Z}:{lastError:void 0}})}}function g5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class wO extends Error{code;statusCode;details;constructor(O,$,Z=500,J){super($);this.code=O;this.statusCode=Z;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class c extends wO{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends wO{constructor(O){super("BAD_REQUEST",O,400)}}class v extends wO{constructor(O){super("CONFLICT",O,409)}}class eO extends wO{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class MO extends wO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class b0 extends wO{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class lO extends wO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class zO extends wO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=z.Object({error:z.Object({code:z.String(),message:z.String(),details:z.Optional(z.Record(z.String(),z.Unknown()))})});import{Hono as v5}from"hono";var G4=OO("Service"),p5=z.Object({updates:z.Record(z.String(),z.Any()),options:z.Optional(z.Object({scope:z.Optional(GO(["local","project","global"])),immediate:z.Optional(z.Boolean())}))});function u5(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 U$=()=>{let O=new v5;return O.get("/",async($)=>{try{let Z=LO();return $.json(Z?u5(Z):{})}catch(Z){return G4.error("[ConfigRoutes] Failed to get config:",Z),$.json({})}}),O.put("/",async($)=>{try{let Z=await $.req.json(),J=h(p5,Z);if(!J.success)throw new F("Invalid config update format");let{updates:Y,options:X}=J.data;return await tO().updateConfig(Y,X),$.json({success:!0,updates:Y})}catch(Z){if(Z instanceof W$)throw new F(Z.message);throw G4.error("[ConfigRoutes] Failed to update config:",Z),Z}}),O.get("/permissions",async($)=>{try{let Z=LO();return $.json(Z?.permissions||{})}catch(Z){return G4.error("[ConfigRoutes] Failed to get permissions:",Z),$.json({})}}),O};import{Hono as d5}from"hono";import{streamSSE as c5}from"hono/streaming";function F$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
|
|
2
|
+
`;if(O.event!==void 0)$+=`event: ${O.event}
|
|
3
|
+
`;for(let Z of O.data.split(/\r\n|\r|\n/))$+=`data: ${Z}
|
|
4
|
+
`;if(O.retry!==void 0)$+=`retry: ${O.retry}
|
|
5
|
+
`;return $+=`
|
|
6
|
+
`,Buffer.byteLength($)}class W1{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??_$,this.maxPendingBytes=O.maxPendingBytes??N$,this.serial=new x$({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??B$,sizeOf:F$,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 G0("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 Z=O.replayed?$.filter((Y)=>Y.sequence!==void 0&&Y.sequence>this.highestReplaySequence).sort((Y,X)=>Y.sequence-X.sequence||Y.order-X.order):$.sort((Y,X)=>Y.order-X.order),J;for(let Y of Z){if(O.replayed&&Y.sequence!==void 0&&Y.sequence===J)continue;if(this.offerLive(Y.message,Y.sequence),this.serial.stats().closed)return;J=Y.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 Z=F$(O),J=this.serial.stats();if(Z>this.maxPendingBytes){this.fail(new G0("oversized",`SSE frame requires ${Z} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}if(J.pendingItems+this.buffered.length>=this.maxPendingItems||J.pendingBytes+this.bufferedBytes+Z>this.maxPendingBytes){this.fail(new G0("overflow","SSE initialization buffer limit exceeded",{pendingItems:J.pendingItems+this.buffered.length,pendingBytes:J.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:Z,sequence:$,order:this.nextOrder}),this.bufferedBytes+=Z}offerLive(O,$){if($!==void 0){if($<=this.highestReplaySequence)return;if($<=this.highestDeliveredSequence){this.fail(new G0("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 G0("closed","SSE egress is closed")}}var l5=15000,i5=OO("Service"),n5=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"]),a5=new Set(["queued","running","completed","failed","cancelled","interrupted"]),o5=new Set(["high","medium","low"]),t5=new Set(["feature","bug","maintenance","research"]);function s5(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,Z=["changedFiles","additions","deletions","commits"];if(Z.some((J)=>typeof $[J]!=="number"||!Number.isInteger($[J])||$[J]<0))return;return Object.fromEntries(Z.map((J)=>[J,$[J]]))}function U1(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function r5(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}:{},...U1($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}function D$(O,$){return $&&O instanceof G0&&(O.kind==="closed"||O.kind==="aborted")}var L$=()=>{let O=new d5,$=new F1;return O.onError((Z,J)=>{if(Z instanceof MO)return J.json(Z.toObject(),503);throw Z}),O.get("/",async(Z)=>{let J;try{J=$.enter(Z.req.raw.signal)}catch(X){if(X instanceof M$)throw new MO;throw X}let Y=!1;try{let X=c5(Z,async(G)=>{let H,B,M=!1,b,I,A=new Promise((_)=>{I=_}),f,L=()=>{if(B!==void 0)clearInterval(B),B=void 0;H?.(),H=void 0},R=(_)=>{if(f)return f;return M=!0,f=(async()=>{try{L(),b?.close(_),G.close()}finally{I()}})(),f},P=()=>{R(J.signal.reason)};if(J.signal.addEventListener("abort",P,{once:!0}),G.onAbort(()=>{R()}),J.signal.aborted){await R(J.signal.reason),J.signal.removeEventListener("abort",P),J.release();return}b=new W1({write:async(_)=>{await G.writeSSE(_)},onFailure:(_)=>{if(D$(_,M))return;i5.warn(`[EventRoutes] SSE egress closed: kind=${_.kind} pendingItems=${_.pendingItems??0} pendingBytes=${_.pendingBytes??0}`),R(_)}});let k=(_,e)=>{b?.observe({data:JSON.stringify({type:_,properties:e})})};H=m.subscribe((_)=>{if(!n5.has(_.type))return;if(_.type==="permission.asked"||_.type==="question.required"||_.type==="elicitation.required"){let a=_.properties.requestId;if(typeof a!=="string"||!a)return;k("interaction.pending",{sessionId:_.sessionId,projectPath:_.projectPath,interactionType:_.type==="question.required"?"question":_.type==="elicitation.required"?"elicitation":"permission",requestId:a});return}if(_.type==="interaction.resolved"){let a=_.properties.requestId;if(typeof a!=="string"||!a)return;k(_.type,{sessionId:_.sessionId,projectPath:_.projectPath,requestId:a});return}if(_.type==="session.created"||_.type==="session.deleted"||_.type==="session.archived"||_.type==="session.unarchived"){k(_.type,{sessionId:_.sessionId,projectPath:_.projectPath});return}if(_.type==="session.updated"){let a=_.properties.title,FO=_.properties.taskPriority,CO=_.properties.taskKind,PO=_.properties.taskDueAt,RO=typeof a==="string"&&Boolean(a.trim()),J0=o5.has(String(FO)),rO=t5.has(String(CO)),cO=PO===null||typeof PO==="string"&&Number.isFinite(Date.parse(PO));if(!RO&&!J0&&!rO&&!cO)return;k(_.type,{sessionId:_.sessionId,projectPath:_.projectPath,...RO?{title:a}:{},...J0?{taskPriority:FO}:{},...rO?{taskKind:CO}:{},...cO?{taskDueAt:PO}:{}});return}if(_.type==="task.delivery"){let a=r5(_.properties.taskDelivery);if(!a)return;k(_.type,{sessionId:_.sessionId,projectPath:_.projectPath,taskDelivery:a,..._.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof _.properties.updatedAt==="string"?{updatedAt:_.properties.updatedAt}:{}});return}if(_.type==="schedule.fired"){let a=_.properties.scheduleId,FO=_.properties.firedAt;if(typeof a!=="string"||typeof FO!=="string")return;k(_.type,{scheduleId:a,firedAt:FO,sessionId:_.sessionId,projectPath:_.projectPath,...typeof _.properties.runId==="string"?{runId:_.properties.runId}:{},...typeof _.properties.status==="string"?{status:_.properties.status}:{}});return}let e=_.properties.taskStatus;if(typeof e!=="string"||!a5.has(e))return;let p=s5(_.properties.taskDiffStat),UO=U1(_.properties.taskQueuePosition,1),y=U1(_.properties.taskQueueDepth,0),SO=U1(_.properties.taskConcurrencyLimit,1),YO=U1(_.properties.taskInFlight,0),u=typeof _.properties.taskAdmissionPaused==="boolean"?_.properties.taskAdmissionPaused:void 0;k(_.type,{sessionId:_.sessionId,projectPath:_.projectPath,taskStatus:e,...typeof _.properties.taskStatusReason==="string"?{taskStatusReason:_.properties.taskStatusReason}:{},..._.properties.taskFailure&&typeof _.properties.taskFailure==="object"?{taskFailure:_.properties.taskFailure}:{},...typeof _.properties.taskStartedAt==="string"?{taskStartedAt:_.properties.taskStartedAt}:{},...typeof _.properties.taskCompletedAt==="string"?{taskCompletedAt:_.properties.taskCompletedAt}:{},...typeof _.properties.updatedAt==="string"?{updatedAt:_.properties.updatedAt}:{},...p?{taskDiffStat:p}:{},...UO!==void 0?{taskQueuePosition:UO}:{},...y!==void 0?{taskQueueDepth:y}:{},...SO!==void 0?{taskConcurrencyLimit:SO}:{},...YO!==void 0?{taskInFlight:YO}:{},...u!==void 0?{taskAdmissionPaused:u}:{}})});try{if(G.aborted||M)return;if(await b.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),G.aborted||M)return;if(b.finishInitialization({replayed:!1}),G.aborted||M)return;B=setInterval(()=>{if(G.aborted||M)return;b?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},l5),await A}catch(_){if(D$(_,M))return;throw _}finally{await R(),J.signal.removeEventListener("abort",P),J.release()}});return Y=!0,X}catch(X){if(!Y)J.release();throw X}}),{app:O,shutdown:(Z)=>$.shutdown(Z),getSseConnectionStats:()=>$.stats()}};import{Hono as e5}from"hono";var O9=z.Object({paused:z.Boolean()}),j$=()=>{let O=new e5;return O.get("/health",($)=>{return $.json({healthy:!0,version:i0()})}),O.get("/info",($)=>{let Z=KO(),J=LO();if(J)N0.configure(J.maxConcurrentTasks,J.maxQueuedTasks,J.maxQueuedTaskBytes);let Y=N0.getStats();return $.json({version:i0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:Z,gitBranch:A$(Z),taskAdmission:{inFlight:Y.inFlight,queued:Y.queued,maxConcurrent:Y.maxConcurrent,maxQueued:Y.maxQueued,paused:Y.paused}})}),O.put("/task-admission",async($)=>{let Z;try{Z=await $.req.json()}catch{throw new F("Invalid request body")}let J=h(O9,Z);if(!J.success)throw new F("Invalid task admission control request");N0.setPaused(J.data.paused);let Y=N0.getStats();return $.json({inFlight:Y.inFlight,queued:Y.queued,maxConcurrent:Y.maxConcurrent,maxQueued:Y.maxQueued,paused:Y.paused})}),O};import{Hono as $9}from"hono";var Z9=z.Object({projectPath:z.String({minLength:1}),action:GO(["trust","revoke"]),expectedDigest:z.Optional(z.String())}),J9=z.Object({projectPath:z.String({minLength:1}),sessionId:z.String({minLength:1}),enabled:z.Boolean()});function K4(O){if(!O)throw new F("projectPath must be absolute");try{return WO(O)}catch{throw new F("projectPath must reference a local workspace")}}function b$(O){if(!O)throw new F("sessionId is required");try{k1(O)}catch($){throw new F($ instanceof Error?$.message:"sessionId is invalid")}return O}async function P1(O){let $=K4(O),Z=LO()?.hooks??I$.hooks,J=await _1.getInstance().loadWorkspaceHooks($,Z,{includeBaseForCurrentWorkspace:!1});return x1($,async()=>{B1($);let Y=n0.getInstance();return Y.loadConfig(J,$),await N1($),Y.getConfig($)})}function T$(O,$){let Z=n0.getInstance(),J=Z.getConfig($).enabled,Y=Z.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:Z.isSessionEnabled(O,$),paused:Y,configEnabled:J}}var C$=()=>{let O=new $9;return O.get("/trust",async($)=>{let Z=$.req.query("projectPath");if(!Z)throw new F("projectPath query parameter is required");return await P1(Z),$.json(await n0.getInstance().getTrustStatus(Z))}),O.post("/trust",async($)=>{let Z=h(Z9,await $.req.json());if(!Z.success)throw new F("Invalid hook trust request");let{projectPath:J,action:Y,expectedDigest:X}=Z.data;await P1(J);let G=n0.getInstance(),H;try{H=Y==="trust"?await G.trustProject(J,X):await G.revokeProjectTrust(J)}catch(B){if(B instanceof q$)throw new v(B.message);throw B}return $.json(H)}),O.get("/session",async($)=>{let Z=K4($.req.query("projectPath")),J=b$($.req.query("sessionId"));return await P1(Z),$.json(T$(J,Z))}),O.post("/session",async($)=>{let Z=h(J9,await $.req.json());if(!Z.success)throw new F("Invalid hook session request");let J=K4(Z.data.projectPath),Y=b$(Z.data.sessionId);await P1(J);let X=n0.getInstance();if(Z.data.enabled)X.enableSession(Y,J);else X.disableSession(Y,J);return $.json(T$(Y,J))}),O};import{Hono as Q9}from"hono";var K0=OO("Service");function Y9(O){try{return E$(O)}catch{return[]}}function X9(O){if(!h1(O)||!h1(O.reference)||!h1(O.argument))throw Error("Invalid MCP completion request");let $=O.reference.type,Z=$==="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(!Z||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let J;if(O.context!==void 0){if(!h1(O.context))throw Error("Invalid MCP completion context");J=Object.create(null);for(let[Y,X]of Object.entries(O.context)){if(typeof X!=="string")throw Error("Invalid MCP completion context");J[Y]=X}}return{reference:Z,argument:{name:O.argument.name,value:O.argument.value},...J?{context:J}:{}}}function h1(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function T0(O,$){let Z=LO()?.mcpServers??{};for(let[J,Y]of Object.entries(Z)){if($&&J!==$)continue;if(!O.getServerStatus(J))await O.registerServer(J,Y,{connect:!1})}}var f$=()=>{let O=new Q9;return O.get("/",async($)=>{try{let Z=iO.getInstance();await T0(Z);let J=Z.getAllServers(),Y=await Promise.all(Array.from(J.entries()).map(async([X,G])=>({id:X,name:X,status:G.status==="connected"?"connected":G.status==="reconnecting"?"reconnecting":G.status==="connecting"?"connecting":G.lastError?"error":"offline",endpoint:G.config.command?`${G.config.command} ${(G.config.args||[]).join(" ")}`.trim():G.config.url||"Unknown",description:`MCP server: ${X}`,tools:G.tools.map((H)=>H.name),completionSupported:G.client.completionSupported,tasks:G.client.tasks,resources:G.contentCatalog.resources,resourceTemplates:G.contentCatalog.resourceTemplates.map((H)=>({...H,variables:Y9(H.uriTemplate)})),prompts:G.contentCatalog.prompts,connectedAt:G.connectedAt?.toISOString(),error:G.lastError?.message,recovery:G.recovery,logging:G.logging,instructions:G.instructions,oauthEnabled:G.client.oauthEnabled,oauthStatus:await G.client.getOAuthStatus()})));return $.json(Y)}catch(Z){return K0.error("[McpRoutes] Failed to get MCP servers:",Z),$.json({error:Z instanceof Error?Z.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async($)=>{try{let Z=$.req.param("name"),J=iO.getInstance();return await T0(J,Z),await J.connectServer(Z),$.json({success:!0})}catch(Z){return K0.error("[McpRoutes] Failed to connect MCP server:",Z),$.json({success:!1,error:Z.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let Z=$.req.param("name"),J=iO.getInstance();return await T0(J,Z),await J.disconnectServer(Z),$.json({success:!0})}catch(Z){return K0.error("[McpRoutes] Failed to disconnect MCP server:",Z),$.json({success:!1,error:Z.message},500)}}),O.get("/:name/logs",async($)=>{try{let Z=$.req.param("name"),J=Number($.req.query("limit")??20),Y=Number($.req.query("afterRevision")??0);if(!Number.isSafeInteger(J)||J<1||J>100||!Number.isSafeInteger(Y)||Y<0)return $.json({error:"Invalid MCP log pagination"},400);let X=iO.getInstance();return await T0(X,Z),$.json(X.getLogSnapshot(Z,{limit:J,afterRevision:Y}))}catch(Z){return K0.error("[McpRoutes] Failed to get MCP logs:",Z),$.json({error:Z.message},500)}}),O.post("/:name/logging-level",async($)=>{try{let Z=$.req.param("name"),J=await $.req.json();if(!R$(J.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let Y=iO.getInstance();return await T0(Y,Z),await Y.setServerLoggingLevel(Z,J.level),$.json({success:!0,level:J.level})}catch(Z){return K0.error("[McpRoutes] Failed to set MCP logging level:",Z),$.json({success:!1,error:Z.message},400)}}),O.post("/:name/complete",async($)=>{try{let Z=$.req.param("name"),J=X9(await $.req.json()),Y=iO.getInstance();await T0(Y,Z);let X=await Y.complete(Z,J);return $.json(X)}catch(Z){return K0.error("[McpRoutes] Failed to complete MCP argument:",Z),$.json({error:Z.message},400)}}),O.post("/:name/oauth/login",async($)=>{try{let Z=$.req.param("name"),J=iO.getInstance();await T0(J,Z);let Y=await J.beginOAuthLogin(Z);return $.json({success:!0,flowId:Y.flowId,authorizationUrl:Y.authorizationUrl},202)}catch(Z){return K0.error("[McpRoutes] Failed to start MCP OAuth login:",Z),$.json({success:!1,error:Z.message},400)}}),O.post("/:name/oauth/logout",async($)=>{try{let Z=$.req.param("name"),J=iO.getInstance();return await T0(J,Z),await J.logoutOAuth(Z),$.json({success:!0})}catch(Z){return K0.error("[McpRoutes] Failed to log out MCP OAuth:",Z),$.json({success:!1,error:Z.message},400)}}),O.delete("/:name",async($)=>{try{let Z=$.req.param("name");await iO.getInstance().unregisterServer(Z);let Y=LO();if(Y?.mcpServers){let{[Z]:X,...G}=Y.mcpServers;await tO().updateConfig({mcpServers:G})}return $.json({success:!0})}catch(Z){return K0.error("[McpRoutes] Failed to delete MCP server:",Z),$.json({success:!1,error:Z.message},500)}}),O.post("/",async($)=>{try{let Z=await $.req.json(),{name:J,config:Y}=Z;if(!J||!Y)return $.json({success:!1,error:"Missing name or config"},400);await iO.getInstance().registerServer(J,Y);let G=LO();return await tO().updateConfig({mcpServers:{...G?.mcpServers,[J]:Y}}),$.json({success:!0})}catch(Z){return K0.error("[McpRoutes] Failed to add MCP server:",Z),$.json({success:!1,error:Z.message},500)}}),O};import{getSupportedThinkingLevels as V9}from"@earendil-works/pi-ai";import{Hono as z9}from"hono";var y1=OO("Service");function G9(O){let $=O||KO();try{return WO($,O?"directory":"cwd")}catch(Z){throw new F(Z instanceof Error?Z.message:"directory is invalid")}}function K9(O,$,Z=h$.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:V9($),supportedServiceTiers:P$($),supportedResponseVerbosities:S$($),communicationStyles:Z,input:$.input}}function w9(O){y$(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function y$(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new F("streamIdleTimeout must be at least 1000ms")}var m$=()=>{let O=new z9;return O.get("/",async($)=>{try{let Z=LO();if(!Z)throw Error("Config not initialized");let J=G9($.get("directory")),[Y,X]=await Promise.all([D1(J,Z),O0(J)]),G=Y.config.models,H=G.find((I)=>I.id===Y.config.currentModelId)??G[0],B=Y.catalog,M=X.communicationStyles.list(),b=(I)=>K9(I,B.resolveConfig(I),M);return $.json({configured:G.map(b),current:H?b(H):null})}catch(Z){if(Z instanceof F)throw Z;y1.error("[ModelsRoutes] Failed to get models:",Z);let J=new zO("Failed to get models");return $.json(J.toObject(),500)}}),O.post("/",async($)=>{let Z=P0(),J,Y;try{let X=await $.req.json(),{provider:G,displayName:H,model:B,overrides:M,apiKey:b,modelProvider:I}=X;if(!G||!B)throw new F("provider and model are required");y$(M);let A;if(I){if(I.id!==G)throw new F("modelProvider.id must match the model provider");if(LO()?.modelProviders[G])throw new F(`model provider already exists: ${G}`);A={name:I.name,baseUrl:I.baseUrl,wireApi:I.wireApi,...I.apiKeyEnv?{apiKeyEnv:I.apiKeyEnv}:{}};try{Z.registerModelProvider(G,A,[B]),Y=G}catch(R){throw new F(R instanceof Error?R.message:"Invalid model provider")}}else Z.getModel(G,B);if(b?.trim()){if(await Z.setApiKey(G,b.trim()),A)J=G}let f={provider:G,displayName:H||void 0,model:B,overrides:M||void 0},L=A?await tO().addModelWithProvider(f,A):await tO().addModel(f);return $.json({success:!0,model:L})}catch(X){if(J)await Z.credentials.delete(J);if(Y){let G=LO();Z.configureModelProviders(G?.modelProviders??{},G?.models??[])}throw y1.error("[ModelsRoutes] Failed to add model:",X),X}}),O.put("/:modelId",async($)=>{try{let Z=$.req.param("modelId"),J=await $.req.json(),{displayName:Y,overrides:X,model:G}=J,H=k$(Z);if(!H)throw new F("model config not found");if(G)P0().getModel(H.provider,G);return await tO().updateModel(Z,w9({displayName:Y,overrides:X,model:G})),$.json({success:!0})}catch(Z){throw y1.error("[ModelsRoutes] Failed to update model:",Z),Z}}),O.delete("/:modelId",async($)=>{try{let Z=$.req.param("modelId");return await tO().removeModel(Z),$.json({success:!0})}catch(Z){throw y1.error("[ModelsRoutes] Failed to delete model:",Z),Z}}),O};import{Hono as P9}from"hono";import{Mutex as B9}from"async-mutex";import{Hono as x9}from"hono";import{streamSSE as D9}from"hono/streaming";import{nanoid as Y2}from"nanoid";class Q0 extends Error{limit;resource="resident_session_projections";retryable=!0;constructor(O){super("Session projection capacity is full");this.limit=O;this.name="SessionProjectionCapacityError"}}class k0 extends Error{reason;constructor(O="Session projection residency is closed"){super(O);this.reason=O;this.name="SessionProjectionResidencyClosedError"}}class w0 extends Error{key;constructor(O,$=`Session projection residency already owns key: ${O}`){super($);this.key=O;this.name="SessionProjectionResidencyConflictError"}}class w4 extends Error{deadlineAt;constructor(O){super(`Session projection close wait timed out at ${O}`);this.deadlineAt=O;this.name="SessionProjectionResidencyCloseTimeoutError"}}function H9(O,$){if(O.size!==$.size)return!1;for(let[Z,J]of O)if(!$.has(Z)||$.get(Z)!==J)return!1;return!0}class H4{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(!g$(O.maxResident))throw Error("Invalid max resident Session projection limit");if(!v$(O.idleMs))throw Error("Invalid Session projection idle timeout");this.maxResident=O.maxResident,this.idleMs=O.idleMs,this.toSnapshot=O.toSnapshot,this.now=O.now??Date.now}acquire(O){if(this.assertNotClosed(),this.closings.has(O))throw new w0(O);let $=this.residents.get(O);if(!$||$.value===void 0)return;return $.pins++,this.createLease($)}reserve(O){this.assertNotClosed(),this.assertKeyOpen(O),this.makeCapacityForReservation();let $={key:O,generation:this.allocateGeneration()};return this.reservations.set(O,$),this.createReservation($)}snapshot(O){let $=this.residents.get(O);if(!$||$.value===void 0)return;return this.projectSnapshot($.value)}snapshotAll(){let O=[];for(let $ of this.residents.values()){if($.value===void 0)continue;let Z=this.projectSnapshot($.value);if(Z!==void 0)O.push(Z)}return O}beginCloseMany(O,$){this.assertNotClosed();let Z=[...new Set(O)].sort((L,R)=>L.localeCompare(R));for(let L of Z)if(this.closings.has(L))throw new w0(L,`Session projection residency is already closing key: ${L}`);let J=new Map,Y=new Map,X=new Map,G=new Set;for(let L of Z){let R=this.reservations.get(L);if(R)this.reservations.delete(L);let P=this.residents.get(L);if(P){if(this.residents.delete(L),P.phase="closing",X.set(L,P),this.closings.set(L,P),J.set(L,P.generation),G.add(L),P.value!==void 0){let _=this.projectSnapshot(P.value);if(_!==void 0)Y.set(L,_)}continue}let k={key:L,generation:R?.generation??this.allocateGeneration(),value:void 0,pins:0,lastUsedAt:this.now(),phase:"closing"};X.set(L,k),this.closings.set(L,k),J.set(L,k.generation)}let H={keys:Z,generations:J,snapshots:Y,entries:X,originalResidentKeys:G,waiters:new Set,state:"open"};this.closeStates.add(H),this.notifyCapacityAvailableIf(!0);let B=()=>{if(H.state==="committed")throw new k0("Session projection close set is already committed");if(H.state==="rolled_back")throw new k0("Session projection close set is already rolled back")},M=()=>{for(let L of H.entries.values())if(L.pins>0)return!1;return!0},b=()=>{if(!M())return;for(let L of H.waiters){if(L.timer!==void 0)clearTimeout(L.timer);L.removeAbortListener?.(),L.resolve()}H.waiters.clear()},I=({signal:L,deadlineAt:R}={})=>{if(H.state!=="open"||M())return Promise.resolve();if(R!==void 0&&R<=this.now())return Promise.reject(new w4(R));return new Promise((P,k)=>{let _={resolve:()=>P(),reject:k,timer:void 0,removeAbortListener:void 0};if(H.waiters.add(_),R!==void 0){let e=Math.max(0,R-this.now());_.timer=setTimeout(()=>{H.waiters.delete(_),_.removeAbortListener?.(),k(new w4(R))},e)}if(L){let e=()=>{if(H.waiters.delete(_),_.timer!==void 0)clearTimeout(_.timer);L.removeEventListener("abort",e),k(L.reason instanceof Error?L.reason:Error(String(L.reason??"AbortError")))};if(L.addEventListener("abort",e,{once:!0}),_.removeAbortListener=()=>{L.removeEventListener("abort",e)},L.aborted)e()}})},A=()=>{if(H.state==="committed")return;if(B(),!M())throw new w0(H.keys[0]??"","Session projection close set still has active pins");let L=!1;for(let R of H.keys){let P=H.entries.get(R);if(!P)continue;if(this.closings.get(R)===P){if(this.closings.delete(R),P.value!==void 0)L=!0}}H.state="committed",this.closeStates.delete(H),b(),this.notifyCapacityAvailableIf(L)},f=(L)=>{if(this.closed)throw new k0(this.closedReason);if(H.state==="committed")throw new k0("Session projection close set is already committed");if(H.state==="rolled_back"){if(!H.rollbackReplacements)return;if(!H9(H.rollbackReplacements,L))throw new w0(H.keys[0]??"","Session projection close set rollback replacements changed");return}if(!M())throw new w0(H.keys[0]??"","Session projection close set still has active pins");for(let _ of H.originalResidentKeys)if(!L.has(_))throw new w0(_,`Session projection close rollback requires replacement for key: ${_}`);let R=!1,P=!1,k=this.now();for(let _ of H.keys){let e=H.entries.get(_);if(!e)continue;if(this.closings.get(_)===e)this.closings.delete(_);if(!H.originalResidentKeys.has(_)){R||=e.value!==void 0;continue}let p=L.get(_);if(p===void 0){R||=e.value!==void 0;continue}if(e.value=p,e.phase="resident",e.lastUsedAt=k,this.residents.set(_,e),e.pins===0)P=!0}H.rollbackReplacements=new Map(L),H.state="rolled_back",this.closeStates.delete(H),b(),this.notifyCapacityAvailableIf(R||P)};return{keys:H.keys,generations:H.generations,snapshots:H.snapshots,waitForIdle:I,commit:A,rollback:f}}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[$,Z]of[...this.residents.entries()])this.residents.delete($),Z.phase="closing",this.closings.set($,Z);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 Z=[...this.residents.values()].filter((J)=>J.pins===0).sort((J,Y)=>J.lastUsedAt-Y.lastUsedAt||J.generation-Y.generation).find((J)=>O-J.lastUsedAt>=this.idleMs);if(!Z)return $;this.residents.delete(Z.key),$++,this.notifyCapacityAvailableIf(!0)}}onCapacityAvailable(O){return this.capacityListeners.add(O),()=>{this.capacityListeners.delete(O)}}getStats(){let O=0,$=0,Z=this.reservations.size,J=0;for(let Y of this.residents.values())if(O++,Y.pins>0)J++;for(let Y of this.closings.values())if($++,Y.pins>0)J++;return{resident:O,closing:$,reserved:Z,pinned:J,retained:O+Z+this.countClosingWithValue(),maxResident:this.maxResident,idleMs:this.idleMs}}getDebugStats(){let O=0,$=0;for(let Z of this.closings.values())if(Z.value===void 0)O++;for(let Z of this.closeStates)$+=Z.waiters.size;return{tombstones:O,waiters:$,listeners:this.capacityListeners.size}}assertNotClosed(){if(this.closed)throw new k0(this.closedReason)}assertKeyOpen(O){if(this.residents.has(O)||this.reservations.has(O)||this.closings.has(O))throw new w0(O)}retainedCount(){return this.residents.size+this.reservations.size+this.countClosingWithValue()}countClosingWithValue(){let O=0;for(let $ of this.closings.values())if($.value!==void 0)O++;return O}allocateGeneration(){let O=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,O}createReservation(O){let $=!1;return{key:O.key,generation:O.generation,commit:(Z)=>{if($)throw new w0(O.key);if(this.closed)throw this.reservations.delete(O.key),$=!0,new k0(this.closedReason);if(this.reservations.get(O.key)!==O)throw $=!0,new w0(O.key);this.reservations.delete(O.key);let J={key:O.key,generation:O.generation,value:Z,pins:1,lastUsedAt:this.now(),phase:"resident"};return this.residents.set(O.key,J),$=!0,this.createLease(J)},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 Z=this.residents.get(O.key);if(Z===O&&Z.generation===O.generation)return!0;let J=this.closings.get(O.key);return J===O&&J.generation===O.generation},release:()=>{if($)return;$=!0;let Z=this.residents.get(O.key),J=this.closings.get(O.key),Y=Z===O&&Z.generation===O.generation?Z:J===O&&J.generation===O.generation?J:void 0;if(!Y)return;Y.pins=Math.max(0,Y.pins-1),Y.lastUsedAt=this.now(),this.notifyCapacityAvailableIf(!0),this.resolveIdleWaitersForEntry(Y),this.maybeFinishInvalidation()}}}makeCapacityForReservation(){while(this.retainedCount()>=this.maxResident){let O=[...this.residents.values()].filter(($)=>$.pins===0).sort(($,Z)=>$.lastUsedAt-Z.lastUsedAt||$.generation-Z.generation)[0];if(!O)throw new Q0(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 Z=!0;for(let J of $.entries.values())if(J.pins>0){Z=!1;break}if(!Z)continue;for(let J of $.waiters){if(J.timer!==void 0)clearTimeout(J.timer);J.removeAbortListener?.(),J.resolve()}$.waiters.clear()}}maybeFinishInvalidation(){if(!this.closed||!this.resolveInvalidation)return;for(let $ of this.closings.values())if($.pins>0)return;this.closings.clear();let O=this.resolveInvalidation;this.resolveInvalidation=void 0,O()}notifyCapacityAvailableIf(O){if(!O)return;for(let $ of[...this.capacityListeners])try{$()}catch{}}}class W4{runtimes=new Map;createRuntime;constructor(O={}){this.createRuntime=O.createRuntime??(($)=>new p$($.projectPath,`web-browser:${$.sessionId}`,{exposeArtifactPaths:!1}))}get(O){let $=i(O),Z=this.runtimes.get($);if(Z?.state==="live")return Z.runtime;if(Z)throw new m1("browser_disposed","Browser Session Runtime is closed",{retryable:!0});let J=this.createRuntime(O);return this.runtimes.set($,{state:"live",runtime:J}),J}async reset(O){let $=this.runtimes.get(i(O));if($?.state==="live")await $.runtime.page({action:{kind:"reset"}})}dispose(O){let $=i(O),Z=this.runtimes.get($);if(!Z)return Promise.resolve();if(Z.state==="disposing")return Z.disposePromise;return this.disposeKey($,Z.runtime)}async disposeAll(){let $=(await Promise.allSettled([...this.runtimes.keys()].map((Z)=>{let J=this.runtimes.get(Z);if(!J)return Promise.resolve();if(J.state==="disposing")return J.disposePromise;return this.disposeKey(Z,J.runtime)}))).find((Z)=>Z.status==="rejected");if($)throw $.reason}stats(){let O=0,$=0,Z=0;for(let J of this.runtimes.values()){if(J.state==="live")O++;if(J.state==="disposing")$++;if(J.state==="failed")Z++}return{sessions:this.runtimes.size,live:O,disposing:$,failed:Z}}disposeKey(O,$){let Z=$.dispose().then(()=>{if(this.runtimes.get(O)?.runtime===$)this.runtimes.delete(O)},(J)=>{if(this.runtimes.get(O)?.runtime===$)this.runtimes.set(O,{state:"failed",runtime:$,error:J});throw J});return this.runtimes.set(O,{state:"disposing",runtime:$,disposePromise:Z}),Z}}import{Hono as U9}from"hono";var u$=z.Object({action:GO(["accept","dismiss"])},{additionalProperties:!1}),W9=sO(z.Union([z.Object({kind:z.Literal("click"),dialog:z.Optional(u$)},{additionalProperties:!1}),z.Object({kind:z.Literal("click_at"),screenshotId:z.String({minLength:1,maxLength:d$}),x:z.Integer({minimum:0,maximum:U4}),y:z.Integer({minimum:0,maximum:U4}),dialog:z.Optional(u$)},{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:GO(["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:GO(["up","down","left","right"]),amount:z.Integer()},{additionalProperties:!1})])),c$=sO(z.Object({action:z.Optional(GO(["goto","back","forward","reload"])),url:z.Optional(z.String()),pageId:z.Optional(z.String()),expectedOrigin:z.Optional(z.String()),waitUntil:z.Optional(GO(["commit","domcontentloaded","load"])),timeoutMs:z.Optional(z.Integer())},{additionalProperties:!1})),l$=sO(z.Object({pageId:z.String(),snapshotId:z.String(),ref:z.Optional(z.String()),expectedOrigin:z.String(),action:W9,timeoutMs:z.Optional(z.Integer())},{additionalProperties:!1}));function i$(O,$){if(O===void 0)return;let Z=Number(O);if(!Number.isSafeInteger(Z))throw new F(`${$} must be an integer`);return Z}function F9(O,$){if(O===void 0)return;if(O==="true")return!0;if(O==="false")return!1;throw new F(`${$} must be true or false`)}function _9(O){let $=O.code==="browser_not_installed"||O.code==="browser_disconnected"||O.code==="browser_disposed"?503:O.code==="browser_capacity"?429:O.code==="browser_unsupported"?400:409;return new wO(O.code.toUpperCase(),O.message,$,O.details)}function n$(O){let $=new U9;$.use("*",(J,Y)=>O.withAdmission(Y)),$.onError((J,Y)=>{let X=J instanceof m1?_9(J):J instanceof wO?J:new zO;return Y.json(X.toObject(),X.statusCode)});let Z=(J,Y)=>O.resolveSessionRef(J,Y);return $.post("/:sessionId/browser/navigate",async(J)=>{let Y=await J.req.json().catch(()=>{return}),X=h(c$,Y);if(!X.success)throw new F("Invalid browser navigation request");let G=await Z(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(await O.getRuntime(G).navigate(X.data))}),$.post("/:sessionId/browser/interact",async(J)=>{let Y=await J.req.json().catch(()=>{return}),X=h(l$,Y);if(!X.success)throw new F("Invalid browser interaction request");let G=await Z(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(await O.getRuntime(G).interact(X.data))}),$.get("/:sessionId/browser/snapshot",async(J)=>{let Y=await Z(J.req.param("sessionId"),J.req.query("projectPath")),X=i$(J.req.query("depth"),"depth"),G=F9(J.req.query("includeBoxes"),"includeBoxes");return J.json(await O.getRuntime(Y).snapshot({...J.req.query("pageId")?{pageId:J.req.query("pageId")}:{},...X===void 0?{}:{depth:X},...G===void 0?{}:{includeBoxes:G}}))}),$.get("/:sessionId/browser/inspect",async(J)=>{let Y=await Z(J.req.param("sessionId"),J.req.query("projectPath")),X=J.req.query("target"),G=J.req.query("pageId"),H=J.req.query("expectedOrigin");if(X==="screenshot"){let b=J.req.query("source")??"user";if(b!=="user"&&b!=="agent")throw new F("Unsupported browser screenshot source");if(b==="agent"&&(!G||!H))throw new F("Agent browser screenshots require pageId and expectedOrigin");let I={...G?{pageId:G}:{},...H?{expectedOrigin:H}:{}},A=b==="agent"?await O.captureAgentScreenshot(Y,I):await O.getRuntime(Y).screenshot(I);return new Response(new Uint8Array(A),{headers:{"Content-Type":"image/png","Content-Length":String(A.length),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}let B=i$(J.req.query("limit"),"limit"),M={...G?{pageId:G}:{},...H?{expectedOrigin:H}:{}};if(X==="find"){let b=J.req.query("text");if(!b)throw new F("text is required for browser find");return J.json(await O.getRuntime(Y).inspect({...M,target:{kind:"find",text:b,...B===void 0?{}:{limit:B}}}))}if(X!=="console"&&X!=="page-errors"&&X!=="network")throw new F("Unsupported browser inspection target");return J.json(await O.getRuntime(Y).inspect({...M,target:{kind:X,...B===void 0?{}:{limit:B}}}))}),$.post("/:sessionId/browser/reset",async(J)=>{let Y=await Z(J.req.param("sessionId"),J.req.query("projectPath"));return await O.resetRuntime(Y),J.json({success:!0})}),$}import{nanoid as u1}from"nanoid";import{LRUCache as N9}from"lru-cache";var H0=new Map,v1=new N9({max:100,ttl:1800000});function QO(O){return{sessionId:O.id,projectPath:O.projectPath}}function a$(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function o$(O){H0.set(O.id,O)}function mO(O){if(!O)return;return H0.get(O)??v1.get(O)}function t$(O){if(H0.get(O.id)!==O)return;H0.delete(O.id),v1.set(O.id,O)}function s$(O){H0.delete(O),v1.delete(O)}function gO(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function h0(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed"||O.status==="attention_required")return!1;let Z=O.pendingPermission;if(O.pendingPermission=void 0,Z?.resolve({approved:!1,reason:g1}),Z)m.publish(a$(O),"interaction.resolved",{requestId:Z.permissionId});return O.abortController.abort($),O.status="cancelled",m.publish(a$(O),"run.cancelled",{runId:O.id}),!0}function r$(O){for(let $ of H0.values())h0($,O);H0.clear(),v1.clear()}function F4(){return[...H0.values()]}function e$(){return H0.size}function O2(O,$){return[...H0.values()].find((Z)=>Z.sessionId===O.sessionId&&Z.projectPath===O.projectPath&&Z.pendingPermission?.permissionId===$)}function p1(O,$=!1){let{permissionId:Z,details:J}=O;if(J.type==="askUserQuestion"&&J.questions)return{type:"question.required",properties:{requestId:Z,toolCallId:J.toolCallId??Z,questions:J.questions,details:J,...$?{replayed:!0}:{}}};if(J.type==="mcpElicitation"&&J.mcpElicitation)return{type:"elicitation.required",properties:{requestId:Z,toolCallId:J.toolCallId??Z,elicitation:J.mcpElicitation,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:Z,toolName:J.toolName,description:J.message,args:J.args,details:J,...$?{replayed:!0}:{}}}}function $0(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 Y0(O){let $=await g.findSessionMetadata(O.id,O.projectPath);if($)$0(O,$)}var a0=OO("Service"),d1="web-pending-resume-recovery-budget-exhausted";class M1 extends Error{evidence;constructor(O){super(O.taskFailure.message);this.evidence=O;this.name="WebAgentRunFailure"}}function $2(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
|
|
7
|
+
`)}async function Q2(O,$,Z,J,Y,X={}){let{abortController:G,sessionId:H,id:B}=O,M=X.preparedInputTurn?.messageId??u1(12),I=X.pendingInputOnly===!0||X.preparedInputTurn?.mode==="pending"||X.goalContinuationOnly===!0?void 0:u1(12),A=X.runtimeLease,f=X.projectionLease,L,R,P=!1,k=!1,_,e=QO($),p=X.pendingResume?.projectedInputIds??new Set,UO=(u)=>{if(p.has(u))return;if(p.size>=Z2){let a=p.values().next().value;if(a!==void 0)p.delete(a)}p.add(u)},y=(u,a)=>{m.publish(e,u,a)},SO=async(u)=>{let a=u.metadata?.recoveryAttention;if(!a||!L)return!1;if(X.preparedInputTurn)await L.finishTurn(X.preparedInputTurn.handle,{preserveStartupRecovery:!0,outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}}).catch(()=>{return});let FO=`Turn recovery requires attention: ${a.reason}`,CO=await L.setTaskStatus("interrupted",FO).catch(()=>{return});if(CO)$0($,CO);else $.taskStatus="interrupted",$.taskStatusReason=FO,$.taskCompletedAt=void 0;return O.status="attention_required",y("session.status",{status:"idle"}),!0},YO=async()=>{let u=String(G.signal.reason||"Task run cancelled");if($.taskIsolation){if(!A)A=await Y($).catch(()=>{return});let a=L??A?.value;if(u==="user-cancel")await a?.discardPendingInput().catch((CO)=>{a0.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,CO)});let FO=await a?.setTaskStatus("cancelled",u).catch(()=>{return});if(FO)$0($,FO);else await Y0($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=u,$.taskCompletedAt??=new Date().toISOString()};try{if(X.pendingResume){let T=X.pendingResume.deadlineAt-Date.now();if(T<=0)throw G.abort(d1),new M1({taskFailure:o0("timeout"),outputStarted:!1,toolExecutionStarted:!1,toolCallsCount:0});_=setTimeout(()=>{G.abort(d1);let JO=O.pendingPermission;if(O.pendingPermission=void 0,JO?.resolve({approved:!1,reason:g1}),JO)y("interaction.resolved",{requestId:JO.permissionId})},T),_.unref?.()}if(X.taskAdmission){if(await X.taskAdmission.ready,await O.taskAdmissionUpdate,G.signal.aborted)throw Error(String(G.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!X.pendingInputOnly&&!X.goalContinuationOnly)y("message.created",{messageId:M,role:"user",content:$2(Z),...X.preparedInputTurn?.metadata?{metadata:X.preparedInputTurn.metadata}:{}});if(y("session.status",{status:"running"}),I)y("message.created",{messageId:I,role:"assistant",content:""});A??=await Y($),L=A.value;let u=L,a=Boolean(X.outputSchema??u.getPendingSteeringMessages().find((T)=>T.outputSchema)?.outputSchema);R=await J2.createWithRuntime(u,{sessionId:H,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let FO=async(T)=>{let JO=T.interactionRequestId??u1(12),_O=300000;O.status="waiting_permission";let R1=new Promise((d0)=>{let O4=setTimeout(()=>{a0.warn(`[SessionRoutes] Permission ${JO} timed out after 300000ms`),y("permission.timeout",{requestId:JO}),d0({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:JO,resolve:(c0)=>{clearTimeout(O4),d0(c0)},details:T}}),z1=O.pendingPermission;if(!z1)throw Error("Permission request was not registered");let E1=p1(z1);y(E1.type,E1.properties),a0.info(`[SessionRoutes] Permission request created: ${JO}, runId: ${B}`);let G1=await R1;if(a0.info(`[SessionRoutes] Permission response received: ${JO}, approved: ${G1.approved}`),!G.signal.aborted)O.status="running";if(O.pendingPermission===z1)O.pendingPermission=void 0;return y("interaction.resolved",{requestId:JO}),G1},PO={messages:await g.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:H,workspaceRoot:$.projectPath,signal:G.signal,permissionMode:J,onPermissionModeChange:async(T)=>{$.permissionMode=T,$.updatedAt=new Date,y("session.updated",{permissionMode:T})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:FO}},RO=()=>{if(!I)I=u1(12),y("message.created",{messageId:I,role:"assistant",content:""});return I},J0=async(T)=>{if(T.kind==="tool_start"||T.kind==="tool_progress"||T.kind==="tool_result")k=!0;let JO=c1(T);if(JO){if(JO.toolName===L1)return;y(JO.type,{...JO.messageScoped?{messageId:RO()}:{},...JO.properties});return}switch(T.kind){case"content_delta":if(T.delta.length>0)P=!0;if(a)break;y("message.delta",{messageId:RO(),delta:T.delta});break;case"structured_output":P=!0,y("structured.output",{messageId:RO(),output:T.output,schemaDigest:T.schemaDigest});break;case"thinking_delta":if(T.delta.length>0)P=!0;y("thinking.delta",{messageId:RO(),delta:T.delta});break;case"token_usage":y("token.usage",{...T.usage});break;case"turn_start":y("turn.started",{turn:T.turn,maxTurns:T.maxTurns});break;case"turn_recovery":y("turn.recovery",{assessment:T.assessment});break;case"provider_recovery":case"turn_activity":break;case"steering_applied":for(let _O of T.messages){if((_O.origin??"user")!=="user")continue;if(_O.persisted)continue;if(p.has(_O.id))continue;y("message.created",{messageId:_O.id,role:"user",content:$2(_O.content),..._O.metadata?{metadata:_O.metadata}:{},..._O.recovered?{recovered:!0}:{}}),UO(_O.id)}y("steering.applied",{runId:B,messageIds:T.messageIds,count:T.count,recovered:T.recovered,delivery:T.delivery,queued:u.getPendingSteeringCount()}),y("follow_up.queue.changed",{queue:T.queue});break;case"follow_up_started":if(I)y("message.complete",{messageId:I}),I=void 0;y("follow_up.started",{runId:B,queued:T.queued,recovered:T.recovered}),y("follow_up.queue.changed",{queue:T.queue}),RO();break;case"follow_up_queue_changed":y("follow_up.queue.changed",{queue:T.queue});break;case"goal_updated":y("goal.updated",{goal:T.goal});break;case"goal_continuation_started":y("goal.continuation.started",{goal:T.goal,continuation:T.continuation,...T.prematureStopPattern?{prematureStopPattern:T.prematureStopPattern}:{},...T.prematureStopCount!==void 0?{prematureStopCount:T.prematureStopCount}:{}}),RO();break;case"compaction":y(T.phase==="start"?"compaction.started":"compaction.completed",{...T.reason?{reason:T.reason}:{},...T.strategy?{strategy:T.strategy}:{},...T.outcome?{outcome:T.outcome}:{},...T.preTokens!==void 0?{preTokens:T.preTokens}:{},...T.preTokenSource?{preTokenSource:T.preTokenSource}:{},...T.estimatedPendingTokens!==void 0?{estimatedPendingTokens:T.estimatedPendingTokens}:{},...T.postTokens!==void 0?{postTokens:T.postTokens}:{},...T.sampleAttempts!==void 0?{sampleAttempts:T.sampleAttempts}:{},...T.inputReductions!==void 0?{inputReductions:T.inputReductions}:{},...T.messagesOmitted!==void 0?{messagesOmitted:T.messagesOmitted}:{},...T.filesOmitted!==void 0?{filesOmitted:T.filesOmitted}:{},...T.imagesOmitted!==void 0?{imagesOmitted:T.imagesOmitted}:{},...T.fallbackTargetTokens!==void 0?{fallbackTargetTokens:T.fallbackTargetTokens}:{},...T.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:T.fallbackMessagesOmitted}:{},...T.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:T.fallbackMessagesTruncated}:{},...T.failureReason?{failureReason:T.failureReason}:{},...T.memory?{memory:T.memory}:{}});break;case"model_fallback":y("model.fallback",{from:T.from,to:T.to,candidate:T.candidate,candidateCount:T.candidateCount,trigger:T.trigger});break;case"task_update":y("task.updated",{tasks:T.tasks});break;case"goal_frontier_updated":y("goal.frontier.updated",{goalId:T.goal.goalId,goalStatus:T.goal.status,frontier:T.frontier,stall:T.goal.frontierStall});break;default:break}},rO=(T)=>{let JO=T.metadata?.toolCallsCount;return new M1({taskFailure:q0(T.error?.details??T.error?.message??"Agent run failed"),outputStarted:P,toolExecutionStarted:k,toolCallsCount:typeof JO==="number"&&Number.isInteger(JO)?JO:-1})},cO=await _4(R.chatStream(Z,PO,{stream:!0,pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:X.taskAdmission}),J0);if(await SO(cO))return;if(!cO.success)throw rO(cO);for(let T=0;T<20;T++){let JO=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,u.getPendingSteeringCount()===0){if(!JO)break;continue}if(G.signal.aborted)break;if(cO=await _4(R.chatStream("",PO,{stream:!0,pendingInputOnly:!0,taskAdmission:X.taskAdmission}),J0),await SO(cO))return;if(!cO.success)throw rO(cO)}if(await Y0($),X.pendingResume&&G.signal.aborted&&G.signal.reason===d1)throw new M1({taskFailure:o0("timeout"),outputStarted:P,toolExecutionStarted:k,toolCallsCount:Number.isInteger(cO.metadata?.toolCallsCount)?cO.metadata?.toolCallsCount??-1:-1});if(G.signal.aborted||O.status==="cancelled"){await YO(),y("session.status",{status:"idle"});return}if(X.pendingResume)X.onPendingResumeSuccess?.(X.pendingResume);if(I)y("message.complete",{messageId:I});y("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),y("session.completed",{runId:B,outputTruncated:cO.metadata?.outputTruncated??!1}),y("session.status",{status:"idle"})}catch(u){if(L&&X.preparedInputTurn)await(L.getTurnRecoveryAssessment().state==="requires_attention"?L.finishTurn(X.preparedInputTurn.handle,{preserveStartupRecovery:!0}):L.finishTurn(X.preparedInputTurn.handle)).catch(()=>{return});let a=X.pendingResume!==void 0&&G.signal.aborted&&G.signal.reason===d1;if(G.signal.aborted&&!a||O.status==="cancelled"){if(X.pendingResume)X.onPendingResumeCancelled?.(X.pendingResume);h0(O,"runtime-abort"),await YO(),y("session.status",{status:"idle"});return}let FO=u instanceof M1?u.evidence:a?{taskFailure:o0("timeout"),outputStarted:P,toolExecutionStarted:k,toolCallsCount:-1}:X.pendingResume?{taskFailure:q0(u),outputStarted:!0,toolExecutionStarted:!0,toolCallsCount:-1}:void 0,CO=X.pendingResume!==void 0&&FO!==void 0&&X.onPendingResumeFailure?.(X.pendingResume,FO,a||(L?.getPendingSteeringCount()??0)>0,a)===!0;if(O.status="failed",CO){let RO=await L?.setTaskStatus("running").catch(()=>{return});if(RO)$0($,RO);$.taskStatus="running",$.taskStatusReason=void 0,$.taskFailure=void 0,$.taskCompletedAt=void 0,y("session.status",{status:"running"});return}await Y0($).catch(()=>{return}),a0.error("[SessionRoutes] Agent execution error:",u),$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let PO=FO?.taskFailure??q0(u);if(!$.taskFailure){let RO=L?await L.setTaskStatus("failed",u).catch(()=>{return}):await g.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:PO.message,taskFailure:PO,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(RO)$0($,RO)}$.taskStatusReason??=PO.message,$.taskFailure??=PO,y("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),y("session.status",{status:"error"})}finally{if(_)clearTimeout(_);if(X.taskAdmission?.release(),X.taskAdmission){let u=N0.getStats();y("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:u.queued,taskConcurrencyLimit:u.maxConcurrent,taskInFlight:u.inFlight,taskAdmissionPaused:u.paused,updatedAt:new Date().toISOString()})}if(await R?.destroy().catch(()=>{return}),A?.release(),f?.release(),O.disposeRuntimeOnSettle&&X.disposeRuntime)await X.disposeRuntime($,L).catch((u)=>{a0.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,u)});t$(O)}}var t=OO("Service"),M9=z.Object({title:z.Optional(z.String()),projectPath:z.Optional(z.String())}),L9=g2,A9=sO(z.Object({projectPath:z.Optional(z.String()),expectedVersion:R2,operation:f2},{additionalProperties:!1})),j9=new Set(["revision_conflict","already_claimed","immutable_origin","immutable_boundary","not_found","runtime_unavailable","invalid_mutation","storage_unavailable"]);function b9(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"&&j9.has($.code)&&h(E2,$.snapshot).success}var T9=z.Object({title:z.Optional(z.String()),projectPath:z.Optional(z.String())}),q9=z.Object({projectPath:z.String()}),I9=z.Object({objective:z.String({minLength:1}),tokenBudget:z.Optional(z.Integer({minimum:1})),permissionMode:z.Optional(GO(["default","autoEdit","plan","yolo"]))}),C9=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})})]),U0,b1,x0=new Map,X0=new Map;function R9(O){let $=structuredClone({...O,createdAt:O.createdAt.toISOString(),updatedAt:O.updatedAt.toISOString()});return{...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)}}function E9(O){if(O.type.startsWith("committed.")){let $=O.properties.event;if(!$||typeof $!=="object"||Array.isArray($))return;let Z=n2($);if(!Z)return;return{...Z.seq!==void 0?{id:String(Z.seq)}:{},data:JSON.stringify({type:Z.type,...Z.seq!==void 0?{seq:Z.seq}:{},properties:{...Z.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 f9(){let O=U0;if(O)O.accepting=!1,O.invalidateAll("route-reset");U0=void 0,r$("route-reset");for(let $ of x0.values())$.controller.abort("route-reset");x0.clear(),b1?.(),b1=void 0}function n2(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 Z=O.data.payload;return{type:"tool.start",...$,properties:{messageId:O.data.messageId,toolCallId:Z.toolCallId??O.data.partId,toolName:Z.toolName??"unknown",arguments:JSON.stringify(Z.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let Z=O.data.payload,J=Z.toolName??"unknown",Y=q4(Z),X=I4(C4(J,Y),T4);return{type:"tool.result",...$,properties:{messageId:O.data.messageId,toolCallId:Z.toolCallId??O.data.partId,toolName:J,success:Y.success,status:Y.success?"completed":"failed",summary:Y.metadata?.summary,output:R4(X),metadata:T1(J,Y.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function S9(O,$,Z){let J=c1(Z);if(J){if(J.type==="tool.start")m.publish(O,"subagent.update",{subagentSessionId:$,toolName:J.toolName});m.publish(O,`subagent.${J.type}`,{subagentSessionId:$,...J.properties});return}switch(Z.kind){case"content_delta":m.publish(O,"subagent.delta",{subagentSessionId:$,delta:Z.delta});break;case"thinking_delta":m.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:Z.delta});break;case"stream_end":m.publish(O,"subagent.stream.end",{subagentSessionId:$});break;default:break}}function I0(O,$="projectPath"){try{return WO(O,$)}catch(Z){throw new F(Z instanceof Error?Z.message:`${$} is invalid`)}}function j1(O){try{k1(O)}catch($){throw new F($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function A1(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 N4(O){return O.flatMap(($)=>{if(!L2($)||$.role==="system"||$.role==="tool"&&$.name===L1)return[];let Z=$.tool_calls?.filter((G)=>!("function"in G)||G.function.name!==L1),J=typeof $.content==="string"?$.content.trim():"";if($.role==="assistant"&&$.tool_calls?.length&&!Z?.length&&!J&&!$.reasoningContent&&!$.metadata)return[];let Y={...$,...$.tool_calls?{tool_calls:Z&&Z.length>0?Z:void 0}:{}};if($.role==="tool"){let G=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0,H=$.name??(typeof G?.toolName==="string"?G.toolName:"unknown");if(G!==void 0&&(Object.hasOwn(G,"output")||Object.hasOwn(G,"error"))){let M=q4(G),b=I4(C4(H,M),T4);return[{...Y,name:H,content:R4(b),metadata:T1(H,{...M.metadata,status:M.success?"completed":"failed"})}]}return[{...Y,name:H,metadata:T1(H,G)}]}let X=j2($.metadata);return[X?{...Y,content:A2(X)}:Y]})}function y0(O){let $=mO(O.currentRunId),Z=$?.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:Z,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:Z==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:Z==="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 uO(O,$){let Z=U0;if(Z?.accepting)return Z.resolveSessionRef(O,$);if(j1(O),$!==void 0){let Y=nO({sessionId:O,projectPath:I0($)}),X=await g.findSessionMetadata(Y.sessionId,Y.projectPath);if(!X)throw new c("Session",O);return nO({sessionId:X.sessionId,projectPath:X.projectPath})}let J=new Map;for(let Y of await g.listSessions()){if(Y.sessionId!==O)continue;let X=nO({sessionId:Y.sessionId,projectPath:Y.projectPath});J.set(i(X),X)}if(J.size===0)try{let Y=await g.findSessionMetadata(O);if(!Y)throw new c("Session",O);return nO({sessionId:Y.sessionId,projectPath:Y.projectPath})}catch(Y){if(Y instanceof c)throw Y;if(Y instanceof Error&&Y.message.startsWith("Ambiguous session ID:"))throw new lO;throw Y}if(J.size>1)throw new lO;return J.values().next().value}function X2(O,$){let Z=($??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(Z.length===0)return O;let J=[];if(O.trim())J.push({type:"text",text:O});return J.push(...Z),J}function V2(O,$){return $&&O instanceof G0&&(O.kind==="closed"||O.kind==="aborted")}var a2=()=>{f9();let O=new x9;O.onError((Q,w)=>{if(Q instanceof t0){let V=new eO("Session runtime capacity is full",{resource:Q.resource,limit:Q.limit});return w.json(V.toObject(),429)}if(Q instanceof Q0){let V=new eO("Session projection capacity is full",{resource:Q.resource,limit:Q.limit,retryable:Q.retryable});return w.json(V.toObject(),429)}if(Q instanceof wO)return w.json(Q.toObject(),Q.statusCode);return t.error("[SessionRoutes] Unhandled route error:",Q),w.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,Z=new W4,J=new Map,Y=new Map,X=new Map,G=new Set,H=new B4,B=new B4,M=new B9,b=LO(),I=new d2({maxResident:b?.maxResidentSessionRuntimes??U2,idleMs:b?.sessionRuntimeIdleMs??F2}),A=new H4({maxResident:b?.maxResidentSessionProjections??K2,idleMs:b?.sessionProjectionIdleMs??w2,toSnapshot:R9}),f=new F1,L=new F1,R=setInterval(()=>{I.sweepIdle().catch((Q)=>{t.warn("[SessionRoutes] Session Runtime idle sweep failed:",Q)})},_2);R.unref?.();let P=setInterval(()=>{try{A.sweepIdle()}catch(Q){t.warn("[SessionRoutes] Session projection idle sweep failed:",Q)}},H2);P.unref?.();let k,_=new Map,e=1,p,UO=(Q)=>{let w=Q.projectionLease;Q.projectionLease=void 0,w?.release()},y=()=>{for(let Q of _.values()){if(Q.timer)clearTimeout(Q.timer);UO(Q)}_.clear()};b1=y;let SO=async(Q,w)=>{let V;try{V=f.enter(w)}catch{throw new MO}try{return await Q(V.signal)}finally{V.release()}};O.use("*",async(Q,w)=>{if(Q.req.method==="GET"||Q.req.method==="HEAD")return w();return SO((V)=>{return Q.set("requestSignal",V),w()},Q.req.raw.signal)});let YO=(Q,w)=>H.runExclusive(i(Q),w),u=(Q,w)=>{let V=i(Q),K=_.get(V);if(!K||w!==void 0&&K.generation!==w)return;if(K.timer)clearTimeout(K.timer);UO(K),_.delete(V)},a=(Q,w)=>{let V=_.get(i(QO(Q)));return V?.generation===w.generation&&V.attempt===w.attempt&&V.inFlight&&!V.terminal},FO=(Q,w)=>{let V=i(QO(Q)),K=_.get(V);if(K){if(w?.release(),K.inFlight||K.timer||K.terminal)return}else{if(!w)throw new MO;K={attempt:0,generation:e++,inFlight:!1,projectedInputIds:new Set,projectionLease:w,startedAt:Date.now(),terminal:!1,timer:void 0},_.set(V,K)}return K.inFlight=!0,K.attempt++,{attempt:K.attempt,deadlineAt:K.startedAt+l2,generation:K.generation,projectedInputIds:K.projectedInputIds}},CO=(Q,w,V,K,W)=>{m.publish(Q,"pending.resume",{phase:w,kind:"pending_input",attempt:V,maxAttempts:c2,...W===void 0?{}:{delayMs:W,nextRetryAt:Date.now()+W},...K?{failure:{code:K.code,retryable:K.retryable,...K.resource?{resource:K.resource}:{}}}:{}})},PO=(Q,w,V,K,W,U)=>{let x=QO(Q),N=i(x),j=_.get(N);if(!j||j.generation!==w.generation)return!1;if(U)return j.inFlight=!1,j.terminal=!0,UO(j),CO(x,"exhausted",w.attempt,V.taskFailure),!1;let D=i2({sessionIdentity:N,failedAttempt:w.attempt,recoveryStartedAt:j.startedAt,workStillPending:K,evidence:V});if(D.phase!=="retry_scheduled")return j.inFlight=!1,j.terminal=!0,UO(j),CO(x,D.phase,w.attempt,V.taskFailure),!1;if(!j.projectionLease)return!1;let C=setTimeout(()=>{(async()=>{if(await W.completion,_.get(N)!==j||j.timer!==C)return;await YO(x,async()=>{if(_.get(N)!==j||j.timer!==C)return;j.timer=void 0,j.inFlight=!1;let E=FO(Q);if(!E)return;try{await p(Q,E)}catch(q){if(_.get(N)!==j)return;let d=q0(q);j.inFlight=!1,j.terminal=!0;try{let NO=new Date().toISOString(),TO;try{TO=await g.updateSessionMetadata(Q.id,Q.projectPath,{taskStatus:"failed",taskStatusReason:d.message,taskFailure:d,taskCompletedAt:NO,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null})}catch{t.error(`[SessionRoutes] Failed to persist terminal pending input state for ${Q.id}`)}if(_.get(N)!==j||!j.terminal)return;if(Q.taskStatus="failed",Q.taskStatusReason=d.message,Q.taskFailure=d,Q.taskCompletedAt=NO,TO)$0(Q,TO);CO(x,"failed",E.attempt,d),m.publish(x,"session.error",{error:d.message,taskFailure:d}),m.publish(x,"session.status",{status:"error"})}finally{UO(j)}}})})().catch((E)=>{t.error(`[SessionRoutes] Failed to retry pending input for ${Q.id}:`,E)})},D.delayMs);return C.unref?.(),j.timer=C,j.inFlight=!1,CO(x,"retry_scheduled",w.attempt+1,V.taskFailure,D.delayMs),!0},RO=(Q,w)=>{let V=QO(Q),K=_.get(i(V));if(!K||K.generation!==w.generation)return!1;if(w.attempt>1)CO(V,"recovered",w.attempt);return u(V,w.generation),!0},J0=(Q,w)=>B.runExclusive(i(Q),w),rO=(Q)=>F4().some((w)=>w.sessionId===Q.sessionId&&w.projectPath===Q.projectPath&&gO(w)),cO=async(Q,w,V)=>{let K=Y.get(w);if(!K)K=(async()=>{if($.get(w)===V)$.delete(w);for(let[U,x]of $)if(x===V)$.delete(U);let W=QO(Q);if(V0(W)?.id===Q.id&&!rO(W)&&!x0.has(w)&&!X0.has(w))await Z4(W,"route-reset").catch(()=>{return});if(await V.dispose(),$.size===0)await iO.getInstance().disconnectAll()})().finally(()=>{if(Y.get(w)===K)Y.delete(w)}),Y.set(w,K);await K},T=(Q,w={})=>{let V=w.communicationStyle??Q.communicationStyle;return{sessionId:Q.id,workspaceRoot:Q.projectPath,permissionMode:w.permissionMode??Q.permissionMode??"default",...Q.reasoningEffort?{reasoningEffort:Q.reasoningEffort}:{},...Q.serviceTier?{serviceTier:Q.serviceTier}:{},...Q.responseVerbosity?{responseVerbosity:Q.responseVerbosity}:{},...V?{communicationStyle:V}:{},...V===Q.communicationStyle&&Q.communicationStyleDigest?{communicationStyleDigest:Q.communicationStyleDigest}:{},...Q.projectInstructionsDigest?{projectInstructionsDigest:Q.projectInstructionsDigest}:{},...Q.taskWorktree?{taskWorktree:Q.taskWorktree}:{},...Q.taskIsolation?{taskIsolation:Q.taskIsolation}:{},...Q.messageCount>0?{sessionStart:{isResume:!0,resumeSessionId:Q.id}}:{}}},JO=async(Q,w={})=>{let V=QO(Q),K=i(V);await Y.get(K);let W=I.acquire(K);if(W){if($.get(K)!==W.value)throw W.release(),Error("Session Runtime residency identity is inconsistent");return W}if(I.owns(K))throw new t0(I.getStats().maxResident);let U=J.get(K);if(!U)U=(async()=>{let x=await I.reserve(K,{surface:"web",allowEviction:!0}),N;try{N=await B0.create(T(Q,w));let j=N.getCurrentModelId();if(j&&(Q.selectedModelId||Q.taskModelId)&&j!==Q.selectedModelId){let E=await g.updateSessionMetadata(Q.id,Q.projectPath,{selectedModelId:j}).catch((q)=>{t.warn(`[SessionRoutes] Failed to migrate restored model for ${Q.id}:`,q);return});if(E)Q.selectedModelId=E.selectedModelId,Q.updatedAt=new Date(E.lastMessageTime)}let D=N,C=x.commit({key:K,surface:"web",value:D,canEvict:()=>!rO(V)&&!x0.has(K)&&!X0.has(K)&&!J.has(K)&&!Y.has(K)&&D.isIdleForResidency(),dispose:()=>cO(Q,K,D)});return N=void 0,$.set(K,D),{runtime:D,claimLease:()=>{if(C){let q=C;return C=void 0,q}let E=I.acquire(K);if(!E||E.value!==D)throw Error("Initialized Session Runtime lost residency");return E}}}catch(j){if(x.cancel(),N)await N.dispose().catch((D)=>{t.warn(`[SessionRoutes] Failed to dispose uncommitted Runtime for ${Q.id}:`,D)});if(j instanceof j4)throw new b0(j.reason);throw j}})(),J.set(K,U);try{return(await U).claimLease()}finally{if(J.get(K)===U)J.delete(K)}},_O=async(Q,w,V={})=>{let K=await JO(Q,V);try{return await w(K.value)}finally{K.release()}},R1=(Q)=>{if(Q instanceof b0||Q instanceof wO)return Q;if(Q instanceof j4)return new b0(Q.reason);if(Q instanceof D2)return new v(Q.message);if(Q instanceof Error&&"code"in Q&&(Q.code==="ENOENT"||Q.code==="ENOTDIR"))return new b0("workspace_missing");return Q instanceof Error?Q:Error(String(Q))},z1=(Q)=>{if(Q.taskIsolation!=="worktree"||Q.taskWorktree)return;if(!Q.taskSourceProjectPath)throw new b0("task_source_project_missing");return I0(Q.taskSourceProjectPath)},E1=async(Q,w)=>{let V=QO(Q),K=i(V),W=z1(Q);if(!W||$.has(K)||J.has(K))try{return await _O(Q,w)}catch(N){throw R1(N)}let U=LO();if(!U)throw new MO("Configuration is not initialized");let x;try{let[N,j]=await Promise.all([D1(W,U),O0(W)]);return x=await B0.create({...T(Q),workspace:P2(W),modelResources:N,agentResources:x2(j),lspResources:{projectRoot:W,servers:{}},auxiliaryReadOnly:!0}),await w(x)}catch(N){throw R1(N)}finally{await x?.dispose()}},G1=async(Q)=>{let w=i(QO(Q));if(!$.has(w)&&!J.has(w)&&!await B0.hasDurableFollowUpInbox(Q.projectPath,Q.id))return S2();return _O(Q,(V)=>V.getFollowUpQueueSnapshot())},d0=async(Q,w)=>{let V=i(QO(Q)),K=J.get(V);if(K)await K.catch(()=>{return});J.delete(V);let W=w??$.get(V);if(!W)return;if(!await I.remove(V,W))throw Error(`Session Runtime is pinned and cannot be disposed: ${V}`)},O4=(Q,w)=>{if(w==="delete")throw new c("Session",Q.sessionId);if(w==="archive")throw new v("Session is archived");throw new MO},c0=(Q,w,V)=>{if(V.invalidatedBy)O4(Q,V.invalidatedBy);if(X.get(w)!==V)throw new MO},$4=(Q,w)=>{let V=i(Q),K=X.get(V);if(!K)return;if(K.invalidatedBy??=w,K.cancelReservation?.(),K.cancelReservation=void 0,X.get(V)===K)X.delete(V)},Q$=(Q)=>{for(let w of G)w.invalidatedBy??=Q,w.cancelReservation?.(),w.cancelReservation=void 0;X.clear()},V0=(Q)=>A.snapshot(i(Q)),f1=()=>A.snapshotAll(),Z4=async(Q,w)=>{$4(Q,w);let V=i(Q);if(!V0(Q))return;let K=A.beginCloseMany([V],w);await K.waitForIdle({deadlineAt:Date.now()+W2}),K.commit()},b5=async(Q,w)=>{if(w!==void 0)return j1(Q),nO({sessionId:Q,projectPath:I0(w)});return J4(Q,w)},J4=async(Q,w)=>{if(j1(Q),w!==void 0){let K=nO({sessionId:Q,projectPath:I0(w)});if(V0(K))return K;let W=await g.findSessionMetadata(K.sessionId,K.projectPath);if(!W)throw new c("Session",Q);return nO({sessionId:W.sessionId,projectPath:W.projectPath})}let V=new Map;for(let K of f1()){if(K.id!==Q)continue;let W=QO(K);V.set(i(W),W)}for(let K of await g.listSessions()){if(K.sessionId!==Q)continue;let W=nO({sessionId:K.sessionId,projectPath:K.projectPath});V.set(i(W),W)}if(V.size===0)try{let K=await g.findSessionMetadata(Q);if(!K)throw new c("Session",Q);return nO({sessionId:K.sessionId,projectPath:K.projectPath})}catch(K){if(K instanceof c)throw K;if(K instanceof Error&&K.message.startsWith("Ambiguous session ID:"))throw new lO;throw K}if(V.size>1)throw new lO;return V.values().next().value},j0=async(Q)=>{let w=U0;if(!w?.accepting||w.acquireOrHydrateSession!==j0)throw new MO;let V=i(Q),K=A.acquire(V);if(K)return K;let W=X.get(V);if(!W){let x;x={promise:Promise.resolve().then(async()=>{let j=A.acquire(V);if(j){j.release();return}c0(Q,V,x);let D=A.reserve(V);x.cancelReservation=()=>D.cancel();try{let C=await g.findSessionMetadata(Q.sessionId,Q.projectPath);if(c0(Q,V,x),!C)throw new c("Session",Q.sessionId);let E=await g.findSessionTaskWorktree(Q.sessionId,Q.projectPath);c0(Q,V,x);let q=A1(C,E);c0(Q,V,x);let d=D.commit(q);x.cancelReservation=void 0,d.release()}catch(C){throw x.cancelReservation?.(),x.cancelReservation=void 0,C}})},W=x,X.set(V,W),G.add(W)}try{await W.promise}finally{if(G.delete(W),X.get(V)===W)X.delete(V)}let U=A.acquire(V);if(!U)throw new MO;return U},T5=async(Q,w)=>{let V=await j0(Q);try{return await w(V.value)}finally{V.release()}},S1=async(Q,w)=>{let V=await J4(Q,w);try{await g.assertSessionWritable(V.sessionId,V.projectPath)}catch(K){if(K instanceof M4)throw new v(K.message);throw K}return j0(V)},S0=(Q)=>{let w=A.acquire(Q.key);if(!w||w.generation!==Q.generation)throw w?.release(),new MO;return w},Y$=async(Q)=>{let w=await j0(Q);try{return S0(w)}finally{w.release()}},oO=async(Q,w,V)=>{let K=await S1(Q,w);try{let W=K.value;return await V(W,QO(W),K)}finally{K.release()}},q5=async(Q,w)=>{let V=await S1(Q.sessionId,Q.projectPath);try{return await w(V.value,V)}finally{V.release()}},X$=async(Q,w)=>{if(Q.permissionMode===w)return;let V=await g.setSessionPermissionMode(Q.id,Q.projectPath,w);Q.permissionMode=V.permissionMode,Q.updatedAt=new Date(V.lastMessageTime),m.publish(QO(Q),"session.updated",{permissionMode:w})},K1=(Q,w,V,K)=>{if(!f.stats().accepting)throw new MO;let W=Y2(12),U={id:W,sessionId:Q.id,projectPath:Q.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:Q.taskIsolation!==void 0&&K.runtimeLease!==void 0,pendingResume:K.pendingResume,projectionLease:K.projectionLease,createdAt:new Date};if(Q.taskIsolation&&K.runtimeLease){let x=K.runtimeLease.value,N=N0.admit({key:`${Q.projectPath}\x00${Q.id}`,...x.getTaskAdmissionLimits(),pendingBytes:k2({content:w,outputSchema:K.outputSchema,pendingMessages:x.getPendingSteeringMessages()}),signal:U.abortController.signal,onUpdate:(D)=>{U.status=D.state,Q.taskStatus=D.state,Q.taskQueuePosition=D.queuePosition,Q.taskQueueDepth=D.queueDepth,Q.taskConcurrencyLimit=D.maxConcurrent,U.taskAdmissionUpdate=(U.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await x.setTaskAdmission(D)}).catch((C)=>{t.warn(`[SessionRoutes] Failed to persist admission for ${Q.id}:`,C)})}});U.taskAdmission=N;let j=N.getSnapshot();U.status=j.state,Q.taskStatus=j.state,Q.taskQueuePosition=j.queuePosition,Q.taskQueueDepth=j.queueDepth,Q.taskConcurrencyLimit=j.maxConcurrent}return o$(U),Q.currentRunId=W,U.completion=Q2(U,Q,w,V,JO,{pendingInputOnly:K.pendingInputOnly,preparedInputTurn:K.preparedInputTurn,goalContinuationOnly:K.goalContinuationOnly,outputSchema:K.outputSchema,taskAdmission:U.taskAdmission,runtimeLease:K.runtimeLease,projectionLease:K.projectionLease,disposeRuntime:d0,pendingResume:K.pendingResume,onPendingResumeFailure:(x,N,j,D)=>PO(Q,x,N,j,U,D),onPendingResumeSuccess:(x)=>RO(Q,x),onPendingResumeCancelled:(x)=>u(QO(Q),x.generation)}).catch((x)=>{t.error(`[SessionRoutes] Run ${W} failed:`,x)}),U},I5=async(Q)=>{let w;if(Q.outputSchema)try{w=D4(Q.outputSchema).schema}catch(l){throw new F(l instanceof Error?l.message:"Invalid output schema")}let V=l1("task",12),K=I0(Q.sourceProjectPath),W=Q.modelId?.trim(),U=LO();if(!U)throw new F("Config not initialized");let[x,N]=await Promise.all([D1(K,U),O0(K)]);if(W&&!x.config.models.some((l)=>l.id===W))throw new F(`Task model not found: ${W}`);let j=W||x.config.models.find((l)=>l.id===x.config.currentModelId)?.id||x.config.models[0]?.id;if(!j)throw new F("No model is configured. Add or select a model before dispatching a task.");let D=x.config.models.find((l)=>l.id===j);if(!D)throw new F(`Task model not found: ${j}`);let C=Q.reasoningEffort??"off",E=Q.serviceTier??"auto",q=Q.responseVerbosity??"auto",d=Q.communicationStyle??"auto",NO,TO=N.projectRules?.staticRules(K),XO=TO&&TO.files.length>0?TO.provenanceSha256:void 0;try{let l=x.catalog.resolveConfig(D);N2(l,C),G2(l,E),z2(l,q);let BO=B2(d,N.communicationStyles);NO=BO.source==="built-in"?void 0:BO.contentSha256}catch(l){throw new F(l instanceof Error?l.message:"Invalid reasoning effort")}let r={version:1,prompt:Q.prompt,...Q.title?{title:Q.title}:{},...Q.taskPriority?{taskPriority:Q.taskPriority}:{},...Q.taskKind?{taskKind:Q.taskKind}:{},...Q.taskDueAt?{taskDueAt:Q.taskDueAt}:{},sourceProjectPath:K,isolation:Q.isolation,permissionMode:Q.permissionMode,modelId:j,reasoningEffort:C,serviceTier:E,responseVerbosity:q,communicationStyle:d,...NO?{communicationStyleDigest:NO}:{},...XO?{projectInstructionsDigest:XO}:{},...Q.attachments?{attachments:Q.attachments.map((l)=>({...l}))}:{},...w?{outputSchema:w}:{}},kO,n,AO,HO,jO,o;try{let l=await M.runExclusive(async()=>{o=i(nO({sessionId:V,projectPath:K})),jO=A.reserve(o);try{return await h2.createSessionTask({sessionId:V,prompt:Q.prompt,title:Q.title,taskPriority:Q.taskPriority,taskKind:Q.taskKind,taskDueAt:Q.taskDueAt,sourceProjectPath:K,isolation:Q.isolation,dispatch:r,retriedFrom:Q.retriedFrom})}catch(hO){throw jO?.cancel(),jO=void 0,hO}}),{metadata:BO}=l;if(kO=l.taskWorktree,n=A1(BO,kO),!jO)throw new MO;let xO=i(QO(n));if(o!==xO)jO.cancel(),jO=A.reserve(xO),o=xO;HO=jO.commit(n),jO=void 0,o=void 0;let vO=QO(n);m.publish(vO,"task.status",{taskStatus:BO.taskStatus,updatedAt:BO.lastMessageTime});let S=X2(Q.prompt,Q.attachments);AO=await JO(n);let pO=AO.value,ZO=w?await pO.prepareInputTurn(S,{outputSchema:w}):await pO.prepareInputTurn(S);if(!ZO.accepted)throw new v(`Task prompt was not accepted: ${ZO.reason}`);if(!HO)throw new MO;let VO=K1(n,S,Q.permissionMode,{preparedInputTurn:ZO,runtimeLease:AO,projectionLease:HO,outputSchema:w});return HO=void 0,AO=void 0,await VO.taskAdmissionUpdate,{session:y0(n),runId:VO.id,messageId:ZO.messageId,status:VO.status==="queued"?"queued":"running",queuePosition:n.taskQueuePosition,queueDepth:n.taskQueueDepth,maxConcurrentTasks:n.taskConcurrencyLimit}}catch(l){if(jO?.cancel(),jO=void 0,o=void 0,HO?.release(),HO=void 0,AO?.release(),AO=void 0,l instanceof Q0&&!n)throw new eO("Session projection capacity is full",{resource:l.resource,limit:l.limit,retryable:l.retryable});if((l instanceof b4||l instanceof t0||l instanceof Q0)&&n){if(kO)await W0.exit({sessionId:n.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await d0(n).catch(()=>{return}),await g.deleteSession(n.id,n.projectPath).catch(()=>{return}),new eO(l instanceof Q0?"Session projection capacity is full":l instanceof t0?"Session runtime capacity is full":"Task admission capacity is full",{resource:l.resource,limit:l.limit,...l instanceof Q0?{retryable:l.retryable}:{}})}if(n){let BO=await g.findSessionMetadata(n.id,n.projectPath).catch(()=>{return});if(!BO||BO.taskStatus==="queued"){let xO=q0(l),vO=await g.updateSessionMetadata(n.id,n.projectPath,{taskStatus:"failed",taskStatusReason:xO.message,taskFailure:xO,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});n.taskStatus=vO?.taskStatus??"failed",n.taskStatusReason=vO?.taskStatusReason??xO.message,n.taskFailure=vO?.taskFailure??xO,n.taskCompletedAt=vO?.taskCompletedAt}else n.taskStatus=BO.taskStatus,n.taskStatusReason=BO.taskStatusReason,n.taskFailure=BO.taskFailure,n.taskCompletedAt=BO.taskCompletedAt}throw l}},V$=(Q)=>SO(()=>I5(Q)),C5=async(Q,w)=>{let V=await uO(Q,w),K=await g.findSessionMetadata(V.sessionId,V.projectPath);if(!K)throw new c("Session",V.sessionId);if(!["failed","interrupted","cancelled"].includes(K.taskStatus))throw new v(`Task cannot be retried while status is ${K.taskStatus}`);let W=await g.findSessionTaskDispatch(V.sessionId,V.projectPath);if(!W)throw new v("Task retry payload is unavailable");return V$({prompt:W.prompt,title:K.title??W.title,taskPriority:K.taskPriority??W.taskPriority,taskKind:K.taskKind??W.taskKind,taskDueAt:K.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})},R5=(Q,w)=>SO(()=>C5(Q,w)),E5=(Q,w,V)=>SO(async()=>{let K=await uO(Q,V);if(!await g.findSessionMetadata(K.sessionId,K.projectPath))throw new c("Session",K.sessionId);let U=await g.updateSessionMetadata(K.sessionId,K.projectPath,w),x=V0(K);if(x)$0(x,U);return m.publish(K,"session.updated",{...U.title?{title:U.title}:{},...U.taskPriority?{taskPriority:U.taskPriority}:{},...U.taskKind?{taskKind:U.taskKind}:{},taskDueAt:U.taskDueAt??null}),x?y0(x):{...U,isActive:!1}}),f5=async(Q,w)=>{return oO(Q,w,async(V)=>{if(!V.taskWorktree)throw new F("Session does not have a task worktree");try{await W0.restoreSession(V.taskWorktree);let K=await W0.getDiffArtifact(V.id);if(!K)throw new v("Task diff artifact is unavailable");return{sessionId:V.id,projectPath:V.projectPath,...K}}catch(K){if(K instanceof v)throw K;throw t.error("[SessionRoutes] Failed to load task diff artifact:",K),new v("Task diff artifact is unavailable")}})},S5=async(Q,w,V)=>{let K=await uO(Q,V);return J0(K,async()=>{return q5(K,async(W)=>{if(["queued","running"].includes(W.taskStatus))throw new v(`Task artifacts cannot be delivered while status is ${W.taskStatus}`);if(W.taskDelivery?.status==="applied")throw new v("Task changes have already been applied");if(W.taskDelivery?.status==="discarded")throw new v("Task changes have already been discarded");if(!W.taskWorktree)throw new v("Task worktree is unavailable");let U=async(x,N=!1)=>{let j=await g.updateSessionMetadata(W.id,W.projectPath,{taskDelivery:x,...N?{taskWorktree:null}:{}});if($0(W,j),N)W.taskWorktree=void 0;return m.publish(K,"task.delivery",{taskDelivery:x,...N?{taskWorktreeRemoved:!0}:{},updatedAt:j.lastMessageTime}),y0(W)};try{if(w==="discard"){try{await W0.restoreSession(W.taskWorktree)}catch(j){return t.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${W.id}:`,j),U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:W.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let N=await W0.exit({sessionId:W.id,action:"remove",discardChanges:!0});return U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:N.discardedFiles??0,message:"Task worktree removed"},!0)}try{await W0.restoreSession(W.taskWorktree)}catch(N){throw t.warn(`[SessionRoutes] Task worktree is unavailable for ${W.id}:`,N),new A4("artifact_unavailable","Task worktree is unavailable")}let x=await W0.apply(W.id);return U({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:x.sourceCommit,changedFiles:x.changedFiles,message:"Task changes applied to the source workspace"})}catch(x){if(x instanceof A4)throw await U({status:"conflicted",updatedAt:new Date().toISOString(),message:x.message}),new v(x.message);throw x}})})},P5=(Q,w,V)=>SO(()=>S5(Q,w,V)),z$=async(Q,w)=>{let V=QO(Q),K=i(V),W=_.get(K);if(!w&&W?.terminal)return;let U=mO(Q.currentRunId);if(gO(U)){if(w)u(QO(Q),w.generation);return}let x=Q.taskIsolation&&Q.taskStatus!=="queued"&&Q.taskStatus!=="running",N=x?await B0.hasRecoverableTurn(Q.projectPath,Q.id):!1;if(x&&!N){if(w)u(QO(Q),w.generation);return}let j=await B0.hasPendingInbox(Q.projectPath,Q.id),D=!j&&await B0.hasActiveGoal(Q.projectPath,Q.id);if(!j&&!D&&!N)N=await B0.hasRecoverableTurn(Q.projectPath,Q.id);if(!j&&!D&&!N){u(QO(Q));return}if(w&&!j){u(QO(Q),w.generation);return}let C=await JO(Q),E=!1,q,d;try{let NO=C.value,TO=mO(Q.currentRunId);if(gO(TO)){if(w)u(QO(Q),w.generation);return}if(j&&NO.getPendingSteeringCount()===0)await NO.reloadPendingInbox();let XO=NO.getPendingSteeringCount()>0,r=XO?null:await NO.getGoal(),kO=r?.status==="active"||r?.status==="verifying",n=NO.getTurnRecoveryAssessment();if(n.state!=="none"&&(n.state==="requires_attention"||!XO&&!kO))m.publish({sessionId:Q.id,projectPath:Q.projectPath},"turn.recovery",{assessment:n});if(n.state==="requires_attention"||x||!XO&&!kO||NO.hasTurnOwner()){if(w||!XO)u(QO(Q),w?.generation);return}let AO=w;if(XO&&!Q.taskIsolation&&!AO){let HO=await Y$(V);try{AO=FO(Q,HO);let jO=_.get(K);if(AO&&jO?.generation===AO.generation&&jO.projectionLease===HO)d=AO,HO=void 0}finally{HO?.release()}}if(XO&&!Q.taskIsolation&&!AO)return;if(w&&!a(Q,w))return;q=w?(()=>{let HO=W?.projectionLease;if(!HO)throw new MO;return S0(HO)})():await Y$(QO(Q)),K1(Q,"",Q.permissionMode??"default",{pendingInputOnly:XO,goalContinuationOnly:kO,runtimeLease:C,projectionLease:q,pendingResume:XO?AO:void 0}),q=void 0,d=void 0,E=!0}finally{if(q?.release(),d)u(V,d.generation);if(!E)C.release()}};p=async(Q,w)=>{let V;try{V=f.enter()}catch{return}try{let K=mO(Q.currentRunId);if(gO(K)){if(w)u(QO(Q),w.generation);return}if(Q.taskIsolation){await z$(Q);return}await z$(Q,w)}finally{V.release()}};let Q4={accepting:!0,resolveSessionRef:J4,getProjectionSnapshot:V0,snapshotAll:f1,acquireOrHydrateSession:j0,invalidateAll:Q$,resumeRecoveredInteraction:p};U0=Q4;let k5=async()=>{let Q={scheduled:0,failed:0,deferred:0};if(!f.stats().accepting)return Q;let w=(await g.listSessions({taskStatus:"queued"})).filter((V)=>V.taskIsolation!==void 0).sort((V,K)=>V.firstMessageTime.localeCompare(K.firstMessageTime)||V.projectPath.localeCompare(K.projectPath)||V.sessionId.localeCompare(K.sessionId));for(let[V,K]of w.entries()){let W={sessionId:K.sessionId,projectPath:K.projectPath};try{if(!await B0.hasPendingInbox(K.projectPath,K.sessionId)){let N=q0("Queued task input is missing");await g.updateSessionMetadata(K.sessionId,K.projectPath,{taskStatus:"failed",taskStatusReason:N.message,taskFailure:N,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Q.failed++;continue}let U=await j0(W),x=U.value;if(U.release(),await p(x),x.currentRunId)Q.scheduled++}catch(U){if(U instanceof b4||U instanceof t0){Q.deferred+=w.length-V;break}t.warn(`[SessionRoutes] Failed to recover queued task ${K.sessionId}:`,U),Q.deferred++}}return Q};return O.route("/",n$({withAdmission:SO,resolveSessionRef:async(Q,w)=>{try{let V=await b5(Q,w);return(await j0(V)).release(),V}catch(V){if(V instanceof Q0)throw new eO("Session projection capacity is full",{resource:V.resource,limit:V.limit,retryable:V.retryable});throw V}},getRuntime:(Q)=>Z.get(Q),captureAgentScreenshot:async(Q,w)=>{return T5(Q,(V)=>_O(V,(K)=>K.captureBrowserScreenshot(w)))},resetRuntime:(Q)=>Z.reset(Q)})),O.get("/",async(Q)=>{try{let w=await g.listSessions(),V=new Set(w.filter((D)=>D.relationType==="subagent").map((D)=>i({sessionId:D.sessionId,projectPath:D.projectPath}))),K=f1().filter((D)=>!V.has(i(QO(D)))&&D.relationType!=="subagent").map((D)=>y0(D)),W=new Set(K.map((D)=>i({sessionId:D.sessionId,projectPath:D.projectPath}))),U=w.filter((D)=>{if(D.relationType==="subagent")return!1;return!W.has(i({sessionId:D.sessionId,projectPath:D.projectPath}))}),x=new Set(W),N=U.filter((D)=>{let C=i({sessionId:D.sessionId,projectPath:D.projectPath});if(x.has(C))return!1;return x.add(C),!0}),j=[...K,...N.map((D)=>({...D,isActive:!1}))];return Q.json(j)}catch(w){throw t.error("[SessionRoutes] Failed to list sessions:",w),new zO("Failed to list sessions")}}),O.get("/catalog",async(Q)=>{try{let w=Q.req.query("limit"),V=w===void 0?void 0:Number(w),K=Q.req.query("cursor"),W=Q.req.query("projectPath"),U=Q.req.query("archived");if(U!==void 0&&U!=="true"&&U!=="false")throw new F("archived must be true or false");let x=U==="true",N=await g.listSessionPage({...W?{cwd:I0(W)}:{},...K?{cursor:K}:{},...V===void 0?{}:{limit:V},includeSubagents:!1,archived:x}),j=new Map((x?[]:f1()).filter((D)=>D.relationType!=="subagent").map((D)=>[i(QO(D)),y0(D)]));return Q.json({sessions:N.sessions.map((D)=>j.get(i({sessionId:D.sessionId,projectPath:D.projectPath}))??D),...N.nextCursor?{nextCursor:N.nextCursor}:{}})}catch(w){if(w instanceof F)throw w;if(w instanceof Error&&(w.message.startsWith("Invalid session cursor")||w.message.startsWith("Session cursor scope")||w.message.startsWith("Session catalog")))throw new F(w.message);throw t.error("[SessionRoutes] Failed to list session catalog:",w),new zO("Failed to list session catalog")}}),O.post("/",async(Q)=>{try{let w=await Q.req.json(),V=h(M9,w);if(!V.success)throw new F("Invalid request body");let{title:K,projectPath:W}=V.data,U=l1("web",12),x=I0(W||Q.get("directory")||KO(),W?"projectPath":"directory"),N=nO({sessionId:U,projectPath:x}),j=await M.runExclusive(async()=>{let C=A.reserve(i(N));try{let E=await g.createSessionMetadata(U,x,{title:K,taskStatus:"completed"}),q=A1(E);return C.commit(q)}catch(E){throw C.cancel(),E}}),D=j.value;return j.release(),m.publish(N,"session.created",{}),Q.json({...y0(D),status:void 0,agentType:void 0,model:void 0})}catch(w){if(t.error("[SessionRoutes] Failed to create session:",w),w instanceof F||w instanceof wO||w instanceof Q0)throw w;throw new zO("Failed to create session")}}),O.get("/:sessionId/export",async(Q)=>{let w=Q.req.param("sessionId");try{let V=Q.req.query("includeReasoning");if(V!==void 0&&V!=="true"&&V!=="false")throw new F("includeReasoning must be true or false");let K=await uO(w,Q.req.query("projectPath")),W=await g.exportSessionMarkdown(K.sessionId,K.projectPath,{includeReasoning:V==="true"});return Q.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 F||V instanceof c||V instanceof lO)throw V;if(V instanceof Error&&V.message==="No conversation content to export")throw new v(V.message);throw t.error("[SessionRoutes] Failed to export session:",V),new zO("Failed to export session")}}),O.post("/:sessionId/fork",async(Q)=>{let w=Q.req.param("sessionId");try{j1(w);let V=await Q.req.json(),K=h(q9,V);if(!K.success)throw new F("Invalid request body");let W=I0(K.data.projectPath),U=l1("fork"),x,N=await M.runExclusive(async()=>{let C=await g.findSessionMetadata(w,W);if(!C)throw new c("Session",w);let E;try{E=A.reserve(i({sessionId:U,projectPath:C.projectPath}))}catch(q){if(!(q instanceof Q0))throw q}try{let q=await g.forkSession(w,{newSessionId:U,sourceProjectPath:C.projectPath,targetProjectPath:C.projectPath});if(E){let d=A1(q.metadata);x=E.commit(d)}return q}catch(q){throw E?.cancel(),q}}),j=A1(N.metadata),D=QO(j);return x?.release(),m.publish(D,"task.status",{taskStatus:N.metadata.taskStatus,...N.metadata.taskCompletedAt?{taskCompletedAt:N.metadata.taskCompletedAt}:{},updatedAt:N.metadata.lastMessageTime}),Q.json({session:N.metadata,messages:N4(N.messages)},201)}catch(V){if(V instanceof F||V instanceof c||V instanceof v)throw V;if(V instanceof b2)throw new v("Session has no durable creation record");throw t.error("[SessionRoutes] Failed to fork session:",V),new zO("Failed to fork session")}}),O.get("/:sessionId",async(Q)=>{let w=Q.req.param("sessionId");try{let V=await uO(w,Q.req.query("projectPath")),K=V0(V);if(K)return Q.json(y0(K));let W=await g.findSessionMetadata(V.sessionId,V.projectPath);if(!W)throw new c("Session",w);return Q.json(W)}catch(V){if(V instanceof F||V instanceof c||V instanceof lO)throw V;throw t.error("[SessionRoutes] Failed to get session:",V),new zO("Failed to get session")}}),O.patch("/:sessionId",async(Q)=>{let w=Q.req.param("sessionId");try{let V=await Q.req.json(),K=h(T9,V);if(!K.success)throw new F("Invalid request body");if(K.data.title===void 0)throw new F("title is required");let W=await uO(w,K.data.projectPath),U=await g.updateSessionMetadata(W.sessionId,W.projectPath,{title:K.data.title}),x=A.acquire(i(W));try{let N=x?.value;if(N)N.title=U.title??N.title,N.updatedAt=new Date(U.lastMessageTime)}finally{x?.release()}if(U.title)m.publish(W,"session.updated",{title:U.title});return Q.json({success:!0,title:U.title})}catch(V){if(t.error("[SessionRoutes] Failed to update session:",V),V instanceof F||V instanceof c||V instanceof lO)throw V;throw new zO("Failed to update session")}}),O.get("/:sessionId/rewind",async(Q)=>{return oO(Q.req.param("sessionId"),Q.req.query("projectPath"),(w)=>_O(w,async(V)=>Q.json({checkpoints:await V.listRewindCheckpoints()})))}),O.post("/:sessionId/rewind",async(Q)=>{let w=h(y2,await Q.req.json());if(!w.success)throw new F("Invalid rewind request");return oO(Q.req.param("sessionId"),Q.req.query("projectPath"),async(V,K,W)=>YO(K,async()=>{let U=mO(V.currentRunId);if(gO(U))throw new v("Cannot rewind while a run is active");return _O(V,async(x)=>{let N;try{N=await x.rewindSession(w.data)}catch(D){if(D instanceof Error&&D.message.startsWith("Cannot rewind while"))throw new v(D.message);throw D}await Y0(V);let j=N4(N.messages);return m.publish(K,"session.rewound",{targetMessageId:N.checkpoint.messageId,mode:N.mode,removedTurns:N.removedTurns,restoredFiles:N.restoredFiles,messages:j}),Q.json({...N,messages:j})})}))}),O.get("/:sessionId/review",async(Q)=>{let w=Q.req.param("sessionId"),V=await uO(w,Q.req.query("projectPath")),K=await m0.list(V.projectPath,V.sessionId);return Q.json({reviews:K.map((W)=>({...W,content:W.completion?M2(W.start,W.completion):void 0}))})}),O.post("/:sessionId/review",async(Q)=>{let w=Q.req.param("sessionId"),V=h(u2,await Q.req.json());if(!V.success)throw new F("Invalid code review request");let K=await S1(w,V.data.projectPath),W=K.value,U=QO(W),x=i(U);try{return await YO(U,async()=>{if(gO(mO(W.currentRunId)))throw new v("Cannot start a review during an active turn");if(X0.has(x))throw new v("Session already has an active review");return _O(W,async(N)=>{if(await m0.recoverInterrupted(U.projectPath,U.sessionId,N),V.data.modelId&&!N.getModelById(V.data.modelId))throw new F(`Model not found: ${V.data.modelId}`);if(V.data.modelId&&N.getCurrentModelId()!==V.data.modelId)await N.refresh({modelId:V.data.modelId});if(V.data.modelId&&W.selectedModelId!==V.data.modelId){let q=await g.updateSessionMetadata(W.id,W.projectPath,{selectedModelId:V.data.modelId});$0(W,q)}let j=new AbortController,D,C;try{D=S0(K),C=await m0.start({sessionId:U.sessionId,projectPath:U.projectPath,runtime:N,request:{kind:V.data.kind,...V.data.ref?{ref:V.data.ref}:{},...V.data.instructions?{instructions:V.data.instructions}:{}},signal:j.signal,onEvent:(q)=>{if(q.kind==="tool_start")m.publish(U,"review.tool.started",{reviewId:C?.reviewId,toolCallId:q.toolCall.id,toolName:q.toolCall.function.name});else if(q.kind==="tool_progress")m.publish(U,"review.tool.progress",{reviewId:C?.reviewId,toolCallId:q.toolCall.id,message:q.update.message.slice(0,1000)});else if(q.kind==="tool_result")m.publish(U,"review.tool.completed",{reviewId:C?.reviewId,toolCallId:q.toolCall.id,success:q.result.success})}})}catch(q){if(D?.release(),q instanceof Error&&(q.message.includes("active review")||q.message.includes("interrupted review")||q.message.includes("active turn")))throw new v(q.message);if(q instanceof Error&&(q.message.includes("review")||q.message.includes("Git")||q.message.includes("changes")||q.message.includes("ref")))throw new F(q.message);throw q}if(!C)throw new zO("Code review failed to start");await Y0(W),m.publish(U,"review.started",{reviewId:C.reviewId,kind:V.data.kind}),m.publish(U,"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 E=C.completion.then(async(q)=>{await Y0(W),m.publish(U,"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()}),m.publish(U,"review.completed",{reviewId:C.reviewId,status:q.status,findings:q.findings.length})}).catch((q)=>{t.error(`[SessionRoutes] Code review ${C.reviewId} failed:`,q)}).finally(()=>{if(X0.get(x)?.reviewId===C.reviewId)X0.delete(x);D?.release()});return X0.set(x,{reviewId:C.reviewId,controller:j,completion:E,projectionLease:D}),Q.json({reviewId:C.reviewId,status:"running"},202)})})}finally{K.release()}}),O.get("/:sessionId/subagents",async(Q)=>{return oO(Q.req.param("sessionId"),Q.req.query("projectPath"),(w)=>_O(w,(V)=>Q.json({subagents:V.listSubagents().map(i1)})))}),O.post("/:sessionId/subagents/:agentId/resume",async(Q)=>{j1(Q.req.param("agentId"));let w=m2.safeParse(await Q.req.json());if(!w.success)throw new F("Invalid subagent resume request");return oO(Q.req.param("sessionId"),Q.req.query("projectPath"),async(V,K,W)=>YO(K,async()=>{let U=mO(V.currentRunId);if(gO(U))throw new v("Cannot resume a subagent while a parent run is active");return _O(V,async(x)=>{let N=!1,j,D=(E)=>{m.publish(K,"subagent.complete",{subagentSessionId:E.id,success:E.status==="completed",status:E.status,summary:E.result?.message?.slice(0,500),type:E.subagentType,verificationVerdict:E.result?.verificationVerdict,resumedFrom:E.resumedFrom,rootAgentId:E.rootAgentId,resumeDepth:E.resumeDepth})},C;try{C=x.resumeSubagent({agentId:Q.req.param("agentId"),prompt:w.data.prompt,onEvent:(E,q)=>{S9(K,q,E)},onCompleted:(E)=>{if(N)D(E);else j=E}})}catch(E){if(E instanceof Error&&(E.message.startsWith("Cannot resume")||E.message.startsWith("Subagent cannot")))throw new v(E.message);if(E instanceof Error&&E.message.startsWith("Subagent not found"))throw new c(E.message);throw E}if(m.publish(K,"subagent.start",{subagentSessionId:C.session.id,type:C.session.subagentType,description:C.session.description,resumedFrom:C.source.id,rootAgentId:C.session.rootAgentId,resumeDepth:C.session.resumeDepth}),N=!0,j)D(j);return Q.json({source:i1(C.source),session:i1(C.session)})})}))}),O.get("/:sessionId/goal",async(Q)=>{return oO(Q.req.param("sessionId"),Q.req.query("projectPath"),async(w)=>Q.json({goal:await new T2(w.projectPath,w.id).get()}))}),O.put("/:sessionId/goal",async(Q)=>{let w=h(I9,await Q.req.json());if(!w.success)throw new F("Invalid goal request");return oO(Q.req.param("sessionId"),Q.req.query("projectPath"),async(V,K,W)=>YO(K,async()=>{let U=mO(V.currentRunId);if(gO(U))return Q.json({status:"rejected",reason:"run_active"},409);let N=w.data.permissionMode??V.permissionMode??"default";if(V.permissionMode!==N)await X$(V,N);let j=await JO(V),D=!1,C;try{let E=await j.value.createGoal(w.data);m.publish(K,"goal.updated",{goal:E}),C=S0(W);let q=K1(V,"",N,{goalContinuationOnly:!0,runtimeLease:j,projectionLease:C});return D=!0,C=void 0,await q.taskAdmissionUpdate,Q.json({status:q.status==="queued"?"queued":"running",runId:q.id,goal:E,queuePosition:V.taskQueuePosition,queueDepth:V.taskQueueDepth,maxConcurrentTasks:V.taskConcurrencyLimit},202)}finally{if(C?.release(),!D)j.release()}}))}),O.patch("/:sessionId/goal",async(Q)=>{let w=h(C9,await Q.req.json());if(!w.success)throw new F("Invalid goal update");return oO(Q.req.param("sessionId"),Q.req.query("projectPath"),async(V,K,W)=>YO(K,async()=>{let U=await JO(V),x=!1,N;try{let j=U.value,D;if(w.data.action==="pause")D=await j.pauseGoal();else if(w.data.action==="edit")D=await j.editGoal(w.data.objective);else D=await j.resumeGoal();if(m.publish(K,"goal.updated",{goal:D}),D.status==="active"&&!gO(mO(V.currentRunId))){N=S0(W);let C=K1(V,"","default",{goalContinuationOnly:!0,runtimeLease:U,projectionLease:N});return x=!0,N=void 0,await C.taskAdmissionUpdate,Q.json({status:C.status==="queued"?"queued":"running",runId:C.id,goal:D,queuePosition:V.taskQueuePosition,queueDepth:V.taskQueueDepth,maxConcurrentTasks:V.taskConcurrencyLimit},202)}return Q.json({status:D.status,goal:D})}finally{if(N?.release(),!x)U.release()}}))}),O.delete("/:sessionId/goal",async(Q)=>{return oO(Q.req.param("sessionId"),Q.req.query("projectPath"),(w,V)=>_O(w,async(K)=>{let W=await K.clearGoal();if(W)m.publish(V,"goal.cleared",{});return Q.json({cleared:W})}))}),O.post("/:sessionId/archive",async(Q)=>{let w=Q.req.param("sessionId");try{let V=await uO(w,Q.req.query("projectPath")),K=await g.listSessionArchiveMembers(V.sessionId,V.projectPath);for(let U of K){let x=nO({sessionId:U.sessionId,projectPath:U.projectPath}),N=V0(x);if(gO(mO(N?.currentRunId)))throw new v(`Stop session ${U.sessionId} before archiving this session tree`)}for(let U of K){let x=nO({sessionId:U.sessionId,projectPath:U.projectPath}),N=V0(x);if(N)await d0(N)}let W=await g.archiveSession(V.sessionId,V.projectPath);for(let U of K){let x=nO({sessionId:U.sessionId,projectPath:U.projectPath}),N=i(x);$4(x,"archive"),await Z4(x,"archive").catch(()=>{return}),J.delete(N),m.publish(x,"session.archived",{archiveRootId:V.sessionId,archivedAt:W.archivedAt})}if($.size===0)await iO.getInstance().disconnectAll();return Q.json({session:W,archivedSessionIds:K.map((U)=>U.sessionId)})}catch(V){if(V instanceof F||V instanceof c||V instanceof lO||V instanceof v)throw V;if(V instanceof L4)throw new v(V.message);throw t.error("[SessionRoutes] Failed to archive session:",V),new zO("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Q)=>{let w=Q.req.param("sessionId");try{let V=await uO(w,Q.req.query("projectPath")),K=await g.listSessionArchiveMembers(V.sessionId,V.projectPath),W=await g.unarchiveSession(V.sessionId,V.projectPath),U=K.filter((x)=>x.sessionId===V.sessionId||x.archivedBySessionId===V.sessionId).map((x)=>x.sessionId);for(let x of U)m.publish({sessionId:x,projectPath:V.projectPath},"session.unarchived",{archiveRootId:V.sessionId});return Q.json({session:W,restoredSessionIds:U})}catch(V){if(V instanceof F||V instanceof c||V instanceof lO)throw V;if(V instanceof L4)throw new v(V.message);throw t.error("[SessionRoutes] Failed to unarchive session:",V),new zO("Failed to unarchive session")}}),O.delete("/:sessionId",async(Q)=>{let w=Q.req.param("sessionId"),V=Q.req.query("projectPath");try{let K=await uO(w,V);u(K);let W=i(K),U=A.acquire(W),x=U?.value,N=x?.currentRunId,j=$.get(W),D=x?.taskWorktree??await g.findSessionTaskWorktree(K.sessionId,K.projectPath);U?.release();let C;if(N){let d=mO(N);if(d)h0(d),await d.completion,C=d.id}let E=X0.get(W);if(E)E.controller.abort("session-delete"),await E.completion;if(j)await j.clearGoal().catch((d)=>{t.warn("[SessionRoutes] Failed to clear session goal:",d)});if(await Z.dispose(K),await g.deleteSession(K.sessionId,K.projectPath),$4(K,"delete"),C)s$(C);await Z4(K,"delete").catch(()=>{return}),J.delete(W),m.publish(K,"session.deleted",{});let q=$.get(W);if(q){if(!await I.remove(W,q))throw new v("Session Runtime is still active and cannot be deleted")}if(D)try{await W0.restoreSession(D),await W0.exit({sessionId:K.sessionId,action:"remove",discardChanges:!0})}catch(d){t.warn(`[SessionRoutes] Failed to remove deleted task worktree ${K.sessionId}:`,d)}return Q.json({success:!0})}catch(K){if(t.error("[SessionRoutes] Failed to delete session:",K),K instanceof F||K instanceof c||K instanceof lO)throw K;throw new zO("Failed to delete session")}}),O.get("/:sessionId/message",async(Q)=>{let w=Q.req.param("sessionId");try{let V=await uO(w,Q.req.query("projectPath")),K=await g.loadSession(V.sessionId,V.projectPath,{includeMessageIds:!0});return Q.json(N4(K))}catch(V){if(t.error("[SessionRoutes] Failed to get messages:",V),V instanceof F||V instanceof c||V instanceof lO)throw V;throw new zO("Failed to get messages")}}),O.get("/:sessionId/follow-ups",async(Q)=>{return oO(Q.req.param("sessionId"),Q.req.query("projectPath"),(w,V)=>YO(V,async()=>Q.json(await G1(w))))}),O.post("/:sessionId/follow-ups/mutate",async(Q)=>{let w=A9.safeParse(await Q.req.json());if(!w.success)throw new F("Invalid follow-up queue mutation");return oO(Q.req.param("sessionId"),w.data.projectPath??Q.req.query("projectPath"),(V,K)=>YO(K,async()=>{try{return await _O(V,async(W)=>{let U={expectedVersion:w.data.expectedVersion,operation:w.data.operation},x=await W.mutateFollowUpQueue(U);if(x.snapshot.version!==U.expectedVersion)m.publish(K,"follow_up.queue.changed",{queue:x.snapshot});return Q.json(x)})}catch(W){if(!b9(W))throw W;let U=W.code==="not_found"?404:W.code==="invalid_mutation"?400:W.code==="storage_unavailable"||W.code==="runtime_unavailable"?503:409;return Q.json({error:{code:W.code,message:W.message},snapshot:W.snapshot},U)}}))}),O.get("/:sessionId/events",async(Q)=>{let w=Q.req.param("sessionId"),V=Q.req.query("resume")!=="false",K;try{K=L.enter(Q.req.raw.signal)}catch{throw new MO}let W=!1;try{let U=await uO(w,Q.req.query("projectPath"));try{await g.assertSessionWritable(U.sessionId,U.projectPath)}catch(q){if(q instanceof M4)throw new v(q.message);throw q}let x=await j0(U),N=x.value,j=Q.req.header("Last-Event-ID")??Q.req.query("lastEventId"),D=j?Number.parseInt(j,10):Number.NaN,C=Number.isInteger(D)?D+1:void 0,E=D9(Q,async(q)=>{let NO=new Set,TO,XO,r=!1,kO,n,AO=new Promise((S)=>{n=S}),HO,jO=new Set,o=(S)=>{let pO=S;return NO.add(pO),S.finally(()=>{NO.delete(pO)})},l=()=>{if(TO?.(),TO=void 0,XO!==void 0)clearInterval(XO),XO=void 0},BO=(S)=>{if(HO)return HO;return r=!0,HO=(async()=>{try{l(),kO?.close(S),q.close()}finally{n()}})(),HO},xO=()=>{BO(K.signal.reason)},vO=async(S)=>{await BO(S),await Promise.allSettled([...NO]),K.signal.removeEventListener("abort",xO),K.release()};if(K.signal.addEventListener("abort",xO,{once:!0}),q.onAbort(()=>{BO()}),K.signal.aborted){await vO(K.signal.reason);return}kO=new W1({write:async(S)=>{await q.writeSSE(S)},onFailure:(S)=>{if(V2(S,r))return;t.warn(`[SessionRoutes] SSE egress closed for ${U.sessionId}: kind=${S.kind} pendingItems=${S.pendingItems??0} pendingBytes=${S.pendingBytes??0}`),BO(S)}}),TO=m.subscribe((S)=>{if(r)return;if(S.sessionId!==U.sessionId||S.projectPath!==U.projectPath)return;let pO=S.properties.requestId;if((S.type==="permission.asked"||S.type==="question.required"||S.type==="elicitation.required")&&typeof pO==="string"){if(jO.has(pO))return;jO.add(pO)}if(S.type==="subagent.completion.queued"){let VO=YO(U,()=>p(N)).catch((hO)=>{t.error(`[SessionRoutes] Failed to wake background completion for ${N.id}:`,hO)});o(VO)}if(S.type==="team.message.received"&&typeof S.properties.teamName==="string"&&typeof S.properties.messageId==="string"&&typeof S.properties.content==="string"&&C2(S.properties.metadata,{messageId:S.properties.messageId,teamName:S.properties.teamName})){let VO=S.properties.teamName,hO=S.properties.messageId,qO=S.properties.content,bO=S.properties.metadata,DO=YO(U,async()=>{let _0=await JO(N),w1=!1;try{let z0=await _0.value.enqueueSteering(qO,{allowBeforeTurn:!0,messageId:hO,origin:"team_message",metadata:bO});if(!z0.accepted)return;if(z0.queue&&!z0.duplicate)m.publish(U,"follow_up.queue.changed",{queue:z0.queue});await new I2(VO,n1()).markDelivered([hO]),w1=z0.delivery==="next_turn"}finally{_0.release()}if(!w1)return;await p(N).catch((z0)=>{t.error(`[SessionRoutes] Failed to wake teammate delivery for ${N.id}:`,z0)})}).catch((_0)=>{t.error(`[SessionRoutes] Failed to deliver teammate message for ${N.id}:`,_0)});o(DO)}if(S.type==="subagent.completion.queued"||S.type==="team.message.received")return;let ZO=E9(S);if(ZO)kO?.observe(ZO,S.seq)});try{if(q.aborted||r)return;let S=mO(N.currentRunId),pO=await YO(U,()=>G1(N)),ZO=gO(S)?await JO(N):void 0;try{let qO=ZO?.value,bO=qO?.getPendingSteeringCount()??0;await kO.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:U.sessionId,projectPath:U.projectPath,timestamp:Date.now(),status:gO(S)?S.status:"idle",runId:gO(S)?S.id:void 0,queued:bO,pendingInputDelivery:bO>0?qO?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:qO?.getRecoveredSteeringCount()??0,followUpQueue:pO,providerRecovery:qO?.getProviderRecoveryProjection()??null,turnActivity:qO?.getTurnActivityProjection()??null}})})}finally{ZO?.release()}if(q.aborted||r)return;if(C!==void 0){if(await q2.for(U.sessionId,U.projectPath).replay({onCommitted:async(bO)=>{if(q.aborted||r)return;let DO=n2(bO);if(!DO||DO.seq===void 0)return;await kO.writeReplay({...typeof bO.seq==="number"?{id:String(bO.seq)}:{},data:JSON.stringify({type:DO.type,...DO.seq!==void 0?{seq:DO.seq}:{},properties:{...DO.properties,sessionId:U.sessionId,projectPath:U.projectPath}})},DO.seq)}},C),q.aborted||r)return}if(kO.finishInitialization({replayed:C!==void 0}),q.aborted||r)return;if(!S&&!X0.has(i(U))){let bO=(await m0.list(U.projectPath,U.sessionId)).some((DO)=>DO.completion===void 0)?await _O(N,(DO)=>m0.recoverInterrupted(U.projectPath,U.sessionId,DO)):void 0;if(bO)await Y0(N),m.publish(U,"review.completed",{reviewId:bO.reviewId,status:bO.status,findings:0,recovered:!0})}if(q.aborted||r)return;if(!S)await g0.recoverResponded(U.projectPath,U.sessionId);if(q.aborted||r)return;let VO=S?void 0:await g0.findPending(U.projectPath,U.sessionId),hO=S?.pendingPermission??(VO?{permissionId:VO.request.requestId,details:g0.confirmationDetails(VO),resolve:()=>{return}}:void 0);if(hO){jO.add(hO.permissionId);let qO=p1(hO,!0);kO.observe({data:JSON.stringify({type:qO.type,properties:{...qO.properties,sessionId:U.sessionId,projectPath:U.projectPath}})})}if(q.aborted||r)return;if(V){let qO=p(N).catch(async(bO)=>{if(bO instanceof b0){await Y0(N).catch(()=>{return});let DO=N.taskFailure?.code==="workspace_unavailable"?N.taskFailure:o0("workspace_unavailable");N.taskStatus="failed",N.taskStatusReason=DO.message,N.taskFailure=DO,m.publish(U,"session.error",{error:DO.message,taskFailure:DO}),m.publish(U,"session.status",{status:"error"})}t.error(`[SessionRoutes] Failed to resume pending input for ${w}:`,bO)});o(qO)}if(q.aborted||r)return;XO=setInterval(()=>{if(q.aborted||r)return;kO?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await AO}catch(S){if(V2(S,r))return;throw S}finally{await vO()}});return W=!0,x.release(),E}catch(U){if(!W)K.release();throw U}}),O.post("/:sessionId/message",async(Q)=>{let w=Q.req.param("sessionId"),V=await Q.req.json(),K=h(L9,V);if(!K.success)throw new F("Invalid message format");let{content:W,attachments:U,modelId:x,reasoningEffort:N,serviceTier:j,responseVerbosity:D,communicationStyle:C,permissionMode:E,projectPath:q,annotations:d,outputSchema:NO}=K.data,TO;if(NO)try{TO=D4(NO).schema}catch(xO){throw new F(xO instanceof Error?xO.message:"Invalid output schema")}let XO=C;if(Buffer.byteLength(W,"utf8")>x4)throw new F(`Message text exceeds the ${x4}-byte limit`);let r=x?.trim();if((U??[]).reduce((xO,vO)=>xO+(typeof vO.content==="string"?Buffer.byteLength(vO.content):0),0)>a1)throw new F("Message attachments exceed the 5 MiB limit");let n=E,AO=X2(W,U),HO=d&&d.length>0?{selectedConversationAnnotations:d}:void 0,jO=await S1(w,q??Q.req.query("projectPath")),o=jO.value,l=QO(o),BO=n??o.permissionMode??"default";try{return await YO(l,async()=>{let xO=mO(o.currentRunId);if(gO(xO)){if(TO)throw new v("Wait for the active turn to finish before setting an output schema");return _O(o,async(ZO)=>{if(r&&!ZO.getModelById(r))throw new F(`Model not found: ${r}`);if(r&&ZO.getCurrentModelId()!==r)throw new v("Wait for the active turn to finish before switching models");if(N&&ZO.getReasoningConfiguration().selection!==N)throw new v("Wait for the active turn to finish before switching reasoning effort");if(j&&ZO.getServiceTierConfiguration().selection!==j)throw new v("Wait for the active turn to finish before switching service tier");if(D&&ZO.getResponseVerbosityConfiguration().selection!==D)throw new v("Wait for the active turn to finish before switching response verbosity");if(XO&&ZO.getCommunicationStyleConfiguration().selection!==XO)throw new v("Wait for the active turn to finish before switching communication style");if(n&&o.permissionMode!==n)throw new v("Wait for the active turn to finish before switching permission mode");let VO=await ZO.enqueueSteering(AO,{allowBeforeTurn:!0,...HO?{metadata:HO}:{}});if(!VO.accepted)return Q.json({status:"rejected",reason:VO.reason??"turn_unavailable"},409);let hO=VO.messageId??Y2(12),qO=VO.queued,bO=VO.queue??await ZO.getFollowUpQueueSnapshot(),DO=VO.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(m.publish(l,DO,{runId:xO.id,messageId:hO,queued:qO}),!VO.duplicate)m.publish(l,"follow_up.queue.changed",{queue:bO});if(VO.delivery==="next_turn"&&xO.status!=="running"&&xO.status!=="waiting_permission")p(o).catch((_0)=>{t.error(`[SessionRoutes] Failed to wake queued follow-up for ${w}:`,_0)});if(VO.delivery==="next_turn")xO.pendingFollowUpRequested=!0;return Q.json({runId:xO.id,messageId:hO,status:VO.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:qO,followUpQueue:bO},202)})}if(u(l),o.permissionMode!==BO)await X$(o,BO);let vO=await JO(o,{permissionMode:BO,...XO&&!XO.includes(":")?{communicationStyle:XO}:{}}),S=!1,pO;try{let ZO=vO.value;if(r&&!ZO.getModelById(r))throw new F(`Model not found: ${r}`);if(N)try{ZO.resolveReasoningConfiguration(N,r)}catch(EO){throw new F(EO instanceof Error?EO.message:"Invalid reasoning effort")}if(j)try{ZO.resolveServiceTierConfiguration(j,r)}catch(EO){throw new F(EO instanceof Error?EO.message:"Invalid service tier")}if(D)try{ZO.resolveResponseVerbosityConfiguration(D,r)}catch(EO){throw new F(EO instanceof Error?EO.message:"Invalid response verbosity")}let VO=XO?ZO.resolveCommunicationStyleConfiguration(XO):void 0;if(VO?.source!==void 0&&VO.source!=="built-in"&&!VO.contentSha256)throw new F("Custom communication style has no provenance");let hO=ZO.getCurrentModelId(),qO=ZO.getReasoningConfiguration(),bO=ZO.getServiceTierConfiguration(),DO=ZO.getResponseVerbosityConfiguration(),_0=ZO.getCommunicationStyleConfiguration(),w1=Boolean(r)&&hO!==r,z0=Boolean(N)&&qO.selection!==N,G$=Boolean(j)&&bO.selection!==j,K$=Boolean(D)&&DO.selection!==D,w$=Boolean(XO)&&_0.selection!==XO;if(w1||z0||G$||K$||w$)await ZO.refresh({...r?{modelId:r}:{},...N?{reasoningEffort:N}:{},...j?{serviceTier:j}:{},...D?{responseVerbosity:D}:{},...XO?{communicationStyle:XO}:{}});let Y4={...r&&o.selectedModelId!==r?{selectedModelId:r}:{},...N&&o.reasoningEffort!==N?{reasoningEffort:N}:{},...j&&o.serviceTier!==j?{serviceTier:j}:{},...D&&o.responseVerbosity!==D?{responseVerbosity:D}:{},...VO&&(o.communicationStyle!==XO||o.communicationStyleDigest!==VO.contentSha256)?{communicationStyle:XO,communicationStyleDigest:VO.source==="built-in"?null:VO.contentSha256}:{}};if(Object.keys(Y4).length>0)try{let EO=await g.updateSessionMetadata(o.id,o.projectPath,Y4);o.permissionMode=EO.permissionMode,o.selectedModelId=EO.selectedModelId,o.reasoningEffort=EO.reasoningEffort,o.serviceTier=EO.serviceTier,o.responseVerbosity=EO.responseVerbosity,o.communicationStyle=EO.communicationStyle,o.communicationStyleDigest=EO.communicationStyleDigest,o.updatedAt=new Date(EO.lastMessageTime),m.publish(l,"session.updated",Y4)}catch(EO){if(w1||z0||G$||K$||w$)await ZO.refresh({...hO?{modelId:hO}:{},reasoningEffort:qO.selection,serviceTier:bO.selection,responseVerbosity:DO.selection,communicationStyle:_0.selection}).catch((h5)=>t.error("[SessionRoutes] Failed to roll back non-durable model settings:",h5));throw EO}let H1=TO||HO?await ZO.prepareInputTurn(AO,{...TO?{outputSchema:TO}:{},...HO?{metadata:HO}:{}}):await ZO.prepareInputTurn(AO);if(!H1.accepted)return Q.json({status:"rejected",reason:H1.reason},H1.reason==="queue_full"?429:409);pO=S0(jO);let X4=K1(o,AO,BO,{preparedInputTurn:H1,outputSchema:TO,runtimeLease:vO,projectionLease:pO});return S=!0,pO=void 0,await X4.taskAdmissionUpdate,Q.json({runId:X4.id,messageId:H1.messageId,status:X4.status==="queued"?"queued":"running",queuePosition:o.taskQueuePosition,queueDepth:o.taskQueueDepth,maxConcurrentTasks:o.taskConcurrencyLimit},202)}finally{if(pO?.release(),!S)vO.release()}})}finally{jO.release()}}),O.post("/:sessionId/side-question",async(Q)=>{let w=Q.req.param("sessionId"),V=h(p2,await Q.req.json());if(!V.success)throw new F("Invalid side conversation request");return oO(w,V.data.projectPath??Q.req.query("projectPath"),(K)=>E1(K,async(W)=>{let U=await W.askSideQuestion(V.data.question,{signal:Q.get("requestSignal")});return Q.json({...U,...W.getCurrentModelId()?{modelId:W.getCurrentModelId()}:{}})}))}),O.post("/:sessionId/shell",async(Q)=>{let w=Q.req.param("sessionId"),V=h(v2,await Q.req.json());if(!V.success)throw new F("Invalid user shell command");return oO(w,V.data.projectPath??Q.req.query("projectPath"),(K,W,U)=>{let x=i(W);return YO(W,async()=>{if(x0.has(x))throw new v("A user shell command is already running in this Session");let N=await JO(K),j=S0(U),D=N.value,C=new AbortController,E,q=new Promise((d)=>{E=d});x0.set(x,{controller:C,completion:q,projectionLease:j});try{let d=await D.executeUserShellCommand(V.data.command,{signal:C.signal});await Y0(K);let NO=mO(K.currentRunId);if(d.delivery==="next_turn"&&gO(NO))NO.pendingFollowUpRequested=!0;if(d.queue)m.publish(W,"follow_up.queue.changed",{queue:d.queue});return Q.json({executionId:d.executionId,messageId:d.messageId,record:d.record,auxiliary:d.auxiliary,...d.delivery?{delivery:d.delivery}:{},...d.queued!==void 0?{queued:d.queued}:{}})}finally{x0.delete(x),E(),N.release(),j.release()}})})}),O.post("/:sessionId/abort",async(Q)=>{let w=Q.req.param("sessionId"),V=await uO(w,Q.req.query("projectPath"));u(V);let K=V0(V);if(K?.currentRunId){let x=mO(K.currentRunId);if(x)h0(x),await x.completion}let W=x0.get(i(V));if(W)W.controller.abort("user-cancel"),await W.completion;let U=X0.get(i(V));if(U)U.controller.abort("user-cancel"),await U.completion;return Q.json({success:!0})}),O.get("/:sessionId/status",async(Q)=>{let w=Q.req.param("sessionId"),V=await uO(w,Q.req.query("projectPath")),K=V0(V),W=X0.get(i(V));if(W)return Q.json({sessionId:w,projectPath:V.projectPath,reviewId:W.reviewId,status:"reviewing"});if(!K?.currentRunId)return Q.json({sessionId:w,projectPath:V.projectPath,status:"idle"});let U=mO(K.currentRunId);return Q.json({sessionId:w,projectPath:V.projectPath,runId:K.currentRunId,status:U?.status==="attention_required"?"idle":U?.status??"idle"})}),{app:O,dispatchTask:V$,retryTask:R5,updateTask:E5,getTaskDiff:f5,deliverTask:P5,recoverQueuedTasks:k5,getRuntimeResidencyStats:()=>I.getStats(),getProjectionResidencyStats:()=>A.getStats(),getCoordinationStats:()=>({messageSubmissions:H.getStats(),taskDeliveries:B.getStats()}),getSseConnectionStats:()=>L.stats(),shutdown:(Q="server-shutdown")=>{if(k)return k;f.close(Q);let w=L.shutdown(Q);Q4.accepting=!1,Q$("server-shutdown");let V=Promise.allSettled([...G].map((K)=>K.promise));return clearInterval(R),clearInterval(P),y(),k=(async()=>{let K,W=async(D)=>{let C=await Promise.allSettled(D);for(let E of C)if(E.status==="rejected")K??=E.reason},U=new Set,x=()=>{for(let D of F4()){if(D.completion)U.add(D.completion);if(gO(D))h0(D,Q)}for(let D of x0.values())D.controller.abort(Q),U.add(D.completion);for(let D of X0.values())D.controller.abort(Q),U.add(D.completion)},N=f.waitForIdle(),j=!1;N.then(()=>{j=!0});while(!j)x(),await Promise.race([N,new Promise((D)=>setImmediate(D))]);if(await N,x(),await W([...U]),await V,await W([...J.values()]),x(),await W([...U]),await W([w]),await W([...J.values()]),await W([I.disposeAll()]),$.clear(),await W([...Y.values()]),await W([Z.disposeAll()]),await W([iO.getInstance().disconnectAll()]),J.clear(),Y.clear(),X.clear(),G.clear(),U0===Q4)U0=void 0;if(b1===y)b1=void 0;if(K!==void 0)throw K})(),k}}};async function o2(O,$,Z){t.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),t.info(`[SessionRoutes] Active runs: ${e$()}`);let J=O2(O,$);if(J){t.info(`[SessionRoutes] Found permission ${$} in run ${J.id}`);let H=J.pendingPermission;if(!H)throw Error("Active permission run lost its pending interaction");if(H.details.interactionRequestId)await g0.respond(O.projectPath,O.sessionId,$,Z);return H.resolve(Z),t.info(`[SessionRoutes] Permission ${$} responded, runId: ${J.id}`),!0}let Y=await g0.findPending(O.projectPath,O.sessionId);if(!Y||Y.request.requestId!==$)return t.error(`[SessionRoutes] Permission not found: ${$}`),!1;await g0.respondAndRecover(O.projectPath,O.sessionId,$,Z),m.publish(O,"interaction.resolved",{requestId:$});let X=U0;if(!X?.accepting)return!0;let G;try{G=await X.acquireOrHydrateSession(O);let H=G.value,B=await g.findSessionMetadata(O.sessionId,O.projectPath);if(U0!==X||!X.accepting||!G.isCurrent())return!0;if(B)$0(H,B);X.resumeRecoveredInteraction(H).catch((M)=>{t.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,M)})}catch(H){if(U0!==X||!X.accepting)return!0;throw H}finally{G?.release()}return!0}var E4=OO("Service"),k9=z.Object({approved:z.Boolean(),remember:z.Optional(z.Boolean()),scope:z.Optional(GO(["once","session","project"])),targetMode:z.Optional(GO(["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:GO(["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}))}))}),t2=()=>{let O=new P9;return O.post("/:permissionId",async($)=>{let Z=$.req.param("permissionId"),J=$.req.query("sessionId"),Y=$.req.query("projectPath");E4.info(`[PermissionRoutes] Received permission response: permissionId=${Z}, sessionId=${J}`);try{let X=await $.req.json(),G=h(k9,X);if(!G.success)throw new F("Invalid permission response format");let{approved:H,remember:B,scope:M,targetMode:b,feedback:I,answers:A,elicitation:f}=G.data;if(!J)throw new F("sessionId query parameter is required");let L=await uO(J,Y);if(!await o2(L,Z,{approved:H,reason:I,scope:M,targetMode:b,feedback:I,answers:A,elicitation:f}))throw new c("Permission request",Z);return E4.info(`[PermissionRoutes] Permission ${Z} ${H?"approved":"denied"}`),$.json({success:!0,approved:H,remember:B})}catch(X){if(E4.error("[PermissionRoutes] Failed to respond to permission:",X),X instanceof F||X instanceof lO||X instanceof c||X instanceof wO)throw X;throw X}}),O};import{homedir as s2}from"node:os";import f4 from"node:path";import{Hono as h9}from"hono";var y9=z.Object({projectPath:z.String({minLength:1}),enabled:z.Boolean(),scope:z.Optional(GO(["local","project","global"]))}),m9=z.Object({projectPath:z.String({minLength:1})}),g9=z.Object({projectPath:z.String({minLength:1}),source:z.String({minLength:1}),trust:z.Literal(!0),ref:z.Optional(z.String({minLength:1}))}),v9=z.Object({projectPath:z.String({minLength:1}),trust:z.Literal(!0)}),p9=z.Object({projectPath:z.String({minLength:1}),confirm:z.Literal(!0)}),u9=z.Object({projectPath:z.String({minLength:1}),source:z.String({minLength:1}),ref:z.Optional(z.String({minLength:1}))}),r2=z.Object({projectPath:z.String({minLength:1}),confirm:z.Optional(z.Literal(!0))}),d9=z.Object({projectPath:z.String({minLength:1}),scope:z.Optional(GO(["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 Z0(O){if(!O)throw new F("projectPath must be absolute");try{return WO(O)}catch{throw new F("projectPath must reference a local workspace")}}function c9(O){return f4.isAbsolute(O)||O.startsWith("./")||O.startsWith("../")||O==="~"||O.startsWith("~/")}function e2(O,$){if(!c9(O))return;let Z=O==="~"?s2():O.startsWith("~/")?f4.join(s2(),O.slice(2)):O;try{WO(f4.resolve($,Z))}catch{throw new F("Plugin source must reference a local workspace")}}async function O3(O){let[$,Z]=await Promise.all([O0(O),_1.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((J)=>({name:J.manifest.name,description:J.manifest.description,version:J.manifest.version,source:J.source,enabled:J.status==="active",status:J.status,commands:J.commands.length,skills:J.skills.length,agents:J.agents.length,hooks:J.hooks?Object.values(J.hooks).reduce((Y,X)=>Y+(Array.isArray(X)?X.length:0),0):0,mcpServers:Object.keys(J.mcpServers??{}).length,configurable:J.source!=="cli",managed:J.installation!==void 0,marketplace:J.installation?.source.type==="marketplace"?J.installation.source.marketplace:void 0,revision:J.installation?.revision,installedAt:J.installation?.installedAt,updatedAt:J.installation?.updatedAt,compatibilityIssues:J.compatibilityIssues??[],effectiveScope:J.source==="cli"?"invocation":Z.settings[J.manifest.name]?.effectiveScope??"default",settingLayers:J.source==="cli"?{invocation:!0}:Z.settings[J.manifest.name]?.layers??{}}))}async function l9(){let O=$3(),[$,Z]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),J=new Map(Z.map((Y)=>[Y.name,Y]));return $.map(({marketplace:Y,manifest:X})=>({name:Y.name,description:X.description??X.metadata?.description??"",sourceType:Y.source.type,revision:Y.revision,updatedAt:Y.updatedAt,plugins:X.plugins.map((G)=>{let H=J.get(G.name);return{name:G.name,description:G.description??"",version:G.version,category:G.category,tags:G.tags??[],installed:H!==void 0,installedVersion:H?.version}})}))}function s0(O,$){if(!O.success)throw new F(O.error??$)}var w3=()=>{let O=new h9;return O.get("/",async($)=>{let Z=Z0($.req.query("projectPath"));return $.json(await O3(Z))}),O.post("/refresh",async($)=>{let Z=h(m9,await $.req.json());if(!Z.success)throw new F("Invalid plugin refresh request");let J=Z0(Z.data.projectPath),Y=await J3(J);return $.json({plugins:await O3(J),errors:Y.discovery.errors.map((X)=>({code:X.code??"LOAD_ERROR",error:X.error}))})}),O.get("/catalog",async($)=>{return Z0($.req.query("projectPath")),$.json(await l9())}),O.get("/policy",async($)=>{let Z=Z0($.req.query("projectPath")),J=await _1.getInstance().loadWorkspacePluginSourcePolicy(Z);return $.json({policy:J,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let Z=h(d9,await $.req.json());if(!Z.success)throw new F("Invalid plugin source policy request");let J=Z0(Z.data.projectPath),Y=await Q3(J,Z.data.policy,Z.data.scope??"global");return $.json({policy:Y})}),O.post("/install",async($)=>{let Z=h(g9,await $.req.json());if(!Z.success)throw new F("Invalid plugin install request; explicit source trust is required");let J=Z0(Z.data.projectPath);e2(Z.data.source,J);let{result:Y}=await Y3(J,Z.data.source,{trusted:Z.data.trust,ref:Z.data.ref});return s0(Y,"Plugin installation failed"),$.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,installedDependencies:Y.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let Z=h(u9,await $.req.json());if(!Z.success)throw new F("Invalid marketplace add request");let J=Z0(Z.data.projectPath);e2(Z.data.source,J);let Y=await z3(J,Z.data.source,Z.data.ref);return s0(Y,"Marketplace installation failed"),$.json({name:Y.marketplace?.name,plugins:Y.manifest?.plugins.length??0,revision:Y.marketplace?.revision,changed:Y.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let Z=h(r2,await $.req.json());if(!Z.success)throw new F("Invalid marketplace refresh request");let J=await G3(Z0(Z.data.projectPath),$.req.param("name"));return s0(J,"Marketplace refresh failed"),$.json({name:J.marketplace?.name,plugins:J.manifest?.plugins.length??0,revision:J.marketplace?.revision,changed:J.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let Z=h(r2,await $.req.json());if(!Z.success||Z.data.confirm!==!0)throw new F("Invalid marketplace removal request; explicit confirmation is required");Z0(Z.data.projectPath);let J=await K3($.req.param("name"),!0);return s0(J,"Marketplace removal failed"),$.json({name:J.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let Z=h(v9,await $.req.json());if(!Z.success)throw new F("Invalid plugin update request; explicit source trust is required");let J=Z0(Z.data.projectPath),{result:Y}=await X3(J,$.req.param("name"),{trusted:Z.data.trust});return s0(Y,"Plugin update failed"),$.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,updatedDependencies:Y.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let Z=h(p9,await $.req.json());if(!Z.success)throw new F("Invalid plugin uninstall request; explicit confirmation is required");let J=Z0(Z.data.projectPath),{result:Y}=await V3(J,$.req.param("name"),Z.data.confirm);return s0(Y,"Plugin uninstall failed"),$.json({name:Y.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let Z=h(y9,await $.req.json());if(!Z.success)throw new F("Invalid plugin state request");let J=Z0(Z.data.projectPath),Y=$.req.param("name"),G=(await O0(J)).plugins.get(Y);if(!G)throw new c("Plugin",Y);if(G.source==="cli")throw new F(`Plugin "${Y}" was loaded with --plugin-dir and is invocation-scoped`);let H=await Z3(J,Y,Z.data.enabled,Z.data.scope??"local");return $.json(H)}),O};import{Hono as t9}from"hono";import{execFile as i9}from"node:child_process";import n9 from"node:path";var k4="__BLADE_DIRECTORY_PICKER_CANCELLED__",a9=900000;function o9(O,$){return new Promise((Z)=>{i9(O,[...$],{timeout:a9,maxBuffer:65536,windowsHide:!0},(J,Y,X)=>{let G=J?.code;Z({stdout:Y,stderr:X,exitCode:typeof G==="number"?G:J?1:0,...typeof G==="string"?{errorCode:G}:{}})})})}function S4(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===k4)return{cancelled:!0};if(!n9.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function P4(O){return O.exitCode!==0||Boolean(O.errorCode)}class H3{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??o9}pick(){if(this.activeSelection)return this.activeSelection;let O=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=O,O}async pickForPlatform(){switch(this.platform){case"darwin":return this.pickOnMac();case"win32":return this.pickOnWindows();case"linux":return this.pickOnLinux();default:throw Error("Native folder selection is unavailable on this system")}}async pickOnMac(){let O=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${k4}"`,"end try"].join(`
|
|
8
|
+
`),$=await this.runCommand("osascript",["-e",O]);if(P4($))throw Error("Unable to open the macOS folder picker");return S4($.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("${k4}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(P4($))throw Error("Unable to open the Windows folder picker");return S4($.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 Z=await this.runCommand($.command,$.args);if(Z.errorCode==="ENOENT")continue;if(Z.exitCode===1&&!Z.stdout.trim()&&!Z.stderr.trim())return{cancelled:!0};if(P4(Z))throw Error("Unable to open the Linux folder picker");return S4(Z.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var W3=new H3;var s9=z.Object({path:z.String({minLength:1})});function U3(O){try{return WO(O)}catch($){throw new F($ instanceof Error?$.message:"Project path is invalid")}}function r9(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let $=new URL(O).hostname;return $==="localhost"||$==="127.0.0.1"||$==="::1"||$==="[::1]"}catch{return!1}}var F3=(O={})=>{let $=new t9,Z=O.pickDirectory??(()=>W3.pick()),J=O.allowDirectoryPickerRequest??r9;return $.get("/",async(Y)=>{return Y.json(await o1.list(KO()))}),$.post("/",async(Y)=>{let X;try{X=await Y.req.json()}catch{throw new F("A valid JSON body is required")}let G=h(s9,X);if(!G.success)throw new F("A project path is required");try{let H=U3(G.data.path),B=await o1.bind(H,KO());return Y.json(B,201)}catch(H){throw new F(H instanceof Error?H.message:"Failed to bind project")}}),$.post("/pick",async(Y)=>{if(!J(Y.req.header("Origin")))throw new wO("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Y.json(await Z())}catch(X){throw new F(X instanceof Error?X.message:"Failed to select a folder")}}),$.delete("/",async(Y)=>{let X=Y.req.query("path");if(!X)throw new F("A project path is required");try{let G=await o1.unbind(U3(X));return Y.json({success:!0,removed:G})}catch(G){throw new F(G instanceof Error?G.message:"Failed to unbind project")}}),$};import{Hono as e9}from"hono";var _3=OO("Service"),D3=()=>{let O=new e9;return O.get("/",async($)=>{try{let Z=await B3();return $.json(Z)}catch(Z){return _3.error("[ProviderRoutes] Failed to list providers:",Z),$.json([])}}),O.get("/:provider/models",async($)=>{let Z=$.req.param("provider");try{let J=await x3(Z);return $.json(J)}catch(J){return _3.error("[ProviderRoutes] Failed to list models:",J),$.json([])}}),O.put("/:provider/credential",async($)=>{let Z=$.req.param("provider"),J=await $.req.json();if(!J.apiKey?.trim())throw new F("apiKey is required");return await P0().setApiKey(Z,J.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await P0().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let Z=$.req.param("provider"),J=LO(),Y=J?.modelProviders[Z];if(!J||!Y)throw new c("Model provider",Z);let X=await $.req.json();if(!X.name||!X.baseUrl||!X.wireApi)throw new F("name, baseUrl and wireApi are required");let G="apiKeyEnv"in X?X.apiKeyEnv?.trim():Y.apiKeyEnv,H={name:X.name,baseUrl:X.baseUrl,wireApi:X.wireApi,...G?{apiKeyEnv:G}:{}},B=P0(),M=X.apiKey?.trim()?await B.credentials.read(Z):void 0;if(X.apiKey?.trim())await B.setApiKey(Z,X.apiKey.trim());try{return await tO().updateModelProvider(Z,H),$.json({success:!0})}catch(b){if(X.apiKey?.trim())if(M)await B.credentials.modify(Z,async()=>M);else await B.credentials.delete(Z);if(b instanceof Error&&(b.message.includes("modelProviders.")||b.message.includes("built-in provider")))throw new F(b.message);throw b}}),O.delete("/:provider",async($)=>{let Z=$.req.param("provider");if(!LO()?.modelProviders[Z])throw new c("Model provider",Z);let Y=$.req.query("removeModels");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new F("removeModels must be true or false");try{let X=await tO().removeModelProvider(Z,{removeModels:Y==="true"});return $.json({success:!0,...X})}catch(X){if(X instanceof Error&&(X.message.includes("still referenced")||X.message.includes("owns the only model")))throw new v(X.message);throw X}}),O.post("/:provider/probe",async($)=>{let Z=$.req.param("provider"),J=LO();if(!J?.modelProviders[Z])throw new c("Model provider",Z);let Y=await $.req.json().catch(()=>({})),X=J.models.filter((H)=>H.provider===Z),G=Y.modelId?X.find((H)=>H.id===Y.modelId):X[0];if(!G)throw new F(Y.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return $.json(await N3(G,J))}),O};import{Hono as O6}from"hono";var $6=OO("Service"),j3=(O,$)=>{let Z=new O6;return Z.onError((J,Y)=>{if(J instanceof wO)return Y.json(J.toObject(),J.statusCode);return $6.error("[ScheduleRoutes] Unhandled route error:",J),Y.json(new zO("Schedule request failed").toObject(),500)}),Z.get("/",async(J)=>{let Y=await O.list();return J.json(A3.parse({schedules:Y}))}),Z.post("/",async(J)=>{let Y;try{Y=await J.req.json()}catch{throw new F("Invalid request body")}let X=h(M3,Y);if(!X.success)throw new F("Invalid schedule request");let G;try{G=WO(X.data.projectPath||J.get("directory")||KO())}catch{throw new F("projectPath must reference a local workspace")}try{let H=await O.create({...X.data,projectPath:G});return J.json(v0.parse(H),201)}catch(H){throw new F(H instanceof Error?H.message:"Failed to create schedule")}}),Z.get("/:id",async(J)=>{let Y=await O.get(J.req.param("id"));if(!Y)throw new c("Schedule not found");return J.json(v0.parse(Y))}),Z.patch("/:id",async(J)=>{let Y;try{Y=await J.req.json()}catch{throw new F("Invalid request body")}let X=h(L3,Y);if(!X.success)throw new F("Invalid schedule update");let{modelId:G,reasoningEffort:H,serviceTier:B,responseVerbosity:M,communicationStyle:b,isolation:I,permissionMode:A,...f}=X.data,L={...G!==void 0?{modelId:G}:{},...H!==void 0?{reasoningEffort:H}:{},...B!==void 0?{serviceTier:B}:{},...M!==void 0?{responseVerbosity:M}:{},...b!==void 0?{communicationStyle:b}:{},...I!==void 0?{isolation:I}:{},...A!==void 0?{permissionMode:A}:{}};try{let R=await O.update(J.req.param("id"),{...f,...Object.keys(L).length>0?{dispatch:L}:{}});if(!R)throw new c("Schedule not found");return J.json(v0.parse(R))}catch(R){if(R instanceof wO)throw R;throw new F(R instanceof Error?R.message:"Failed to update schedule")}}),Z.delete("/:id",async(J)=>{if(!await O.remove(J.req.param("id")))throw new c("Schedule not found");return J.json({ok:!0})}),Z.post("/:id/enable",async(J)=>{let Y=await O.setEnabled(J.req.param("id"),!0);if(!Y)throw new c("Schedule not found");return J.json(v0.parse(Y))}),Z.post("/:id/disable",async(J)=>{let Y=await O.setEnabled(J.req.param("id"),!1);if(!Y)throw new c("Schedule not found");return J.json(v0.parse(Y))}),Z.post("/:id/run",async(J)=>{let Y=await O.get(J.req.param("id"));if(!Y)throw new c("Schedule not found");if(!$)throw new zO("Scheduler is not running in this process");await $.fire(Y,new Date,{manual:!0});let X=await O.get(Y.id);return J.json(v0.parse(X??Y),202)}),Z};import{createHash as Z6}from"node:crypto";import{Hono as J6}from"hono";var h4={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},Q6=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(GO(["true","false"])),workspaceKind:z.Optional(GO(["local","acp-remote"]))},{additionalProperties:!1}),t1=65536,Y6=new Set(["cursor","limit","archived","workspaceKind"]),X6=new Set(["locator","limit"]),V6=new Set(["locator","cursor","expectedSnapshot","limit"]),z6=new Set(["locator"]),G6=new Set(["version","sessionId","workspace"]),K6=new Set(["kind","projectPath","workspaceRef"]),w6=OO("Service");function P3(O={}){let $=O.service?void 0:new f3(O.cursorRegistryOptions),Z=O.service??new S3({database:O.database,cursorRegistry:$}),J=O.logger??w6,Y=new J6,X=!0,G=0,H,B=new Set,M=()=>new r0("session_surface_unavailable"),b=()=>{if(G===0)return Promise.resolve();return new Promise((A)=>B.add(A))};return Y.onError((A,f)=>{let L=U6(A);return J.warn(`[SessionSurfaceRoutes] method=${f.req.method} path=${f.req.path} code=${L.error.code} kind=${f.get("surfaceKind")??"unknown"} locator=${f.get("surfaceLocatorDigest")??"none"}`),f.json(L,h4[L.error.code])}),Y.use("*",async(A,f)=>{if(A.set("surfaceKind","unknown"),A.set("surfaceLocatorDigest","none"),!X){let L=s1(M());return A.json(L,h4[L.error.code])}G+=1;try{if(await f(),!X){let L=s1(M());A.res=A.json(L,h4[L.error.code])}return A.res}finally{if(G-=1,G===0){for(let L of B)L();B.clear()}}}),Y.get("/catalog",async(A)=>{let f=H6(A.req.url),L=await Z.listPage(f);return A.json(q3.parse(L))}),Y.post("/open",async(A)=>{y4(A.req.url);let f=await v4(A.req.raw);q1(f,X6,dO());let L=m4(f);g4(A,L);let R=h(C3,f);if(!R.success)throw dO();let P=await Z.open(L,{limit:R.data.limit});return A.json(p4.parse(P))}),Y.post("/history",async(A)=>{y4(A.req.url);let f=await v4(A.req.raw);q1(f,V6,dO());let L=m4(f);g4(A,L);let R=h(R3,f);if(!R.success)throw dO();let P=await Z.historyPage(L,{cursor:R.data.cursor,expectedSnapshot:R.data.expectedSnapshot,limit:R.data.limit});return A.json(I3.parse(P))}),Y.post("/fork",async(A)=>{y4(A.req.url);let f=await v4(A.req.raw);q1(f,z6,dO());let L=m4(f);if(g4(A,L),!h(E3,f).success)throw dO();let P=await Z.fork(L);return A.json(p4.parse(P))}),{app:Y,getStats:()=>({accepting:X,active:G,cursors:$?.stats().entryCount??0}),shutdown:(A="server-shutdown")=>{if(H)return H;return X=!1,H=(async()=>{let L=(await Promise.allSettled([Promise.resolve().then(()=>Z.close(A)),b()])).find((R)=>R.status==="rejected");if(L)throw L.reason})(),H}}}function dO(){return new r0("invalid_session_surface_request")}function H6(O){let $=new URL(O).searchParams,Z={},J=new Set;for(let[X,G]of $){if(!Y6.has(X)||J.has(X))throw dO();J.add(X),Z[X]=G}let Y=h(Q6,Z);if(!Y.success)throw dO();return{...Y.data.archived!==void 0?{archived:Y.data.archived==="true"}:{},...Y.data.cursor!==void 0?{cursor:Y.data.cursor}:{},...Y.data.limit!==void 0?{limit:Number(Y.data.limit)}:{},...Y.data.workspaceKind!==void 0?{workspaceKind:Y.data.workspaceKind}:{}}}function y4(O){if(new URL(O).searchParams.size>0)throw dO()}function q1(O,$,Z){if(!O||typeof O!=="object"||Array.isArray(O))throw Z;if(Object.keys(O).some((J)=>!$.has(J)))throw Z}function m4(O){if(!O||typeof O!=="object"||Array.isArray(O))throw dO();let $=Reflect.get(O,"locator");if($===void 0)throw dO();let Z=new r0("invalid_session_locator");q1($,G6,Z),q1(Reflect.get($,"workspace"),K6,Z);let J=h(b3,$);if(!J.success)throw Z;return J.data}function g4(O,$){O.set("surfaceKind",$.workspace.kind),O.set("surfaceLocatorDigest",F6($))}async function v4(O){let $=O.headers.get("content-length");if($!==null&&(!/^\d+$/.test($)||Number($)>t1))throw dO();let Z=O.body?.getReader();if(!Z)throw dO();let J=[],Y=0;try{while(!0){let{done:B,value:M}=await Z.read();if(B)break;if(Y+=M.byteLength,Y>t1){try{await Z.cancel()}catch{}throw dO()}J.push(M)}}finally{Z.releaseLock()}let X=new Uint8Array(Y),G=0;for(let B of J)X.set(B,G),G+=B.byteLength;let H=new TextDecoder().decode(X);if(!H)throw dO();try{return W6(H),JSON.parse(H)}catch{throw dO()}}function W6(O){let $=0,Z=()=>{while(/\s/.test(O[$]??""))$+=1},J=()=>{let X=$;if(O[$]!=='"')throw Error("expected string");$+=1;while($<O.length){let G=O[$];if(G==="\\"){$+=2;continue}if($+=1,G==='"')return JSON.parse(O.slice(X,$))}throw Error("unterminated string")},Y=()=>{Z();let X=O[$];if(X==="{"){$+=1,Z();let H=new Set;if(O[$]==="}"){$+=1;return}while($<O.length){Z();let B=J();if(H.has(B))throw Error("duplicate key");if(H.add(B),Z(),O[$]!==":")throw Error("expected colon");if($+=1,Y(),Z(),O[$]==="}"){$+=1;return}if(O[$]!==",")throw Error("expected comma");$+=1}throw Error("unterminated object")}if(X==="["){if($+=1,Z(),O[$]==="]"){$+=1;return}while($<O.length){if(Y(),Z(),O[$]==="]"){$+=1;return}if(O[$]!==",")throw Error("expected comma");$+=1}throw Error("unterminated array")}if(X==='"'){J();return}let G=/^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(O.slice($))?.[0];if(!G)throw Error("invalid primitive");$+=G.length};if(Y(),Z(),$!==O.length)throw Error("trailing JSON")}function U6(O){if(O instanceof r0)return s1(O);return s1(new r0("session_surface_state_invalid"))}function s1(O){return T3.parse({error:{code:O.code,message:O.message,retryable:O.retryable}})}function F6(O){if(!O)return"none";return Z6("sha256").update("session-surface-route-locator-v2\x00").update(JSON.stringify(O)).digest("hex").slice(0,16)}import*as R0 from"node:fs/promises";import{homedir as g3}from"node:os";import*as aO from"node:path";import{Hono as D6}from"hono";import{execFile as _6}from"node:child_process";import*as s from"node:fs/promises";import{homedir as N6}from"node:os";import*as $O from"node:path";import{promisify as B6}from"node:util";var x6=B6(_6),IO=OO("General");function p0(O){return typeof O==="string"&&O===O.trim()&&/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/.test(O)}function d4(O){if(typeof O!=="string"||!O||/\s/.test(O))return!1;if([...O].some(($)=>$.charCodeAt(0)<32||$.charCodeAt(0)===127))return!1;if(O.startsWith("git@"))return/^git@[A-Za-z0-9][A-Za-z0-9.-]*:[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+$/.test(O);if(!/^(https|ssh):\/\//.test(O))return!1;try{let $=new URL(O);return($.protocol==="https:"||$.protocol==="ssh:")&&Boolean($.hostname)&&!$.hostname.startsWith("-")&&!$.password&&!($.protocol==="https:"&&$.username)&&!($.username&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test($.username))&&!$.search&&!$.hash&&$.pathname!=="/"}catch{return!1}}function c4(O){let $=O.startsWith("git@")?O.slice(O.indexOf(":")+1):new URL(O).pathname;return $O.posix.basename($.replace(/\/+$/,"")).replace(/\.git$/,"")}var k3={url:"https://github.com/anthropics/skills.git",branch:"main"};class h3{skillsDir;constructor(O){this.skillsDir=O||$O.join(N6(),".blade","skills")}async isGitAvailable(){try{return await this.runGit(["--version"],5000),!0}catch{return!1}}async runGit(O,$){await x6("git",O,{shell:!1,timeout:$,maxBuffer:4194304,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}})}async installOfficialSkill(O){if(!p0(O))return!1;let{url:$,branch:Z}=k3,J=$O.join(this.skillsDir,O),Y=$O.join(this.skillsDir,`.tmp-${O}-${Date.now()}`);try{if(!await this.isGitAvailable())return IO.warn("Git not available, skipping skill installation"),!1;IO.info(`Installing official skill: ${O}...`),await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),await this.runGit(["clone","--depth","1","--branch",Z,"--single-branch","--",$,Y],30000);let X=$O.join(Y,"skills",O);try{await s.access(X)}catch{return IO.warn(`Skill ${O} not found in official repository`),await s.rm(Y,{recursive:!0,force:!0}),!1}try{await s.rm(J,{recursive:!0,force:!0})}catch{}return await s.cp(X,J,{recursive:!0}),await s.rm(Y,{recursive:!0,force:!0}),IO.info(`Successfully installed: ${O}`),!0}catch(X){try{await s.rm(Y,{recursive:!0,force:!0})}catch{}return IO.warn(`Failed to install ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installFromRepo(O,$){if(!d4(O))return!1;let Z=$??c4(O);if(!p0(Z))return!1;let J=$O.join(this.skillsDir,Z),Y=$O.join(this.skillsDir,`.tmp-repo-${Z}-${Date.now()}`);try{if(!await this.isGitAvailable())return IO.warn("Git not available, cannot install from repo"),!1;IO.info(`Installing skill from repo: ${O}...`),await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),await this.runGit(["clone","--depth","1","--",O,Y],60000);let X=$O.join(Y,"SKILL.md");try{await s.access(X)}catch{return IO.warn(`No SKILL.md found in repository ${O}`),await s.rm(Y,{recursive:!0,force:!0}),!1}await s.rm(J,{recursive:!0,force:!0}),await s.rename(Y,J);try{await s.rm($O.join(J,".git"),{recursive:!0,force:!0})}catch{}return IO.info(`Successfully installed skill from repo: ${Z}`),!0}catch(X){try{await s.rm(Y,{recursive:!0,force:!0})}catch{}return IO.warn(`Failed to install from repo ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installFromLocal(O,$,Z=!0){if(typeof O!=="string"||!O.trim()||O.includes("\x00"))return!1;let J=$??$O.basename(O);if(!p0(J))return!1;let Y=$O.resolve(this.skillsDir,J);try{let X=await s.realpath($O.resolve(O)),G=$O.dirname(Y),H=[];while(!0)try{G=$O.join(await s.realpath(G),...H);break}catch(b){if(b.code!=="ENOENT")throw b;H.unshift($O.basename(G)),G=$O.dirname(G)}let B=$O.join(G,J);try{if(!(await s.lstat(B)).isSymbolicLink())B=await s.realpath(B)}catch(b){if(b.code!=="ENOENT")throw b}if([$O.relative(B,X),$O.relative(X,B)].some((b)=>b===""||!b.startsWith(`..${$O.sep}`)&&b!==".."&&!$O.isAbsolute(b)))return!1;let M=$O.join(X,"SKILL.md");try{await s.access(M)}catch{return IO.warn(`No SKILL.md found in local path: ${X}`),!1}if(IO.info(`Installing skill from local path: ${X}...`),await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),await s.rm(Y,{recursive:!0,force:!0}),Z)await s.symlink(X,Y,"dir"),IO.info(`Created symlink for skill: ${J}`);else await s.cp(X,Y,{recursive:!0}),IO.info(`Copied skill to: ${J}`);return!0}catch(X){return IO.warn(`Failed to install from local path ${O}: ${X instanceof Error?X.message:"Unknown error"}`),!1}}async installAllOfficialSkills(){let{url:O,branch:$}=k3,Z=$O.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],Y=[];try{if(!await this.isGitAvailable())return IO.warn("Git not available, skipping skill installation"),{installed:J,failed:Y};await s.mkdir(this.skillsDir,{recursive:!0,mode:493}),IO.info("Cloning official skills repository..."),await this.runGit(["clone","--depth","1","--branch",$,"--single-branch","--",O,Z],60000);let X=$O.join(Z,"skills"),G=await s.readdir(X,{withFileTypes:!0});for(let H of G){if(!H.isDirectory())continue;let B=H.name;if(!p0(B)){Y.push(B);continue}let M=$O.join(X,B),b=$O.join(this.skillsDir,B);try{await s.access($O.join(M,"SKILL.md")),await s.rm(b,{recursive:!0,force:!0}),await s.cp(M,b,{recursive:!0}),IO.info(`Installed: ${B}`),J.push(B)}catch(I){IO.warn(`Failed to install ${B}`),Y.push(B)}}await s.rm(Z,{recursive:!0,force:!0})}catch(X){try{await s.rm(Z,{recursive:!0,force:!0})}catch{}IO.warn(`Failed to install skills: ${X instanceof Error?X.message:"Unknown error"}`)}return{installed:J,failed:Y}}}var u4=null;function y3(O){if(!u4)u4=new h3(O);return u4}var u0=OO("Service"),m3=aO.join(g3(),".blade","skills"),l4=aO.join(g3(),".blade","skills-config.json"),M6=z.Union([z.Object({source:z.Literal("catalog"),name:z.String({minLength:1,maxLength:64})}),z.Object({source:z.Literal("repo"),url:z.String({minLength:1,maxLength:4096}),name:z.Optional(z.String({minLength:1,maxLength:64}))}),z.Object({source:z.Literal("local"),path:z.String({minLength:1,maxLength:4096}),name:z.Optional(z.String({minLength:1,maxLength:64}))})]);function r1(O){try{return WO(O,"directory")}catch{throw new F("directory must reference a local workspace")}}async function v3(){try{let O=await R0.readFile(l4,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function L6(O){await R0.mkdir(aO.dirname(l4),{recursive:!0}),await R0.writeFile(l4,JSON.stringify(O,null,2))}async function A6(O,$){let Z=await v3();if($)Z.disabled=Z.disabled.filter((J)=>J!==O);else if(!Z.disabled.includes(O))Z.disabled.push(O);await L6(Z)}var C0=null,j6=300000,b6=6;async function T6(){if(C0&&Date.now()-C0.timestamp<j6)return C0.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(u0.warn(`GitHub API returned ${O.status}`),C0)return C0.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let Z=(await O.json()).filter((G)=>G.type==="dir"),J=Array(Z.length),Y=0,X=Math.min(b6,Z.length);return await Promise.all(Array.from({length:X},async()=>{while(Y<Z.length){let G=Y++,H=Z[G];if(!H)continue;let B=`Official ${H.name} skill`;try{let M=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${H.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(M.ok){let I=(await M.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(I)B=I[1].trim().slice(0,100)}}catch{}J[G]={name:H.name,description:B,tag:"Official",author:"Anthropic"}}})),C0={data:J,timestamp:Date.now()},J}catch(O){if(u0.warn("Failed to fetch skills catalog from GitHub:",O),C0)return C0.data;throw O}}var p3=()=>{let O=new D6;return O.get("/",async($)=>{try{let Z=r1($.get("directory")||KO()),Y=(await O0(Z)).skills.getAll(),X=await v3(),G=Y.map((H)=>({id:H.name,name:H.name,enabled:!X.disabled.includes(H.name),description:H.description||"",version:H.version||"1.0.0",provider:"Local",location:H.source==="builtin"?"Built-in":H.basePath,removable:H.source==="user"&&aO.dirname(aO.resolve(H.basePath))===aO.resolve(m3),capabilities:["prompts"],allowedTools:H.allowedTools||[]}));return $.json(G)}catch(Z){if(Z instanceof F)throw Z;return u0.error("[SkillsRoutes] Failed to get skills:",Z),$.json({error:Z instanceof Error?Z.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async($)=>{try{let Z=$.req.param("name"),J=await $.req.json();return await A6(Z,J.enabled),$.json({success:!0,enabled:J.enabled})}catch(Z){return u0.error("[SkillsRoutes] Failed to toggle skill:",Z),$.json({success:!1,error:Z.message},500)}}),O.delete("/:name",async($)=>{try{let Z=$.req.param("name"),J=r1($.get("directory")||KO());return x1(J,async(Y)=>{let X=Y.skills,G=X.get(Z);if(!G)return $.json({success:!1,error:"Skill not found"},404);let H=aO.resolve(G.basePath),B=aO.resolve(m3);if(G.source!=="user"||aO.dirname(H)!==B)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await R0.rm(H,{recursive:!0,force:!0}),await X.refresh(),B1(J),await N1(J),$.json({success:!0})})}catch(Z){if(Z instanceof F)throw Z;return u0.error("[SkillsRoutes] Failed to uninstall skill:",Z),$.json({success:!1,error:Z.message},500)}}),O.post("/install",async($)=>{try{let Z=h(M6,await $.req.json().catch(()=>null));if(!Z.success)throw new F("Invalid skill install request");let J=Z.data;if(J.name!==void 0&&!p0(J.name))throw new F("Invalid skill name");if(J.source==="repo"&&!d4(J.url))throw new F("Skill repositories must use HTTPS or SSH without embedded credentials");if(J.source==="local"&&(!J.path.trim()||J.path.includes("\x00")))throw new F("Invalid local skill path");let Y=J.name??(J.source==="repo"?c4(J.url):J.source==="local"?aO.basename(J.path):void 0);if(!p0(Y))throw new F("Invalid skill name");let X=y3(),G=r1($.get("directory")||KO());return x1(G,async(H)=>{let B=H.skills,M=!1;if(J.source==="catalog"&&J.name){if(M=await X.installOfficialSkill(J.name),!M)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(J.source==="repo"&&J.url){if(M=await X.installFromRepo(J.url,J.name),!M)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(J.source==="local"&&J.path){let b=r1(aO.resolve(J.path));if(M=await X.installFromLocal(b,J.name),!M)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 B.refresh(),B1(G),await N1(G),$.json({success:!0})})}catch(Z){if(Z instanceof F)throw Z;return u0.error("[SkillsRoutes] Failed to install skill:",Z),$.json({success:!1,error:Z.message},500)}}),O.get("/catalog",async($)=>{try{let Z=await T6();return $.json(Z)}catch(Z){return u0.error("[SkillsRoutes] Failed to get catalog:",Z),$.json({error:Z instanceof Error?Z.message:"Failed to get skills catalog"},502)}}),O};import{execSync as q6}from"node:child_process";import{readdir as I6,realpath as C6}from"node:fs/promises";import D0 from"node:path";import R6 from"fast-glob";import{Hono as E6}from"hono";var I1=OO("Service"),f6=(O)=>{try{return q6("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},S6=[...O1.map((O)=>`${O}/**`),...O1,...O1.map((O)=>`**/${O}/**`),...O1.map((O)=>`**/${O}`),...i4.map((O)=>`**/${O}`)],P6=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]);function e0(O){try{return WO(O,"directory")}catch($){throw new F($ instanceof Error?$.message:"directory is invalid")}}function u3(O,$){let Z=D0.relative(O,$);return Z===""||Z!==".."&&!Z.startsWith(`..${D0.sep}`)&&!D0.isAbsolute(Z)}async function d3(O){let $=D0.resolve(O),Z=[];while(!0)try{return D0.resolve(await C6($),...Z.reverse())}catch(J){let Y=J.code;if(Y!=="ENOENT"&&Y!=="ENOTDIR")throw J;let X=D0.dirname($);if(X===$)return D0.resolve(O);Z.push(D0.basename($)),$=X}}async function c3(O,$){let Z=D0.resolve(O,$);if(!u3(O,Z))return null;let J=await d3(O),Y=await d3(Z);if(!u3(J,Y))return null;try{e0(Y)}catch{return null}return Y}var n3=()=>{let O=new E6;return O.get("/commands",async($)=>{let Z=e0($.get("directory")||KO());try{let J=$.req.query("q")||"",Y=await O0(Z),X=i3(J,Z,Y).filter((G)=>!P6.has(G.command));return $.json(X)}catch(J){return I1.error("[SuggestionsRoutes] Failed to get command suggestions:",J),$.json([])}}),O.get("/files",async($)=>{let Z=e0($.get("directory")||KO());try{let J=$.req.query("q")||"",Y=Math.min(Number($.req.query("limit"))||100,1000),X=$.req.query("type")==="file",H=(await R6("**/*",{cwd:Z,dot:!1,followSymbolicLinks:!1,onlyFiles:X,markDirectories:!0,unique:!0,ignore:S6})).map((b)=>b.replace(/\\/g,"/"));if(!J)return $.json(H.slice(0,Y));let B=J.toLowerCase(),M=H.filter((b)=>b.toLowerCase().includes(B)).slice(0,Y);return $.json(M)}catch(J){return I1.error("[SuggestionsRoutes] Failed to get file suggestions:",J),$.json([])}}),O.get("/files/tree",async($)=>{let Z=e0($.get("directory")||KO());try{let J=$.req.query("path")||"",Y=await c3(Z,J);if(!Y)return $.json({error:"Invalid file path"},400);let G=(await I6(Y,{withFileTypes:!0})).map((M)=>({name:M.name,path:J?`${J}/${M.name}`:M.name,type:M.isDirectory()?"dir":"file"}));G.sort((M,b)=>{if(M.type!==b.type)return M.type==="dir"?-1:1;return M.name.localeCompare(b.name)});let H=new Set(O1),B=G.filter((M)=>{let b=M.name;if(b.startsWith("."))return!1;if(H.has(b))return!1;for(let I of i4)if(b.match(new RegExp(I.replace("*",".*"))))return!1;return!0});return $.json(B)}catch(J){return I1.error("[SuggestionsRoutes] Failed to get file tree:",J),$.json([])}}),O.get("/files/content",async($)=>{let Z=e0($.get("directory")||KO());try{let J=$.req.query("path");if(!J)return $.json({error:"Missing file path"},400);let Y=await c3(Z,J);if(!Y)return $.json({error:"Invalid file path"},400);let X=l3(),G=await X.stat(Y);if(!G?.isFile)return $.json({error:"File not found"},404);let H=200000,B=await X.readTextFile(Y),M=B.length>H;return $.json({path:J,content:M?B.slice(0,H):B,truncated:M,size:G.size})}catch(J){return I1.error("[SuggestionsRoutes] Failed to get file content:",J),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{let Z=e0($.get("directory")||KO());try{let J=f6(Z);return $.json({branch:J})}catch(J){return I1.error("[SuggestionsRoutes] Failed to get git info:",J),$.json({branch:null})}}),O};import{Hono as k6}from"hono";var $1=OO("Service"),r3=(O)=>{let $=new k6;return $.onError((Z,J)=>{if(Z instanceof wO)return J.json(Z.toObject(),Z.statusCode);return $1.error("[TaskRoutes] Unhandled route error:",Z),J.json(new zO("Failed to dispatch task").toObject(),500)}),$.post("/",async(Z)=>{let J;try{J=await Z.req.json()}catch{throw new F("Invalid request body")}let Y=h(o3,J);if(!Y.success)throw new F("Invalid task request");if((Y.data.attachments??[]).reduce((G,H)=>G+(typeof H.content==="string"?Buffer.byteLength(H.content):0),0)>a1)throw new F("Task attachments exceed the 5 MiB limit");if(Y.data.taskDueAt&&!Number.isFinite(Date.parse(Y.data.taskDueAt)))throw new F("Invalid task due date");try{let G=await O.dispatchTask({prompt:Y.data.prompt,title:Y.data.title,taskPriority:Y.data.taskPriority,taskKind:Y.data.taskKind,taskDueAt:Y.data.taskDueAt?new Date(Y.data.taskDueAt).toISOString():void 0,sourceProjectPath:Y.data.projectPath||Z.get("directory")||KO(),isolation:Y.data.isolation,permissionMode:Y.data.permissionMode,modelId:Y.data.modelId,reasoningEffort:Y.data.reasoningEffort,serviceTier:Y.data.serviceTier,responseVerbosity:Y.data.responseVerbosity,communicationStyle:Y.data.communicationStyle,attachments:Y.data.attachments,outputSchema:Y.data.outputSchema});return Z.json(a4.parse(G),202)}catch(G){if(G instanceof F||G instanceof v||G instanceof MO||G instanceof eO)throw G;throw $1.error("[TaskRoutes] Failed to dispatch task:",G),new zO("Failed to dispatch task")}}),$.patch("/:sessionId",async(Z)=>{let J;try{J=await Z.req.json()}catch{throw new F("Invalid request body")}let Y=h(t3,J);if(!Y.success)throw new F("Invalid task update");if(Y.data.title===void 0&&Y.data.taskPriority===void 0&&Y.data.taskKind===void 0&&Y.data.taskDueAt===void 0)throw new F("Task update must include at least one field");if(typeof Y.data.taskDueAt==="string"&&!Number.isFinite(Date.parse(Y.data.taskDueAt)))throw new F("Invalid task due date");try{let X=await O.updateTask(Z.req.param("sessionId"),{...Y.data,...typeof Y.data.taskDueAt==="string"?{taskDueAt:new Date(Y.data.taskDueAt).toISOString()}:{}},Z.req.query("projectPath"));return Z.json(n4.parse(X))}catch(X){if(X instanceof F||X instanceof c||X instanceof v)throw X;throw $1.error("[TaskRoutes] Failed to update task:",X),new zO("Failed to update task")}}),$.post("/:sessionId/retry",async(Z)=>{try{let J=await O.retryTask(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json(a4.parse(J),202)}catch(J){if(J instanceof F||J instanceof c||J instanceof v||J instanceof MO||J instanceof eO)throw J;throw $1.error("[TaskRoutes] Failed to retry task:",J),new zO("Failed to retry task")}}),$.get("/:sessionId/diff",async(Z)=>{try{let J=await O.getTaskDiff(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json(a3.parse(J))}catch(J){if(J instanceof F||J instanceof c||J instanceof v)throw J;throw $1.error("[TaskRoutes] Failed to load task diff:",J),new zO("Failed to load task diff")}}),$.post("/:sessionId/delivery",async(Z)=>{let J;try{J=await Z.req.json()}catch{throw new F("Invalid request body")}let Y=h(s3,J);if(!Y.success)throw new F("Invalid task delivery request");try{let X=await O.deliverTask(Z.req.param("sessionId"),Y.data.action,Z.req.query("projectPath"));return Z.json(n4.parse(X))}catch(X){if(X instanceof F||X instanceof c||X instanceof v)throw X;throw $1.error("[TaskRoutes] Failed to deliver task:",X),new zO("Failed to deliver task")}}),$};import{Hono as m6}from"hono";var h6=sO(z.Object({id:z.String(),name:z.String(),subagentType:z.String(),description:z.String(),agentId:z.Optional(z.String()),status:GO(["leader","running","completed","failed","cancelled","unknown"]),result:z.Optional(z.Unknown()),stats:z.Optional(z.Unknown()),worktreePath:z.Optional(z.String())})),y6=sO(z.Object({id:z.String(),subject:z.String(),description:z.String(),status:GO(["pending","blocked","running","completed"]),owner:z.Optional(z.String()),priority:GO(["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())})),XY=sO(z.Object({name:z.String(),description:z.Optional(z.String()),status:GO(["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(h6),tasks:z.Array(y6)})),e3=sO(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(GO(["high","medium","low"]))}),{maxItems:256}))})),O5=sO(z.Object({sessionId:z.String({minLength:1}),projectPath:z.String({minLength:1}),to:z.String({minLength:1}),message:z.String({minLength:1,maxLength:32768})})),$5=sO(z.Object({sessionId:z.String({minLength:1}),projectPath:z.String({minLength:1}),memberId:z.String({minLength:1})}));var g6=OO("Service"),Y5=()=>{let O=new m6;return O.onError(($,Z)=>{if($ instanceof wO)return Z.json($.toObject(),$.statusCode);return g6.error("[TeamRoutes] Unhandled route error:",$),Z.json(new zO("Team operation failed").toObject(),500)}),O.get("/",async($)=>{J1();let Z=await Q1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await Z1(Z.projectPath).list(Z))}),O.post("/",async($)=>{J1();let Z=h(e3,await o4($.req));if(!Z.success)throw new F("Invalid team request");let J=await Q1(Z.data.sessionId,Z.data.projectPath),Y=await g.findSessionMetadata(J.sessionId,J.projectPath);return $.json(await Z1(J.projectPath).create({name:Z.data.name,description:Z.data.description,leadAgentType:Z.data.leadAgentType,owner:J,modelId:Y?.selectedModelId,peerMessagingEnabled:Z.data.peerMessagingEnabled,members:Z.data.members,tasks:Z.data.tasks}),201)}),O.get("/:teamName",async($)=>{J1();let Z=await Q1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await Z1(Z.projectPath).getSnapshot($.req.param("teamName"),Z))}),O.post("/:teamName/messages",async($)=>{J1();let Z=h(O5,await o4($.req));if(!Z.success)throw new F("Invalid team message");let J=await Q1(Z.data.sessionId,Z.data.projectPath),Y=await Z1(J.projectPath).sendMessage({name:$.req.param("teamName"),to:Z.data.to,body:Z.data.message,owner:J});return $.json({messages:Y})}),O.post("/:teamName/tasks/claim",async($)=>{J1();let Z=h($5,await o4($.req));if(!Z.success)throw new F("Invalid team task claim");let J=await Q1(Z.data.sessionId,Z.data.projectPath);return $.json({task:await Z1(J.projectPath).claimTask($.req.param("teamName"),Z.data.memberId,J)})}),O.delete("/:teamName",async($)=>{J1();let Z=await Q1($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await Z1(Z.projectPath).delete($.req.param("teamName"),{owner:Z,killRunning:!0}))}),O};function Z1(O){return new Q5({configDir:n1(),subagentRegistry:J5(O)})}function J1(){if(Z5().config.config?.agentTeamsEnabled!==!0)throw new MO("Agent Teams are disabled")}async function Q1(O,$){if(!O||!$)throw new F("sessionId and absolute projectPath are required");let Z;try{Z=WO($)}catch{throw new F("sessionId and local projectPath are required")}if(!await g.findSessionMetadata(O,Z))throw new c(`Session not found: ${O}`);return{sessionId:O,projectPath:Z}}async function o4(O){try{return await O.json()}catch{throw new F("Invalid request body")}}import{Hono as v6}from"hono";var E0=OO("Service"),Y1=new Map,X5=2097152,V5=65536;function z5(){return typeof globalThis.Bun<"u"}function G5(O,$){return WO(O||$||KO(),"cwd")}async function p6(O,$,Z){if(z5()){let{spawn:X}=await import("bun-pty"),G=X(O,$,{name:"xterm-256color",cwd:Z.cwd,env:Z.env});return{pid:G.pid,write:(H)=>G.write(H),resize:(H,B)=>G.resize(H,B),kill:()=>G.kill(),onData:(H)=>G.onData(H),onExit:(H)=>G.onExit(H)}}let Y=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:Z.cwd,env:Z.env,cols:80,rows:24});return{pid:Y.pid,write:(X)=>Y.write(X),resize:(X,G)=>Y.resize(X,G),kill:()=>Y.kill(),onData:(X)=>{Y.onData(X)},onExit:(X)=>{Y.onExit(X)}}}var r4=void 0,s4;if(z5())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();s4=$.upgradeWebSocket,r4=$.websocket}catch(O){E0.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function K5(O,$){let Z=`term-${Date.now()}`;E0.info(`[Terminal] New connection: ${Z}, cwd: ${O}`);let J=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=J.endsWith("sh")?["-l"]:[],X=await p6(J,Y,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),G={id:Z,process:X,cwd:O,buffer:"",subscribers:new Set};if(Y1.set(Z,G),G.subscribers.add($),X.onData((H)=>{let B=!1;for(let M of G.subscribers)try{M.send(H),B=!0}catch{G.subscribers.delete(M)}if(B)return;if(G.buffer+=H,G.buffer.length>X5)G.buffer=G.buffer.slice(-X5)}),X.onExit(({exitCode:H})=>{E0.info(`[Terminal] Process exited: ${Z}, code: ${H}`);for(let B of G.subscribers)try{B.close()}catch{}Y1.delete(Z)}),G.buffer){let H=G.buffer;G.buffer="";for(let B=0;B<H.length;B+=V5)$.send(H.slice(B,B+V5))}return{session:G,cleanup:()=>{if(E0.info(`[Terminal] Connection closed: ${Z}`),G.subscribers.delete($),G.subscribers.size===0){try{G.process.kill()}catch{}Y1.delete(Z)}}}}function w5(O,$){O.on("connection",async(Z,J)=>{try{let Y=new URL(J.url||"/",`http://${J.headers.host}`);if(!Y.pathname.endsWith("/terminal/ws")){Z.close();return}let X=G5(Y.searchParams.get("cwd")??void 0,$()),{session:G,cleanup:H}=await K5(X,{send:(B)=>Z.send(B),close:()=>Z.close()});Z.on("message",(B)=>{try{G.process.write(String(B))}catch(M){E0.error("[Terminal] Failed to write to PTY:",M)}}),Z.on("close",H),Z.on("error",H)}catch(Y){E0.error("[Terminal] Failed to spawn PTY:",Y),Z.close()}})}var H5=()=>{let O=new v6;if(O.get("/status",($)=>{let Z=Array.from(Y1.values()).map((J)=>({id:J.id,cwd:J.cwd}));return $.json({active:Z.length,terminals:Z})}),O.post("/kill/:terminalId",($)=>{let Z=$.req.param("terminalId"),J=Y1.get(Z);if(J){try{J.process.kill()}catch{}for(let Y of J.subscribers)Y.close();return Y1.delete(Z),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),s4)O.get("/ws",async($,Z)=>{let J=$.req.query("cwd")??void 0,Y;try{Y=G5(J,$.get("directory"))}catch(H){let B=H instanceof Error?H.message:"cwd must reference a local workspace";return $.text(B,400)}let X;return s4(()=>{return{async onOpen(H,B){try{X=await K5(Y,{send:(M)=>B.send(M),close:()=>B.close()})}catch(M){E0.error("[Terminal] Failed to spawn PTY:",M),B.close()}},onMessage(H){if(!X)return;try{X.session.process.write(String(H.data))}catch(B){E0.error("[Terminal] Failed to write to PTY:",B)}},onClose(){X?.cleanup()}}})($,Z)});else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import{Hono as u6}from"hono";var d6=z.Object({projectPath:z.String({minLength:1}),action:GO(["trust","revoke"])});function W5(O){try{return WO(O)}catch{throw new F("projectPath must reference a local workspace")}}var F5=()=>{let O=new u6;return O.get("/",async($)=>{let Z=$.req.query("projectPath");if(!Z)throw new F("projectPath query parameter is required");let J=W5(Z);return $.json(await e4.getInstance().getStatus(J))}),O.post("/",async($)=>{let Z=h(d6,await $.req.json());if(!Z.success)throw new F("Invalid workspace trust request");let{action:J}=Z.data,Y=W5(Z.data.projectPath),X=e4.getInstance(),G=J==="trust"?await X.trust(Y):await X.revoke(Y);return await U5(),$.json({...G,reloadRequired:G.sensitiveSources>0})}),O};var fO=OO("Service"),J$=[],X1,A0,V1,F0,M0,L0,_5=new Map,N5=new Map,$8=new Set([".css",".html",".js",".json",".svg"]),Z8=1024,J8=3600000;class e1 extends Error{}function Q8(O){return O==="/sessions/v2"||O.startsWith("/sessions/v2/")}function Y8(O,$,Z){return new Promise((J,Y)=>{let X=[],G=0,H=()=>{O.off("data",B),O.off("end",M),O.off("error",b),$.removeEventListener("abort",I)},B=(f)=>{if(G+=f.byteLength,Z!==void 0&&G>Z){H(),O.resume(),Y(new e1);return}X.push(f)},M=()=>{H(),J(Buffer.concat(X,G))},b=(f)=>{H(),Y(f)},I=()=>{H(),Y($.reason)},A=O.headers["content-length"];if(Z!==void 0&&A!==void 0&&(!/^\d+$/.test(A)||Number(A)>Z)){O.resume(),Y(new e1);return}if(O.on("data",B),O.once("end",M),O.once("error",b),$.addEventListener("abort",I,{once:!0}),$.aborted)I()})}function X8(O,$){if(!O)return 0;let Z=O.split(",").map((J)=>{let[Y,...X]=J.trim().toLowerCase().split(";"),G=X.find((B)=>B.trim().startsWith("q=")),H=G?Number(G.trim().slice(2)):1;return{name:Y,quality:Number.isFinite(H)?Math.max(0,Math.min(1,H)):0}});return Z.find((J)=>J.name===$)?.quality??Z.find((J)=>J.name==="*")?.quality??0}function B5(){if(V1)return;let O=()=>{g.collectStaleEmptySessions().then(($)=>{if($>0)fO.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{fO.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),V1=setInterval(O,J8),V1.unref?.()}function x5(){if(!V1)return;clearInterval(V1),V1=void 0}function V8(O){return["br","gzip"].map((Z)=>({encoding:Z,quality:X8(O,Z)})).filter((Z)=>Z.quality>0).sort((Z,J)=>J.quality-Z.quality||(Z.encoding==="br"?-1:1))[0]?.encoding}function z8(O){let $=_5.get(O);if($)return $;let Z=C1(O);return _5.set(O,Z),Z}function G8(O,$,Z){let J=`${Z}:${O}`,Y=N5.get(J);if(Y)return Y;let X=Z==="br"?o6($,{params:{[s6.BROTLI_PARAM_QUALITY]:5}}):t6($,{level:6});return N5.set(J,X),X}function K8(){let O=i6(a6(import.meta.url)),$=[f0(O,"web"),f0(KO(),"dist/web"),f0(KO(),"packages/cli/dist/web")];for(let Z of $){let J=f0(Z,"index.html");if(Z$(J)){if(C1(J,"utf-8").includes("/assets/"))return fO.debug(`[Server] Found web dist at: ${Z}`),Z}}return null}function w8(){let O=new r6;O.onError((X,G)=>{if(fO.error("[Server] Request error:",X),X instanceof L5){let B=new eO(X.message,{resource:"workspace_agent_resources",limit:X.capacity});return G.json(B.toObject(),429)}if(X instanceof wO)return G.json(X.toObject(),X.statusCode);let H=X instanceof Error?X.message:String(X);return G.json({error:{code:"INTERNAL_ERROR",message:H}},500)}),O.use(async(X,G)=>{let H=process.env.BLADE_SERVER_PASSWORD;if(!H)return G();let B=X.req.path;if(B==="/"||B==="/favicon.svg"||B.startsWith("/assets/")||B.endsWith(".html")||B.endsWith(".js")||B.endsWith(".css"))return G();let M=X.req.header("Authorization");if(!M?.startsWith("Basic "))return X.header("WWW-Authenticate",'Basic realm="Blade Server"'),X.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let b=Buffer.from(M.slice(6),"base64").toString(),[I,A]=b.split(":"),f=process.env.BLADE_SERVER_USERNAME??"blade";if(I!==f||A!==H)return X.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return G()}),O.use(async(X,G)=>{let H=X.req.path==="/health"||X.req.path==="/global/health"||X.req.path.startsWith("/assets/");if(!H)fO.debug(`[Server] ${X.req.method} ${X.req.path}`);let B=Date.now();if(await G(),!H){let M=Date.now()-B;fO.debug(`[Server] ${X.req.method} ${X.req.path} - ${X.res.status} (${M}ms)`)}}),O.use(e6({origin(X){if(!X)return;if(X.startsWith("http://localhost:"))return X;if(X.startsWith("http://127.0.0.1:"))return X;if(X==="tauri://localhost"||X==="http://tauri.localhost")return X;if(J$.includes(X))return X;return}})),O.use(async(X,G)=>{let H=X.req.query("directory")||X.req.header("x-blade-directory")||KO();try{H=decodeURIComponent(H)}catch{}return X.set("directory",H),G()});let $,Z,J;try{$=a2(),Z=P3(),J=L$(),F0=$,M0=Z,L0=J,X1=$.recoverQueuedTasks,A0=new z4({dispatch:(X)=>$.dispatchTask(X),store:$$}),O.route("/global",j$()),O.route("/events",J.app),O.route("/sessions/v2",Z.app),O.route("/sessions",$.app),O.route("/tasks",r3($)),O.route("/teams",Y5()),O.route("/schedules",j3($$,A0)),O.route("/configs",U$()),O.route("/permissions",t2()),O.route("/plugins",w3()),O.route("/hooks",C$()),O.route("/workspace-trust",F5()),O.route("/providers",D3()),O.route("/models",m$()),O.route("/projects",F3()),O.route("/suggestions",n3()),O.route("/terminal",H5()),O.route("/mcp",f$()),O.route("/skills",p3())}catch(X){throw A5($,Z,J,"server-startup-failure").catch((G)=>{fO.error("[Server] Failed to clean up route controllers:",G)}),F0=void 0,M0=void 0,L0=void 0,X1=void 0,A0=void 0,X}O.get("/health",(X)=>{return X.json({healthy:!0,version:i0()})});let Y=K8();if(Y)fO.info(`[Server] Serving static files from ${Y}`),O.get("/favicon.svg",()=>{let X=f0(Y,"favicon.svg");if(!Z$(X))return new Response(null,{status:404});return new Response(C1(X),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(X)=>{let G=f0(Y,X.req.path);if(!Z$(G))return X.json({error:{code:"NOT_FOUND",message:`File not found: ${X.req.path}`}},404);let H=z8(G),B=n6(G).toLowerCase(),b={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[B]||"application/octet-stream",I=$8.has(B)&&H.byteLength>=Z8?V8(X.req.header("Accept-Encoding")):void 0,A=I?G8(G,H,I):H;return new Response(new Uint8Array(A),{headers:{"Content-Type":b,"Content-Length":String(A.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...I?{"Content-Encoding":I}:{}}})}),O.get("/",(X)=>{let G=f0(Y,"index.html"),H=C1(G,"utf-8");return X.html(H,200,{"Cache-Control":"no-cache"})}),O.get("*",(X)=>{let G=X.req.path;if(G.includes("."))return X.json({error:{code:"NOT_FOUND",message:`File not found: ${G}`}},404);let H=f0(Y,"index.html"),B=C1(H,"utf-8");return X.html(B,200,{"Cache-Control":"no-cache"})});else fO.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(X)=>{return X.json({message:"Blade API Server",version:i0(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),O.all("*",(X)=>{return X.json({error:{code:"NOT_FOUND",message:`Route not found: ${X.req.path}`}},404)});return O}async function A5(O,$,Z,J){let Y=[],X;for(let B of[O,$,Z])try{Y.push(B?.shutdown(J)??Promise.resolve())}catch(M){X??=M}let H=(await Promise.allSettled(Y)).find((B)=>B.status==="rejected");if(X!==void 0)throw X;if(H)throw H.reason}function H8(){let O=l6(),$=[];for(let Z of Object.keys(O)){let J=O[Z];if(!J)continue;for(let Y of J){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;$.push(Y.address)}}return $}function D5(){return typeof globalThis.Bun<"u"}function M5(O,$){let Z=globalThis.Bun,J=(X)=>{try{return Z.serve({hostname:$.hostname,port:X,fetch:O.fetch,idleTimeout:0,websocket:r4})}catch(G){fO.error("Failed to start Bun server:",G);return}},Y=$.port===0?J(4096)??J(0):J($.port);if(!Y)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Y.url,port:Y.port,hostname:Y.hostname,stop:async()=>{Y.stop(!0)}}}function W8(O,$){return new Promise((Z,J)=>{let Y=c6(async(M,b)=>{let I=new AbortController,A=()=>{if(!I.signal.aborted)I.abort("client-disconnected")},f=()=>A(),L=()=>{if(!b.writableEnded)A()};if(M.once("aborted",f),b.once("close",L),M.aborted||b.destroyed)A();try{let R=new URL(M.url||"/",`http://${M.headers.host}`),P=new Headers;for(let[p,UO]of Object.entries(M.headers))if(UO)if(Array.isArray(UO))for(let y of UO)P.append(p,y);else P.set(p,UO);let k;if(M.method!=="GET"&&M.method!=="HEAD")k=(await Y8(M,I.signal,Q8(R.pathname)?t1:void 0)).toString();let _=new Request(R.toString(),{method:M.method,headers:P,body:k,signal:I.signal}),e=await O.fetch(_);if(b.statusCode=e.status,e.headers.forEach((p,UO)=>{b.setHeader(UO,p)}),e.body){let p=e.body.getReader(),UO=async()=>{let{done:y,value:SO}=await p.read();if(y){b.end();return}return b.write(SO),UO()};await UO()}else{let p=await e.text();b.end(p)}}catch(R){if(I.signal.aborted)return;if(R instanceof e1){b.statusCode=400,b.setHeader("content-type","application/json; charset=UTF-8"),b.setHeader("connection","close"),b.end(JSON.stringify({error:{code:"invalid_session_surface_request",message:"Session surface request is invalid",retryable:!1}}));return}fO.error("[Server] Node request error:",R),b.statusCode=500,b.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}finally{M.off("aborted",f),b.off("close",L)}}),X=new O8({noServer:!0}),G=KO();w5(X,()=>G),Y.on("upgrade",(M,b,I)=>{let A;try{A=new URL(M.url||"/",`http://${M.headers.host}`)}catch{b.end(`HTTP/1.1 400 Bad Request\r
|
|
9
|
+
Connection: close\r
|
|
10
|
+
\r
|
|
11
|
+
`);return}if(A.pathname==="/terminal/ws"){try{WO(A.searchParams.get("cwd")||G,"cwd")}catch{b.end(`HTTP/1.1 400 Bad Request\r
|
|
12
|
+
Connection: close\r
|
|
13
|
+
\r
|
|
14
|
+
`);return}X.handleUpgrade(M,b,I,(f)=>{X.emit("connection",f,M)})}else b.destroy()});let H=(M)=>{return new Promise((b,I)=>{Y.once("error",(A)=>{if(A.code==="EADDRINUSE")I(A);else I(A)}),Y.listen(M,$.hostname,()=>{let A=Y.address();if(A&&typeof A==="object")b(A.port);else b(M)})})};(async()=>{let M;if($.port===0)try{M=await H(4096)}catch{M=await H(0)}else M=await H($.port);let b=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${M}`);Z({url:b,port:M,hostname:$.hostname,stop:async()=>{return new Promise((I)=>{X.close(()=>{Y.close(()=>I())})})}})})().catch(J)})}var j5;((FX)=>{let O,$,Z,J=async(A,f,L,R)=>{let P=[],k=A0,_=[];if($=void 0,F0===A)F0=void 0;if(M0===f)M0=void 0;if(L0===L)L0=void 0;if(X1=void 0,A0=void 0,R&&O===R)O=void 0,Z=void 0;try{_.push(A5(A,f,L,"server-startup-failure"))}catch(p){P.push(p)}try{k?.stop()}catch(p){P.push(p)}try{x5()}catch(p){P.push(p)}try{O$()}catch(p){P.push(p)}if(R)try{_.push(R.stop())}catch(p){P.push(p)}let e=await Promise.allSettled(_);for(let p of e)if(p.status==="rejected")P.push(p.reason);for(let p of P)fO.error("[Server] Startup cleanup failed:",p)},Y=(A,f,L,R)=>{if(O!==A)return Promise.resolve();if(Z)return Z;let P,k,_,e,p,UO,y,SO;try{UO=f?.shutdown("server-shutdown")}catch(YO){P=YO}try{y=L?.shutdown("server-shutdown")}catch(YO){k=YO}try{SO=R?.shutdown("server-shutdown")}catch(YO){_=YO}try{A0?.stop()}catch(YO){e=YO}try{x5()}catch(YO){p=YO}return Z=(async()=>{let YO=Promise.resolve().then(()=>A.stop()),[u,a,FO,CO]=await Promise.allSettled([UO??Promise.resolve(),y??Promise.resolve(),SO??Promise.resolve(),YO]),PO;try{O$()}catch(rO){PO=rO}let J0=[P,u.status==="rejected"?u.reason:void 0,k,a.status==="rejected"?a.reason:void 0,_,FO.status==="rejected"?FO.reason:void 0,e,p,CO.status==="rejected"?CO.reason:void 0,PO].find((rO)=>rO!==void 0);if(J0!==void 0){if(O===A)Z=void 0;throw J0}if(O===A){if(O=void 0,$=void 0,F0===f)F0=void 0;if(M0===L)M0=void 0;if(L0===R)L0=void 0;X1=void 0,A0=void 0}fO.info("[Server] Blade server stopped")})(),Z};function X(){if(!$)$=w8();return $}FX.getApp=X;function G(A){J$=A.cors??[];let f=X(),L=F0,R=M0,P=L0,k;try{if(D5())k=M5(f,A),O=k,Z=void 0,fO.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");X1?.().catch((_)=>{fO.warn("[Server] Failed to recover queued tasks:",_)}),A0?.start(),B5()}catch(_){throw J(L,R,P,k),_}if(!k)throw Error("Server transport failed to initialize");return{url:k.url,port:k.port,hostname:k.hostname,stop:()=>Y(k,L,R,P)}}FX.listen=G;async function H(A){J$=A.cors??[];let f=X(),L=F0,R=M0,P=L0,k;try{if(D5())k=M5(f,A),O=k,fO.info(`[Server] Blade server listening on ${k.url} (Bun runtime)`);else k=await W8(f,A),O=k,fO.info(`[Server] Blade server listening on ${k.url} (Node.js runtime)`);Z=void 0;try{await X1?.()}catch(_){fO.warn("[Server] Failed to recover queued tasks:",_)}A0?.start(),B5()}catch(_){throw await J(L,R,P,k),_}if(!k)throw Error("Server transport failed to initialize");return{url:k.url,port:k.port,hostname:k.hostname,stop:()=>Y(k,L,R,P)}}FX.listenAsync=H;function B(){return O!==void 0}FX.isRunning=B;function M(){return F0?.getCoordinationStats()}FX.getSessionCoordinationStatsForTests=M;function b(){return M0?.getStats()}FX.getSessionSurfaceStatsForTests=b;function I(){return{global:L0?.getSseConnectionStats(),session:F0?.getSseConnectionStats()}}FX.getSseConnectionStatsForTests=I})(j5||={});export{F8 as a,_8 as b,H8 as c,j5 as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var I=600000,r=30000,t=3600000,o=12,O=15000,P=60000;function R(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=30000&&_<=3600000}var C=1e4,M=1000,p=300000;function E(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=300000}var T=1,s=16,n=Number.MAX_SAFE_INTEGER,D=180000,m=1000,x=600000,S=134217728,U=65536,V=134217728;function A(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=16}function w(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=n}function z(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=600000}function F(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=65536&&_<=134217728}
|
|
2
|
-
export{I as
|
|
2
|
+
export{I as Zi,r as _i,t as $i,o as aj,O as bj,P as cj,R as dj,C as ej,M as fj,p as gj,E as hj,T as ij,s as jj,n as kj,D as lj,m as mj,x as nj,S as oj,U as pj,V as qj,A as rj,w as sj,z as tj,F as uj};
|