blade-code 0.10.108 → 0.10.109
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-bp7bn0ka.js → chunk-18metkce.js} +1 -1
- package/dist/{chunk-0734ktp4.js → chunk-21z1cm7p.js} +1 -1
- package/dist/{chunk-6z2g9bhy.js → chunk-2cdys9m5.js} +1 -1
- package/dist/{chunk-408wmns7.js → chunk-2jhj3462.js} +1 -1
- package/dist/{chunk-j4n443dn.js → chunk-5yvqbshs.js} +1 -1
- package/dist/{chunk-fb44m8vk.js → chunk-7wnx6fq5.js} +1 -1
- package/dist/{chunk-ph338zx1.js → chunk-88rbkzqr.js} +1 -1
- package/dist/{chunk-70srdp2m.js → chunk-9metwvwb.js} +1 -1
- package/dist/chunk-9xa0mdxg.js +1 -0
- package/dist/{chunk-c7r5s02f.js → chunk-aydxzp31.js} +1 -1
- package/dist/chunk-cdtwwc9v.js +1 -0
- package/dist/{chunk-bycxhv2r.js → chunk-dx95g6sa.js} +1 -1
- package/dist/{chunk-5bsn3bsh.js → chunk-dzsjjhqy.js} +1 -1
- package/dist/{chunk-vk01pnqk.js → chunk-e2mcqkgv.js} +1 -1
- package/dist/{chunk-jm794j70.js → chunk-f8f96dca.js} +1 -1
- package/dist/{chunk-37j8v3pq.js → chunk-gbbtksvv.js} +1 -1
- package/dist/{chunk-zgnsc2f8.js → chunk-gc3qqxhf.js} +1 -1
- package/dist/{chunk-jdjaqhby.js → chunk-hwzwjfvc.js} +1 -1
- package/dist/{chunk-cv3yxy1k.js → chunk-jdx7c2pd.js} +1 -1
- package/dist/{chunk-wxq8kypj.js → chunk-jvedgz9x.js} +1 -1
- package/dist/{chunk-dvsmvk1j.js → chunk-k359hejz.js} +1 -1
- package/dist/chunk-kckkqtyj.js +8 -0
- package/dist/{chunk-4k2c1g73.js → chunk-kdrn84pk.js} +1 -1
- package/dist/{chunk-8crjkt55.js → chunk-m3w413zt.js} +3 -3
- package/dist/{chunk-9q4dvzc0.js → chunk-m8k3j75k.js} +1 -1
- package/dist/{chunk-jqtspa26.js → chunk-mvr12g3x.js} +1 -1
- package/dist/{chunk-83rn6ezc.js → chunk-nehwxpq2.js} +1 -1
- package/dist/{chunk-8xcrjnrp.js → chunk-nshgwxk5.js} +1 -1
- package/dist/{chunk-543180gh.js → chunk-pa8pkt00.js} +1 -1
- package/dist/{chunk-f3x4w3fc.js → chunk-q0x3jwz1.js} +1 -1
- package/dist/{chunk-5ar697sg.js → chunk-qxa90mwt.js} +1 -1
- package/dist/{chunk-5sbzjxm5.js → chunk-rqmaqthv.js} +1 -1
- package/dist/{chunk-a8ak0gkr.js → chunk-ta43te9m.js} +1 -1
- package/dist/{chunk-nswm0qtm.js → chunk-y5fet3r6.js} +1 -1
- package/dist/{chunk-asp9yz7j.js → chunk-ynjqrans.js} +2 -2
- package/dist/{chunk-se1af4zj.js → chunk-z38a3vvk.js} +1 -1
- package/dist/{chunk-za7zs9fq.js → chunk-zjgfvqjk.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-50xeb1cz.js +0 -1
- package/dist/chunk-nk0egcxh.js +0 -1
- package/dist/chunk-xbpzq84r.js +0 -8
package/dist/chunk-xbpzq84r.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{e as s4,f as r4}from"./chunk-3pwq56je.js";import{g as G1}from"./chunk-xv3a1se1.js";import{s as V0,t as j4,u as S4,v as M4,w as T4}from"./chunk-za7zs9fq.js";import{x as x0}from"./chunk-j4n443dn.js";import{A as Bx,B as Ux,C as X0,D as Kx,y as _4,z as Vx}from"./chunk-dvsmvk1j.js";import{$ as v0,G as N4,H as ux,I as W$,L as W4,M as L0,N as c1,O as J1,P as yx,Q as y1,R as z4,S as mO,T as G4,U as V4,V as B4,W as P1,X as dO,Y as O0,aa as l0,ba as A$,ca as U4,da as K4,ea as P4,fa as m4,ga as h4,ha as g4,ia as u4,ja as p4,ka as d4,la as v4,ma as l4,pa as t4,sa as k$,xa as X$}from"./chunk-8crjkt55.js";import{Ea as Tx,Ka as HO}from"./chunk-bycxhv2r.js";import{$a as x$,Oa as D1,Ra as G$,Sa as a1,Ta as F4,Ua as L4,Va as V$,Wa as B$,Xa as o1,Ya as U$,Za as w0,_a as O$,ab as $$,bb as D4,cb as H4,db as b4,eb as A4,fb as Xx,gb as Ox}from"./chunk-23v8c9b8.js";import{Gb as f1,Pb as $0,rb as lO,sb as P,ub as I,vb as X4}from"./chunk-fb44m8vk.js";import{_b as g1}from"./chunk-cnhw5mqv.js";import{Ac as ex,Bc as I1,Cc as O4,Dc as y0,Ec as x4,Fd as Z4,Gd as J4,Hc as S1,Id as K0,Ld as C1,Qd as Y4,Rd as k1,Sd as E1,Td as C,Uc as $4,dd as w4,nd as N1,od as U0,tc as rx,vd as p0,wd as u1,xd as d0,zd as Q4}from"./chunk-zgnsc2f8.js";import{Pe as H$,Te as WO,Xe as Cx,cf as TO}from"./chunk-vk01pnqk.js";import{df as q1}from"./chunk-pshyn3yy.js";import{uf as tx}from"./chunk-hv6hrsnk.js";import{wf as Q1}from"./chunk-83rn6ezc.js";import{Ef as b$,Gf as Z$,Jf as y4,Nf as k0,Of as E0,Sf as g$,Vf as kO,Wf as f0,Zf as u$}from"./chunk-8xcrjnrp.js";import{ng as kx,og as sx}from"./chunk-9g64g1np.js";import{sg as Ax,tg as G0}from"./chunk-jqtspa26.js";import{Ah as C0,Lg as Mx,dh as ax,gh as ox,ih as nx,vh as jx}from"./chunk-408wmns7.js";import{Dh as T1}from"./chunk-4w4wjm49.js";import{Eh as f,Gh as W,Hh as EO,Jh as OO}from"./chunk-6k5k40p8.js";import{Lh as X1,Oh as R1}from"./chunk-p3m1jyg5.js";import{Sh as a}from"./chunk-ecd727xh.js";import{si as t}from"./chunk-dvv28pkc.js";import{yi as rO}from"./chunk-dgf2xzzd.js";import{Ai as qx,Bi as ix,Di as Ix,Ei as cx}from"./chunk-z52s82k7.js";import{Gi as z0}from"./chunk-jdjaqhby.js";import{Ni as e1}from"./chunk-vbwvsgs1.js";import{Ti as x1,Xi as Fx,Yi as W1}from"./chunk-rkdxqx8m.js";import{_i as t1}from"./chunk-tf7ezqew.js";var O3={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 x3(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as xx,readFileSync as a0}from"node:fs";import{createServer as I2}from"node:http";import{networkInterfaces as C2}from"node:os";import{dirname as k2,extname as E2,join as tO}from"node:path";import{fileURLToPath as f2}from"node:url";import{brotliCompressSync as y2,gzipSync as P2,constants as m2}from"node:zlib";import{Hono as h2}from"hono";import{cors as g2}from"hono/cors";import{WebSocketServer as u2}from"ws";var W0=t("Service"),i$=30000,c$=new Set(["completed","failed","cancelled","interrupted"]);class H1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??Xx.getInstance(),this.tickMs=O.tickMs??i$}start(){if(this.timer)return;W0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=I.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!c$.has(x))return;this.recordTerminalStatus(O.sessionId,x,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,W0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){W0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),W0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let w=x.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??a$(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}),Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:D1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),I.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:w,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),W0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);W0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let N=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:D1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastStatus:"error",lastError:Y,nextRunAt:N?N.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Q=(await this.store.list()).find((Y)=>Y.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function a$(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class e extends Error{code;statusCode;details;constructor(O,x,$=500,w){super(x);this.code=O;this.statusCode=$;this.details=w;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class h extends e{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class F extends e{constructor(O){super("BAD_REQUEST",O,400)}}class E extends e{constructor(O){super("CONFLICT",O,409)}}class hO extends e{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class gO extends e{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class e0 extends e{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class MO extends e{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class s extends e{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var W3=W.Object({error:W.Object({code:W.String(),message:W.String(),details:W.Optional(W.Record(W.String(),W.Unknown()))})});import{Hono as o$}from"hono";var b1=t("Service"),n$=W.Object({updates:W.Record(W.String(),W.Any()),options:W.Optional(W.Object({scope:W.Optional(OO(["local","project","global"])),immediate:W.Optional(W.Boolean())}))});function t$(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}}var zx=()=>{let O=new o$;return O.get("/",async(x)=>{try{let $=WO();return x.json($?t$($):{})}catch($){return b1.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),w=f(n$,$);if(!w.success)throw new F("Invalid config update format");let{updates:Q,options:Y}=w.data;return await TO().updateConfig(Q,Y),x.json({success:!0,updates:Q})}catch($){throw b1.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=WO();return x.json($?.permissions||{})}catch($){return b1.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as s$}from"hono";import{streamSSE as r$}from"hono/streaming";function Gx(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
|
|
2
|
-
`;if(O.event!==void 0)x+=`event: ${O.event}
|
|
3
|
-
`;for(let $ of O.data.split(/\r\n|\r|\n/))x+=`data: ${$}
|
|
4
|
-
`;if(O.retry!==void 0)x+=`retry: ${O.retry}
|
|
5
|
-
`;return x+=`
|
|
6
|
-
`,Buffer.byteLength(x)}class q0{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??Vx,this.maxPendingBytes=O.maxPendingBytes??Bx,this.serial=new Kx({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??Ux,sizeOf:Gx,write:O.write,onFailure:(x)=>{this.failure=x,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,O.onFailure?.(x)}})}async writeInitial(O){await this.offerDirect(O)}observe(O,x){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer(O,x);return}this.offerLive(O,x)}async writeReplay(O,x){if(!Number.isSafeInteger(x)||x<=0)throw this.fail(new X0("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if(x<=this.highestReplaySequence)return;await this.offerDirect(O),this.highestReplaySequence=x,this.highestDeliveredSequence=x}finishInitialization(O){if(this.phase!=="buffering")return;let x=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let $=O.replayed?x.filter((Q)=>Q.sequence!==void 0&&Q.sequence>this.highestReplaySequence).sort((Q,Y)=>Q.sequence-Y.sequence||Q.order-Y.order):x.sort((Q,Y)=>Q.order-Y.order),w;for(let Q of $){if(O.replayed&&Q.sequence!==void 0&&Q.sequence===w)continue;if(this.offerLive(Q.message,Q.sequence),this.serial.stats().closed)return;w=Q.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,x){let $=Gx(O),w=this.serial.stats();if($>this.maxPendingBytes){this.fail(new X0("oversized",`SSE frame requires ${$} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:w.pendingItems+this.buffered.length,pendingBytes:w.pendingBytes+this.bufferedBytes}));return}if(w.pendingItems+this.buffered.length>=this.maxPendingItems||w.pendingBytes+this.bufferedBytes+$>this.maxPendingBytes){this.fail(new X0("overflow","SSE initialization buffer limit exceeded",{pendingItems:w.pendingItems+this.buffered.length,pendingBytes:w.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:$,sequence:x,order:this.nextOrder}),this.bufferedBytes+=$}offerLive(O,x){if(x!==void 0){if(x<=this.highestReplaySequence)return;if(x<=this.highestDeliveredSequence){this.fail(new X0("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=x}if(!this.serial.offer(O).accepted)this.phase="closed"}async offerDirect(O){if(this.phase==="closed")throw this.currentFailure();let x=this.serial.offer(O);if(!x.accepted)throw this.phase="closed",x.error;await x.completion}fail(O){this.serial.close(O)}currentFailure(){return this.failure??new X0("closed","SSE egress is closed")}}var e$=15000,Ow=t("Service"),xw=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),$w=new Set(["queued","running","completed","failed","cancelled","interrupted"]),ww=new Set(["high","medium","low"]),Qw=new Set(["feature","bug","maintenance","research"]);function Zw(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let x=O,$=["changedFiles","additions","deletions","commits"];if($.some((w)=>typeof x[w]!=="number"||!Number.isInteger(x[w])||x[w]<0))return;return Object.fromEntries($.map((w)=>[w,x[w]]))}function I0(O,x){return typeof O==="number"&&Number.isInteger(O)&&O>=x?O:void 0}function Jw(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let x=O;if(!["applied","discarded","conflicted"].includes(String(x.status))||typeof x.updatedAt!=="string")return;return{status:x.status,updatedAt:x.updatedAt,...typeof x.sourceCommit==="string"?{sourceCommit:x.sourceCommit}:{},...I0(x.changedFiles,0)!==void 0?{changedFiles:x.changedFiles}:{},...typeof x.message==="string"?{message:x.message}:{}}}var _x=()=>{let O=new s$;return O.get("/",(x)=>r$(x,async($)=>{let w,Q,Y=!1,N,K,S=new Promise((U)=>{K=U}),B=()=>{if(Q!==void 0)clearInterval(Q),Q=void 0;w?.(),w=void 0},j=(U)=>{if(Y)return;Y=!0,B(),N?.close(U),K()};$.onAbort(j),N=new q0({write:async(U)=>{await $.writeSSE(U)},onFailure:(U)=>{Ow.warn(`[EventRoutes] SSE egress closed: kind=${U.kind} pendingItems=${U.pendingItems??0} pendingBytes=${U.pendingBytes??0}`),j(U)}});let b=(U,R)=>{N?.observe({data:JSON.stringify({type:U,properties:R})})};w=I.subscribe((U)=>{if(!xw.has(U.type))return;if(U.type==="permission.asked"||U.type==="question.required"||U.type==="elicitation.required"){let T=U.properties.requestId;if(typeof T!=="string"||!T)return;b("interaction.pending",{sessionId:U.sessionId,projectPath:U.projectPath,interactionType:U.type==="question.required"?"question":U.type==="elicitation.required"?"elicitation":"permission",requestId:T});return}if(U.type==="interaction.resolved"){let T=U.properties.requestId;if(typeof T!=="string"||!T)return;b(U.type,{sessionId:U.sessionId,projectPath:U.projectPath,requestId:T});return}if(U.type==="session.created"||U.type==="session.deleted"){b(U.type,{sessionId:U.sessionId,projectPath:U.projectPath});return}if(U.type==="session.updated"){let T=U.properties.title,jO=U.properties.taskPriority,i=U.properties.taskKind,XO=U.properties.taskDueAt,UO=typeof T==="string"&&Boolean(T.trim()),SO=ww.has(String(jO)),RO=Qw.has(String(i)),v=XO===null||typeof XO==="string"&&Number.isFinite(Date.parse(XO));if(!UO&&!SO&&!RO&&!v)return;b(U.type,{sessionId:U.sessionId,projectPath:U.projectPath,...UO?{title:T}:{},...SO?{taskPriority:jO}:{},...RO?{taskKind:i}:{},...v?{taskDueAt:XO}:{}});return}if(U.type==="task.delivery"){let T=Jw(U.properties.taskDelivery);if(!T)return;b(U.type,{sessionId:U.sessionId,projectPath:U.projectPath,taskDelivery:T,...U.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof U.properties.updatedAt==="string"?{updatedAt:U.properties.updatedAt}:{}});return}if(U.type==="schedule.fired"){let T=U.properties.scheduleId,jO=U.properties.firedAt;if(typeof T!=="string"||typeof jO!=="string")return;b(U.type,{scheduleId:T,firedAt:jO,sessionId:U.sessionId,projectPath:U.projectPath,...typeof U.properties.runId==="string"?{runId:U.properties.runId}:{},...typeof U.properties.status==="string"?{status:U.properties.status}:{}});return}let R=U.properties.taskStatus;if(typeof R!=="string"||!$w.has(R))return;let JO=Zw(U.properties.taskDiffStat),y=I0(U.properties.taskQueuePosition,1),r=I0(U.properties.taskQueueDepth,0),ZO=I0(U.properties.taskConcurrencyLimit,1),GO=I0(U.properties.taskInFlight,0),YO=typeof U.properties.taskAdmissionPaused==="boolean"?U.properties.taskAdmissionPaused:void 0;b(U.type,{sessionId:U.sessionId,projectPath:U.projectPath,taskStatus:R,...typeof U.properties.taskStatusReason==="string"?{taskStatusReason:U.properties.taskStatusReason}:{},...U.properties.taskFailure&&typeof U.properties.taskFailure==="object"?{taskFailure:U.properties.taskFailure}:{},...typeof U.properties.taskStartedAt==="string"?{taskStartedAt:U.properties.taskStartedAt}:{},...typeof U.properties.taskCompletedAt==="string"?{taskCompletedAt:U.properties.taskCompletedAt}:{},...typeof U.properties.updatedAt==="string"?{updatedAt:U.properties.updatedAt}:{},...JO?{taskDiffStat:JO}:{},...y!==void 0?{taskQueuePosition:y}:{},...r!==void 0?{taskQueueDepth:r}:{},...ZO!==void 0?{taskConcurrencyLimit:ZO}:{},...GO!==void 0?{taskInFlight:GO}:{},...YO!==void 0?{taskAdmissionPaused:YO}:{}})});try{if($.aborted||Y)return;if(await N.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),$.aborted||Y)return;if(N.finishInitialization({replayed:!1}),$.aborted||Y)return;Q=setInterval(()=>{if($.aborted||Y)return;N?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},e$),await S}finally{j()}})),O};import{Hono as Yw}from"hono";var Nw=W.Object({paused:W.Boolean()}),Lx=()=>{let O=new Yw;return O.get("/health",(x)=>{return x.json({healthy:!0,version:z0()})}),O.get("/info",(x)=>{let $=a(),w=WO();if(w)dO.configure(w.maxConcurrentTasks,w.maxQueuedTasks,w.maxQueuedTaskBytes);let Q=dO.getStats();return x.json({version:z0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:$,gitBranch:Fx($),taskAdmission:{inFlight:Q.inFlight,queued:Q.queued,maxConcurrent:Q.maxConcurrent,maxQueued:Q.maxQueued,paused:Q.paused}})}),O.put("/task-admission",async(x)=>{let $;try{$=await x.req.json()}catch{throw new F("Invalid request body")}let w=f(Nw,$);if(!w.success)throw new F("Invalid task admission control request");dO.setPaused(w.data.paused);let Q=dO.getStats();return x.json({inFlight:Q.inFlight,queued:Q.queued,maxConcurrent:Q.maxConcurrent,maxQueued:Q.maxQueued,paused:Q.paused})}),O};import Dx from"node:path";import{Hono as Ww}from"hono";var Xw=W.Object({projectPath:W.String({minLength:1}),action:OO(["trust","revoke"]),expectedDigest:W.Optional(W.String())}),zw=W.Object({projectPath:W.String({minLength:1}),sessionId:W.String({minLength:1}),enabled:W.Boolean()});function A1(O){if(!O||!Dx.isAbsolute(O))throw new F("projectPath must be absolute");return Dx.resolve(O)}function Hx(O){if(!O)throw new F("sessionId is required");try{x1(O)}catch(x){throw new F(x instanceof Error?x.message:"sessionId is invalid")}return O}async function O1(O){let x=A1(O),$=WO()?.hooks??jx.hooks,w=await C0.getInstance().loadWorkspaceHooks(x,$,{includeBaseForCurrentWorkspace:!1});return f0(x,async()=>{E0(x);let Q=G0.getInstance();return Q.loadConfig(w,x),await k0(x),Q.getConfig(x)})}function bx(O,x){let $=G0.getInstance(),w=$.getConfig(x).enabled,Q=$.isSessionPaused(O,x);return{sessionId:O,projectPath:x,enabled:$.isSessionEnabled(O,x),paused:Q,configEnabled:w}}var Sx=()=>{let O=new Ww;return O.get("/trust",async(x)=>{let $=x.req.query("projectPath");if(!$)throw new F("projectPath query parameter is required");return await O1($),x.json(await G0.getInstance().getTrustStatus($))}),O.post("/trust",async(x)=>{let $=f(Xw,await x.req.json());if(!$.success)throw new F("Invalid hook trust request");let{projectPath:w,action:Q,expectedDigest:Y}=$.data;await O1(w);let N=G0.getInstance(),K;try{K=Q==="trust"?await N.trustProject(w,Y):await N.revokeProjectTrust(w)}catch(S){if(S instanceof Ax)throw new E(S.message);throw S}return x.json(K)}),O.get("/session",async(x)=>{let $=A1(x.req.query("projectPath")),w=Hx(x.req.query("sessionId"));return await O1($),x.json(bx(w,$))}),O.post("/session",async(x)=>{let $=f(zw,await x.req.json());if(!$.success)throw new F("Invalid hook session request");let w=A1($.data.projectPath),Q=Hx($.data.sessionId);await O1(w);let Y=G0.getInstance();if($.data.enabled)Y.enableSession(Q,w);else Y.disableSession(Q,w);return x.json(bx(Q,w))}),O};import{Hono as Gw}from"hono";var PO=t("Service");function Vw(O){try{return Tx(O)}catch{return[]}}function Bw(O){if(!$1(O)||!$1(O.reference)||!$1(O.argument))throw Error("Invalid MCP completion request");let x=O.reference.type,$=x==="prompt"&&typeof O.reference.name==="string"?{type:"prompt",name:O.reference.name}:x==="resource"&&typeof O.reference.uri==="string"?{type:"resource",uri:O.reference.uri}:void 0;if(!$||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let w;if(O.context!==void 0){if(!$1(O.context))throw Error("Invalid MCP completion context");w=Object.create(null);for(let[Q,Y]of Object.entries(O.context)){if(typeof Y!=="string")throw Error("Invalid MCP completion context");w[Q]=Y}}return{reference:$,argument:{name:O.argument.name,value:O.argument.value},...w?{context:w}:{}}}function $1(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function vO(O,x){let $=WO()?.mcpServers??{};for(let[w,Q]of Object.entries($)){if(x&&w!==x)continue;if(!O.getServerStatus(w))await O.registerServer(w,Q,{connect:!1})}}var Rx=()=>{let O=new Gw;return O.get("/",async(x)=>{try{let $=HO.getInstance();await vO($);let w=$.getAllServers(),Q=await Promise.all(Array.from(w.entries()).map(async([Y,N])=>({id:Y,name:Y,status:N.status==="connected"?"connected":N.status==="reconnecting"?"reconnecting":N.status==="connecting"?"connecting":N.lastError?"error":"offline",endpoint:N.config.command?`${N.config.command} ${(N.config.args||[]).join(" ")}`.trim():N.config.url||"Unknown",description:`MCP server: ${Y}`,tools:N.tools.map((K)=>K.name),completionSupported:N.client.completionSupported,tasks:N.client.tasks,resources:N.contentCatalog.resources,resourceTemplates:N.contentCatalog.resourceTemplates.map((K)=>({...K,variables:Vw(K.uriTemplate)})),prompts:N.contentCatalog.prompts,connectedAt:N.connectedAt?.toISOString(),error:N.lastError?.message,recovery:N.recovery,logging:N.logging,instructions:N.instructions,oauthEnabled:N.client.oauthEnabled,oauthStatus:await N.client.getOAuthStatus()})));return x.json(Q)}catch($){return PO.error("[McpRoutes] Failed to get MCP servers:",$),x.json({error:$ instanceof Error?$.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async(x)=>{try{let $=x.req.param("name"),w=HO.getInstance();return await vO(w,$),await w.connectServer($),x.json({success:!0})}catch($){return PO.error("[McpRoutes] Failed to connect MCP server:",$),x.json({success:!1,error:$.message},500)}}),O.post("/:name/disconnect",async(x)=>{try{let $=x.req.param("name"),w=HO.getInstance();return await vO(w,$),await w.disconnectServer($),x.json({success:!0})}catch($){return PO.error("[McpRoutes] Failed to disconnect MCP server:",$),x.json({success:!1,error:$.message},500)}}),O.get("/:name/logs",async(x)=>{try{let $=x.req.param("name"),w=Number(x.req.query("limit")??20),Q=Number(x.req.query("afterRevision")??0);if(!Number.isSafeInteger(w)||w<1||w>100||!Number.isSafeInteger(Q)||Q<0)return x.json({error:"Invalid MCP log pagination"},400);let Y=HO.getInstance();return await vO(Y,$),x.json(Y.getLogSnapshot($,{limit:w,afterRevision:Q}))}catch($){return PO.error("[McpRoutes] Failed to get MCP logs:",$),x.json({error:$.message},500)}}),O.post("/:name/logging-level",async(x)=>{try{let $=x.req.param("name"),w=await x.req.json();if(!Mx(w.level))return x.json({success:!1,error:"Invalid MCP logging level"},400);let Q=HO.getInstance();return await vO(Q,$),await Q.setServerLoggingLevel($,w.level),x.json({success:!0,level:w.level})}catch($){return PO.error("[McpRoutes] Failed to set MCP logging level:",$),x.json({success:!1,error:$.message},400)}}),O.post("/:name/complete",async(x)=>{try{let $=x.req.param("name"),w=Bw(await x.req.json()),Q=HO.getInstance();await vO(Q,$);let Y=await Q.complete($,w);return x.json(Y)}catch($){return PO.error("[McpRoutes] Failed to complete MCP argument:",$),x.json({error:$.message},400)}}),O.post("/:name/oauth/login",async(x)=>{try{let $=x.req.param("name"),w=HO.getInstance();await vO(w,$);let Q=await w.beginOAuthLogin($);return x.json({success:!0,flowId:Q.flowId,authorizationUrl:Q.authorizationUrl},202)}catch($){return PO.error("[McpRoutes] Failed to start MCP OAuth login:",$),x.json({success:!1,error:$.message},400)}}),O.post("/:name/oauth/logout",async(x)=>{try{let $=x.req.param("name"),w=HO.getInstance();return await vO(w,$),await w.logoutOAuth($),x.json({success:!0})}catch($){return PO.error("[McpRoutes] Failed to log out MCP OAuth:",$),x.json({success:!1,error:$.message},400)}}),O.delete("/:name",async(x)=>{try{let $=x.req.param("name");await HO.getInstance().unregisterServer($);let Q=WO();if(Q?.mcpServers){let{[$]:Y,...N}=Q.mcpServers;await TO().updateConfig({mcpServers:N})}return x.json({success:!0})}catch($){return PO.error("[McpRoutes] Failed to delete MCP server:",$),x.json({success:!1,error:$.message},500)}}),O.post("/",async(x)=>{try{let $=await x.req.json(),{name:w,config:Q}=$;if(!w||!Q)return x.json({success:!1,error:"Missing name or config"},400);await HO.getInstance().registerServer(w,Q);let N=WO();return await TO().updateConfig({mcpServers:{...N?.mcpServers,[w]:Q}}),x.json({success:!0})}catch($){return PO.error("[McpRoutes] Failed to add MCP server:",$),x.json({success:!1,error:$.message},500)}}),O};import{getSupportedThinkingLevels as Uw}from"@earendil-works/pi-ai";import{Hono as Kw}from"hono";var w1=t("Service");function _w(O,x,$=kx.list()){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:x.contextWindow,maxTokens:x.maxTokens,reasoning:x.reasoning,supportedReasoningEfforts:Uw(x),supportedServiceTiers:Ix(x),supportedResponseVerbosities:qx(x),communicationStyles:$,input:x.input}}function Fw(O){Ex(O.overrides);let x={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)x.model=O.model;return x}function Ex(O){let x=O?.streamIdleTimeout;if(x!==void 0&&(!Number.isFinite(x)||x<1000))throw new F("streamIdleTimeout must be at least 1000ms")}var fx=()=>{let O=new Kw;return O.get("/",async(x)=>{try{let $=WO();if(!$)throw Error("Config not initialized");let w=x.get("directory")||a(),[Q,Y]=await Promise.all([Q1(w,$),kO(w)]),N=Q.config.models,K=N.find((b)=>b.id===Q.config.currentModelId)??N[0],S=Q.catalog,B=Y.communicationStyles.list(),j=(b)=>_w(b,S.resolveConfig(b),B);return x.json({configured:N.map(j),current:K?j(K):null})}catch($){w1.error("[ModelsRoutes] Failed to get models:",$);let w=new s("Failed to get models");return x.json(w.toObject(),500)}}),O.post("/",async(x)=>{let $=rO(),w,Q;try{let Y=await x.req.json(),{provider:N,displayName:K,model:S,overrides:B,apiKey:j,modelProvider:b}=Y;if(!N||!S)throw new F("provider and model are required");Ex(B);let U;if(b){if(b.id!==N)throw new F("modelProvider.id must match the model provider");if(WO()?.modelProviders[N])throw new F(`model provider already exists: ${N}`);U={name:b.name,baseUrl:b.baseUrl,wireApi:b.wireApi,...b.apiKeyEnv?{apiKeyEnv:b.apiKeyEnv}:{}};try{$.registerModelProvider(N,U,[S]),Q=N}catch(y){throw new F(y instanceof Error?y.message:"Invalid model provider")}}else $.getModel(N,S);if(j?.trim()){if(await $.setApiKey(N,j.trim()),U)w=N}let R={provider:N,displayName:K||void 0,model:S,overrides:B||void 0},JO=U?await TO().addModelWithProvider(R,U):await TO().addModel(R);return x.json({success:!0,model:JO})}catch(Y){if(w)await $.credentials.delete(w);if(Q){let N=WO();$.configureModelProviders(N?.modelProviders??{},N?.models??[])}throw w1.error("[ModelsRoutes] Failed to add model:",Y),Y}}),O.put("/:modelId",async(x)=>{try{let $=x.req.param("modelId"),w=await x.req.json(),{displayName:Q,overrides:Y,model:N}=w,K=Cx($);if(!K)throw new F("model config not found");if(N)rO().getModel(K.provider,N);return await TO().updateModel($,Fw({displayName:Q,overrides:Y,model:N})),x.json({success:!0})}catch($){throw w1.error("[ModelsRoutes] Failed to update model:",$),$}}),O.delete("/:modelId",async(x)=>{try{let $=x.req.param("modelId");return await TO().removeModel($),x.json({success:!0})}catch($){throw w1.error("[ModelsRoutes] Failed to delete model:",$),$}}),O};import{Hono as uw}from"hono";import dx from"node:path";import{Hono as Aw}from"hono";import{streamSSE as jw}from"hono/streaming";import{LRUCache as Sw}from"lru-cache";import{nanoid as B0}from"nanoid";class j1{runtimes=new Map;createRuntime;constructor(O={}){this.createRuntime=O.createRuntime??((x)=>new yx(x.projectPath,`web-browser:${x.sessionId}`,{exposeArtifactPaths:!1}))}get(O){let x=P(O),$=this.runtimes.get(x);if(!$)$=this.createRuntime(O),this.runtimes.set(x,$);return $}async reset(O){let x=this.runtimes.get(P(O));if(x)await x.page({action:{kind:"reset"}})}async dispose(O){let x=P(O),$=this.runtimes.get(x);if(!$)return;this.runtimes.delete(x),await $.dispose()}async disposeAll(){let O=[...this.runtimes.values()];this.runtimes.clear();let $=(await Promise.allSettled(O.map((w)=>w.dispose()))).find((w)=>w.status==="rejected");if($)throw $.reason}stats(){return{sessions:this.runtimes.size}}}import{Hono as Dw}from"hono";var Px=W.Object({action:OO(["accept","dismiss"])},{additionalProperties:!1}),Lw=EO(W.Union([W.Object({kind:W.Literal("click"),dialog:W.Optional(Px)},{additionalProperties:!1}),W.Object({kind:W.Literal("click_at"),screenshotId:W.String({minLength:1,maxLength:y0}),x:W.Integer({minimum:0,maximum:S1}),y:W.Integer({minimum:0,maximum:S1}),dialog:W.Optional(Px)},{additionalProperties:!1}),W.Object({kind:W.Literal("hover")},{additionalProperties:!1}),W.Object({kind:W.Literal("fill"),value:W.String()},{additionalProperties:!1}),W.Object({kind:W.Literal("type"),value:W.String()},{additionalProperties:!1}),W.Object({kind:W.Literal("press"),key:OO(["Enter","Tab","Escape","Backspace","Delete","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown","Space"])},{additionalProperties:!1}),W.Object({kind:W.Literal("select"),values:W.Array(W.String())},{additionalProperties:!1}),W.Object({kind:W.Literal("check")},{additionalProperties:!1}),W.Object({kind:W.Literal("uncheck")},{additionalProperties:!1}),W.Object({kind:W.Literal("scroll"),direction:OO(["up","down","left","right"]),amount:W.Integer()},{additionalProperties:!1})])),mx=EO(W.Object({action:W.Optional(OO(["goto","back","forward","reload"])),url:W.Optional(W.String()),pageId:W.Optional(W.String()),expectedOrigin:W.Optional(W.String()),waitUntil:W.Optional(OO(["commit","domcontentloaded","load"])),timeoutMs:W.Optional(W.Integer())},{additionalProperties:!1})),hx=EO(W.Object({pageId:W.String(),snapshotId:W.String(),ref:W.Optional(W.String()),expectedOrigin:W.String(),action:Lw,timeoutMs:W.Optional(W.Integer())},{additionalProperties:!1}));function gx(O,x){if(O===void 0)return;let $=Number(O);if(!Number.isSafeInteger($))throw new F(`${x} must be an integer`);return $}function Hw(O,x){if(O===void 0)return;if(O==="true")return!0;if(O==="false")return!1;throw new F(`${x} must be true or false`)}function bw(O){let x=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 e(O.code.toUpperCase(),O.message,x,O.details)}function px(O){let x=new Dw;x.use("*",(w,Q)=>O.withAdmission(Q)),x.onError((w,Q)=>{let Y=w instanceof ux?bw(w):w instanceof e?w:new s;return Q.json(Y.toObject(),Y.statusCode)});let $=(w,Q)=>O.resolveSessionRef(w,Q);return x.post("/:sessionId/browser/navigate",async(w)=>{let Q=await w.req.json().catch(()=>{return}),Y=f(mx,Q);if(!Y.success)throw new F("Invalid browser navigation request");let N=await $(w.req.param("sessionId"),w.req.query("projectPath"));return w.json(await O.getRuntime(N).navigate(Y.data))}),x.post("/:sessionId/browser/interact",async(w)=>{let Q=await w.req.json().catch(()=>{return}),Y=f(hx,Q);if(!Y.success)throw new F("Invalid browser interaction request");let N=await $(w.req.param("sessionId"),w.req.query("projectPath"));return w.json(await O.getRuntime(N).interact(Y.data))}),x.get("/:sessionId/browser/snapshot",async(w)=>{let Q=await $(w.req.param("sessionId"),w.req.query("projectPath")),Y=gx(w.req.query("depth"),"depth"),N=Hw(w.req.query("includeBoxes"),"includeBoxes");return w.json(await O.getRuntime(Q).snapshot({...w.req.query("pageId")?{pageId:w.req.query("pageId")}:{},...Y===void 0?{}:{depth:Y},...N===void 0?{}:{includeBoxes:N}}))}),x.get("/:sessionId/browser/inspect",async(w)=>{let Q=await $(w.req.param("sessionId"),w.req.query("projectPath")),Y=w.req.query("target"),N=w.req.query("pageId"),K=w.req.query("expectedOrigin");if(Y==="screenshot"){let j=w.req.query("source")??"user";if(j!=="user"&&j!=="agent")throw new F("Unsupported browser screenshot source");if(j==="agent"&&(!N||!K))throw new F("Agent browser screenshots require pageId and expectedOrigin");let b={...N?{pageId:N}:{},...K?{expectedOrigin:K}:{}},U=j==="agent"?await O.captureAgentScreenshot(Q,b):await O.getRuntime(Q).screenshot(b);return new Response(new Uint8Array(U),{headers:{"Content-Type":"image/png","Content-Length":String(U.length),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}let S=gx(w.req.query("limit"),"limit"),B={...N?{pageId:N}:{},...K?{expectedOrigin:K}:{}};if(Y==="find"){let j=w.req.query("text");if(!j)throw new F("text is required for browser find");return w.json(await O.getRuntime(Q).inspect({...B,target:{kind:"find",text:j,...S===void 0?{}:{limit:S}}}))}if(Y!=="console"&&Y!=="page-errors"&&Y!=="network")throw new F("Unsupported browser inspection target");return w.json(await O.getRuntime(Q).inspect({...B,target:{kind:Y,...S===void 0?{}:{limit:S}}}))}),x.post("/:sessionId/browser/reset",async(w)=>{let Q=await $(w.req.param("sessionId"),w.req.query("projectPath"));return await O.resetRuntime(Q),w.json({success:!0})}),x}var g=t("Service"),Z1="web-pending-resume-recovery-budget-exhausted";class Y1 extends Error{evidence;constructor(O){super(O.taskFailure.message);this.evidence=O;this.name="WebAgentRunFailure"}}var Mw=W.Object({title:W.Optional(W.String()),projectPath:W.Optional(W.String())}),Tw=D4,Rw=W.Object({title:W.Optional(W.String()),projectPath:W.Optional(W.String())}),qw=W.Object({projectPath:W.String()}),Iw=W.Object({objective:W.String({minLength:1}),tokenBudget:W.Optional(W.Integer({minimum:1})),permissionMode:W.Optional(OO(["default","autoEdit","plan","yolo"]))}),Cw=W.Union([W.Object({action:W.Literal("pause")}),W.Object({action:W.Literal("resume")}),W.Object({action:W.Literal("edit"),objective:W.String({minLength:1})})]),xO=new Map,_0,h0,yO=new Map,uO=new Map,fO=new Map,z1=new Sw({max:100,ttl:1800000});function vx(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function LO(O){if(!O)return;return yO.get(O)??z1.get(O)}function kw(O){if(yO.get(O.id)!==O)return;yO.delete(O.id),z1.set(O.id,O)}function Ew(O){yO.delete(O),z1.delete(O)}function FO(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function g0(O,x="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed"||O.status==="attention_required")return!1;let $=O.pendingPermission;if(O.pendingPermission=void 0,$?.resolve({approved:!1,reason:g1}),$)I.publish(vx(O),"interaction.resolved",{requestId:$.permissionId});return O.abortController.abort(x),O.status="cancelled",I.publish(vx(O),"run.cancelled",{runId:O.id}),!0}function R4(O,x=!1){let{permissionId:$,details:w}=O;if(w.type==="askUserQuestion"&&w.questions)return{type:"question.required",properties:{requestId:$,toolCallId:w.toolCallId??$,questions:w.questions,details:w,...x?{replayed:!0}:{}}};if(w.type==="mcpElicitation"&&w.mcpElicitation)return{type:"elicitation.required",properties:{requestId:$,toolCallId:w.toolCallId??$,elicitation:w.mcpElicitation,...x?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:$,toolName:w.toolName,description:w.message,args:w.args,details:w,...x?{replayed:!0}:{}}}}function fw(O){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 yw(){for(let O of yO.values())g0(O,"route-reset");yO.clear();for(let O of uO.values())O.controller.abort("route-reset");uO.clear(),z1.clear(),_0=void 0,h0?.(),h0=void 0,xO.clear()}function Pw(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let x=O,$=x.code,w=x.reason,Q=x.scope,Y=x.kind,N=x.limit;if($!=="tool_busy"&&$!=="tool_batch_full"||w!=="queue_full"&&w!=="wait_timeout"&&w!=="turn_limit"||Q!=="global"&&Q!=="session"||typeof x.retryable!=="boolean"||!Number.isSafeInteger(N)||N<=0||Y!==void 0&&Y!=="readonly"&&Y!=="write"&&Y!=="execute")return;return{code:$,reason:w,scope:Q,retryable:x.retryable,...Y===void 0?{}:{kind:Y},limit:N}}var u0=(O,x)=>{if(!x||typeof x!=="object")return x;let $={...x},w=Pw($.tool_admission);if(w)$.tool_admission=w;else delete $.tool_admission;if(N4(O)){let N=$.browser&&typeof $.browser==="object"&&!Array.isArray($.browser)?$.browser:{},K={},S=(B,j,b)=>{let U=N[B];if(typeof U==="string"&&Buffer.byteLength(U)<=j&&(!b||b.test(U)))K[B]=U};if(S("action",64),S("status",16,/^(?:ok|warning|error)$/),S("pageId",y0,/^browser_page_[a-f0-9-]+$/),S("snapshotId",y0,/^browser_snapshot_[a-f0-9-]+$/),S("origin",I1),S("candidateOrigin",I1),S("url",ex),S("title",O4),S("errorCode",64,/^browser_[a-z_]+$/),typeof N.truncated==="boolean")K.truncated=N.truncated;if(typeof N.actionApplied==="boolean"||N.actionApplied==="unknown")K.actionApplied=N.actionApplied;if(typeof N.sideEffectsUncertain==="boolean")K.sideEffectsUncertain=N.sideEffectsUncertain;if(typeof N.diagnosticCount==="number"&&Number.isSafeInteger(N.diagnosticCount)&&N.diagnosticCount>=0&&N.diagnosticCount<=rx)K.diagnosticCount=N.diagnosticCount;if(N.interaction&&typeof N.interaction==="object"&&!Array.isArray(N.interaction)){let B=N.interaction,j=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof B.action==="string"&&j.has(B.action)){let b={action:B.action};if(typeof B.ref==="string"&&Buffer.byteLength(B.ref)<=x4&&/^[a-z][a-z0-9]*$/.test(B.ref))b.ref=B.ref;let U=(R,JO,y)=>typeof R==="number"&&Number.isFinite(R)&&R>=JO&&R<=y;if(B.viewport&&typeof B.viewport==="object"&&!Array.isArray(B.viewport)){let R=B.viewport;if(U(R.width,1,16384)&&U(R.height,1,16384))b.viewport={width:R.width,height:R.height}}if(B.targetBox&&typeof B.targetBox==="object"&&!Array.isArray(B.targetBox)){let R=B.targetBox;if(U(R.x,-16384,32768)&&U(R.y,-16384,32768)&&U(R.width,0,16384)&&U(R.height,0,16384))b.targetBox={x:R.x,y:R.y,width:R.width,height:R.height}}K.interaction=b}}if(N.artifact&&typeof N.artifact==="object"&&!Array.isArray(N.artifact)){let B=N.artifact;if(typeof B.id==="string"&&/^[a-f0-9]{64}$/.test(B.id)&&B.sha256===B.id&&B.kind==="image"&&B.mimeType==="image/png"&&typeof B.size==="number"&&Number.isSafeInteger(B.size)&&B.size>=0&&B.size<=$4&&B.persisted===!0)K.artifact={id:B.id,sha256:B.sha256,kind:B.kind,mimeType:B.mimeType,size:B.size,persisted:!0,...typeof B.path==="string"&&Buffer.byteLength(B.path)<=8192?{path:B.path}:{}}}return{...typeof $.summary==="string"?{summary:$.summary.slice(0,512)}:{},browser:K,...w?{tool_admission:w}:{}}}if(O==="Bash"){let N={},K=["message","signal","status","summary"],S=["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"],B=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let b of K){let U=$[b];if(typeof U==="string")N[b]=U.slice(0,8192)}for(let b of S){let U=$[b];if(typeof U==="boolean")N[b]=U}for(let b of B){let U=$[b];if(typeof U==="number"&&Number.isSafeInteger(U)&&U>=0)N[b]=U}if($.exit_code===null||typeof $.exit_code==="number"&&Number.isSafeInteger($.exit_code))N.exit_code=$.exit_code;if($.terminal_transport==="local"||$.terminal_transport==="acp"||$.terminal_transport==="local_fallback")N.terminal_transport=$.terminal_transport;if($.background_reason==="explicit"||$.background_reason==="foreground_budget")N.background_reason=$.background_reason;for(let b of["bash_id","shell_id"]){let U=$[b];if(typeof U==="string"&&U.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(U))N[b]=U}if(w)N.tool_admission=w;let j=$.background_shell_admission;if(j&&typeof j==="object"&&!Array.isArray(j)){let b=j;if(b.code==="background_shell_busy"&&(b.scope==="session"||b.scope==="global")&&b.retryable===!0&&Number.isSafeInteger(b.limit)&&b.limit>0)N.background_shell_admission={code:b.code,scope:b.scope,retryable:b.retryable,limit:b.limit}}return N}let Q=200000,Y=(N,K)=>typeof N==="number"&&Number.isSafeInteger(N)&&N>=0&&N<=K?N:0;if(typeof $.oldContent==="string"&&$.oldContent.length>Q)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>Q)delete $.newContent;if($.mcpResult&&typeof $.mcpResult==="object"&&!Array.isArray($.mcpResult)){let N=$.mcpResult,K=Array.isArray(N.artifacts)?N.artifacts.slice(0,64).flatMap((S)=>{if(!S||typeof S!=="object"||Array.isArray(S))return[];let B=S,j=new Set(["text","image","audio","resource"]);if(typeof B.id!=="string"||!/^[a-f0-9]{64}$/.test(B.id)||typeof B.sha256!=="string"||B.sha256!==B.id||typeof B.kind!=="string"||!j.has(B.kind)||Y(B.size,67108864)!==B.size||typeof B.persisted!=="boolean")return[];return[{id:B.id.slice(0,128),sha256:B.sha256.slice(0,128),kind:B.kind,size:B.size,persisted:B.persisted,...typeof B.mimeType==="string"?{mimeType:B.mimeType.slice(0,256)}:{},...typeof B.sourceUri==="string"?{sourceUri:B.sourceUri.slice(0,8192)}:{},...typeof B.path==="string"?{path:B.path.slice(0,8192)}:{}}]}):[];$.mcpResult={isError:N.isError===!0,contentCount:Y(N.contentCount,64),textBytes:Y(N.textBytes,4194304),structuredBytes:Y(N.structuredBytes,4194304),artifactCount:Y(N.artifactCount,64),truncated:N.truncated===!0,binaryOmitted:N.binaryOmitted===!0,artifacts:K}}else delete $.mcpResult;return $};function mw(O){let x=typeof O.seq==="number"?{seq:O.seq}:{};if(O.type==="part_created"&&O.data.partType==="tool_call"){let $=O.data.payload;return{type:"tool.start",...x,properties:{messageId:O.data.messageId,toolCallId:$.toolCallId??O.data.partId,toolName:$.toolName??"unknown",arguments:JSON.stringify($.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let $=O.data.payload,w=$.toolName??"unknown",Q=u1($),Y=d0(v0(w,Q),p0);return{type:"tool.result",...x,properties:{messageId:O.data.messageId,toolCallId:$.toolCallId??O.data.partId,toolName:w,success:Q.success,status:Q.success?"completed":"failed",summary:Q.metadata?.summary,output:l0(Y),metadata:u0(w,Q.metadata)}}}return{type:`committed.${O.type}`,...x,properties:{event:O}}}function hw(O,x,$){switch($.kind){case"tool_start":if("function"in $.toolCall)I.publish(O,"subagent.update",{subagentSessionId:x,toolName:$.toolCall.function.name}),I.publish(O,"subagent.tool.start",{subagentSessionId:x,toolCallId:$.toolCall.id,toolName:$.toolCall.function.name,arguments:$.toolCall.function.arguments,toolKind:$.toolKind});break;case"tool_result":if("function"in $.toolCall)I.publish(O,"subagent.tool.result",{subagentSessionId:x,toolCallId:$.toolCall.id,toolName:$.toolCall.function.name,success:$.result.success,summary:$.result.metadata?.summary,output:l0(d0(v0($.toolCall.function.name,$.result),p0)),metadata:u0($.toolCall.function.name,$.result.metadata)});break;case"tool_progress":if("function"in $.toolCall)I.publish(O,"subagent.tool.progress",{subagentSessionId:x,toolCallId:$.toolCall.id,toolName:$.toolCall.function.name,...$.update});break;case"content_delta":I.publish(O,"subagent.delta",{subagentSessionId:x,delta:$.delta});break;case"thinking_delta":I.publish(O,"subagent.thinking.delta",{subagentSessionId:x,delta:$.delta});break;case"stream_end":I.publish(O,"subagent.stream.end",{subagentSessionId:x});break;case"provider_admission":I.publish(O,"subagent.provider.admission",{subagentSessionId:x,phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,reason:$.reason,queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,recoveryRemainingMs:$.recoveryRemainingMs});break;case"provider_circuit":I.publish(O,"subagent.provider.circuit",{subagentSessionId:x,phase:$.phase,reason:$.reason,statusCode:$.statusCode,retryAfterMs:$.retryAfterMs,nextProbeAt:$.nextProbeAt,openDurationMs:$.openDurationMs,sampleCount:$.sampleCount,failureCount:$.failureCount,recoveryRemainingMs:$.recoveryRemainingMs});break;case"provider_retry":I.publish(O,"subagent.provider.retry",{subagentSessionId:x,phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,statusCode:$.statusCode,delayMs:$.delayMs,nextRetryAt:$.nextRetryAt,mode:$.mode,recoveryBudgetMs:$.recoveryBudgetMs,recoveryElapsedMs:$.recoveryElapsedMs,recoveryRemainingMs:$.recoveryRemainingMs,exhaustedBy:$.exhaustedBy});break;case"provider_stall":I.publish(O,"subagent.provider.stall",{subagentSessionId:x,phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted});break;case"action_stationarity":I.publish(O,"subagent.action.stationarity",{subagentSessionId:x,phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware});break;case"mcp_catalog_changed":I.publish(O,"subagent.mcp.catalog.changed",{subagentSessionId:x,revision:$.revision,serverName:$.serverName,added:$.added,removed:$.removed,updated:$.updated});break;case"mcp_content_changed":I.publish(O,"subagent.mcp.content.changed",{subagentSessionId:x,revision:$.revision,serverName:$.serverName,contentKind:$.contentKind,added:$.added,removed:$.removed,updated:$.updated});break;case"mcp_resource_updated":I.publish(O,"subagent.mcp.resource.updated",{subagentSessionId:x,revision:$.revision,serverName:$.serverName,uri:$.uri});break;case"mcp_connection_changed":I.publish(O,"subagent.mcp.connection.changed",{subagentSessionId:x,revision:$.revision,serverName:$.serverName,phase:$.phase,reason:$.reason,attempt:$.attempt,maxAttempts:$.maxAttempts,nextRetryAt:$.nextRetryAt,error:$.error});break;case"mcp_log":I.publish(O,"subagent.mcp.log",{subagentSessionId:x,revision:$.revision,serverName:$.serverName,level:$.level,logger:$.logger,message:$.message,projectedBytes:$.projectedBytes,dataSha256:$.dataSha256,truncated:$.truncated,detailsOmitted:$.detailsOmitted,timestamp:$.timestamp,synthetic:$.synthetic});break;case"mcp_instructions_changed":I.publish(O,"subagent.mcp.instructions.changed",{subagentSessionId:x,revision:$.revision,serverName:$.serverName,action:$.action,reason:$.reason,text:$.text,sourceBytes:$.sourceBytes,projectedBytes:$.projectedBytes,sha256:$.sha256,truncated:$.truncated,detailsOmitted:$.detailsOmitted});break;case"mcp_task_changed":I.publish(O,"subagent.mcp.task.changed",{subagentSessionId:x,revision:$.revision,taskId:$.taskId,serverName:$.serverName,toolName:$.toolName,status:$.status,statusMessage:$.statusMessage,createdAt:$.createdAt,updatedAt:$.updatedAt,completedAt:$.completedAt,hasResult:$.hasResult,error:$.error});break;case"project_rules_loaded":I.publish(O,"subagent.project.rules.loaded",{subagentSessionId:x,files:$.files,triggerPaths:$.triggerPaths,blockedWrite:$.blockedWrite});break;default:break}}function P0(O,x="projectPath"){if(!dx.isAbsolute(O))throw new F(`${x} must be absolute`);return dx.resolve(O)}function m1(O){try{x1(O)}catch(x){throw new F(x instanceof Error?x.message:`Invalid session ID: ${O}`)}}function o(O){return{sessionId:O.id,projectPath:O.projectPath}}function m0(O,x,$){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:$,messages:x}}function M1(O){return O.flatMap((x)=>{if(!Q4(x)||x.role==="system"||x.role==="tool"&&x.name===K0)return[];let $=x.tool_calls?.filter((N)=>!("function"in N)||N.function.name!==K0),w=typeof x.content==="string"?x.content.trim():"";if(x.role==="assistant"&&x.tool_calls?.length&&!$?.length&&!w&&!x.reasoningContent&&!x.metadata)return[];let Q={...x,...x.tool_calls?{tool_calls:$&&$.length>0?$:void 0}:{}};if(x.role==="tool"){let N=x.metadata&&typeof x.metadata==="object"&&!Array.isArray(x.metadata)?x.metadata:void 0,K=x.name??(typeof N?.toolName==="string"?N.toolName:"unknown");if(N!==void 0&&(Object.hasOwn(N,"output")||Object.hasOwn(N,"error"))){let B=u1(N),j=d0(v0(K,B),p0);return[{...Q,name:K,content:l0(j),metadata:u0(K,{...B.metadata,status:B.success?"completed":"failed"})}]}return[{...Q,name:K,metadata:u0(K,N)}]}let Y=J4(x.metadata);return[Y?{...Q,content:Z4(Y)}:Q]})}function iO(O,x){O.title=x.title??O.title,O.taskStatus=x.taskStatus,O.taskStatusReason=x.taskStatusReason,O.taskFailure=x.taskFailure,O.taskStartedAt=x.taskStartedAt,O.taskCompletedAt=x.taskCompletedAt,O.taskPromptSummary=x.taskPromptSummary,O.taskPriority=x.taskPriority,O.taskKind=x.taskKind,O.taskDueAt=x.taskDueAt,O.taskModelId=x.taskModelId,O.selectedModelId=x.selectedModelId,O.permissionMode=x.permissionMode,O.reasoningEffort=x.reasoningEffort,O.serviceTier=x.serviceTier,O.responseVerbosity=x.responseVerbosity,O.communicationStyle=x.communicationStyle,O.communicationStyleDigest=x.communicationStyleDigest,O.projectInstructionsDigest=x.projectInstructionsDigest,O.pendingInteraction=x.pendingInteraction,O.taskRetryAvailable=x.taskRetryAvailable,O.taskRetriedFrom=x.taskRetriedFrom,O.taskDelivery=x.taskDelivery,O.taskIsolation=x.taskIsolation,O.taskSourceProjectPath=x.taskSourceProjectPath,O.taskWorktreePath=x.taskWorktreePath,O.taskWorktreeBranch=x.taskWorktreeBranch,O.taskBaseCommit=x.taskBaseCommit,O.taskDiffStat=x.taskDiffStat,O.taskQueuePosition=x.taskQueuePosition,O.taskQueueDepth=x.taskQueueDepth,O.taskConcurrencyLimit=x.taskConcurrencyLimit,O.archivedAt=x.archivedAt,O.archivedBySessionId=x.archivedBySessionId,O.updatedAt=new Date(x.lastMessageTime)}async function cO(O){let x=await C.findSessionMetadata(O.id,O.projectPath);if(x)iO(O,x)}function eO(O){let x=LO(O.currentRunId),$=x?.status==="waiting_permission"?"running":x?.status==="attention_required"?"interrupted":x?.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:$,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:$==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:$==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:x?.pendingPermission?{type:x.pendingPermission.details.type==="askUserQuestion"?"question":x.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:x.pendingPermission.permissionId}:O.pendingInteraction,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function BO(O,x){if(m1(O),x!==void 0){let w=lO({sessionId:O,projectPath:P0(x)});if(xO.has(P(w)))return w;let Q=await C.findSessionMetadata(w.sessionId,w.projectPath);if(!Q)throw new h("Session",O);return lO({sessionId:Q.sessionId,projectPath:Q.projectPath})}let $=new Map;for(let w of xO.values()){if(w.id!==O)continue;let Q=o(w);$.set(P(Q),Q)}for(let w of await C.listSessions()){if(w.sessionId!==O)continue;let Q=lO({sessionId:w.sessionId,projectPath:w.projectPath});$.set(P(Q),Q)}if($.size===0)try{let w=await C.findSessionMetadata(O);if(!w)throw new h("Session",O);return lO({sessionId:w.sessionId,projectPath:w.projectPath})}catch(w){if(w instanceof h)throw w;if(w instanceof Error&&w.message.startsWith("Ambiguous session ID:"))throw new MO;throw w}if($.size>1)throw new MO;return $.values().next().value}function h1(O){if(typeof O==="string")return O;return O.filter((x)=>x.type==="text").map((x)=>x.text).join(`
|
|
7
|
-
`)}function lx(O,x){let $=(x??[]).filter((Q)=>Q.type==="image"&&typeof Q.content==="string").map((Q)=>({type:"image_url",image_url:{url:Q.content}}));if($.length===0)return O;let w=[];if(O.trim())w.push({type:"text",text:O});return w.push(...$),w}var q4=()=>{yw();let O=new Aw;O.onError((Z,G)=>{if(Z instanceof V0){let J=new hO("Session runtime capacity is full",{resource:Z.resource,limit:Z.limit});return G.json(J.toObject(),429)}if(Z instanceof e)return G.json(Z.toObject(),Z.statusCode);return g.error("[SessionRoutes] Unhandled route error:",Z),G.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let x=new Map,$=new j1,w=new Map,Q=new Map,Y=new Map,N=new T1,K=new T1,S=WO(),B=new j4({maxResident:S?.maxResidentSessionRuntimes??ax,idleMs:S?.sessionRuntimeIdleMs??ox}),j=new B4,b=setInterval(()=>{B.sweepIdle().catch((Z)=>{g.warn("[SessionRoutes] Session Runtime idle sweep failed:",Z)})},nx);b.unref?.();let U,R=new Map,JO=1,y,r=()=>{for(let Z of R.values())if(Z.timer)clearTimeout(Z.timer);R.clear()};h0=r;let ZO=async(Z)=>{let G;try{G=j.enter()}catch{throw new gO}try{return await Z()}finally{G.release()}};O.use("*",async(Z,G)=>{if(Z.req.method==="GET"||Z.req.method==="HEAD")return G();return ZO(G)});let GO=(Z,G)=>N.runExclusive(P(Z),G),YO=(Z,G)=>{let J=P(Z),X=R.get(J);if(!X||G!==void 0&&X.generation!==G)return;if(X.timer)clearTimeout(X.timer);R.delete(J)},T=(Z)=>{let G=P(o(Z)),J=R.get(G);if(J?.inFlight||J?.timer)return;if(!J)J={attempt:0,generation:JO++,inFlight:!1,projectedInputIds:new Set,startedAt:Date.now(),timer:void 0},R.set(G,J);return J.inFlight=!0,J.attempt++,{attempt:J.attempt,deadlineAt:J.startedAt+M4,generation:J.generation,projectedInputIds:J.projectedInputIds}},jO=(Z,G,J,X,V)=>{I.publish(Z,"pending.resume",{phase:G,kind:"pending_input",attempt:J,maxAttempts:S4,...V===void 0?{}:{delayMs:V,nextRetryAt:Date.now()+V},...X?{failure:{code:X.code,retryable:X.retryable,...X.resource?{resource:X.resource}:{}}}:{}})},i=(Z,G,J,X,V,L)=>{let _=o(Z),D=P(_),H=R.get(D);if(!H||H.generation!==G.generation)return!1;if(L)return H.inFlight=!1,jO(_,"exhausted",G.attempt,J.taskFailure),YO(_,G.generation),!1;let A=T4({sessionIdentity:D,failedAttempt:G.attempt,recoveryStartedAt:H.startedAt,workStillPending:X,evidence:J});if(A.phase!=="retry_scheduled")return H.inFlight=!1,jO(_,A.phase,G.attempt,J.taskFailure),YO(_,G.generation),!1;let M=setTimeout(()=>{(async()=>{if(await V.completion,R.get(D)!==H||H.timer!==M)return;await GO(_,async()=>{if(R.get(D)!==H||H.timer!==M)return;H.timer=void 0,H.inFlight=!1;let q=T(Z);if(!q)return;try{await y(Z,q)}catch(wO){throw YO(_,q.generation),wO}})})().catch((q)=>{g.error(`[SessionRoutes] Failed to retry pending input for ${Z.id}:`,q)})},A.delayMs);return M.unref?.(),H.timer=M,H.inFlight=!1,jO(_,"retry_scheduled",G.attempt+1,J.taskFailure,A.delayMs),!0},XO=(Z,G)=>{let J=o(Z),X=R.get(P(J));if(!X||X.generation!==G.generation)return!1;if(G.attempt>1)jO(J,"recovered",G.attempt);return YO(J,G.generation),!0},UO=(Z,G)=>K.runExclusive(P(Z),G),SO=(Z)=>[...yO.values()].some((G)=>G.sessionId===Z.sessionId&&G.projectPath===Z.projectPath&&FO(G)),RO=async(Z,G,J)=>{let X=Q.get(G);if(!X)X=(async()=>{if(x.get(G)===J)x.delete(G);for(let[L,_]of x)if(_===J)x.delete(L);let V=o(Z);if(xO.get(G)===Z&&!SO(V)&&!uO.has(G)&&!fO.has(G))xO.delete(G);if(await J.dispose(),x.size===0)await HO.getInstance().disconnectAll()})().finally(()=>{if(Q.get(G)===X)Q.delete(G)}),Q.set(G,X);await X},v=async(Z,G={})=>{let J=o(Z),X=P(J);await Q.get(X);let V=B.acquire(X);if(V){if(x.get(X)!==V.value)throw V.release(),Error("Session Runtime residency identity is inconsistent");return V}if(B.owns(X))throw new V0(B.getStats().maxResident);let L=w.get(X);if(!L){let _=G.communicationStyle??Z.communicationStyle;L=(async()=>{let D=await B.reserve(X,{surface:"web",allowEviction:!0});try{let H=await O0.create({sessionId:Z.id,workspaceRoot:Z.projectPath,permissionMode:G.permissionMode??Z.permissionMode??"default",...Z.reasoningEffort?{reasoningEffort:Z.reasoningEffort}:{},...Z.serviceTier?{serviceTier:Z.serviceTier}:{},...Z.responseVerbosity?{responseVerbosity:Z.responseVerbosity}:{},..._?{communicationStyle:_}:{},..._===Z.communicationStyle&&Z.communicationStyleDigest?{communicationStyleDigest:Z.communicationStyleDigest}:{},...Z.projectInstructionsDigest?{projectInstructionsDigest:Z.projectInstructionsDigest}:{},...Z.taskWorktree?{taskWorktree:Z.taskWorktree}:{},...Z.taskIsolation?{taskIsolation:Z.taskIsolation}:{},...Z.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:Z.id}}:{}}),A=H.getCurrentModelId();if(A&&(Z.selectedModelId||Z.taskModelId)&&A!==Z.selectedModelId){let q=await C.updateSessionMetadata(Z.id,Z.projectPath,{selectedModelId:A}).catch((wO)=>{g.warn(`[SessionRoutes] Failed to migrate restored model for ${Z.id}:`,wO);return});if(q)Z.selectedModelId=q.selectedModelId,Z.updatedAt=new Date(q.lastMessageTime)}let M=D.commit({key:X,surface:"web",value:H,canEvict:()=>!SO(J)&&!uO.has(X)&&!fO.has(X)&&!w.has(X)&&!Q.has(X)&&H.isIdleForResidency(),dispose:()=>RO(Z,X,H)});return x.set(X,H),{runtime:H,claimLease:()=>{if(M){let wO=M;return M=void 0,wO}let q=B.acquire(X);if(!q||q.value!==H)throw Error("Initialized Session Runtime lost residency");return q}}}catch(H){if(D.cancel(),H instanceof z4)throw new e0(H.reason);throw H}})(),w.set(X,L)}try{return(await L).claimLease()}finally{if(w.get(X)===L)w.delete(X)}},bO=async(Z,G,J={})=>{let X=await v(Z,J);try{return await G(X.value)}finally{X.release()}},Z0=async(Z,G)=>{let J=P(o(Z)),X=w.get(J);if(X)await X.catch(()=>{return});w.delete(J);let V=G??x.get(J);if(!V)return;if(!await B.remove(J,V))throw Error(`Session Runtime is pinned and cannot be disposed: ${J}`)},KO=async(Z)=>{let G=P(Z),J=xO.get(G);if(J)return J;let X=Y.get(G);if(!X)X=(async()=>{let V=await C.findSessionMetadata(Z.sessionId,Z.projectPath);if(!V)throw new h("Session",Z.sessionId);let[L,_]=await Promise.all([C.loadSession(Z.sessionId,Z.projectPath),C.findSessionTaskWorktree(Z.sessionId,Z.projectPath)]),D=m0(V,L,_);return xO.set(G,D),D})(),Y.set(G,X);try{return await X}finally{if(Y.get(G)===X)Y.delete(G)}},z=async(Z,G)=>{let J=await BO(Z,G);try{await C.assertSessionWritable(J.sessionId,J.projectPath)}catch(X){if(X instanceof k1)throw new E(X.message);throw X}return KO(J)},$O=async(Z,G)=>{if(Z.permissionMode===G)return;let J=await C.setSessionPermissionMode(Z.id,Z.projectPath,G);Z.permissionMode=J.permissionMode,Z.updatedAt=new Date(J.lastMessageTime),I.publish(o(Z),"session.updated",{permissionMode:G})},J0=(Z,G,J,X={})=>{if(!j.stats().accepting)throw new gO;let V=B0(12),L={id:V,sessionId:Z.id,projectPath:Z.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:Z.taskIsolation!==void 0&&X.runtimeLease!==void 0,pendingResume:X.pendingResume,createdAt:new Date};if(Z.taskIsolation&&X.runtimeLease){let _=X.runtimeLease.value,D=dO.admit({key:`${Z.projectPath}\x00${Z.id}`,..._.getTaskAdmissionLimits(),pendingBytes:U4({content:G,outputSchema:X.outputSchema,pendingMessages:_.getPendingSteeringMessages()}),signal:L.abortController.signal,onUpdate:(A)=>{L.status=A.state,Z.taskStatus=A.state,Z.taskQueuePosition=A.queuePosition,Z.taskQueueDepth=A.queueDepth,Z.taskConcurrencyLimit=A.maxConcurrent,L.taskAdmissionUpdate=(L.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await _.setTaskAdmission(A)}).catch((M)=>{g.warn(`[SessionRoutes] Failed to persist admission for ${Z.id}:`,M)})}});L.taskAdmission=D;let H=D.getSnapshot();L.status=H.state,Z.taskStatus=H.state,Z.taskQueuePosition=H.queuePosition,Z.taskQueueDepth=H.queueDepth,Z.taskConcurrencyLimit=H.maxConcurrent}return yO.set(V,L),Z.currentRunId=V,L.completion=gw(L,Z,G,J,v,{pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:L.taskAdmission,runtimeLease:X.runtimeLease,disposeRuntime:Z0,pendingResume:X.pendingResume,onPendingResumeFailure:(_,D,H,A)=>i(Z,_,D,H,L,A),onPendingResumeSuccess:(_)=>XO(Z,_),onPendingResumeCancelled:(_)=>YO(o(Z),_.generation)}).catch((_)=>{g.error(`[SessionRoutes] Run ${V} failed:`,_)}),L},U1=async(Z)=>{let G;if(Z.outputSchema)try{G=C1(Z.outputSchema).schema}catch(p){throw new F(p instanceof Error?p.message:"Invalid output schema")}let J=q1("task",12),X=P0(Z.sourceProjectPath),V=Z.modelId?.trim(),L=WO();if(!L)throw new F("Config not initialized");let[_,D]=await Promise.all([Q1(X,L),kO(X)]);if(V&&!_.config.models.some((p)=>p.id===V))throw new F(`Task model not found: ${V}`);let H=V||_.config.models.find((p)=>p.id===_.config.currentModelId)?.id||_.config.models[0]?.id;if(!H)throw new F("No model is configured. Add or select a model before dispatching a task.");let A=_.config.models.find((p)=>p.id===H);if(!A)throw new F(`Task model not found: ${H}`);let M=Z.reasoningEffort??"off",q=Z.serviceTier??"auto",wO=Z.responseVerbosity??"auto",qO=Z.communicationStyle??"auto",_O,NO=D.projectRules?.staticRules(X),QO=NO&&NO.files.length>0?NO.provenanceSha256:void 0;try{let p=_.catalog.resolveConfig(A);tx(p,M),cx(p,q),ix(p,wO);let l=sx(qO,D.communicationStyles);_O=l.source==="built-in"?void 0:l.contentSha256}catch(p){throw new F(p instanceof Error?p.message:"Invalid reasoning effort")}let N0={version:1,prompt:Z.prompt,...Z.title?{title:Z.title}:{},...Z.taskPriority?{taskPriority:Z.taskPriority}:{},...Z.taskKind?{taskKind:Z.taskKind}:{},...Z.taskDueAt?{taskDueAt:Z.taskDueAt}:{},sourceProjectPath:X,isolation:Z.isolation,permissionMode:Z.permissionMode,modelId:H,reasoningEffort:M,serviceTier:q,responseVerbosity:wO,communicationStyle:qO,..._O?{communicationStyleDigest:_O}:{},...QO?{projectInstructionsDigest:QO}:{},...Z.attachments?{attachments:Z.attachments.map((p)=>({...p}))}:{},...G?{outputSchema:G}:{}},k,u,m;try{let p=await _4.createSessionTask({sessionId:J,prompt:Z.prompt,title:Z.title,taskPriority:Z.taskPriority,taskKind:Z.taskKind,taskDueAt:Z.taskDueAt,sourceProjectPath:X,isolation:Z.isolation,dispatch:N0,retriedFrom:Z.retriedFrom}),{metadata:l}=p;k=p.taskWorktree,u=m0(l,[],k);let d=o(u);xO.set(P(d),u),I.publish(d,"task.status",{taskStatus:l.taskStatus,updatedAt:l.lastMessageTime});let c=lx(Z.prompt,Z.attachments);m=await v(u);let pO=m.value,n=G?await pO.prepareInputTurn(c,{outputSchema:G}):await pO.prepareInputTurn(c);if(!n.accepted)throw new E(`Task prompt was not accepted: ${n.reason}`);let zO=J0(u,c,Z.permissionMode,{preparedInputTurn:n,runtimeLease:m,outputSchema:G});return m=void 0,await zO.taskAdmissionUpdate,{session:eO(u),runId:zO.id,messageId:n.messageId,status:zO.status==="queued"?"queued":"running",queuePosition:u.taskQueuePosition,queueDepth:u.taskQueueDepth,maxConcurrentTasks:u.taskConcurrencyLimit}}catch(p){if(m?.release(),m=void 0,(p instanceof P1||p instanceof V0)&&u){let l=o(u),d=P(l);if(k)await mO.exit({sessionId:u.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await Z0(u).catch(()=>{return}),await C.deleteSession(u.id,u.projectPath).catch(()=>{return}),xO.delete(d),new hO(p instanceof V0?"Session runtime capacity is full":"Task admission capacity is full",{resource:p.resource,limit:p.limit})}if(u){let l=await C.findSessionMetadata(u.id,u.projectPath).catch(()=>{return});if(!l||l.taskStatus==="queued"){let d=U0(p),c=await C.updateSessionMetadata(u.id,u.projectPath,{taskStatus:"failed",taskStatusReason:d.message,taskFailure:d,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});u.taskStatus=c?.taskStatus??"failed",u.taskStatusReason=c?.taskStatusReason??d.message,u.taskFailure=c?.taskFailure??d,u.taskCompletedAt=c?.taskCompletedAt}else u.taskStatus=l.taskStatus,u.taskStatusReason=l.taskStatusReason,u.taskFailure=l.taskFailure,u.taskCompletedAt=l.taskCompletedAt}throw p}},Y0=(Z)=>ZO(()=>U1(Z)),o0=async(Z,G)=>{let J=await BO(Z,G),X=await C.findSessionMetadata(J.sessionId,J.projectPath);if(!X)throw new h("Session",J.sessionId);if(!["failed","interrupted","cancelled"].includes(X.taskStatus))throw new E(`Task cannot be retried while status is ${X.taskStatus}`);let V=await C.findSessionTaskDispatch(J.sessionId,J.projectPath);if(!V)throw new E("Task retry payload is unavailable");return Y0({prompt:V.prompt,title:X.title??V.title,taskPriority:X.taskPriority??V.taskPriority,taskKind:X.taskKind??V.taskKind,taskDueAt:X.taskDueAt,sourceProjectPath:V.sourceProjectPath,isolation:V.isolation,permissionMode:V.permissionMode,modelId:V.modelId,reasoningEffort:V.reasoningEffort,serviceTier:V.serviceTier,responseVerbosity:V.responseVerbosity,communicationStyle:V.communicationStyle,attachments:V.attachments,outputSchema:V.outputSchema,retriedFrom:J})},n0=(Z,G)=>ZO(()=>o0(Z,G)),t0=(Z,G,J)=>ZO(async()=>{let X=await BO(Z,J);if(!await C.findSessionMetadata(X.sessionId,X.projectPath))throw new h("Session",X.sessionId);let L=await C.updateSessionMetadata(X.sessionId,X.projectPath,G),_=xO.get(P(X));if(_)iO(_,L);return I.publish(X,"session.updated",{...L.title?{title:L.title}:{},...L.taskPriority?{taskPriority:L.taskPriority}:{},...L.taskKind?{taskKind:L.taskKind}:{},taskDueAt:L.taskDueAt??null}),_?eO(_):{...L,isActive:!1}}),K1=async(Z,G)=>{let J=await z(Z,G);if(!J.taskWorktree)throw new F("Session does not have a task worktree");try{await mO.restoreSession(J.taskWorktree);let X=await mO.getDiffArtifact(J.id);if(!X)throw new E("Task diff artifact is unavailable");return{sessionId:J.id,projectPath:J.projectPath,...X}}catch(X){if(X instanceof E)throw X;throw g.error("[SessionRoutes] Failed to load task diff artifact:",X),new E("Task diff artifact is unavailable")}},_1=async(Z,G,J)=>{let X=await BO(Z,J);return UO(X,async()=>{let V=await z(X.sessionId,X.projectPath);if(["queued","running"].includes(V.taskStatus))throw new E(`Task artifacts cannot be delivered while status is ${V.taskStatus}`);if(V.taskDelivery?.status==="applied")throw new E("Task changes have already been applied");if(V.taskDelivery?.status==="discarded")throw new E("Task changes have already been discarded");if(!V.taskWorktree)throw new E("Task worktree is unavailable");let L=async(_,D=!1)=>{let H=await C.updateSessionMetadata(V.id,V.projectPath,{taskDelivery:_,...D?{taskWorktree:null}:{}});if(iO(V,H),D)V.taskWorktree=void 0;return I.publish(X,"task.delivery",{taskDelivery:_,...D?{taskWorktreeRemoved:!0}:{},updatedAt:H.lastMessageTime}),eO(V)};try{if(G==="discard"){try{await mO.restoreSession(V.taskWorktree)}catch(H){return g.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${V.id}:`,H),L({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:V.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let D=await mO.exit({sessionId:V.id,action:"remove",discardChanges:!0});return L({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:D.discardedFiles??0,message:"Task worktree removed"},!0)}try{await mO.restoreSession(V.taskWorktree)}catch(D){throw g.warn(`[SessionRoutes] Task worktree is unavailable for ${V.id}:`,D),new y1("artifact_unavailable","Task worktree is unavailable")}let _=await mO.apply(V.id);return L({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:_.sourceCommit,changedFiles:_.changedFiles,message:"Task changes applied to the source workspace"})}catch(_){if(_ instanceof y1)throw await L({status:"conflicted",updatedAt:new Date().toISOString(),message:_.message}),new E(_.message);throw _}})},d$=(Z,G,J)=>ZO(()=>_1(Z,G,J)),wx=async(Z,G)=>{let J=LO(Z.currentRunId);if(FO(J)){if(G)YO(o(Z),G.generation);return}let X=Z.taskIsolation&&Z.taskStatus!=="queued"&&Z.taskStatus!=="running",V=X?await O0.hasRecoverableTurn(Z.projectPath,Z.id):!1;if(X&&!V){if(G)YO(o(Z),G.generation);return}let L=await O0.hasPendingInbox(Z.projectPath,Z.id),_=!L&&await O0.hasActiveGoal(Z.projectPath,Z.id);if(!L&&!_&&!V)V=await O0.hasRecoverableTurn(Z.projectPath,Z.id);if(!L&&!_&&!V){YO(o(Z));return}if(G&&!L){YO(o(Z),G.generation);return}let D=await v(Z),H=!1;try{let A=D.value,M=LO(Z.currentRunId);if(FO(M)){if(G)YO(o(Z),G.generation);return}if(L&&A.getPendingSteeringCount()===0)await A.reloadPendingInbox();let q=A.getPendingSteeringCount()>0,wO=q?null:await A.getGoal(),qO=wO?.status==="active"||wO?.status==="verifying",_O=A.getTurnRecoveryAssessment();if(_O.state!=="none"&&(_O.state==="requires_attention"||!q&&!qO))I.publish({sessionId:Z.id,projectPath:Z.projectPath},"turn.recovery",{assessment:_O});if(_O.state==="requires_attention"||X||!q&&!qO||A.hasTurnOwner()){if(G||!q)YO(o(Z),G?.generation);return}let NO=q&&!Z.taskIsolation?G??T(Z):void 0;if(q&&!Z.taskIsolation&&!NO)return;J0(Z,"",Z.permissionMode??"default",{pendingInputOnly:q,goalContinuationOnly:qO,runtimeLease:D,pendingResume:q?NO:void 0}),H=!0}finally{if(!H)D.release()}};y=async(Z,G)=>{let J;try{J=j.enter()}catch{return}try{let X=LO(Z.currentRunId);if(FO(X)){if(G)YO(o(Z),G.generation);return}if(Z.taskIsolation){await wx(Z);return}await wx(Z,G)}finally{J.release()}},_0=y;let v$=async()=>{let Z={scheduled:0,failed:0,deferred:0};if(!j.stats().accepting)return Z;let G=(await C.listSessions({taskStatus:"queued"})).filter((J)=>J.taskIsolation!==void 0).sort((J,X)=>J.firstMessageTime.localeCompare(X.firstMessageTime)||J.projectPath.localeCompare(X.projectPath)||J.sessionId.localeCompare(X.sessionId));for(let[J,X]of G.entries()){let V={sessionId:X.sessionId,projectPath:X.projectPath};try{if(!await O0.hasPendingInbox(X.projectPath,X.sessionId)){let _=U0("Queued task input is missing");await C.updateSessionMetadata(X.sessionId,X.projectPath,{taskStatus:"failed",taskStatusReason:_.message,taskFailure:_,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),Z.failed++;continue}let L=await KO(V);if(await y(L),L.currentRunId)Z.scheduled++}catch(L){if(L instanceof P1||L instanceof V0){Z.deferred+=G.length-J;break}g.warn(`[SessionRoutes] Failed to recover queued task ${X.sessionId}:`,L),Z.deferred++}}return Z};return O.route("/",px({withAdmission:ZO,resolveSessionRef:async(Z,G)=>{let J=await BO(Z,G);return await KO(J),J},getRuntime:(Z)=>$.get(Z),captureAgentScreenshot:async(Z,G)=>{let J=await KO(Z);return bO(J,(X)=>X.captureBrowserScreenshot(G))},resetRuntime:(Z)=>$.reset(Z)})),O.get("/",async(Z)=>{try{let G=await C.listSessions(),J=new Set(G.filter((A)=>A.relationType==="subagent").map((A)=>P({sessionId:A.sessionId,projectPath:A.projectPath}))),X=Array.from(xO.values()).filter((A)=>!J.has(P(o(A)))&&A.relationType!=="subagent").map((A)=>eO(A)),V=new Set(X.map((A)=>P({sessionId:A.sessionId,projectPath:A.projectPath}))),L=G.filter((A)=>{if(A.relationType==="subagent")return!1;return!V.has(P({sessionId:A.sessionId,projectPath:A.projectPath}))}),_=new Set(V),D=L.filter((A)=>{let M=P({sessionId:A.sessionId,projectPath:A.projectPath});if(_.has(M))return!1;return _.add(M),!0}),H=[...X,...D];return Z.json(H)}catch(G){throw g.error("[SessionRoutes] Failed to list sessions:",G),new s("Failed to list sessions")}}),O.get("/catalog",async(Z)=>{try{let G=Z.req.query("limit"),J=G===void 0?void 0:Number(G),X=Z.req.query("cursor"),V=Z.req.query("projectPath"),L=Z.req.query("archived");if(L!==void 0&&L!=="true"&&L!=="false")throw new F("archived must be true or false");let _=L==="true",D=await C.listSessionPage({...V?{cwd:P0(V)}:{},...X?{cursor:X}:{},...J===void 0?{}:{limit:J},includeSubagents:!1,archived:_}),H=new Map((_?[]:Array.from(xO.values())).filter((A)=>A.relationType!=="subagent").map((A)=>[P(o(A)),eO(A)]));return Z.json({sessions:D.sessions.map((A)=>H.get(P({sessionId:A.sessionId,projectPath:A.projectPath}))??A),...D.nextCursor?{nextCursor:D.nextCursor}:{}})}catch(G){if(G instanceof F)throw G;if(G instanceof Error&&(G.message.startsWith("Invalid session cursor")||G.message.startsWith("Session cursor scope")||G.message.startsWith("Session catalog")))throw new F(G.message);throw g.error("[SessionRoutes] Failed to list session catalog:",G),new s("Failed to list session catalog")}}),O.post("/",async(Z)=>{try{let G=await Z.req.json(),J=f(Mw,G);if(!J.success)throw new F("Invalid request body");let{title:X,projectPath:V}=J.data,L=q1("web",12),_=P0(V||Z.get("directory")||a(),V?"projectPath":"directory"),D=await C.createSessionMetadata(L,_,{title:X,taskStatus:"completed"}),H=m0(D,[]),A=o(H);return xO.set(P(A),H),I.publish(A,"session.created",{}),Z.json({...eO(H),status:void 0,agentType:void 0,model:void 0})}catch(G){if(g.error("[SessionRoutes] Failed to create session:",G),G instanceof F)throw G;throw new s("Failed to create session")}}),O.get("/:sessionId/export",async(Z)=>{let G=Z.req.param("sessionId");try{let J=Z.req.query("includeReasoning");if(J!==void 0&&J!=="true"&&J!=="false")throw new F("includeReasoning must be true or false");let X=await BO(G,Z.req.query("projectPath")),V=await C.exportSessionMarkdown(X.sessionId,X.projectPath,{includeReasoning:J==="true"});return Z.body(V.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${V.filename}"`,"Content-Length":String(Buffer.byteLength(V.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":V.contentSha256,"X-Blade-Export-Activities":String(V.activityCount),"X-Blade-Export-Messages":String(V.messageCount),"X-Blade-Export-Redactions":String(V.redactionCount)})}catch(J){if(J instanceof F||J instanceof h||J instanceof MO)throw J;if(J instanceof Error&&J.message==="No conversation content to export")throw new E(J.message);throw g.error("[SessionRoutes] Failed to export session:",J),new s("Failed to export session")}}),O.post("/:sessionId/fork",async(Z)=>{let G=Z.req.param("sessionId");try{m1(G);let J=await Z.req.json(),X=f(qw,J);if(!X.success)throw new F("Invalid request body");let V=P0(X.data.projectPath),L=await C.findSessionMetadata(G,V);if(!L)throw new h("Session",G);let _=await C.forkSession(G,{sourceProjectPath:L.projectPath,targetProjectPath:L.projectPath}),D=m0(_.metadata,_.messages),H=o(D);return xO.set(P(H),D),I.publish(H,"task.status",{taskStatus:_.metadata.taskStatus,..._.metadata.taskCompletedAt?{taskCompletedAt:_.metadata.taskCompletedAt}:{},updatedAt:_.metadata.lastMessageTime}),Z.json({session:_.metadata,messages:M1(_.messages)},201)}catch(J){if(J instanceof F||J instanceof h||J instanceof E)throw J;if(J instanceof Y4)throw new E("Session has no durable creation record");throw g.error("[SessionRoutes] Failed to fork session:",J),new s("Failed to fork session")}}),O.get("/:sessionId",async(Z)=>{let G=Z.req.param("sessionId");try{let J=await BO(G,Z.req.query("projectPath")),X=xO.get(P(J));if(X)return Z.json(eO(X));let V=await C.findSessionMetadata(J.sessionId,J.projectPath);if(!V)throw new h("Session",G);return Z.json(V)}catch(J){if(J instanceof F||J instanceof h||J instanceof MO)throw J;throw g.error("[SessionRoutes] Failed to get session:",J),new s("Failed to get session")}}),O.patch("/:sessionId",async(Z)=>{let G=Z.req.param("sessionId");try{let J=await Z.req.json(),X=f(Rw,J);if(!X.success)throw new F("Invalid request body");if(X.data.title===void 0)throw new F("title is required");let V=await BO(G,X.data.projectPath),L=await C.updateSessionMetadata(V.sessionId,V.projectPath,{title:X.data.title}),_=xO.get(P(V));if(_)_.title=L.title??_.title,_.updatedAt=new Date(L.lastMessageTime);if(L.title)I.publish(V,"session.updated",{title:L.title});return Z.json({success:!0,title:L.title})}catch(J){if(g.error("[SessionRoutes] Failed to update session:",J),J instanceof F||J instanceof h||J instanceof MO)throw J;throw new s("Failed to update session")}}),O.get("/:sessionId/rewind",async(Z)=>{let G=await z(Z.req.param("sessionId"),Z.req.query("projectPath"));return bO(G,async(J)=>Z.json({checkpoints:await J.listRewindCheckpoints()}))}),O.post("/:sessionId/rewind",async(Z)=>{let G=f(F4,await Z.req.json());if(!G.success)throw new F("Invalid rewind request");let J=await z(Z.req.param("sessionId"),Z.req.query("projectPath")),X=o(J);return GO(X,async()=>{let V=LO(J.currentRunId);if(FO(V))throw new E("Cannot rewind while a run is active");return bO(J,async(L)=>{let _;try{_=await L.rewindSession(G.data)}catch(H){if(H instanceof Error&&H.message.startsWith("Cannot rewind while"))throw new E(H.message);throw H}J.messages=[..._.messages],J.updatedAt=new Date;let D=M1(_.messages);return I.publish(X,"session.rewound",{targetMessageId:_.checkpoint.messageId,mode:_.mode,removedTurns:_.removedTurns,restoredFiles:_.restoredFiles,messages:D}),Z.json({..._,messages:D})})})}),O.get("/:sessionId/review",async(Z)=>{let G=Z.req.param("sessionId"),J=await BO(G,Z.req.query("projectPath")),X=await x0.list(J.projectPath,J.sessionId);return Z.json({reviews:X.map((V)=>({...V,content:V.completion?w4(V.start,V.completion):void 0}))})}),O.post("/:sessionId/review",async(Z)=>{let G=Z.req.param("sessionId"),J=f(A4,await Z.req.json());if(!J.success)throw new F("Invalid code review request");let X=await z(G,J.data.projectPath),V=o(X),L=P(V);return GO(V,async()=>{if(FO(LO(X.currentRunId)))throw new E("Cannot start a review during an active turn");if(fO.has(L))throw new E("Session already has an active review");return bO(X,async(_)=>{if(await x0.recoverInterrupted(V.projectPath,V.sessionId,_),J.data.modelId&&!_.getModelById(J.data.modelId))throw new F(`Model not found: ${J.data.modelId}`);if(J.data.modelId&&_.getCurrentModelId()!==J.data.modelId)await _.refresh({modelId:J.data.modelId});if(J.data.modelId&&X.selectedModelId!==J.data.modelId){let M=await C.updateSessionMetadata(X.id,X.projectPath,{selectedModelId:J.data.modelId});iO(X,M)}let D=new AbortController,H;try{H=await x0.start({sessionId:V.sessionId,projectPath:V.projectPath,runtime:_,request:{kind:J.data.kind,...J.data.ref?{ref:J.data.ref}:{},...J.data.instructions?{instructions:J.data.instructions}:{}},signal:D.signal,onEvent:(M)=>{if(M.kind==="tool_start")I.publish(V,"review.tool.started",{reviewId:H?.reviewId,toolCallId:M.toolCall.id,toolName:M.toolCall.function.name});else if(M.kind==="tool_progress")I.publish(V,"review.tool.progress",{reviewId:H?.reviewId,toolCallId:M.toolCall.id,message:M.update.message.slice(0,1000)});else if(M.kind==="tool_result")I.publish(V,"review.tool.completed",{reviewId:H?.reviewId,toolCallId:M.toolCall.id,success:M.result.success})}})}catch(M){if(M instanceof Error&&(M.message.includes("active review")||M.message.includes("interrupted review")||M.message.includes("active turn")))throw new E(M.message);if(M instanceof Error&&(M.message.includes("review")||M.message.includes("Git")||M.message.includes("changes")||M.message.includes("ref")))throw new F(M.message);throw M}if(!H)throw new s("Code review failed to start");await cO(X),I.publish(V,"review.started",{reviewId:H.reviewId,kind:J.data.kind}),I.publish(V,"task.status",{taskStatus:X.taskStatus,...X.taskStatusReason?{taskStatusReason:X.taskStatusReason}:{},...X.taskStartedAt?{taskStartedAt:X.taskStartedAt}:{},...X.taskPromptSummary?{taskPromptSummary:X.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let A=H.completion.then(async(M)=>{X.messages=await C.loadSession(V.sessionId,V.projectPath),await cO(X),I.publish(V,"task.status",{taskStatus:X.taskStatus,...X.taskStatusReason?{taskStatusReason:X.taskStatusReason}:{},...X.taskFailure?{taskFailure:X.taskFailure}:{},...X.taskStartedAt?{taskStartedAt:X.taskStartedAt}:{},...X.taskCompletedAt?{taskCompletedAt:X.taskCompletedAt}:{},...X.taskPromptSummary?{taskPromptSummary:X.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),I.publish(V,"review.completed",{reviewId:H.reviewId,status:M.status,findings:M.findings.length})}).catch((M)=>{g.error(`[SessionRoutes] Code review ${H.reviewId} failed:`,M)}).finally(()=>{if(fO.get(L)?.reviewId===H.reviewId)fO.delete(L)});return fO.set(L,{reviewId:H.reviewId,controller:D,completion:A}),Z.json({reviewId:H.reviewId,status:"running"},202)})})}),O.get("/:sessionId/subagents",async(Z)=>{let G=await z(Z.req.param("sessionId"),Z.req.query("projectPath"));return bO(G,(J)=>Z.json({subagents:J.listSubagents().map(J1)}))}),O.post("/:sessionId/subagents/:agentId/resume",async(Z)=>{m1(Z.req.param("agentId"));let G=L4.safeParse(await Z.req.json());if(!G.success)throw new F("Invalid subagent resume request");let J=await z(Z.req.param("sessionId"),Z.req.query("projectPath")),X=o(J);return GO(X,async()=>{let V=LO(J.currentRunId);if(FO(V))throw new E("Cannot resume a subagent while a parent run is active");return bO(J,async(L)=>{let _=!1,D,H=(M)=>{I.publish(X,"subagent.complete",{subagentSessionId:M.id,success:M.status==="completed",status:M.status,summary:M.result?.message?.slice(0,500),type:M.subagentType,verificationVerdict:M.result?.verificationVerdict,resumedFrom:M.resumedFrom,rootAgentId:M.rootAgentId,resumeDepth:M.resumeDepth})},A;try{A=L.resumeSubagent({agentId:Z.req.param("agentId"),prompt:G.data.prompt,onEvent:(M,q)=>{hw(X,q,M)},onCompleted:(M)=>{if(_)H(M);else D=M}})}catch(M){if(M instanceof Error&&(M.message.startsWith("Cannot resume")||M.message.startsWith("Subagent cannot")))throw new E(M.message);if(M instanceof Error&&M.message.startsWith("Subagent not found"))throw new h(M.message);throw M}if(I.publish(X,"subagent.start",{subagentSessionId:A.session.id,type:A.session.subagentType,description:A.session.description,resumedFrom:A.source.id,rootAgentId:A.session.rootAgentId,resumeDepth:A.session.resumeDepth}),_=!0,D)H(D);return Z.json({source:J1(A.source),session:J1(A.session)})})})}),O.get("/:sessionId/goal",async(Z)=>{let G=await z(Z.req.param("sessionId"),Z.req.query("projectPath"));return Z.json({goal:await new W4(G.projectPath,G.id).get()})}),O.put("/:sessionId/goal",async(Z)=>{let G=f(Iw,await Z.req.json());if(!G.success)throw new F("Invalid goal request");let J=await z(Z.req.param("sessionId"),Z.req.query("projectPath")),X=o(J);return GO(X,async()=>{let V=LO(J.currentRunId);if(FO(V))return Z.json({status:"rejected",reason:"run_active"},409);let _=G.data.permissionMode??J.permissionMode??"default";if(J.permissionMode!==_)await $O(J,_);let D=await v(J),H=!1;try{let A=await D.value.createGoal(G.data);I.publish(X,"goal.updated",{goal:A});let M=J0(J,"",_,{goalContinuationOnly:!0,runtimeLease:D});return H=!0,await M.taskAdmissionUpdate,Z.json({status:M.status==="queued"?"queued":"running",runId:M.id,goal:A,queuePosition:J.taskQueuePosition,queueDepth:J.taskQueueDepth,maxConcurrentTasks:J.taskConcurrencyLimit},202)}finally{if(!H)D.release()}})}),O.patch("/:sessionId/goal",async(Z)=>{let G=f(Cw,await Z.req.json());if(!G.success)throw new F("Invalid goal update");let J=await z(Z.req.param("sessionId"),Z.req.query("projectPath")),X=o(J);return GO(X,async()=>{let V=await v(J),L=!1;try{let _=V.value,D;if(G.data.action==="pause")D=await _.pauseGoal();else if(G.data.action==="edit")D=await _.editGoal(G.data.objective);else D=await _.resumeGoal();if(I.publish(X,"goal.updated",{goal:D}),D.status==="active"&&!FO(LO(J.currentRunId))){let H=J0(J,"","default",{goalContinuationOnly:!0,runtimeLease:V});return L=!0,await H.taskAdmissionUpdate,Z.json({status:H.status==="queued"?"queued":"running",runId:H.id,goal:D,queuePosition:J.taskQueuePosition,queueDepth:J.taskQueueDepth,maxConcurrentTasks:J.taskConcurrencyLimit},202)}return Z.json({status:D.status,goal:D})}finally{if(!L)V.release()}})}),O.delete("/:sessionId/goal",async(Z)=>{let G=await z(Z.req.param("sessionId"),Z.req.query("projectPath")),J=o(G);return bO(G,async(X)=>{let V=await X.clearGoal();if(V)I.publish(J,"goal.cleared",{});return Z.json({cleared:V})})}),O.post("/:sessionId/archive",async(Z)=>{let G=Z.req.param("sessionId");try{let J=await BO(G,Z.req.query("projectPath")),X=await C.listSessionArchiveMembers(J.sessionId,J.projectPath);for(let L of X){let _=lO({sessionId:L.sessionId,projectPath:L.projectPath}),D=xO.get(P(_));if(FO(LO(D?.currentRunId)))throw new E(`Stop session ${L.sessionId} before archiving this session tree`)}for(let L of X){let _=lO({sessionId:L.sessionId,projectPath:L.projectPath}),D=xO.get(P(_));if(D)await Z0(D)}let V=await C.archiveSession(J.sessionId,J.projectPath);for(let L of X){let _=lO({sessionId:L.sessionId,projectPath:L.projectPath}),D=P(_);xO.delete(D),Y.delete(D),w.delete(D),I.publish(_,"session.archived",{archiveRootId:J.sessionId,archivedAt:V.archivedAt})}if(x.size===0)await HO.getInstance().disconnectAll();return Z.json({session:V,archivedSessionIds:X.map((L)=>L.sessionId)})}catch(J){if(J instanceof F||J instanceof h||J instanceof MO||J instanceof E)throw J;if(J instanceof E1)throw new E(J.message);throw g.error("[SessionRoutes] Failed to archive session:",J),new s("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(Z)=>{let G=Z.req.param("sessionId");try{let J=await BO(G,Z.req.query("projectPath")),X=await C.listSessionArchiveMembers(J.sessionId,J.projectPath),V=await C.unarchiveSession(J.sessionId,J.projectPath),L=X.filter((_)=>_.sessionId===J.sessionId||_.archivedBySessionId===J.sessionId).map((_)=>_.sessionId);for(let _ of L)I.publish({sessionId:_,projectPath:J.projectPath},"session.unarchived",{archiveRootId:J.sessionId});return Z.json({session:V,restoredSessionIds:L})}catch(J){if(J instanceof F||J instanceof h||J instanceof MO)throw J;if(J instanceof E1)throw new E(J.message);throw g.error("[SessionRoutes] Failed to unarchive session:",J),new s("Failed to unarchive session")}}),O.delete("/:sessionId",async(Z)=>{let G=Z.req.param("sessionId"),J=Z.req.query("projectPath");try{let X=await BO(G,J);YO(X);let V=P(X),L=xO.get(V),_=x.get(V),D=L?.taskWorktree??await C.findSessionTaskWorktree(X.sessionId,X.projectPath),H;if(L?.currentRunId){let q=LO(L.currentRunId);if(q)g0(q),await q.completion,H=q.id}let A=fO.get(V);if(A)A.controller.abort("session-delete"),await A.completion;if(_)await _.clearGoal().catch((q)=>{g.warn("[SessionRoutes] Failed to clear session goal:",q)});if(await $.dispose(X),await C.deleteSession(X.sessionId,X.projectPath),I.publish(X,"session.deleted",{}),H)Ew(H);xO.delete(V),Y.delete(V),w.delete(V);let M=x.get(V);if(M){if(!await B.remove(V,M))throw new E("Session Runtime is still active and cannot be deleted")}if(D)try{await mO.restoreSession(D),await mO.exit({sessionId:X.sessionId,action:"remove",discardChanges:!0})}catch(q){g.warn(`[SessionRoutes] Failed to remove deleted task worktree ${X.sessionId}:`,q)}return Z.json({success:!0})}catch(X){if(g.error("[SessionRoutes] Failed to delete session:",X),X instanceof F||X instanceof h||X instanceof MO)throw X;throw new s("Failed to delete session")}}),O.get("/:sessionId/message",async(Z)=>{let G=Z.req.param("sessionId");try{let J=await BO(G,Z.req.query("projectPath")),X=xO.get(P(J)),V=X?.messages?X.messages:await C.loadSession(J.sessionId,J.projectPath);return Z.json(M1(V))}catch(J){if(g.error("[SessionRoutes] Failed to get messages:",J),J instanceof F||J instanceof h||J instanceof MO)throw J;throw new s("Failed to get messages")}}),O.get("/:sessionId/events",async(Z)=>{let G=Z.req.param("sessionId"),J=await BO(G,Z.req.query("projectPath"));try{await C.assertSessionWritable(J.sessionId,J.projectPath)}catch(D){if(D instanceof k1)throw new E(D.message);throw D}let X=await KO(J),V=Z.req.header("Last-Event-ID")??Z.req.query("lastEventId"),L=V?Number.parseInt(V,10):Number.NaN,_=Number.isInteger(L)?L+1:void 0;return jw(Z,async(D)=>{let A,M,q=!1,wO,qO,_O=new Promise((k)=>{qO=k}),NO=()=>{if(M!==void 0)clearInterval(M),M=void 0;A?.(),A=void 0},QO=(k)=>{if(q)return;q=!0,NO(),wO?.close(k),qO()},N0=new Set;D.onAbort(QO),wO=new q0({write:async(k)=>{await D.writeSSE(k)},onFailure:(k)=>{g.warn(`[SessionRoutes] SSE egress closed for ${J.sessionId}: kind=${k.kind} pendingItems=${k.pendingItems??0} pendingBytes=${k.pendingBytes??0}`),QO(k)}}),A=I.subscribe((k)=>{if(k.sessionId!==J.sessionId||k.projectPath!==J.projectPath)return;let u=k.properties.requestId;if((k.type==="permission.asked"||k.type==="question.required"||k.type==="elicitation.required")&&typeof u==="string"){if(N0.has(u))return;N0.add(u)}if(k.type==="subagent.completion.queued")GO(J,()=>y(X)).catch((m)=>{g.error(`[SessionRoutes] Failed to wake background completion for ${X.id}:`,m)});if(k.type==="team.message.received"&&typeof k.properties.teamName==="string"&&typeof k.properties.messageId==="string"&&typeof k.properties.content==="string"&&V4(k.properties.metadata,{messageId:k.properties.messageId,teamName:k.properties.teamName})){let m=k.properties.teamName,p=k.properties.messageId,l=k.properties.content,d=k.properties.metadata;GO(J,async()=>{let c=await v(X),pO=!1;try{let n=await c.value.enqueueSteering(l,{allowBeforeTurn:!0,messageId:p,origin:"team_message",metadata:d});if(!n.accepted)return;await new G4(m,W1()).markDelivered([p]),pO=n.delivery==="next_turn"}finally{c.release()}if(pO)await y(X)}).catch((c)=>{g.error(`[SessionRoutes] Failed to deliver teammate message for ${X.id}:`,c)})}wO?.observe(fw(k),k.seq)});try{if(D.aborted||q)return;let k=LO(X.currentRunId),u=FO(k)?await v(X):void 0;try{let l=u?.value,d=l?.getPendingSteeringCount()??0;await wO.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:J.sessionId,projectPath:J.projectPath,timestamp:Date.now(),status:FO(k)?k.status:"idle",runId:FO(k)?k.id:void 0,queued:d,pendingInputDelivery:d>0?l?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:l?.getRecoveredSteeringCount()??0}})})}finally{u?.release()}if(D.aborted||q)return;if(_!==void 0){if(await X4.for(J.sessionId,J.projectPath).replay({onCommitted:async(d)=>{if(D.aborted||q)return;let c=mw(d);if(c.seq===void 0)return;await wO.writeReplay({...typeof d.seq==="number"?{id:String(d.seq)}:{},data:JSON.stringify({type:c.type,...c.seq!==void 0?{seq:c.seq}:{},properties:{...c.properties,sessionId:J.sessionId,projectPath:J.projectPath}})},c.seq)}},_),D.aborted||q)return}if(wO.finishInitialization({replayed:_!==void 0}),D.aborted||q)return;if(!k&&!fO.has(P(J))){let d=(await x0.list(J.projectPath,J.sessionId)).some((c)=>c.completion===void 0)?await bO(X,(c)=>x0.recoverInterrupted(J.projectPath,J.sessionId,c)):void 0;if(d)X.messages=await C.loadSession(J.sessionId,J.projectPath),await cO(X),I.publish(J,"review.completed",{reviewId:d.reviewId,status:d.status,findings:0,recovered:!0})}if(D.aborted||q)return;if(!k)await $0.recoverResponded(J.projectPath,J.sessionId);if(D.aborted||q)return;let m=k?void 0:await $0.findPending(J.projectPath,J.sessionId),p=k?.pendingPermission??(m?{permissionId:m.request.requestId,details:$0.confirmationDetails(m),resolve:()=>{return}}:void 0);if(p){N0.add(p.permissionId);let l=R4(p,!0);wO.observe({data:JSON.stringify({type:l.type,properties:{...l.properties,sessionId:J.sessionId,projectPath:J.projectPath}})})}if(D.aborted||q)return;if(y(X).catch(async(l)=>{if(l instanceof e0){await cO(X).catch(()=>{return});let d=X.taskFailure?.code==="workspace_unavailable"?X.taskFailure:N1("workspace_unavailable");X.taskStatus="failed",X.taskStatusReason=d.message,X.taskFailure=d,I.publish(J,"session.error",{error:d.message,taskFailure:d}),I.publish(J,"session.status",{status:"error"})}g.error(`[SessionRoutes] Failed to resume pending input for ${G}:`,l)}),D.aborted||q)return;M=setInterval(()=>{if(D.aborted||q)return;wO?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await _O}finally{QO()}})}),O.post("/:sessionId/message",async(Z)=>{let G=Z.req.param("sessionId"),J=await Z.req.json(),X=f(Tw,J);if(!X.success)throw new F("Invalid message format");let{content:V,attachments:L,modelId:_,reasoningEffort:D,serviceTier:H,responseVerbosity:A,communicationStyle:M,permissionMode:q,projectPath:wO,outputSchema:qO}=X.data,_O;if(qO)try{_O=C1(qO).schema}catch(d){throw new F(d instanceof Error?d.message:"Invalid output schema")}let NO=M;if(Buffer.byteLength(V,"utf8")>R1)throw new F(`Message text exceeds the ${R1}-byte limit`);let QO=_?.trim();if((L??[]).reduce((d,c)=>d+(typeof c.content==="string"?Buffer.byteLength(c.content):0),0)>X1)throw new F("Message attachments exceed the 5 MiB limit");let k=q,u=lx(V,L),m=await z(G,wO??Z.req.query("projectPath")),p=k??m.permissionMode??"default",l=o(m);return GO(l,async()=>{let d=LO(m.currentRunId);if(FO(d)){if(_O)throw new E("Wait for the active turn to finish before setting an output schema");return bO(m,async(n)=>{if(QO&&!n.getModelById(QO))throw new F(`Model not found: ${QO}`);if(QO&&n.getCurrentModelId()!==QO)throw new E("Wait for the active turn to finish before switching models");if(D&&n.getReasoningConfiguration().selection!==D)throw new E("Wait for the active turn to finish before switching reasoning effort");if(H&&n.getServiceTierConfiguration().selection!==H)throw new E("Wait for the active turn to finish before switching service tier");if(A&&n.getResponseVerbosityConfiguration().selection!==A)throw new E("Wait for the active turn to finish before switching response verbosity");if(NO&&n.getCommunicationStyleConfiguration().selection!==NO)throw new E("Wait for the active turn to finish before switching communication style");if(k&&m.permissionMode!==k)throw new E("Wait for the active turn to finish before switching permission mode");let zO=await n.enqueueSteering(u,{allowBeforeTurn:!0});if(!zO.accepted)return Z.json({status:"rejected",reason:zO.reason??"turn_unavailable"},409);let sO=zO.messageId??B0(12),T0=zO.queued;I.publish(l,"message.created",{messageId:sO,role:"user",content:h1(u)});let s0=zO.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(I.publish(l,s0,{runId:d.id,messageId:sO,queued:T0}),zO.delivery==="next_turn"&&d.status!=="running"&&d.status!=="waiting_permission")y(m).catch((r0)=>{g.error(`[SessionRoutes] Failed to wake queued follow-up for ${G}:`,r0)});if(zO.delivery==="next_turn")d.pendingFollowUpRequested=!0;return Z.json({runId:d.id,messageId:sO,status:zO.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:T0},202)})}if(YO(l),m.permissionMode!==p)await $O(m,p);let c=await v(m,{permissionMode:p,...NO&&!NO.includes(":")?{communicationStyle:NO}:{}}),pO=!1;try{let n=c.value;if(QO&&!n.getModelById(QO))throw new F(`Model not found: ${QO}`);if(D)try{n.resolveReasoningConfiguration(D,QO)}catch(VO){throw new F(VO instanceof Error?VO.message:"Invalid reasoning effort")}if(H)try{n.resolveServiceTierConfiguration(H,QO)}catch(VO){throw new F(VO instanceof Error?VO.message:"Invalid service tier")}if(A)try{n.resolveResponseVerbosityConfiguration(A,QO)}catch(VO){throw new F(VO instanceof Error?VO.message:"Invalid response verbosity")}let zO=NO?n.resolveCommunicationStyleConfiguration(NO):void 0;if(zO?.source!==void 0&&zO.source!=="built-in"&&!zO.contentSha256)throw new F("Custom communication style has no provenance");let sO=n.getCurrentModelId(),T0=n.getReasoningConfiguration(),s0=n.getServiceTierConfiguration(),r0=n.getResponseVerbosityConfiguration(),Qx=n.getCommunicationStyleConfiguration(),Zx=Boolean(QO)&&sO!==QO,Jx=Boolean(D)&&T0.selection!==D,Yx=Boolean(H)&&s0.selection!==H,Nx=Boolean(A)&&r0.selection!==A,Wx=Boolean(NO)&&Qx.selection!==NO;if(Zx||Jx||Yx||Nx||Wx)await n.refresh({...QO?{modelId:QO}:{},...D?{reasoningEffort:D}:{},...H?{serviceTier:H}:{},...A?{responseVerbosity:A}:{},...NO?{communicationStyle:NO}:{}});let F1={...QO&&m.selectedModelId!==QO?{selectedModelId:QO}:{},...D&&m.reasoningEffort!==D?{reasoningEffort:D}:{},...H&&m.serviceTier!==H?{serviceTier:H}:{},...A&&m.responseVerbosity!==A?{responseVerbosity:A}:{},...zO&&(m.communicationStyle!==NO||m.communicationStyleDigest!==zO.contentSha256)?{communicationStyle:NO,communicationStyleDigest:zO.source==="built-in"?null:zO.contentSha256}:{}};if(Object.keys(F1).length>0)try{let VO=await C.updateSessionMetadata(m.id,m.projectPath,F1);m.permissionMode=VO.permissionMode,m.selectedModelId=VO.selectedModelId,m.reasoningEffort=VO.reasoningEffort,m.serviceTier=VO.serviceTier,m.responseVerbosity=VO.responseVerbosity,m.communicationStyle=VO.communicationStyle,m.communicationStyleDigest=VO.communicationStyleDigest,m.updatedAt=new Date(VO.lastMessageTime),I.publish(l,"session.updated",F1)}catch(VO){if(Zx||Jx||Yx||Nx||Wx)await n.refresh({...sO?{modelId:sO}:{},reasoningEffort:T0.selection,serviceTier:s0.selection,responseVerbosity:r0.selection,communicationStyle:Qx.selection}).catch((l$)=>g.error("[SessionRoutes] Failed to roll back non-durable model settings:",l$));throw VO}let R0=_O?await n.prepareInputTurn(u,{outputSchema:_O}):await n.prepareInputTurn(u);if(!R0.accepted)return Z.json({status:"rejected",reason:R0.reason},R0.reason==="queue_full"?429:409);let L1=J0(m,u,p,{preparedInputTurn:R0,outputSchema:_O,runtimeLease:c});return pO=!0,await L1.taskAdmissionUpdate,Z.json({runId:L1.id,messageId:R0.messageId,status:L1.status==="queued"?"queued":"running",queuePosition:m.taskQueuePosition,queueDepth:m.taskQueueDepth,maxConcurrentTasks:m.taskConcurrencyLimit},202)}finally{if(!pO)c.release()}})}),O.post("/:sessionId/side-question",async(Z)=>{let G=Z.req.param("sessionId"),J=f(b4,await Z.req.json());if(!J.success)throw new F("Invalid side conversation request");let X=await z(G,J.data.projectPath??Z.req.query("projectPath"));return bO(X,async(V)=>{let L=await V.askSideQuestion(J.data.question,{signal:Z.req.raw.signal});return Z.json({...L,...V.getCurrentModelId()?{modelId:V.getCurrentModelId()}:{}})})}),O.post("/:sessionId/shell",async(Z)=>{let G=Z.req.param("sessionId"),J=f(H4,await Z.req.json());if(!J.success)throw new F("Invalid user shell command");let X=await z(G,J.data.projectPath??Z.req.query("projectPath")),V=o(X),L=P(V);return GO(V,async()=>{if(uO.has(L))throw new E("A user shell command is already running in this Session");let _=await v(X),D=_.value,H=new AbortController,A,M=new Promise((q)=>{A=q});uO.set(L,{controller:H,completion:M});try{let q=await D.executeUserShellCommand(J.data.command,{signal:H.signal});X.messages=await C.loadSession(X.id,X.projectPath),X.updatedAt=new Date;let wO=LO(X.currentRunId);if(q.delivery==="next_turn"&&FO(wO))wO.pendingFollowUpRequested=!0;return Z.json({executionId:q.executionId,messageId:q.messageId,record:q.record,auxiliary:q.auxiliary,...q.delivery?{delivery:q.delivery}:{},...q.queued!==void 0?{queued:q.queued}:{}})}finally{uO.delete(L),A(),_.release()}})}),O.post("/:sessionId/abort",async(Z)=>{let G=Z.req.param("sessionId"),J=await BO(G,Z.req.query("projectPath"));YO(J);let X=xO.get(P(J));if(X?.currentRunId){let _=LO(X.currentRunId);if(_)g0(_),await _.completion}let V=uO.get(P(J));if(V)V.controller.abort("user-cancel"),await V.completion;let L=fO.get(P(J));if(L)L.controller.abort("user-cancel"),await L.completion;return Z.json({success:!0})}),O.get("/:sessionId/status",async(Z)=>{let G=Z.req.param("sessionId"),J=await BO(G,Z.req.query("projectPath")),X=xO.get(P(J)),V=fO.get(P(J));if(V)return Z.json({sessionId:G,projectPath:J.projectPath,reviewId:V.reviewId,status:"reviewing"});if(!X?.currentRunId)return Z.json({sessionId:G,projectPath:J.projectPath,status:"idle"});let L=LO(X.currentRunId);return Z.json({sessionId:G,projectPath:J.projectPath,runId:X.currentRunId,status:L?.status==="attention_required"?"idle":L?.status??"idle"})}),{app:O,dispatchTask:Y0,retryTask:n0,updateTask:t0,getTaskDiff:K1,deliverTask:d$,recoverQueuedTasks:v$,getRuntimeResidencyStats:()=>B.getStats(),getCoordinationStats:()=>({messageSubmissions:N.getStats(),taskDeliveries:K.getStats()}),shutdown:(Z="server-shutdown")=>{if(U)return U;return j.close(Z),clearInterval(b),r(),U=(async()=>{let G,J=async(D)=>{let H=await Promise.allSettled(D);for(let A of H)if(A.status==="rejected")G??=A.reason},X=new Set,V=()=>{for(let D of yO.values()){if(D.completion)X.add(D.completion);if(FO(D))g0(D,Z)}for(let D of uO.values())D.controller.abort(Z),X.add(D.completion);for(let D of fO.values())D.controller.abort(Z),X.add(D.completion)},L=j.waitForIdle(),_=!1;L.then(()=>{_=!0});while(!_)V(),await Promise.race([L,new Promise((D)=>setImmediate(D))]);if(await L,V(),await J([...X]),await J([...w.values()]),V(),await J([...X]),await J([B.disposeAll()]),x.clear(),await J([...Q.values()]),await J([$.disposeAll()]),await J([HO.getInstance().disconnectAll()]),w.clear(),Q.clear(),Y.clear(),xO.clear(),_0===y)_0=void 0;if(h0===r)h0=void 0;if(G!==void 0)throw G})(),U}}};async function gw(O,x,$,w,Q,Y={}){let{abortController:N,sessionId:K,id:S}=O,B=Y.preparedInputTurn?.messageId??B0(12),b=Y.pendingInputOnly===!0||Y.preparedInputTurn?.mode==="pending"||Y.goalContinuationOnly===!0?void 0:B0(12),U=Y.runtimeLease,R,JO,y=!1,r=!1,ZO,GO=o(x),YO=async(i)=>{let XO=i.metadata?.recoveryAttention;if(!XO||!R)return!1;if(Y.preparedInputTurn)await R.finishTurn(Y.preparedInputTurn.handle,{preserveStartupRecovery:!0,outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}}).catch(()=>{return});let UO=`Turn recovery requires attention: ${XO.reason}`,SO=await R.setTaskStatus("interrupted",UO).catch(()=>{return});if(SO)iO(x,SO);else x.taskStatus="interrupted",x.taskStatusReason=UO,x.taskCompletedAt=void 0;return O.status="attention_required",T("session.status",{status:"idle"}),!0},T=(i,XO)=>{I.publish(GO,i,XO)},jO=async()=>{let i=String(N.signal.reason||"Task run cancelled");if(x.taskIsolation){if(!U)U=await Q(x).catch(()=>{return});let XO=R??U?.value;if(i==="user-cancel")await XO?.discardPendingInput().catch((SO)=>{g.warn(`[SessionRoutes] Failed to discard cancelled input for ${x.id}:`,SO)});let UO=await XO?.setTaskStatus("cancelled",i).catch(()=>{return});if(UO)iO(x,UO);else await cO(x).catch(()=>{return})}x.taskStatus="cancelled",x.taskStatusReason=i,x.taskCompletedAt??=new Date().toISOString()};try{if(Y.pendingResume){let z=Y.pendingResume.deadlineAt-Date.now();if(z<=0)N.abort(Z1);else ZO=setTimeout(()=>{N.abort(Z1);let $O=O.pendingPermission;if(O.pendingPermission=void 0,$O?.resolve({approved:!1,reason:g1}),$O)T("interaction.resolved",{requestId:$O.permissionId})},z),ZO.unref?.()}if(Y.taskAdmission){if(await Y.taskAdmission.ready,await O.taskAdmissionUpdate,N.signal.aborted)throw Error(String(N.signal.reason||"Task run cancelled"))}if(x.taskStatus="running",x.taskStatusReason=void 0,x.taskStartedAt=new Date().toISOString(),x.taskCompletedAt=void 0,!Y.pendingInputOnly&&!Y.goalContinuationOnly)T("message.created",{messageId:B,role:"user",content:h1($)});if(T("session.status",{status:"running"}),b)T("message.created",{messageId:b,role:"assistant",content:""});U??=await Q(x),R=U.value;let i=R,XO=Boolean(Y.outputSchema??i.getPendingSteeringMessages().find((z)=>z.outputSchema)?.outputSchema);JO=await K4.createWithRuntime(i,{sessionId:K,...x.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let UO=async(z)=>{let $O=z.interactionRequestId??B0(12),J0=300000;O.status="waiting_permission";let U1=new Promise((t0)=>{let K1=setTimeout(()=>{g.warn(`[SessionRoutes] Permission ${$O} timed out after 300000ms`),T("permission.timeout",{requestId:$O}),t0({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:$O,resolve:(_1)=>{clearTimeout(K1),t0(_1)},details:z}}),Y0=O.pendingPermission;if(!Y0)throw Error("Permission request was not registered");let o0=R4(Y0);T(o0.type,o0.properties),g.info(`[SessionRoutes] Permission request created: ${$O}, runId: ${S}`);let n0=await U1;if(g.info(`[SessionRoutes] Permission response received: ${$O}, approved: ${n0.approved}`),!N.signal.aborted)O.status="running";if(O.pendingPermission===Y0)O.pendingPermission=void 0;return T("interaction.resolved",{requestId:$O}),n0},RO={messages:await C.loadSessionModelContext(x.id,x.projectPath),userId:"web-user",sessionId:K,workspaceRoot:x.projectPath,signal:N.signal,permissionMode:w,onPermissionModeChange:async(z)=>{x.permissionMode=z,x.updatedAt=new Date,T("session.updated",{permissionMode:z})},...x.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:UO}},v=()=>{if(!b)b=B0(12),T("message.created",{messageId:b,role:"assistant",content:""});return b},bO=async(z)=>{switch(z.kind){case"content_delta":if(z.delta.length>0)y=!0;if(XO)break;T("message.delta",{messageId:v(),delta:z.delta});break;case"structured_output":y=!0,T("structured.output",{messageId:v(),output:z.output,schemaDigest:z.schemaDigest});break;case"thinking_delta":if(z.delta.length>0)y=!0;T("thinking.delta",{messageId:v(),delta:z.delta});break;case"tool_start":if(r=!0,"function"in z.toolCall){if(z.toolCall.function.name===K0)break;T("tool.start",{messageId:v(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,arguments:z.toolCall.function.arguments,toolKind:z.toolKind})}break;case"tool_result":if(r=!0,"function"in z.toolCall){if(z.toolCall.function.name===K0)break;T("tool.result",{messageId:v(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,success:z.result.success,summary:z.result.metadata?.summary,output:l0(d0(v0(z.toolCall.function.name,z.result),p0)),metadata:u0(z.toolCall.function.name,z.result.metadata)})}break;case"tool_progress":if(r=!0,"function"in z.toolCall){if(z.toolCall.function.name===K0)break;T("tool.progress",{messageId:v(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,...z.update})}break;case"token_usage":T("token.usage",{...z.usage});break;case"turn_start":T("turn.started",{turn:z.turn,maxTurns:z.maxTurns});break;case"turn_recovery":T("turn.recovery",{assessment:z.assessment});break;case"provider_admission":T("provider.admission",{phase:z.phase,requestClass:z.requestClass,resource:z.resource,scope:z.scope,reason:z.reason,queuePosition:z.queuePosition,queueDepth:z.queueDepth,inFlight:z.inFlight,limit:z.limit,waitMs:z.waitMs,maxWaitMs:z.maxWaitMs,recoveryRemainingMs:z.recoveryRemainingMs});break;case"provider_circuit":T("provider.circuit",{phase:z.phase,reason:z.reason,statusCode:z.statusCode,retryAfterMs:z.retryAfterMs,nextProbeAt:z.nextProbeAt,openDurationMs:z.openDurationMs,sampleCount:z.sampleCount,failureCount:z.failureCount,recoveryRemainingMs:z.recoveryRemainingMs});break;case"provider_retry":T("provider.retry",{phase:z.phase,attempt:z.attempt,maxRetries:z.maxRetries,reason:z.reason,statusCode:z.statusCode,delayMs:z.delayMs,nextRetryAt:z.nextRetryAt,mode:z.mode,recoveryBudgetMs:z.recoveryBudgetMs,recoveryElapsedMs:z.recoveryElapsedMs,recoveryRemainingMs:z.recoveryRemainingMs,exhaustedBy:z.exhaustedBy});break;case"provider_stall":T("provider.stall",{phase:z.phase,stallCount:z.stallCount,durationMs:z.durationMs,warningAfterMs:z.warningAfterMs,timeoutMs:z.timeoutMs,outputStarted:z.outputStarted});break;case"action_stationarity":T("action.stationarity",{phase:z.phase,toolName:z.toolName,runLength:z.runLength,nudgeThreshold:z.nudgeThreshold,haltThreshold:z.haltThreshold,progressAware:z.progressAware});break;case"mcp_catalog_changed":T("mcp.catalog.changed",{messageId:v(),revision:z.revision,serverName:z.serverName,added:z.added,removed:z.removed,updated:z.updated});break;case"mcp_content_changed":T("mcp.content.changed",{messageId:v(),revision:z.revision,serverName:z.serverName,contentKind:z.contentKind,added:z.added,removed:z.removed,updated:z.updated});break;case"mcp_resource_updated":T("mcp.resource.updated",{messageId:v(),revision:z.revision,serverName:z.serverName,uri:z.uri});break;case"mcp_connection_changed":T("mcp.connection.changed",{messageId:v(),revision:z.revision,serverName:z.serverName,phase:z.phase,reason:z.reason,attempt:z.attempt,maxAttempts:z.maxAttempts,nextRetryAt:z.nextRetryAt,error:z.error});break;case"mcp_log":T("mcp.log",{messageId:v(),revision:z.revision,serverName:z.serverName,level:z.level,logger:z.logger,message:z.message,projectedBytes:z.projectedBytes,dataSha256:z.dataSha256,truncated:z.truncated,detailsOmitted:z.detailsOmitted,timestamp:z.timestamp,synthetic:z.synthetic});break;case"mcp_instructions_changed":T("mcp.instructions.changed",{messageId:v(),revision:z.revision,serverName:z.serverName,action:z.action,reason:z.reason,text:z.text,sourceBytes:z.sourceBytes,projectedBytes:z.projectedBytes,sha256:z.sha256,truncated:z.truncated,detailsOmitted:z.detailsOmitted});break;case"mcp_task_changed":T("mcp.task.changed",{messageId:v(),revision:z.revision,taskId:z.taskId,serverName:z.serverName,toolName:z.toolName,status:z.status,statusMessage:z.statusMessage,createdAt:z.createdAt,updatedAt:z.updatedAt,completedAt:z.completedAt,hasResult:z.hasResult,error:z.error});break;case"project_rules_loaded":T("project.rules.loaded",{messageId:v(),files:z.files,triggerPaths:z.triggerPaths,blockedWrite:z.blockedWrite});break;case"steering_applied":T("steering.applied",{runId:S,messageIds:z.messageIds,count:z.count,recovered:z.recovered,delivery:z.delivery,queued:i.getPendingSteeringCount()});break;case"follow_up_started":{if(b)T("message.complete",{messageId:b}),b=void 0;for(let $O of z.messages){if(!$O.recovered||$O.persisted)continue;if(Y.pendingResume?.projectedInputIds.has($O.id))continue;T("message.created",{messageId:$O.id,role:"user",content:h1($O.content),recovered:!0}),Y.pendingResume?.projectedInputIds.add($O.id)}T("follow_up.started",{runId:S,queued:z.queued,recovered:z.recovered}),v();break}case"goal_updated":T("goal.updated",{goal:z.goal});break;case"goal_continuation_started":T("goal.continuation.started",{goal:z.goal,continuation:z.continuation,...z.prematureStopPattern?{prematureStopPattern:z.prematureStopPattern}:{},...z.prematureStopCount!==void 0?{prematureStopCount:z.prematureStopCount}:{}}),v();break;case"compaction":T(z.phase==="start"?"compaction.started":"compaction.completed",{...z.reason?{reason:z.reason}:{},...z.strategy?{strategy:z.strategy}:{},...z.outcome?{outcome:z.outcome}:{},...z.preTokens!==void 0?{preTokens:z.preTokens}:{},...z.preTokenSource?{preTokenSource:z.preTokenSource}:{},...z.estimatedPendingTokens!==void 0?{estimatedPendingTokens:z.estimatedPendingTokens}:{},...z.postTokens!==void 0?{postTokens:z.postTokens}:{},...z.sampleAttempts!==void 0?{sampleAttempts:z.sampleAttempts}:{},...z.inputReductions!==void 0?{inputReductions:z.inputReductions}:{},...z.messagesOmitted!==void 0?{messagesOmitted:z.messagesOmitted}:{},...z.filesOmitted!==void 0?{filesOmitted:z.filesOmitted}:{},...z.imagesOmitted!==void 0?{imagesOmitted:z.imagesOmitted}:{},...z.fallbackTargetTokens!==void 0?{fallbackTargetTokens:z.fallbackTargetTokens}:{},...z.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:z.fallbackMessagesOmitted}:{},...z.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:z.fallbackMessagesTruncated}:{},...z.failureReason?{failureReason:z.failureReason}:{}});break;case"model_fallback":T("model.fallback",{});break;case"task_update":T("task.updated",{tasks:z.tasks});break;case"goal_frontier_updated":T("goal.frontier.updated",{goalId:z.goal.goalId,goalStatus:z.goal.status,frontier:z.frontier,stall:z.goal.frontierStall});break;default:break}},Z0=(z)=>{let $O=z.metadata?.toolCallsCount;return new Y1({taskFailure:U0(z.error?.details??z.error?.message??"Agent run failed"),outputStarted:y,toolExecutionStarted:r,toolCallsCount:typeof $O==="number"&&Number.isInteger($O)?$O:-1})},KO=await f1(JO.chatStream($,RO,{stream:!0,pendingInputOnly:Y.pendingInputOnly,preparedInputTurn:Y.preparedInputTurn,goalContinuationOnly:Y.goalContinuationOnly,outputSchema:Y.outputSchema,taskAdmission:Y.taskAdmission}),bO);if(await YO(KO))return;if(!KO.success)throw Z0(KO);for(let z=0;z<20;z++){let $O=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,i.getPendingSteeringCount()===0){if(!$O)break;continue}if(N.signal.aborted)break;if(KO=await f1(JO.chatStream("",RO,{stream:!0,pendingInputOnly:!0,taskAdmission:Y.taskAdmission}),bO),await YO(KO))return;if(!KO.success)throw Z0(KO)}if(x.messages=await C.loadSession(x.id,x.projectPath),x.updatedAt=new Date,await cO(x),Y.pendingResume&&N.signal.aborted&&N.signal.reason===Z1)throw new Y1({taskFailure:N1("timeout"),outputStarted:y,toolExecutionStarted:r,toolCallsCount:Number.isInteger(KO.metadata?.toolCallsCount)?KO.metadata?.toolCallsCount??-1:-1});if(N.signal.aborted||O.status==="cancelled"){await jO(),T("session.status",{status:"idle"});return}if(Y.pendingResume)Y.onPendingResumeSuccess?.(Y.pendingResume);if(b)T("message.complete",{messageId:b});T("thinking.completed",{}),O.status="completed",x.taskStatus="completed",x.taskCompletedAt??=new Date().toISOString(),T("session.completed",{runId:S,outputTruncated:KO.metadata?.outputTruncated??!1}),T("session.status",{status:"idle"})}catch(i){if(R&&Y.preparedInputTurn)await(R.getTurnRecoveryAssessment().state==="requires_attention"?R.finishTurn(Y.preparedInputTurn.handle,{preserveStartupRecovery:!0}):R.finishTurn(Y.preparedInputTurn.handle)).catch(()=>{return});let XO=Y.pendingResume!==void 0&&N.signal.aborted&&N.signal.reason===Z1;if(N.signal.aborted&&!XO||O.status==="cancelled"){if(Y.pendingResume)Y.onPendingResumeCancelled?.(Y.pendingResume);g0(O,"runtime-abort"),await jO(),T("session.status",{status:"idle"});return}let UO=i instanceof Y1?i.evidence:XO?{taskFailure:N1("timeout"),outputStarted:y,toolExecutionStarted:r,toolCallsCount:-1}:Y.pendingResume?{taskFailure:U0(i),outputStarted:!0,toolExecutionStarted:!0,toolCallsCount:-1}:void 0,SO=Y.pendingResume!==void 0&&UO!==void 0&&Y.onPendingResumeFailure?.(Y.pendingResume,UO,XO||(R?.getPendingSteeringCount()??0)>0,XO)===!0;if(O.status="failed",SO){let v=await R?.setTaskStatus("running").catch(()=>{return});if(v)iO(x,v);x.taskStatus="running",x.taskStatusReason=void 0,x.taskFailure=void 0,x.taskCompletedAt=void 0,T("session.status",{status:"running"});return}await cO(x).catch(()=>{return}),g.error("[SessionRoutes] Agent execution error:",i),x.taskStatus="failed",x.taskCompletedAt??=new Date().toISOString();let RO=UO?.taskFailure??U0(i);if(!x.taskFailure){let v=R?await R.setTaskStatus("failed",i).catch(()=>{return}):await C.updateSessionMetadata(x.id,x.projectPath,{taskStatus:"failed",taskStatusReason:RO.message,taskFailure:RO,taskCompletedAt:x.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(v)iO(x,v)}x.taskStatusReason??=RO.message,x.taskFailure??=RO,T("session.error",{error:x.taskFailure.message,taskFailure:x.taskFailure}),T("session.status",{status:"error"})}finally{if(ZO)clearTimeout(ZO);if(Y.taskAdmission?.release(),Y.taskAdmission){let i=dO.getStats();T("task.status",{taskStatus:x.taskStatus,...x.taskStatusReason?{taskStatusReason:x.taskStatusReason}:{},...x.taskFailure?{taskFailure:x.taskFailure}:{},...x.taskStartedAt?{taskStartedAt:x.taskStartedAt}:{},...x.taskCompletedAt?{taskCompletedAt:x.taskCompletedAt}:{},...x.taskDiffStat?{taskDiffStat:x.taskDiffStat}:{},taskQueueDepth:i.queued,taskConcurrencyLimit:i.maxConcurrent,taskInFlight:i.inFlight,taskAdmissionPaused:i.paused,updatedAt:new Date().toISOString()})}if(await JO?.destroy().catch(()=>{return}),U?.release(),O.disposeRuntimeOnSettle&&Y.disposeRuntime)await Y.disposeRuntime(x,R).catch((i)=>{g.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${x.id}:`,i)});kw(O)}}async function I4(O,x,$){g.info(`[SessionRoutes] Looking for permission ${x} in session ${O.sessionId}`),g.info(`[SessionRoutes] Active runs: ${yO.size}`);for(let[Y,N]of yO.entries())if(g.info(`[SessionRoutes] Checking run ${Y}: sessionId=${N.sessionId}, projectPath=${N.projectPath}, pendingPermission=${N.pendingPermission?.permissionId}`),N.sessionId===O.sessionId&&N.projectPath===O.projectPath&&N.pendingPermission?.permissionId===x){if(N.pendingPermission.details.interactionRequestId)await $0.respond(O.projectPath,O.sessionId,x,$);return N.pendingPermission.resolve($),g.info(`[SessionRoutes] Permission ${x} responded, runId: ${N.id}`),!0}let w=await $0.findPending(O.projectPath,O.sessionId);if(!w||w.request.requestId!==x)return g.error(`[SessionRoutes] Permission not found: ${x}`),!1;await $0.respondAndRecover(O.projectPath,O.sessionId,x,$);let Q=xO.get(P(O));if(!Q){let Y=await C.findSessionMetadata(O.sessionId,O.projectPath);if(!Y)return!1;let[N,K]=await Promise.all([C.loadSession(O.sessionId,O.projectPath),C.findSessionTaskWorktree(O.sessionId,O.projectPath)]);Q=m0(Y,N,K),xO.set(P(O),Q)}else await cO(Q);if(I.publish(O,"interaction.resolved",{requestId:x}),_0)_0(Q).catch((Y)=>{g.error(`[SessionRoutes] Failed to resume recovered interaction ${x}:`,Y)});return!0}var p1=t("Service"),pw=W.Object({approved:W.Boolean(),remember:W.Optional(W.Boolean()),scope:W.Optional(OO(["once","session","project"])),targetMode:W.Optional(OO(["default","autoEdit","plan","yolo"])),feedback:W.Optional(W.String({maxLength:4000})),answers:W.Optional(W.Record(W.String({maxLength:80}),W.Union([W.String({maxLength:4000}),W.Array(W.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:W.Optional(W.Object({action:OO(["accept","decline","cancel"]),content:W.Optional(W.Record(W.String(),W.Union([W.String({maxLength:4000}),W.Number(),W.Boolean(),W.Array(W.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),C4=()=>{let O=new uw;return O.post("/:permissionId",async(x)=>{let $=x.req.param("permissionId"),w=x.req.query("sessionId"),Q=x.req.query("projectPath");p1.info(`[PermissionRoutes] Received permission response: permissionId=${$}, sessionId=${w}`);try{let Y=await x.req.json(),N=f(pw,Y);if(!N.success)throw new F("Invalid permission response format");let{approved:K,remember:S,scope:B,targetMode:j,feedback:b,answers:U,elicitation:R}=N.data;if(!w)throw new F("sessionId query parameter is required");let JO=await BO(w,Q);if(!await I4(JO,$,{approved:K,reason:b,scope:B,targetMode:j,feedback:b,answers:U,elicitation:R}))throw new h("Permission request",$);return p1.info(`[PermissionRoutes] Permission ${$} ${K?"approved":"denied"}`),x.json({success:!0,approved:K,remember:S})}catch(Y){if(p1.error("[PermissionRoutes] Failed to respond to permission:",Y),Y instanceof F||Y instanceof MO||Y instanceof h||Y instanceof e)throw Y;throw Y}}),O};import k4 from"node:path";import{Hono as dw}from"hono";var vw=W.Object({projectPath:W.String({minLength:1}),enabled:W.Boolean(),scope:W.Optional(OO(["local","project","global"]))}),lw=W.Object({projectPath:W.String({minLength:1})}),iw=W.Object({projectPath:W.String({minLength:1}),source:W.String({minLength:1}),trust:W.Literal(!0),ref:W.Optional(W.String({minLength:1}))}),cw=W.Object({projectPath:W.String({minLength:1}),trust:W.Literal(!0)}),aw=W.Object({projectPath:W.String({minLength:1}),confirm:W.Literal(!0)}),ow=W.Object({projectPath:W.String({minLength:1}),source:W.String({minLength:1}),ref:W.Optional(W.String({minLength:1}))}),E4=W.Object({projectPath:W.String({minLength:1}),confirm:W.Optional(W.Literal(!0))}),nw=W.Object({projectPath:W.String({minLength:1}),scope:W.Optional(OO(["local","project","global"])),policy:W.Object({restrictToAllowedSources:W.Boolean(),requireGitCommitSha:W.Boolean(),allowedGitHosts:W.Array(W.String()),allowedMarketplaces:W.Array(W.String()),allowedLocalRoots:W.Array(W.String())})});function IO(O){if(!O||!k4.isAbsolute(O))throw new F("projectPath must be absolute");return k4.resolve(O)}async function f4(O){let[x,$]=await Promise.all([kO(O),C0.getInstance().loadWorkspacePluginSettingsResolution(O)]);return x.plugins.getAll().map((w)=>({name:w.manifest.name,description:w.manifest.description,version:w.manifest.version,source:w.source,enabled:w.status==="active",status:w.status,commands:w.commands.length,skills:w.skills.length,agents:w.agents.length,hooks:w.hooks?Object.values(w.hooks).reduce((Q,Y)=>Q+(Array.isArray(Y)?Y.length:0),0):0,mcpServers:Object.keys(w.mcpServers??{}).length,configurable:w.source!=="cli",managed:w.installation!==void 0,marketplace:w.installation?.source.type==="marketplace"?w.installation.source.marketplace:void 0,revision:w.installation?.revision,installedAt:w.installation?.installedAt,updatedAt:w.installation?.updatedAt,compatibilityIssues:w.compatibilityIssues??[],effectiveScope:w.source==="cli"?"invocation":$.settings[w.manifest.name]?.effectiveScope??"default",settingLayers:w.source==="cli"?{invocation:!0}:$.settings[w.manifest.name]?.layers??{}}))}async function tw(){let O=y4(),[x,$]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),w=new Map($.map((Q)=>[Q.name,Q]));return x.map(({marketplace:Q,manifest:Y})=>({name:Q.name,description:Y.description??Y.metadata?.description??"",sourceType:Q.source.type,revision:Q.revision,updatedAt:Q.updatedAt,plugins:Y.plugins.map((N)=>{let K=w.get(N.name);return{name:N.name,description:N.description??"",version:N.version,category:N.category,tags:N.tags??[],installed:K!==void 0,installedVersion:K?.version}})}))}function F0(O,x){if(!O.success)throw new F(O.error??x)}var i4=()=>{let O=new dw;return O.get("/",async(x)=>{let $=IO(x.req.query("projectPath"));return x.json(await f4($))}),O.post("/refresh",async(x)=>{let $=f(lw,await x.req.json());if(!$.success)throw new F("Invalid plugin refresh request");let w=IO($.data.projectPath),Q=await m4(w);return x.json({plugins:await f4(w),errors:Q.discovery.errors.map((Y)=>({code:Y.code??"LOAD_ERROR",error:Y.error}))})}),O.get("/catalog",async(x)=>{return IO(x.req.query("projectPath")),x.json(await tw())}),O.get("/policy",async(x)=>{let $=IO(x.req.query("projectPath")),w=await C0.getInstance().loadWorkspacePluginSourcePolicy($);return x.json({policy:w,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async(x)=>{let $=f(nw,await x.req.json());if(!$.success)throw new F("Invalid plugin source policy request");let w=IO($.data.projectPath),Q=await h4(w,$.data.policy,$.data.scope??"global");return x.json({policy:Q})}),O.post("/install",async(x)=>{let $=f(iw,await x.req.json());if(!$.success)throw new F("Invalid plugin install request; explicit source trust is required");let w=IO($.data.projectPath),{result:Q}=await g4(w,$.data.source,{trusted:$.data.trust,ref:$.data.ref});return F0(Q,"Plugin installation failed"),x.json({name:Q.pluginName,version:Q.manifest?.version,revision:Q.installation?.revision,changed:Q.changed,installedDependencies:Q.installedDependencies??[]})}),O.post("/marketplaces",async(x)=>{let $=f(ow,await x.req.json());if(!$.success)throw new F("Invalid marketplace add request");let w=IO($.data.projectPath),Q=await d4(w,$.data.source,$.data.ref);return F0(Q,"Marketplace installation failed"),x.json({name:Q.marketplace?.name,plugins:Q.manifest?.plugins.length??0,revision:Q.marketplace?.revision,changed:Q.changed})}),O.post("/marketplaces/:name/refresh",async(x)=>{let $=f(E4,await x.req.json());if(!$.success)throw new F("Invalid marketplace refresh request");let w=await v4(IO($.data.projectPath),x.req.param("name"));return F0(w,"Marketplace refresh failed"),x.json({name:w.marketplace?.name,plugins:w.manifest?.plugins.length??0,revision:w.marketplace?.revision,changed:w.changed})}),O.post("/marketplaces/:name/remove",async(x)=>{let $=f(E4,await x.req.json());if(!$.success||$.data.confirm!==!0)throw new F("Invalid marketplace removal request; explicit confirmation is required");IO($.data.projectPath);let w=await l4(x.req.param("name"),!0);return F0(w,"Marketplace removal failed"),x.json({name:w.marketplace?.name,removed:!0})}),O.post("/:name/update",async(x)=>{let $=f(cw,await x.req.json());if(!$.success)throw new F("Invalid plugin update request; explicit source trust is required");let w=IO($.data.projectPath),{result:Q}=await u4(w,x.req.param("name"),{trusted:$.data.trust});return F0(Q,"Plugin update failed"),x.json({name:Q.pluginName,version:Q.manifest?.version,revision:Q.installation?.revision,changed:Q.changed,updatedDependencies:Q.updatedDependencies??[]})}),O.post("/:name/uninstall",async(x)=>{let $=f(aw,await x.req.json());if(!$.success)throw new F("Invalid plugin uninstall request; explicit confirmation is required");let w=IO($.data.projectPath),{result:Q}=await p4(w,x.req.param("name"),$.data.confirm);return F0(Q,"Plugin uninstall failed"),x.json({name:Q.pluginName,removed:!0})}),O.post("/:name/state",async(x)=>{let $=f(vw,await x.req.json());if(!$.success)throw new F("Invalid plugin state request");let w=IO($.data.projectPath),Q=x.req.param("name"),N=(await kO(w)).plugins.get(Q);if(!N)throw new h("Plugin",Q);if(N.source==="cli")throw new F(`Plugin "${Q}" was loaded with --plugin-dir and is invocation-scoped`);let K=await P4(w,Q,$.data.enabled,$.data.scope??"local");return x.json(K)}),O};import{Hono as x2}from"hono";import{execFile as sw}from"node:child_process";import rw from"node:path";var l1="__BLADE_DIRECTORY_PICKER_CANCELLED__",ew=900000;function O2(O,x){return new Promise(($)=>{sw(O,[...x],{timeout:ew,maxBuffer:65536,windowsHide:!0},(w,Q,Y)=>{let N=w?.code;$({stdout:Q,stderr:Y,exitCode:typeof N==="number"?N:w?1:0,...typeof N==="string"?{errorCode:N}:{}})})})}function d1(O){let x=O.replace(/[\r\n]+$/,"");if(!x||x===l1)return{cancelled:!0};if(!rw.isAbsolute(x))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:x}}function v1(O){return O.exitCode!==0||Boolean(O.errorCode)}class c4{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??O2}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 "${l1}"`,"end try"].join(`
|
|
8
|
-
`),x=await this.runCommand("osascript",["-e",O]);if(v1(x))throw Error("Unable to open the macOS folder picker");return d1(x.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("${l1}")`,"}"].join("; "),x=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(v1(x))throw Error("Unable to open the Windows folder picker");return d1(x.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 x of O){let $=await this.runCommand(x.command,x.args);if($.errorCode==="ENOENT")continue;if($.exitCode===1&&!$.stdout.trim()&&!$.stderr.trim())return{cancelled:!0};if(v1($))throw Error("Unable to open the Linux folder picker");return d1($.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var a4=new c4;var $2=W.Object({path:W.String({minLength:1})});function w2(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let x=new URL(O).hostname;return x==="localhost"||x==="127.0.0.1"||x==="::1"||x==="[::1]"}catch{return!1}}var o4=(O={})=>{let x=new x2,$=O.pickDirectory??(()=>a4.pick()),w=O.allowDirectoryPickerRequest??w2;return x.get("/",async(Q)=>{return Q.json(await G1.list(a()))}),x.post("/",async(Q)=>{let Y;try{Y=await Q.req.json()}catch{throw new F("A valid JSON body is required")}let N=f($2,Y);if(!N.success)throw new F("A project path is required");try{let K=await G1.bind(N.data.path,a());return Q.json(K,201)}catch(K){throw new F(K instanceof Error?K.message:"Failed to bind project")}}),x.post("/pick",async(Q)=>{if(!w(Q.req.header("Origin")))throw new e("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Q.json(await $())}catch(Y){throw new F(Y instanceof Error?Y.message:"Failed to select a folder")}}),x.delete("/",async(Q)=>{let Y=Q.req.query("path");if(!Y)throw new F("A project path is required");try{let N=await G1.unbind(Y);return Q.json({success:!0,removed:N})}catch(N){throw new F(N instanceof Error?N.message:"Failed to unbind project")}}),x};import{Hono as Q2}from"hono";var n4=t("Service"),e4=()=>{let O=new Q2;return O.get("/",async(x)=>{try{let $=await s4();return x.json($)}catch($){return n4.error("[ProviderRoutes] Failed to list providers:",$),x.json([])}}),O.get("/:provider/models",async(x)=>{let $=x.req.param("provider");try{let w=await r4($);return x.json(w)}catch(w){return n4.error("[ProviderRoutes] Failed to list models:",w),x.json([])}}),O.put("/:provider/credential",async(x)=>{let $=x.req.param("provider"),w=await x.req.json();if(!w.apiKey?.trim())throw new F("apiKey is required");return await rO().setApiKey($,w.apiKey.trim()),x.json({success:!0})}),O.delete("/:provider/credential",async(x)=>{return await rO().clearCredential(x.req.param("provider")),x.json({success:!0})}),O.put("/:provider",async(x)=>{let $=x.req.param("provider"),w=WO(),Q=w?.modelProviders[$];if(!w||!Q)throw new h("Model provider",$);let Y=await x.req.json();if(!Y.name||!Y.baseUrl||!Y.wireApi)throw new F("name, baseUrl and wireApi are required");let N="apiKeyEnv"in Y?Y.apiKeyEnv?.trim():Q.apiKeyEnv,K={name:Y.name,baseUrl:Y.baseUrl,wireApi:Y.wireApi,...N?{apiKeyEnv:N}:{}},S=rO(),B=Y.apiKey?.trim()?await S.credentials.read($):void 0;if(Y.apiKey?.trim())await S.setApiKey($,Y.apiKey.trim());try{return await TO().updateModelProvider($,K),x.json({success:!0})}catch(j){if(Y.apiKey?.trim())if(B)await S.credentials.modify($,async()=>B);else await S.credentials.delete($);if(j instanceof Error&&(j.message.includes("modelProviders.")||j.message.includes("built-in provider")))throw new F(j.message);throw j}}),O.delete("/:provider",async(x)=>{let $=x.req.param("provider");if(!WO()?.modelProviders[$])throw new h("Model provider",$);let Q=x.req.query("removeModels");if(Q!==void 0&&Q!=="true"&&Q!=="false")throw new F("removeModels must be true or false");try{let Y=await TO().removeModelProvider($,{removeModels:Q==="true"});return x.json({success:!0,...Y})}catch(Y){if(Y instanceof Error&&(Y.message.includes("still referenced")||Y.message.includes("owns the only model")))throw new E(Y.message);throw Y}}),O.post("/:provider/probe",async(x)=>{let $=x.req.param("provider"),w=WO();if(!w?.modelProviders[$])throw new h("Model provider",$);let Q=await x.req.json().catch(()=>({})),Y=w.models.filter((K)=>K.provider===$),N=Q.modelId?Y.find((K)=>K.id===Q.modelId):Y[0];if(!N)throw new F(Q.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return x.json(await t4(N,w))}),O};import{Hono as Z2}from"hono";var J2=t("Service"),w$=(O,x)=>{let $=new Z2;return $.onError((w,Q)=>{if(w instanceof e)return Q.json(w.toObject(),w.statusCode);return J2.error("[ScheduleRoutes] Unhandled route error:",w),Q.json(new s("Schedule request failed").toObject(),500)}),$.get("/",async(w)=>{let Q=await O.list();return w.json($$.parse({schedules:Q}))}),$.post("/",async(w)=>{let Q;try{Q=await w.req.json()}catch{throw new F("Invalid request body")}let Y=f(O$,Q);if(!Y.success)throw new F("Invalid schedule request");let N=Y.data.projectPath||w.get("directory")||a();try{let K=await O.create({...Y.data,projectPath:N});return w.json(w0.parse(K),201)}catch(K){throw new F(K instanceof Error?K.message:"Failed to create schedule")}}),$.get("/:id",async(w)=>{let Q=await O.get(w.req.param("id"));if(!Q)throw new h("Schedule not found");return w.json(w0.parse(Q))}),$.patch("/:id",async(w)=>{let Q;try{Q=await w.req.json()}catch{throw new F("Invalid request body")}let Y=f(x$,Q);if(!Y.success)throw new F("Invalid schedule update");let{modelId:N,reasoningEffort:K,serviceTier:S,responseVerbosity:B,communicationStyle:j,isolation:b,permissionMode:U,...R}=Y.data,JO={...N!==void 0?{modelId:N}:{},...K!==void 0?{reasoningEffort:K}:{},...S!==void 0?{serviceTier:S}:{},...B!==void 0?{responseVerbosity:B}:{},...j!==void 0?{communicationStyle:j}:{},...b!==void 0?{isolation:b}:{},...U!==void 0?{permissionMode:U}:{}};try{let y=await O.update(w.req.param("id"),{...R,...Object.keys(JO).length>0?{dispatch:JO}:{}});if(!y)throw new h("Schedule not found");return w.json(w0.parse(y))}catch(y){if(y instanceof e)throw y;throw new F(y instanceof Error?y.message:"Failed to update schedule")}}),$.delete("/:id",async(w)=>{if(!await O.remove(w.req.param("id")))throw new h("Schedule not found");return w.json({ok:!0})}),$.post("/:id/enable",async(w)=>{let Q=await O.setEnabled(w.req.param("id"),!0);if(!Q)throw new h("Schedule not found");return w.json(w0.parse(Q))}),$.post("/:id/disable",async(w)=>{let Q=await O.setEnabled(w.req.param("id"),!1);if(!Q)throw new h("Schedule not found");return w.json(w0.parse(Q))}),$.post("/:id/run",async(w)=>{let Q=await O.get(w.req.param("id"));if(!Q)throw new h("Schedule not found");if(!x)throw new s("Scheduler is not running in this process");await x.fire(Q,new Date,{manual:!0});let Y=await O.get(Q.id);return w.json(w0.parse(Y??Q),202)}),$};import*as oO from"node:fs/promises";import{homedir as J$}from"node:os";import*as CO from"node:path";import{Hono as Y2}from"hono";var Q0=t("Service"),Q$=CO.join(J$(),".blade","skills"),i1=CO.join(J$(),".blade","skills-config.json");async function Y$(){try{let O=await oO.readFile(i1,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function N2(O){await oO.mkdir(CO.dirname(i1),{recursive:!0}),await oO.writeFile(i1,JSON.stringify(O,null,2))}async function W2(O,x){let $=await Y$();if(x)$.disabled=$.disabled.filter((w)=>w!==O);else if(!$.disabled.includes(O))$.disabled.push(O);await N2($)}var aO=null,X2=300000,z2=6;async function G2(){if(aO&&Date.now()-aO.timestamp<X2)return aO.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(Q0.warn(`GitHub API returned ${O.status}`),aO)return aO.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let $=(await O.json()).filter((N)=>N.type==="dir"),w=Array($.length),Q=0,Y=Math.min(z2,$.length);return await Promise.all(Array.from({length:Y},async()=>{while(Q<$.length){let N=Q++,K=$[N];if(!K)continue;let S=`Official ${K.name} skill`;try{let B=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${K.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(B.ok){let b=(await B.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(b)S=b[1].trim().slice(0,100)}}catch{}w[N]={name:K.name,description:S,tag:"Official",author:"Anthropic"}}})),aO={data:w,timestamp:Date.now()},w}catch(O){if(Q0.warn("Failed to fetch skills catalog from GitHub:",O),aO)return aO.data;throw O}}var N$=()=>{let O=new Y2;return O.get("/",async(x)=>{try{let $=x.get("directory")||a(),Q=(await kO($)).skills.getAll(),Y=await Y$(),N=Q.map((K)=>({id:K.name,name:K.name,enabled:!Y.disabled.includes(K.name),description:K.description||"",version:K.version||"1.0.0",provider:"Local",location:K.source==="builtin"?"Built-in":K.basePath,removable:K.source==="user"&&CO.dirname(CO.resolve(K.basePath))===CO.resolve(Q$),capabilities:["prompts"],allowedTools:K.allowedTools||[]}));return x.json(N)}catch($){return Q0.error("[SkillsRoutes] Failed to get skills:",$),x.json({error:$ instanceof Error?$.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async(x)=>{try{let $=x.req.param("name"),w=await x.req.json();return await W2($,w.enabled),x.json({success:!0,enabled:w.enabled})}catch($){return Q0.error("[SkillsRoutes] Failed to toggle skill:",$),x.json({success:!1,error:$.message},500)}}),O.delete("/:name",async(x)=>{try{let $=x.req.param("name"),w=x.get("directory")||a();return f0(w,async(Q)=>{let Y=Q.skills,N=Y.get($);if(!N)return x.json({success:!1,error:"Skill not found"},404);let K=CO.resolve(N.basePath),S=CO.resolve(Q$);if(N.source!=="user"||CO.dirname(K)!==S)return x.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await oO.rm(K,{recursive:!0,force:!0}),await Y.refresh(),E0(w),await k0(w),x.json({success:!0})})}catch($){return Q0.error("[SkillsRoutes] Failed to uninstall skill:",$),x.json({success:!1,error:$.message},500)}}),O.post("/install",async(x)=>{try{let $=await x.req.json(),w=Z$(),Q=x.get("directory")||a();return f0(Q,async(Y)=>{let N=Y.skills,K=!1;if($.source==="catalog"&&$.name){if(K=await w.installOfficialSkill($.name),!K)return x.json({success:!1,error:"Failed to install skill from catalog"},500)}else if($.source==="repo"&&$.url){if(K=await w.installFromRepo($.url,$.name),!K)return x.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if($.source==="local"&&$.path){if(K=await w.installFromLocal($.path,$.name),!K)return x.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 x.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await N.refresh(),E0(Q),await k0(Q),x.json({success:!0})})}catch($){return Q0.error("[SkillsRoutes] Failed to install skill:",$),x.json({success:!1,error:$.message},500)}}),O.get("/catalog",async(x)=>{try{let $=await G2();return x.json($)}catch($){return Q0.error("[SkillsRoutes] Failed to get catalog:",$),x.json({error:$ instanceof Error?$.message:"Failed to get skills catalog"},502)}}),O};import{execSync as V2}from"node:child_process";import{readdir as B2}from"node:fs/promises";import V1 from"node:path";import U2 from"fast-glob";import{Hono as K2}from"hono";var i0=t("Service"),_2=(O)=>{try{return V2("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},F2=[...L0.map((O)=>`${O}/**`),...L0,...L0.map((O)=>`**/${O}/**`),...L0.map((O)=>`**/${O}`),...c1.map((O)=>`**/${O}`)],L2=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),z$=()=>{let O=new K2;return O.get("/commands",async(x)=>{try{let $=x.req.query("q")||"",w=x.get("directory")||a(),Q=await kO(w),Y=X$($,w,Q).filter((N)=>!L2.has(N.command));return x.json(Y)}catch($){return i0.error("[SuggestionsRoutes] Failed to get command suggestions:",$),x.json([])}}),O.get("/files",async(x)=>{try{let $=x.req.query("q")||"",w=x.get("directory")||a(),Q=Math.min(Number(x.req.query("limit"))||100,1000),Y=x.req.query("type")==="file",K=(await U2("**/*",{cwd:w,dot:!1,followSymbolicLinks:!1,onlyFiles:Y,markDirectories:!0,unique:!0,ignore:F2})).map((j)=>j.replace(/\\/g,"/"));if(!$)return x.json(K.slice(0,Q));let S=$.toLowerCase(),B=K.filter((j)=>j.toLowerCase().includes(S)).slice(0,Q);return x.json(B)}catch($){return i0.error("[SuggestionsRoutes] Failed to get file suggestions:",$),x.json([])}}),O.get("/files/tree",async(x)=>{try{let $=x.get("directory")||a(),w=x.req.query("path")||"",Q=w?V1.join($,w):$,N=(await B2(Q,{withFileTypes:!0})).map((B)=>({name:B.name,path:w?`${w}/${B.name}`:B.name,type:B.isDirectory()?"dir":"file"}));N.sort((B,j)=>{if(B.type!==j.type)return B.type==="dir"?-1:1;return B.name.localeCompare(j.name)});let K=new Set(L0),S=N.filter((B)=>{let j=B.name;if(j.startsWith("."))return!1;if(K.has(j))return!1;for(let b of c1)if(j.match(new RegExp(b.replace("*",".*"))))return!1;return!0});return x.json(S)}catch($){return i0.error("[SuggestionsRoutes] Failed to get file tree:",$),x.json([])}}),O.get("/files/content",async(x)=>{try{let $=x.req.query("path");if(!$)return x.json({error:"Missing file path"},400);let w=x.get("directory")||a(),Q=V1.resolve(w,$),Y=V1.relative(w,Q);if(Y.startsWith("..")||V1.isAbsolute(Y))return x.json({error:"Invalid file path"},400);let N=W$(),K=await N.stat(Q);if(!K?.isFile)return x.json({error:"File not found"},404);let S=200000,B=await N.readTextFile(Q),j=B.length>S;return x.json({path:$,content:j?B.slice(0,S):B,truncated:j,size:K.size})}catch($){return i0.error("[SuggestionsRoutes] Failed to get file content:",$),x.json({error:"Failed to read file"},500)}}),O.get("/git-info",async(x)=>{try{let $=x.get("directory")||a(),w=_2($);return x.json({branch:w})}catch($){return i0.error("[SuggestionsRoutes] Failed to get git info:",$),x.json({branch:null})}}),O};import{Hono as D2}from"hono";var D0=t("Service"),K$=(O)=>{let x=new D2;return x.onError(($,w)=>{if($ instanceof e)return w.json($.toObject(),$.statusCode);return D0.error("[TaskRoutes] Unhandled route error:",$),w.json(new s("Failed to dispatch task").toObject(),500)}),x.post("/",async($)=>{let w;try{w=await $.req.json()}catch{throw new F("Invalid request body")}let Q=f(V$,w);if(!Q.success)throw new F("Invalid task request");if((Q.data.attachments??[]).reduce((N,K)=>N+(typeof K.content==="string"?Buffer.byteLength(K.content):0),0)>X1)throw new F("Task attachments exceed the 5 MiB limit");if(Q.data.taskDueAt&&!Number.isFinite(Date.parse(Q.data.taskDueAt)))throw new F("Invalid task due date");try{let N=await O.dispatchTask({prompt:Q.data.prompt,title:Q.data.title,taskPriority:Q.data.taskPriority,taskKind:Q.data.taskKind,taskDueAt:Q.data.taskDueAt?new Date(Q.data.taskDueAt).toISOString():void 0,sourceProjectPath:Q.data.projectPath||$.get("directory")||a(),isolation:Q.data.isolation,permissionMode:Q.data.permissionMode,modelId:Q.data.modelId,reasoningEffort:Q.data.reasoningEffort,serviceTier:Q.data.serviceTier,responseVerbosity:Q.data.responseVerbosity,communicationStyle:Q.data.communicationStyle,attachments:Q.data.attachments,outputSchema:Q.data.outputSchema});return $.json(o1.parse(N),202)}catch(N){if(N instanceof F||N instanceof E||N instanceof gO||N instanceof hO)throw N;throw D0.error("[TaskRoutes] Failed to dispatch task:",N),new s("Failed to dispatch task")}}),x.patch("/:sessionId",async($)=>{let w;try{w=await $.req.json()}catch{throw new F("Invalid request body")}let Q=f(B$,w);if(!Q.success)throw new F("Invalid task update");if(Q.data.title===void 0&&Q.data.taskPriority===void 0&&Q.data.taskKind===void 0&&Q.data.taskDueAt===void 0)throw new F("Task update must include at least one field");if(typeof Q.data.taskDueAt==="string"&&!Number.isFinite(Date.parse(Q.data.taskDueAt)))throw new F("Invalid task due date");try{let Y=await O.updateTask($.req.param("sessionId"),{...Q.data,...typeof Q.data.taskDueAt==="string"?{taskDueAt:new Date(Q.data.taskDueAt).toISOString()}:{}},$.req.query("projectPath"));return $.json(a1.parse(Y))}catch(Y){if(Y instanceof F||Y instanceof h||Y instanceof E)throw Y;throw D0.error("[TaskRoutes] Failed to update task:",Y),new s("Failed to update task")}}),x.post("/:sessionId/retry",async($)=>{try{let w=await O.retryTask($.req.param("sessionId"),$.req.query("projectPath"));return $.json(o1.parse(w),202)}catch(w){if(w instanceof F||w instanceof h||w instanceof E||w instanceof gO||w instanceof hO)throw w;throw D0.error("[TaskRoutes] Failed to retry task:",w),new s("Failed to retry task")}}),x.get("/:sessionId/diff",async($)=>{try{let w=await O.getTaskDiff($.req.param("sessionId"),$.req.query("projectPath"));return $.json(G$.parse(w))}catch(w){if(w instanceof F||w instanceof h||w instanceof E)throw w;throw D0.error("[TaskRoutes] Failed to load task diff:",w),new s("Failed to load task diff")}}),x.post("/:sessionId/delivery",async($)=>{let w;try{w=await $.req.json()}catch{throw new F("Invalid request body")}let Q=f(U$,w);if(!Q.success)throw new F("Invalid task delivery request");try{let Y=await O.deliverTask($.req.param("sessionId"),Q.data.action,$.req.query("projectPath"));return $.json(a1.parse(Y))}catch(Y){if(Y instanceof F||Y instanceof h||Y instanceof E)throw Y;throw D0.error("[TaskRoutes] Failed to deliver task:",Y),new s("Failed to deliver task")}}),x};import D$ from"node:path";import{Hono as A2}from"hono";var H2=EO(W.Object({id:W.String(),name:W.String(),subagentType:W.String(),description:W.String(),agentId:W.Optional(W.String()),status:OO(["leader","running","completed","failed","cancelled","unknown"]),result:W.Optional(W.Unknown()),stats:W.Optional(W.Unknown()),worktreePath:W.Optional(W.String())})),b2=EO(W.Object({id:W.String(),subject:W.String(),description:W.String(),status:OO(["pending","blocked","running","completed"]),owner:W.Optional(W.String()),priority:OO(["high","medium","low"]),dependsOn:W.Array(W.String()),blocks:W.Array(W.String()),result:W.Optional(W.String()),createdAt:W.String(),startedAt:W.Optional(W.String()),completedAt:W.Optional(W.String())})),i6=EO(W.Object({name:W.String(),description:W.Optional(W.String()),status:OO(["idle","running","completed","failed","deleted"]),leadAgentId:W.String(),leadSessionId:W.Optional(W.String()),workspaceRoot:W.Optional(W.String()),peerMessagingEnabled:W.Boolean(),createdAt:W.Number(),updatedAt:W.Number(),deletedAt:W.Optional(W.Number()),members:W.Array(H2),tasks:W.Array(b2)})),_$=EO(W.Object({sessionId:W.String({minLength:1}),projectPath:W.String({minLength:1}),name:W.String({minLength:1}),description:W.Optional(W.String()),leadAgentType:W.Optional(W.String()),peerMessagingEnabled:W.Optional(W.Boolean()),members:W.Array(W.Object({name:W.String({minLength:1}),subagentType:W.String({minLength:1}),description:W.Optional(W.String()),prompt:W.String({minLength:10,maxLength:32768})}),{maxItems:32}),tasks:W.Optional(W.Array(W.Object({subject:W.String({minLength:1}),description:W.String({minLength:1}),dependsOn:W.Optional(W.Array(W.String())),assignedTo:W.Optional(W.String()),priority:W.Optional(OO(["high","medium","low"]))}),{maxItems:256}))})),F$=EO(W.Object({sessionId:W.String({minLength:1}),projectPath:W.String({minLength:1}),to:W.String({minLength:1}),message:W.String({minLength:1,maxLength:32768})})),L$=EO(W.Object({sessionId:W.String({minLength:1}),projectPath:W.String({minLength:1}),memberId:W.String({minLength:1})}));var j2=t("Service"),j$=()=>{let O=new A2;return O.onError((x,$)=>{if(x instanceof e)return $.json(x.toObject(),x.statusCode);return j2.error("[TeamRoutes] Unhandled route error:",x),$.json(new s("Team operation failed").toObject(),500)}),O.get("/",async(x)=>{b0();let $=await A0(x.req.query("sessionId"),x.req.query("projectPath"));return x.json(await H0($.projectPath).list($))}),O.post("/",async(x)=>{b0();let $=f(_$,await n1(x.req));if(!$.success)throw new F("Invalid team request");let w=await A0($.data.sessionId,$.data.projectPath),Q=await C.findSessionMetadata(w.sessionId,w.projectPath);return x.json(await H0(w.projectPath).create({name:$.data.name,description:$.data.description,leadAgentType:$.data.leadAgentType,owner:w,modelId:Q?.selectedModelId,peerMessagingEnabled:$.data.peerMessagingEnabled,members:$.data.members,tasks:$.data.tasks}),201)}),O.get("/:teamName",async(x)=>{b0();let $=await A0(x.req.query("sessionId"),x.req.query("projectPath"));return x.json(await H0($.projectPath).getSnapshot(x.req.param("teamName"),$))}),O.post("/:teamName/messages",async(x)=>{b0();let $=f(F$,await n1(x.req));if(!$.success)throw new F("Invalid team message");let w=await A0($.data.sessionId,$.data.projectPath),Q=await H0(w.projectPath).sendMessage({name:x.req.param("teamName"),to:$.data.to,body:$.data.message,owner:w});return x.json({messages:Q})}),O.post("/:teamName/tasks/claim",async(x)=>{b0();let $=f(L$,await n1(x.req));if(!$.success)throw new F("Invalid team task claim");let w=await A0($.data.sessionId,$.data.projectPath);return x.json({task:await H0(w.projectPath).claimTask(x.req.param("teamName"),$.data.memberId,w)})}),O.delete("/:teamName",async(x)=>{b0();let $=await A0(x.req.query("sessionId"),x.req.query("projectPath"));return x.json(await H0($.projectPath).delete(x.req.param("teamName"),{owner:$,killRunning:!0}))}),O};function H0(O){return new A$({configDir:W1(),subagentRegistry:b$(O)})}function b0(){if(H$().config.config?.agentTeamsEnabled!==!0)throw new gO("Agent Teams are disabled")}async function A0(O,x){if(!O||!x||!D$.isAbsolute(x))throw new F("sessionId and absolute projectPath are required");let $=D$.resolve(x);if(!await C.findSessionMetadata(O,$))throw new h(`Session not found: ${O}`);return{sessionId:O,projectPath:$}}async function n1(O){try{return await O.json()}catch{throw new F("Invalid request body")}}import{Hono as S2}from"hono";var nO=t("Service"),j0=new Map,S$=2097152,M$=65536;function T$(){return typeof globalThis.Bun<"u"}async function M2(O,x,$){if(T$()){let{spawn:Y}=await import("bun-pty"),N=Y(O,x,{name:"xterm-256color",cwd:$.cwd,env:$.env});return{pid:N.pid,write:(K)=>N.write(K),resize:(K,S)=>N.resize(K,S),kill:()=>N.kill(),onData:(K)=>N.onData(K),onExit:(K)=>N.onExit(K)}}let Q=(await import("node-pty")).spawn(O,x,{name:"xterm-256color",cwd:$.cwd,env:$.env,cols:80,rows:24});return{pid:Q.pid,write:(Y)=>Q.write(Y),resize:(Y,N)=>Q.resize(Y,N),kill:()=>Q.kill(),onData:(Y)=>{Q.onData(Y)},onExit:(Y)=>{Q.onExit(Y)}}}var r1=void 0,s1;if(T$())try{let{createBunWebSocket:O}=await import("hono/bun"),x=O();s1=x.upgradeWebSocket,r1=x.websocket}catch(O){nO.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function R$(O,x){let $=`term-${Date.now()}`;nO.info(`[Terminal] New connection: ${$}, cwd: ${O}`);let w=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Q=w.endsWith("sh")?["-l"]:[],Y=await M2(w,Q,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),N={id:$,process:Y,cwd:O,buffer:"",subscribers:new Set};if(j0.set($,N),N.subscribers.add(x),Y.onData((K)=>{let S=!1;for(let B of N.subscribers)try{B.send(K),S=!0}catch{N.subscribers.delete(B)}if(S)return;if(N.buffer+=K,N.buffer.length>S$)N.buffer=N.buffer.slice(-S$)}),Y.onExit(({exitCode:K})=>{nO.info(`[Terminal] Process exited: ${$}, code: ${K}`);for(let S of N.subscribers)try{S.close()}catch{}j0.delete($)}),N.buffer){let K=N.buffer;N.buffer="";for(let S=0;S<K.length;S+=M$)x.send(K.slice(S,S+M$))}return{session:N,cleanup:()=>{if(nO.info(`[Terminal] Connection closed: ${$}`),N.subscribers.delete(x),N.subscribers.size===0){try{N.process.kill()}catch{}j0.delete($)}}}}function q$(O,x){O.on("connection",async($,w)=>{let Q=new URL(w.url||"/",`http://${w.headers.host}`);if(!Q.pathname.endsWith("/terminal/ws")){$.close();return}let Y=Q.searchParams.get("cwd")||x()||a();try{let{session:N,cleanup:K}=await R$(Y,{send:(S)=>$.send(S),close:()=>$.close()});$.on("message",(S)=>{try{N.process.write(String(S))}catch(B){nO.error("[Terminal] Failed to write to PTY:",B)}}),$.on("close",K),$.on("error",K)}catch(N){nO.error("[Terminal] Failed to spawn PTY:",N),$.close()}})}var I$=()=>{let O=new S2;if(O.get("/status",(x)=>{let $=Array.from(j0.values()).map((w)=>({id:w.id,cwd:w.cwd}));return x.json({active:$.length,terminals:$})}),O.post("/kill/:terminalId",(x)=>{let $=x.req.param("terminalId"),w=j0.get($);if(w){try{w.process.kill()}catch{}for(let Q of w.subscribers)Q.close();return j0.delete($),x.json({success:!0})}return x.json({success:!1,error:"Terminal not found"},404)}),s1)O.get("/ws",s1((x)=>{let $=x.req.query("cwd")||x.get("directory")||a(),w;return{async onOpen(Q,Y){try{w=await R$($,{send:(N)=>Y.send(N),close:()=>Y.close()})}catch(N){nO.error("[Terminal] Failed to spawn PTY:",N),Y.close()}},onMessage(Q){if(!w)return;try{w.session.process.write(String(Q.data))}catch(Y){nO.error("[Terminal] Failed to write to PTY:",Y)}},onClose(){w?.cleanup()}}}));else O.get("/ws",(x)=>{return x.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import T2 from"node:path";import{Hono as R2}from"hono";var q2=W.Object({projectPath:W.String({minLength:1}),action:OO(["trust","revoke"])});function C$(O){if(!T2.isAbsolute(O))throw new F("projectPath must be absolute")}var E$=()=>{let O=new R2;return O.get("/",async(x)=>{let $=x.req.query("projectPath");if(!$)throw new F("projectPath query parameter is required");return C$($),x.json(await e1.getInstance().getStatus($))}),O.post("/",async(x)=>{let $=f(q2,await x.req.json());if(!$.success)throw new F("Invalid workspace trust request");let{projectPath:w,action:Q}=$.data;C$(w);let Y=e1.getInstance(),N=Q==="trust"?await Y.trust(w):await Y.revoke(w);return await k$(),x.json({...N,reloadRequired:N.sensitiveSources>0})}),O};var DO=t("Service"),$x=[],B1,S0,M0,c0,f$=new Map,y$=new Map,p2=new Set([".css",".html",".js",".json",".svg"]),d2=1024,v2=3600000;function l2(O,x){if(!O)return 0;let $=O.split(",").map((w)=>{let[Q,...Y]=w.trim().toLowerCase().split(";"),N=Y.find((S)=>S.trim().startsWith("q=")),K=N?Number(N.trim().slice(2)):1;return{name:Q,quality:Number.isFinite(K)?Math.max(0,Math.min(1,K)):0}});return $.find((w)=>w.name===x)?.quality??$.find((w)=>w.name==="*")?.quality??0}function P$(){if(M0)return;let O=()=>{C.collectStaleEmptySessions().then((x)=>{if(x>0)DO.info(`[SessionGC] removed ${x} stale empty session(s)`)}).catch((x)=>{DO.warn("[SessionGC] failed to collect stale empty sessions:",x)})};O(),M0=setInterval(O,v2),M0.unref?.()}function i2(){if(!M0)return;clearInterval(M0),M0=void 0}function c2(O){return["br","gzip"].map(($)=>({encoding:$,quality:l2(O,$)})).filter(($)=>$.quality>0).sort(($,w)=>w.quality-$.quality||($.encoding==="br"?-1:1))[0]?.encoding}function a2(O){let x=f$.get(O);if(x)return x;let $=a0(O);return f$.set(O,$),$}function o2(O,x,$){let w=`${$}:${O}`,Q=y$.get(w);if(Q)return Q;let Y=$==="br"?y2(x,{params:{[m2.BROTLI_PARAM_QUALITY]:5}}):P2(x,{level:6});return y$.set(w,Y),Y}function n2(){let O=k2(f2(import.meta.url)),x=[tO(O,"web"),tO(a(),"dist/web"),tO(a(),"packages/cli/dist/web")];for(let $ of x){let w=tO($,"index.html");if(xx(w)){if(a0(w,"utf-8").includes("/assets/"))return DO.debug(`[Server] Found web dist at: ${$}`),$}}return null}function t2(){let O=new h2;O.onError((w,Q)=>{if(DO.error("[Server] Request error:",w),w instanceof g$){let N=new hO(w.message,{resource:"workspace_agent_resources",limit:w.capacity});return Q.json(N.toObject(),429)}if(w instanceof e)return Q.json(w.toObject(),w.statusCode);let Y=w instanceof Error?w.message:String(w);return Q.json({error:{code:"INTERNAL_ERROR",message:Y}},500)}),O.use(async(w,Q)=>{let Y=process.env.BLADE_SERVER_PASSWORD;if(!Y)return Q();let N=w.req.path;if(N==="/"||N==="/favicon.svg"||N.startsWith("/assets/")||N.endsWith(".html")||N.endsWith(".js")||N.endsWith(".css"))return Q();let K=w.req.header("Authorization");if(!K?.startsWith("Basic "))return w.header("WWW-Authenticate",'Basic realm="Blade Server"'),w.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let S=Buffer.from(K.slice(6),"base64").toString(),[B,j]=S.split(":"),b=process.env.BLADE_SERVER_USERNAME??"blade";if(B!==b||j!==Y)return w.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Q()}),O.use(async(w,Q)=>{let Y=w.req.path==="/health"||w.req.path==="/global/health"||w.req.path.startsWith("/assets/");if(!Y)DO.debug(`[Server] ${w.req.method} ${w.req.path}`);let N=Date.now();if(await Q(),!Y){let K=Date.now()-N;DO.debug(`[Server] ${w.req.method} ${w.req.path} - ${w.res.status} (${K}ms)`)}}),O.use(g2({origin(w){if(!w)return;if(w.startsWith("http://localhost:"))return w;if(w.startsWith("http://127.0.0.1:"))return w;if(w==="tauri://localhost"||w==="http://tauri.localhost")return w;if($x.includes(w))return w;return}})),O.use(async(w,Q)=>{let Y=w.req.query("directory")||w.req.header("x-blade-directory")||a();try{Y=decodeURIComponent(Y)}catch{}return w.set("directory",Y),Q()});let x=q4();c0=x,B1=x.recoverQueuedTasks,S0=new H1({dispatch:(w)=>x.dispatchTask(w),store:Ox}),O.route("/global",Lx()),O.route("/events",_x()),O.route("/sessions",x.app),O.route("/tasks",K$(x)),O.route("/teams",j$()),O.route("/schedules",w$(Ox,S0)),O.route("/configs",zx()),O.route("/permissions",C4()),O.route("/plugins",i4()),O.route("/hooks",Sx()),O.route("/workspace-trust",E$()),O.route("/providers",e4()),O.route("/models",fx()),O.route("/projects",o4()),O.route("/suggestions",z$()),O.route("/terminal",I$()),O.route("/mcp",Rx()),O.route("/skills",N$()),O.get("/health",(w)=>{return w.json({healthy:!0,version:z0()})});let $=n2();if($)DO.info(`[Server] Serving static files from ${$}`),O.get("/favicon.svg",()=>{let w=tO($,"favicon.svg");if(!xx(w))return new Response(null,{status:404});return new Response(a0(w),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(w)=>{let Q=tO($,w.req.path);if(!xx(Q))return w.json({error:{code:"NOT_FOUND",message:`File not found: ${w.req.path}`}},404);let Y=a2(Q),N=E2(Q).toLowerCase(),S={".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",B=p2.has(N)&&Y.byteLength>=d2?c2(w.req.header("Accept-Encoding")):void 0,j=B?o2(Q,Y,B):Y;return new Response(new Uint8Array(j),{headers:{"Content-Type":S,"Content-Length":String(j.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...B?{"Content-Encoding":B}:{}}})}),O.get("/",(w)=>{let Q=tO($,"index.html"),Y=a0(Q,"utf-8");return w.html(Y,200,{"Cache-Control":"no-cache"})}),O.get("*",(w)=>{let Q=w.req.path;if(Q.includes("."))return w.json({error:{code:"NOT_FOUND",message:`File not found: ${Q}`}},404);let Y=tO($,"index.html"),N=a0(Y,"utf-8");return w.html(N,200,{"Cache-Control":"no-cache"})});else DO.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(w)=>{return w.json({message:"Blade API Server",version:z0(),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("*",(w)=>{return w.json({error:{code:"NOT_FOUND",message:`Route not found: ${w.req.path}`}},404)});return O}function s2(){let O=C2(),x=[];for(let $ of Object.keys(O)){let w=O[$];if(!w)continue;for(let Q of w){if(Q.internal||Q.family!=="IPv4")continue;if(Q.address.startsWith("172."))continue;x.push(Q.address)}}return x}function m$(){return typeof globalThis.Bun<"u"}function h$(O,x){let $=globalThis.Bun,w=(Y)=>{try{return $.serve({hostname:x.hostname,port:Y,fetch:O.fetch,idleTimeout:0,websocket:r1})}catch(N){DO.error("Failed to start Bun server:",N);return}},Q=x.port===0?w(4096)??w(0):w(x.port);if(!Q)throw Error(`Failed to start Bun server on port ${x.port}`);return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{Q.stop(!0)}}}function r2(O,x){return new Promise(($,w)=>{let Q=I2(async(B,j)=>{let b=new URL(B.url||"/",`http://${B.headers.host}`),U=new Headers;for(let[y,r]of Object.entries(B.headers))if(r)if(Array.isArray(r))for(let ZO of r)U.append(y,ZO);else U.set(y,r);let R;if(B.method!=="GET"&&B.method!=="HEAD")R=(await new Promise((r)=>{let ZO=[];B.on("data",(GO)=>ZO.push(GO)),B.on("end",()=>r(Buffer.concat(ZO)))})).toString();let JO=new Request(b.toString(),{method:B.method,headers:U,body:R});try{let y=await O.fetch(JO);if(j.statusCode=y.status,y.headers.forEach((r,ZO)=>{j.setHeader(ZO,r)}),y.body){let r=y.body.getReader(),ZO=async()=>{let{done:GO,value:YO}=await r.read();if(GO){j.end();return}return j.write(YO),ZO()};await ZO()}else{let r=await y.text();j.end(r)}}catch(y){DO.error("[Server] Node request error:",y),j.statusCode=500,j.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),Y=new u2({noServer:!0}),N=a();q$(Y,()=>N),Q.on("upgrade",(B,j,b)=>{if(new URL(B.url||"/",`http://${B.headers.host}`).pathname==="/terminal/ws")Y.handleUpgrade(B,j,b,(R)=>{Y.emit("connection",R,B)});else j.destroy()});let K=(B)=>{return new Promise((j,b)=>{Q.once("error",(U)=>{if(U.code==="EADDRINUSE")b(U);else b(U)}),Q.listen(B,x.hostname,()=>{let U=Q.address();if(U&&typeof U==="object")j(U.port);else j(B)})})};(async()=>{let B;if(x.port===0)try{B=await K(4096)}catch{B=await K(0)}else B=await K(x.port);let j=new URL(`http://${x.hostname==="0.0.0.0"?"localhost":x.hostname}:${B}`);$({url:j,port:B,hostname:x.hostname,stop:async()=>{return new Promise((b)=>{Y.close(()=>{Q.close(()=>b())})})}})})().catch(w)})}var p$;((s8)=>{let O,x,$,w=(B,j)=>{if(O!==B)return Promise.resolve();if($)return $;let b=j?.shutdown("server-shutdown");return S0?.stop(),i2(),$=(async()=>{let U,R=async(JO)=>{if(!JO)return;try{await JO()}catch(y){U??=y}};if(await R(()=>B.stop()),await R(b?()=>b:void 0),u$(),O===B)O=void 0,x=void 0,c0=void 0,B1=void 0,S0=void 0;if(DO.info("[Server] Blade server stopped"),U!==void 0)throw U})(),$};function Q(){if(!x)x=t2();return x}s8.getApp=Q;function Y(B){$x=B.cors??[];let j=Q();if(m$())O=h$(j,B),$=void 0,DO.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");let b=O,U=c0;return B1?.().catch((R)=>{DO.warn("[Server] Failed to recover queued tasks:",R)}),S0?.start(),P$(),{url:b.url,port:b.port,hostname:b.hostname,stop:()=>w(b,U)}}s8.listen=Y;async function N(B){$x=B.cors??[];let j=Q();if(m$())O=h$(j,B),DO.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await r2(j,B),DO.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);$=void 0;let b=O,U=c0;try{await B1?.()}catch(R){DO.warn("[Server] Failed to recover queued tasks:",R)}return S0?.start(),P$(),{url:b.url,port:b.port,hostname:b.hostname,stop:()=>w(b,U)}}s8.listenAsync=N;function K(){return O!==void 0}s8.isRunning=K;function S(){return c0?.getCoordinationStats()}s8.getSessionCoordinationStatsForTests=S})(p$||={});export{O3 as a,x3 as b,s2 as c,p$ as d};
|