blade-code 0.10.117 → 0.10.119

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