blade-code 0.10.76 → 0.10.77
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-9fm80wbr.js → chunk-0141jad7.js} +1 -1
- package/dist/{chunk-aq15mcwm.js → chunk-091qx62q.js} +1 -1
- package/dist/{chunk-fmkntp49.js → chunk-0a0sj79a.js} +2 -2
- package/dist/chunk-0cbr2gs7.js +168 -0
- package/dist/{chunk-zvpr8s8r.js → chunk-0hpenwph.js} +1 -1
- package/dist/{chunk-9x141v5g.js → chunk-0ra945vt.js} +2 -2
- package/dist/{chunk-yg7cacsc.js → chunk-1mc7nfb4.js} +1 -1
- package/dist/chunk-28drv25s.js +1 -0
- package/dist/{chunk-j67n7v73.js → chunk-2herdn98.js} +1 -1
- package/dist/{chunk-wx9zxzgm.js → chunk-33bpwkyk.js} +2 -2
- package/dist/chunk-3ekj5azv.js +1 -0
- package/dist/chunk-3j0dhewn.js +1 -0
- package/dist/{chunk-6h3x4jv0.js → chunk-5e56atqj.js} +26 -26
- package/dist/{chunk-68stvfdj.js → chunk-5nezhmnq.js} +2 -2
- package/dist/{chunk-zk34d9mm.js → chunk-69s3e453.js} +1 -1
- package/dist/chunk-6adxyred.js +1 -0
- package/dist/{chunk-9dspha54.js → chunk-72kqnntm.js} +2 -2
- package/dist/{chunk-kxgr18gy.js → chunk-7ffdedgc.js} +2 -2
- package/dist/{chunk-n5d0d6q7.js → chunk-7nx0pzfk.js} +1 -1
- package/dist/chunk-8k4jza38.js +1 -0
- package/dist/chunk-9tb7cwem.js +1 -0
- package/dist/{chunk-cgd0vjw2.js → chunk-b86m3bpv.js} +1 -1
- package/dist/{chunk-ttbq1xmz.js → chunk-b948f9w9.js} +2 -2
- package/dist/chunk-b9hdp0n4.js +1 -0
- package/dist/{chunk-8bsse16j.js → chunk-b9nhnzaj.js} +1 -1
- package/dist/{chunk-z37v80c1.js → chunk-b9vm7gns.js} +2 -2
- package/dist/{chunk-vwa2kczj.js → chunk-c8td6vaa.js} +1 -1
- package/dist/{chunk-db2v383v.js → chunk-cq5gtwxb.js} +1 -1
- package/dist/chunk-cr1xp3re.js +10 -0
- package/dist/{chunk-tssmnn37.js → chunk-dj99h8ca.js} +2 -2
- package/dist/{chunk-ts96epcd.js → chunk-dshgm836.js} +1 -1
- package/dist/{chunk-qnj3dajb.js → chunk-eeb2945p.js} +1 -1
- package/dist/{chunk-ehks2r00.js → chunk-fsm3fb2m.js} +1 -1
- package/dist/{chunk-h0ys86rn.js → chunk-geam96gd.js} +1 -1
- package/dist/chunk-gn6ftvjy.js +1 -0
- package/dist/{chunk-tnaxxgje.js → chunk-gre57x9m.js} +1 -1
- package/dist/{chunk-bvhbc0wr.js → chunk-h0fh3j9w.js} +1 -1
- package/dist/{chunk-zwd5q6dt.js → chunk-h3w814js.js} +1 -1
- package/dist/{chunk-vn1r6z64.js → chunk-h6a0nct6.js} +1 -1
- package/dist/{chunk-ckvq6z49.js → chunk-h9xayrwp.js} +1 -1
- package/dist/chunk-hchn7baz.js +1 -0
- package/dist/{chunk-r8ayexxd.js → chunk-jdb2mwbn.js} +1 -1
- package/dist/{chunk-9k3tg2hs.js → chunk-je4xvy93.js} +3 -3
- package/dist/{chunk-vdtma2yq.js → chunk-jwx10h5z.js} +1 -1
- package/dist/{chunk-c80pzvhs.js → chunk-jzvbjn6e.js} +1 -1
- package/dist/{chunk-eesa8c5h.js → chunk-ky9q53m7.js} +1 -1
- package/dist/{chunk-abzn9eba.js → chunk-mb3htbeh.js} +1 -1
- package/dist/{chunk-625krpnt.js → chunk-mctkgv0d.js} +4 -4
- package/dist/{chunk-js4vqnds.js → chunk-mygw13zd.js} +1 -1
- package/dist/{chunk-8chhdkg2.js → chunk-n3amyjrd.js} +8 -5
- package/dist/{chunk-90yjhvjb.js → chunk-nqcpyazv.js} +1 -1
- package/dist/chunk-nx4z7pxk.js +1 -0
- package/dist/chunk-nxmssc56.js +1 -0
- package/dist/{chunk-9ra452yc.js → chunk-pfvgkexe.js} +1 -1
- package/dist/{chunk-xmty01x3.js → chunk-phgcgfv1.js} +1 -1
- package/dist/{chunk-chmf8s1j.js → chunk-pq4fjmnj.js} +2 -2
- package/dist/{chunk-gx1wx7z5.js → chunk-pr8c6qef.js} +1 -1
- package/dist/{chunk-js4aekf1.js → chunk-qxn5bg5k.js} +1 -1
- package/dist/{chunk-gpxvyxz1.js → chunk-qz5xm4cr.js} +1 -1
- package/dist/chunk-rdvm8zvw.js +6 -0
- package/dist/chunk-reakyamv.js +2 -0
- package/dist/chunk-rpbyc2k4.js +1 -0
- package/dist/{chunk-01k69v34.js → chunk-seamt0j3.js} +2 -2
- package/dist/{chunk-426sb4tk.js → chunk-shq0pkxq.js} +1 -1
- package/dist/{chunk-79cxktz1.js → chunk-sj0k8cdf.js} +1 -1
- package/dist/{chunk-vpn2e8tj.js → chunk-xrt796d6.js} +2 -2
- package/dist/{chunk-yhyqcmh1.js → chunk-yqkyhp0e.js} +1 -1
- package/dist/{chunk-psy247es.js → chunk-zkhb55jz.js} +1 -1
- package/dist/chunk-zwbv30np.js +1 -0
- package/package.json +1 -1
- package/dist/chunk-0z6fn1mt.js +0 -1
- package/dist/chunk-25q79gk4.js +0 -6
- package/dist/chunk-2nnfx3s7.js +0 -1
- package/dist/chunk-5b0tejhz.js +0 -1
- package/dist/chunk-66w68q81.js +0 -168
- package/dist/chunk-6r150c8y.js +0 -1
- package/dist/chunk-9eah1889.js +0 -1
- package/dist/chunk-9tcrrjzg.js +0 -1
- package/dist/chunk-bpf84msg.js +0 -1
- package/dist/chunk-c074qee7.js +0 -1
- package/dist/chunk-d8gn6hw5.js +0 -1
- package/dist/chunk-egv5k7t5.js +0 -1
- package/dist/chunk-et3d69av.js +0 -1
- package/dist/chunk-mjq7rrq1.js +0 -1
- package/dist/chunk-t1bvxk3s.js +0 -2
- package/dist/chunk-tppvhg2n.js +0 -1
- package/dist/chunk-zjfdj7be.js +0 -10
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{j as H4,k as L4}from"./chunk-
|
|
1
|
+
import{j as H4,k as L4}from"./chunk-1mc7nfb4.js";import{l as O1}from"./chunk-shq0pkxq.js";import{s as J0,t as o$}from"./chunk-qz5xm4cr.js";import{u as oO}from"./chunk-dshgm836.js";import{A as e1,v as v$,w as t1,x as s1,y as r1,z as x0}from"./chunk-geam96gd.js";import{$ as J4,C as E4,F as P$,G as N0,H as S1,I as n0,J as H1,K as EO,L as f$,M as m$,N as h$,O as L1,P as mO,Q as S0,T as y0,U as f0,W as l4,X as g$,Y as u$,Z as Q4,_ as Z4,aa as Y4,ba as z4,ca as G4,da as X4,ea as V4,fa as N4,ia as D4,la as e4,qa as k4}from"./chunk-n3amyjrd.js";import{ta as V$,za as UO}from"./chunk-b86m3bpv.js";import{Da as z1,Ga as I4,Ha as R1,Ia as p$,Ja as d$,Ka as P4,La as y4,Ma as E1,Na as f4,Oa as sO,Pa as w4,Qa as A4,Ra as M4,Sa as l$,Ta as i$,Ua as c$,Va as a$,Wa as a1,Xa as f1}from"./chunk-ky9q53m7.js";import{Eb as nO,gb as gO,hb as v,jb as S,kb as y$,vb as D1}from"./chunk-0cbr2gs7.js";import{Pb as S$}from"./chunk-r8wbvxn7.js";import{Bc as E$,Hc as k$,Ic as q$,Kc as z0,Nc as F1,Sc as I$,Tc as U1,Uc as _1,Vc as R,gc as R$,rc as t0,xc as I0,yc as A1,zc as P0}from"./chunk-5e56atqj.js";import{Pd as p4,Td as QO,Xd as F$,ce as BO}from"./chunk-yqkyhp0e.js";import{de as W1}from"./chunk-c9e0fbyh.js";import{ue as b$}from"./chunk-mygw13zd.js";import{we as o0}from"./chunk-b948f9w9.js";import{Ee as d4,Ge as b4,Je as x4,Ne as j0,Oe as b0,Se as Yx,Ve as jO,We as C0,Ze as zx}from"./chunk-xrt796d6.js";import{lf as U$,mf as C$}from"./chunk-7nx0pzfk.js";import{qf as Y$,rf as Z0}from"./chunk-je4xvy93.js";import{Jf as X$,bg as M$,eg as T$,gg as j$,tg as z$,yg as T0}from"./chunk-dj99h8ca.js";import{Bg as K1}from"./chunk-pfvgkexe.js";import{Cg as q,Eg as V,Fg as eO,Hg as JO}from"./chunk-qxn5bg5k.js";import{Jg as r0}from"./chunk-reakyamv.js";import{Og as c}from"./chunk-0141jad7.js";import{oh as o}from"./chunk-b9vm7gns.js";import{uh as cO}from"./chunk-5nezhmnq.js";import{Ah as A$,wh as K$,xh as w$,zh as W$}from"./chunk-h6a0nct6.js";import{Ch as Q0}from"./chunk-7ffdedgc.js";import{Jh as y1}from"./chunk-0a0sj79a.js";import{Ph as i0,Th as $$,Uh as s0}from"./chunk-0ra945vt.js";import{Wh as q1}from"./chunk-h0fh3j9w.js";var F3={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 U3(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as m1,readFileSync as g0}from"node:fs";import{createServer as i2}from"node:http";import{networkInterfaces as c2}from"node:os";import{dirname as a2,extname as o2,join as dO}from"node:path";import{fileURLToPath as n2}from"node:url";import{brotliCompressSync as t2,gzipSync as s2,constants as r2}from"node:zlib";import{Hono as e2}from"hono";import{cors as O3}from"hono/cors";import{WebSocketServer as $3}from"ws";var $0=o("Service"),Vx=30000,Nx=new Set(["completed","failed","cancelled","interrupted"]);class G1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??a1.getInstance(),this.tickMs=O.tickMs??Vx}start(){if(this.timer)return;$0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=S.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!Nx.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,$0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){$0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),$0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Q=$.toISOString();try{let Z=await this.dispatch({prompt:O.prompt,title:O.title??Kx(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}),G=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:z1(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Q,lastRunSessionId:Z.session.sessionId,lastStatus:Z.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),S.publish({sessionId:Z.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Q,sessionId:Z.session.sessionId,runId:Z.runId,status:Z.status}),$0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Z.session.sessionId} (${Z.status})`)}catch(Z){let G=Z instanceof Error?Z.message:String(Z);$0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Z);let z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:z1(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Q,lastStatus:"error",lastError:G,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Z=(await this.store.list()).find((G)=>G.lastRunSessionId===O);if(!Z)return;await this.store.update(Z.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function Kx(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class xO extends Error{code;statusCode;details;constructor(O,$,x=500,Q){super($);this.code=O;this.statusCode=x;this.details=Q;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class f extends xO{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class _ extends xO{constructor(O){super("BAD_REQUEST",O,400)}}class k extends xO{constructor(O){super("CONFLICT",O,409)}}class kO extends xO{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class qO extends xO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class LO extends xO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class t extends xO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var M3=V.Object({error:V.Object({code:V.String(),message:V.String(),details:V.Optional(V.Record(V.String(),V.Unknown()))})});import{Hono as Wx}from"hono";var X1=o("Service"),Fx=V.Object({updates:V.Record(V.String(),V.Any()),options:V.Optional(V.Object({scope:V.Optional(JO(["local","project","global"])),immediate:V.Optional(V.Boolean())}))});function Ux(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 o1=()=>{let O=new Wx;return O.get("/",async($)=>{try{let x=QO();return $.json(x?Ux(x):{})}catch(x){return X1.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),Q=q(Fx,x);if(!Q.success)throw new _("Invalid config update format");let{updates:Z,options:G}=Q.data;return await BO().updateConfig(Z,G),$.json({success:!0,updates:Z})}catch(x){throw X1.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=QO();return $.json(x?.permissions||{})}catch(x){return X1.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as _x}from"hono";import{streamSSE as Dx}from"hono/streaming";function n1(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
|
|
2
2
|
`;if(O.event!==void 0)$+=`event: ${O.event}
|
|
3
3
|
`;for(let x of O.data.split(/\r\n|\r|\n/))$+=`data: ${x}
|
|
4
4
|
`;if(O.retry!==void 0)$+=`retry: ${O.retry}
|
|
5
5
|
`;return $+=`
|
|
6
|
-
`,Buffer.byteLength($)}class A0{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??t1,this.maxPendingBytes=O.maxPendingBytes??s1,this.serial=new e1({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??r1,sizeOf:n1,write:O.write,onFailure:($)=>{this.failure=$,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,O.onFailure?.($)}})}async writeInitial(O){await this.offerDirect(O)}observe(O,$){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer(O,$);return}this.offerLive(O,$)}async writeReplay(O,$){if(!Number.isSafeInteger($)||$<=0)throw this.fail(new x0("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if($<=this.highestReplaySequence)return;await this.offerDirect(O),this.highestReplaySequence=$,this.highestDeliveredSequence=$}finishInitialization(O){if(this.phase!=="buffering")return;let $=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let x=O.replayed?$.filter((Z)=>Z.sequence!==void 0&&Z.sequence>this.highestReplaySequence).sort((Z,G)=>Z.sequence-G.sequence||Z.order-G.order):$.sort((Z,G)=>Z.order-G.order),Q;for(let Z of x){if(O.replayed&&Z.sequence!==void 0&&Z.sequence===Q)continue;if(this.offerLive(Z.message,Z.sequence),this.serial.stats().closed)return;Q=Z.sequence}}offerHeartbeat(O){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive(O),!this.serial.stats().closed}async flush(){await this.serial.flush()}close(O){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close(O)}stats(){let O=this.serial.stats();return{closed:this.phase==="closed",pendingItems:O.pendingItems+this.buffered.length,pendingBytes:O.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer(O,$){let x=n1(O),Q=this.serial.stats();if(x>this.maxPendingBytes){this.fail(new x0("oversized",`SSE frame requires ${x} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:Q.pendingItems+this.buffered.length,pendingBytes:Q.pendingBytes+this.bufferedBytes}));return}if(Q.pendingItems+this.buffered.length>=this.maxPendingItems||Q.pendingBytes+this.bufferedBytes+x>this.maxPendingBytes){this.fail(new x0("overflow","SSE initialization buffer limit exceeded",{pendingItems:Q.pendingItems+this.buffered.length,pendingBytes:Q.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:x,sequence:$,order:this.nextOrder}),this.bufferedBytes+=x}offerLive(O,$){if($!==void 0){if($<=this.highestReplaySequence)return;if($<=this.highestDeliveredSequence){this.fail(new x0("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=$}if(!this.serial.offer(O).accepted)this.phase="closed"}async offerDirect(O){if(this.phase==="closed")throw this.currentFailure();let $=this.serial.offer(O);if(!$.accepted)throw this.phase="closed",$.error;await $.completion}fail(O){this.serial.close(O)}currentFailure(){return this.failure??new x0("closed","SSE egress is closed")}}var Hx=15000,Lx=o("Service"),Bx=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),wx=new Set(["queued","running","completed","failed","cancelled","interrupted"]),Ax=new Set(["high","medium","low"]),Mx=new Set(["feature","bug","maintenance","research"]);function Tx(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=["changedFiles","additions","deletions","commits"];if(x.some((Q)=>typeof $[Q]!=="number"||!Number.isInteger($[Q])||$[Q]<0))return;return Object.fromEntries(x.map((Q)=>[Q,$[Q]]))}function M0(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function jx(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if(!["applied","discarded","conflicted"].includes(String($.status))||typeof $.updatedAt!=="string")return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},...M0($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}var O$=()=>{let O=new _x;return O.get("/",($)=>Dx($,async(x)=>{let Q,Z,G=!1,z,U,j=new Promise((F)=>{U=F}),L=()=>{if(Z!==void 0)clearInterval(Z),Z=void 0;Q?.(),Q=void 0},b=(F)=>{if(G)return;G=!0,L(),z?.close(F),U()};x.onAbort(b),z=new A0({write:async(F)=>{await x.writeSSE(F)},onFailure:(F)=>{Lx.warn(`[EventRoutes] SSE egress closed: kind=${F.kind} pendingItems=${F.pendingItems??0} pendingBytes=${F.pendingBytes??0}`),b(F)}});let w=(F,P)=>{z?.observe({data:JSON.stringify({type:F,properties:P})})};Q=S.subscribe((F)=>{if(!Bx.has(F.type))return;if(F.type==="permission.asked"||F.type==="question.required"||F.type==="elicitation.required"){let n=F.properties.requestId;if(typeof n!=="string"||!n)return;w("interaction.pending",{sessionId:F.sessionId,projectPath:F.projectPath,interactionType:F.type==="question.required"?"question":F.type==="elicitation.required"?"elicitation":"permission",requestId:n});return}if(F.type==="interaction.resolved"){let n=F.properties.requestId;if(typeof n!=="string"||!n)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,requestId:n});return}if(F.type==="session.created"||F.type==="session.deleted"){w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath});return}if(F.type==="session.updated"){let n=F.properties.title,$O=F.properties.taskPriority,PO=F.properties.taskKind,s=F.properties.taskDueAt,lO=typeof n==="string"&&Boolean(n.trim()),wO=Ax.has(String($O)),N=Mx.has(String(PO)),NO=s===null||typeof s==="string"&&Number.isFinite(Date.parse(s));if(!lO&&!wO&&!N&&!NO)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,...lO?{title:n}:{},...wO?{taskPriority:$O}:{},...N?{taskKind:PO}:{},...NO?{taskDueAt:s}:{}});return}if(F.type==="task.delivery"){let n=jx(F.properties.taskDelivery);if(!n)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,taskDelivery:n,...F.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof F.properties.updatedAt==="string"?{updatedAt:F.properties.updatedAt}:{}});return}if(F.type==="schedule.fired"){let n=F.properties.scheduleId,$O=F.properties.firedAt;if(typeof n!=="string"||typeof $O!=="string")return;w(F.type,{scheduleId:n,firedAt:$O,sessionId:F.sessionId,projectPath:F.projectPath,...typeof F.properties.runId==="string"?{runId:F.properties.runId}:{},...typeof F.properties.status==="string"?{status:F.properties.status}:{}});return}let P=F.properties.taskStatus;if(typeof P!=="string"||!wx.has(P))return;let ZO=Tx(F.properties.taskDiffStat),d=M0(F.properties.taskQueuePosition,1),C=M0(F.properties.taskQueueDepth,0),e=M0(F.properties.taskConcurrencyLimit,1),v=M0(F.properties.taskInFlight,0),YO=typeof F.properties.taskAdmissionPaused==="boolean"?F.properties.taskAdmissionPaused:void 0;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,taskStatus:P,...typeof F.properties.taskStatusReason==="string"?{taskStatusReason:F.properties.taskStatusReason}:{},...F.properties.taskFailure&&typeof F.properties.taskFailure==="object"?{taskFailure:F.properties.taskFailure}:{},...typeof F.properties.taskStartedAt==="string"?{taskStartedAt:F.properties.taskStartedAt}:{},...typeof F.properties.taskCompletedAt==="string"?{taskCompletedAt:F.properties.taskCompletedAt}:{},...typeof F.properties.updatedAt==="string"?{updatedAt:F.properties.updatedAt}:{},...ZO?{taskDiffStat:ZO}:{},...d!==void 0?{taskQueuePosition:d}:{},...C!==void 0?{taskQueueDepth:C}:{},...e!==void 0?{taskConcurrencyLimit:e}:{},...v!==void 0?{taskInFlight:v}:{},...YO!==void 0?{taskAdmissionPaused:YO}:{}})});try{if(x.aborted||G)return;if(await z.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),x.aborted||G)return;if(z.finishInitialization({replayed:!1}),x.aborted||G)return;Z=setInterval(()=>{if(x.aborted||G)return;z?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},Hx),await j}finally{b()}})),O};import{Hono as bx}from"hono";var Cx=V.Object({paused:V.Boolean()}),x$=()=>{let O=new bx;return O.get("/health",($)=>{return $.json({healthy:!0,version:Q0()})}),O.get("/info",($)=>{let x=c(),Q=QO();if(Q)mO.configure(Q.maxConcurrentTasks,Q.maxQueuedTasks,Q.maxQueuedTaskBytes);let Z=mO.getStats();return $.json({version:Q0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:x,gitBranch:$$(x),taskAdmission:{inFlight:Z.inFlight,queued:Z.queued,maxConcurrent:Z.maxConcurrent,maxQueued:Z.maxQueued,paused:Z.paused}})}),O.put("/task-admission",async($)=>{let x;try{x=await $.req.json()}catch{throw new _("Invalid request body")}let Q=q(Cx,x);if(!Q.success)throw new _("Invalid task admission control request");mO.setPaused(Q.data.paused);let Z=mO.getStats();return $.json({inFlight:Z.inFlight,queued:Z.queued,maxConcurrent:Z.maxConcurrent,maxQueued:Z.maxQueued,paused:Z.paused})}),O};import Q$ from"node:path";import{Hono as Sx}from"hono";var Rx=V.Object({projectPath:V.String({minLength:1}),action:JO(["trust","revoke"]),expectedDigest:V.Optional(V.String())}),Ex=V.Object({projectPath:V.String({minLength:1}),sessionId:V.String({minLength:1}),enabled:V.Boolean()});function V1(O){if(!O||!Q$.isAbsolute(O))throw new _("projectPath must be absolute");return Q$.resolve(O)}function Z$(O){if(!O)throw new _("sessionId is required");try{i0(O)}catch($){throw new _($ instanceof Error?$.message:"sessionId is invalid")}return O}async function l0(O){let $=V1(O),x=QO()?.hooks??z$.hooks,Q=await T0.getInstance().loadWorkspaceHooks($,x,{includeBaseForCurrentWorkspace:!1});return C0($,async()=>{b0($);let Z=Z0.getInstance();return Z.loadConfig(Q,$),await j0($),Z.getConfig($)})}function J$(O,$){let x=Z0.getInstance(),Q=x.getConfig($).enabled,Z=x.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:x.isSessionEnabled(O,$),paused:Z,configEnabled:Q}}var G$=()=>{let O=new Sx;return O.get("/trust",async($)=>{let x=$.req.query("projectPath");if(!x)throw new _("projectPath query parameter is required");return await l0(x),$.json(await Z0.getInstance().getTrustStatus(x))}),O.post("/trust",async($)=>{let x=q(Rx,await $.req.json());if(!x.success)throw new _("Invalid hook trust request");let{projectPath:Q,action:Z,expectedDigest:G}=x.data;await l0(Q);let z=Z0.getInstance(),U;try{U=Z==="trust"?await z.trustProject(Q,G):await z.revokeProjectTrust(Q)}catch(j){if(j instanceof Y$)throw new k(j.message);throw j}return $.json(U)}),O.get("/session",async($)=>{let x=V1($.req.query("projectPath")),Q=Z$($.req.query("sessionId"));return await l0(x),$.json(J$(Q,x))}),O.post("/session",async($)=>{let x=q(Ex,await $.req.json());if(!x.success)throw new _("Invalid hook session request");let Q=V1(x.data.projectPath),Z=Z$(x.data.sessionId);await l0(Q);let G=Z0.getInstance();if(x.data.enabled)G.enableSession(Z,Q);else G.disableSession(Z,Q);return $.json(J$(Z,Q))}),O};import{Hono as kx}from"hono";var RO=o("Service");function qx(O){try{return V$(O)}catch{return[]}}function Ix(O){if(!c0(O)||!c0(O.reference)||!c0(O.argument))throw Error("Invalid MCP completion request");let $=O.reference.type,x=$==="prompt"&&typeof O.reference.name==="string"?{type:"prompt",name:O.reference.name}:$==="resource"&&typeof O.reference.uri==="string"?{type:"resource",uri:O.reference.uri}:void 0;if(!x||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let Q;if(O.context!==void 0){if(!c0(O.context))throw Error("Invalid MCP completion context");Q=Object.create(null);for(let[Z,G]of Object.entries(O.context)){if(typeof G!=="string")throw Error("Invalid MCP completion context");Q[Z]=G}}return{reference:x,argument:{name:O.argument.name,value:O.argument.value},...Q?{context:Q}:{}}}function c0(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function hO(O,$){let x=QO()?.mcpServers??{};for(let[Q,Z]of Object.entries(x)){if($&&Q!==$)continue;if(!O.getServerStatus(Q))await O.registerServer(Q,Z,{connect:!1})}}var N$=()=>{let O=new kx;return O.get("/",async($)=>{try{let x=UO.getInstance();await hO(x);let Q=x.getAllServers(),Z=await Promise.all(Array.from(Q.entries()).map(async([G,z])=>({id:G,name:G,status:z.status==="connected"?"connected":z.status==="reconnecting"?"reconnecting":z.status==="connecting"?"connecting":z.lastError?"error":"offline",endpoint:z.config.command?`${z.config.command} ${(z.config.args||[]).join(" ")}`.trim():z.config.url||"Unknown",description:`MCP server: ${G}`,tools:z.tools.map((U)=>U.name),completionSupported:z.client.completionSupported,tasks:z.client.tasks,resources:z.contentCatalog.resources,resourceTemplates:z.contentCatalog.resourceTemplates.map((U)=>({...U,variables:qx(U.uriTemplate)})),prompts:z.contentCatalog.prompts,connectedAt:z.connectedAt?.toISOString(),error:z.lastError?.message,recovery:z.recovery,logging:z.logging,instructions:z.instructions,oauthEnabled:z.client.oauthEnabled,oauthStatus:await z.client.getOAuthStatus()})));return $.json(Z)}catch(x){return RO.error("[McpRoutes] Failed to get MCP servers:",x),$.json({error:x instanceof Error?x.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();return await hO(Q,x),await Q.connectServer(x),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to connect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();return await hO(Q,x),await Q.disconnectServer(x),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to disconnect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.get("/:name/logs",async($)=>{try{let x=$.req.param("name"),Q=Number($.req.query("limit")??20),Z=Number($.req.query("afterRevision")??0);if(!Number.isSafeInteger(Q)||Q<1||Q>100||!Number.isSafeInteger(Z)||Z<0)return $.json({error:"Invalid MCP log pagination"},400);let G=UO.getInstance();return await hO(G,x),$.json(G.getLogSnapshot(x,{limit:Q,afterRevision:Z}))}catch(x){return RO.error("[McpRoutes] Failed to get MCP logs:",x),$.json({error:x.message},500)}}),O.post("/:name/logging-level",async($)=>{try{let x=$.req.param("name"),Q=await $.req.json();if(!X$(Q.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let Z=UO.getInstance();return await hO(Z,x),await Z.setServerLoggingLevel(x,Q.level),$.json({success:!0,level:Q.level})}catch(x){return RO.error("[McpRoutes] Failed to set MCP logging level:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/complete",async($)=>{try{let x=$.req.param("name"),Q=Ix(await $.req.json()),Z=UO.getInstance();await hO(Z,x);let G=await Z.complete(x,Q);return $.json(G)}catch(x){return RO.error("[McpRoutes] Failed to complete MCP argument:",x),$.json({error:x.message},400)}}),O.post("/:name/oauth/login",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();await hO(Q,x);let Z=await Q.beginOAuthLogin(x);return $.json({success:!0,flowId:Z.flowId,authorizationUrl:Z.authorizationUrl},202)}catch(x){return RO.error("[McpRoutes] Failed to start MCP OAuth login:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/oauth/logout",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();return await hO(Q,x),await Q.logoutOAuth(x),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to log out MCP OAuth:",x),$.json({success:!1,error:x.message},400)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name");await UO.getInstance().unregisterServer(x);let Z=QO();if(Z?.mcpServers){let{[x]:G,...z}=Z.mcpServers;await BO().updateConfig({mcpServers:z})}return $.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to delete MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/",async($)=>{try{let x=await $.req.json(),{name:Q,config:Z}=x;if(!Q||!Z)return $.json({success:!1,error:"Missing name or config"},400);await UO.getInstance().registerServer(Q,Z);let z=QO();return await BO().updateConfig({mcpServers:{...z?.mcpServers,[Q]:Z}}),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to add MCP server:",x),$.json({success:!1,error:x.message},500)}}),O};import{getSupportedThinkingLevels as Px}from"@earendil-works/pi-ai";import{Hono as yx}from"hono";var a0=o("Service");function fx(O,$,x=U$.list()){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,supportedReasoningEfforts:Px($),supportedServiceTiers:W$($),supportedResponseVerbosities:K$($),communicationStyles:x,input:$.input}}function mx(O){_$(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function _$(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new _("streamIdleTimeout must be at least 1000ms")}var D$=()=>{let O=new yx;return O.get("/",async($)=>{try{let x=QO();if(!x)throw Error("Config not initialized");let Q=$.get("directory")||c(),[Z,G]=await Promise.all([o0(Q,x),jO(Q)]),z=Z.config.models,U=z.find((w)=>w.id===Z.config.currentModelId)??z[0],j=Z.catalog,L=G.communicationStyles.list(),b=(w)=>fx(w,j.resolveConfig(w),L);return $.json({configured:z.map(b),current:U?b(U):null})}catch(x){a0.error("[ModelsRoutes] Failed to get models:",x);let Q=new t("Failed to get models");return $.json(Q.toObject(),500)}}),O.post("/",async($)=>{let x=cO(),Q,Z;try{let G=await $.req.json(),{provider:z,displayName:U,model:j,overrides:L,apiKey:b,modelProvider:w}=G;if(!z||!j)throw new _("provider and model are required");_$(L);let F;if(w){if(w.id!==z)throw new _("modelProvider.id must match the model provider");if(QO()?.modelProviders[z])throw new _(`model provider already exists: ${z}`);F={name:w.name,baseUrl:w.baseUrl,wireApi:w.wireApi,...w.apiKeyEnv?{apiKeyEnv:w.apiKeyEnv}:{}};try{x.registerModelProvider(z,F,[j]),Z=z}catch(d){throw new _(d instanceof Error?d.message:"Invalid model provider")}}else x.getModel(z,j);if(b?.trim()){if(await x.setApiKey(z,b.trim()),F)Q=z}let P={provider:z,displayName:U||void 0,model:j,overrides:L||void 0},ZO=F?await BO().addModelWithProvider(P,F):await BO().addModel(P);return $.json({success:!0,model:ZO})}catch(G){if(Q)await x.credentials.delete(Q);if(Z){let z=QO();x.configureModelProviders(z?.modelProviders??{},z?.models??[])}throw a0.error("[ModelsRoutes] Failed to add model:",G),G}}),O.put("/:modelId",async($)=>{try{let x=$.req.param("modelId"),Q=await $.req.json(),{displayName:Z,overrides:G,model:z}=Q,U=F$(x);if(!U)throw new _("model config not found");if(z)cO().getModel(U.provider,z);return await BO().updateModel(x,mx({displayName:Z,overrides:G,model:z})),$.json({success:!0})}catch(x){throw a0.error("[ModelsRoutes] Failed to update model:",x),x}}),O.delete("/:modelId",async($)=>{try{let x=$.req.param("modelId");return await BO().removeModel(x),$.json({success:!0})}catch(x){throw a0.error("[ModelsRoutes] Failed to delete model:",x),x}}),O};import{Hono as $2}from"hono";import H$ from"node:path";import{Hono as hx}from"hono";import{streamSSE as gx}from"hono/streaming";import{LRUCache as vx}from"lru-cache";import{nanoid as Y0}from"nanoid";var g=o("Service"),ux=V.Object({title:V.Optional(V.String()),projectPath:V.Optional(V.String())}),px=l$,dx=V.Object({title:V.Optional(V.String()),projectPath:V.Optional(V.String())}),lx=V.Object({projectPath:V.String()}),ix=V.Object({objective:V.String({minLength:1}),tokenBudget:V.Optional(V.Integer({minimum:1})),permissionMode:V.Optional(JO(["default","autoEdit","plan","yolo"]))}),cx=V.Union([V.Object({action:V.Literal("pause")}),V.Object({action:V.Literal("resume")}),V.Object({action:V.Literal("edit"),objective:V.String({minLength:1})})]),r=new Map,G0,CO=new Map,IO=new Map,bO=new Map,e0=new vx({max:100,ttl:1800000});function L$(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function DO(O){if(!O)return;return CO.get(O)??e0.get(O)}function ax(O){if(CO.get(O.id)!==O)return;CO.delete(O.id),e0.set(O.id,O)}function ox(O){CO.delete(O),e0.delete(O)}function _O(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function k0(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let x=O.pendingPermission;if(O.pendingPermission=void 0,x?.resolve({approved:!1,reason:S$}),x)S.publish(L$(O),"interaction.resolved",{requestId:x.permissionId});return O.abortController.abort($),O.status="cancelled",S.publish(L$(O),"run.cancelled",{runId:O.id}),!0}function n$(O,$=!1){let{permissionId:x,details:Q}=O;if(Q.type==="askUserQuestion"&&Q.questions)return{type:"question.required",properties:{requestId:x,toolCallId:Q.toolCallId??x,questions:Q.questions,details:Q,...$?{replayed:!0}:{}}};if(Q.type==="mcpElicitation"&&Q.mcpElicitation)return{type:"elicitation.required",properties:{requestId:x,toolCallId:Q.toolCallId??x,elicitation:Q.mcpElicitation,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:Q.toolName,description:Q.message,args:Q.args,details:Q,...$?{replayed:!0}:{}}}}function nx(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 tx(){for(let O of CO.values())k0(O,"route-reset");CO.clear();for(let O of IO.values())O.controller.abort("route-reset");IO.clear(),e0.clear(),G0=void 0,r.clear()}function sx(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=$.code,Q=$.reason,Z=$.scope,G=$.kind,z=$.limit;if(x!=="tool_busy"&&x!=="tool_batch_full"||Q!=="queue_full"&&Q!=="wait_timeout"&&Q!=="turn_limit"||Z!=="global"&&Z!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(z)||z<=0||G!==void 0&&G!=="readonly"&&G!=="write"&&G!=="execute")return;return{code:x,reason:Q,scope:Z,retryable:$.retryable,...G===void 0?{}:{kind:G},limit:z}}var q0=(O,$)=>{if(!$||typeof $!=="object")return $;let x={...$},Q=sx(x.tool_admission);if(Q)x.tool_admission=Q;else delete x.tool_admission;if(O==="Bash"){let z={},U=["message","signal","status","summary"],j=["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"],L=["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 w of U){let F=x[w];if(typeof F==="string")z[w]=F.slice(0,8192)}for(let w of j){let F=x[w];if(typeof F==="boolean")z[w]=F}for(let w of L){let F=x[w];if(typeof F==="number"&&Number.isSafeInteger(F)&&F>=0)z[w]=F}if(x.exit_code===null||typeof x.exit_code==="number"&&Number.isSafeInteger(x.exit_code))z.exit_code=x.exit_code;if(x.terminal_transport==="local"||x.terminal_transport==="acp"||x.terminal_transport==="local_fallback")z.terminal_transport=x.terminal_transport;if(x.background_reason==="explicit"||x.background_reason==="foreground_budget")z.background_reason=x.background_reason;for(let w of["bash_id","shell_id"]){let F=x[w];if(typeof F==="string"&&F.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(F))z[w]=F}if(Q)z.tool_admission=Q;let b=x.background_shell_admission;if(b&&typeof b==="object"&&!Array.isArray(b)){let w=b;if(w.code==="background_shell_busy"&&(w.scope==="session"||w.scope==="global")&&w.retryable===!0&&Number.isSafeInteger(w.limit)&&w.limit>0)z.background_shell_admission={code:w.code,scope:w.scope,retryable:w.retryable,limit:w.limit}}return z}let Z=200000,G=(z,U)=>typeof z==="number"&&Number.isSafeInteger(z)&&z>=0&&z<=U?z:0;if(typeof x.oldContent==="string"&&x.oldContent.length>Z)delete x.oldContent;if(typeof x.newContent==="string"&&x.newContent.length>Z)delete x.newContent;if(x.mcpResult&&typeof x.mcpResult==="object"&&!Array.isArray(x.mcpResult)){let z=x.mcpResult,U=Array.isArray(z.artifacts)?z.artifacts.slice(0,64).flatMap((j)=>{if(!j||typeof j!=="object"||Array.isArray(j))return[];let L=j,b=new Set(["text","image","audio","resource"]);if(typeof L.id!=="string"||!/^[a-f0-9]{64}$/.test(L.id)||typeof L.sha256!=="string"||L.sha256!==L.id||typeof L.kind!=="string"||!b.has(L.kind)||G(L.size,67108864)!==L.size||typeof L.persisted!=="boolean")return[];return[{id:L.id.slice(0,128),sha256:L.sha256.slice(0,128),kind:L.kind,size:L.size,persisted:L.persisted,...typeof L.mimeType==="string"?{mimeType:L.mimeType.slice(0,256)}:{},...typeof L.sourceUri==="string"?{sourceUri:L.sourceUri.slice(0,8192)}:{},...typeof L.path==="string"?{path:L.path.slice(0,8192)}:{}}]}):[];x.mcpResult={isError:z.isError===!0,contentCount:G(z.contentCount,64),textBytes:G(z.textBytes,4194304),structuredBytes:G(z.structuredBytes,4194304),artifactCount:G(z.artifactCount,64),truncated:z.truncated===!0,binaryOmitted:z.binaryOmitted===!0,artifacts:U}}else delete x.mcpResult;return x};function rx(O){let $=typeof O.seq==="number"?{seq:O.seq}:{};if(O.type==="part_created"&&O.data.partType==="tool_call"){let x=O.data.payload;return{type:"tool.start",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let x=O.data.payload,Q=x.toolName??"unknown",Z=A1(x),G=P0(y0(Q,Z),I0);return{type:"tool.result",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:Q,success:Z.success,status:Z.success?"completed":"failed",summary:Z.metadata?.summary,output:f0(G),metadata:q0(Q,Z.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function ex(O,$,x){switch(x.kind){case"tool_start":if("function"in x.toolCall)S.publish(O,"subagent.update",{subagentSessionId:$,toolName:x.toolCall.function.name}),S.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,arguments:x.toolCall.function.arguments,toolKind:x.toolKind});break;case"tool_result":if("function"in x.toolCall)S.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,success:x.result.success,summary:x.result.metadata?.summary,output:f0(P0(y0(x.toolCall.function.name,x.result),I0)),metadata:q0(x.toolCall.function.name,x.result.metadata)});break;case"tool_progress":if("function"in x.toolCall)S.publish(O,"subagent.tool.progress",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,...x.update});break;case"content_delta":S.publish(O,"subagent.delta",{subagentSessionId:$,delta:x.delta});break;case"thinking_delta":S.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:x.delta});break;case"stream_end":S.publish(O,"subagent.stream.end",{subagentSessionId:$});break;case"provider_admission":S.publish(O,"subagent.provider.admission",{subagentSessionId:$,phase:x.phase,requestClass:x.requestClass,resource:x.resource,scope:x.scope,reason:x.reason,queuePosition:x.queuePosition,queueDepth:x.queueDepth,inFlight:x.inFlight,limit:x.limit,waitMs:x.waitMs,maxWaitMs:x.maxWaitMs,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_circuit":S.publish(O,"subagent.provider.circuit",{subagentSessionId:$,phase:x.phase,reason:x.reason,statusCode:x.statusCode,retryAfterMs:x.retryAfterMs,nextProbeAt:x.nextProbeAt,openDurationMs:x.openDurationMs,sampleCount:x.sampleCount,failureCount:x.failureCount,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_retry":S.publish(O,"subagent.provider.retry",{subagentSessionId:$,phase:x.phase,attempt:x.attempt,maxRetries:x.maxRetries,reason:x.reason,statusCode:x.statusCode,delayMs:x.delayMs,nextRetryAt:x.nextRetryAt,mode:x.mode,recoveryBudgetMs:x.recoveryBudgetMs,recoveryElapsedMs:x.recoveryElapsedMs,recoveryRemainingMs:x.recoveryRemainingMs,exhaustedBy:x.exhaustedBy});break;case"provider_stall":S.publish(O,"subagent.provider.stall",{subagentSessionId:$,phase:x.phase,stallCount:x.stallCount,durationMs:x.durationMs,warningAfterMs:x.warningAfterMs,timeoutMs:x.timeoutMs,outputStarted:x.outputStarted});break;case"action_stationarity":S.publish(O,"subagent.action.stationarity",{subagentSessionId:$,phase:x.phase,toolName:x.toolName,runLength:x.runLength,nudgeThreshold:x.nudgeThreshold,haltThreshold:x.haltThreshold,progressAware:x.progressAware});break;case"mcp_catalog_changed":S.publish(O,"subagent.mcp.catalog.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_content_changed":S.publish(O,"subagent.mcp.content.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,contentKind:x.contentKind,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_resource_updated":S.publish(O,"subagent.mcp.resource.updated",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,uri:x.uri});break;case"mcp_connection_changed":S.publish(O,"subagent.mcp.connection.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,phase:x.phase,reason:x.reason,attempt:x.attempt,maxAttempts:x.maxAttempts,nextRetryAt:x.nextRetryAt,error:x.error});break;case"mcp_log":S.publish(O,"subagent.mcp.log",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,level:x.level,logger:x.logger,message:x.message,projectedBytes:x.projectedBytes,dataSha256:x.dataSha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted,timestamp:x.timestamp,synthetic:x.synthetic});break;case"mcp_instructions_changed":S.publish(O,"subagent.mcp.instructions.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,action:x.action,reason:x.reason,text:x.text,sourceBytes:x.sourceBytes,projectedBytes:x.projectedBytes,sha256:x.sha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted});break;case"mcp_task_changed":S.publish(O,"subagent.mcp.task.changed",{subagentSessionId:$,revision:x.revision,taskId:x.taskId,serverName:x.serverName,toolName:x.toolName,status:x.status,statusMessage:x.statusMessage,createdAt:x.createdAt,updatedAt:x.updatedAt,completedAt:x.completedAt,hasResult:x.hasResult,error:x.error});break;case"project_rules_loaded":S.publish(O,"subagent.project.rules.loaded",{subagentSessionId:$,files:x.files,triggerPaths:x.triggerPaths,blockedWrite:x.blockedWrite});break;default:break}}function R0(O,$="projectPath"){if(!H$.isAbsolute(O))throw new _(`${$} must be absolute`);return H$.resolve(O)}function B1(O){try{i0(O)}catch($){throw new _($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function GO(O){return{sessionId:O.id,projectPath:O.projectPath}}function E0(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:x,messages:$}}function N1(O){return O.flatMap(($)=>{if(!E$($)||$.role==="system"||$.role==="tool"&&$.name===z0)return[];let x=$.tool_calls?.filter((z)=>!("function"in z)||z.function.name!==z0),Q=typeof $.content==="string"?$.content.trim():"";if($.role==="assistant"&&$.tool_calls?.length&&!x?.length&&!Q&&!$.reasoningContent&&!$.metadata)return[];let Z={...$,...$.tool_calls?{tool_calls:x&&x.length>0?x:void 0}:{}};if($.role==="tool"){let z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0,U=$.name??(typeof z?.toolName==="string"?z.toolName:"unknown");if(z!==void 0&&(Object.hasOwn(z,"output")||Object.hasOwn(z,"error"))){let L=A1(z),b=P0(y0(U,L),I0);return[{...Z,name:U,content:f0(b),metadata:q0(U,{...L.metadata,status:L.success?"completed":"failed"})}]}return[{...Z,name:U,metadata:q0(U,z)}]}let G=q$($.metadata);return[G?{...Z,content:k$(G)}:Z]})}function X0(O,$){O.title=$.title??O.title,O.taskStatus=$.taskStatus,O.taskStatusReason=$.taskStatusReason,O.taskFailure=$.taskFailure,O.taskStartedAt=$.taskStartedAt,O.taskCompletedAt=$.taskCompletedAt,O.taskPromptSummary=$.taskPromptSummary,O.taskPriority=$.taskPriority,O.taskKind=$.taskKind,O.taskDueAt=$.taskDueAt,O.taskModelId=$.taskModelId,O.selectedModelId=$.selectedModelId,O.permissionMode=$.permissionMode,O.reasoningEffort=$.reasoningEffort,O.serviceTier=$.serviceTier,O.responseVerbosity=$.responseVerbosity,O.communicationStyle=$.communicationStyle,O.communicationStyleDigest=$.communicationStyleDigest,O.projectInstructionsDigest=$.projectInstructionsDigest,O.pendingInteraction=$.pendingInteraction,O.taskRetryAvailable=$.taskRetryAvailable,O.taskRetriedFrom=$.taskRetriedFrom,O.taskDelivery=$.taskDelivery,O.taskIsolation=$.taskIsolation,O.taskSourceProjectPath=$.taskSourceProjectPath,O.taskWorktreePath=$.taskWorktreePath,O.taskWorktreeBranch=$.taskWorktreeBranch,O.taskBaseCommit=$.taskBaseCommit,O.taskDiffStat=$.taskDiffStat,O.taskQueuePosition=$.taskQueuePosition,O.taskQueueDepth=$.taskQueueDepth,O.taskConcurrencyLimit=$.taskConcurrencyLimit,O.archivedAt=$.archivedAt,O.archivedBySessionId=$.archivedBySessionId,O.updatedAt=new Date($.lastMessageTime)}async function tO(O){let $=await R.findSessionMetadata(O.id,O.projectPath);if($)X0(O,$)}function aO(O){let $=DO(O.currentRunId),x=$?.status==="waiting_permission"?"running":$?.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:x,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:x==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:x==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:$?.pendingPermission?{type:$.pendingPermission.details.type==="askUserQuestion"?"question":$.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:$.pendingPermission.permissionId}:O.pendingInteraction,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function KO(O,$){if(B1(O),$!==void 0){let Q=gO({sessionId:O,projectPath:R0($)});if(r.has(u(Q)))return Q;let Z=await R.findSessionMetadata(Q.sessionId,Q.projectPath);if(!Z)throw new f("Session",O);return gO({sessionId:Z.sessionId,projectPath:Z.projectPath})}let x=new Map;for(let Q of r.values()){if(Q.id!==O)continue;let Z=GO(Q);x.set(u(Z),Z)}for(let Q of await R.listSessions()){if(Q.sessionId!==O)continue;let Z=gO({sessionId:Q.sessionId,projectPath:Q.projectPath});x.set(u(Z),Z)}if(x.size===0)try{let Q=await R.findSessionMetadata(O);if(!Q)throw new f("Session",O);return gO({sessionId:Q.sessionId,projectPath:Q.projectPath})}catch(Q){if(Q instanceof f)throw Q;if(Q instanceof Error&&Q.message.startsWith("Ambiguous session ID:"))throw new LO;throw Q}if(x.size>1)throw new LO;return x.values().next().value}function w1(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
|
|
7
|
-
`)}function B$(O,$){let x=($??[]).filter((Z)=>Z.type==="image"&&typeof Z.content==="string").map((Z)=>({type:"image_url",image_url:{url:Z.content}}));if(x.length===0)return O;let Q=[];if(O.trim())Q.push({type:"text",text:O});return Q.push(...x),Q}var t$=()=>{tx();let O=new hx;O.onError((J,K)=>{if(J instanceof J0){let Y=new kO("Session runtime capacity is full",{resource:J.resource,limit:J.limit});return K.json(Y.toObject(),429)}if(J instanceof xO)return K.json(J.toObject(),J.statusCode);return g.error("[SessionRoutes] Unhandled route error:",J),K.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,x=new Map,Q=new Map,Z=new Map,G=new K1,z=new K1,U=QO(),j=new o$({maxResident:U?.maxResidentSessionRuntimes??M$,idleMs:U?.sessionRuntimeIdleMs??T$}),L=new h$,b=setInterval(()=>{j.sweepIdle().catch((J)=>{g.warn("[SessionRoutes] Session Runtime idle sweep failed:",J)})},j$);b.unref?.();let w,F=async(J)=>{let K;try{K=L.enter()}catch{throw new qO}try{return await J()}finally{K.release()}};O.use("*",async(J,K)=>{if(J.req.method==="GET"||J.req.method==="HEAD")return K();return F(K)});let P=(J,K)=>G.runExclusive(u(J),K),ZO=(J,K)=>z.runExclusive(u(J),K),d=(J)=>[...CO.values()].some((K)=>K.sessionId===J.sessionId&&K.projectPath===J.projectPath&&_O(K)),C=async(J,K,Y)=>{let X=Q.get(K);if(!X)X=(async()=>{if($.get(K)===Y)$.delete(K);for(let[H,D]of $)if(D===Y)$.delete(H);let W=GO(J);if(r.get(K)===J&&!d(W)&&!IO.has(K)&&!bO.has(K))r.delete(K);if(await Y.dispose(),$.size===0)await UO.getInstance().disconnectAll()})().finally(()=>{if(Q.get(K)===X)Q.delete(K)}),Q.set(K,X);await X},e=async(J,K={})=>{let Y=GO(J),X=u(Y);await Q.get(X);let W=j.acquire(X);if(W){if($.get(X)!==W.value)throw W.release(),Error("Session Runtime residency identity is inconsistent");return W}if(j.owns(X))throw new J0(j.getStats().maxResident);let H=x.get(X);if(!H){let D=K.communicationStyle??J.communicationStyle;H=(async()=>{let B=await j.reserve(X,{surface:"web",allowEviction:!0});try{let A=await S0.create({sessionId:J.id,workspaceRoot:J.projectPath,...J.selectedModelId??J.taskModelId?{modelId:J.selectedModelId??J.taskModelId}:{},permissionMode:K.permissionMode??J.permissionMode??"default",...J.reasoningEffort?{reasoningEffort:J.reasoningEffort}:{},...J.serviceTier?{serviceTier:J.serviceTier}:{},...J.responseVerbosity?{responseVerbosity:J.responseVerbosity}:{},...D?{communicationStyle:D}:{},...D===J.communicationStyle&&J.communicationStyleDigest?{communicationStyleDigest:J.communicationStyleDigest}:{},...J.projectInstructionsDigest?{projectInstructionsDigest:J.projectInstructionsDigest}:{},...J.taskWorktree?{taskWorktree:J.taskWorktree}:{},...J.taskIsolation?{taskIsolation:J.taskIsolation}:{},...J.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:J.id}}:{}}),M=B.commit({key:X,surface:"web",value:A,canEvict:()=>!d(Y)&&!IO.has(X)&&!bO.has(X)&&!x.has(X)&&!Q.has(X)&&A.isIdleForResidency(),dispose:()=>C(J,X,A)});return $.set(X,A),{runtime:A,claimLease:()=>{if(M){let y=M;return M=void 0,y}let T=j.acquire(X);if(!T||T.value!==A)throw Error("Initialized Session Runtime lost residency");return T}}}catch(A){throw B.cancel(),A}})(),x.set(X,H)}try{return(await H).claimLease()}finally{if(x.get(X)===H)x.delete(X)}},v=async(J,K,Y={})=>{let X=await e(J,Y);try{return await K(X.value)}finally{X.release()}},YO=async(J,K)=>{let Y=u(GO(J)),X=x.get(Y);if(X)await X.catch(()=>{return});x.delete(Y);let W=K??$.get(Y);if(!W)return;if(!await j.remove(Y,W))throw Error(`Session Runtime is pinned and cannot be disposed: ${Y}`)},n=async(J)=>{let K=u(J),Y=r.get(K);if(Y)return Y;let X=Z.get(K);if(!X)X=(async()=>{let W=await R.findSessionMetadata(J.sessionId,J.projectPath);if(!W)throw new f("Session",J.sessionId);let[H,D]=await Promise.all([R.loadSession(J.sessionId,J.projectPath),R.findSessionTaskWorktree(J.sessionId,J.projectPath)]),B=E0(W,H,D);return r.set(K,B),B})(),Z.set(K,X);try{return await X}finally{if(Z.get(K)===X)Z.delete(K)}},$O=async(J,K)=>{let Y=await KO(J,K);try{await R.assertSessionWritable(Y.sessionId,Y.projectPath)}catch(X){if(X instanceof U1)throw new k(X.message);throw X}return n(Y)},PO=async(J,K)=>{if(J.permissionMode===K)return;let Y=await R.setSessionPermissionMode(J.id,J.projectPath,K);J.permissionMode=Y.permissionMode,J.updatedAt=new Date(Y.lastMessageTime),S.publish(GO(J),"session.updated",{permissionMode:K})},s=(J,K,Y,X={})=>{if(!L.stats().accepting)throw new qO;let W=Y0(12),H={id:W,sessionId:J.id,projectPath:J.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:J.taskIsolation!==void 0&&X.runtimeLease!==void 0,createdAt:new Date};if(J.taskIsolation&&X.runtimeLease){let D=X.runtimeLease.value,B=mO.admit({key:`${J.projectPath}\x00${J.id}`,...D.getTaskAdmissionLimits(),pendingBytes:g$({content:K,outputSchema:X.outputSchema,pendingMessages:D.getPendingSteeringMessages()}),signal:H.abortController.signal,onUpdate:(M)=>{H.status=M.state,J.taskStatus=M.state,J.taskQueuePosition=M.queuePosition,J.taskQueueDepth=M.queueDepth,J.taskConcurrencyLimit=M.maxConcurrent,H.taskAdmissionUpdate=(H.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await D.setTaskAdmission(M)}).catch((T)=>{g.warn(`[SessionRoutes] Failed to persist admission for ${J.id}:`,T)})}});H.taskAdmission=B;let A=B.getSnapshot();H.status=A.state,J.taskStatus=A.state,J.taskQueuePosition=A.queuePosition,J.taskQueueDepth=A.queueDepth,J.taskConcurrencyLimit=A.maxConcurrent}return CO.set(W,H),J.currentRunId=W,H.completion=O2(H,J,K,Y,e,{pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:H.taskAdmission,runtimeLease:X.runtimeLease,disposeRuntime:YO}).catch((D)=>{g.error(`[SessionRoutes] Run ${W} failed:`,D)}),H},lO=async(J)=>{let K;if(J.outputSchema)try{K=F1(J.outputSchema).schema}catch(h){throw new _(h instanceof Error?h.message:"Invalid output schema")}let Y=W1("task",12),X=R0(J.sourceProjectPath),W=J.modelId?.trim(),H=QO();if(!H)throw new _("Config not initialized");let[D,B]=await Promise.all([o0(X,H),jO(X)]);if(W&&!D.config.models.some((h)=>h.id===W))throw new _(`Task model not found: ${W}`);let A=W||D.config.models.find((h)=>h.id===D.config.currentModelId)?.id||D.config.models[0]?.id;if(!A)throw new _("No model is configured. Add or select a model before dispatching a task.");let M=D.config.models.find((h)=>h.id===A);if(!M)throw new _(`Task model not found: ${A}`);let T=J.reasoningEffort??"off",y=J.serviceTier??"auto",WO=J.responseVerbosity??"auto",yO=J.communicationStyle??"auto",TO,XO=B.projectRules?.staticRules(X),OO=XO&&XO.files.length>0?XO.provenanceSha256:void 0;try{let h=D.catalog.resolveConfig(M);b$(h,T),A$(h,y),w$(h,WO);let l=C$(yO,B.communicationStyles);TO=l.source==="built-in"?void 0:l.contentSha256}catch(h){throw new _(h instanceof Error?h.message:"Invalid reasoning effort")}let O0={version:1,prompt:J.prompt,...J.title?{title:J.title}:{},...J.taskPriority?{taskPriority:J.taskPriority}:{},...J.taskKind?{taskKind:J.taskKind}:{},...J.taskDueAt?{taskDueAt:J.taskDueAt}:{},sourceProjectPath:X,isolation:J.isolation,permissionMode:J.permissionMode,modelId:A,reasoningEffort:T,serviceTier:y,responseVerbosity:WO,communicationStyle:yO,...TO?{communicationStyleDigest:TO}:{},...OO?{projectInstructionsDigest:OO}:{},...J.attachments?{attachments:J.attachments.map((h)=>({...h}))}:{},...K?{outputSchema:K}:{}},E,m,I;try{let h=await u$.createSessionTask({sessionId:Y,prompt:J.prompt,title:J.title,taskPriority:J.taskPriority,taskKind:J.taskKind,taskDueAt:J.taskDueAt,sourceProjectPath:X,isolation:J.isolation,dispatch:O0,retriedFrom:J.retriedFrom}),{metadata:l}=h;E=h.taskWorktree,m=E0(l,[],E);let p=GO(m);r.set(u(p),m),S.publish(p,"task.status",{taskStatus:l.taskStatus,updatedAt:l.lastMessageTime});let i=B$(J.prompt,J.attachments);I=await e(m);let fO=I.value,a=K?await fO.prepareInputTurn(i,{outputSchema:K}):await fO.prepareInputTurn(i);if(!a.accepted)throw new k(`Task prompt was not accepted: ${a.reason}`);let zO=s(m,i,J.permissionMode,{preparedInputTurn:a,runtimeLease:I,outputSchema:K});return I=void 0,await zO.taskAdmissionUpdate,{session:aO(m),runId:zO.id,messageId:a.messageId,status:zO.status==="queued"?"queued":"running",queuePosition:m.taskQueuePosition,queueDepth:m.taskQueueDepth,maxConcurrentTasks:m.taskConcurrencyLimit}}catch(h){if(I?.release(),I=void 0,(h instanceof L1||h instanceof J0)&&m){let l=GO(m),p=u(l);if(E)await EO.exit({sessionId:m.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await YO(m).catch(()=>{return}),await R.deleteSession(m.id,m.projectPath).catch(()=>{return}),r.delete(p),new kO(h instanceof J0?"Session runtime capacity is full":"Task admission capacity is full",{resource:h.resource,limit:h.limit})}if(m){let l=await R.findSessionMetadata(m.id,m.projectPath).catch(()=>{return});if(!l||l.taskStatus==="queued"){let p=t0(h),i=await R.updateSessionMetadata(m.id,m.projectPath,{taskStatus:"failed",taskStatusReason:p.message,taskFailure:p,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});m.taskStatus=i?.taskStatus??"failed",m.taskStatusReason=i?.taskStatusReason??p.message,m.taskFailure=i?.taskFailure??p,m.taskCompletedAt=i?.taskCompletedAt}else m.taskStatus=l.taskStatus,m.taskStatusReason=l.taskStatusReason,m.taskFailure=l.taskFailure,m.taskCompletedAt=l.taskCompletedAt}throw h}},wO=(J)=>F(()=>lO(J)),N=async(J,K)=>{let Y=await KO(J,K),X=await R.findSessionMetadata(Y.sessionId,Y.projectPath);if(!X)throw new f("Session",Y.sessionId);if(!["failed","interrupted","cancelled"].includes(X.taskStatus))throw new k(`Task cannot be retried while status is ${X.taskStatus}`);let W=await R.findSessionTaskDispatch(Y.sessionId,Y.projectPath);if(!W)throw new k("Task retry payload is unavailable");return wO({prompt:W.prompt,title:X.title??W.title,taskPriority:X.taskPriority??W.taskPriority,taskKind:X.taskKind??W.taskKind,taskDueAt:X.taskDueAt,sourceProjectPath:W.sourceProjectPath,isolation:W.isolation,permissionMode:W.permissionMode,modelId:W.modelId,reasoningEffort:W.reasoningEffort,serviceTier:W.serviceTier,responseVerbosity:W.responseVerbosity,communicationStyle:W.communicationStyle,attachments:W.attachments,outputSchema:W.outputSchema,retriedFrom:Y})},NO=(J,K)=>F(()=>N(J,K)),g1=(J,K,Y)=>F(async()=>{let X=await KO(J,Y);if(!await R.findSessionMetadata(X.sessionId,X.projectPath))throw new f("Session",X.sessionId);let H=await R.updateSessionMetadata(X.sessionId,X.projectPath,K),D=r.get(u(X));if(D)X0(D,H);return S.publish(X,"session.updated",{...H.title?{title:H.title}:{},...H.taskPriority?{taskPriority:H.taskPriority}:{},...H.taskKind?{taskKind:H.taskKind}:{},taskDueAt:H.taskDueAt??null}),D?aO(D):{...H,isActive:!1}}),Q1=async(J,K)=>{let Y=await $O(J,K);if(!Y.taskWorktree)throw new _("Session does not have a task worktree");try{await EO.restoreSession(Y.taskWorktree);let X=await EO.getDiffArtifact(Y.id);if(!X)throw new k("Task diff artifact is unavailable");return{sessionId:Y.id,projectPath:Y.projectPath,...X}}catch(X){if(X instanceof k)throw X;throw g.error("[SessionRoutes] Failed to load task diff artifact:",X),new k("Task diff artifact is unavailable")}},L0=async(J,K,Y)=>{let X=await KO(J,Y);return ZO(X,async()=>{let W=await $O(X.sessionId,X.projectPath);if(["queued","running"].includes(W.taskStatus))throw new k(`Task artifacts cannot be delivered while status is ${W.taskStatus}`);if(W.taskDelivery?.status==="applied")throw new k("Task changes have already been applied");if(W.taskDelivery?.status==="discarded")throw new k("Task changes have already been discarded");if(!W.taskWorktree)throw new k("Task worktree is unavailable");let H=async(D,B=!1)=>{let A=await R.updateSessionMetadata(W.id,W.projectPath,{taskDelivery:D,...B?{taskWorktree:null}:{}});if(X0(W,A),B)W.taskWorktree=void 0;return S.publish(X,"task.delivery",{taskDelivery:D,...B?{taskWorktreeRemoved:!0}:{},updatedAt:A.lastMessageTime}),aO(W)};try{if(K==="discard"){try{await EO.restoreSession(W.taskWorktree)}catch(A){return g.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${W.id}:`,A),H({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:W.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let B=await EO.exit({sessionId:W.id,action:"remove",discardChanges:!0});return H({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:B.discardedFiles??0,message:"Task worktree removed"},!0)}try{await EO.restoreSession(W.taskWorktree)}catch(B){throw g.warn(`[SessionRoutes] Task worktree is unavailable for ${W.id}:`,B),new H1("artifact_unavailable","Task worktree is unavailable")}let D=await EO.apply(W.id);return H({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:D.sourceCommit,changedFiles:D.changedFiles,message:"Task changes applied to the source workspace"})}catch(D){if(D instanceof H1)throw await H({status:"conflicted",updatedAt:new Date().toISOString(),message:D.message}),new k(D.message);throw D}})},v0=(J,K,Y)=>F(()=>L0(J,K,Y)),u0=async(J)=>{let K=DO(J.currentRunId);if(_O(K))return;if(J.taskIsolation&&J.taskStatus!=="queued"&&J.taskStatus!=="running")return;let Y=await S0.hasPendingInbox(J.projectPath,J.id),X=!Y&&await S0.hasActiveGoal(J.projectPath,J.id);if(!Y&&!X)return;let W=await e(J),H=!1;try{let D=W.value,B=DO(J.currentRunId);if(_O(B))return;if(Y&&D.getPendingSteeringCount()===0)await D.reloadPendingInbox();let A=D.getPendingSteeringCount()>0,M=A?null:await D.getGoal(),T=M?.status==="active"||M?.status==="verifying";if(!A&&!T||D.hasTurnOwner())return;s(J,"",J.permissionMode??"default",{pendingInputOnly:A,goalContinuationOnly:T,runtimeLease:W}),H=!0}finally{if(!H)W.release()}},SO=async(J)=>{let K;try{K=L.enter()}catch{return}try{await u0(J)}finally{K.release()}};G0=SO;let Z1=async()=>{let J={scheduled:0,failed:0,deferred:0};if(!L.stats().accepting)return J;let K=(await R.listSessions({taskStatus:"queued"})).filter((Y)=>Y.taskIsolation!==void 0).sort((Y,X)=>Y.firstMessageTime.localeCompare(X.firstMessageTime)||Y.projectPath.localeCompare(X.projectPath)||Y.sessionId.localeCompare(X.sessionId));for(let[Y,X]of K.entries()){let W={sessionId:X.sessionId,projectPath:X.projectPath};try{if(!await S0.hasPendingInbox(X.projectPath,X.sessionId)){let D=t0("Queued task input is missing");await R.updateSessionMetadata(X.sessionId,X.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),J.failed++;continue}let H=await n(W);if(await SO(H),H.currentRunId)J.scheduled++}catch(H){if(H instanceof L1||H instanceof J0){J.deferred+=K.length-Y;break}g.warn(`[SessionRoutes] Failed to recover queued task ${X.sessionId}:`,H),J.deferred++}}return J};return O.get("/",async(J)=>{try{let K=await R.listSessions(),Y=new Set(K.filter((M)=>M.relationType==="subagent").map((M)=>u({sessionId:M.sessionId,projectPath:M.projectPath}))),X=Array.from(r.values()).filter((M)=>!Y.has(u(GO(M)))&&M.relationType!=="subagent").map((M)=>aO(M)),W=new Set(X.map((M)=>u({sessionId:M.sessionId,projectPath:M.projectPath}))),H=K.filter((M)=>{if(M.relationType==="subagent")return!1;return!W.has(u({sessionId:M.sessionId,projectPath:M.projectPath}))}),D=new Set(W),B=H.filter((M)=>{let T=u({sessionId:M.sessionId,projectPath:M.projectPath});if(D.has(T))return!1;return D.add(T),!0}),A=[...X,...B];return J.json(A)}catch(K){throw g.error("[SessionRoutes] Failed to list sessions:",K),new t("Failed to list sessions")}}),O.get("/catalog",async(J)=>{try{let K=J.req.query("limit"),Y=K===void 0?void 0:Number(K),X=J.req.query("cursor"),W=J.req.query("projectPath"),H=J.req.query("archived");if(H!==void 0&&H!=="true"&&H!=="false")throw new _("archived must be true or false");let D=H==="true",B=await R.listSessionPage({...W?{cwd:R0(W)}:{},...X?{cursor:X}:{},...Y===void 0?{}:{limit:Y},includeSubagents:!1,archived:D}),A=new Map((D?[]:Array.from(r.values())).filter((M)=>M.relationType!=="subagent").map((M)=>[u(GO(M)),aO(M)]));return J.json({sessions:B.sessions.map((M)=>A.get(u({sessionId:M.sessionId,projectPath:M.projectPath}))??M),...B.nextCursor?{nextCursor:B.nextCursor}:{}})}catch(K){if(K instanceof _)throw K;if(K instanceof Error&&(K.message.startsWith("Invalid session cursor")||K.message.startsWith("Session cursor scope")||K.message.startsWith("Session catalog")))throw new _(K.message);throw g.error("[SessionRoutes] Failed to list session catalog:",K),new t("Failed to list session catalog")}}),O.post("/",async(J)=>{try{let K=await J.req.json(),Y=q(ux,K);if(!Y.success)throw new _("Invalid request body");let{title:X,projectPath:W}=Y.data,H=W1("web",12),D=R0(W||J.get("directory")||c(),W?"projectPath":"directory"),B=await R.createSessionMetadata(H,D,{title:X,taskStatus:"completed"}),A=E0(B,[]),M=GO(A);return r.set(u(M),A),S.publish(M,"session.created",{}),J.json({...aO(A),status:void 0,agentType:void 0,model:void 0})}catch(K){if(g.error("[SessionRoutes] Failed to create session:",K),K instanceof _)throw K;throw new t("Failed to create session")}}),O.get("/:sessionId/export",async(J)=>{let K=J.req.param("sessionId");try{let Y=J.req.query("includeReasoning");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new _("includeReasoning must be true or false");let X=await KO(K,J.req.query("projectPath")),W=await R.exportSessionMarkdown(X.sessionId,X.projectPath,{includeReasoning:Y==="true"});return J.body(W.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${W.filename}"`,"Content-Length":String(Buffer.byteLength(W.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":W.contentSha256,"X-Blade-Export-Activities":String(W.activityCount),"X-Blade-Export-Messages":String(W.messageCount),"X-Blade-Export-Redactions":String(W.redactionCount)})}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;if(Y instanceof Error&&Y.message==="No conversation content to export")throw new k(Y.message);throw g.error("[SessionRoutes] Failed to export session:",Y),new t("Failed to export session")}}),O.post("/:sessionId/fork",async(J)=>{let K=J.req.param("sessionId");try{B1(K);let Y=await J.req.json(),X=q(lx,Y);if(!X.success)throw new _("Invalid request body");let W=R0(X.data.projectPath),H=await R.findSessionMetadata(K,W);if(!H)throw new f("Session",K);let D=await R.forkSession(K,{sourceProjectPath:H.projectPath,targetProjectPath:H.projectPath}),B=E0(D.metadata,D.messages),A=GO(B);return r.set(u(A),B),S.publish(A,"task.status",{taskStatus:D.metadata.taskStatus,...D.metadata.taskCompletedAt?{taskCompletedAt:D.metadata.taskCompletedAt}:{},updatedAt:D.metadata.lastMessageTime}),J.json({session:D.metadata,messages:N1(D.messages)},201)}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof k)throw Y;if(Y instanceof I$)throw new k("Session has no durable creation record");throw g.error("[SessionRoutes] Failed to fork session:",Y),new t("Failed to fork session")}}),O.get("/:sessionId",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=r.get(u(Y));if(X)return J.json(aO(X));let W=await R.findSessionMetadata(Y.sessionId,Y.projectPath);if(!W)throw new f("Session",K);return J.json(W)}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;throw g.error("[SessionRoutes] Failed to get session:",Y),new t("Failed to get session")}}),O.patch("/:sessionId",async(J)=>{let K=J.req.param("sessionId");try{let Y=await J.req.json(),X=q(dx,Y);if(!X.success)throw new _("Invalid request body");if(X.data.title===void 0)throw new _("title is required");let W=await KO(K,X.data.projectPath),H=await R.updateSessionMetadata(W.sessionId,W.projectPath,{title:X.data.title}),D=r.get(u(W));if(D)D.title=H.title??D.title,D.updatedAt=new Date(H.lastMessageTime);if(H.title)S.publish(W,"session.updated",{title:H.title});return J.json({success:!0,title:H.title})}catch(Y){if(g.error("[SessionRoutes] Failed to update session:",Y),Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;throw new t("Failed to update session")}}),O.get("/:sessionId/rewind",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath"));return v(K,async(Y)=>J.json({checkpoints:await Y.listRewindCheckpoints()}))}),O.post("/:sessionId/rewind",async(J)=>{let K=q(p$,await J.req.json());if(!K.success)throw new _("Invalid rewind request");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=DO(Y.currentRunId);if(_O(W))throw new k("Cannot rewind while a run is active");return v(Y,async(H)=>{let D;try{D=await H.rewindSession(K.data)}catch(A){if(A instanceof Error&&A.message.startsWith("Cannot rewind while"))throw new k(A.message);throw A}Y.messages=[...D.messages],Y.updatedAt=new Date;let B=N1(D.messages);return S.publish(X,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:B}),J.json({...D,messages:B})})})}),O.get("/:sessionId/review",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath")),X=await oO.list(Y.projectPath,Y.sessionId);return J.json({reviews:X.map((W)=>({...W,content:W.completion?R$(W.start,W.completion):void 0}))})}),O.post("/:sessionId/review",async(J)=>{let K=J.req.param("sessionId"),Y=q(a$,await J.req.json());if(!Y.success)throw new _("Invalid code review request");let X=await $O(K,Y.data.projectPath),W=GO(X),H=u(W);return P(W,async()=>{if(_O(DO(X.currentRunId)))throw new k("Cannot start a review during an active turn");if(bO.has(H))throw new k("Session already has an active review");return v(X,async(D)=>{if(await oO.recoverInterrupted(W.projectPath,W.sessionId,D),Y.data.modelId&&!D.getModelById(Y.data.modelId))throw new _(`Model not found: ${Y.data.modelId}`);if(Y.data.modelId&&D.getCurrentModelId()!==Y.data.modelId)await D.refresh({modelId:Y.data.modelId});if(Y.data.modelId&&X.selectedModelId!==Y.data.modelId){let T=await R.updateSessionMetadata(X.id,X.projectPath,{selectedModelId:Y.data.modelId});X0(X,T)}let B=new AbortController,A;try{A=await oO.start({sessionId:W.sessionId,projectPath:W.projectPath,runtime:D,request:{kind:Y.data.kind,...Y.data.ref?{ref:Y.data.ref}:{},...Y.data.instructions?{instructions:Y.data.instructions}:{}},signal:B.signal,onEvent:(T)=>{if(T.kind==="tool_start")S.publish(W,"review.tool.started",{reviewId:A?.reviewId,toolCallId:T.toolCall.id,toolName:T.toolCall.function.name});else if(T.kind==="tool_progress")S.publish(W,"review.tool.progress",{reviewId:A?.reviewId,toolCallId:T.toolCall.id,message:T.update.message.slice(0,1000)});else if(T.kind==="tool_result")S.publish(W,"review.tool.completed",{reviewId:A?.reviewId,toolCallId:T.toolCall.id,success:T.result.success})}})}catch(T){if(T instanceof Error&&(T.message.includes("active review")||T.message.includes("interrupted review")||T.message.includes("active turn")))throw new k(T.message);if(T instanceof Error&&(T.message.includes("review")||T.message.includes("Git")||T.message.includes("changes")||T.message.includes("ref")))throw new _(T.message);throw T}if(!A)throw new t("Code review failed to start");await tO(X),S.publish(W,"review.started",{reviewId:A.reviewId,kind:Y.data.kind}),S.publish(W,"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 M=A.completion.then(async(T)=>{X.messages=await R.loadSession(W.sessionId,W.projectPath),await tO(X),S.publish(W,"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()}),S.publish(W,"review.completed",{reviewId:A.reviewId,status:T.status,findings:T.findings.length})}).catch((T)=>{g.error(`[SessionRoutes] Code review ${A.reviewId} failed:`,T)}).finally(()=>{if(bO.get(H)?.reviewId===A.reviewId)bO.delete(H)});return bO.set(H,{reviewId:A.reviewId,controller:B,completion:M}),J.json({reviewId:A.reviewId,status:"running"},202)})})}),O.get("/:sessionId/subagents",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath"));return v(K,(Y)=>J.json({subagents:Y.listSubagents().map(n0)}))}),O.post("/:sessionId/subagents/:agentId/resume",async(J)=>{B1(J.req.param("agentId"));let K=d$.safeParse(await J.req.json());if(!K.success)throw new _("Invalid subagent resume request");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=DO(Y.currentRunId);if(_O(W))throw new k("Cannot resume a subagent while a parent run is active");return v(Y,async(H)=>{let D=!1,B,A=(T)=>{S.publish(X,"subagent.complete",{subagentSessionId:T.id,success:T.status==="completed",status:T.status,summary:T.result?.message?.slice(0,500),type:T.subagentType,verificationVerdict:T.result?.verificationVerdict,resumedFrom:T.resumedFrom,rootAgentId:T.rootAgentId,resumeDepth:T.resumeDepth})},M;try{M=H.resumeSubagent({agentId:J.req.param("agentId"),prompt:K.data.prompt,onEvent:(T,y)=>{ex(X,y,T)},onCompleted:(T)=>{if(D)A(T);else B=T}})}catch(T){if(T instanceof Error&&(T.message.startsWith("Cannot resume")||T.message.startsWith("Subagent cannot")))throw new k(T.message);if(T instanceof Error&&T.message.startsWith("Subagent not found"))throw new f(T.message);throw T}if(S.publish(X,"subagent.start",{subagentSessionId:M.session.id,type:M.session.subagentType,description:M.session.description,resumedFrom:M.source.id,rootAgentId:M.session.rootAgentId,resumeDepth:M.session.resumeDepth}),D=!0,B)A(B);return J.json({source:n0(M.source),session:n0(M.session)})})})}),O.get("/:sessionId/goal",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath"));return J.json({goal:await new P$(K.projectPath,K.id).get()})}),O.put("/:sessionId/goal",async(J)=>{let K=q(ix,await J.req.json());if(!K.success)throw new _("Invalid goal request");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=DO(Y.currentRunId);if(_O(W))return J.json({status:"rejected",reason:"run_active"},409);let D=K.data.permissionMode??Y.permissionMode??"default";if(Y.permissionMode!==D)await PO(Y,D);let B=await e(Y),A=!1;try{let M=await B.value.createGoal(K.data);S.publish(X,"goal.updated",{goal:M});let T=s(Y,"",D,{goalContinuationOnly:!0,runtimeLease:B});return A=!0,await T.taskAdmissionUpdate,J.json({status:T.status==="queued"?"queued":"running",runId:T.id,goal:M,queuePosition:Y.taskQueuePosition,queueDepth:Y.taskQueueDepth,maxConcurrentTasks:Y.taskConcurrencyLimit},202)}finally{if(!A)B.release()}})}),O.patch("/:sessionId/goal",async(J)=>{let K=q(cx,await J.req.json());if(!K.success)throw new _("Invalid goal update");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=await e(Y),H=!1;try{let D=W.value,B;if(K.data.action==="pause")B=await D.pauseGoal();else if(K.data.action==="edit")B=await D.editGoal(K.data.objective);else B=await D.resumeGoal();if(S.publish(X,"goal.updated",{goal:B}),B.status==="active"&&!_O(DO(Y.currentRunId))){let A=s(Y,"","default",{goalContinuationOnly:!0,runtimeLease:W});return H=!0,await A.taskAdmissionUpdate,J.json({status:A.status==="queued"?"queued":"running",runId:A.id,goal:B,queuePosition:Y.taskQueuePosition,queueDepth:Y.taskQueueDepth,maxConcurrentTasks:Y.taskConcurrencyLimit},202)}return J.json({status:B.status,goal:B})}finally{if(!H)W.release()}})}),O.delete("/:sessionId/goal",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath")),Y=GO(K);return v(K,async(X)=>{let W=await X.clearGoal();if(W)S.publish(Y,"goal.cleared",{});return J.json({cleared:W})})}),O.post("/:sessionId/archive",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=await R.listSessionArchiveMembers(Y.sessionId,Y.projectPath);for(let H of X){let D=gO({sessionId:H.sessionId,projectPath:H.projectPath}),B=r.get(u(D));if(_O(DO(B?.currentRunId)))throw new k(`Stop session ${H.sessionId} before archiving this session tree`)}for(let H of X){let D=gO({sessionId:H.sessionId,projectPath:H.projectPath}),B=r.get(u(D));if(B)await YO(B)}let W=await R.archiveSession(Y.sessionId,Y.projectPath);for(let H of X){let D=gO({sessionId:H.sessionId,projectPath:H.projectPath}),B=u(D);r.delete(B),Z.delete(B),x.delete(B),S.publish(D,"session.archived",{archiveRootId:Y.sessionId,archivedAt:W.archivedAt})}if($.size===0)await UO.getInstance().disconnectAll();return J.json({session:W,archivedSessionIds:X.map((H)=>H.sessionId)})}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO||Y instanceof k)throw Y;if(Y instanceof _1)throw new k(Y.message);throw g.error("[SessionRoutes] Failed to archive session:",Y),new t("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=await R.listSessionArchiveMembers(Y.sessionId,Y.projectPath),W=await R.unarchiveSession(Y.sessionId,Y.projectPath),H=X.filter((D)=>D.sessionId===Y.sessionId||D.archivedBySessionId===Y.sessionId).map((D)=>D.sessionId);for(let D of H)S.publish({sessionId:D,projectPath:Y.projectPath},"session.unarchived",{archiveRootId:Y.sessionId});return J.json({session:W,restoredSessionIds:H})}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;if(Y instanceof _1)throw new k(Y.message);throw g.error("[SessionRoutes] Failed to unarchive session:",Y),new t("Failed to unarchive session")}}),O.delete("/:sessionId",async(J)=>{let K=J.req.param("sessionId"),Y=J.req.query("projectPath");try{let X=await KO(K,Y),W=u(X),H=r.get(W),D=$.get(W),B=H?.taskWorktree??await R.findSessionTaskWorktree(X.sessionId,X.projectPath),A;if(H?.currentRunId){let y=DO(H.currentRunId);if(y)k0(y),await y.completion,A=y.id}let M=bO.get(W);if(M)M.controller.abort("session-delete"),await M.completion;if(D)await D.clearGoal().catch((y)=>{g.warn("[SessionRoutes] Failed to clear session goal:",y)});if(await R.deleteSession(X.sessionId,X.projectPath),S.publish(X,"session.deleted",{}),A)ox(A);r.delete(W),Z.delete(W),x.delete(W);let T=$.get(W);if(T){if(!await j.remove(W,T))throw new k("Session Runtime is still active and cannot be deleted")}if(B)try{await EO.restoreSession(B),await EO.exit({sessionId:X.sessionId,action:"remove",discardChanges:!0})}catch(y){g.warn(`[SessionRoutes] Failed to remove deleted task worktree ${X.sessionId}:`,y)}return J.json({success:!0})}catch(X){if(g.error("[SessionRoutes] Failed to delete session:",X),X instanceof _||X instanceof f||X instanceof LO)throw X;throw new t("Failed to delete session")}}),O.get("/:sessionId/message",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=r.get(u(Y)),W=X?.messages?X.messages:await R.loadSession(Y.sessionId,Y.projectPath);return J.json(N1(W))}catch(Y){if(g.error("[SessionRoutes] Failed to get messages:",Y),Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;throw new t("Failed to get messages")}}),O.get("/:sessionId/events",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath"));try{await R.assertSessionWritable(Y.sessionId,Y.projectPath)}catch(B){if(B instanceof U1)throw new k(B.message);throw B}let X=await n(Y),W=J.req.header("Last-Event-ID")??J.req.query("lastEventId"),H=W?Number.parseInt(W,10):Number.NaN,D=Number.isInteger(H)?H+1:void 0;return gx(J,async(B)=>{let M,T,y=!1,WO,yO,TO=new Promise((E)=>{yO=E}),XO=()=>{if(T!==void 0)clearInterval(T),T=void 0;M?.(),M=void 0},OO=(E)=>{if(y)return;y=!0,XO(),WO?.close(E),yO()},O0=new Set;B.onAbort(OO),WO=new A0({write:async(E)=>{await B.writeSSE(E)},onFailure:(E)=>{g.warn(`[SessionRoutes] SSE egress closed for ${Y.sessionId}: kind=${E.kind} pendingItems=${E.pendingItems??0} pendingBytes=${E.pendingBytes??0}`),OO(E)}}),M=S.subscribe((E)=>{if(E.sessionId!==Y.sessionId||E.projectPath!==Y.projectPath)return;let m=E.properties.requestId;if((E.type==="permission.asked"||E.type==="question.required"||E.type==="elicitation.required")&&typeof m==="string"){if(O0.has(m))return;O0.add(m)}if(E.type==="subagent.completion.queued")P(Y,()=>SO(X)).catch((I)=>{g.error(`[SessionRoutes] Failed to wake background completion for ${X.id}:`,I)});if(E.type==="team.message.received"&&typeof E.properties.teamName==="string"&&typeof E.properties.messageId==="string"&&typeof E.properties.content==="string"&&m$(E.properties.metadata,{messageId:E.properties.messageId,teamName:E.properties.teamName})){let I=E.properties.teamName,h=E.properties.messageId,l=E.properties.content,p=E.properties.metadata;P(Y,async()=>{let i=await e(X),fO=!1;try{let a=await i.value.enqueueSteering(l,{allowBeforeTurn:!0,messageId:h,origin:"team_message",metadata:p});if(!a.accepted)return;await new f$(I,s0()).markDelivered([h]),fO=a.delivery==="next_turn"}finally{i.release()}if(fO)await SO(X)}).catch((i)=>{g.error(`[SessionRoutes] Failed to deliver teammate message for ${X.id}:`,i)})}WO?.observe(nx(E),E.seq)});try{if(B.aborted||y)return;let E=DO(X.currentRunId),m=_O(E)?await e(X):void 0;try{let l=m?.value,p=l?.getPendingSteeringCount()??0;await WO.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:Y.sessionId,projectPath:Y.projectPath,timestamp:Date.now(),status:_O(E)?E.status:"idle",runId:_O(E)?E.id:void 0,queued:p,pendingInputDelivery:p>0?l?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:l?.getRecoveredSteeringCount()??0}})})}finally{m?.release()}if(B.aborted||y)return;if(D!==void 0){if(await y$.for(Y.sessionId,Y.projectPath).replay({onCommitted:async(p)=>{if(B.aborted||y)return;let i=rx(p);if(i.seq===void 0)return;await WO.writeReplay({...typeof p.seq==="number"?{id:String(p.seq)}:{},data:JSON.stringify({type:i.type,...i.seq!==void 0?{seq:i.seq}:{},properties:{...i.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})},i.seq)}},D),B.aborted||y)return}if(WO.finishInitialization({replayed:D!==void 0}),B.aborted||y)return;if(!E&&!bO.has(u(Y))){let p=(await oO.list(Y.projectPath,Y.sessionId)).some((i)=>i.completion===void 0)?await v(X,(i)=>oO.recoverInterrupted(Y.projectPath,Y.sessionId,i)):void 0;if(p)X.messages=await R.loadSession(Y.sessionId,Y.projectPath),await tO(X),S.publish(Y,"review.completed",{reviewId:p.reviewId,status:p.status,findings:0,recovered:!0})}if(B.aborted||y)return;if(!E)await nO.recoverResponded(Y.projectPath,Y.sessionId);if(B.aborted||y)return;let I=E?void 0:await nO.findPending(Y.projectPath,Y.sessionId),h=E?.pendingPermission??(I?{permissionId:I.request.requestId,details:nO.confirmationDetails(I),resolve:()=>{return}}:void 0);if(h){O0.add(h.permissionId);let l=n$(h,!0);WO.observe({data:JSON.stringify({type:l.type,properties:{...l.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})})}if(B.aborted||y)return;if(SO(X).catch((l)=>{g.error(`[SessionRoutes] Failed to resume pending input for ${K}:`,l)}),B.aborted||y)return;T=setInterval(()=>{if(B.aborted||y)return;WO?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await TO}finally{OO()}})}),O.post("/:sessionId/message",async(J)=>{let K=J.req.param("sessionId"),Y=await J.req.json(),X=q(px,Y);if(!X.success)throw new _("Invalid message format");let{content:W,attachments:H,modelId:D,reasoningEffort:B,serviceTier:A,responseVerbosity:M,communicationStyle:T,permissionMode:y,projectPath:WO,outputSchema:yO}=X.data,TO;if(yO)try{TO=F1(yO).schema}catch(p){throw new _(p instanceof Error?p.message:"Invalid output schema")}let XO=T,OO=D?.trim();if((H??[]).reduce((p,i)=>p+(typeof i.content==="string"?Buffer.byteLength(i.content):0),0)>r0)throw new _("Message attachments exceed the 5 MiB limit");let E=y,m=B$(W,H),I=await $O(K,WO??J.req.query("projectPath")),h=E??I.permissionMode??"default",l=GO(I);return P(l,async()=>{let p=DO(I.currentRunId);if(_O(p)){if(TO)throw new k("Wait for the active turn to finish before setting an output schema");return v(I,async(a)=>{if(OO&&!a.getModelById(OO))throw new _(`Model not found: ${OO}`);if(OO&&a.getCurrentModelId()!==OO)throw new k("Wait for the active turn to finish before switching models");if(B&&a.getReasoningConfiguration().selection!==B)throw new k("Wait for the active turn to finish before switching reasoning effort");if(A&&a.getServiceTierConfiguration().selection!==A)throw new k("Wait for the active turn to finish before switching service tier");if(M&&a.getResponseVerbosityConfiguration().selection!==M)throw new k("Wait for the active turn to finish before switching response verbosity");if(XO&&a.getCommunicationStyleConfiguration().selection!==XO)throw new k("Wait for the active turn to finish before switching communication style");if(E&&I.permissionMode!==E)throw new k("Wait for the active turn to finish before switching permission mode");let zO=await a.enqueueSteering(m,{allowBeforeTurn:!0});if(!zO.accepted)return J.json({status:"rejected",reason:zO.reason??"turn_unavailable"},409);let iO=zO.messageId??Y0(12),B0=zO.queued;S.publish(l,"message.created",{messageId:iO,role:"user",content:w1(m)});let p0=zO.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(S.publish(l,p0,{runId:p.id,messageId:iO,queued:B0}),zO.delivery==="next_turn"&&p.status!=="running"&&p.status!=="waiting_permission")SO(I).catch((d0)=>{g.error(`[SessionRoutes] Failed to wake queued follow-up for ${K}:`,d0)});if(zO.delivery==="next_turn")p.pendingFollowUpRequested=!0;return J.json({runId:p.id,messageId:iO,status:zO.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:B0},202)})}if(I.permissionMode!==h)await PO(I,h);let i=await e(I,{permissionMode:h,...XO&&!XO.includes(":")?{communicationStyle:XO}:{}}),fO=!1;try{let a=i.value;if(OO&&!a.getModelById(OO))throw new _(`Model not found: ${OO}`);if(B)try{a.resolveReasoningConfiguration(B,OO)}catch(VO){throw new _(VO instanceof Error?VO.message:"Invalid reasoning effort")}if(A)try{a.resolveServiceTierConfiguration(A,OO)}catch(VO){throw new _(VO instanceof Error?VO.message:"Invalid service tier")}if(M)try{a.resolveResponseVerbosityConfiguration(M,OO)}catch(VO){throw new _(VO instanceof Error?VO.message:"Invalid response verbosity")}let zO=XO?a.resolveCommunicationStyleConfiguration(XO):void 0;if(zO?.source!==void 0&&zO.source!=="built-in"&&!zO.contentSha256)throw new _("Custom communication style has no provenance");let iO=a.getCurrentModelId(),B0=a.getReasoningConfiguration(),p0=a.getServiceTierConfiguration(),d0=a.getResponseVerbosityConfiguration(),u1=a.getCommunicationStyleConfiguration(),p1=Boolean(OO)&&iO!==OO,d1=Boolean(B)&&B0.selection!==B,l1=Boolean(A)&&p0.selection!==A,i1=Boolean(M)&&d0.selection!==M,c1=Boolean(XO)&&u1.selection!==XO;if(p1||d1||l1||i1||c1)await a.refresh({...OO?{modelId:OO}:{},...B?{reasoningEffort:B}:{},...A?{serviceTier:A}:{},...M?{responseVerbosity:M}:{},...XO?{communicationStyle:XO}:{}});let J1={...OO&&I.selectedModelId!==OO?{selectedModelId:OO}:{},...B&&I.reasoningEffort!==B?{reasoningEffort:B}:{},...A&&I.serviceTier!==A?{serviceTier:A}:{},...M&&I.responseVerbosity!==M?{responseVerbosity:M}:{},...zO&&(I.communicationStyle!==XO||I.communicationStyleDigest!==zO.contentSha256)?{communicationStyle:XO,communicationStyleDigest:zO.source==="built-in"?null:zO.contentSha256}:{}};if(Object.keys(J1).length>0)try{let VO=await R.updateSessionMetadata(I.id,I.projectPath,J1);I.permissionMode=VO.permissionMode,I.selectedModelId=VO.selectedModelId,I.reasoningEffort=VO.reasoningEffort,I.serviceTier=VO.serviceTier,I.responseVerbosity=VO.responseVerbosity,I.communicationStyle=VO.communicationStyle,I.communicationStyleDigest=VO.communicationStyleDigest,I.updatedAt=new Date(VO.lastMessageTime),S.publish(l,"session.updated",J1)}catch(VO){if(p1||d1||l1||i1||c1)await a.refresh({...iO?{modelId:iO}:{},reasoningEffort:B0.selection,serviceTier:p0.selection,responseVerbosity:d0.selection,communicationStyle:u1.selection}).catch((Xx)=>g.error("[SessionRoutes] Failed to roll back non-durable model settings:",Xx));throw VO}let w0=TO?await a.prepareInputTurn(m,{outputSchema:TO}):await a.prepareInputTurn(m);if(!w0.accepted)return J.json({status:"rejected",reason:w0.reason},w0.reason==="queue_full"?429:409);let Y1=s(I,m,h,{preparedInputTurn:w0,outputSchema:TO,runtimeLease:i});return fO=!0,await Y1.taskAdmissionUpdate,J.json({runId:Y1.id,messageId:w0.messageId,status:Y1.status==="queued"?"queued":"running",queuePosition:I.taskQueuePosition,queueDepth:I.taskQueueDepth,maxConcurrentTasks:I.taskConcurrencyLimit},202)}finally{if(!fO)i.release()}})}),O.post("/:sessionId/side-question",async(J)=>{let K=J.req.param("sessionId"),Y=q(c$,await J.req.json());if(!Y.success)throw new _("Invalid side conversation request");let X=await $O(K,Y.data.projectPath??J.req.query("projectPath"));return v(X,async(W)=>{let H=await W.askSideQuestion(Y.data.question,{signal:J.req.raw.signal});return J.json({...H,...W.getCurrentModelId()?{modelId:W.getCurrentModelId()}:{}})})}),O.post("/:sessionId/shell",async(J)=>{let K=J.req.param("sessionId"),Y=q(i$,await J.req.json());if(!Y.success)throw new _("Invalid user shell command");let X=await $O(K,Y.data.projectPath??J.req.query("projectPath")),W=GO(X),H=u(W);return P(W,async()=>{if(IO.has(H))throw new k("A user shell command is already running in this Session");let D=await e(X),B=D.value,A=new AbortController,M,T=new Promise((y)=>{M=y});IO.set(H,{controller:A,completion:T});try{let y=await B.executeUserShellCommand(Y.data.command,{signal:A.signal});X.messages=await R.loadSession(X.id,X.projectPath),X.updatedAt=new Date;let WO=DO(X.currentRunId);if(y.delivery==="next_turn"&&_O(WO))WO.pendingFollowUpRequested=!0;return J.json({executionId:y.executionId,messageId:y.messageId,record:y.record,auxiliary:y.auxiliary,...y.delivery?{delivery:y.delivery}:{},...y.queued!==void 0?{queued:y.queued}:{}})}finally{IO.delete(H),M(),D.release()}})}),O.post("/:sessionId/abort",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath")),X=r.get(u(Y));if(X?.currentRunId){let D=DO(X.currentRunId);if(D)k0(D),await D.completion}let W=IO.get(u(Y));if(W)W.controller.abort("user-cancel"),await W.completion;let H=bO.get(u(Y));if(H)H.controller.abort("user-cancel"),await H.completion;return J.json({success:!0})}),O.get("/:sessionId/status",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath")),X=r.get(u(Y)),W=bO.get(u(Y));if(W)return J.json({sessionId:K,projectPath:Y.projectPath,reviewId:W.reviewId,status:"reviewing"});if(!X?.currentRunId)return J.json({sessionId:K,projectPath:Y.projectPath,status:"idle"});let H=DO(X.currentRunId);return J.json({sessionId:K,projectPath:Y.projectPath,runId:X.currentRunId,status:H?.status||"idle"})}),{app:O,dispatchTask:wO,retryTask:NO,updateTask:g1,getTaskDiff:Q1,deliverTask:v0,recoverQueuedTasks:Z1,getRuntimeResidencyStats:()=>j.getStats(),getCoordinationStats:()=>({messageSubmissions:G.getStats(),taskDeliveries:z.getStats()}),shutdown:(J="server-shutdown")=>{if(w)return w;return L.close(J),clearInterval(b),w=(async()=>{let K,Y=async(B)=>{let A=await Promise.allSettled(B);for(let M of A)if(M.status==="rejected")K??=M.reason},X=new Set,W=()=>{for(let B of CO.values()){if(B.completion)X.add(B.completion);if(_O(B))k0(B,J)}for(let B of IO.values())B.controller.abort(J),X.add(B.completion);for(let B of bO.values())B.controller.abort(J),X.add(B.completion)},H=L.waitForIdle(),D=!1;H.then(()=>{D=!0});while(!D)W(),await Promise.race([H,new Promise((B)=>setImmediate(B))]);if(await H,W(),await Y([...X]),await Y([...x.values()]),W(),await Y([...X]),await Y([j.disposeAll()]),$.clear(),await Y([...Q.values()]),await Y([UO.getInstance().disconnectAll()]),x.clear(),Q.clear(),Z.clear(),r.clear(),G0===SO)G0=void 0;if(K!==void 0)throw K})(),w}}};async function O2(O,$,x,Q,Z,G={}){let{abortController:z,sessionId:U,id:j}=O,L=G.preparedInputTurn?.messageId??Y0(12),w=G.pendingInputOnly===!0||G.preparedInputTurn?.mode==="pending"||G.goalContinuationOnly===!0?void 0:Y0(12),F=G.runtimeLease,P,ZO,d=GO($),C=(v,YO)=>{S.publish(d,v,YO)},e=async()=>{let v=String(z.signal.reason||"Task run cancelled");if($.taskIsolation){if(!F)F=await Z($).catch(()=>{return});let YO=P??F?.value;if(v==="user-cancel")await YO?.discardPendingInput().catch(($O)=>{g.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,$O)});let n=await YO?.setTaskStatus("cancelled",v).catch(()=>{return});if(n)X0($,n);else await tO($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=v,$.taskCompletedAt??=new Date().toISOString()};try{if(G.taskAdmission){if(await G.taskAdmission.ready,await O.taskAdmissionUpdate,z.signal.aborted)throw Error(String(z.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!G.pendingInputOnly&&!G.goalContinuationOnly)C("message.created",{messageId:L,role:"user",content:w1(x)});if(C("session.status",{status:"running"}),w)C("message.created",{messageId:w,role:"assistant",content:""});F??=await Z($),P=F.value;let v=P,YO=Boolean(G.outputSchema??v.getPendingSteeringMessages().find((N)=>N.outputSchema)?.outputSchema);ZO=await v$.createWithRuntime(v,{sessionId:U,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let n=async(N)=>{let NO=N.interactionRequestId??Y0(12),g1=300000;O.status="waiting_permission";let Q1=new Promise((SO)=>{let Z1=setTimeout(()=>{g.warn(`[SessionRoutes] Permission ${NO} timed out after 300000ms`),C("permission.timeout",{requestId:NO}),SO({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:NO,resolve:(v1)=>{clearTimeout(Z1),SO(v1)},details:N}}),L0=O.pendingPermission;if(!L0)throw Error("Permission request was not registered");let v0=n$(L0);C(v0.type,v0.properties),g.info(`[SessionRoutes] Permission request created: ${NO}, runId: ${j}`);let u0=await Q1;if(g.info(`[SessionRoutes] Permission response received: ${NO}, approved: ${u0.approved}`),!z.signal.aborted)O.status="running";if(O.pendingPermission===L0)O.pendingPermission=void 0;return C("interaction.resolved",{requestId:NO}),u0},PO={messages:await R.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:U,workspaceRoot:$.projectPath,signal:z.signal,permissionMode:Q,onPermissionModeChange:async(N)=>{$.permissionMode=N,$.updatedAt=new Date,C("session.updated",{permissionMode:N})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:n}},s=()=>{if(!w)w=Y0(12),C("message.created",{messageId:w,role:"assistant",content:""});return w},lO=async(N)=>{switch(N.kind){case"content_delta":if(YO)break;C("message.delta",{messageId:s(),delta:N.delta});break;case"structured_output":C("structured.output",{messageId:s(),output:N.output,schemaDigest:N.schemaDigest});break;case"thinking_delta":C("thinking.delta",{messageId:s(),delta:N.delta});break;case"tool_start":if("function"in N.toolCall){if(N.toolCall.function.name===z0)break;C("tool.start",{messageId:s(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,arguments:N.toolCall.function.arguments,toolKind:N.toolKind})}break;case"tool_result":if("function"in N.toolCall){if(N.toolCall.function.name===z0)break;C("tool.result",{messageId:s(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,success:N.result.success,summary:N.result.metadata?.summary,output:f0(P0(y0(N.toolCall.function.name,N.result),I0)),metadata:q0(N.toolCall.function.name,N.result.metadata)})}break;case"tool_progress":if("function"in N.toolCall){if(N.toolCall.function.name===z0)break;C("tool.progress",{messageId:s(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,...N.update})}break;case"token_usage":C("token.usage",{...N.usage});break;case"turn_start":C("turn.started",{turn:N.turn,maxTurns:N.maxTurns});break;case"provider_admission":C("provider.admission",{phase:N.phase,requestClass:N.requestClass,resource:N.resource,scope:N.scope,reason:N.reason,queuePosition:N.queuePosition,queueDepth:N.queueDepth,inFlight:N.inFlight,limit:N.limit,waitMs:N.waitMs,maxWaitMs:N.maxWaitMs,recoveryRemainingMs:N.recoveryRemainingMs});break;case"provider_circuit":C("provider.circuit",{phase:N.phase,reason:N.reason,statusCode:N.statusCode,retryAfterMs:N.retryAfterMs,nextProbeAt:N.nextProbeAt,openDurationMs:N.openDurationMs,sampleCount:N.sampleCount,failureCount:N.failureCount,recoveryRemainingMs:N.recoveryRemainingMs});break;case"provider_retry":C("provider.retry",{phase:N.phase,attempt:N.attempt,maxRetries:N.maxRetries,reason:N.reason,statusCode:N.statusCode,delayMs:N.delayMs,nextRetryAt:N.nextRetryAt,mode:N.mode,recoveryBudgetMs:N.recoveryBudgetMs,recoveryElapsedMs:N.recoveryElapsedMs,recoveryRemainingMs:N.recoveryRemainingMs,exhaustedBy:N.exhaustedBy});break;case"provider_stall":C("provider.stall",{phase:N.phase,stallCount:N.stallCount,durationMs:N.durationMs,warningAfterMs:N.warningAfterMs,timeoutMs:N.timeoutMs,outputStarted:N.outputStarted});break;case"action_stationarity":C("action.stationarity",{phase:N.phase,toolName:N.toolName,runLength:N.runLength,nudgeThreshold:N.nudgeThreshold,haltThreshold:N.haltThreshold,progressAware:N.progressAware});break;case"mcp_catalog_changed":C("mcp.catalog.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,added:N.added,removed:N.removed,updated:N.updated});break;case"mcp_content_changed":C("mcp.content.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,contentKind:N.contentKind,added:N.added,removed:N.removed,updated:N.updated});break;case"mcp_resource_updated":C("mcp.resource.updated",{messageId:s(),revision:N.revision,serverName:N.serverName,uri:N.uri});break;case"mcp_connection_changed":C("mcp.connection.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,phase:N.phase,reason:N.reason,attempt:N.attempt,maxAttempts:N.maxAttempts,nextRetryAt:N.nextRetryAt,error:N.error});break;case"mcp_log":C("mcp.log",{messageId:s(),revision:N.revision,serverName:N.serverName,level:N.level,logger:N.logger,message:N.message,projectedBytes:N.projectedBytes,dataSha256:N.dataSha256,truncated:N.truncated,detailsOmitted:N.detailsOmitted,timestamp:N.timestamp,synthetic:N.synthetic});break;case"mcp_instructions_changed":C("mcp.instructions.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,action:N.action,reason:N.reason,text:N.text,sourceBytes:N.sourceBytes,projectedBytes:N.projectedBytes,sha256:N.sha256,truncated:N.truncated,detailsOmitted:N.detailsOmitted});break;case"mcp_task_changed":C("mcp.task.changed",{messageId:s(),revision:N.revision,taskId:N.taskId,serverName:N.serverName,toolName:N.toolName,status:N.status,statusMessage:N.statusMessage,createdAt:N.createdAt,updatedAt:N.updatedAt,completedAt:N.completedAt,hasResult:N.hasResult,error:N.error});break;case"project_rules_loaded":C("project.rules.loaded",{messageId:s(),files:N.files,triggerPaths:N.triggerPaths,blockedWrite:N.blockedWrite});break;case"steering_applied":C("steering.applied",{runId:j,messageIds:N.messageIds,count:N.count,recovered:N.recovered,delivery:N.delivery,queued:v.getPendingSteeringCount()});break;case"follow_up_started":{if(w)C("message.complete",{messageId:w}),w=void 0;for(let NO of N.messages){if(!NO.recovered||NO.persisted)continue;C("message.created",{messageId:NO.id,role:"user",content:w1(NO.content),recovered:!0})}C("follow_up.started",{runId:j,queued:N.queued,recovered:N.recovered}),s();break}case"goal_updated":C("goal.updated",{goal:N.goal});break;case"goal_continuation_started":C("goal.continuation.started",{goal:N.goal,continuation:N.continuation,...N.prematureStopPattern?{prematureStopPattern:N.prematureStopPattern}:{},...N.prematureStopCount!==void 0?{prematureStopCount:N.prematureStopCount}:{}}),s();break;case"compaction":C(N.phase==="start"?"compaction.started":"compaction.completed",{...N.reason?{reason:N.reason}:{},...N.strategy?{strategy:N.strategy}:{},...N.outcome?{outcome:N.outcome}:{},...N.preTokens!==void 0?{preTokens:N.preTokens}:{},...N.postTokens!==void 0?{postTokens:N.postTokens}:{}});break;case"model_fallback":C("model.fallback",{});break;case"task_update":C("task.updated",{tasks:N.tasks});break;default:break}},wO=await D1(ZO.chatStream(x,PO,{stream:!0,pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly,outputSchema:G.outputSchema,taskAdmission:G.taskAdmission}),lO);if(!wO.success)throw Error(wO.error?.message??"Agent run failed");for(let N=0;N<20;N++){let NO=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,v.getPendingSteeringCount()===0){if(!NO)break;continue}if(z.signal.aborted)break;if(wO=await D1(ZO.chatStream("",PO,{stream:!0,pendingInputOnly:!0,taskAdmission:G.taskAdmission}),lO),!wO.success)throw Error(wO.error?.message??"Agent follow-up failed")}if($.messages=await R.loadSession($.id,$.projectPath),$.updatedAt=new Date,await tO($),z.signal.aborted||O.status==="cancelled"){await e(),C("session.status",{status:"idle"});return}if(w)C("message.complete",{messageId:w});C("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),C("session.completed",{runId:j,outputTruncated:wO.metadata?.outputTruncated??!1}),C("session.status",{status:"idle"})}catch(v){if(P&&G.preparedInputTurn)await P.finishTurn(G.preparedInputTurn.handle).catch(()=>{return});if(z.signal.aborted||O.status==="cancelled"){k0(O,"runtime-abort"),await e(),C("session.status",{status:"idle"});return}await tO($).catch(()=>{return}),g.error("[SessionRoutes] Agent execution error:",v),O.status="failed",$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let YO=t0(v);if(!$.taskFailure){let n=P?await P.setTaskStatus("failed",v).catch(()=>{return}):await R.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:YO.message,taskFailure:YO,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(n)X0($,n)}$.taskStatusReason??=YO.message,$.taskFailure??=YO,C("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),C("session.status",{status:"error"})}finally{if(G.taskAdmission?.release(),G.taskAdmission){let v=mO.getStats();C("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:v.queued,taskConcurrencyLimit:v.maxConcurrent,taskInFlight:v.inFlight,taskAdmissionPaused:v.paused,updatedAt:new Date().toISOString()})}if(await ZO?.destroy().catch(()=>{return}),F?.release(),O.disposeRuntimeOnSettle&&G.disposeRuntime)await G.disposeRuntime($,P).catch((v)=>{g.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,v)});ax(O)}}async function s$(O,$,x){g.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),g.info(`[SessionRoutes] Active runs: ${CO.size}`);for(let[G,z]of CO.entries())if(g.info(`[SessionRoutes] Checking run ${G}: sessionId=${z.sessionId}, projectPath=${z.projectPath}, pendingPermission=${z.pendingPermission?.permissionId}`),z.sessionId===O.sessionId&&z.projectPath===O.projectPath&&z.pendingPermission?.permissionId===$){if(z.pendingPermission.details.interactionRequestId)await nO.respond(O.projectPath,O.sessionId,$,x);return z.pendingPermission.resolve(x),g.info(`[SessionRoutes] Permission ${$} responded, runId: ${z.id}`),!0}let Q=await nO.findPending(O.projectPath,O.sessionId);if(!Q||Q.request.requestId!==$)return g.error(`[SessionRoutes] Permission not found: ${$}`),!1;await nO.respondAndRecover(O.projectPath,O.sessionId,$,x);let Z=r.get(u(O));if(!Z){let G=await R.findSessionMetadata(O.sessionId,O.projectPath);if(!G)return!1;let[z,U]=await Promise.all([R.loadSession(O.sessionId,O.projectPath),R.findSessionTaskWorktree(O.sessionId,O.projectPath)]);Z=E0(G,z,U),r.set(u(O),Z)}else await tO(Z);if(S.publish(O,"interaction.resolved",{requestId:$}),G0)G0(Z).catch((G)=>{g.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,G)});return!0}var M1=o("Service"),x2=V.Object({approved:V.Boolean(),remember:V.Optional(V.Boolean()),scope:V.Optional(JO(["once","session","project"])),targetMode:V.Optional(JO(["default","autoEdit","plan","yolo"])),feedback:V.Optional(V.String({maxLength:4000})),answers:V.Optional(V.Record(V.String({maxLength:80}),V.Union([V.String({maxLength:4000}),V.Array(V.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:V.Optional(V.Object({action:JO(["accept","decline","cancel"]),content:V.Optional(V.Record(V.String(),V.Union([V.String({maxLength:4000}),V.Number(),V.Boolean(),V.Array(V.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),r$=()=>{let O=new $2;return O.post("/:permissionId",async($)=>{let x=$.req.param("permissionId"),Q=$.req.query("sessionId"),Z=$.req.query("projectPath");M1.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${Q}`);try{let G=await $.req.json(),z=q(x2,G);if(!z.success)throw new _("Invalid permission response format");let{approved:U,remember:j,scope:L,targetMode:b,feedback:w,answers:F,elicitation:P}=z.data;if(!Q)throw new _("sessionId query parameter is required");let ZO=await KO(Q,Z);if(!await s$(ZO,x,{approved:U,reason:w,scope:L,targetMode:b,feedback:w,answers:F,elicitation:P}))throw new f("Permission request",x);return M1.info(`[PermissionRoutes] Permission ${x} ${U?"approved":"denied"}`),$.json({success:!0,approved:U,remember:j})}catch(G){if(M1.error("[PermissionRoutes] Failed to respond to permission:",G),G instanceof _||G instanceof LO||G instanceof f||G instanceof xO)throw G;throw G}}),O};import e$ from"node:path";import{Hono as Q2}from"hono";var Z2=V.Object({projectPath:V.String({minLength:1}),enabled:V.Boolean(),scope:V.Optional(JO(["local","project","global"]))}),J2=V.Object({projectPath:V.String({minLength:1})}),Y2=V.Object({projectPath:V.String({minLength:1}),source:V.String({minLength:1}),trust:V.Literal(!0),ref:V.Optional(V.String({minLength:1}))}),z2=V.Object({projectPath:V.String({minLength:1}),trust:V.Literal(!0)}),G2=V.Object({projectPath:V.String({minLength:1}),confirm:V.Literal(!0)}),X2=V.Object({projectPath:V.String({minLength:1}),source:V.String({minLength:1}),ref:V.Optional(V.String({minLength:1}))}),O4=V.Object({projectPath:V.String({minLength:1}),confirm:V.Optional(V.Literal(!0))}),V2=V.Object({projectPath:V.String({minLength:1}),scope:V.Optional(JO(["local","project","global"])),policy:V.Object({restrictToAllowedSources:V.Boolean(),requireGitCommitSha:V.Boolean(),allowedGitHosts:V.Array(V.String()),allowedMarketplaces:V.Array(V.String()),allowedLocalRoots:V.Array(V.String())})});function AO(O){if(!O||!e$.isAbsolute(O))throw new _("projectPath must be absolute");return e$.resolve(O)}async function $4(O){let[$,x]=await Promise.all([jO(O),T0.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((Q)=>({name:Q.manifest.name,description:Q.manifest.description,version:Q.manifest.version,source:Q.source,enabled:Q.status==="active",status:Q.status,commands:Q.commands.length,skills:Q.skills.length,agents:Q.agents.length,hooks:Q.hooks?Object.values(Q.hooks).reduce((Z,G)=>Z+(Array.isArray(G)?G.length:0),0):0,mcpServers:Object.keys(Q.mcpServers??{}).length,configurable:Q.source!=="cli",managed:Q.installation!==void 0,marketplace:Q.installation?.source.type==="marketplace"?Q.installation.source.marketplace:void 0,revision:Q.installation?.revision,installedAt:Q.installation?.installedAt,updatedAt:Q.installation?.updatedAt,compatibilityIssues:Q.compatibilityIssues??[],effectiveScope:Q.source==="cli"?"invocation":x.settings[Q.manifest.name]?.effectiveScope??"default",settingLayers:Q.source==="cli"?{invocation:!0}:x.settings[Q.manifest.name]?.layers??{}}))}async function N2(){let O=x4(),[$,x]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),Q=new Map(x.map((Z)=>[Z.name,Z]));return $.map(({marketplace:Z,manifest:G})=>({name:Z.name,description:G.description??G.metadata?.description??"",sourceType:Z.source.type,revision:Z.revision,updatedAt:Z.updatedAt,plugins:G.plugins.map((z)=>{let U=Q.get(z.name);return{name:z.name,description:z.description??"",version:z.version,category:z.category,tags:z.tags??[],installed:U!==void 0,installedVersion:U?.version}})}))}function V0(O,$){if(!O.success)throw new _(O.error??$)}var K4=()=>{let O=new Q2;return O.get("/",async($)=>{let x=AO($.req.query("projectPath"));return $.json(await $4(x))}),O.post("/refresh",async($)=>{let x=q(J2,await $.req.json());if(!x.success)throw new _("Invalid plugin refresh request");let Q=AO(x.data.projectPath),Z=await Z4(Q);return $.json({plugins:await $4(Q),errors:Z.discovery.errors.map((G)=>({code:G.code??"LOAD_ERROR",error:G.error}))})}),O.get("/catalog",async($)=>{return AO($.req.query("projectPath")),$.json(await N2())}),O.get("/policy",async($)=>{let x=AO($.req.query("projectPath")),Q=await T0.getInstance().loadWorkspacePluginSourcePolicy(x);return $.json({policy:Q,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let x=q(V2,await $.req.json());if(!x.success)throw new _("Invalid plugin source policy request");let Q=AO(x.data.projectPath),Z=await J4(Q,x.data.policy,x.data.scope??"global");return $.json({policy:Z})}),O.post("/install",async($)=>{let x=q(Y2,await $.req.json());if(!x.success)throw new _("Invalid plugin install request; explicit source trust is required");let Q=AO(x.data.projectPath),{result:Z}=await Y4(Q,x.data.source,{trusted:x.data.trust,ref:x.data.ref});return V0(Z,"Plugin installation failed"),$.json({name:Z.pluginName,version:Z.manifest?.version,revision:Z.installation?.revision,changed:Z.changed,installedDependencies:Z.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let x=q(X2,await $.req.json());if(!x.success)throw new _("Invalid marketplace add request");let Q=AO(x.data.projectPath),Z=await X4(Q,x.data.source,x.data.ref);return V0(Z,"Marketplace installation failed"),$.json({name:Z.marketplace?.name,plugins:Z.manifest?.plugins.length??0,revision:Z.marketplace?.revision,changed:Z.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let x=q(O4,await $.req.json());if(!x.success)throw new _("Invalid marketplace refresh request");let Q=await V4(AO(x.data.projectPath),$.req.param("name"));return V0(Q,"Marketplace refresh failed"),$.json({name:Q.marketplace?.name,plugins:Q.manifest?.plugins.length??0,revision:Q.marketplace?.revision,changed:Q.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let x=q(O4,await $.req.json());if(!x.success||x.data.confirm!==!0)throw new _("Invalid marketplace removal request; explicit confirmation is required");AO(x.data.projectPath);let Q=await N4($.req.param("name"),!0);return V0(Q,"Marketplace removal failed"),$.json({name:Q.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let x=q(z2,await $.req.json());if(!x.success)throw new _("Invalid plugin update request; explicit source trust is required");let Q=AO(x.data.projectPath),{result:Z}=await z4(Q,$.req.param("name"),{trusted:x.data.trust});return V0(Z,"Plugin update failed"),$.json({name:Z.pluginName,version:Z.manifest?.version,revision:Z.installation?.revision,changed:Z.changed,updatedDependencies:Z.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let x=q(G2,await $.req.json());if(!x.success)throw new _("Invalid plugin uninstall request; explicit confirmation is required");let Q=AO(x.data.projectPath),{result:Z}=await G4(Q,$.req.param("name"),x.data.confirm);return V0(Z,"Plugin uninstall failed"),$.json({name:Z.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let x=q(Z2,await $.req.json());if(!x.success)throw new _("Invalid plugin state request");let Q=AO(x.data.projectPath),Z=$.req.param("name"),z=(await jO(Q)).plugins.get(Z);if(!z)throw new f("Plugin",Z);if(z.source==="cli")throw new _(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);let U=await Q4(Q,Z,x.data.enabled,x.data.scope??"local");return $.json(U)}),O};import{Hono as _2}from"hono";import{execFile as K2}from"node:child_process";import W2 from"node:path";var b1="__BLADE_DIRECTORY_PICKER_CANCELLED__",F2=900000;function U2(O,$){return new Promise((x)=>{K2(O,[...$],{timeout:F2,maxBuffer:65536,windowsHide:!0},(Q,Z,G)=>{let z=Q?.code;x({stdout:Z,stderr:G,exitCode:typeof z==="number"?z:Q?1:0,...typeof z==="string"?{errorCode:z}:{}})})})}function T1(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===b1)return{cancelled:!0};if(!W2.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function j1(O){return O.exitCode!==0||Boolean(O.errorCode)}class W4{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??U2}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 "${b1}"`,"end try"].join(`
|
|
8
|
-
`),$=await this.runCommand("osascript",["-e",O]);if(j1($))throw Error("Unable to open the macOS folder picker");return T1($.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("${b1}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(j1($))throw Error("Unable to open the Windows folder picker");return T1($.stdout)}async pickOnLinux(){let O=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let $ of O){let x=await this.runCommand($.command,$.args);if(x.errorCode==="ENOENT")continue;if(x.exitCode===1&&!x.stdout.trim()&&!x.stderr.trim())return{cancelled:!0};if(j1(x))throw Error("Unable to open the Linux folder picker");return T1(x.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var F4=new W4;var D2=V.Object({path:V.String({minLength:1})});function H2(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let $=new URL(O).hostname;return $==="localhost"||$==="127.0.0.1"||$==="::1"||$==="[::1]"}catch{return!1}}var U4=(O={})=>{let $=new _2,x=O.pickDirectory??(()=>F4.pick()),Q=O.allowDirectoryPickerRequest??H2;return $.get("/",async(Z)=>{return Z.json(await O1.list(c()))}),$.post("/",async(Z)=>{let G;try{G=await Z.req.json()}catch{throw new _("A valid JSON body is required")}let z=q(D2,G);if(!z.success)throw new _("A project path is required");try{let U=await O1.bind(z.data.path,c());return Z.json(U,201)}catch(U){throw new _(U instanceof Error?U.message:"Failed to bind project")}}),$.post("/pick",async(Z)=>{if(!Q(Z.req.header("Origin")))throw new xO("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Z.json(await x())}catch(G){throw new _(G instanceof Error?G.message:"Failed to select a folder")}}),$.delete("/",async(Z)=>{let G=Z.req.query("path");if(!G)throw new _("A project path is required");try{let z=await O1.unbind(G);return Z.json({success:!0,removed:z})}catch(z){throw new _(z instanceof Error?z.message:"Failed to unbind project")}}),$};import{Hono as L2}from"hono";var _4=o("Service"),B4=()=>{let O=new L2;return O.get("/",async($)=>{try{let x=await H4();return $.json(x)}catch(x){return _4.error("[ProviderRoutes] Failed to list providers:",x),$.json([])}}),O.get("/:provider/models",async($)=>{let x=$.req.param("provider");try{let Q=await L4(x);return $.json(Q)}catch(Q){return _4.error("[ProviderRoutes] Failed to list models:",Q),$.json([])}}),O.put("/:provider/credential",async($)=>{let x=$.req.param("provider"),Q=await $.req.json();if(!Q.apiKey?.trim())throw new _("apiKey is required");return await cO().setApiKey(x,Q.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await cO().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let x=$.req.param("provider"),Q=QO(),Z=Q?.modelProviders[x];if(!Q||!Z)throw new f("Model provider",x);let G=await $.req.json();if(!G.name||!G.baseUrl||!G.wireApi)throw new _("name, baseUrl and wireApi are required");let z="apiKeyEnv"in G?G.apiKeyEnv?.trim():Z.apiKeyEnv,U={name:G.name,baseUrl:G.baseUrl,wireApi:G.wireApi,...z?{apiKeyEnv:z}:{}},j=cO(),L=G.apiKey?.trim()?await j.credentials.read(x):void 0;if(G.apiKey?.trim())await j.setApiKey(x,G.apiKey.trim());try{return await BO().updateModelProvider(x,U),$.json({success:!0})}catch(b){if(G.apiKey?.trim())if(L)await j.credentials.modify(x,async()=>L);else await j.credentials.delete(x);if(b instanceof Error&&(b.message.includes("modelProviders.")||b.message.includes("built-in provider")))throw new _(b.message);throw b}}),O.delete("/:provider",async($)=>{let x=$.req.param("provider");if(!QO()?.modelProviders[x])throw new f("Model provider",x);let Z=$.req.query("removeModels");if(Z!==void 0&&Z!=="true"&&Z!=="false")throw new _("removeModels must be true or false");try{let G=await BO().removeModelProvider(x,{removeModels:Z==="true"});return $.json({success:!0,...G})}catch(G){if(G instanceof Error&&(G.message.includes("still referenced")||G.message.includes("owns the only model")))throw new k(G.message);throw G}}),O.post("/:provider/probe",async($)=>{let x=$.req.param("provider"),Q=QO();if(!Q?.modelProviders[x])throw new f("Model provider",x);let Z=await $.req.json().catch(()=>({})),G=Q.models.filter((U)=>U.provider===x),z=Z.modelId?G.find((U)=>U.id===Z.modelId):G[0];if(!z)throw new _(Z.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return $.json(await D4(z,Q))}),O};import{Hono as B2}from"hono";var w2=o("Service"),T4=(O,$)=>{let x=new B2;return x.onError((Q,Z)=>{if(Q instanceof xO)return Z.json(Q.toObject(),Q.statusCode);return w2.error("[ScheduleRoutes] Unhandled route error:",Q),Z.json(new t("Schedule request failed").toObject(),500)}),x.get("/",async(Q)=>{let Z=await O.list();return Q.json(M4.parse({schedules:Z}))}),x.post("/",async(Q)=>{let Z;try{Z=await Q.req.json()}catch{throw new _("Invalid request body")}let G=q(w4,Z);if(!G.success)throw new _("Invalid schedule request");let z=G.data.projectPath||Q.get("directory")||c();try{let U=await O.create({...G.data,projectPath:z});return Q.json(sO.parse(U),201)}catch(U){throw new _(U instanceof Error?U.message:"Failed to create schedule")}}),x.get("/:id",async(Q)=>{let Z=await O.get(Q.req.param("id"));if(!Z)throw new f("Schedule not found");return Q.json(sO.parse(Z))}),x.patch("/:id",async(Q)=>{let Z;try{Z=await Q.req.json()}catch{throw new _("Invalid request body")}let G=q(A4,Z);if(!G.success)throw new _("Invalid schedule update");let{modelId:z,reasoningEffort:U,serviceTier:j,responseVerbosity:L,communicationStyle:b,isolation:w,permissionMode:F,...P}=G.data,ZO={...z!==void 0?{modelId:z}:{},...U!==void 0?{reasoningEffort:U}:{},...j!==void 0?{serviceTier:j}:{},...L!==void 0?{responseVerbosity:L}:{},...b!==void 0?{communicationStyle:b}:{},...w!==void 0?{isolation:w}:{},...F!==void 0?{permissionMode:F}:{}};try{let d=await O.update(Q.req.param("id"),{...P,...Object.keys(ZO).length>0?{dispatch:ZO}:{}});if(!d)throw new f("Schedule not found");return Q.json(sO.parse(d))}catch(d){if(d instanceof xO)throw d;throw new _(d instanceof Error?d.message:"Failed to update schedule")}}),x.delete("/:id",async(Q)=>{if(!await O.remove(Q.req.param("id")))throw new f("Schedule not found");return Q.json({ok:!0})}),x.post("/:id/enable",async(Q)=>{let Z=await O.setEnabled(Q.req.param("id"),!0);if(!Z)throw new f("Schedule not found");return Q.json(sO.parse(Z))}),x.post("/:id/disable",async(Q)=>{let Z=await O.setEnabled(Q.req.param("id"),!1);if(!Z)throw new f("Schedule not found");return Q.json(sO.parse(Z))}),x.post("/:id/run",async(Q)=>{let Z=await O.get(Q.req.param("id"));if(!Z)throw new f("Schedule not found");if(!$)throw new t("Scheduler is not running in this process");await $.fire(Z,new Date,{manual:!0});let G=await O.get(Z.id);return Q.json(sO.parse(G??Z),202)}),x};import*as uO from"node:fs/promises";import{homedir as C4}from"node:os";import*as MO from"node:path";import{Hono as A2}from"hono";var rO=o("Service"),j4=MO.join(C4(),".blade","skills"),C1=MO.join(C4(),".blade","skills-config.json");async function S4(){try{let O=await uO.readFile(C1,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function M2(O){await uO.mkdir(MO.dirname(C1),{recursive:!0}),await uO.writeFile(C1,JSON.stringify(O,null,2))}async function T2(O,$){let x=await S4();if($)x.disabled=x.disabled.filter((Q)=>Q!==O);else if(!x.disabled.includes(O))x.disabled.push(O);await M2(x)}var vO=null,j2=300000,b2=6;async function C2(){if(vO&&Date.now()-vO.timestamp<j2)return vO.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(rO.warn(`GitHub API returned ${O.status}`),vO)return vO.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let x=(await O.json()).filter((z)=>z.type==="dir"),Q=Array(x.length),Z=0,G=Math.min(b2,x.length);return await Promise.all(Array.from({length:G},async()=>{while(Z<x.length){let z=Z++,U=x[z];if(!U)continue;let j=`Official ${U.name} skill`;try{let L=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${U.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(L.ok){let w=(await L.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(w)j=w[1].trim().slice(0,100)}}catch{}Q[z]={name:U.name,description:j,tag:"Official",author:"Anthropic"}}})),vO={data:Q,timestamp:Date.now()},Q}catch(O){if(rO.warn("Failed to fetch skills catalog from GitHub:",O),vO)return vO.data;throw O}}var R4=()=>{let O=new A2;return O.get("/",async($)=>{try{let x=$.get("directory")||c(),Z=(await jO(x)).skills.getAll(),G=await S4(),z=Z.map((U)=>({id:U.name,name:U.name,enabled:!G.disabled.includes(U.name),description:U.description||"",version:U.version||"1.0.0",provider:"Local",location:U.source==="builtin"?"Built-in":U.basePath,removable:U.source==="user"&&MO.dirname(MO.resolve(U.basePath))===MO.resolve(j4),capabilities:["prompts"],allowedTools:U.allowedTools||[]}));return $.json(z)}catch(x){return rO.error("[SkillsRoutes] Failed to get skills:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async($)=>{try{let x=$.req.param("name"),Q=await $.req.json();return await T2(x,Q.enabled),$.json({success:!0,enabled:Q.enabled})}catch(x){return rO.error("[SkillsRoutes] Failed to toggle skill:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name"),Q=$.get("directory")||c();return C0(Q,async(Z)=>{let G=Z.skills,z=G.get(x);if(!z)return $.json({success:!1,error:"Skill not found"},404);let U=MO.resolve(z.basePath),j=MO.resolve(j4);if(z.source!=="user"||MO.dirname(U)!==j)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await uO.rm(U,{recursive:!0,force:!0}),await G.refresh(),b0(Q),await j0(Q),$.json({success:!0})})}catch(x){return rO.error("[SkillsRoutes] Failed to uninstall skill:",x),$.json({success:!1,error:x.message},500)}}),O.post("/install",async($)=>{try{let x=await $.req.json(),Q=b4(),Z=$.get("directory")||c();return C0(Z,async(G)=>{let z=G.skills,U=!1;if(x.source==="catalog"&&x.name){if(U=await Q.installOfficialSkill(x.name),!U)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(U=await Q.installFromRepo(x.url,x.name),!U)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(x.source==="local"&&x.path){if(U=await Q.installFromLocal(x.path,x.name),!U)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await z.refresh(),b0(Z),await j0(Z),$.json({success:!0})})}catch(x){return rO.error("[SkillsRoutes] Failed to install skill:",x),$.json({success:!1,error:x.message},500)}}),O.get("/catalog",async($)=>{try{let x=await C2();return $.json(x)}catch(x){return rO.error("[SkillsRoutes] Failed to get catalog:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills catalog"},502)}}),O};import{execSync as S2}from"node:child_process";import{readdir as R2}from"node:fs/promises";import $1 from"node:path";import E2 from"fast-glob";import{Hono as k2}from"hono";var m0=o("Service"),q2=(O)=>{try{return S2("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},I2=[...N0.map((O)=>`${O}/**`),...N0,...N0.map((O)=>`**/${O}/**`),...N0.map((O)=>`**/${O}`),...S1.map((O)=>`**/${O}`)],P2=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),q4=()=>{let O=new k2;return O.get("/commands",async($)=>{try{let x=$.req.query("q")||"",Q=$.get("directory")||c(),Z=await jO(Q),G=k4(x,Q,Z).filter((z)=>!P2.has(z.command));return $.json(G)}catch(x){return m0.error("[SuggestionsRoutes] Failed to get command suggestions:",x),$.json([])}}),O.get("/files",async($)=>{try{let x=$.req.query("q")||"",Q=$.get("directory")||c(),Z=Math.min(Number($.req.query("limit"))||100,1000),G=$.req.query("type")==="file",U=(await E2("**/*",{cwd:Q,dot:!1,followSymbolicLinks:!1,onlyFiles:G,markDirectories:!0,unique:!0,ignore:I2})).map((b)=>b.replace(/\\/g,"/"));if(!x)return $.json(U.slice(0,Z));let j=x.toLowerCase(),L=U.filter((b)=>b.toLowerCase().includes(j)).slice(0,Z);return $.json(L)}catch(x){return m0.error("[SuggestionsRoutes] Failed to get file suggestions:",x),$.json([])}}),O.get("/files/tree",async($)=>{try{let x=$.get("directory")||c(),Q=$.req.query("path")||"",Z=Q?$1.join(x,Q):x,z=(await R2(Z,{withFileTypes:!0})).map((L)=>({name:L.name,path:Q?`${Q}/${L.name}`:L.name,type:L.isDirectory()?"dir":"file"}));z.sort((L,b)=>{if(L.type!==b.type)return L.type==="dir"?-1:1;return L.name.localeCompare(b.name)});let U=new Set(N0),j=z.filter((L)=>{let b=L.name;if(b.startsWith("."))return!1;if(U.has(b))return!1;for(let w of S1)if(b.match(new RegExp(w.replace("*",".*"))))return!1;return!0});return $.json(j)}catch(x){return m0.error("[SuggestionsRoutes] Failed to get file tree:",x),$.json([])}}),O.get("/files/content",async($)=>{try{let x=$.req.query("path");if(!x)return $.json({error:"Missing file path"},400);let Q=$.get("directory")||c(),Z=$1.resolve(Q,x),G=$1.relative(Q,Z);if(G.startsWith("..")||$1.isAbsolute(G))return $.json({error:"Invalid file path"},400);let z=E4(),U=await z.stat(Z);if(!U?.isFile)return $.json({error:"File not found"},404);let j=200000,L=await z.readTextFile(Z),b=L.length>j;return $.json({path:x,content:b?L.slice(0,j):L,truncated:b,size:U.size})}catch(x){return m0.error("[SuggestionsRoutes] Failed to get file content:",x),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{try{let x=$.get("directory")||c(),Q=q2(x);return $.json({branch:Q})}catch(x){return m0.error("[SuggestionsRoutes] Failed to get git info:",x),$.json({branch:null})}}),O};import{Hono as y2}from"hono";var K0=o("Service"),m4=(O)=>{let $=new y2;return $.onError((x,Q)=>{if(x instanceof xO)return Q.json(x.toObject(),x.statusCode);return K0.error("[TaskRoutes] Unhandled route error:",x),Q.json(new t("Failed to dispatch task").toObject(),500)}),$.post("/",async(x)=>{let Q;try{Q=await x.req.json()}catch{throw new _("Invalid request body")}let Z=q(P4,Q);if(!Z.success)throw new _("Invalid task request");if((Z.data.attachments??[]).reduce((z,U)=>z+(typeof U.content==="string"?Buffer.byteLength(U.content):0),0)>r0)throw new _("Task attachments exceed the 5 MiB limit");if(Z.data.taskDueAt&&!Number.isFinite(Date.parse(Z.data.taskDueAt)))throw new _("Invalid task due date");try{let z=await O.dispatchTask({prompt:Z.data.prompt,title:Z.data.title,taskPriority:Z.data.taskPriority,taskKind:Z.data.taskKind,taskDueAt:Z.data.taskDueAt?new Date(Z.data.taskDueAt).toISOString():void 0,sourceProjectPath:Z.data.projectPath||x.get("directory")||c(),isolation:Z.data.isolation,permissionMode:Z.data.permissionMode,modelId:Z.data.modelId,reasoningEffort:Z.data.reasoningEffort,serviceTier:Z.data.serviceTier,responseVerbosity:Z.data.responseVerbosity,communicationStyle:Z.data.communicationStyle,attachments:Z.data.attachments,outputSchema:Z.data.outputSchema});return x.json(E1.parse(z),202)}catch(z){if(z instanceof _||z instanceof k||z instanceof qO||z instanceof kO)throw z;throw K0.error("[TaskRoutes] Failed to dispatch task:",z),new t("Failed to dispatch task")}}),$.patch("/:sessionId",async(x)=>{let Q;try{Q=await x.req.json()}catch{throw new _("Invalid request body")}let Z=q(y4,Q);if(!Z.success)throw new _("Invalid task update");if(Z.data.title===void 0&&Z.data.taskPriority===void 0&&Z.data.taskKind===void 0&&Z.data.taskDueAt===void 0)throw new _("Task update must include at least one field");if(typeof Z.data.taskDueAt==="string"&&!Number.isFinite(Date.parse(Z.data.taskDueAt)))throw new _("Invalid task due date");try{let G=await O.updateTask(x.req.param("sessionId"),{...Z.data,...typeof Z.data.taskDueAt==="string"?{taskDueAt:new Date(Z.data.taskDueAt).toISOString()}:{}},x.req.query("projectPath"));return x.json(R1.parse(G))}catch(G){if(G instanceof _||G instanceof f||G instanceof k)throw G;throw K0.error("[TaskRoutes] Failed to update task:",G),new t("Failed to update task")}}),$.post("/:sessionId/retry",async(x)=>{try{let Q=await O.retryTask(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(E1.parse(Q),202)}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof k||Q instanceof qO||Q instanceof kO)throw Q;throw K0.error("[TaskRoutes] Failed to retry task:",Q),new t("Failed to retry task")}}),$.get("/:sessionId/diff",async(x)=>{try{let Q=await O.getTaskDiff(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(I4.parse(Q))}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof k)throw Q;throw K0.error("[TaskRoutes] Failed to load task diff:",Q),new t("Failed to load task diff")}}),$.post("/:sessionId/delivery",async(x)=>{let Q;try{Q=await x.req.json()}catch{throw new _("Invalid request body")}let Z=q(f4,Q);if(!Z.success)throw new _("Invalid task delivery request");try{let G=await O.deliverTask(x.req.param("sessionId"),Z.data.action,x.req.query("projectPath"));return x.json(R1.parse(G))}catch(G){if(G instanceof _||G instanceof f||G instanceof k)throw G;throw K0.error("[TaskRoutes] Failed to deliver task:",G),new t("Failed to deliver task")}}),$};import u4 from"node:path";import{Hono as h2}from"hono";var f2=eO(V.Object({id:V.String(),name:V.String(),subagentType:V.String(),description:V.String(),agentId:V.Optional(V.String()),status:JO(["leader","running","completed","failed","cancelled","unknown"]),result:V.Optional(V.Unknown()),stats:V.Optional(V.Unknown()),worktreePath:V.Optional(V.String())})),m2=eO(V.Object({id:V.String(),subject:V.String(),description:V.String(),status:JO(["pending","blocked","running","completed"]),owner:V.Optional(V.String()),priority:JO(["high","medium","low"]),dependsOn:V.Array(V.String()),blocks:V.Array(V.String()),result:V.Optional(V.String()),createdAt:V.String(),startedAt:V.Optional(V.String()),completedAt:V.Optional(V.String())})),p9=eO(V.Object({name:V.String(),description:V.Optional(V.String()),status:JO(["idle","running","completed","failed","deleted"]),leadAgentId:V.String(),leadSessionId:V.Optional(V.String()),workspaceRoot:V.Optional(V.String()),peerMessagingEnabled:V.Boolean(),createdAt:V.Number(),updatedAt:V.Number(),deletedAt:V.Optional(V.Number()),members:V.Array(f2),tasks:V.Array(m2)})),h4=eO(V.Object({sessionId:V.String({minLength:1}),projectPath:V.String({minLength:1}),name:V.String({minLength:1}),description:V.Optional(V.String()),leadAgentType:V.Optional(V.String()),peerMessagingEnabled:V.Optional(V.Boolean()),members:V.Array(V.Object({name:V.String({minLength:1}),subagentType:V.String({minLength:1}),description:V.Optional(V.String()),prompt:V.String({minLength:10,maxLength:32768})}),{maxItems:32}),tasks:V.Optional(V.Array(V.Object({subject:V.String({minLength:1}),description:V.String({minLength:1}),dependsOn:V.Optional(V.Array(V.String())),assignedTo:V.Optional(V.String()),priority:V.Optional(JO(["high","medium","low"]))}),{maxItems:256}))})),g4=eO(V.Object({sessionId:V.String({minLength:1}),projectPath:V.String({minLength:1}),to:V.String({minLength:1}),message:V.String({minLength:1,maxLength:32768})})),v4=eO(V.Object({sessionId:V.String({minLength:1}),projectPath:V.String({minLength:1}),memberId:V.String({minLength:1})}));var g2=o("Service"),i4=()=>{let O=new h2;return O.onError(($,x)=>{if($ instanceof xO)return x.json($.toObject(),$.statusCode);return g2.error("[TeamRoutes] Unhandled route error:",$),x.json(new t("Team operation failed").toObject(),500)}),O.get("/",async($)=>{F0();let x=await U0($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await W0(x.projectPath).list(x))}),O.post("/",async($)=>{F0();let x=q(h4,await k1($.req));if(!x.success)throw new _("Invalid team request");let Q=await U0(x.data.sessionId,x.data.projectPath),Z=await R.findSessionMetadata(Q.sessionId,Q.projectPath);return $.json(await W0(Q.projectPath).create({name:x.data.name,description:x.data.description,leadAgentType:x.data.leadAgentType,owner:Q,modelId:Z?.selectedModelId,peerMessagingEnabled:x.data.peerMessagingEnabled,members:x.data.members,tasks:x.data.tasks}),201)}),O.get("/:teamName",async($)=>{F0();let x=await U0($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await W0(x.projectPath).getSnapshot($.req.param("teamName"),x))}),O.post("/:teamName/messages",async($)=>{F0();let x=q(g4,await k1($.req));if(!x.success)throw new _("Invalid team message");let Q=await U0(x.data.sessionId,x.data.projectPath),Z=await W0(Q.projectPath).sendMessage({name:$.req.param("teamName"),to:x.data.to,body:x.data.message,owner:Q});return $.json({messages:Z})}),O.post("/:teamName/tasks/claim",async($)=>{F0();let x=q(v4,await k1($.req));if(!x.success)throw new _("Invalid team task claim");let Q=await U0(x.data.sessionId,x.data.projectPath);return $.json({task:await W0(Q.projectPath).claimTask($.req.param("teamName"),x.data.memberId,Q)})}),O.delete("/:teamName",async($)=>{F0();let x=await U0($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await W0(x.projectPath).delete($.req.param("teamName"),{owner:x,killRunning:!0}))}),O};function W0(O){return new l4({configDir:s0(),subagentRegistry:d4(O)})}function F0(){if(p4().config.config?.agentTeamsEnabled!==!0)throw new qO("Agent Teams are disabled")}async function U0(O,$){if(!O||!$||!u4.isAbsolute($))throw new _("sessionId and absolute projectPath are required");let x=u4.resolve($);if(!await R.findSessionMetadata(O,x))throw new f(`Session not found: ${O}`);return{sessionId:O,projectPath:x}}async function k1(O){try{return await O.json()}catch{throw new _("Invalid request body")}}import{Hono as v2}from"hono";var pO=o("Service"),_0=new Map,c4=2097152,a4=65536;function o4(){return typeof globalThis.Bun<"u"}async function u2(O,$,x){if(o4()){let{spawn:G}=await import("bun-pty"),z=G(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:z.pid,write:(U)=>z.write(U),resize:(U,j)=>z.resize(U,j),kill:()=>z.kill(),onData:(U)=>z.onData(U),onExit:(U)=>z.onExit(U)}}let Z=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:Z.pid,write:(G)=>Z.write(G),resize:(G,z)=>Z.resize(G,z),kill:()=>Z.kill(),onData:(G)=>{Z.onData(G)},onExit:(G)=>{Z.onExit(G)}}}var P1=void 0,I1;if(o4())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();I1=$.upgradeWebSocket,P1=$.websocket}catch(O){pO.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function n4(O,$){let x=`term-${Date.now()}`;pO.info(`[Terminal] New connection: ${x}, cwd: ${O}`);let Q=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Z=Q.endsWith("sh")?["-l"]:[],G=await u2(Q,Z,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),z={id:x,process:G,cwd:O,buffer:"",subscribers:new Set};if(_0.set(x,z),z.subscribers.add($),G.onData((U)=>{let j=!1;for(let L of z.subscribers)try{L.send(U),j=!0}catch{z.subscribers.delete(L)}if(j)return;if(z.buffer+=U,z.buffer.length>c4)z.buffer=z.buffer.slice(-c4)}),G.onExit(({exitCode:U})=>{pO.info(`[Terminal] Process exited: ${x}, code: ${U}`);for(let j of z.subscribers)try{j.close()}catch{}_0.delete(x)}),z.buffer){let U=z.buffer;z.buffer="";for(let j=0;j<U.length;j+=a4)$.send(U.slice(j,j+a4))}return{session:z,cleanup:()=>{if(pO.info(`[Terminal] Connection closed: ${x}`),z.subscribers.delete($),z.subscribers.size===0){try{z.process.kill()}catch{}_0.delete(x)}}}}function t4(O,$){O.on("connection",async(x,Q)=>{let Z=new URL(Q.url||"/",`http://${Q.headers.host}`);if(!Z.pathname.endsWith("/terminal/ws")){x.close();return}let G=Z.searchParams.get("cwd")||$()||c();try{let{session:z,cleanup:U}=await n4(G,{send:(j)=>x.send(j),close:()=>x.close()});x.on("message",(j)=>{try{z.process.write(String(j))}catch(L){pO.error("[Terminal] Failed to write to PTY:",L)}}),x.on("close",U),x.on("error",U)}catch(z){pO.error("[Terminal] Failed to spawn PTY:",z),x.close()}})}var s4=()=>{let O=new v2;if(O.get("/status",($)=>{let x=Array.from(_0.values()).map((Q)=>({id:Q.id,cwd:Q.cwd}));return $.json({active:x.length,terminals:x})}),O.post("/kill/:terminalId",($)=>{let x=$.req.param("terminalId"),Q=_0.get(x);if(Q){try{Q.process.kill()}catch{}for(let Z of Q.subscribers)Z.close();return _0.delete(x),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),I1)O.get("/ws",I1(($)=>{let x=$.req.query("cwd")||$.get("directory")||c(),Q;return{async onOpen(Z,G){try{Q=await n4(x,{send:(z)=>G.send(z),close:()=>G.close()})}catch(z){pO.error("[Terminal] Failed to spawn PTY:",z),G.close()}},onMessage(Z){if(!Q)return;try{Q.session.process.write(String(Z.data))}catch(G){pO.error("[Terminal] Failed to write to PTY:",G)}},onClose(){Q?.cleanup()}}}));else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import p2 from"node:path";import{Hono as d2}from"hono";var l2=V.Object({projectPath:V.String({minLength:1}),action:JO(["trust","revoke"])});function r4(O){if(!p2.isAbsolute(O))throw new _("projectPath must be absolute")}var Ox=()=>{let O=new d2;return O.get("/",async($)=>{let x=$.req.query("projectPath");if(!x)throw new _("projectPath query parameter is required");return r4(x),$.json(await y1.getInstance().getStatus(x))}),O.post("/",async($)=>{let x=q(l2,await $.req.json());if(!x.success)throw new _("Invalid workspace trust request");let{projectPath:Q,action:Z}=x.data;r4(Q);let G=y1.getInstance(),z=Z==="trust"?await G.trust(Q):await G.revoke(Q);return await e4(),$.json({...z,reloadRequired:z.sensitiveSources>0})}),O};var FO=o("Service"),h1=[],x1,D0,H0,h0,$x=new Map,xx=new Map,x3=new Set([".css",".html",".js",".json",".svg"]),Q3=1024,Z3=3600000;function J3(O,$){if(!O)return 0;let x=O.split(",").map((Q)=>{let[Z,...G]=Q.trim().toLowerCase().split(";"),z=G.find((j)=>j.trim().startsWith("q=")),U=z?Number(z.trim().slice(2)):1;return{name:Z,quality:Number.isFinite(U)?Math.max(0,Math.min(1,U)):0}});return x.find((Q)=>Q.name===$)?.quality??x.find((Q)=>Q.name==="*")?.quality??0}function Qx(){if(H0)return;let O=()=>{R.collectStaleEmptySessions().then(($)=>{if($>0)FO.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{FO.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),H0=setInterval(O,Z3),H0.unref?.()}function Y3(){if(!H0)return;clearInterval(H0),H0=void 0}function z3(O){return["br","gzip"].map((x)=>({encoding:x,quality:J3(O,x)})).filter((x)=>x.quality>0).sort((x,Q)=>Q.quality-x.quality||(x.encoding==="br"?-1:1))[0]?.encoding}function G3(O){let $=$x.get(O);if($)return $;let x=g0(O);return $x.set(O,x),x}function X3(O,$,x){let Q=`${x}:${O}`,Z=xx.get(Q);if(Z)return Z;let G=x==="br"?t2($,{params:{[r2.BROTLI_PARAM_QUALITY]:5}}):s2($,{level:6});return xx.set(Q,G),G}function V3(){let O=a2(n2(import.meta.url)),$=[dO(O,"web"),dO(c(),"dist/web"),dO(c(),"packages/cli/dist/web")];for(let x of $){let Q=dO(x,"index.html");if(m1(Q)){if(g0(Q,"utf-8").includes("/assets/"))return FO.debug(`[Server] Found web dist at: ${x}`),x}}return null}function N3(){let O=new e2;O.onError((Q,Z)=>{if(FO.error("[Server] Request error:",Q),Q instanceof Yx){let z=new kO(Q.message,{resource:"workspace_agent_resources",limit:Q.capacity});return Z.json(z.toObject(),429)}if(Q instanceof xO)return Z.json(Q.toObject(),Q.statusCode);let G=Q instanceof Error?Q.message:String(Q);return Z.json({error:{code:"INTERNAL_ERROR",message:G}},500)}),O.use(async(Q,Z)=>{let G=process.env.BLADE_SERVER_PASSWORD;if(!G)return Z();let z=Q.req.path;if(z==="/"||z==="/favicon.svg"||z.startsWith("/assets/")||z.endsWith(".html")||z.endsWith(".js")||z.endsWith(".css"))return Z();let U=Q.req.header("Authorization");if(!U?.startsWith("Basic "))return Q.header("WWW-Authenticate",'Basic realm="Blade Server"'),Q.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let j=Buffer.from(U.slice(6),"base64").toString(),[L,b]=j.split(":"),w=process.env.BLADE_SERVER_USERNAME??"blade";if(L!==w||b!==G)return Q.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Z()}),O.use(async(Q,Z)=>{let G=Q.req.path==="/health"||Q.req.path==="/global/health"||Q.req.path.startsWith("/assets/");if(!G)FO.debug(`[Server] ${Q.req.method} ${Q.req.path}`);let z=Date.now();if(await Z(),!G){let U=Date.now()-z;FO.debug(`[Server] ${Q.req.method} ${Q.req.path} - ${Q.res.status} (${U}ms)`)}}),O.use(O3({origin(Q){if(!Q)return;if(Q.startsWith("http://localhost:"))return Q;if(Q.startsWith("http://127.0.0.1:"))return Q;if(Q==="tauri://localhost"||Q==="http://tauri.localhost")return Q;if(h1.includes(Q))return Q;return}})),O.use(async(Q,Z)=>{let G=Q.req.query("directory")||Q.req.header("x-blade-directory")||c();try{G=decodeURIComponent(G)}catch{}return Q.set("directory",G),Z()});let $=t$();h0=$,x1=$.recoverQueuedTasks,D0=new G1({dispatch:(Q)=>$.dispatchTask(Q),store:f1}),O.route("/global",x$()),O.route("/events",O$()),O.route("/sessions",$.app),O.route("/tasks",m4($)),O.route("/teams",i4()),O.route("/schedules",T4(f1,D0)),O.route("/configs",o1()),O.route("/permissions",r$()),O.route("/plugins",K4()),O.route("/hooks",G$()),O.route("/workspace-trust",Ox()),O.route("/providers",B4()),O.route("/models",D$()),O.route("/projects",U4()),O.route("/suggestions",q4()),O.route("/terminal",s4()),O.route("/mcp",N$()),O.route("/skills",R4()),O.get("/health",(Q)=>{return Q.json({healthy:!0,version:Q0()})});let x=V3();if(x)FO.info(`[Server] Serving static files from ${x}`),O.get("/favicon.svg",()=>{let Q=dO(x,"favicon.svg");if(!m1(Q))return new Response(null,{status:404});return new Response(g0(Q),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(Q)=>{let Z=dO(x,Q.req.path);if(!m1(Z))return Q.json({error:{code:"NOT_FOUND",message:`File not found: ${Q.req.path}`}},404);let G=G3(Z),z=o2(Z).toLowerCase(),j={".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"}[z]||"application/octet-stream",L=x3.has(z)&&G.byteLength>=Q3?z3(Q.req.header("Accept-Encoding")):void 0,b=L?X3(Z,G,L):G;return new Response(new Uint8Array(b),{headers:{"Content-Type":j,"Content-Length":String(b.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...L?{"Content-Encoding":L}:{}}})}),O.get("/",(Q)=>{let Z=dO(x,"index.html"),G=g0(Z,"utf-8");return Q.html(G,200,{"Cache-Control":"no-cache"})}),O.get("*",(Q)=>{let Z=Q.req.path;if(Z.includes("."))return Q.json({error:{code:"NOT_FOUND",message:`File not found: ${Z}`}},404);let G=dO(x,"index.html"),z=g0(G,"utf-8");return Q.html(z,200,{"Cache-Control":"no-cache"})});else FO.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(Q)=>{return Q.json({message:"Blade API Server",version:Q0(),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("*",(Q)=>{return Q.json({error:{code:"NOT_FOUND",message:`Route not found: ${Q.req.path}`}},404)});return O}function K3(){let O=c2(),$=[];for(let x of Object.keys(O)){let Q=O[x];if(!Q)continue;for(let Z of Q){if(Z.internal||Z.family!=="IPv4")continue;if(Z.address.startsWith("172."))continue;$.push(Z.address)}}return $}function Zx(){return typeof globalThis.Bun<"u"}function Jx(O,$){let x=globalThis.Bun,Q=(G)=>{try{return x.serve({hostname:$.hostname,port:G,fetch:O.fetch,idleTimeout:0,websocket:P1})}catch(z){FO.error("Failed to start Bun server:",z);return}},Z=$.port===0?Q(4096)??Q(0):Q($.port);if(!Z)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Z.url,port:Z.port,hostname:Z.hostname,stop:async()=>{Z.stop(!0)}}}function W3(O,$){return new Promise((x,Q)=>{let Z=i2(async(L,b)=>{let w=new URL(L.url||"/",`http://${L.headers.host}`),F=new Headers;for(let[d,C]of Object.entries(L.headers))if(C)if(Array.isArray(C))for(let e of C)F.append(d,e);else F.set(d,C);let P;if(L.method!=="GET"&&L.method!=="HEAD")P=(await new Promise((C)=>{let e=[];L.on("data",(v)=>e.push(v)),L.on("end",()=>C(Buffer.concat(e)))})).toString();let ZO=new Request(w.toString(),{method:L.method,headers:F,body:P});try{let d=await O.fetch(ZO);if(b.statusCode=d.status,d.headers.forEach((C,e)=>{b.setHeader(e,C)}),d.body){let C=d.body.getReader(),e=async()=>{let{done:v,value:YO}=await C.read();if(v){b.end();return}return b.write(YO),e()};await e()}else{let C=await d.text();b.end(C)}}catch(d){FO.error("[Server] Node request error:",d),b.statusCode=500,b.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),G=new $3({noServer:!0}),z=c();t4(G,()=>z),Z.on("upgrade",(L,b,w)=>{if(new URL(L.url||"/",`http://${L.headers.host}`).pathname==="/terminal/ws")G.handleUpgrade(L,b,w,(P)=>{G.emit("connection",P,L)});else b.destroy()});let U=(L)=>{return new Promise((b,w)=>{Z.once("error",(F)=>{if(F.code==="EADDRINUSE")w(F);else w(F)}),Z.listen(L,$.hostname,()=>{let F=Z.address();if(F&&typeof F==="object")b(F.port);else b(L)})})};(async()=>{let L;if($.port===0)try{L=await U(4096)}catch{L=await U(0)}else L=await U($.port);let b=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${L}`);x({url:b,port:L,hostname:$.hostname,stop:async()=>{return new Promise((w)=>{G.close(()=>{Z.close(()=>w())})})}})})().catch(Q)})}var Gx;((o7)=>{let O,$,x,Q=(L,b)=>{if(O!==L)return Promise.resolve();if(x)return x;let w=b?.shutdown("server-shutdown");return D0?.stop(),Y3(),x=(async()=>{let F,P=async(ZO)=>{if(!ZO)return;try{await ZO()}catch(d){F??=d}};if(await P(()=>L.stop()),await P(w?()=>w:void 0),zx(),O===L)O=void 0,$=void 0,h0=void 0,x1=void 0,D0=void 0;if(FO.info("[Server] Blade server stopped"),F!==void 0)throw F})(),x};function Z(){if(!$)$=N3();return $}o7.getApp=Z;function G(L){h1=L.cors??[];let b=Z();if(Zx())O=Jx(b,L),x=void 0,FO.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let w=O,F=h0;return x1?.().catch((P)=>{FO.warn("[Server] Failed to recover queued tasks:",P)}),D0?.start(),Qx(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>Q(w,F)}}o7.listen=G;async function z(L){h1=L.cors??[];let b=Z();if(Zx())O=Jx(b,L),FO.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await W3(b,L),FO.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);x=void 0;let w=O,F=h0;try{await x1?.()}catch(P){FO.warn("[Server] Failed to recover queued tasks:",P)}return D0?.start(),Qx(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>Q(w,F)}}o7.listenAsync=z;function U(){return O!==void 0}o7.isRunning=U;function j(){return h0?.getCoordinationStats()}o7.getSessionCoordinationStatsForTests=j})(Gx||={});export{F3 as f,U3 as g,K3 as h,Gx as i};
|
|
6
|
+
`,Buffer.byteLength($)}class A0{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??t1,this.maxPendingBytes=O.maxPendingBytes??s1,this.serial=new e1({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??r1,sizeOf:n1,write:O.write,onFailure:($)=>{this.failure=$,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,O.onFailure?.($)}})}async writeInitial(O){await this.offerDirect(O)}observe(O,$){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer(O,$);return}this.offerLive(O,$)}async writeReplay(O,$){if(!Number.isSafeInteger($)||$<=0)throw this.fail(new x0("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if($<=this.highestReplaySequence)return;await this.offerDirect(O),this.highestReplaySequence=$,this.highestDeliveredSequence=$}finishInitialization(O){if(this.phase!=="buffering")return;let $=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let x=O.replayed?$.filter((Z)=>Z.sequence!==void 0&&Z.sequence>this.highestReplaySequence).sort((Z,G)=>Z.sequence-G.sequence||Z.order-G.order):$.sort((Z,G)=>Z.order-G.order),Q;for(let Z of x){if(O.replayed&&Z.sequence!==void 0&&Z.sequence===Q)continue;if(this.offerLive(Z.message,Z.sequence),this.serial.stats().closed)return;Q=Z.sequence}}offerHeartbeat(O){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive(O),!this.serial.stats().closed}async flush(){await this.serial.flush()}close(O){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close(O)}stats(){let O=this.serial.stats();return{closed:this.phase==="closed",pendingItems:O.pendingItems+this.buffered.length,pendingBytes:O.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer(O,$){let x=n1(O),Q=this.serial.stats();if(x>this.maxPendingBytes){this.fail(new x0("oversized",`SSE frame requires ${x} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:Q.pendingItems+this.buffered.length,pendingBytes:Q.pendingBytes+this.bufferedBytes}));return}if(Q.pendingItems+this.buffered.length>=this.maxPendingItems||Q.pendingBytes+this.bufferedBytes+x>this.maxPendingBytes){this.fail(new x0("overflow","SSE initialization buffer limit exceeded",{pendingItems:Q.pendingItems+this.buffered.length,pendingBytes:Q.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:x,sequence:$,order:this.nextOrder}),this.bufferedBytes+=x}offerLive(O,$){if($!==void 0){if($<=this.highestReplaySequence)return;if($<=this.highestDeliveredSequence){this.fail(new x0("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=$}if(!this.serial.offer(O).accepted)this.phase="closed"}async offerDirect(O){if(this.phase==="closed")throw this.currentFailure();let $=this.serial.offer(O);if(!$.accepted)throw this.phase="closed",$.error;await $.completion}fail(O){this.serial.close(O)}currentFailure(){return this.failure??new x0("closed","SSE egress is closed")}}var Hx=15000,Lx=o("Service"),Bx=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),wx=new Set(["queued","running","completed","failed","cancelled","interrupted"]),Ax=new Set(["high","medium","low"]),Mx=new Set(["feature","bug","maintenance","research"]);function Tx(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=["changedFiles","additions","deletions","commits"];if(x.some((Q)=>typeof $[Q]!=="number"||!Number.isInteger($[Q])||$[Q]<0))return;return Object.fromEntries(x.map((Q)=>[Q,$[Q]]))}function M0(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function jx(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if(!["applied","discarded","conflicted"].includes(String($.status))||typeof $.updatedAt!=="string")return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},...M0($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}var O$=()=>{let O=new _x;return O.get("/",($)=>Dx($,async(x)=>{let Q,Z,G=!1,z,U,j=new Promise((F)=>{U=F}),L=()=>{if(Z!==void 0)clearInterval(Z),Z=void 0;Q?.(),Q=void 0},b=(F)=>{if(G)return;G=!0,L(),z?.close(F),U()};x.onAbort(b),z=new A0({write:async(F)=>{await x.writeSSE(F)},onFailure:(F)=>{Lx.warn(`[EventRoutes] SSE egress closed: kind=${F.kind} pendingItems=${F.pendingItems??0} pendingBytes=${F.pendingBytes??0}`),b(F)}});let w=(F,P)=>{z?.observe({data:JSON.stringify({type:F,properties:P})})};Q=S.subscribe((F)=>{if(!Bx.has(F.type))return;if(F.type==="permission.asked"||F.type==="question.required"||F.type==="elicitation.required"){let n=F.properties.requestId;if(typeof n!=="string"||!n)return;w("interaction.pending",{sessionId:F.sessionId,projectPath:F.projectPath,interactionType:F.type==="question.required"?"question":F.type==="elicitation.required"?"elicitation":"permission",requestId:n});return}if(F.type==="interaction.resolved"){let n=F.properties.requestId;if(typeof n!=="string"||!n)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,requestId:n});return}if(F.type==="session.created"||F.type==="session.deleted"){w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath});return}if(F.type==="session.updated"){let n=F.properties.title,$O=F.properties.taskPriority,PO=F.properties.taskKind,s=F.properties.taskDueAt,lO=typeof n==="string"&&Boolean(n.trim()),wO=Ax.has(String($O)),N=Mx.has(String(PO)),NO=s===null||typeof s==="string"&&Number.isFinite(Date.parse(s));if(!lO&&!wO&&!N&&!NO)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,...lO?{title:n}:{},...wO?{taskPriority:$O}:{},...N?{taskKind:PO}:{},...NO?{taskDueAt:s}:{}});return}if(F.type==="task.delivery"){let n=jx(F.properties.taskDelivery);if(!n)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,taskDelivery:n,...F.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof F.properties.updatedAt==="string"?{updatedAt:F.properties.updatedAt}:{}});return}if(F.type==="schedule.fired"){let n=F.properties.scheduleId,$O=F.properties.firedAt;if(typeof n!=="string"||typeof $O!=="string")return;w(F.type,{scheduleId:n,firedAt:$O,sessionId:F.sessionId,projectPath:F.projectPath,...typeof F.properties.runId==="string"?{runId:F.properties.runId}:{},...typeof F.properties.status==="string"?{status:F.properties.status}:{}});return}let P=F.properties.taskStatus;if(typeof P!=="string"||!wx.has(P))return;let ZO=Tx(F.properties.taskDiffStat),d=M0(F.properties.taskQueuePosition,1),C=M0(F.properties.taskQueueDepth,0),e=M0(F.properties.taskConcurrencyLimit,1),u=M0(F.properties.taskInFlight,0),YO=typeof F.properties.taskAdmissionPaused==="boolean"?F.properties.taskAdmissionPaused:void 0;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,taskStatus:P,...typeof F.properties.taskStatusReason==="string"?{taskStatusReason:F.properties.taskStatusReason}:{},...F.properties.taskFailure&&typeof F.properties.taskFailure==="object"?{taskFailure:F.properties.taskFailure}:{},...typeof F.properties.taskStartedAt==="string"?{taskStartedAt:F.properties.taskStartedAt}:{},...typeof F.properties.taskCompletedAt==="string"?{taskCompletedAt:F.properties.taskCompletedAt}:{},...typeof F.properties.updatedAt==="string"?{updatedAt:F.properties.updatedAt}:{},...ZO?{taskDiffStat:ZO}:{},...d!==void 0?{taskQueuePosition:d}:{},...C!==void 0?{taskQueueDepth:C}:{},...e!==void 0?{taskConcurrencyLimit:e}:{},...u!==void 0?{taskInFlight:u}:{},...YO!==void 0?{taskAdmissionPaused:YO}:{}})});try{if(x.aborted||G)return;if(await z.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),x.aborted||G)return;if(z.finishInitialization({replayed:!1}),x.aborted||G)return;Z=setInterval(()=>{if(x.aborted||G)return;z?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},Hx),await j}finally{b()}})),O};import{Hono as bx}from"hono";var Cx=V.Object({paused:V.Boolean()}),x$=()=>{let O=new bx;return O.get("/health",($)=>{return $.json({healthy:!0,version:Q0()})}),O.get("/info",($)=>{let x=c(),Q=QO();if(Q)mO.configure(Q.maxConcurrentTasks,Q.maxQueuedTasks,Q.maxQueuedTaskBytes);let Z=mO.getStats();return $.json({version:Q0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:x,gitBranch:$$(x),taskAdmission:{inFlight:Z.inFlight,queued:Z.queued,maxConcurrent:Z.maxConcurrent,maxQueued:Z.maxQueued,paused:Z.paused}})}),O.put("/task-admission",async($)=>{let x;try{x=await $.req.json()}catch{throw new _("Invalid request body")}let Q=q(Cx,x);if(!Q.success)throw new _("Invalid task admission control request");mO.setPaused(Q.data.paused);let Z=mO.getStats();return $.json({inFlight:Z.inFlight,queued:Z.queued,maxConcurrent:Z.maxConcurrent,maxQueued:Z.maxQueued,paused:Z.paused})}),O};import Q$ from"node:path";import{Hono as Sx}from"hono";var Rx=V.Object({projectPath:V.String({minLength:1}),action:JO(["trust","revoke"]),expectedDigest:V.Optional(V.String())}),Ex=V.Object({projectPath:V.String({minLength:1}),sessionId:V.String({minLength:1}),enabled:V.Boolean()});function V1(O){if(!O||!Q$.isAbsolute(O))throw new _("projectPath must be absolute");return Q$.resolve(O)}function Z$(O){if(!O)throw new _("sessionId is required");try{i0(O)}catch($){throw new _($ instanceof Error?$.message:"sessionId is invalid")}return O}async function l0(O){let $=V1(O),x=QO()?.hooks??z$.hooks,Q=await T0.getInstance().loadWorkspaceHooks($,x,{includeBaseForCurrentWorkspace:!1});return C0($,async()=>{b0($);let Z=Z0.getInstance();return Z.loadConfig(Q,$),await j0($),Z.getConfig($)})}function J$(O,$){let x=Z0.getInstance(),Q=x.getConfig($).enabled,Z=x.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:x.isSessionEnabled(O,$),paused:Z,configEnabled:Q}}var G$=()=>{let O=new Sx;return O.get("/trust",async($)=>{let x=$.req.query("projectPath");if(!x)throw new _("projectPath query parameter is required");return await l0(x),$.json(await Z0.getInstance().getTrustStatus(x))}),O.post("/trust",async($)=>{let x=q(Rx,await $.req.json());if(!x.success)throw new _("Invalid hook trust request");let{projectPath:Q,action:Z,expectedDigest:G}=x.data;await l0(Q);let z=Z0.getInstance(),U;try{U=Z==="trust"?await z.trustProject(Q,G):await z.revokeProjectTrust(Q)}catch(j){if(j instanceof Y$)throw new k(j.message);throw j}return $.json(U)}),O.get("/session",async($)=>{let x=V1($.req.query("projectPath")),Q=Z$($.req.query("sessionId"));return await l0(x),$.json(J$(Q,x))}),O.post("/session",async($)=>{let x=q(Ex,await $.req.json());if(!x.success)throw new _("Invalid hook session request");let Q=V1(x.data.projectPath),Z=Z$(x.data.sessionId);await l0(Q);let G=Z0.getInstance();if(x.data.enabled)G.enableSession(Z,Q);else G.disableSession(Z,Q);return $.json(J$(Z,Q))}),O};import{Hono as kx}from"hono";var RO=o("Service");function qx(O){try{return V$(O)}catch{return[]}}function Ix(O){if(!c0(O)||!c0(O.reference)||!c0(O.argument))throw Error("Invalid MCP completion request");let $=O.reference.type,x=$==="prompt"&&typeof O.reference.name==="string"?{type:"prompt",name:O.reference.name}:$==="resource"&&typeof O.reference.uri==="string"?{type:"resource",uri:O.reference.uri}:void 0;if(!x||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let Q;if(O.context!==void 0){if(!c0(O.context))throw Error("Invalid MCP completion context");Q=Object.create(null);for(let[Z,G]of Object.entries(O.context)){if(typeof G!=="string")throw Error("Invalid MCP completion context");Q[Z]=G}}return{reference:x,argument:{name:O.argument.name,value:O.argument.value},...Q?{context:Q}:{}}}function c0(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function hO(O,$){let x=QO()?.mcpServers??{};for(let[Q,Z]of Object.entries(x)){if($&&Q!==$)continue;if(!O.getServerStatus(Q))await O.registerServer(Q,Z,{connect:!1})}}var N$=()=>{let O=new kx;return O.get("/",async($)=>{try{let x=UO.getInstance();await hO(x);let Q=x.getAllServers(),Z=await Promise.all(Array.from(Q.entries()).map(async([G,z])=>({id:G,name:G,status:z.status==="connected"?"connected":z.status==="reconnecting"?"reconnecting":z.status==="connecting"?"connecting":z.lastError?"error":"offline",endpoint:z.config.command?`${z.config.command} ${(z.config.args||[]).join(" ")}`.trim():z.config.url||"Unknown",description:`MCP server: ${G}`,tools:z.tools.map((U)=>U.name),completionSupported:z.client.completionSupported,tasks:z.client.tasks,resources:z.contentCatalog.resources,resourceTemplates:z.contentCatalog.resourceTemplates.map((U)=>({...U,variables:qx(U.uriTemplate)})),prompts:z.contentCatalog.prompts,connectedAt:z.connectedAt?.toISOString(),error:z.lastError?.message,recovery:z.recovery,logging:z.logging,instructions:z.instructions,oauthEnabled:z.client.oauthEnabled,oauthStatus:await z.client.getOAuthStatus()})));return $.json(Z)}catch(x){return RO.error("[McpRoutes] Failed to get MCP servers:",x),$.json({error:x instanceof Error?x.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();return await hO(Q,x),await Q.connectServer(x),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to connect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();return await hO(Q,x),await Q.disconnectServer(x),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to disconnect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.get("/:name/logs",async($)=>{try{let x=$.req.param("name"),Q=Number($.req.query("limit")??20),Z=Number($.req.query("afterRevision")??0);if(!Number.isSafeInteger(Q)||Q<1||Q>100||!Number.isSafeInteger(Z)||Z<0)return $.json({error:"Invalid MCP log pagination"},400);let G=UO.getInstance();return await hO(G,x),$.json(G.getLogSnapshot(x,{limit:Q,afterRevision:Z}))}catch(x){return RO.error("[McpRoutes] Failed to get MCP logs:",x),$.json({error:x.message},500)}}),O.post("/:name/logging-level",async($)=>{try{let x=$.req.param("name"),Q=await $.req.json();if(!X$(Q.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let Z=UO.getInstance();return await hO(Z,x),await Z.setServerLoggingLevel(x,Q.level),$.json({success:!0,level:Q.level})}catch(x){return RO.error("[McpRoutes] Failed to set MCP logging level:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/complete",async($)=>{try{let x=$.req.param("name"),Q=Ix(await $.req.json()),Z=UO.getInstance();await hO(Z,x);let G=await Z.complete(x,Q);return $.json(G)}catch(x){return RO.error("[McpRoutes] Failed to complete MCP argument:",x),$.json({error:x.message},400)}}),O.post("/:name/oauth/login",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();await hO(Q,x);let Z=await Q.beginOAuthLogin(x);return $.json({success:!0,flowId:Z.flowId,authorizationUrl:Z.authorizationUrl},202)}catch(x){return RO.error("[McpRoutes] Failed to start MCP OAuth login:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/oauth/logout",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();return await hO(Q,x),await Q.logoutOAuth(x),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to log out MCP OAuth:",x),$.json({success:!1,error:x.message},400)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name");await UO.getInstance().unregisterServer(x);let Z=QO();if(Z?.mcpServers){let{[x]:G,...z}=Z.mcpServers;await BO().updateConfig({mcpServers:z})}return $.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to delete MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/",async($)=>{try{let x=await $.req.json(),{name:Q,config:Z}=x;if(!Q||!Z)return $.json({success:!1,error:"Missing name or config"},400);await UO.getInstance().registerServer(Q,Z);let z=QO();return await BO().updateConfig({mcpServers:{...z?.mcpServers,[Q]:Z}}),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to add MCP server:",x),$.json({success:!1,error:x.message},500)}}),O};import{getSupportedThinkingLevels as Px}from"@earendil-works/pi-ai";import{Hono as yx}from"hono";var a0=o("Service");function fx(O,$,x=U$.list()){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,supportedReasoningEfforts:Px($),supportedServiceTiers:W$($),supportedResponseVerbosities:K$($),communicationStyles:x,input:$.input}}function mx(O){_$(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function _$(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new _("streamIdleTimeout must be at least 1000ms")}var D$=()=>{let O=new yx;return O.get("/",async($)=>{try{let x=QO();if(!x)throw Error("Config not initialized");let Q=$.get("directory")||c(),[Z,G]=await Promise.all([o0(Q,x),jO(Q)]),z=Z.config.models,U=z.find((w)=>w.id===Z.config.currentModelId)??z[0],j=Z.catalog,L=G.communicationStyles.list(),b=(w)=>fx(w,j.resolveConfig(w),L);return $.json({configured:z.map(b),current:U?b(U):null})}catch(x){a0.error("[ModelsRoutes] Failed to get models:",x);let Q=new t("Failed to get models");return $.json(Q.toObject(),500)}}),O.post("/",async($)=>{let x=cO(),Q,Z;try{let G=await $.req.json(),{provider:z,displayName:U,model:j,overrides:L,apiKey:b,modelProvider:w}=G;if(!z||!j)throw new _("provider and model are required");_$(L);let F;if(w){if(w.id!==z)throw new _("modelProvider.id must match the model provider");if(QO()?.modelProviders[z])throw new _(`model provider already exists: ${z}`);F={name:w.name,baseUrl:w.baseUrl,wireApi:w.wireApi,...w.apiKeyEnv?{apiKeyEnv:w.apiKeyEnv}:{}};try{x.registerModelProvider(z,F,[j]),Z=z}catch(d){throw new _(d instanceof Error?d.message:"Invalid model provider")}}else x.getModel(z,j);if(b?.trim()){if(await x.setApiKey(z,b.trim()),F)Q=z}let P={provider:z,displayName:U||void 0,model:j,overrides:L||void 0},ZO=F?await BO().addModelWithProvider(P,F):await BO().addModel(P);return $.json({success:!0,model:ZO})}catch(G){if(Q)await x.credentials.delete(Q);if(Z){let z=QO();x.configureModelProviders(z?.modelProviders??{},z?.models??[])}throw a0.error("[ModelsRoutes] Failed to add model:",G),G}}),O.put("/:modelId",async($)=>{try{let x=$.req.param("modelId"),Q=await $.req.json(),{displayName:Z,overrides:G,model:z}=Q,U=F$(x);if(!U)throw new _("model config not found");if(z)cO().getModel(U.provider,z);return await BO().updateModel(x,mx({displayName:Z,overrides:G,model:z})),$.json({success:!0})}catch(x){throw a0.error("[ModelsRoutes] Failed to update model:",x),x}}),O.delete("/:modelId",async($)=>{try{let x=$.req.param("modelId");return await BO().removeModel(x),$.json({success:!0})}catch(x){throw a0.error("[ModelsRoutes] Failed to delete model:",x),x}}),O};import{Hono as $2}from"hono";import H$ from"node:path";import{Hono as hx}from"hono";import{streamSSE as gx}from"hono/streaming";import{LRUCache as ux}from"lru-cache";import{nanoid as Y0}from"nanoid";var g=o("Service"),vx=V.Object({title:V.Optional(V.String()),projectPath:V.Optional(V.String())}),px=l$,dx=V.Object({title:V.Optional(V.String()),projectPath:V.Optional(V.String())}),lx=V.Object({projectPath:V.String()}),ix=V.Object({objective:V.String({minLength:1}),tokenBudget:V.Optional(V.Integer({minimum:1})),permissionMode:V.Optional(JO(["default","autoEdit","plan","yolo"]))}),cx=V.Union([V.Object({action:V.Literal("pause")}),V.Object({action:V.Literal("resume")}),V.Object({action:V.Literal("edit"),objective:V.String({minLength:1})})]),r=new Map,G0,CO=new Map,IO=new Map,bO=new Map,e0=new ux({max:100,ttl:1800000});function L$(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function DO(O){if(!O)return;return CO.get(O)??e0.get(O)}function ax(O){if(CO.get(O.id)!==O)return;CO.delete(O.id),e0.set(O.id,O)}function ox(O){CO.delete(O),e0.delete(O)}function _O(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function k0(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let x=O.pendingPermission;if(O.pendingPermission=void 0,x?.resolve({approved:!1,reason:S$}),x)S.publish(L$(O),"interaction.resolved",{requestId:x.permissionId});return O.abortController.abort($),O.status="cancelled",S.publish(L$(O),"run.cancelled",{runId:O.id}),!0}function n$(O,$=!1){let{permissionId:x,details:Q}=O;if(Q.type==="askUserQuestion"&&Q.questions)return{type:"question.required",properties:{requestId:x,toolCallId:Q.toolCallId??x,questions:Q.questions,details:Q,...$?{replayed:!0}:{}}};if(Q.type==="mcpElicitation"&&Q.mcpElicitation)return{type:"elicitation.required",properties:{requestId:x,toolCallId:Q.toolCallId??x,elicitation:Q.mcpElicitation,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:Q.toolName,description:Q.message,args:Q.args,details:Q,...$?{replayed:!0}:{}}}}function nx(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 tx(){for(let O of CO.values())k0(O,"route-reset");CO.clear();for(let O of IO.values())O.controller.abort("route-reset");IO.clear(),e0.clear(),G0=void 0,r.clear()}function sx(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=$.code,Q=$.reason,Z=$.scope,G=$.kind,z=$.limit;if(x!=="tool_busy"&&x!=="tool_batch_full"||Q!=="queue_full"&&Q!=="wait_timeout"&&Q!=="turn_limit"||Z!=="global"&&Z!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(z)||z<=0||G!==void 0&&G!=="readonly"&&G!=="write"&&G!=="execute")return;return{code:x,reason:Q,scope:Z,retryable:$.retryable,...G===void 0?{}:{kind:G},limit:z}}var q0=(O,$)=>{if(!$||typeof $!=="object")return $;let x={...$},Q=sx(x.tool_admission);if(Q)x.tool_admission=Q;else delete x.tool_admission;if(O==="Bash"){let z={},U=["message","signal","status","summary"],j=["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"],L=["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 w of U){let F=x[w];if(typeof F==="string")z[w]=F.slice(0,8192)}for(let w of j){let F=x[w];if(typeof F==="boolean")z[w]=F}for(let w of L){let F=x[w];if(typeof F==="number"&&Number.isSafeInteger(F)&&F>=0)z[w]=F}if(x.exit_code===null||typeof x.exit_code==="number"&&Number.isSafeInteger(x.exit_code))z.exit_code=x.exit_code;if(x.terminal_transport==="local"||x.terminal_transport==="acp"||x.terminal_transport==="local_fallback")z.terminal_transport=x.terminal_transport;if(x.background_reason==="explicit"||x.background_reason==="foreground_budget")z.background_reason=x.background_reason;for(let w of["bash_id","shell_id"]){let F=x[w];if(typeof F==="string"&&F.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(F))z[w]=F}if(Q)z.tool_admission=Q;let b=x.background_shell_admission;if(b&&typeof b==="object"&&!Array.isArray(b)){let w=b;if(w.code==="background_shell_busy"&&(w.scope==="session"||w.scope==="global")&&w.retryable===!0&&Number.isSafeInteger(w.limit)&&w.limit>0)z.background_shell_admission={code:w.code,scope:w.scope,retryable:w.retryable,limit:w.limit}}return z}let Z=200000,G=(z,U)=>typeof z==="number"&&Number.isSafeInteger(z)&&z>=0&&z<=U?z:0;if(typeof x.oldContent==="string"&&x.oldContent.length>Z)delete x.oldContent;if(typeof x.newContent==="string"&&x.newContent.length>Z)delete x.newContent;if(x.mcpResult&&typeof x.mcpResult==="object"&&!Array.isArray(x.mcpResult)){let z=x.mcpResult,U=Array.isArray(z.artifacts)?z.artifacts.slice(0,64).flatMap((j)=>{if(!j||typeof j!=="object"||Array.isArray(j))return[];let L=j,b=new Set(["text","image","audio","resource"]);if(typeof L.id!=="string"||!/^[a-f0-9]{64}$/.test(L.id)||typeof L.sha256!=="string"||L.sha256!==L.id||typeof L.kind!=="string"||!b.has(L.kind)||G(L.size,67108864)!==L.size||typeof L.persisted!=="boolean")return[];return[{id:L.id.slice(0,128),sha256:L.sha256.slice(0,128),kind:L.kind,size:L.size,persisted:L.persisted,...typeof L.mimeType==="string"?{mimeType:L.mimeType.slice(0,256)}:{},...typeof L.sourceUri==="string"?{sourceUri:L.sourceUri.slice(0,8192)}:{},...typeof L.path==="string"?{path:L.path.slice(0,8192)}:{}}]}):[];x.mcpResult={isError:z.isError===!0,contentCount:G(z.contentCount,64),textBytes:G(z.textBytes,4194304),structuredBytes:G(z.structuredBytes,4194304),artifactCount:G(z.artifactCount,64),truncated:z.truncated===!0,binaryOmitted:z.binaryOmitted===!0,artifacts:U}}else delete x.mcpResult;return x};function rx(O){let $=typeof O.seq==="number"?{seq:O.seq}:{};if(O.type==="part_created"&&O.data.partType==="tool_call"){let x=O.data.payload;return{type:"tool.start",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let x=O.data.payload,Q=x.toolName??"unknown",Z=A1(x),G=P0(y0(Q,Z),I0);return{type:"tool.result",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:Q,success:Z.success,status:Z.success?"completed":"failed",summary:Z.metadata?.summary,output:f0(G),metadata:q0(Q,Z.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function ex(O,$,x){switch(x.kind){case"tool_start":if("function"in x.toolCall)S.publish(O,"subagent.update",{subagentSessionId:$,toolName:x.toolCall.function.name}),S.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,arguments:x.toolCall.function.arguments,toolKind:x.toolKind});break;case"tool_result":if("function"in x.toolCall)S.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,success:x.result.success,summary:x.result.metadata?.summary,output:f0(P0(y0(x.toolCall.function.name,x.result),I0)),metadata:q0(x.toolCall.function.name,x.result.metadata)});break;case"tool_progress":if("function"in x.toolCall)S.publish(O,"subagent.tool.progress",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,...x.update});break;case"content_delta":S.publish(O,"subagent.delta",{subagentSessionId:$,delta:x.delta});break;case"thinking_delta":S.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:x.delta});break;case"stream_end":S.publish(O,"subagent.stream.end",{subagentSessionId:$});break;case"provider_admission":S.publish(O,"subagent.provider.admission",{subagentSessionId:$,phase:x.phase,requestClass:x.requestClass,resource:x.resource,scope:x.scope,reason:x.reason,queuePosition:x.queuePosition,queueDepth:x.queueDepth,inFlight:x.inFlight,limit:x.limit,waitMs:x.waitMs,maxWaitMs:x.maxWaitMs,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_circuit":S.publish(O,"subagent.provider.circuit",{subagentSessionId:$,phase:x.phase,reason:x.reason,statusCode:x.statusCode,retryAfterMs:x.retryAfterMs,nextProbeAt:x.nextProbeAt,openDurationMs:x.openDurationMs,sampleCount:x.sampleCount,failureCount:x.failureCount,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_retry":S.publish(O,"subagent.provider.retry",{subagentSessionId:$,phase:x.phase,attempt:x.attempt,maxRetries:x.maxRetries,reason:x.reason,statusCode:x.statusCode,delayMs:x.delayMs,nextRetryAt:x.nextRetryAt,mode:x.mode,recoveryBudgetMs:x.recoveryBudgetMs,recoveryElapsedMs:x.recoveryElapsedMs,recoveryRemainingMs:x.recoveryRemainingMs,exhaustedBy:x.exhaustedBy});break;case"provider_stall":S.publish(O,"subagent.provider.stall",{subagentSessionId:$,phase:x.phase,stallCount:x.stallCount,durationMs:x.durationMs,warningAfterMs:x.warningAfterMs,timeoutMs:x.timeoutMs,outputStarted:x.outputStarted});break;case"action_stationarity":S.publish(O,"subagent.action.stationarity",{subagentSessionId:$,phase:x.phase,toolName:x.toolName,runLength:x.runLength,nudgeThreshold:x.nudgeThreshold,haltThreshold:x.haltThreshold,progressAware:x.progressAware});break;case"mcp_catalog_changed":S.publish(O,"subagent.mcp.catalog.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_content_changed":S.publish(O,"subagent.mcp.content.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,contentKind:x.contentKind,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_resource_updated":S.publish(O,"subagent.mcp.resource.updated",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,uri:x.uri});break;case"mcp_connection_changed":S.publish(O,"subagent.mcp.connection.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,phase:x.phase,reason:x.reason,attempt:x.attempt,maxAttempts:x.maxAttempts,nextRetryAt:x.nextRetryAt,error:x.error});break;case"mcp_log":S.publish(O,"subagent.mcp.log",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,level:x.level,logger:x.logger,message:x.message,projectedBytes:x.projectedBytes,dataSha256:x.dataSha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted,timestamp:x.timestamp,synthetic:x.synthetic});break;case"mcp_instructions_changed":S.publish(O,"subagent.mcp.instructions.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,action:x.action,reason:x.reason,text:x.text,sourceBytes:x.sourceBytes,projectedBytes:x.projectedBytes,sha256:x.sha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted});break;case"mcp_task_changed":S.publish(O,"subagent.mcp.task.changed",{subagentSessionId:$,revision:x.revision,taskId:x.taskId,serverName:x.serverName,toolName:x.toolName,status:x.status,statusMessage:x.statusMessage,createdAt:x.createdAt,updatedAt:x.updatedAt,completedAt:x.completedAt,hasResult:x.hasResult,error:x.error});break;case"project_rules_loaded":S.publish(O,"subagent.project.rules.loaded",{subagentSessionId:$,files:x.files,triggerPaths:x.triggerPaths,blockedWrite:x.blockedWrite});break;default:break}}function R0(O,$="projectPath"){if(!H$.isAbsolute(O))throw new _(`${$} must be absolute`);return H$.resolve(O)}function B1(O){try{i0(O)}catch($){throw new _($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function GO(O){return{sessionId:O.id,projectPath:O.projectPath}}function E0(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:x,messages:$}}function N1(O){return O.flatMap(($)=>{if(!E$($)||$.role==="system"||$.role==="tool"&&$.name===z0)return[];let x=$.tool_calls?.filter((z)=>!("function"in z)||z.function.name!==z0),Q=typeof $.content==="string"?$.content.trim():"";if($.role==="assistant"&&$.tool_calls?.length&&!x?.length&&!Q&&!$.reasoningContent&&!$.metadata)return[];let Z={...$,...$.tool_calls?{tool_calls:x&&x.length>0?x:void 0}:{}};if($.role==="tool"){let z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0,U=$.name??(typeof z?.toolName==="string"?z.toolName:"unknown");if(z!==void 0&&(Object.hasOwn(z,"output")||Object.hasOwn(z,"error"))){let L=A1(z),b=P0(y0(U,L),I0);return[{...Z,name:U,content:f0(b),metadata:q0(U,{...L.metadata,status:L.success?"completed":"failed"})}]}return[{...Z,name:U,metadata:q0(U,z)}]}let G=q$($.metadata);return[G?{...Z,content:k$(G)}:Z]})}function X0(O,$){O.title=$.title??O.title,O.taskStatus=$.taskStatus,O.taskStatusReason=$.taskStatusReason,O.taskFailure=$.taskFailure,O.taskStartedAt=$.taskStartedAt,O.taskCompletedAt=$.taskCompletedAt,O.taskPromptSummary=$.taskPromptSummary,O.taskPriority=$.taskPriority,O.taskKind=$.taskKind,O.taskDueAt=$.taskDueAt,O.taskModelId=$.taskModelId,O.selectedModelId=$.selectedModelId,O.permissionMode=$.permissionMode,O.reasoningEffort=$.reasoningEffort,O.serviceTier=$.serviceTier,O.responseVerbosity=$.responseVerbosity,O.communicationStyle=$.communicationStyle,O.communicationStyleDigest=$.communicationStyleDigest,O.projectInstructionsDigest=$.projectInstructionsDigest,O.pendingInteraction=$.pendingInteraction,O.taskRetryAvailable=$.taskRetryAvailable,O.taskRetriedFrom=$.taskRetriedFrom,O.taskDelivery=$.taskDelivery,O.taskIsolation=$.taskIsolation,O.taskSourceProjectPath=$.taskSourceProjectPath,O.taskWorktreePath=$.taskWorktreePath,O.taskWorktreeBranch=$.taskWorktreeBranch,O.taskBaseCommit=$.taskBaseCommit,O.taskDiffStat=$.taskDiffStat,O.taskQueuePosition=$.taskQueuePosition,O.taskQueueDepth=$.taskQueueDepth,O.taskConcurrencyLimit=$.taskConcurrencyLimit,O.archivedAt=$.archivedAt,O.archivedBySessionId=$.archivedBySessionId,O.updatedAt=new Date($.lastMessageTime)}async function tO(O){let $=await R.findSessionMetadata(O.id,O.projectPath);if($)X0(O,$)}function aO(O){let $=DO(O.currentRunId),x=$?.status==="waiting_permission"?"running":$?.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:x,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:x==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:x==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:$?.pendingPermission?{type:$.pendingPermission.details.type==="askUserQuestion"?"question":$.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:$.pendingPermission.permissionId}:O.pendingInteraction,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function KO(O,$){if(B1(O),$!==void 0){let Q=gO({sessionId:O,projectPath:R0($)});if(r.has(v(Q)))return Q;let Z=await R.findSessionMetadata(Q.sessionId,Q.projectPath);if(!Z)throw new f("Session",O);return gO({sessionId:Z.sessionId,projectPath:Z.projectPath})}let x=new Map;for(let Q of r.values()){if(Q.id!==O)continue;let Z=GO(Q);x.set(v(Z),Z)}for(let Q of await R.listSessions()){if(Q.sessionId!==O)continue;let Z=gO({sessionId:Q.sessionId,projectPath:Q.projectPath});x.set(v(Z),Z)}if(x.size===0)try{let Q=await R.findSessionMetadata(O);if(!Q)throw new f("Session",O);return gO({sessionId:Q.sessionId,projectPath:Q.projectPath})}catch(Q){if(Q instanceof f)throw Q;if(Q instanceof Error&&Q.message.startsWith("Ambiguous session ID:"))throw new LO;throw Q}if(x.size>1)throw new LO;return x.values().next().value}function w1(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
|
|
7
|
+
`)}function B$(O,$){let x=($??[]).filter((Z)=>Z.type==="image"&&typeof Z.content==="string").map((Z)=>({type:"image_url",image_url:{url:Z.content}}));if(x.length===0)return O;let Q=[];if(O.trim())Q.push({type:"text",text:O});return Q.push(...x),Q}var t$=()=>{tx();let O=new hx;O.onError((J,K)=>{if(J instanceof J0){let Y=new kO("Session runtime capacity is full",{resource:J.resource,limit:J.limit});return K.json(Y.toObject(),429)}if(J instanceof xO)return K.json(J.toObject(),J.statusCode);return g.error("[SessionRoutes] Unhandled route error:",J),K.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,x=new Map,Q=new Map,Z=new Map,G=new K1,z=new K1,U=QO(),j=new o$({maxResident:U?.maxResidentSessionRuntimes??M$,idleMs:U?.sessionRuntimeIdleMs??T$}),L=new h$,b=setInterval(()=>{j.sweepIdle().catch((J)=>{g.warn("[SessionRoutes] Session Runtime idle sweep failed:",J)})},j$);b.unref?.();let w,F=async(J)=>{let K;try{K=L.enter()}catch{throw new qO}try{return await J()}finally{K.release()}};O.use("*",async(J,K)=>{if(J.req.method==="GET"||J.req.method==="HEAD")return K();return F(K)});let P=(J,K)=>G.runExclusive(v(J),K),ZO=(J,K)=>z.runExclusive(v(J),K),d=(J)=>[...CO.values()].some((K)=>K.sessionId===J.sessionId&&K.projectPath===J.projectPath&&_O(K)),C=async(J,K,Y)=>{let X=Q.get(K);if(!X)X=(async()=>{if($.get(K)===Y)$.delete(K);for(let[H,D]of $)if(D===Y)$.delete(H);let W=GO(J);if(r.get(K)===J&&!d(W)&&!IO.has(K)&&!bO.has(K))r.delete(K);if(await Y.dispose(),$.size===0)await UO.getInstance().disconnectAll()})().finally(()=>{if(Q.get(K)===X)Q.delete(K)}),Q.set(K,X);await X},e=async(J,K={})=>{let Y=GO(J),X=v(Y);await Q.get(X);let W=j.acquire(X);if(W){if($.get(X)!==W.value)throw W.release(),Error("Session Runtime residency identity is inconsistent");return W}if(j.owns(X))throw new J0(j.getStats().maxResident);let H=x.get(X);if(!H){let D=K.communicationStyle??J.communicationStyle;H=(async()=>{let B=await j.reserve(X,{surface:"web",allowEviction:!0});try{let A=await S0.create({sessionId:J.id,workspaceRoot:J.projectPath,...J.selectedModelId??J.taskModelId?{modelId:J.selectedModelId??J.taskModelId}:{},permissionMode:K.permissionMode??J.permissionMode??"default",...J.reasoningEffort?{reasoningEffort:J.reasoningEffort}:{},...J.serviceTier?{serviceTier:J.serviceTier}:{},...J.responseVerbosity?{responseVerbosity:J.responseVerbosity}:{},...D?{communicationStyle:D}:{},...D===J.communicationStyle&&J.communicationStyleDigest?{communicationStyleDigest:J.communicationStyleDigest}:{},...J.projectInstructionsDigest?{projectInstructionsDigest:J.projectInstructionsDigest}:{},...J.taskWorktree?{taskWorktree:J.taskWorktree}:{},...J.taskIsolation?{taskIsolation:J.taskIsolation}:{},...J.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:J.id}}:{}}),M=B.commit({key:X,surface:"web",value:A,canEvict:()=>!d(Y)&&!IO.has(X)&&!bO.has(X)&&!x.has(X)&&!Q.has(X)&&A.isIdleForResidency(),dispose:()=>C(J,X,A)});return $.set(X,A),{runtime:A,claimLease:()=>{if(M){let y=M;return M=void 0,y}let T=j.acquire(X);if(!T||T.value!==A)throw Error("Initialized Session Runtime lost residency");return T}}}catch(A){throw B.cancel(),A}})(),x.set(X,H)}try{return(await H).claimLease()}finally{if(x.get(X)===H)x.delete(X)}},u=async(J,K,Y={})=>{let X=await e(J,Y);try{return await K(X.value)}finally{X.release()}},YO=async(J,K)=>{let Y=v(GO(J)),X=x.get(Y);if(X)await X.catch(()=>{return});x.delete(Y);let W=K??$.get(Y);if(!W)return;if(!await j.remove(Y,W))throw Error(`Session Runtime is pinned and cannot be disposed: ${Y}`)},n=async(J)=>{let K=v(J),Y=r.get(K);if(Y)return Y;let X=Z.get(K);if(!X)X=(async()=>{let W=await R.findSessionMetadata(J.sessionId,J.projectPath);if(!W)throw new f("Session",J.sessionId);let[H,D]=await Promise.all([R.loadSession(J.sessionId,J.projectPath),R.findSessionTaskWorktree(J.sessionId,J.projectPath)]),B=E0(W,H,D);return r.set(K,B),B})(),Z.set(K,X);try{return await X}finally{if(Z.get(K)===X)Z.delete(K)}},$O=async(J,K)=>{let Y=await KO(J,K);try{await R.assertSessionWritable(Y.sessionId,Y.projectPath)}catch(X){if(X instanceof U1)throw new k(X.message);throw X}return n(Y)},PO=async(J,K)=>{if(J.permissionMode===K)return;let Y=await R.setSessionPermissionMode(J.id,J.projectPath,K);J.permissionMode=Y.permissionMode,J.updatedAt=new Date(Y.lastMessageTime),S.publish(GO(J),"session.updated",{permissionMode:K})},s=(J,K,Y,X={})=>{if(!L.stats().accepting)throw new qO;let W=Y0(12),H={id:W,sessionId:J.id,projectPath:J.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:J.taskIsolation!==void 0&&X.runtimeLease!==void 0,createdAt:new Date};if(J.taskIsolation&&X.runtimeLease){let D=X.runtimeLease.value,B=mO.admit({key:`${J.projectPath}\x00${J.id}`,...D.getTaskAdmissionLimits(),pendingBytes:g$({content:K,outputSchema:X.outputSchema,pendingMessages:D.getPendingSteeringMessages()}),signal:H.abortController.signal,onUpdate:(M)=>{H.status=M.state,J.taskStatus=M.state,J.taskQueuePosition=M.queuePosition,J.taskQueueDepth=M.queueDepth,J.taskConcurrencyLimit=M.maxConcurrent,H.taskAdmissionUpdate=(H.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await D.setTaskAdmission(M)}).catch((T)=>{g.warn(`[SessionRoutes] Failed to persist admission for ${J.id}:`,T)})}});H.taskAdmission=B;let A=B.getSnapshot();H.status=A.state,J.taskStatus=A.state,J.taskQueuePosition=A.queuePosition,J.taskQueueDepth=A.queueDepth,J.taskConcurrencyLimit=A.maxConcurrent}return CO.set(W,H),J.currentRunId=W,H.completion=O2(H,J,K,Y,e,{pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:H.taskAdmission,runtimeLease:X.runtimeLease,disposeRuntime:YO}).catch((D)=>{g.error(`[SessionRoutes] Run ${W} failed:`,D)}),H},lO=async(J)=>{let K;if(J.outputSchema)try{K=F1(J.outputSchema).schema}catch(h){throw new _(h instanceof Error?h.message:"Invalid output schema")}let Y=W1("task",12),X=R0(J.sourceProjectPath),W=J.modelId?.trim(),H=QO();if(!H)throw new _("Config not initialized");let[D,B]=await Promise.all([o0(X,H),jO(X)]);if(W&&!D.config.models.some((h)=>h.id===W))throw new _(`Task model not found: ${W}`);let A=W||D.config.models.find((h)=>h.id===D.config.currentModelId)?.id||D.config.models[0]?.id;if(!A)throw new _("No model is configured. Add or select a model before dispatching a task.");let M=D.config.models.find((h)=>h.id===A);if(!M)throw new _(`Task model not found: ${A}`);let T=J.reasoningEffort??"off",y=J.serviceTier??"auto",WO=J.responseVerbosity??"auto",yO=J.communicationStyle??"auto",TO,XO=B.projectRules?.staticRules(X),OO=XO&&XO.files.length>0?XO.provenanceSha256:void 0;try{let h=D.catalog.resolveConfig(M);b$(h,T),A$(h,y),w$(h,WO);let l=C$(yO,B.communicationStyles);TO=l.source==="built-in"?void 0:l.contentSha256}catch(h){throw new _(h instanceof Error?h.message:"Invalid reasoning effort")}let O0={version:1,prompt:J.prompt,...J.title?{title:J.title}:{},...J.taskPriority?{taskPriority:J.taskPriority}:{},...J.taskKind?{taskKind:J.taskKind}:{},...J.taskDueAt?{taskDueAt:J.taskDueAt}:{},sourceProjectPath:X,isolation:J.isolation,permissionMode:J.permissionMode,modelId:A,reasoningEffort:T,serviceTier:y,responseVerbosity:WO,communicationStyle:yO,...TO?{communicationStyleDigest:TO}:{},...OO?{projectInstructionsDigest:OO}:{},...J.attachments?{attachments:J.attachments.map((h)=>({...h}))}:{},...K?{outputSchema:K}:{}},E,m,I;try{let h=await v$.createSessionTask({sessionId:Y,prompt:J.prompt,title:J.title,taskPriority:J.taskPriority,taskKind:J.taskKind,taskDueAt:J.taskDueAt,sourceProjectPath:X,isolation:J.isolation,dispatch:O0,retriedFrom:J.retriedFrom}),{metadata:l}=h;E=h.taskWorktree,m=E0(l,[],E);let p=GO(m);r.set(v(p),m),S.publish(p,"task.status",{taskStatus:l.taskStatus,updatedAt:l.lastMessageTime});let i=B$(J.prompt,J.attachments);I=await e(m);let fO=I.value,a=K?await fO.prepareInputTurn(i,{outputSchema:K}):await fO.prepareInputTurn(i);if(!a.accepted)throw new k(`Task prompt was not accepted: ${a.reason}`);let zO=s(m,i,J.permissionMode,{preparedInputTurn:a,runtimeLease:I,outputSchema:K});return I=void 0,await zO.taskAdmissionUpdate,{session:aO(m),runId:zO.id,messageId:a.messageId,status:zO.status==="queued"?"queued":"running",queuePosition:m.taskQueuePosition,queueDepth:m.taskQueueDepth,maxConcurrentTasks:m.taskConcurrencyLimit}}catch(h){if(I?.release(),I=void 0,(h instanceof L1||h instanceof J0)&&m){let l=GO(m),p=v(l);if(E)await EO.exit({sessionId:m.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await YO(m).catch(()=>{return}),await R.deleteSession(m.id,m.projectPath).catch(()=>{return}),r.delete(p),new kO(h instanceof J0?"Session runtime capacity is full":"Task admission capacity is full",{resource:h.resource,limit:h.limit})}if(m){let l=await R.findSessionMetadata(m.id,m.projectPath).catch(()=>{return});if(!l||l.taskStatus==="queued"){let p=t0(h),i=await R.updateSessionMetadata(m.id,m.projectPath,{taskStatus:"failed",taskStatusReason:p.message,taskFailure:p,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});m.taskStatus=i?.taskStatus??"failed",m.taskStatusReason=i?.taskStatusReason??p.message,m.taskFailure=i?.taskFailure??p,m.taskCompletedAt=i?.taskCompletedAt}else m.taskStatus=l.taskStatus,m.taskStatusReason=l.taskStatusReason,m.taskFailure=l.taskFailure,m.taskCompletedAt=l.taskCompletedAt}throw h}},wO=(J)=>F(()=>lO(J)),N=async(J,K)=>{let Y=await KO(J,K),X=await R.findSessionMetadata(Y.sessionId,Y.projectPath);if(!X)throw new f("Session",Y.sessionId);if(!["failed","interrupted","cancelled"].includes(X.taskStatus))throw new k(`Task cannot be retried while status is ${X.taskStatus}`);let W=await R.findSessionTaskDispatch(Y.sessionId,Y.projectPath);if(!W)throw new k("Task retry payload is unavailable");return wO({prompt:W.prompt,title:X.title??W.title,taskPriority:X.taskPriority??W.taskPriority,taskKind:X.taskKind??W.taskKind,taskDueAt:X.taskDueAt,sourceProjectPath:W.sourceProjectPath,isolation:W.isolation,permissionMode:W.permissionMode,modelId:W.modelId,reasoningEffort:W.reasoningEffort,serviceTier:W.serviceTier,responseVerbosity:W.responseVerbosity,communicationStyle:W.communicationStyle,attachments:W.attachments,outputSchema:W.outputSchema,retriedFrom:Y})},NO=(J,K)=>F(()=>N(J,K)),g1=(J,K,Y)=>F(async()=>{let X=await KO(J,Y);if(!await R.findSessionMetadata(X.sessionId,X.projectPath))throw new f("Session",X.sessionId);let H=await R.updateSessionMetadata(X.sessionId,X.projectPath,K),D=r.get(v(X));if(D)X0(D,H);return S.publish(X,"session.updated",{...H.title?{title:H.title}:{},...H.taskPriority?{taskPriority:H.taskPriority}:{},...H.taskKind?{taskKind:H.taskKind}:{},taskDueAt:H.taskDueAt??null}),D?aO(D):{...H,isActive:!1}}),Q1=async(J,K)=>{let Y=await $O(J,K);if(!Y.taskWorktree)throw new _("Session does not have a task worktree");try{await EO.restoreSession(Y.taskWorktree);let X=await EO.getDiffArtifact(Y.id);if(!X)throw new k("Task diff artifact is unavailable");return{sessionId:Y.id,projectPath:Y.projectPath,...X}}catch(X){if(X instanceof k)throw X;throw g.error("[SessionRoutes] Failed to load task diff artifact:",X),new k("Task diff artifact is unavailable")}},L0=async(J,K,Y)=>{let X=await KO(J,Y);return ZO(X,async()=>{let W=await $O(X.sessionId,X.projectPath);if(["queued","running"].includes(W.taskStatus))throw new k(`Task artifacts cannot be delivered while status is ${W.taskStatus}`);if(W.taskDelivery?.status==="applied")throw new k("Task changes have already been applied");if(W.taskDelivery?.status==="discarded")throw new k("Task changes have already been discarded");if(!W.taskWorktree)throw new k("Task worktree is unavailable");let H=async(D,B=!1)=>{let A=await R.updateSessionMetadata(W.id,W.projectPath,{taskDelivery:D,...B?{taskWorktree:null}:{}});if(X0(W,A),B)W.taskWorktree=void 0;return S.publish(X,"task.delivery",{taskDelivery:D,...B?{taskWorktreeRemoved:!0}:{},updatedAt:A.lastMessageTime}),aO(W)};try{if(K==="discard"){try{await EO.restoreSession(W.taskWorktree)}catch(A){return g.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${W.id}:`,A),H({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:W.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let B=await EO.exit({sessionId:W.id,action:"remove",discardChanges:!0});return H({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:B.discardedFiles??0,message:"Task worktree removed"},!0)}try{await EO.restoreSession(W.taskWorktree)}catch(B){throw g.warn(`[SessionRoutes] Task worktree is unavailable for ${W.id}:`,B),new H1("artifact_unavailable","Task worktree is unavailable")}let D=await EO.apply(W.id);return H({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:D.sourceCommit,changedFiles:D.changedFiles,message:"Task changes applied to the source workspace"})}catch(D){if(D instanceof H1)throw await H({status:"conflicted",updatedAt:new Date().toISOString(),message:D.message}),new k(D.message);throw D}})},u0=(J,K,Y)=>F(()=>L0(J,K,Y)),v0=async(J)=>{let K=DO(J.currentRunId);if(_O(K))return;if(J.taskIsolation&&J.taskStatus!=="queued"&&J.taskStatus!=="running")return;let Y=await S0.hasPendingInbox(J.projectPath,J.id),X=!Y&&await S0.hasActiveGoal(J.projectPath,J.id);if(!Y&&!X)return;let W=await e(J),H=!1;try{let D=W.value,B=DO(J.currentRunId);if(_O(B))return;if(Y&&D.getPendingSteeringCount()===0)await D.reloadPendingInbox();let A=D.getPendingSteeringCount()>0,M=A?null:await D.getGoal(),T=M?.status==="active"||M?.status==="verifying";if(!A&&!T||D.hasTurnOwner())return;s(J,"",J.permissionMode??"default",{pendingInputOnly:A,goalContinuationOnly:T,runtimeLease:W}),H=!0}finally{if(!H)W.release()}},SO=async(J)=>{let K;try{K=L.enter()}catch{return}try{await v0(J)}finally{K.release()}};G0=SO;let Z1=async()=>{let J={scheduled:0,failed:0,deferred:0};if(!L.stats().accepting)return J;let K=(await R.listSessions({taskStatus:"queued"})).filter((Y)=>Y.taskIsolation!==void 0).sort((Y,X)=>Y.firstMessageTime.localeCompare(X.firstMessageTime)||Y.projectPath.localeCompare(X.projectPath)||Y.sessionId.localeCompare(X.sessionId));for(let[Y,X]of K.entries()){let W={sessionId:X.sessionId,projectPath:X.projectPath};try{if(!await S0.hasPendingInbox(X.projectPath,X.sessionId)){let D=t0("Queued task input is missing");await R.updateSessionMetadata(X.sessionId,X.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),J.failed++;continue}let H=await n(W);if(await SO(H),H.currentRunId)J.scheduled++}catch(H){if(H instanceof L1||H instanceof J0){J.deferred+=K.length-Y;break}g.warn(`[SessionRoutes] Failed to recover queued task ${X.sessionId}:`,H),J.deferred++}}return J};return O.get("/",async(J)=>{try{let K=await R.listSessions(),Y=new Set(K.filter((M)=>M.relationType==="subagent").map((M)=>v({sessionId:M.sessionId,projectPath:M.projectPath}))),X=Array.from(r.values()).filter((M)=>!Y.has(v(GO(M)))&&M.relationType!=="subagent").map((M)=>aO(M)),W=new Set(X.map((M)=>v({sessionId:M.sessionId,projectPath:M.projectPath}))),H=K.filter((M)=>{if(M.relationType==="subagent")return!1;return!W.has(v({sessionId:M.sessionId,projectPath:M.projectPath}))}),D=new Set(W),B=H.filter((M)=>{let T=v({sessionId:M.sessionId,projectPath:M.projectPath});if(D.has(T))return!1;return D.add(T),!0}),A=[...X,...B];return J.json(A)}catch(K){throw g.error("[SessionRoutes] Failed to list sessions:",K),new t("Failed to list sessions")}}),O.get("/catalog",async(J)=>{try{let K=J.req.query("limit"),Y=K===void 0?void 0:Number(K),X=J.req.query("cursor"),W=J.req.query("projectPath"),H=J.req.query("archived");if(H!==void 0&&H!=="true"&&H!=="false")throw new _("archived must be true or false");let D=H==="true",B=await R.listSessionPage({...W?{cwd:R0(W)}:{},...X?{cursor:X}:{},...Y===void 0?{}:{limit:Y},includeSubagents:!1,archived:D}),A=new Map((D?[]:Array.from(r.values())).filter((M)=>M.relationType!=="subagent").map((M)=>[v(GO(M)),aO(M)]));return J.json({sessions:B.sessions.map((M)=>A.get(v({sessionId:M.sessionId,projectPath:M.projectPath}))??M),...B.nextCursor?{nextCursor:B.nextCursor}:{}})}catch(K){if(K instanceof _)throw K;if(K instanceof Error&&(K.message.startsWith("Invalid session cursor")||K.message.startsWith("Session cursor scope")||K.message.startsWith("Session catalog")))throw new _(K.message);throw g.error("[SessionRoutes] Failed to list session catalog:",K),new t("Failed to list session catalog")}}),O.post("/",async(J)=>{try{let K=await J.req.json(),Y=q(vx,K);if(!Y.success)throw new _("Invalid request body");let{title:X,projectPath:W}=Y.data,H=W1("web",12),D=R0(W||J.get("directory")||c(),W?"projectPath":"directory"),B=await R.createSessionMetadata(H,D,{title:X,taskStatus:"completed"}),A=E0(B,[]),M=GO(A);return r.set(v(M),A),S.publish(M,"session.created",{}),J.json({...aO(A),status:void 0,agentType:void 0,model:void 0})}catch(K){if(g.error("[SessionRoutes] Failed to create session:",K),K instanceof _)throw K;throw new t("Failed to create session")}}),O.get("/:sessionId/export",async(J)=>{let K=J.req.param("sessionId");try{let Y=J.req.query("includeReasoning");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new _("includeReasoning must be true or false");let X=await KO(K,J.req.query("projectPath")),W=await R.exportSessionMarkdown(X.sessionId,X.projectPath,{includeReasoning:Y==="true"});return J.body(W.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${W.filename}"`,"Content-Length":String(Buffer.byteLength(W.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":W.contentSha256,"X-Blade-Export-Activities":String(W.activityCount),"X-Blade-Export-Messages":String(W.messageCount),"X-Blade-Export-Redactions":String(W.redactionCount)})}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;if(Y instanceof Error&&Y.message==="No conversation content to export")throw new k(Y.message);throw g.error("[SessionRoutes] Failed to export session:",Y),new t("Failed to export session")}}),O.post("/:sessionId/fork",async(J)=>{let K=J.req.param("sessionId");try{B1(K);let Y=await J.req.json(),X=q(lx,Y);if(!X.success)throw new _("Invalid request body");let W=R0(X.data.projectPath),H=await R.findSessionMetadata(K,W);if(!H)throw new f("Session",K);let D=await R.forkSession(K,{sourceProjectPath:H.projectPath,targetProjectPath:H.projectPath}),B=E0(D.metadata,D.messages),A=GO(B);return r.set(v(A),B),S.publish(A,"task.status",{taskStatus:D.metadata.taskStatus,...D.metadata.taskCompletedAt?{taskCompletedAt:D.metadata.taskCompletedAt}:{},updatedAt:D.metadata.lastMessageTime}),J.json({session:D.metadata,messages:N1(D.messages)},201)}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof k)throw Y;if(Y instanceof I$)throw new k("Session has no durable creation record");throw g.error("[SessionRoutes] Failed to fork session:",Y),new t("Failed to fork session")}}),O.get("/:sessionId",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=r.get(v(Y));if(X)return J.json(aO(X));let W=await R.findSessionMetadata(Y.sessionId,Y.projectPath);if(!W)throw new f("Session",K);return J.json(W)}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;throw g.error("[SessionRoutes] Failed to get session:",Y),new t("Failed to get session")}}),O.patch("/:sessionId",async(J)=>{let K=J.req.param("sessionId");try{let Y=await J.req.json(),X=q(dx,Y);if(!X.success)throw new _("Invalid request body");if(X.data.title===void 0)throw new _("title is required");let W=await KO(K,X.data.projectPath),H=await R.updateSessionMetadata(W.sessionId,W.projectPath,{title:X.data.title}),D=r.get(v(W));if(D)D.title=H.title??D.title,D.updatedAt=new Date(H.lastMessageTime);if(H.title)S.publish(W,"session.updated",{title:H.title});return J.json({success:!0,title:H.title})}catch(Y){if(g.error("[SessionRoutes] Failed to update session:",Y),Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;throw new t("Failed to update session")}}),O.get("/:sessionId/rewind",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath"));return u(K,async(Y)=>J.json({checkpoints:await Y.listRewindCheckpoints()}))}),O.post("/:sessionId/rewind",async(J)=>{let K=q(p$,await J.req.json());if(!K.success)throw new _("Invalid rewind request");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=DO(Y.currentRunId);if(_O(W))throw new k("Cannot rewind while a run is active");return u(Y,async(H)=>{let D;try{D=await H.rewindSession(K.data)}catch(A){if(A instanceof Error&&A.message.startsWith("Cannot rewind while"))throw new k(A.message);throw A}Y.messages=[...D.messages],Y.updatedAt=new Date;let B=N1(D.messages);return S.publish(X,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:B}),J.json({...D,messages:B})})})}),O.get("/:sessionId/review",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath")),X=await oO.list(Y.projectPath,Y.sessionId);return J.json({reviews:X.map((W)=>({...W,content:W.completion?R$(W.start,W.completion):void 0}))})}),O.post("/:sessionId/review",async(J)=>{let K=J.req.param("sessionId"),Y=q(a$,await J.req.json());if(!Y.success)throw new _("Invalid code review request");let X=await $O(K,Y.data.projectPath),W=GO(X),H=v(W);return P(W,async()=>{if(_O(DO(X.currentRunId)))throw new k("Cannot start a review during an active turn");if(bO.has(H))throw new k("Session already has an active review");return u(X,async(D)=>{if(await oO.recoverInterrupted(W.projectPath,W.sessionId,D),Y.data.modelId&&!D.getModelById(Y.data.modelId))throw new _(`Model not found: ${Y.data.modelId}`);if(Y.data.modelId&&D.getCurrentModelId()!==Y.data.modelId)await D.refresh({modelId:Y.data.modelId});if(Y.data.modelId&&X.selectedModelId!==Y.data.modelId){let T=await R.updateSessionMetadata(X.id,X.projectPath,{selectedModelId:Y.data.modelId});X0(X,T)}let B=new AbortController,A;try{A=await oO.start({sessionId:W.sessionId,projectPath:W.projectPath,runtime:D,request:{kind:Y.data.kind,...Y.data.ref?{ref:Y.data.ref}:{},...Y.data.instructions?{instructions:Y.data.instructions}:{}},signal:B.signal,onEvent:(T)=>{if(T.kind==="tool_start")S.publish(W,"review.tool.started",{reviewId:A?.reviewId,toolCallId:T.toolCall.id,toolName:T.toolCall.function.name});else if(T.kind==="tool_progress")S.publish(W,"review.tool.progress",{reviewId:A?.reviewId,toolCallId:T.toolCall.id,message:T.update.message.slice(0,1000)});else if(T.kind==="tool_result")S.publish(W,"review.tool.completed",{reviewId:A?.reviewId,toolCallId:T.toolCall.id,success:T.result.success})}})}catch(T){if(T instanceof Error&&(T.message.includes("active review")||T.message.includes("interrupted review")||T.message.includes("active turn")))throw new k(T.message);if(T instanceof Error&&(T.message.includes("review")||T.message.includes("Git")||T.message.includes("changes")||T.message.includes("ref")))throw new _(T.message);throw T}if(!A)throw new t("Code review failed to start");await tO(X),S.publish(W,"review.started",{reviewId:A.reviewId,kind:Y.data.kind}),S.publish(W,"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 M=A.completion.then(async(T)=>{X.messages=await R.loadSession(W.sessionId,W.projectPath),await tO(X),S.publish(W,"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()}),S.publish(W,"review.completed",{reviewId:A.reviewId,status:T.status,findings:T.findings.length})}).catch((T)=>{g.error(`[SessionRoutes] Code review ${A.reviewId} failed:`,T)}).finally(()=>{if(bO.get(H)?.reviewId===A.reviewId)bO.delete(H)});return bO.set(H,{reviewId:A.reviewId,controller:B,completion:M}),J.json({reviewId:A.reviewId,status:"running"},202)})})}),O.get("/:sessionId/subagents",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath"));return u(K,(Y)=>J.json({subagents:Y.listSubagents().map(n0)}))}),O.post("/:sessionId/subagents/:agentId/resume",async(J)=>{B1(J.req.param("agentId"));let K=d$.safeParse(await J.req.json());if(!K.success)throw new _("Invalid subagent resume request");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=DO(Y.currentRunId);if(_O(W))throw new k("Cannot resume a subagent while a parent run is active");return u(Y,async(H)=>{let D=!1,B,A=(T)=>{S.publish(X,"subagent.complete",{subagentSessionId:T.id,success:T.status==="completed",status:T.status,summary:T.result?.message?.slice(0,500),type:T.subagentType,verificationVerdict:T.result?.verificationVerdict,resumedFrom:T.resumedFrom,rootAgentId:T.rootAgentId,resumeDepth:T.resumeDepth})},M;try{M=H.resumeSubagent({agentId:J.req.param("agentId"),prompt:K.data.prompt,onEvent:(T,y)=>{ex(X,y,T)},onCompleted:(T)=>{if(D)A(T);else B=T}})}catch(T){if(T instanceof Error&&(T.message.startsWith("Cannot resume")||T.message.startsWith("Subagent cannot")))throw new k(T.message);if(T instanceof Error&&T.message.startsWith("Subagent not found"))throw new f(T.message);throw T}if(S.publish(X,"subagent.start",{subagentSessionId:M.session.id,type:M.session.subagentType,description:M.session.description,resumedFrom:M.source.id,rootAgentId:M.session.rootAgentId,resumeDepth:M.session.resumeDepth}),D=!0,B)A(B);return J.json({source:n0(M.source),session:n0(M.session)})})})}),O.get("/:sessionId/goal",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath"));return J.json({goal:await new P$(K.projectPath,K.id).get()})}),O.put("/:sessionId/goal",async(J)=>{let K=q(ix,await J.req.json());if(!K.success)throw new _("Invalid goal request");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=DO(Y.currentRunId);if(_O(W))return J.json({status:"rejected",reason:"run_active"},409);let D=K.data.permissionMode??Y.permissionMode??"default";if(Y.permissionMode!==D)await PO(Y,D);let B=await e(Y),A=!1;try{let M=await B.value.createGoal(K.data);S.publish(X,"goal.updated",{goal:M});let T=s(Y,"",D,{goalContinuationOnly:!0,runtimeLease:B});return A=!0,await T.taskAdmissionUpdate,J.json({status:T.status==="queued"?"queued":"running",runId:T.id,goal:M,queuePosition:Y.taskQueuePosition,queueDepth:Y.taskQueueDepth,maxConcurrentTasks:Y.taskConcurrencyLimit},202)}finally{if(!A)B.release()}})}),O.patch("/:sessionId/goal",async(J)=>{let K=q(cx,await J.req.json());if(!K.success)throw new _("Invalid goal update");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=await e(Y),H=!1;try{let D=W.value,B;if(K.data.action==="pause")B=await D.pauseGoal();else if(K.data.action==="edit")B=await D.editGoal(K.data.objective);else B=await D.resumeGoal();if(S.publish(X,"goal.updated",{goal:B}),B.status==="active"&&!_O(DO(Y.currentRunId))){let A=s(Y,"","default",{goalContinuationOnly:!0,runtimeLease:W});return H=!0,await A.taskAdmissionUpdate,J.json({status:A.status==="queued"?"queued":"running",runId:A.id,goal:B,queuePosition:Y.taskQueuePosition,queueDepth:Y.taskQueueDepth,maxConcurrentTasks:Y.taskConcurrencyLimit},202)}return J.json({status:B.status,goal:B})}finally{if(!H)W.release()}})}),O.delete("/:sessionId/goal",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath")),Y=GO(K);return u(K,async(X)=>{let W=await X.clearGoal();if(W)S.publish(Y,"goal.cleared",{});return J.json({cleared:W})})}),O.post("/:sessionId/archive",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=await R.listSessionArchiveMembers(Y.sessionId,Y.projectPath);for(let H of X){let D=gO({sessionId:H.sessionId,projectPath:H.projectPath}),B=r.get(v(D));if(_O(DO(B?.currentRunId)))throw new k(`Stop session ${H.sessionId} before archiving this session tree`)}for(let H of X){let D=gO({sessionId:H.sessionId,projectPath:H.projectPath}),B=r.get(v(D));if(B)await YO(B)}let W=await R.archiveSession(Y.sessionId,Y.projectPath);for(let H of X){let D=gO({sessionId:H.sessionId,projectPath:H.projectPath}),B=v(D);r.delete(B),Z.delete(B),x.delete(B),S.publish(D,"session.archived",{archiveRootId:Y.sessionId,archivedAt:W.archivedAt})}if($.size===0)await UO.getInstance().disconnectAll();return J.json({session:W,archivedSessionIds:X.map((H)=>H.sessionId)})}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO||Y instanceof k)throw Y;if(Y instanceof _1)throw new k(Y.message);throw g.error("[SessionRoutes] Failed to archive session:",Y),new t("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=await R.listSessionArchiveMembers(Y.sessionId,Y.projectPath),W=await R.unarchiveSession(Y.sessionId,Y.projectPath),H=X.filter((D)=>D.sessionId===Y.sessionId||D.archivedBySessionId===Y.sessionId).map((D)=>D.sessionId);for(let D of H)S.publish({sessionId:D,projectPath:Y.projectPath},"session.unarchived",{archiveRootId:Y.sessionId});return J.json({session:W,restoredSessionIds:H})}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;if(Y instanceof _1)throw new k(Y.message);throw g.error("[SessionRoutes] Failed to unarchive session:",Y),new t("Failed to unarchive session")}}),O.delete("/:sessionId",async(J)=>{let K=J.req.param("sessionId"),Y=J.req.query("projectPath");try{let X=await KO(K,Y),W=v(X),H=r.get(W),D=$.get(W),B=H?.taskWorktree??await R.findSessionTaskWorktree(X.sessionId,X.projectPath),A;if(H?.currentRunId){let y=DO(H.currentRunId);if(y)k0(y),await y.completion,A=y.id}let M=bO.get(W);if(M)M.controller.abort("session-delete"),await M.completion;if(D)await D.clearGoal().catch((y)=>{g.warn("[SessionRoutes] Failed to clear session goal:",y)});if(await R.deleteSession(X.sessionId,X.projectPath),S.publish(X,"session.deleted",{}),A)ox(A);r.delete(W),Z.delete(W),x.delete(W);let T=$.get(W);if(T){if(!await j.remove(W,T))throw new k("Session Runtime is still active and cannot be deleted")}if(B)try{await EO.restoreSession(B),await EO.exit({sessionId:X.sessionId,action:"remove",discardChanges:!0})}catch(y){g.warn(`[SessionRoutes] Failed to remove deleted task worktree ${X.sessionId}:`,y)}return J.json({success:!0})}catch(X){if(g.error("[SessionRoutes] Failed to delete session:",X),X instanceof _||X instanceof f||X instanceof LO)throw X;throw new t("Failed to delete session")}}),O.get("/:sessionId/message",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=r.get(v(Y)),W=X?.messages?X.messages:await R.loadSession(Y.sessionId,Y.projectPath);return J.json(N1(W))}catch(Y){if(g.error("[SessionRoutes] Failed to get messages:",Y),Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;throw new t("Failed to get messages")}}),O.get("/:sessionId/events",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath"));try{await R.assertSessionWritable(Y.sessionId,Y.projectPath)}catch(B){if(B instanceof U1)throw new k(B.message);throw B}let X=await n(Y),W=J.req.header("Last-Event-ID")??J.req.query("lastEventId"),H=W?Number.parseInt(W,10):Number.NaN,D=Number.isInteger(H)?H+1:void 0;return gx(J,async(B)=>{let M,T,y=!1,WO,yO,TO=new Promise((E)=>{yO=E}),XO=()=>{if(T!==void 0)clearInterval(T),T=void 0;M?.(),M=void 0},OO=(E)=>{if(y)return;y=!0,XO(),WO?.close(E),yO()},O0=new Set;B.onAbort(OO),WO=new A0({write:async(E)=>{await B.writeSSE(E)},onFailure:(E)=>{g.warn(`[SessionRoutes] SSE egress closed for ${Y.sessionId}: kind=${E.kind} pendingItems=${E.pendingItems??0} pendingBytes=${E.pendingBytes??0}`),OO(E)}}),M=S.subscribe((E)=>{if(E.sessionId!==Y.sessionId||E.projectPath!==Y.projectPath)return;let m=E.properties.requestId;if((E.type==="permission.asked"||E.type==="question.required"||E.type==="elicitation.required")&&typeof m==="string"){if(O0.has(m))return;O0.add(m)}if(E.type==="subagent.completion.queued")P(Y,()=>SO(X)).catch((I)=>{g.error(`[SessionRoutes] Failed to wake background completion for ${X.id}:`,I)});if(E.type==="team.message.received"&&typeof E.properties.teamName==="string"&&typeof E.properties.messageId==="string"&&typeof E.properties.content==="string"&&m$(E.properties.metadata,{messageId:E.properties.messageId,teamName:E.properties.teamName})){let I=E.properties.teamName,h=E.properties.messageId,l=E.properties.content,p=E.properties.metadata;P(Y,async()=>{let i=await e(X),fO=!1;try{let a=await i.value.enqueueSteering(l,{allowBeforeTurn:!0,messageId:h,origin:"team_message",metadata:p});if(!a.accepted)return;await new f$(I,s0()).markDelivered([h]),fO=a.delivery==="next_turn"}finally{i.release()}if(fO)await SO(X)}).catch((i)=>{g.error(`[SessionRoutes] Failed to deliver teammate message for ${X.id}:`,i)})}WO?.observe(nx(E),E.seq)});try{if(B.aborted||y)return;let E=DO(X.currentRunId),m=_O(E)?await e(X):void 0;try{let l=m?.value,p=l?.getPendingSteeringCount()??0;await WO.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:Y.sessionId,projectPath:Y.projectPath,timestamp:Date.now(),status:_O(E)?E.status:"idle",runId:_O(E)?E.id:void 0,queued:p,pendingInputDelivery:p>0?l?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:l?.getRecoveredSteeringCount()??0}})})}finally{m?.release()}if(B.aborted||y)return;if(D!==void 0){if(await y$.for(Y.sessionId,Y.projectPath).replay({onCommitted:async(p)=>{if(B.aborted||y)return;let i=rx(p);if(i.seq===void 0)return;await WO.writeReplay({...typeof p.seq==="number"?{id:String(p.seq)}:{},data:JSON.stringify({type:i.type,...i.seq!==void 0?{seq:i.seq}:{},properties:{...i.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})},i.seq)}},D),B.aborted||y)return}if(WO.finishInitialization({replayed:D!==void 0}),B.aborted||y)return;if(!E&&!bO.has(v(Y))){let p=(await oO.list(Y.projectPath,Y.sessionId)).some((i)=>i.completion===void 0)?await u(X,(i)=>oO.recoverInterrupted(Y.projectPath,Y.sessionId,i)):void 0;if(p)X.messages=await R.loadSession(Y.sessionId,Y.projectPath),await tO(X),S.publish(Y,"review.completed",{reviewId:p.reviewId,status:p.status,findings:0,recovered:!0})}if(B.aborted||y)return;if(!E)await nO.recoverResponded(Y.projectPath,Y.sessionId);if(B.aborted||y)return;let I=E?void 0:await nO.findPending(Y.projectPath,Y.sessionId),h=E?.pendingPermission??(I?{permissionId:I.request.requestId,details:nO.confirmationDetails(I),resolve:()=>{return}}:void 0);if(h){O0.add(h.permissionId);let l=n$(h,!0);WO.observe({data:JSON.stringify({type:l.type,properties:{...l.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})})}if(B.aborted||y)return;if(SO(X).catch((l)=>{g.error(`[SessionRoutes] Failed to resume pending input for ${K}:`,l)}),B.aborted||y)return;T=setInterval(()=>{if(B.aborted||y)return;WO?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await TO}finally{OO()}})}),O.post("/:sessionId/message",async(J)=>{let K=J.req.param("sessionId"),Y=await J.req.json(),X=q(px,Y);if(!X.success)throw new _("Invalid message format");let{content:W,attachments:H,modelId:D,reasoningEffort:B,serviceTier:A,responseVerbosity:M,communicationStyle:T,permissionMode:y,projectPath:WO,outputSchema:yO}=X.data,TO;if(yO)try{TO=F1(yO).schema}catch(p){throw new _(p instanceof Error?p.message:"Invalid output schema")}let XO=T,OO=D?.trim();if((H??[]).reduce((p,i)=>p+(typeof i.content==="string"?Buffer.byteLength(i.content):0),0)>r0)throw new _("Message attachments exceed the 5 MiB limit");let E=y,m=B$(W,H),I=await $O(K,WO??J.req.query("projectPath")),h=E??I.permissionMode??"default",l=GO(I);return P(l,async()=>{let p=DO(I.currentRunId);if(_O(p)){if(TO)throw new k("Wait for the active turn to finish before setting an output schema");return u(I,async(a)=>{if(OO&&!a.getModelById(OO))throw new _(`Model not found: ${OO}`);if(OO&&a.getCurrentModelId()!==OO)throw new k("Wait for the active turn to finish before switching models");if(B&&a.getReasoningConfiguration().selection!==B)throw new k("Wait for the active turn to finish before switching reasoning effort");if(A&&a.getServiceTierConfiguration().selection!==A)throw new k("Wait for the active turn to finish before switching service tier");if(M&&a.getResponseVerbosityConfiguration().selection!==M)throw new k("Wait for the active turn to finish before switching response verbosity");if(XO&&a.getCommunicationStyleConfiguration().selection!==XO)throw new k("Wait for the active turn to finish before switching communication style");if(E&&I.permissionMode!==E)throw new k("Wait for the active turn to finish before switching permission mode");let zO=await a.enqueueSteering(m,{allowBeforeTurn:!0});if(!zO.accepted)return J.json({status:"rejected",reason:zO.reason??"turn_unavailable"},409);let iO=zO.messageId??Y0(12),B0=zO.queued;S.publish(l,"message.created",{messageId:iO,role:"user",content:w1(m)});let p0=zO.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(S.publish(l,p0,{runId:p.id,messageId:iO,queued:B0}),zO.delivery==="next_turn"&&p.status!=="running"&&p.status!=="waiting_permission")SO(I).catch((d0)=>{g.error(`[SessionRoutes] Failed to wake queued follow-up for ${K}:`,d0)});if(zO.delivery==="next_turn")p.pendingFollowUpRequested=!0;return J.json({runId:p.id,messageId:iO,status:zO.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:B0},202)})}if(I.permissionMode!==h)await PO(I,h);let i=await e(I,{permissionMode:h,...XO&&!XO.includes(":")?{communicationStyle:XO}:{}}),fO=!1;try{let a=i.value;if(OO&&!a.getModelById(OO))throw new _(`Model not found: ${OO}`);if(B)try{a.resolveReasoningConfiguration(B,OO)}catch(VO){throw new _(VO instanceof Error?VO.message:"Invalid reasoning effort")}if(A)try{a.resolveServiceTierConfiguration(A,OO)}catch(VO){throw new _(VO instanceof Error?VO.message:"Invalid service tier")}if(M)try{a.resolveResponseVerbosityConfiguration(M,OO)}catch(VO){throw new _(VO instanceof Error?VO.message:"Invalid response verbosity")}let zO=XO?a.resolveCommunicationStyleConfiguration(XO):void 0;if(zO?.source!==void 0&&zO.source!=="built-in"&&!zO.contentSha256)throw new _("Custom communication style has no provenance");let iO=a.getCurrentModelId(),B0=a.getReasoningConfiguration(),p0=a.getServiceTierConfiguration(),d0=a.getResponseVerbosityConfiguration(),v1=a.getCommunicationStyleConfiguration(),p1=Boolean(OO)&&iO!==OO,d1=Boolean(B)&&B0.selection!==B,l1=Boolean(A)&&p0.selection!==A,i1=Boolean(M)&&d0.selection!==M,c1=Boolean(XO)&&v1.selection!==XO;if(p1||d1||l1||i1||c1)await a.refresh({...OO?{modelId:OO}:{},...B?{reasoningEffort:B}:{},...A?{serviceTier:A}:{},...M?{responseVerbosity:M}:{},...XO?{communicationStyle:XO}:{}});let J1={...OO&&I.selectedModelId!==OO?{selectedModelId:OO}:{},...B&&I.reasoningEffort!==B?{reasoningEffort:B}:{},...A&&I.serviceTier!==A?{serviceTier:A}:{},...M&&I.responseVerbosity!==M?{responseVerbosity:M}:{},...zO&&(I.communicationStyle!==XO||I.communicationStyleDigest!==zO.contentSha256)?{communicationStyle:XO,communicationStyleDigest:zO.source==="built-in"?null:zO.contentSha256}:{}};if(Object.keys(J1).length>0)try{let VO=await R.updateSessionMetadata(I.id,I.projectPath,J1);I.permissionMode=VO.permissionMode,I.selectedModelId=VO.selectedModelId,I.reasoningEffort=VO.reasoningEffort,I.serviceTier=VO.serviceTier,I.responseVerbosity=VO.responseVerbosity,I.communicationStyle=VO.communicationStyle,I.communicationStyleDigest=VO.communicationStyleDigest,I.updatedAt=new Date(VO.lastMessageTime),S.publish(l,"session.updated",J1)}catch(VO){if(p1||d1||l1||i1||c1)await a.refresh({...iO?{modelId:iO}:{},reasoningEffort:B0.selection,serviceTier:p0.selection,responseVerbosity:d0.selection,communicationStyle:v1.selection}).catch((Xx)=>g.error("[SessionRoutes] Failed to roll back non-durable model settings:",Xx));throw VO}let w0=TO?await a.prepareInputTurn(m,{outputSchema:TO}):await a.prepareInputTurn(m);if(!w0.accepted)return J.json({status:"rejected",reason:w0.reason},w0.reason==="queue_full"?429:409);let Y1=s(I,m,h,{preparedInputTurn:w0,outputSchema:TO,runtimeLease:i});return fO=!0,await Y1.taskAdmissionUpdate,J.json({runId:Y1.id,messageId:w0.messageId,status:Y1.status==="queued"?"queued":"running",queuePosition:I.taskQueuePosition,queueDepth:I.taskQueueDepth,maxConcurrentTasks:I.taskConcurrencyLimit},202)}finally{if(!fO)i.release()}})}),O.post("/:sessionId/side-question",async(J)=>{let K=J.req.param("sessionId"),Y=q(c$,await J.req.json());if(!Y.success)throw new _("Invalid side conversation request");let X=await $O(K,Y.data.projectPath??J.req.query("projectPath"));return u(X,async(W)=>{let H=await W.askSideQuestion(Y.data.question,{signal:J.req.raw.signal});return J.json({...H,...W.getCurrentModelId()?{modelId:W.getCurrentModelId()}:{}})})}),O.post("/:sessionId/shell",async(J)=>{let K=J.req.param("sessionId"),Y=q(i$,await J.req.json());if(!Y.success)throw new _("Invalid user shell command");let X=await $O(K,Y.data.projectPath??J.req.query("projectPath")),W=GO(X),H=v(W);return P(W,async()=>{if(IO.has(H))throw new k("A user shell command is already running in this Session");let D=await e(X),B=D.value,A=new AbortController,M,T=new Promise((y)=>{M=y});IO.set(H,{controller:A,completion:T});try{let y=await B.executeUserShellCommand(Y.data.command,{signal:A.signal});X.messages=await R.loadSession(X.id,X.projectPath),X.updatedAt=new Date;let WO=DO(X.currentRunId);if(y.delivery==="next_turn"&&_O(WO))WO.pendingFollowUpRequested=!0;return J.json({executionId:y.executionId,messageId:y.messageId,record:y.record,auxiliary:y.auxiliary,...y.delivery?{delivery:y.delivery}:{},...y.queued!==void 0?{queued:y.queued}:{}})}finally{IO.delete(H),M(),D.release()}})}),O.post("/:sessionId/abort",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath")),X=r.get(v(Y));if(X?.currentRunId){let D=DO(X.currentRunId);if(D)k0(D),await D.completion}let W=IO.get(v(Y));if(W)W.controller.abort("user-cancel"),await W.completion;let H=bO.get(v(Y));if(H)H.controller.abort("user-cancel"),await H.completion;return J.json({success:!0})}),O.get("/:sessionId/status",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath")),X=r.get(v(Y)),W=bO.get(v(Y));if(W)return J.json({sessionId:K,projectPath:Y.projectPath,reviewId:W.reviewId,status:"reviewing"});if(!X?.currentRunId)return J.json({sessionId:K,projectPath:Y.projectPath,status:"idle"});let H=DO(X.currentRunId);return J.json({sessionId:K,projectPath:Y.projectPath,runId:X.currentRunId,status:H?.status||"idle"})}),{app:O,dispatchTask:wO,retryTask:NO,updateTask:g1,getTaskDiff:Q1,deliverTask:u0,recoverQueuedTasks:Z1,getRuntimeResidencyStats:()=>j.getStats(),getCoordinationStats:()=>({messageSubmissions:G.getStats(),taskDeliveries:z.getStats()}),shutdown:(J="server-shutdown")=>{if(w)return w;return L.close(J),clearInterval(b),w=(async()=>{let K,Y=async(B)=>{let A=await Promise.allSettled(B);for(let M of A)if(M.status==="rejected")K??=M.reason},X=new Set,W=()=>{for(let B of CO.values()){if(B.completion)X.add(B.completion);if(_O(B))k0(B,J)}for(let B of IO.values())B.controller.abort(J),X.add(B.completion);for(let B of bO.values())B.controller.abort(J),X.add(B.completion)},H=L.waitForIdle(),D=!1;H.then(()=>{D=!0});while(!D)W(),await Promise.race([H,new Promise((B)=>setImmediate(B))]);if(await H,W(),await Y([...X]),await Y([...x.values()]),W(),await Y([...X]),await Y([j.disposeAll()]),$.clear(),await Y([...Q.values()]),await Y([UO.getInstance().disconnectAll()]),x.clear(),Q.clear(),Z.clear(),r.clear(),G0===SO)G0=void 0;if(K!==void 0)throw K})(),w}}};async function O2(O,$,x,Q,Z,G={}){let{abortController:z,sessionId:U,id:j}=O,L=G.preparedInputTurn?.messageId??Y0(12),w=G.pendingInputOnly===!0||G.preparedInputTurn?.mode==="pending"||G.goalContinuationOnly===!0?void 0:Y0(12),F=G.runtimeLease,P,ZO,d=GO($),C=(u,YO)=>{S.publish(d,u,YO)},e=async()=>{let u=String(z.signal.reason||"Task run cancelled");if($.taskIsolation){if(!F)F=await Z($).catch(()=>{return});let YO=P??F?.value;if(u==="user-cancel")await YO?.discardPendingInput().catch(($O)=>{g.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,$O)});let n=await YO?.setTaskStatus("cancelled",u).catch(()=>{return});if(n)X0($,n);else await tO($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=u,$.taskCompletedAt??=new Date().toISOString()};try{if(G.taskAdmission){if(await G.taskAdmission.ready,await O.taskAdmissionUpdate,z.signal.aborted)throw Error(String(z.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!G.pendingInputOnly&&!G.goalContinuationOnly)C("message.created",{messageId:L,role:"user",content:w1(x)});if(C("session.status",{status:"running"}),w)C("message.created",{messageId:w,role:"assistant",content:""});F??=await Z($),P=F.value;let u=P,YO=Boolean(G.outputSchema??u.getPendingSteeringMessages().find((N)=>N.outputSchema)?.outputSchema);ZO=await u$.createWithRuntime(u,{sessionId:U,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let n=async(N)=>{let NO=N.interactionRequestId??Y0(12),g1=300000;O.status="waiting_permission";let Q1=new Promise((SO)=>{let Z1=setTimeout(()=>{g.warn(`[SessionRoutes] Permission ${NO} timed out after 300000ms`),C("permission.timeout",{requestId:NO}),SO({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:NO,resolve:(u1)=>{clearTimeout(Z1),SO(u1)},details:N}}),L0=O.pendingPermission;if(!L0)throw Error("Permission request was not registered");let u0=n$(L0);C(u0.type,u0.properties),g.info(`[SessionRoutes] Permission request created: ${NO}, runId: ${j}`);let v0=await Q1;if(g.info(`[SessionRoutes] Permission response received: ${NO}, approved: ${v0.approved}`),!z.signal.aborted)O.status="running";if(O.pendingPermission===L0)O.pendingPermission=void 0;return C("interaction.resolved",{requestId:NO}),v0},PO={messages:await R.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:U,workspaceRoot:$.projectPath,signal:z.signal,permissionMode:Q,onPermissionModeChange:async(N)=>{$.permissionMode=N,$.updatedAt=new Date,C("session.updated",{permissionMode:N})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:n}},s=()=>{if(!w)w=Y0(12),C("message.created",{messageId:w,role:"assistant",content:""});return w},lO=async(N)=>{switch(N.kind){case"content_delta":if(YO)break;C("message.delta",{messageId:s(),delta:N.delta});break;case"structured_output":C("structured.output",{messageId:s(),output:N.output,schemaDigest:N.schemaDigest});break;case"thinking_delta":C("thinking.delta",{messageId:s(),delta:N.delta});break;case"tool_start":if("function"in N.toolCall){if(N.toolCall.function.name===z0)break;C("tool.start",{messageId:s(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,arguments:N.toolCall.function.arguments,toolKind:N.toolKind})}break;case"tool_result":if("function"in N.toolCall){if(N.toolCall.function.name===z0)break;C("tool.result",{messageId:s(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,success:N.result.success,summary:N.result.metadata?.summary,output:f0(P0(y0(N.toolCall.function.name,N.result),I0)),metadata:q0(N.toolCall.function.name,N.result.metadata)})}break;case"tool_progress":if("function"in N.toolCall){if(N.toolCall.function.name===z0)break;C("tool.progress",{messageId:s(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,...N.update})}break;case"token_usage":C("token.usage",{...N.usage});break;case"turn_start":C("turn.started",{turn:N.turn,maxTurns:N.maxTurns});break;case"provider_admission":C("provider.admission",{phase:N.phase,requestClass:N.requestClass,resource:N.resource,scope:N.scope,reason:N.reason,queuePosition:N.queuePosition,queueDepth:N.queueDepth,inFlight:N.inFlight,limit:N.limit,waitMs:N.waitMs,maxWaitMs:N.maxWaitMs,recoveryRemainingMs:N.recoveryRemainingMs});break;case"provider_circuit":C("provider.circuit",{phase:N.phase,reason:N.reason,statusCode:N.statusCode,retryAfterMs:N.retryAfterMs,nextProbeAt:N.nextProbeAt,openDurationMs:N.openDurationMs,sampleCount:N.sampleCount,failureCount:N.failureCount,recoveryRemainingMs:N.recoveryRemainingMs});break;case"provider_retry":C("provider.retry",{phase:N.phase,attempt:N.attempt,maxRetries:N.maxRetries,reason:N.reason,statusCode:N.statusCode,delayMs:N.delayMs,nextRetryAt:N.nextRetryAt,mode:N.mode,recoveryBudgetMs:N.recoveryBudgetMs,recoveryElapsedMs:N.recoveryElapsedMs,recoveryRemainingMs:N.recoveryRemainingMs,exhaustedBy:N.exhaustedBy});break;case"provider_stall":C("provider.stall",{phase:N.phase,stallCount:N.stallCount,durationMs:N.durationMs,warningAfterMs:N.warningAfterMs,timeoutMs:N.timeoutMs,outputStarted:N.outputStarted});break;case"action_stationarity":C("action.stationarity",{phase:N.phase,toolName:N.toolName,runLength:N.runLength,nudgeThreshold:N.nudgeThreshold,haltThreshold:N.haltThreshold,progressAware:N.progressAware});break;case"mcp_catalog_changed":C("mcp.catalog.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,added:N.added,removed:N.removed,updated:N.updated});break;case"mcp_content_changed":C("mcp.content.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,contentKind:N.contentKind,added:N.added,removed:N.removed,updated:N.updated});break;case"mcp_resource_updated":C("mcp.resource.updated",{messageId:s(),revision:N.revision,serverName:N.serverName,uri:N.uri});break;case"mcp_connection_changed":C("mcp.connection.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,phase:N.phase,reason:N.reason,attempt:N.attempt,maxAttempts:N.maxAttempts,nextRetryAt:N.nextRetryAt,error:N.error});break;case"mcp_log":C("mcp.log",{messageId:s(),revision:N.revision,serverName:N.serverName,level:N.level,logger:N.logger,message:N.message,projectedBytes:N.projectedBytes,dataSha256:N.dataSha256,truncated:N.truncated,detailsOmitted:N.detailsOmitted,timestamp:N.timestamp,synthetic:N.synthetic});break;case"mcp_instructions_changed":C("mcp.instructions.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,action:N.action,reason:N.reason,text:N.text,sourceBytes:N.sourceBytes,projectedBytes:N.projectedBytes,sha256:N.sha256,truncated:N.truncated,detailsOmitted:N.detailsOmitted});break;case"mcp_task_changed":C("mcp.task.changed",{messageId:s(),revision:N.revision,taskId:N.taskId,serverName:N.serverName,toolName:N.toolName,status:N.status,statusMessage:N.statusMessage,createdAt:N.createdAt,updatedAt:N.updatedAt,completedAt:N.completedAt,hasResult:N.hasResult,error:N.error});break;case"project_rules_loaded":C("project.rules.loaded",{messageId:s(),files:N.files,triggerPaths:N.triggerPaths,blockedWrite:N.blockedWrite});break;case"steering_applied":C("steering.applied",{runId:j,messageIds:N.messageIds,count:N.count,recovered:N.recovered,delivery:N.delivery,queued:u.getPendingSteeringCount()});break;case"follow_up_started":{if(w)C("message.complete",{messageId:w}),w=void 0;for(let NO of N.messages){if(!NO.recovered||NO.persisted)continue;C("message.created",{messageId:NO.id,role:"user",content:w1(NO.content),recovered:!0})}C("follow_up.started",{runId:j,queued:N.queued,recovered:N.recovered}),s();break}case"goal_updated":C("goal.updated",{goal:N.goal});break;case"goal_continuation_started":C("goal.continuation.started",{goal:N.goal,continuation:N.continuation,...N.prematureStopPattern?{prematureStopPattern:N.prematureStopPattern}:{},...N.prematureStopCount!==void 0?{prematureStopCount:N.prematureStopCount}:{}}),s();break;case"compaction":C(N.phase==="start"?"compaction.started":"compaction.completed",{...N.reason?{reason:N.reason}:{},...N.strategy?{strategy:N.strategy}:{},...N.outcome?{outcome:N.outcome}:{},...N.preTokens!==void 0?{preTokens:N.preTokens}:{},...N.postTokens!==void 0?{postTokens:N.postTokens}:{},...N.sampleAttempts!==void 0?{sampleAttempts:N.sampleAttempts}:{},...N.failureReason?{failureReason:N.failureReason}:{}});break;case"model_fallback":C("model.fallback",{});break;case"task_update":C("task.updated",{tasks:N.tasks});break;default:break}},wO=await D1(ZO.chatStream(x,PO,{stream:!0,pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly,outputSchema:G.outputSchema,taskAdmission:G.taskAdmission}),lO);if(!wO.success)throw Error(wO.error?.message??"Agent run failed");for(let N=0;N<20;N++){let NO=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,u.getPendingSteeringCount()===0){if(!NO)break;continue}if(z.signal.aborted)break;if(wO=await D1(ZO.chatStream("",PO,{stream:!0,pendingInputOnly:!0,taskAdmission:G.taskAdmission}),lO),!wO.success)throw Error(wO.error?.message??"Agent follow-up failed")}if($.messages=await R.loadSession($.id,$.projectPath),$.updatedAt=new Date,await tO($),z.signal.aborted||O.status==="cancelled"){await e(),C("session.status",{status:"idle"});return}if(w)C("message.complete",{messageId:w});C("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),C("session.completed",{runId:j,outputTruncated:wO.metadata?.outputTruncated??!1}),C("session.status",{status:"idle"})}catch(u){if(P&&G.preparedInputTurn)await P.finishTurn(G.preparedInputTurn.handle).catch(()=>{return});if(z.signal.aborted||O.status==="cancelled"){k0(O,"runtime-abort"),await e(),C("session.status",{status:"idle"});return}await tO($).catch(()=>{return}),g.error("[SessionRoutes] Agent execution error:",u),O.status="failed",$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let YO=t0(u);if(!$.taskFailure){let n=P?await P.setTaskStatus("failed",u).catch(()=>{return}):await R.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:YO.message,taskFailure:YO,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(n)X0($,n)}$.taskStatusReason??=YO.message,$.taskFailure??=YO,C("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),C("session.status",{status:"error"})}finally{if(G.taskAdmission?.release(),G.taskAdmission){let u=mO.getStats();C("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:u.queued,taskConcurrencyLimit:u.maxConcurrent,taskInFlight:u.inFlight,taskAdmissionPaused:u.paused,updatedAt:new Date().toISOString()})}if(await ZO?.destroy().catch(()=>{return}),F?.release(),O.disposeRuntimeOnSettle&&G.disposeRuntime)await G.disposeRuntime($,P).catch((u)=>{g.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,u)});ax(O)}}async function s$(O,$,x){g.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),g.info(`[SessionRoutes] Active runs: ${CO.size}`);for(let[G,z]of CO.entries())if(g.info(`[SessionRoutes] Checking run ${G}: sessionId=${z.sessionId}, projectPath=${z.projectPath}, pendingPermission=${z.pendingPermission?.permissionId}`),z.sessionId===O.sessionId&&z.projectPath===O.projectPath&&z.pendingPermission?.permissionId===$){if(z.pendingPermission.details.interactionRequestId)await nO.respond(O.projectPath,O.sessionId,$,x);return z.pendingPermission.resolve(x),g.info(`[SessionRoutes] Permission ${$} responded, runId: ${z.id}`),!0}let Q=await nO.findPending(O.projectPath,O.sessionId);if(!Q||Q.request.requestId!==$)return g.error(`[SessionRoutes] Permission not found: ${$}`),!1;await nO.respondAndRecover(O.projectPath,O.sessionId,$,x);let Z=r.get(v(O));if(!Z){let G=await R.findSessionMetadata(O.sessionId,O.projectPath);if(!G)return!1;let[z,U]=await Promise.all([R.loadSession(O.sessionId,O.projectPath),R.findSessionTaskWorktree(O.sessionId,O.projectPath)]);Z=E0(G,z,U),r.set(v(O),Z)}else await tO(Z);if(S.publish(O,"interaction.resolved",{requestId:$}),G0)G0(Z).catch((G)=>{g.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,G)});return!0}var M1=o("Service"),x2=V.Object({approved:V.Boolean(),remember:V.Optional(V.Boolean()),scope:V.Optional(JO(["once","session","project"])),targetMode:V.Optional(JO(["default","autoEdit","plan","yolo"])),feedback:V.Optional(V.String({maxLength:4000})),answers:V.Optional(V.Record(V.String({maxLength:80}),V.Union([V.String({maxLength:4000}),V.Array(V.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:V.Optional(V.Object({action:JO(["accept","decline","cancel"]),content:V.Optional(V.Record(V.String(),V.Union([V.String({maxLength:4000}),V.Number(),V.Boolean(),V.Array(V.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),r$=()=>{let O=new $2;return O.post("/:permissionId",async($)=>{let x=$.req.param("permissionId"),Q=$.req.query("sessionId"),Z=$.req.query("projectPath");M1.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${Q}`);try{let G=await $.req.json(),z=q(x2,G);if(!z.success)throw new _("Invalid permission response format");let{approved:U,remember:j,scope:L,targetMode:b,feedback:w,answers:F,elicitation:P}=z.data;if(!Q)throw new _("sessionId query parameter is required");let ZO=await KO(Q,Z);if(!await s$(ZO,x,{approved:U,reason:w,scope:L,targetMode:b,feedback:w,answers:F,elicitation:P}))throw new f("Permission request",x);return M1.info(`[PermissionRoutes] Permission ${x} ${U?"approved":"denied"}`),$.json({success:!0,approved:U,remember:j})}catch(G){if(M1.error("[PermissionRoutes] Failed to respond to permission:",G),G instanceof _||G instanceof LO||G instanceof f||G instanceof xO)throw G;throw G}}),O};import e$ from"node:path";import{Hono as Q2}from"hono";var Z2=V.Object({projectPath:V.String({minLength:1}),enabled:V.Boolean(),scope:V.Optional(JO(["local","project","global"]))}),J2=V.Object({projectPath:V.String({minLength:1})}),Y2=V.Object({projectPath:V.String({minLength:1}),source:V.String({minLength:1}),trust:V.Literal(!0),ref:V.Optional(V.String({minLength:1}))}),z2=V.Object({projectPath:V.String({minLength:1}),trust:V.Literal(!0)}),G2=V.Object({projectPath:V.String({minLength:1}),confirm:V.Literal(!0)}),X2=V.Object({projectPath:V.String({minLength:1}),source:V.String({minLength:1}),ref:V.Optional(V.String({minLength:1}))}),O4=V.Object({projectPath:V.String({minLength:1}),confirm:V.Optional(V.Literal(!0))}),V2=V.Object({projectPath:V.String({minLength:1}),scope:V.Optional(JO(["local","project","global"])),policy:V.Object({restrictToAllowedSources:V.Boolean(),requireGitCommitSha:V.Boolean(),allowedGitHosts:V.Array(V.String()),allowedMarketplaces:V.Array(V.String()),allowedLocalRoots:V.Array(V.String())})});function AO(O){if(!O||!e$.isAbsolute(O))throw new _("projectPath must be absolute");return e$.resolve(O)}async function $4(O){let[$,x]=await Promise.all([jO(O),T0.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((Q)=>({name:Q.manifest.name,description:Q.manifest.description,version:Q.manifest.version,source:Q.source,enabled:Q.status==="active",status:Q.status,commands:Q.commands.length,skills:Q.skills.length,agents:Q.agents.length,hooks:Q.hooks?Object.values(Q.hooks).reduce((Z,G)=>Z+(Array.isArray(G)?G.length:0),0):0,mcpServers:Object.keys(Q.mcpServers??{}).length,configurable:Q.source!=="cli",managed:Q.installation!==void 0,marketplace:Q.installation?.source.type==="marketplace"?Q.installation.source.marketplace:void 0,revision:Q.installation?.revision,installedAt:Q.installation?.installedAt,updatedAt:Q.installation?.updatedAt,compatibilityIssues:Q.compatibilityIssues??[],effectiveScope:Q.source==="cli"?"invocation":x.settings[Q.manifest.name]?.effectiveScope??"default",settingLayers:Q.source==="cli"?{invocation:!0}:x.settings[Q.manifest.name]?.layers??{}}))}async function N2(){let O=x4(),[$,x]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),Q=new Map(x.map((Z)=>[Z.name,Z]));return $.map(({marketplace:Z,manifest:G})=>({name:Z.name,description:G.description??G.metadata?.description??"",sourceType:Z.source.type,revision:Z.revision,updatedAt:Z.updatedAt,plugins:G.plugins.map((z)=>{let U=Q.get(z.name);return{name:z.name,description:z.description??"",version:z.version,category:z.category,tags:z.tags??[],installed:U!==void 0,installedVersion:U?.version}})}))}function V0(O,$){if(!O.success)throw new _(O.error??$)}var K4=()=>{let O=new Q2;return O.get("/",async($)=>{let x=AO($.req.query("projectPath"));return $.json(await $4(x))}),O.post("/refresh",async($)=>{let x=q(J2,await $.req.json());if(!x.success)throw new _("Invalid plugin refresh request");let Q=AO(x.data.projectPath),Z=await Z4(Q);return $.json({plugins:await $4(Q),errors:Z.discovery.errors.map((G)=>({code:G.code??"LOAD_ERROR",error:G.error}))})}),O.get("/catalog",async($)=>{return AO($.req.query("projectPath")),$.json(await N2())}),O.get("/policy",async($)=>{let x=AO($.req.query("projectPath")),Q=await T0.getInstance().loadWorkspacePluginSourcePolicy(x);return $.json({policy:Q,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let x=q(V2,await $.req.json());if(!x.success)throw new _("Invalid plugin source policy request");let Q=AO(x.data.projectPath),Z=await J4(Q,x.data.policy,x.data.scope??"global");return $.json({policy:Z})}),O.post("/install",async($)=>{let x=q(Y2,await $.req.json());if(!x.success)throw new _("Invalid plugin install request; explicit source trust is required");let Q=AO(x.data.projectPath),{result:Z}=await Y4(Q,x.data.source,{trusted:x.data.trust,ref:x.data.ref});return V0(Z,"Plugin installation failed"),$.json({name:Z.pluginName,version:Z.manifest?.version,revision:Z.installation?.revision,changed:Z.changed,installedDependencies:Z.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let x=q(X2,await $.req.json());if(!x.success)throw new _("Invalid marketplace add request");let Q=AO(x.data.projectPath),Z=await X4(Q,x.data.source,x.data.ref);return V0(Z,"Marketplace installation failed"),$.json({name:Z.marketplace?.name,plugins:Z.manifest?.plugins.length??0,revision:Z.marketplace?.revision,changed:Z.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let x=q(O4,await $.req.json());if(!x.success)throw new _("Invalid marketplace refresh request");let Q=await V4(AO(x.data.projectPath),$.req.param("name"));return V0(Q,"Marketplace refresh failed"),$.json({name:Q.marketplace?.name,plugins:Q.manifest?.plugins.length??0,revision:Q.marketplace?.revision,changed:Q.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let x=q(O4,await $.req.json());if(!x.success||x.data.confirm!==!0)throw new _("Invalid marketplace removal request; explicit confirmation is required");AO(x.data.projectPath);let Q=await N4($.req.param("name"),!0);return V0(Q,"Marketplace removal failed"),$.json({name:Q.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let x=q(z2,await $.req.json());if(!x.success)throw new _("Invalid plugin update request; explicit source trust is required");let Q=AO(x.data.projectPath),{result:Z}=await z4(Q,$.req.param("name"),{trusted:x.data.trust});return V0(Z,"Plugin update failed"),$.json({name:Z.pluginName,version:Z.manifest?.version,revision:Z.installation?.revision,changed:Z.changed,updatedDependencies:Z.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let x=q(G2,await $.req.json());if(!x.success)throw new _("Invalid plugin uninstall request; explicit confirmation is required");let Q=AO(x.data.projectPath),{result:Z}=await G4(Q,$.req.param("name"),x.data.confirm);return V0(Z,"Plugin uninstall failed"),$.json({name:Z.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let x=q(Z2,await $.req.json());if(!x.success)throw new _("Invalid plugin state request");let Q=AO(x.data.projectPath),Z=$.req.param("name"),z=(await jO(Q)).plugins.get(Z);if(!z)throw new f("Plugin",Z);if(z.source==="cli")throw new _(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);let U=await Q4(Q,Z,x.data.enabled,x.data.scope??"local");return $.json(U)}),O};import{Hono as _2}from"hono";import{execFile as K2}from"node:child_process";import W2 from"node:path";var b1="__BLADE_DIRECTORY_PICKER_CANCELLED__",F2=900000;function U2(O,$){return new Promise((x)=>{K2(O,[...$],{timeout:F2,maxBuffer:65536,windowsHide:!0},(Q,Z,G)=>{let z=Q?.code;x({stdout:Z,stderr:G,exitCode:typeof z==="number"?z:Q?1:0,...typeof z==="string"?{errorCode:z}:{}})})})}function T1(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===b1)return{cancelled:!0};if(!W2.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function j1(O){return O.exitCode!==0||Boolean(O.errorCode)}class W4{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??U2}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 "${b1}"`,"end try"].join(`
|
|
8
|
+
`),$=await this.runCommand("osascript",["-e",O]);if(j1($))throw Error("Unable to open the macOS folder picker");return T1($.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("${b1}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(j1($))throw Error("Unable to open the Windows folder picker");return T1($.stdout)}async pickOnLinux(){let O=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let $ of O){let x=await this.runCommand($.command,$.args);if(x.errorCode==="ENOENT")continue;if(x.exitCode===1&&!x.stdout.trim()&&!x.stderr.trim())return{cancelled:!0};if(j1(x))throw Error("Unable to open the Linux folder picker");return T1(x.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var F4=new W4;var D2=V.Object({path:V.String({minLength:1})});function H2(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let $=new URL(O).hostname;return $==="localhost"||$==="127.0.0.1"||$==="::1"||$==="[::1]"}catch{return!1}}var U4=(O={})=>{let $=new _2,x=O.pickDirectory??(()=>F4.pick()),Q=O.allowDirectoryPickerRequest??H2;return $.get("/",async(Z)=>{return Z.json(await O1.list(c()))}),$.post("/",async(Z)=>{let G;try{G=await Z.req.json()}catch{throw new _("A valid JSON body is required")}let z=q(D2,G);if(!z.success)throw new _("A project path is required");try{let U=await O1.bind(z.data.path,c());return Z.json(U,201)}catch(U){throw new _(U instanceof Error?U.message:"Failed to bind project")}}),$.post("/pick",async(Z)=>{if(!Q(Z.req.header("Origin")))throw new xO("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Z.json(await x())}catch(G){throw new _(G instanceof Error?G.message:"Failed to select a folder")}}),$.delete("/",async(Z)=>{let G=Z.req.query("path");if(!G)throw new _("A project path is required");try{let z=await O1.unbind(G);return Z.json({success:!0,removed:z})}catch(z){throw new _(z instanceof Error?z.message:"Failed to unbind project")}}),$};import{Hono as L2}from"hono";var _4=o("Service"),B4=()=>{let O=new L2;return O.get("/",async($)=>{try{let x=await H4();return $.json(x)}catch(x){return _4.error("[ProviderRoutes] Failed to list providers:",x),$.json([])}}),O.get("/:provider/models",async($)=>{let x=$.req.param("provider");try{let Q=await L4(x);return $.json(Q)}catch(Q){return _4.error("[ProviderRoutes] Failed to list models:",Q),$.json([])}}),O.put("/:provider/credential",async($)=>{let x=$.req.param("provider"),Q=await $.req.json();if(!Q.apiKey?.trim())throw new _("apiKey is required");return await cO().setApiKey(x,Q.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await cO().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let x=$.req.param("provider"),Q=QO(),Z=Q?.modelProviders[x];if(!Q||!Z)throw new f("Model provider",x);let G=await $.req.json();if(!G.name||!G.baseUrl||!G.wireApi)throw new _("name, baseUrl and wireApi are required");let z="apiKeyEnv"in G?G.apiKeyEnv?.trim():Z.apiKeyEnv,U={name:G.name,baseUrl:G.baseUrl,wireApi:G.wireApi,...z?{apiKeyEnv:z}:{}},j=cO(),L=G.apiKey?.trim()?await j.credentials.read(x):void 0;if(G.apiKey?.trim())await j.setApiKey(x,G.apiKey.trim());try{return await BO().updateModelProvider(x,U),$.json({success:!0})}catch(b){if(G.apiKey?.trim())if(L)await j.credentials.modify(x,async()=>L);else await j.credentials.delete(x);if(b instanceof Error&&(b.message.includes("modelProviders.")||b.message.includes("built-in provider")))throw new _(b.message);throw b}}),O.delete("/:provider",async($)=>{let x=$.req.param("provider");if(!QO()?.modelProviders[x])throw new f("Model provider",x);let Z=$.req.query("removeModels");if(Z!==void 0&&Z!=="true"&&Z!=="false")throw new _("removeModels must be true or false");try{let G=await BO().removeModelProvider(x,{removeModels:Z==="true"});return $.json({success:!0,...G})}catch(G){if(G instanceof Error&&(G.message.includes("still referenced")||G.message.includes("owns the only model")))throw new k(G.message);throw G}}),O.post("/:provider/probe",async($)=>{let x=$.req.param("provider"),Q=QO();if(!Q?.modelProviders[x])throw new f("Model provider",x);let Z=await $.req.json().catch(()=>({})),G=Q.models.filter((U)=>U.provider===x),z=Z.modelId?G.find((U)=>U.id===Z.modelId):G[0];if(!z)throw new _(Z.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return $.json(await D4(z,Q))}),O};import{Hono as B2}from"hono";var w2=o("Service"),T4=(O,$)=>{let x=new B2;return x.onError((Q,Z)=>{if(Q instanceof xO)return Z.json(Q.toObject(),Q.statusCode);return w2.error("[ScheduleRoutes] Unhandled route error:",Q),Z.json(new t("Schedule request failed").toObject(),500)}),x.get("/",async(Q)=>{let Z=await O.list();return Q.json(M4.parse({schedules:Z}))}),x.post("/",async(Q)=>{let Z;try{Z=await Q.req.json()}catch{throw new _("Invalid request body")}let G=q(w4,Z);if(!G.success)throw new _("Invalid schedule request");let z=G.data.projectPath||Q.get("directory")||c();try{let U=await O.create({...G.data,projectPath:z});return Q.json(sO.parse(U),201)}catch(U){throw new _(U instanceof Error?U.message:"Failed to create schedule")}}),x.get("/:id",async(Q)=>{let Z=await O.get(Q.req.param("id"));if(!Z)throw new f("Schedule not found");return Q.json(sO.parse(Z))}),x.patch("/:id",async(Q)=>{let Z;try{Z=await Q.req.json()}catch{throw new _("Invalid request body")}let G=q(A4,Z);if(!G.success)throw new _("Invalid schedule update");let{modelId:z,reasoningEffort:U,serviceTier:j,responseVerbosity:L,communicationStyle:b,isolation:w,permissionMode:F,...P}=G.data,ZO={...z!==void 0?{modelId:z}:{},...U!==void 0?{reasoningEffort:U}:{},...j!==void 0?{serviceTier:j}:{},...L!==void 0?{responseVerbosity:L}:{},...b!==void 0?{communicationStyle:b}:{},...w!==void 0?{isolation:w}:{},...F!==void 0?{permissionMode:F}:{}};try{let d=await O.update(Q.req.param("id"),{...P,...Object.keys(ZO).length>0?{dispatch:ZO}:{}});if(!d)throw new f("Schedule not found");return Q.json(sO.parse(d))}catch(d){if(d instanceof xO)throw d;throw new _(d instanceof Error?d.message:"Failed to update schedule")}}),x.delete("/:id",async(Q)=>{if(!await O.remove(Q.req.param("id")))throw new f("Schedule not found");return Q.json({ok:!0})}),x.post("/:id/enable",async(Q)=>{let Z=await O.setEnabled(Q.req.param("id"),!0);if(!Z)throw new f("Schedule not found");return Q.json(sO.parse(Z))}),x.post("/:id/disable",async(Q)=>{let Z=await O.setEnabled(Q.req.param("id"),!1);if(!Z)throw new f("Schedule not found");return Q.json(sO.parse(Z))}),x.post("/:id/run",async(Q)=>{let Z=await O.get(Q.req.param("id"));if(!Z)throw new f("Schedule not found");if(!$)throw new t("Scheduler is not running in this process");await $.fire(Z,new Date,{manual:!0});let G=await O.get(Z.id);return Q.json(sO.parse(G??Z),202)}),x};import*as vO from"node:fs/promises";import{homedir as C4}from"node:os";import*as MO from"node:path";import{Hono as A2}from"hono";var rO=o("Service"),j4=MO.join(C4(),".blade","skills"),C1=MO.join(C4(),".blade","skills-config.json");async function S4(){try{let O=await vO.readFile(C1,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function M2(O){await vO.mkdir(MO.dirname(C1),{recursive:!0}),await vO.writeFile(C1,JSON.stringify(O,null,2))}async function T2(O,$){let x=await S4();if($)x.disabled=x.disabled.filter((Q)=>Q!==O);else if(!x.disabled.includes(O))x.disabled.push(O);await M2(x)}var uO=null,j2=300000,b2=6;async function C2(){if(uO&&Date.now()-uO.timestamp<j2)return uO.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(rO.warn(`GitHub API returned ${O.status}`),uO)return uO.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let x=(await O.json()).filter((z)=>z.type==="dir"),Q=Array(x.length),Z=0,G=Math.min(b2,x.length);return await Promise.all(Array.from({length:G},async()=>{while(Z<x.length){let z=Z++,U=x[z];if(!U)continue;let j=`Official ${U.name} skill`;try{let L=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${U.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(L.ok){let w=(await L.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(w)j=w[1].trim().slice(0,100)}}catch{}Q[z]={name:U.name,description:j,tag:"Official",author:"Anthropic"}}})),uO={data:Q,timestamp:Date.now()},Q}catch(O){if(rO.warn("Failed to fetch skills catalog from GitHub:",O),uO)return uO.data;throw O}}var R4=()=>{let O=new A2;return O.get("/",async($)=>{try{let x=$.get("directory")||c(),Z=(await jO(x)).skills.getAll(),G=await S4(),z=Z.map((U)=>({id:U.name,name:U.name,enabled:!G.disabled.includes(U.name),description:U.description||"",version:U.version||"1.0.0",provider:"Local",location:U.source==="builtin"?"Built-in":U.basePath,removable:U.source==="user"&&MO.dirname(MO.resolve(U.basePath))===MO.resolve(j4),capabilities:["prompts"],allowedTools:U.allowedTools||[]}));return $.json(z)}catch(x){return rO.error("[SkillsRoutes] Failed to get skills:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async($)=>{try{let x=$.req.param("name"),Q=await $.req.json();return await T2(x,Q.enabled),$.json({success:!0,enabled:Q.enabled})}catch(x){return rO.error("[SkillsRoutes] Failed to toggle skill:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name"),Q=$.get("directory")||c();return C0(Q,async(Z)=>{let G=Z.skills,z=G.get(x);if(!z)return $.json({success:!1,error:"Skill not found"},404);let U=MO.resolve(z.basePath),j=MO.resolve(j4);if(z.source!=="user"||MO.dirname(U)!==j)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await vO.rm(U,{recursive:!0,force:!0}),await G.refresh(),b0(Q),await j0(Q),$.json({success:!0})})}catch(x){return rO.error("[SkillsRoutes] Failed to uninstall skill:",x),$.json({success:!1,error:x.message},500)}}),O.post("/install",async($)=>{try{let x=await $.req.json(),Q=b4(),Z=$.get("directory")||c();return C0(Z,async(G)=>{let z=G.skills,U=!1;if(x.source==="catalog"&&x.name){if(U=await Q.installOfficialSkill(x.name),!U)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(U=await Q.installFromRepo(x.url,x.name),!U)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(x.source==="local"&&x.path){if(U=await Q.installFromLocal(x.path,x.name),!U)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await z.refresh(),b0(Z),await j0(Z),$.json({success:!0})})}catch(x){return rO.error("[SkillsRoutes] Failed to install skill:",x),$.json({success:!1,error:x.message},500)}}),O.get("/catalog",async($)=>{try{let x=await C2();return $.json(x)}catch(x){return rO.error("[SkillsRoutes] Failed to get catalog:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills catalog"},502)}}),O};import{execSync as S2}from"node:child_process";import{readdir as R2}from"node:fs/promises";import $1 from"node:path";import E2 from"fast-glob";import{Hono as k2}from"hono";var m0=o("Service"),q2=(O)=>{try{return S2("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},I2=[...N0.map((O)=>`${O}/**`),...N0,...N0.map((O)=>`**/${O}/**`),...N0.map((O)=>`**/${O}`),...S1.map((O)=>`**/${O}`)],P2=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),q4=()=>{let O=new k2;return O.get("/commands",async($)=>{try{let x=$.req.query("q")||"",Q=$.get("directory")||c(),Z=await jO(Q),G=k4(x,Q,Z).filter((z)=>!P2.has(z.command));return $.json(G)}catch(x){return m0.error("[SuggestionsRoutes] Failed to get command suggestions:",x),$.json([])}}),O.get("/files",async($)=>{try{let x=$.req.query("q")||"",Q=$.get("directory")||c(),Z=Math.min(Number($.req.query("limit"))||100,1000),G=$.req.query("type")==="file",U=(await E2("**/*",{cwd:Q,dot:!1,followSymbolicLinks:!1,onlyFiles:G,markDirectories:!0,unique:!0,ignore:I2})).map((b)=>b.replace(/\\/g,"/"));if(!x)return $.json(U.slice(0,Z));let j=x.toLowerCase(),L=U.filter((b)=>b.toLowerCase().includes(j)).slice(0,Z);return $.json(L)}catch(x){return m0.error("[SuggestionsRoutes] Failed to get file suggestions:",x),$.json([])}}),O.get("/files/tree",async($)=>{try{let x=$.get("directory")||c(),Q=$.req.query("path")||"",Z=Q?$1.join(x,Q):x,z=(await R2(Z,{withFileTypes:!0})).map((L)=>({name:L.name,path:Q?`${Q}/${L.name}`:L.name,type:L.isDirectory()?"dir":"file"}));z.sort((L,b)=>{if(L.type!==b.type)return L.type==="dir"?-1:1;return L.name.localeCompare(b.name)});let U=new Set(N0),j=z.filter((L)=>{let b=L.name;if(b.startsWith("."))return!1;if(U.has(b))return!1;for(let w of S1)if(b.match(new RegExp(w.replace("*",".*"))))return!1;return!0});return $.json(j)}catch(x){return m0.error("[SuggestionsRoutes] Failed to get file tree:",x),$.json([])}}),O.get("/files/content",async($)=>{try{let x=$.req.query("path");if(!x)return $.json({error:"Missing file path"},400);let Q=$.get("directory")||c(),Z=$1.resolve(Q,x),G=$1.relative(Q,Z);if(G.startsWith("..")||$1.isAbsolute(G))return $.json({error:"Invalid file path"},400);let z=E4(),U=await z.stat(Z);if(!U?.isFile)return $.json({error:"File not found"},404);let j=200000,L=await z.readTextFile(Z),b=L.length>j;return $.json({path:x,content:b?L.slice(0,j):L,truncated:b,size:U.size})}catch(x){return m0.error("[SuggestionsRoutes] Failed to get file content:",x),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{try{let x=$.get("directory")||c(),Q=q2(x);return $.json({branch:Q})}catch(x){return m0.error("[SuggestionsRoutes] Failed to get git info:",x),$.json({branch:null})}}),O};import{Hono as y2}from"hono";var K0=o("Service"),m4=(O)=>{let $=new y2;return $.onError((x,Q)=>{if(x instanceof xO)return Q.json(x.toObject(),x.statusCode);return K0.error("[TaskRoutes] Unhandled route error:",x),Q.json(new t("Failed to dispatch task").toObject(),500)}),$.post("/",async(x)=>{let Q;try{Q=await x.req.json()}catch{throw new _("Invalid request body")}let Z=q(P4,Q);if(!Z.success)throw new _("Invalid task request");if((Z.data.attachments??[]).reduce((z,U)=>z+(typeof U.content==="string"?Buffer.byteLength(U.content):0),0)>r0)throw new _("Task attachments exceed the 5 MiB limit");if(Z.data.taskDueAt&&!Number.isFinite(Date.parse(Z.data.taskDueAt)))throw new _("Invalid task due date");try{let z=await O.dispatchTask({prompt:Z.data.prompt,title:Z.data.title,taskPriority:Z.data.taskPriority,taskKind:Z.data.taskKind,taskDueAt:Z.data.taskDueAt?new Date(Z.data.taskDueAt).toISOString():void 0,sourceProjectPath:Z.data.projectPath||x.get("directory")||c(),isolation:Z.data.isolation,permissionMode:Z.data.permissionMode,modelId:Z.data.modelId,reasoningEffort:Z.data.reasoningEffort,serviceTier:Z.data.serviceTier,responseVerbosity:Z.data.responseVerbosity,communicationStyle:Z.data.communicationStyle,attachments:Z.data.attachments,outputSchema:Z.data.outputSchema});return x.json(E1.parse(z),202)}catch(z){if(z instanceof _||z instanceof k||z instanceof qO||z instanceof kO)throw z;throw K0.error("[TaskRoutes] Failed to dispatch task:",z),new t("Failed to dispatch task")}}),$.patch("/:sessionId",async(x)=>{let Q;try{Q=await x.req.json()}catch{throw new _("Invalid request body")}let Z=q(y4,Q);if(!Z.success)throw new _("Invalid task update");if(Z.data.title===void 0&&Z.data.taskPriority===void 0&&Z.data.taskKind===void 0&&Z.data.taskDueAt===void 0)throw new _("Task update must include at least one field");if(typeof Z.data.taskDueAt==="string"&&!Number.isFinite(Date.parse(Z.data.taskDueAt)))throw new _("Invalid task due date");try{let G=await O.updateTask(x.req.param("sessionId"),{...Z.data,...typeof Z.data.taskDueAt==="string"?{taskDueAt:new Date(Z.data.taskDueAt).toISOString()}:{}},x.req.query("projectPath"));return x.json(R1.parse(G))}catch(G){if(G instanceof _||G instanceof f||G instanceof k)throw G;throw K0.error("[TaskRoutes] Failed to update task:",G),new t("Failed to update task")}}),$.post("/:sessionId/retry",async(x)=>{try{let Q=await O.retryTask(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(E1.parse(Q),202)}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof k||Q instanceof qO||Q instanceof kO)throw Q;throw K0.error("[TaskRoutes] Failed to retry task:",Q),new t("Failed to retry task")}}),$.get("/:sessionId/diff",async(x)=>{try{let Q=await O.getTaskDiff(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(I4.parse(Q))}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof k)throw Q;throw K0.error("[TaskRoutes] Failed to load task diff:",Q),new t("Failed to load task diff")}}),$.post("/:sessionId/delivery",async(x)=>{let Q;try{Q=await x.req.json()}catch{throw new _("Invalid request body")}let Z=q(f4,Q);if(!Z.success)throw new _("Invalid task delivery request");try{let G=await O.deliverTask(x.req.param("sessionId"),Z.data.action,x.req.query("projectPath"));return x.json(R1.parse(G))}catch(G){if(G instanceof _||G instanceof f||G instanceof k)throw G;throw K0.error("[TaskRoutes] Failed to deliver task:",G),new t("Failed to deliver task")}}),$};import v4 from"node:path";import{Hono as h2}from"hono";var f2=eO(V.Object({id:V.String(),name:V.String(),subagentType:V.String(),description:V.String(),agentId:V.Optional(V.String()),status:JO(["leader","running","completed","failed","cancelled","unknown"]),result:V.Optional(V.Unknown()),stats:V.Optional(V.Unknown()),worktreePath:V.Optional(V.String())})),m2=eO(V.Object({id:V.String(),subject:V.String(),description:V.String(),status:JO(["pending","blocked","running","completed"]),owner:V.Optional(V.String()),priority:JO(["high","medium","low"]),dependsOn:V.Array(V.String()),blocks:V.Array(V.String()),result:V.Optional(V.String()),createdAt:V.String(),startedAt:V.Optional(V.String()),completedAt:V.Optional(V.String())})),p9=eO(V.Object({name:V.String(),description:V.Optional(V.String()),status:JO(["idle","running","completed","failed","deleted"]),leadAgentId:V.String(),leadSessionId:V.Optional(V.String()),workspaceRoot:V.Optional(V.String()),peerMessagingEnabled:V.Boolean(),createdAt:V.Number(),updatedAt:V.Number(),deletedAt:V.Optional(V.Number()),members:V.Array(f2),tasks:V.Array(m2)})),h4=eO(V.Object({sessionId:V.String({minLength:1}),projectPath:V.String({minLength:1}),name:V.String({minLength:1}),description:V.Optional(V.String()),leadAgentType:V.Optional(V.String()),peerMessagingEnabled:V.Optional(V.Boolean()),members:V.Array(V.Object({name:V.String({minLength:1}),subagentType:V.String({minLength:1}),description:V.Optional(V.String()),prompt:V.String({minLength:10,maxLength:32768})}),{maxItems:32}),tasks:V.Optional(V.Array(V.Object({subject:V.String({minLength:1}),description:V.String({minLength:1}),dependsOn:V.Optional(V.Array(V.String())),assignedTo:V.Optional(V.String()),priority:V.Optional(JO(["high","medium","low"]))}),{maxItems:256}))})),g4=eO(V.Object({sessionId:V.String({minLength:1}),projectPath:V.String({minLength:1}),to:V.String({minLength:1}),message:V.String({minLength:1,maxLength:32768})})),u4=eO(V.Object({sessionId:V.String({minLength:1}),projectPath:V.String({minLength:1}),memberId:V.String({minLength:1})}));var g2=o("Service"),i4=()=>{let O=new h2;return O.onError(($,x)=>{if($ instanceof xO)return x.json($.toObject(),$.statusCode);return g2.error("[TeamRoutes] Unhandled route error:",$),x.json(new t("Team operation failed").toObject(),500)}),O.get("/",async($)=>{F0();let x=await U0($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await W0(x.projectPath).list(x))}),O.post("/",async($)=>{F0();let x=q(h4,await k1($.req));if(!x.success)throw new _("Invalid team request");let Q=await U0(x.data.sessionId,x.data.projectPath),Z=await R.findSessionMetadata(Q.sessionId,Q.projectPath);return $.json(await W0(Q.projectPath).create({name:x.data.name,description:x.data.description,leadAgentType:x.data.leadAgentType,owner:Q,modelId:Z?.selectedModelId,peerMessagingEnabled:x.data.peerMessagingEnabled,members:x.data.members,tasks:x.data.tasks}),201)}),O.get("/:teamName",async($)=>{F0();let x=await U0($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await W0(x.projectPath).getSnapshot($.req.param("teamName"),x))}),O.post("/:teamName/messages",async($)=>{F0();let x=q(g4,await k1($.req));if(!x.success)throw new _("Invalid team message");let Q=await U0(x.data.sessionId,x.data.projectPath),Z=await W0(Q.projectPath).sendMessage({name:$.req.param("teamName"),to:x.data.to,body:x.data.message,owner:Q});return $.json({messages:Z})}),O.post("/:teamName/tasks/claim",async($)=>{F0();let x=q(u4,await k1($.req));if(!x.success)throw new _("Invalid team task claim");let Q=await U0(x.data.sessionId,x.data.projectPath);return $.json({task:await W0(Q.projectPath).claimTask($.req.param("teamName"),x.data.memberId,Q)})}),O.delete("/:teamName",async($)=>{F0();let x=await U0($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await W0(x.projectPath).delete($.req.param("teamName"),{owner:x,killRunning:!0}))}),O};function W0(O){return new l4({configDir:s0(),subagentRegistry:d4(O)})}function F0(){if(p4().config.config?.agentTeamsEnabled!==!0)throw new qO("Agent Teams are disabled")}async function U0(O,$){if(!O||!$||!v4.isAbsolute($))throw new _("sessionId and absolute projectPath are required");let x=v4.resolve($);if(!await R.findSessionMetadata(O,x))throw new f(`Session not found: ${O}`);return{sessionId:O,projectPath:x}}async function k1(O){try{return await O.json()}catch{throw new _("Invalid request body")}}import{Hono as u2}from"hono";var pO=o("Service"),_0=new Map,c4=2097152,a4=65536;function o4(){return typeof globalThis.Bun<"u"}async function v2(O,$,x){if(o4()){let{spawn:G}=await import("bun-pty"),z=G(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:z.pid,write:(U)=>z.write(U),resize:(U,j)=>z.resize(U,j),kill:()=>z.kill(),onData:(U)=>z.onData(U),onExit:(U)=>z.onExit(U)}}let Z=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:Z.pid,write:(G)=>Z.write(G),resize:(G,z)=>Z.resize(G,z),kill:()=>Z.kill(),onData:(G)=>{Z.onData(G)},onExit:(G)=>{Z.onExit(G)}}}var P1=void 0,I1;if(o4())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();I1=$.upgradeWebSocket,P1=$.websocket}catch(O){pO.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function n4(O,$){let x=`term-${Date.now()}`;pO.info(`[Terminal] New connection: ${x}, cwd: ${O}`);let Q=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Z=Q.endsWith("sh")?["-l"]:[],G=await v2(Q,Z,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),z={id:x,process:G,cwd:O,buffer:"",subscribers:new Set};if(_0.set(x,z),z.subscribers.add($),G.onData((U)=>{let j=!1;for(let L of z.subscribers)try{L.send(U),j=!0}catch{z.subscribers.delete(L)}if(j)return;if(z.buffer+=U,z.buffer.length>c4)z.buffer=z.buffer.slice(-c4)}),G.onExit(({exitCode:U})=>{pO.info(`[Terminal] Process exited: ${x}, code: ${U}`);for(let j of z.subscribers)try{j.close()}catch{}_0.delete(x)}),z.buffer){let U=z.buffer;z.buffer="";for(let j=0;j<U.length;j+=a4)$.send(U.slice(j,j+a4))}return{session:z,cleanup:()=>{if(pO.info(`[Terminal] Connection closed: ${x}`),z.subscribers.delete($),z.subscribers.size===0){try{z.process.kill()}catch{}_0.delete(x)}}}}function t4(O,$){O.on("connection",async(x,Q)=>{let Z=new URL(Q.url||"/",`http://${Q.headers.host}`);if(!Z.pathname.endsWith("/terminal/ws")){x.close();return}let G=Z.searchParams.get("cwd")||$()||c();try{let{session:z,cleanup:U}=await n4(G,{send:(j)=>x.send(j),close:()=>x.close()});x.on("message",(j)=>{try{z.process.write(String(j))}catch(L){pO.error("[Terminal] Failed to write to PTY:",L)}}),x.on("close",U),x.on("error",U)}catch(z){pO.error("[Terminal] Failed to spawn PTY:",z),x.close()}})}var s4=()=>{let O=new u2;if(O.get("/status",($)=>{let x=Array.from(_0.values()).map((Q)=>({id:Q.id,cwd:Q.cwd}));return $.json({active:x.length,terminals:x})}),O.post("/kill/:terminalId",($)=>{let x=$.req.param("terminalId"),Q=_0.get(x);if(Q){try{Q.process.kill()}catch{}for(let Z of Q.subscribers)Z.close();return _0.delete(x),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),I1)O.get("/ws",I1(($)=>{let x=$.req.query("cwd")||$.get("directory")||c(),Q;return{async onOpen(Z,G){try{Q=await n4(x,{send:(z)=>G.send(z),close:()=>G.close()})}catch(z){pO.error("[Terminal] Failed to spawn PTY:",z),G.close()}},onMessage(Z){if(!Q)return;try{Q.session.process.write(String(Z.data))}catch(G){pO.error("[Terminal] Failed to write to PTY:",G)}},onClose(){Q?.cleanup()}}}));else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import p2 from"node:path";import{Hono as d2}from"hono";var l2=V.Object({projectPath:V.String({minLength:1}),action:JO(["trust","revoke"])});function r4(O){if(!p2.isAbsolute(O))throw new _("projectPath must be absolute")}var Ox=()=>{let O=new d2;return O.get("/",async($)=>{let x=$.req.query("projectPath");if(!x)throw new _("projectPath query parameter is required");return r4(x),$.json(await y1.getInstance().getStatus(x))}),O.post("/",async($)=>{let x=q(l2,await $.req.json());if(!x.success)throw new _("Invalid workspace trust request");let{projectPath:Q,action:Z}=x.data;r4(Q);let G=y1.getInstance(),z=Z==="trust"?await G.trust(Q):await G.revoke(Q);return await e4(),$.json({...z,reloadRequired:z.sensitiveSources>0})}),O};var FO=o("Service"),h1=[],x1,D0,H0,h0,$x=new Map,xx=new Map,x3=new Set([".css",".html",".js",".json",".svg"]),Q3=1024,Z3=3600000;function J3(O,$){if(!O)return 0;let x=O.split(",").map((Q)=>{let[Z,...G]=Q.trim().toLowerCase().split(";"),z=G.find((j)=>j.trim().startsWith("q=")),U=z?Number(z.trim().slice(2)):1;return{name:Z,quality:Number.isFinite(U)?Math.max(0,Math.min(1,U)):0}});return x.find((Q)=>Q.name===$)?.quality??x.find((Q)=>Q.name==="*")?.quality??0}function Qx(){if(H0)return;let O=()=>{R.collectStaleEmptySessions().then(($)=>{if($>0)FO.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{FO.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),H0=setInterval(O,Z3),H0.unref?.()}function Y3(){if(!H0)return;clearInterval(H0),H0=void 0}function z3(O){return["br","gzip"].map((x)=>({encoding:x,quality:J3(O,x)})).filter((x)=>x.quality>0).sort((x,Q)=>Q.quality-x.quality||(x.encoding==="br"?-1:1))[0]?.encoding}function G3(O){let $=$x.get(O);if($)return $;let x=g0(O);return $x.set(O,x),x}function X3(O,$,x){let Q=`${x}:${O}`,Z=xx.get(Q);if(Z)return Z;let G=x==="br"?t2($,{params:{[r2.BROTLI_PARAM_QUALITY]:5}}):s2($,{level:6});return xx.set(Q,G),G}function V3(){let O=a2(n2(import.meta.url)),$=[dO(O,"web"),dO(c(),"dist/web"),dO(c(),"packages/cli/dist/web")];for(let x of $){let Q=dO(x,"index.html");if(m1(Q)){if(g0(Q,"utf-8").includes("/assets/"))return FO.debug(`[Server] Found web dist at: ${x}`),x}}return null}function N3(){let O=new e2;O.onError((Q,Z)=>{if(FO.error("[Server] Request error:",Q),Q instanceof Yx){let z=new kO(Q.message,{resource:"workspace_agent_resources",limit:Q.capacity});return Z.json(z.toObject(),429)}if(Q instanceof xO)return Z.json(Q.toObject(),Q.statusCode);let G=Q instanceof Error?Q.message:String(Q);return Z.json({error:{code:"INTERNAL_ERROR",message:G}},500)}),O.use(async(Q,Z)=>{let G=process.env.BLADE_SERVER_PASSWORD;if(!G)return Z();let z=Q.req.path;if(z==="/"||z==="/favicon.svg"||z.startsWith("/assets/")||z.endsWith(".html")||z.endsWith(".js")||z.endsWith(".css"))return Z();let U=Q.req.header("Authorization");if(!U?.startsWith("Basic "))return Q.header("WWW-Authenticate",'Basic realm="Blade Server"'),Q.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let j=Buffer.from(U.slice(6),"base64").toString(),[L,b]=j.split(":"),w=process.env.BLADE_SERVER_USERNAME??"blade";if(L!==w||b!==G)return Q.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Z()}),O.use(async(Q,Z)=>{let G=Q.req.path==="/health"||Q.req.path==="/global/health"||Q.req.path.startsWith("/assets/");if(!G)FO.debug(`[Server] ${Q.req.method} ${Q.req.path}`);let z=Date.now();if(await Z(),!G){let U=Date.now()-z;FO.debug(`[Server] ${Q.req.method} ${Q.req.path} - ${Q.res.status} (${U}ms)`)}}),O.use(O3({origin(Q){if(!Q)return;if(Q.startsWith("http://localhost:"))return Q;if(Q.startsWith("http://127.0.0.1:"))return Q;if(Q==="tauri://localhost"||Q==="http://tauri.localhost")return Q;if(h1.includes(Q))return Q;return}})),O.use(async(Q,Z)=>{let G=Q.req.query("directory")||Q.req.header("x-blade-directory")||c();try{G=decodeURIComponent(G)}catch{}return Q.set("directory",G),Z()});let $=t$();h0=$,x1=$.recoverQueuedTasks,D0=new G1({dispatch:(Q)=>$.dispatchTask(Q),store:f1}),O.route("/global",x$()),O.route("/events",O$()),O.route("/sessions",$.app),O.route("/tasks",m4($)),O.route("/teams",i4()),O.route("/schedules",T4(f1,D0)),O.route("/configs",o1()),O.route("/permissions",r$()),O.route("/plugins",K4()),O.route("/hooks",G$()),O.route("/workspace-trust",Ox()),O.route("/providers",B4()),O.route("/models",D$()),O.route("/projects",U4()),O.route("/suggestions",q4()),O.route("/terminal",s4()),O.route("/mcp",N$()),O.route("/skills",R4()),O.get("/health",(Q)=>{return Q.json({healthy:!0,version:Q0()})});let x=V3();if(x)FO.info(`[Server] Serving static files from ${x}`),O.get("/favicon.svg",()=>{let Q=dO(x,"favicon.svg");if(!m1(Q))return new Response(null,{status:404});return new Response(g0(Q),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(Q)=>{let Z=dO(x,Q.req.path);if(!m1(Z))return Q.json({error:{code:"NOT_FOUND",message:`File not found: ${Q.req.path}`}},404);let G=G3(Z),z=o2(Z).toLowerCase(),j={".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"}[z]||"application/octet-stream",L=x3.has(z)&&G.byteLength>=Q3?z3(Q.req.header("Accept-Encoding")):void 0,b=L?X3(Z,G,L):G;return new Response(new Uint8Array(b),{headers:{"Content-Type":j,"Content-Length":String(b.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...L?{"Content-Encoding":L}:{}}})}),O.get("/",(Q)=>{let Z=dO(x,"index.html"),G=g0(Z,"utf-8");return Q.html(G,200,{"Cache-Control":"no-cache"})}),O.get("*",(Q)=>{let Z=Q.req.path;if(Z.includes("."))return Q.json({error:{code:"NOT_FOUND",message:`File not found: ${Z}`}},404);let G=dO(x,"index.html"),z=g0(G,"utf-8");return Q.html(z,200,{"Cache-Control":"no-cache"})});else FO.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(Q)=>{return Q.json({message:"Blade API Server",version:Q0(),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("*",(Q)=>{return Q.json({error:{code:"NOT_FOUND",message:`Route not found: ${Q.req.path}`}},404)});return O}function K3(){let O=c2(),$=[];for(let x of Object.keys(O)){let Q=O[x];if(!Q)continue;for(let Z of Q){if(Z.internal||Z.family!=="IPv4")continue;if(Z.address.startsWith("172."))continue;$.push(Z.address)}}return $}function Zx(){return typeof globalThis.Bun<"u"}function Jx(O,$){let x=globalThis.Bun,Q=(G)=>{try{return x.serve({hostname:$.hostname,port:G,fetch:O.fetch,idleTimeout:0,websocket:P1})}catch(z){FO.error("Failed to start Bun server:",z);return}},Z=$.port===0?Q(4096)??Q(0):Q($.port);if(!Z)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Z.url,port:Z.port,hostname:Z.hostname,stop:async()=>{Z.stop(!0)}}}function W3(O,$){return new Promise((x,Q)=>{let Z=i2(async(L,b)=>{let w=new URL(L.url||"/",`http://${L.headers.host}`),F=new Headers;for(let[d,C]of Object.entries(L.headers))if(C)if(Array.isArray(C))for(let e of C)F.append(d,e);else F.set(d,C);let P;if(L.method!=="GET"&&L.method!=="HEAD")P=(await new Promise((C)=>{let e=[];L.on("data",(u)=>e.push(u)),L.on("end",()=>C(Buffer.concat(e)))})).toString();let ZO=new Request(w.toString(),{method:L.method,headers:F,body:P});try{let d=await O.fetch(ZO);if(b.statusCode=d.status,d.headers.forEach((C,e)=>{b.setHeader(e,C)}),d.body){let C=d.body.getReader(),e=async()=>{let{done:u,value:YO}=await C.read();if(u){b.end();return}return b.write(YO),e()};await e()}else{let C=await d.text();b.end(C)}}catch(d){FO.error("[Server] Node request error:",d),b.statusCode=500,b.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),G=new $3({noServer:!0}),z=c();t4(G,()=>z),Z.on("upgrade",(L,b,w)=>{if(new URL(L.url||"/",`http://${L.headers.host}`).pathname==="/terminal/ws")G.handleUpgrade(L,b,w,(P)=>{G.emit("connection",P,L)});else b.destroy()});let U=(L)=>{return new Promise((b,w)=>{Z.once("error",(F)=>{if(F.code==="EADDRINUSE")w(F);else w(F)}),Z.listen(L,$.hostname,()=>{let F=Z.address();if(F&&typeof F==="object")b(F.port);else b(L)})})};(async()=>{let L;if($.port===0)try{L=await U(4096)}catch{L=await U(0)}else L=await U($.port);let b=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${L}`);x({url:b,port:L,hostname:$.hostname,stop:async()=>{return new Promise((w)=>{G.close(()=>{Z.close(()=>w())})})}})})().catch(Q)})}var Gx;((o7)=>{let O,$,x,Q=(L,b)=>{if(O!==L)return Promise.resolve();if(x)return x;let w=b?.shutdown("server-shutdown");return D0?.stop(),Y3(),x=(async()=>{let F,P=async(ZO)=>{if(!ZO)return;try{await ZO()}catch(d){F??=d}};if(await P(()=>L.stop()),await P(w?()=>w:void 0),zx(),O===L)O=void 0,$=void 0,h0=void 0,x1=void 0,D0=void 0;if(FO.info("[Server] Blade server stopped"),F!==void 0)throw F})(),x};function Z(){if(!$)$=N3();return $}o7.getApp=Z;function G(L){h1=L.cors??[];let b=Z();if(Zx())O=Jx(b,L),x=void 0,FO.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let w=O,F=h0;return x1?.().catch((P)=>{FO.warn("[Server] Failed to recover queued tasks:",P)}),D0?.start(),Qx(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>Q(w,F)}}o7.listen=G;async function z(L){h1=L.cors??[];let b=Z();if(Zx())O=Jx(b,L),FO.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await W3(b,L),FO.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);x=void 0;let w=O,F=h0;try{await x1?.()}catch(P){FO.warn("[Server] Failed to recover queued tasks:",P)}return D0?.start(),Qx(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>Q(w,F)}}o7.listenAsync=z;function U(){return O!==void 0}o7.isRunning=U;function j(){return h0?.getCoordinationStats()}o7.getSessionCoordinationStatsForTests=j})(Gx||={});export{F3 as f,U3 as g,K3 as h,Gx as i};
|