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