blade-code 0.10.86 → 0.10.88

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 (97) hide show
  1. package/README.md +6 -0
  2. package/dist/blade.js +2 -2
  3. package/dist/chunk-12e2yj9p.js +2 -0
  4. package/dist/{chunk-sb84vdcf.js → chunk-1g5s5vf3.js} +1 -1
  5. package/dist/{chunk-shr5cg46.js → chunk-1mb2y0e0.js} +2 -2
  6. package/dist/{chunk-p3jvzk1f.js → chunk-28pywda6.js} +2 -2
  7. package/dist/{chunk-hjr9r44k.js → chunk-33g68zy1.js} +1 -1
  8. package/dist/{chunk-g9xjcfrf.js → chunk-3aejg2jy.js} +1 -1
  9. package/dist/{chunk-sk8h4m9m.js → chunk-45a1tsk1.js} +1 -1
  10. package/dist/{chunk-00xsfm2j.js → chunk-48r0nbj0.js} +1 -1
  11. package/dist/{chunk-b1mh28yd.js → chunk-4v0jqa9g.js} +1 -1
  12. package/dist/{chunk-bthb5c55.js → chunk-4yf7b4ev.js} +2 -2
  13. package/dist/{chunk-z21es9vg.js → chunk-5d1mmf11.js} +3 -3
  14. package/dist/{chunk-90b512gm.js → chunk-5fbasngx.js} +1 -1
  15. package/dist/{chunk-zg8g2jcr.js → chunk-5j1pfevy.js} +2 -2
  16. package/dist/{chunk-hazs43pe.js → chunk-6f4zxqcg.js} +1 -1
  17. package/dist/{chunk-m5f934fh.js → chunk-7a8j14gg.js} +1 -1
  18. package/dist/{chunk-r8wbvxn7.js → chunk-7avnhnjn.js} +1 -1
  19. package/dist/{chunk-deeh2eq1.js → chunk-7x82wtvn.js} +2 -2
  20. package/dist/{chunk-mp90dsxs.js → chunk-84te16y6.js} +1 -1
  21. package/dist/chunk-85s1nyaz.js +1 -0
  22. package/dist/{chunk-83caxxbt.js → chunk-8mee32xq.js} +1 -1
  23. package/dist/chunk-93q3t4jk.js +1 -0
  24. package/dist/chunk-943vkrwc.js +2 -0
  25. package/dist/{chunk-t5d4p0gc.js → chunk-96ma25s6.js} +2 -2
  26. package/dist/{chunk-yq5vm0hf.js → chunk-9e96b872.js} +2 -2
  27. package/dist/chunk-a3eynw8a.js +1 -0
  28. package/dist/{chunk-jf4bxxyf.js → chunk-anpph83s.js} +1 -1
  29. package/dist/{chunk-rwvaapta.js → chunk-bvp5wpz8.js} +2 -2
  30. package/dist/{chunk-272swnyr.js → chunk-ckqz2btx.js} +1 -1
  31. package/dist/{chunk-0nb8999e.js → chunk-crzktq2e.js} +1 -1
  32. package/dist/chunk-cx3ghkdn.js +1 -0
  33. package/dist/chunk-d0wn5caz.js +1 -0
  34. package/dist/{chunk-sr4zv59p.js → chunk-d83meq4k.js} +1 -1
  35. package/dist/{chunk-skg520wq.js → chunk-dm1knbf8.js} +2 -2
  36. package/dist/{chunk-6n63ev2e.js → chunk-dst8h9c7.js} +38 -38
  37. package/dist/{chunk-zpryec89.js → chunk-e6adb7n8.js} +2 -2
  38. package/dist/{chunk-cdx9tebt.js → chunk-eexw1r8q.js} +1 -1
  39. package/dist/{chunk-x89n28mq.js → chunk-em42qzg6.js} +2 -2
  40. package/dist/{chunk-tpxs85cg.js → chunk-f7p7tzx2.js} +2 -2
  41. package/dist/chunk-hdgee5xk.js +118 -0
  42. package/dist/chunk-hj41cbd6.js +1 -0
  43. package/dist/{chunk-ffa6hhee.js → chunk-hkh2nsam.js} +2 -2
  44. package/dist/{chunk-9vmxd900.js → chunk-hrzfmdhp.js} +1 -1
  45. package/dist/chunk-jpbj8h8f.js +1 -0
  46. package/dist/{chunk-wktx761x.js → chunk-k358j1vk.js} +2 -2
  47. package/dist/chunk-kbgsbq7k.js +1 -0
  48. package/dist/{chunk-6jsmac0q.js → chunk-m5hnyxf3.js} +1 -1
  49. package/dist/{chunk-2dq84j8s.js → chunk-m7y3rvxj.js} +1 -1
  50. package/dist/{chunk-gzjt969t.js → chunk-mgnjmbwq.js} +1 -1
  51. package/dist/{chunk-jndq361v.js → chunk-mh92e9gy.js} +1 -1
  52. package/dist/{chunk-b8p2mwq9.js → chunk-mjx5epcb.js} +2 -2
  53. package/dist/chunk-n9y19kem.js +1691 -0
  54. package/dist/{chunk-7m5q8vxf.js → chunk-ne5w9ds8.js} +1 -1
  55. package/dist/{chunk-ww51801m.js → chunk-q15sm6vj.js} +1 -1
  56. package/dist/{chunk-44dzrn0p.js → chunk-q8jfwyr4.js} +1 -1
  57. package/dist/chunk-qsxt9ejm.js +1 -0
  58. package/dist/{chunk-r77pcb0f.js → chunk-r2nzt9jm.js} +2 -2
  59. package/dist/chunk-r5zejm8a.js +10 -0
  60. package/dist/chunk-rhgaymf2.js +1 -0
  61. package/dist/{chunk-01zar8q6.js → chunk-rj49h1x1.js} +2 -2
  62. package/dist/{chunk-e1ry8aj5.js → chunk-rm8w0qg7.js} +1 -1
  63. package/dist/chunk-rx60xs95.js +8 -0
  64. package/dist/{chunk-t1633e8m.js → chunk-rxjyc6ff.js} +2 -2
  65. package/dist/{chunk-7rfhmbqw.js → chunk-tc1001nx.js} +1 -1
  66. package/dist/{chunk-0q5bz3nm.js → chunk-vyk5nxsz.js} +2 -2
  67. package/dist/chunk-w19aw6n3.js +1 -0
  68. package/dist/chunk-wattrxqd.js +1 -0
  69. package/dist/chunk-wtj4ft4m.js +1 -0
  70. package/dist/{chunk-fv8b98tz.js → chunk-x079eg84.js} +2 -2
  71. package/dist/{chunk-bwt1djsp.js → chunk-xcp4zpby.js} +2 -2
  72. package/dist/{chunk-d2pwwdab.js → chunk-xhhgpbzs.js} +1 -1
  73. package/dist/chunk-xxk5d2v6.js +2 -0
  74. package/dist/chunk-y1vpje4h.js +1 -0
  75. package/dist/{chunk-b2p9qm6j.js → chunk-y7dtdwqx.js} +2 -2
  76. package/dist/chunk-zd028k7y.js +1 -0
  77. package/package.json +2 -2
  78. package/dist/chunk-2ps02f7j.js +0 -1
  79. package/dist/chunk-4y34e9ty.js +0 -1
  80. package/dist/chunk-7jp7e0zj.js +0 -1
  81. package/dist/chunk-9erhm3gg.js +0 -8
  82. package/dist/chunk-9zm7v41x.js +0 -1
  83. package/dist/chunk-gd2sw9zm.js +0 -2
  84. package/dist/chunk-gk79etn6.js +0 -118
  85. package/dist/chunk-hg8d4vhj.js +0 -2
  86. package/dist/chunk-hm92k82b.js +0 -1
  87. package/dist/chunk-hxgzj76t.js +0 -1
  88. package/dist/chunk-j2s2g9ep.js +0 -1
  89. package/dist/chunk-k6m9wmsq.js +0 -1
  90. package/dist/chunk-tap68662.js +0 -1
  91. package/dist/chunk-vt654hsf.js +0 -10
  92. package/dist/chunk-w2sb1hy9.js +0 -1
  93. package/dist/chunk-x2rraka3.js +0 -1
  94. package/dist/chunk-x564avfw.js +0 -1
  95. package/dist/chunk-xj65p2sn.js +0 -1
  96. package/dist/chunk-xwtx2vng.js +0 -1
  97. package/dist/chunk-zpbbcdme.js +0 -1673
@@ -1,8 +0,0 @@
1
- import{j as L4,k as B4}from"./chunk-gd2sw9zm.js";import{l as O1}from"./chunk-01zar8q6.js";import{s as J0,t as n$}from"./chunk-9vmxd900.js";import{u as oO}from"./chunk-gzjt969t.js";import{A as O$,v as v$,w as s1,x as r1,y as e1,z as x0}from"./chunk-00xsfm2j.js";import{$ as Y4,C as k4,F as y$,G as N0,H as R1,I as n0,J as L1,K as EO,L as m$,M as h$,N as g$,O as B1,P as mO,Q as S0,T as y0,U as f0,W as i4,X as u$,Y as p$,Z as Z4,_ as J4,aa as z4,ba as G4,ca as X4,da as V4,ea as N4,fa as K4,ia as H4,la as Ox,qa as q4}from"./chunk-zpbbcdme.js";import{ta as N$,za as UO}from"./chunk-b8p2mwq9.js";import{Da as z1,Ga as P4,Ha as E1,Ia as d$,Ja as l$,Ka as y4,La as f4,Ma as k1,Na as m4,Oa as sO,Pa as A4,Qa as M4,Ra as T4,Sa as i$,Ta as c$,Ua as a$,Va as o$,Wa as o1,Xa as m1}from"./chunk-tpxs85cg.js";import{Eb as nO,gb as gO,hb as p,jb as S,kb as f$,vb as H1}from"./chunk-6n63ev2e.js";import{Pb as R$}from"./chunk-r8wbvxn7.js";import{Ac as I0,Bc as M1,Cc as P0,Ec as k$,Kc as q$,Lc as I$,Nc as z0,Qc as U1,Vc as P$,Wc as _1,Xc as D1,Yc as R,jc as E$,uc as t0}from"./chunk-gk79etn6.js";import{Sd as d4,Wd as QO,_d as U$,fe as BO}from"./chunk-bthb5c55.js";import{ge as F1}from"./chunk-g9xjcfrf.js";import{xe as C$}from"./chunk-44dzrn0p.js";import{ze as o0}from"./chunk-deeh2eq1.js";import{He as l4,Je as C4,Me as Q4,Qe as j0,Re as b0,Ve as zx,Ye as jO,Ze as C0,af as Gx}from"./chunk-t5d4p0gc.js";import{of as _$,pf as S$}from"./chunk-ww51801m.js";import{tf as z$,uf as Z0}from"./chunk-z21es9vg.js";import{Bg as T0,Mf as V$,eg as T$,hg as j$,jg as b$,wg as G$}from"./chunk-zpryec89.js";import{Eg as K1}from"./chunk-7m5q8vxf.js";import{Fg as q,Hg as V,Ig as eO,Kg as JO}from"./chunk-sk8h4m9m.js";import{Mg as r0,Pg as W1}from"./chunk-hg8d4vhj.js";import{Tg as c}from"./chunk-sb84vdcf.js";import{th as o}from"./chunk-ffa6hhee.js";import{zh as cO}from"./chunk-t1633e8m.js";import{Bh as W$,Ch as A$,Eh as F$,Fh as M$}from"./chunk-m5f934fh.js";import{Hh as Q0}from"./chunk-p3jvzk1f.js";import{Oh as f1}from"./chunk-rwvaapta.js";import{Uh as i0,Yh as x$,Zh as s0}from"./chunk-shr5cg46.js";import{$h as I1}from"./chunk-6jsmac0q.js";var U3={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 h1,readFileSync as g0}from"node:fs";import{createServer as c2}from"node:http";import{networkInterfaces as a2}from"node:os";import{dirname as o2,extname as n2,join as dO}from"node:path";import{fileURLToPath as t2}from"node:url";import{brotliCompressSync as s2,gzipSync as r2,constants as e2}from"node:zlib";import{Hono as O3}from"hono";import{cors as $3}from"hono/cors";import{WebSocketServer as x3}from"ws";var $0=o("Service"),Nx=30000,Kx=new Set(["completed","failed","cancelled","interrupted"]);class G1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??o1.getInstance(),this.tickMs=O.tickMs??Nx}start(){if(this.timer)return;$0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=S.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!Kx.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,$0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){$0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),$0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Q=$.toISOString();try{let Z=await this.dispatch({prompt:O.prompt,title:O.title??Wx(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),G=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:z1(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Q,lastRunSessionId:Z.session.sessionId,lastStatus:Z.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),S.publish({sessionId:Z.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Q,sessionId:Z.session.sessionId,runId:Z.runId,status:Z.status}),$0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Z.session.sessionId} (${Z.status})`)}catch(Z){let G=Z instanceof Error?Z.message:String(Z);$0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Z);let z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:z1(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Q,lastStatus:"error",lastError:G,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Z=(await this.store.list()).find((G)=>G.lastRunSessionId===O);if(!Z)return;await this.store.update(Z.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function Wx(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class xO extends Error{code;statusCode;details;constructor(O,$,x=500,Q){super($);this.code=O;this.statusCode=x;this.details=Q;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class f extends xO{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class _ extends xO{constructor(O){super("BAD_REQUEST",O,400)}}class k extends xO{constructor(O){super("CONFLICT",O,409)}}class kO extends xO{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class qO extends xO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class LO extends xO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class t extends xO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var T3=V.Object({error:V.Object({code:V.String(),message:V.String(),details:V.Optional(V.Record(V.String(),V.Unknown()))})});import{Hono as Fx}from"hono";var X1=o("Service"),Ux=V.Object({updates:V.Record(V.String(),V.Any()),options:V.Optional(V.Object({scope:V.Optional(JO(["local","project","global"])),immediate:V.Optional(V.Boolean())}))});function _x(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 n1=()=>{let O=new Fx;return O.get("/",async($)=>{try{let x=QO();return $.json(x?_x(x):{})}catch(x){return X1.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),Q=q(Ux,x);if(!Q.success)throw new _("Invalid config update format");let{updates:Z,options:G}=Q.data;return await BO().updateConfig(Z,G),$.json({success:!0,updates:Z})}catch(x){throw X1.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=QO();return $.json(x?.permissions||{})}catch(x){return X1.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as Dx}from"hono";import{streamSSE as Hx}from"hono/streaming";function t1(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
- `;if(O.event!==void 0)$+=`event: ${O.event}
3
- `;for(let x of O.data.split(/\r\n|\r|\n/))$+=`data: ${x}
4
- `;if(O.retry!==void 0)$+=`retry: ${O.retry}
5
- `;return $+=`
6
- `,Buffer.byteLength($)}class A0{serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor(O){this.maxPendingItems=O.maxPendingItems??s1,this.maxPendingBytes=O.maxPendingBytes??r1,this.serial=new O$({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:O.writeTimeoutMs??e1,sizeOf:t1,write:O.write,onFailure:($)=>{this.failure=$,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,O.onFailure?.($)}})}async writeInitial(O){await this.offerDirect(O)}observe(O,$){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer(O,$);return}this.offerLive(O,$)}async writeReplay(O,$){if(!Number.isSafeInteger($)||$<=0)throw this.fail(new x0("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if($<=this.highestReplaySequence)return;await this.offerDirect(O),this.highestReplaySequence=$,this.highestDeliveredSequence=$}finishInitialization(O){if(this.phase!=="buffering")return;let $=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let x=O.replayed?$.filter((Z)=>Z.sequence!==void 0&&Z.sequence>this.highestReplaySequence).sort((Z,G)=>Z.sequence-G.sequence||Z.order-G.order):$.sort((Z,G)=>Z.order-G.order),Q;for(let Z of x){if(O.replayed&&Z.sequence!==void 0&&Z.sequence===Q)continue;if(this.offerLive(Z.message,Z.sequence),this.serial.stats().closed)return;Q=Z.sequence}}offerHeartbeat(O){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive(O),!this.serial.stats().closed}async flush(){await this.serial.flush()}close(O){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close(O)}stats(){let O=this.serial.stats();return{closed:this.phase==="closed",pendingItems:O.pendingItems+this.buffered.length,pendingBytes:O.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer(O,$){let x=t1(O),Q=this.serial.stats();if(x>this.maxPendingBytes){this.fail(new x0("oversized",`SSE frame requires ${x} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:Q.pendingItems+this.buffered.length,pendingBytes:Q.pendingBytes+this.bufferedBytes}));return}if(Q.pendingItems+this.buffered.length>=this.maxPendingItems||Q.pendingBytes+this.bufferedBytes+x>this.maxPendingBytes){this.fail(new x0("overflow","SSE initialization buffer limit exceeded",{pendingItems:Q.pendingItems+this.buffered.length,pendingBytes:Q.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:O,bytes:x,sequence:$,order:this.nextOrder}),this.bufferedBytes+=x}offerLive(O,$){if($!==void 0){if($<=this.highestReplaySequence)return;if($<=this.highestDeliveredSequence){this.fail(new x0("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=$}if(!this.serial.offer(O).accepted)this.phase="closed"}async offerDirect(O){if(this.phase==="closed")throw this.currentFailure();let $=this.serial.offer(O);if(!$.accepted)throw this.phase="closed",$.error;await $.completion}fail(O){this.serial.close(O)}currentFailure(){return this.failure??new x0("closed","SSE egress is closed")}}var Lx=15000,Bx=o("Service"),wx=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),Ax=new Set(["queued","running","completed","failed","cancelled","interrupted"]),Mx=new Set(["high","medium","low"]),Tx=new Set(["feature","bug","maintenance","research"]);function jx(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=["changedFiles","additions","deletions","commits"];if(x.some((Q)=>typeof $[Q]!=="number"||!Number.isInteger($[Q])||$[Q]<0))return;return Object.fromEntries(x.map((Q)=>[Q,$[Q]]))}function M0(O,$){return typeof O==="number"&&Number.isInteger(O)&&O>=$?O:void 0}function bx(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if(!["applied","discarded","conflicted"].includes(String($.status))||typeof $.updatedAt!=="string")return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},...M0($.changedFiles,0)!==void 0?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}var $$=()=>{let O=new Dx;return O.get("/",($)=>Hx($,async(x)=>{let Q,Z,G=!1,z,U,j=new Promise((F)=>{U=F}),L=()=>{if(Z!==void 0)clearInterval(Z),Z=void 0;Q?.(),Q=void 0},b=(F)=>{if(G)return;G=!0,L(),z?.close(F),U()};x.onAbort(b),z=new A0({write:async(F)=>{await x.writeSSE(F)},onFailure:(F)=>{Bx.warn(`[EventRoutes] SSE egress closed: kind=${F.kind} pendingItems=${F.pendingItems??0} pendingBytes=${F.pendingBytes??0}`),b(F)}});let w=(F,P)=>{z?.observe({data:JSON.stringify({type:F,properties:P})})};Q=S.subscribe((F)=>{if(!wx.has(F.type))return;if(F.type==="permission.asked"||F.type==="question.required"||F.type==="elicitation.required"){let n=F.properties.requestId;if(typeof n!=="string"||!n)return;w("interaction.pending",{sessionId:F.sessionId,projectPath:F.projectPath,interactionType:F.type==="question.required"?"question":F.type==="elicitation.required"?"elicitation":"permission",requestId:n});return}if(F.type==="interaction.resolved"){let n=F.properties.requestId;if(typeof n!=="string"||!n)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,requestId:n});return}if(F.type==="session.created"||F.type==="session.deleted"){w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath});return}if(F.type==="session.updated"){let n=F.properties.title,$O=F.properties.taskPriority,PO=F.properties.taskKind,s=F.properties.taskDueAt,lO=typeof n==="string"&&Boolean(n.trim()),wO=Mx.has(String($O)),N=Tx.has(String(PO)),NO=s===null||typeof s==="string"&&Number.isFinite(Date.parse(s));if(!lO&&!wO&&!N&&!NO)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,...lO?{title:n}:{},...wO?{taskPriority:$O}:{},...N?{taskKind:PO}:{},...NO?{taskDueAt:s}:{}});return}if(F.type==="task.delivery"){let n=bx(F.properties.taskDelivery);if(!n)return;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,taskDelivery:n,...F.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof F.properties.updatedAt==="string"?{updatedAt:F.properties.updatedAt}:{}});return}if(F.type==="schedule.fired"){let n=F.properties.scheduleId,$O=F.properties.firedAt;if(typeof n!=="string"||typeof $O!=="string")return;w(F.type,{scheduleId:n,firedAt:$O,sessionId:F.sessionId,projectPath:F.projectPath,...typeof F.properties.runId==="string"?{runId:F.properties.runId}:{},...typeof F.properties.status==="string"?{status:F.properties.status}:{}});return}let P=F.properties.taskStatus;if(typeof P!=="string"||!Ax.has(P))return;let ZO=jx(F.properties.taskDiffStat),d=M0(F.properties.taskQueuePosition,1),C=M0(F.properties.taskQueueDepth,0),e=M0(F.properties.taskConcurrencyLimit,1),u=M0(F.properties.taskInFlight,0),YO=typeof F.properties.taskAdmissionPaused==="boolean"?F.properties.taskAdmissionPaused:void 0;w(F.type,{sessionId:F.sessionId,projectPath:F.projectPath,taskStatus:P,...typeof F.properties.taskStatusReason==="string"?{taskStatusReason:F.properties.taskStatusReason}:{},...F.properties.taskFailure&&typeof F.properties.taskFailure==="object"?{taskFailure:F.properties.taskFailure}:{},...typeof F.properties.taskStartedAt==="string"?{taskStartedAt:F.properties.taskStartedAt}:{},...typeof F.properties.taskCompletedAt==="string"?{taskCompletedAt:F.properties.taskCompletedAt}:{},...typeof F.properties.updatedAt==="string"?{updatedAt:F.properties.updatedAt}:{},...ZO?{taskDiffStat:ZO}:{},...d!==void 0?{taskQueuePosition:d}:{},...C!==void 0?{taskQueueDepth:C}:{},...e!==void 0?{taskConcurrencyLimit:e}:{},...u!==void 0?{taskInFlight:u}:{},...YO!==void 0?{taskAdmissionPaused:YO}:{}})});try{if(x.aborted||G)return;if(await z.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),x.aborted||G)return;if(z.finishInitialization({replayed:!1}),x.aborted||G)return;Z=setInterval(()=>{if(x.aborted||G)return;z?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},Lx),await j}finally{b()}})),O};import{Hono as Cx}from"hono";var Sx=V.Object({paused:V.Boolean()}),Q$=()=>{let O=new Cx;return O.get("/health",($)=>{return $.json({healthy:!0,version:Q0()})}),O.get("/info",($)=>{let x=c(),Q=QO();if(Q)mO.configure(Q.maxConcurrentTasks,Q.maxQueuedTasks,Q.maxQueuedTaskBytes);let Z=mO.getStats();return $.json({version:Q0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:x,gitBranch:x$(x),taskAdmission:{inFlight:Z.inFlight,queued:Z.queued,maxConcurrent:Z.maxConcurrent,maxQueued:Z.maxQueued,paused:Z.paused}})}),O.put("/task-admission",async($)=>{let x;try{x=await $.req.json()}catch{throw new _("Invalid request body")}let Q=q(Sx,x);if(!Q.success)throw new _("Invalid task admission control request");mO.setPaused(Q.data.paused);let Z=mO.getStats();return $.json({inFlight:Z.inFlight,queued:Z.queued,maxConcurrent:Z.maxConcurrent,maxQueued:Z.maxQueued,paused:Z.paused})}),O};import Z$ from"node:path";import{Hono as Rx}from"hono";var Ex=V.Object({projectPath:V.String({minLength:1}),action:JO(["trust","revoke"]),expectedDigest:V.Optional(V.String())}),kx=V.Object({projectPath:V.String({minLength:1}),sessionId:V.String({minLength:1}),enabled:V.Boolean()});function V1(O){if(!O||!Z$.isAbsolute(O))throw new _("projectPath must be absolute");return Z$.resolve(O)}function J$(O){if(!O)throw new _("sessionId is required");try{i0(O)}catch($){throw new _($ instanceof Error?$.message:"sessionId is invalid")}return O}async function l0(O){let $=V1(O),x=QO()?.hooks??G$.hooks,Q=await T0.getInstance().loadWorkspaceHooks($,x,{includeBaseForCurrentWorkspace:!1});return C0($,async()=>{b0($);let Z=Z0.getInstance();return Z.loadConfig(Q,$),await j0($),Z.getConfig($)})}function Y$(O,$){let x=Z0.getInstance(),Q=x.getConfig($).enabled,Z=x.isSessionPaused(O,$);return{sessionId:O,projectPath:$,enabled:x.isSessionEnabled(O,$),paused:Z,configEnabled:Q}}var X$=()=>{let O=new Rx;return O.get("/trust",async($)=>{let x=$.req.query("projectPath");if(!x)throw new _("projectPath query parameter is required");return await l0(x),$.json(await Z0.getInstance().getTrustStatus(x))}),O.post("/trust",async($)=>{let x=q(Ex,await $.req.json());if(!x.success)throw new _("Invalid hook trust request");let{projectPath:Q,action:Z,expectedDigest:G}=x.data;await l0(Q);let z=Z0.getInstance(),U;try{U=Z==="trust"?await z.trustProject(Q,G):await z.revokeProjectTrust(Q)}catch(j){if(j instanceof z$)throw new k(j.message);throw j}return $.json(U)}),O.get("/session",async($)=>{let x=V1($.req.query("projectPath")),Q=J$($.req.query("sessionId"));return await l0(x),$.json(Y$(Q,x))}),O.post("/session",async($)=>{let x=q(kx,await $.req.json());if(!x.success)throw new _("Invalid hook session request");let Q=V1(x.data.projectPath),Z=J$(x.data.sessionId);await l0(Q);let G=Z0.getInstance();if(x.data.enabled)G.enableSession(Z,Q);else G.disableSession(Z,Q);return $.json(Y$(Z,Q))}),O};import{Hono as qx}from"hono";var RO=o("Service");function Ix(O){try{return N$(O)}catch{return[]}}function Px(O){if(!c0(O)||!c0(O.reference)||!c0(O.argument))throw Error("Invalid MCP completion request");let $=O.reference.type,x=$==="prompt"&&typeof O.reference.name==="string"?{type:"prompt",name:O.reference.name}:$==="resource"&&typeof O.reference.uri==="string"?{type:"resource",uri:O.reference.uri}:void 0;if(!x||typeof O.argument.name!=="string"||typeof O.argument.value!=="string")throw Error("Invalid MCP completion request");let Q;if(O.context!==void 0){if(!c0(O.context))throw Error("Invalid MCP completion context");Q=Object.create(null);for(let[Z,G]of Object.entries(O.context)){if(typeof G!=="string")throw Error("Invalid MCP completion context");Q[Z]=G}}return{reference:x,argument:{name:O.argument.name,value:O.argument.value},...Q?{context:Q}:{}}}function c0(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}async function hO(O,$){let x=QO()?.mcpServers??{};for(let[Q,Z]of Object.entries(x)){if($&&Q!==$)continue;if(!O.getServerStatus(Q))await O.registerServer(Q,Z,{connect:!1})}}var K$=()=>{let O=new qx;return O.get("/",async($)=>{try{let x=UO.getInstance();await hO(x);let Q=x.getAllServers(),Z=await Promise.all(Array.from(Q.entries()).map(async([G,z])=>({id:G,name:G,status:z.status==="connected"?"connected":z.status==="reconnecting"?"reconnecting":z.status==="connecting"?"connecting":z.lastError?"error":"offline",endpoint:z.config.command?`${z.config.command} ${(z.config.args||[]).join(" ")}`.trim():z.config.url||"Unknown",description:`MCP server: ${G}`,tools:z.tools.map((U)=>U.name),completionSupported:z.client.completionSupported,tasks:z.client.tasks,resources:z.contentCatalog.resources,resourceTemplates:z.contentCatalog.resourceTemplates.map((U)=>({...U,variables:Ix(U.uriTemplate)})),prompts:z.contentCatalog.prompts,connectedAt:z.connectedAt?.toISOString(),error:z.lastError?.message,recovery:z.recovery,logging:z.logging,instructions:z.instructions,oauthEnabled:z.client.oauthEnabled,oauthStatus:await z.client.getOAuthStatus()})));return $.json(Z)}catch(x){return RO.error("[McpRoutes] Failed to get MCP servers:",x),$.json({error:x instanceof Error?x.message:"Failed to get MCP servers"},500)}}),O.post("/:name/connect",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();return await hO(Q,x),await Q.connectServer(x),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to connect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();return await hO(Q,x),await Q.disconnectServer(x),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to disconnect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.get("/:name/logs",async($)=>{try{let x=$.req.param("name"),Q=Number($.req.query("limit")??20),Z=Number($.req.query("afterRevision")??0);if(!Number.isSafeInteger(Q)||Q<1||Q>100||!Number.isSafeInteger(Z)||Z<0)return $.json({error:"Invalid MCP log pagination"},400);let G=UO.getInstance();return await hO(G,x),$.json(G.getLogSnapshot(x,{limit:Q,afterRevision:Z}))}catch(x){return RO.error("[McpRoutes] Failed to get MCP logs:",x),$.json({error:x.message},500)}}),O.post("/:name/logging-level",async($)=>{try{let x=$.req.param("name"),Q=await $.req.json();if(!V$(Q.level))return $.json({success:!1,error:"Invalid MCP logging level"},400);let Z=UO.getInstance();return await hO(Z,x),await Z.setServerLoggingLevel(x,Q.level),$.json({success:!0,level:Q.level})}catch(x){return RO.error("[McpRoutes] Failed to set MCP logging level:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/complete",async($)=>{try{let x=$.req.param("name"),Q=Px(await $.req.json()),Z=UO.getInstance();await hO(Z,x);let G=await Z.complete(x,Q);return $.json(G)}catch(x){return RO.error("[McpRoutes] Failed to complete MCP argument:",x),$.json({error:x.message},400)}}),O.post("/:name/oauth/login",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();await hO(Q,x);let Z=await Q.beginOAuthLogin(x);return $.json({success:!0,flowId:Z.flowId,authorizationUrl:Z.authorizationUrl},202)}catch(x){return RO.error("[McpRoutes] Failed to start MCP OAuth login:",x),$.json({success:!1,error:x.message},400)}}),O.post("/:name/oauth/logout",async($)=>{try{let x=$.req.param("name"),Q=UO.getInstance();return await hO(Q,x),await Q.logoutOAuth(x),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to log out MCP OAuth:",x),$.json({success:!1,error:x.message},400)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name");await UO.getInstance().unregisterServer(x);let Z=QO();if(Z?.mcpServers){let{[x]:G,...z}=Z.mcpServers;await BO().updateConfig({mcpServers:z})}return $.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to delete MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/",async($)=>{try{let x=await $.req.json(),{name:Q,config:Z}=x;if(!Q||!Z)return $.json({success:!1,error:"Missing name or config"},400);await UO.getInstance().registerServer(Q,Z);let z=QO();return await BO().updateConfig({mcpServers:{...z?.mcpServers,[Q]:Z}}),$.json({success:!0})}catch(x){return RO.error("[McpRoutes] Failed to add MCP server:",x),$.json({success:!1,error:x.message},500)}}),O};import{getSupportedThinkingLevels as yx}from"@earendil-works/pi-ai";import{Hono as fx}from"hono";var a0=o("Service");function mx(O,$,x=_$.list()){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,supportedReasoningEfforts:yx($),supportedServiceTiers:F$($),supportedResponseVerbosities:W$($),communicationStyles:x,input:$.input}}function hx(O){D$(O.overrides);let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}function D$(O){let $=O?.streamIdleTimeout;if($!==void 0&&(!Number.isFinite($)||$<1000))throw new _("streamIdleTimeout must be at least 1000ms")}var H$=()=>{let O=new fx;return O.get("/",async($)=>{try{let x=QO();if(!x)throw Error("Config not initialized");let Q=$.get("directory")||c(),[Z,G]=await Promise.all([o0(Q,x),jO(Q)]),z=Z.config.models,U=z.find((w)=>w.id===Z.config.currentModelId)??z[0],j=Z.catalog,L=G.communicationStyles.list(),b=(w)=>mx(w,j.resolveConfig(w),L);return $.json({configured:z.map(b),current:U?b(U):null})}catch(x){a0.error("[ModelsRoutes] Failed to get models:",x);let Q=new t("Failed to get models");return $.json(Q.toObject(),500)}}),O.post("/",async($)=>{let x=cO(),Q,Z;try{let G=await $.req.json(),{provider:z,displayName:U,model:j,overrides:L,apiKey:b,modelProvider:w}=G;if(!z||!j)throw new _("provider and model are required");D$(L);let F;if(w){if(w.id!==z)throw new _("modelProvider.id must match the model provider");if(QO()?.modelProviders[z])throw new _(`model provider already exists: ${z}`);F={name:w.name,baseUrl:w.baseUrl,wireApi:w.wireApi,...w.apiKeyEnv?{apiKeyEnv:w.apiKeyEnv}:{}};try{x.registerModelProvider(z,F,[j]),Z=z}catch(d){throw new _(d instanceof Error?d.message:"Invalid model provider")}}else x.getModel(z,j);if(b?.trim()){if(await x.setApiKey(z,b.trim()),F)Q=z}let P={provider:z,displayName:U||void 0,model:j,overrides:L||void 0},ZO=F?await BO().addModelWithProvider(P,F):await BO().addModel(P);return $.json({success:!0,model:ZO})}catch(G){if(Q)await x.credentials.delete(Q);if(Z){let z=QO();x.configureModelProviders(z?.modelProviders??{},z?.models??[])}throw a0.error("[ModelsRoutes] Failed to add model:",G),G}}),O.put("/:modelId",async($)=>{try{let x=$.req.param("modelId"),Q=await $.req.json(),{displayName:Z,overrides:G,model:z}=Q,U=U$(x);if(!U)throw new _("model config not found");if(z)cO().getModel(U.provider,z);return await BO().updateModel(x,hx({displayName:Z,overrides:G,model:z})),$.json({success:!0})}catch(x){throw a0.error("[ModelsRoutes] Failed to update model:",x),x}}),O.delete("/:modelId",async($)=>{try{let x=$.req.param("modelId");return await BO().removeModel(x),$.json({success:!0})}catch(x){throw a0.error("[ModelsRoutes] Failed to delete model:",x),x}}),O};import{Hono as x2}from"hono";import L$ from"node:path";import{Hono as gx}from"hono";import{streamSSE as ux}from"hono/streaming";import{LRUCache as px}from"lru-cache";import{nanoid as Y0}from"nanoid";var g=o("Service"),vx=V.Object({title:V.Optional(V.String()),projectPath:V.Optional(V.String())}),dx=i$,lx=V.Object({title:V.Optional(V.String()),projectPath:V.Optional(V.String())}),ix=V.Object({projectPath:V.String()}),cx=V.Object({objective:V.String({minLength:1}),tokenBudget:V.Optional(V.Integer({minimum:1})),permissionMode:V.Optional(JO(["default","autoEdit","plan","yolo"]))}),ax=V.Union([V.Object({action:V.Literal("pause")}),V.Object({action:V.Literal("resume")}),V.Object({action:V.Literal("edit"),objective:V.String({minLength:1})})]),r=new Map,G0,CO=new Map,IO=new Map,bO=new Map,e0=new px({max:100,ttl:1800000});function B$(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function DO(O){if(!O)return;return CO.get(O)??e0.get(O)}function ox(O){if(CO.get(O.id)!==O)return;CO.delete(O.id),e0.set(O.id,O)}function nx(O){CO.delete(O),e0.delete(O)}function _O(O){return O?.status==="queued"||O?.status==="running"||O?.status==="waiting_permission"}function k0(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let x=O.pendingPermission;if(O.pendingPermission=void 0,x?.resolve({approved:!1,reason:R$}),x)S.publish(B$(O),"interaction.resolved",{requestId:x.permissionId});return O.abortController.abort($),O.status="cancelled",S.publish(B$(O),"run.cancelled",{runId:O.id}),!0}function t$(O,$=!1){let{permissionId:x,details:Q}=O;if(Q.type==="askUserQuestion"&&Q.questions)return{type:"question.required",properties:{requestId:x,toolCallId:Q.toolCallId??x,questions:Q.questions,details:Q,...$?{replayed:!0}:{}}};if(Q.type==="mcpElicitation"&&Q.mcpElicitation)return{type:"elicitation.required",properties:{requestId:x,toolCallId:Q.toolCallId??x,elicitation:Q.mcpElicitation,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:Q.toolName,description:Q.message,args:Q.args,details:Q,...$?{replayed:!0}:{}}}}function tx(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 sx(){for(let O of CO.values())k0(O,"route-reset");CO.clear();for(let O of IO.values())O.controller.abort("route-reset");IO.clear(),e0.clear(),G0=void 0,r.clear()}function rx(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O,x=$.code,Q=$.reason,Z=$.scope,G=$.kind,z=$.limit;if(x!=="tool_busy"&&x!=="tool_batch_full"||Q!=="queue_full"&&Q!=="wait_timeout"&&Q!=="turn_limit"||Z!=="global"&&Z!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(z)||z<=0||G!==void 0&&G!=="readonly"&&G!=="write"&&G!=="execute")return;return{code:x,reason:Q,scope:Z,retryable:$.retryable,...G===void 0?{}:{kind:G},limit:z}}var q0=(O,$)=>{if(!$||typeof $!=="object")return $;let x={...$},Q=rx(x.tool_admission);if(Q)x.tool_admission=Q;else delete x.tool_admission;if(O==="Bash"){let z={},U=["message","signal","status","summary"],j=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],L=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let w of U){let F=x[w];if(typeof F==="string")z[w]=F.slice(0,8192)}for(let w of j){let F=x[w];if(typeof F==="boolean")z[w]=F}for(let w of L){let F=x[w];if(typeof F==="number"&&Number.isSafeInteger(F)&&F>=0)z[w]=F}if(x.exit_code===null||typeof x.exit_code==="number"&&Number.isSafeInteger(x.exit_code))z.exit_code=x.exit_code;if(x.terminal_transport==="local"||x.terminal_transport==="acp"||x.terminal_transport==="local_fallback")z.terminal_transport=x.terminal_transport;if(x.background_reason==="explicit"||x.background_reason==="foreground_budget")z.background_reason=x.background_reason;for(let w of["bash_id","shell_id"]){let F=x[w];if(typeof F==="string"&&F.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(F))z[w]=F}if(Q)z.tool_admission=Q;let b=x.background_shell_admission;if(b&&typeof b==="object"&&!Array.isArray(b)){let w=b;if(w.code==="background_shell_busy"&&(w.scope==="session"||w.scope==="global")&&w.retryable===!0&&Number.isSafeInteger(w.limit)&&w.limit>0)z.background_shell_admission={code:w.code,scope:w.scope,retryable:w.retryable,limit:w.limit}}return z}let Z=200000,G=(z,U)=>typeof z==="number"&&Number.isSafeInteger(z)&&z>=0&&z<=U?z:0;if(typeof x.oldContent==="string"&&x.oldContent.length>Z)delete x.oldContent;if(typeof x.newContent==="string"&&x.newContent.length>Z)delete x.newContent;if(x.mcpResult&&typeof x.mcpResult==="object"&&!Array.isArray(x.mcpResult)){let z=x.mcpResult,U=Array.isArray(z.artifacts)?z.artifacts.slice(0,64).flatMap((j)=>{if(!j||typeof j!=="object"||Array.isArray(j))return[];let L=j,b=new Set(["text","image","audio","resource"]);if(typeof L.id!=="string"||!/^[a-f0-9]{64}$/.test(L.id)||typeof L.sha256!=="string"||L.sha256!==L.id||typeof L.kind!=="string"||!b.has(L.kind)||G(L.size,67108864)!==L.size||typeof L.persisted!=="boolean")return[];return[{id:L.id.slice(0,128),sha256:L.sha256.slice(0,128),kind:L.kind,size:L.size,persisted:L.persisted,...typeof L.mimeType==="string"?{mimeType:L.mimeType.slice(0,256)}:{},...typeof L.sourceUri==="string"?{sourceUri:L.sourceUri.slice(0,8192)}:{},...typeof L.path==="string"?{path:L.path.slice(0,8192)}:{}}]}):[];x.mcpResult={isError:z.isError===!0,contentCount:G(z.contentCount,64),textBytes:G(z.textBytes,4194304),structuredBytes:G(z.structuredBytes,4194304),artifactCount:G(z.artifactCount,64),truncated:z.truncated===!0,binaryOmitted:z.binaryOmitted===!0,artifacts:U}}else delete x.mcpResult;return x};function ex(O){let $=typeof O.seq==="number"?{seq:O.seq}:{};if(O.type==="part_created"&&O.data.partType==="tool_call"){let x=O.data.payload;return{type:"tool.start",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}}}if(O.type==="part_created"&&O.data.partType==="tool_result"){let x=O.data.payload,Q=x.toolName??"unknown",Z=M1(x),G=P0(y0(Q,Z),I0);return{type:"tool.result",...$,properties:{messageId:O.data.messageId,toolCallId:x.toolCallId??O.data.partId,toolName:Q,success:Z.success,status:Z.success?"completed":"failed",summary:Z.metadata?.summary,output:f0(G),metadata:q0(Q,Z.metadata)}}}return{type:`committed.${O.type}`,...$,properties:{event:O}}}function O2(O,$,x){switch(x.kind){case"tool_start":if("function"in x.toolCall)S.publish(O,"subagent.update",{subagentSessionId:$,toolName:x.toolCall.function.name}),S.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,arguments:x.toolCall.function.arguments,toolKind:x.toolKind});break;case"tool_result":if("function"in x.toolCall)S.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,success:x.result.success,summary:x.result.metadata?.summary,output:f0(P0(y0(x.toolCall.function.name,x.result),I0)),metadata:q0(x.toolCall.function.name,x.result.metadata)});break;case"tool_progress":if("function"in x.toolCall)S.publish(O,"subagent.tool.progress",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,...x.update});break;case"content_delta":S.publish(O,"subagent.delta",{subagentSessionId:$,delta:x.delta});break;case"thinking_delta":S.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:x.delta});break;case"stream_end":S.publish(O,"subagent.stream.end",{subagentSessionId:$});break;case"provider_admission":S.publish(O,"subagent.provider.admission",{subagentSessionId:$,phase:x.phase,requestClass:x.requestClass,resource:x.resource,scope:x.scope,reason:x.reason,queuePosition:x.queuePosition,queueDepth:x.queueDepth,inFlight:x.inFlight,limit:x.limit,waitMs:x.waitMs,maxWaitMs:x.maxWaitMs,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_circuit":S.publish(O,"subagent.provider.circuit",{subagentSessionId:$,phase:x.phase,reason:x.reason,statusCode:x.statusCode,retryAfterMs:x.retryAfterMs,nextProbeAt:x.nextProbeAt,openDurationMs:x.openDurationMs,sampleCount:x.sampleCount,failureCount:x.failureCount,recoveryRemainingMs:x.recoveryRemainingMs});break;case"provider_retry":S.publish(O,"subagent.provider.retry",{subagentSessionId:$,phase:x.phase,attempt:x.attempt,maxRetries:x.maxRetries,reason:x.reason,statusCode:x.statusCode,delayMs:x.delayMs,nextRetryAt:x.nextRetryAt,mode:x.mode,recoveryBudgetMs:x.recoveryBudgetMs,recoveryElapsedMs:x.recoveryElapsedMs,recoveryRemainingMs:x.recoveryRemainingMs,exhaustedBy:x.exhaustedBy});break;case"provider_stall":S.publish(O,"subagent.provider.stall",{subagentSessionId:$,phase:x.phase,stallCount:x.stallCount,durationMs:x.durationMs,warningAfterMs:x.warningAfterMs,timeoutMs:x.timeoutMs,outputStarted:x.outputStarted});break;case"action_stationarity":S.publish(O,"subagent.action.stationarity",{subagentSessionId:$,phase:x.phase,toolName:x.toolName,runLength:x.runLength,nudgeThreshold:x.nudgeThreshold,haltThreshold:x.haltThreshold,progressAware:x.progressAware});break;case"mcp_catalog_changed":S.publish(O,"subagent.mcp.catalog.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_content_changed":S.publish(O,"subagent.mcp.content.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,contentKind:x.contentKind,added:x.added,removed:x.removed,updated:x.updated});break;case"mcp_resource_updated":S.publish(O,"subagent.mcp.resource.updated",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,uri:x.uri});break;case"mcp_connection_changed":S.publish(O,"subagent.mcp.connection.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,phase:x.phase,reason:x.reason,attempt:x.attempt,maxAttempts:x.maxAttempts,nextRetryAt:x.nextRetryAt,error:x.error});break;case"mcp_log":S.publish(O,"subagent.mcp.log",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,level:x.level,logger:x.logger,message:x.message,projectedBytes:x.projectedBytes,dataSha256:x.dataSha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted,timestamp:x.timestamp,synthetic:x.synthetic});break;case"mcp_instructions_changed":S.publish(O,"subagent.mcp.instructions.changed",{subagentSessionId:$,revision:x.revision,serverName:x.serverName,action:x.action,reason:x.reason,text:x.text,sourceBytes:x.sourceBytes,projectedBytes:x.projectedBytes,sha256:x.sha256,truncated:x.truncated,detailsOmitted:x.detailsOmitted});break;case"mcp_task_changed":S.publish(O,"subagent.mcp.task.changed",{subagentSessionId:$,revision:x.revision,taskId:x.taskId,serverName:x.serverName,toolName:x.toolName,status:x.status,statusMessage:x.statusMessage,createdAt:x.createdAt,updatedAt:x.updatedAt,completedAt:x.completedAt,hasResult:x.hasResult,error:x.error});break;case"project_rules_loaded":S.publish(O,"subagent.project.rules.loaded",{subagentSessionId:$,files:x.files,triggerPaths:x.triggerPaths,blockedWrite:x.blockedWrite});break;default:break}}function R0(O,$="projectPath"){if(!L$.isAbsolute(O))throw new _(`${$} must be absolute`);return L$.resolve(O)}function w1(O){try{i0(O)}catch($){throw new _($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function GO(O){return{sessionId:O.id,projectPath:O.projectPath}}function E0(O,$,x){return{id:O.sessionId,projectPath:O.projectPath,title:O.title??`Session ${O.sessionId.slice(0,6)}`,createdAt:new Date(O.firstMessageTime),updatedAt:new Date(O.lastMessageTime),rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,taskStatus:O.taskStatus,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,pendingInteraction:O.pendingInteraction,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:O.taskQueuePosition,taskQueueDepth:O.taskQueueDepth,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,taskWorktree:x,messages:$}}function N1(O){return O.flatMap(($)=>{if(!k$($)||$.role==="system"||$.role==="tool"&&$.name===z0)return[];let x=$.tool_calls?.filter((z)=>!("function"in z)||z.function.name!==z0),Q=typeof $.content==="string"?$.content.trim():"";if($.role==="assistant"&&$.tool_calls?.length&&!x?.length&&!Q&&!$.reasoningContent&&!$.metadata)return[];let Z={...$,...$.tool_calls?{tool_calls:x&&x.length>0?x:void 0}:{}};if($.role==="tool"){let z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0,U=$.name??(typeof z?.toolName==="string"?z.toolName:"unknown");if(z!==void 0&&(Object.hasOwn(z,"output")||Object.hasOwn(z,"error"))){let L=M1(z),b=P0(y0(U,L),I0);return[{...Z,name:U,content:f0(b),metadata:q0(U,{...L.metadata,status:L.success?"completed":"failed"})}]}return[{...Z,name:U,metadata:q0(U,z)}]}let G=I$($.metadata);return[G?{...Z,content:q$(G)}:Z]})}function X0(O,$){O.title=$.title??O.title,O.taskStatus=$.taskStatus,O.taskStatusReason=$.taskStatusReason,O.taskFailure=$.taskFailure,O.taskStartedAt=$.taskStartedAt,O.taskCompletedAt=$.taskCompletedAt,O.taskPromptSummary=$.taskPromptSummary,O.taskPriority=$.taskPriority,O.taskKind=$.taskKind,O.taskDueAt=$.taskDueAt,O.taskModelId=$.taskModelId,O.selectedModelId=$.selectedModelId,O.permissionMode=$.permissionMode,O.reasoningEffort=$.reasoningEffort,O.serviceTier=$.serviceTier,O.responseVerbosity=$.responseVerbosity,O.communicationStyle=$.communicationStyle,O.communicationStyleDigest=$.communicationStyleDigest,O.projectInstructionsDigest=$.projectInstructionsDigest,O.pendingInteraction=$.pendingInteraction,O.taskRetryAvailable=$.taskRetryAvailable,O.taskRetriedFrom=$.taskRetriedFrom,O.taskDelivery=$.taskDelivery,O.taskIsolation=$.taskIsolation,O.taskSourceProjectPath=$.taskSourceProjectPath,O.taskWorktreePath=$.taskWorktreePath,O.taskWorktreeBranch=$.taskWorktreeBranch,O.taskBaseCommit=$.taskBaseCommit,O.taskDiffStat=$.taskDiffStat,O.taskQueuePosition=$.taskQueuePosition,O.taskQueueDepth=$.taskQueueDepth,O.taskConcurrencyLimit=$.taskConcurrencyLimit,O.archivedAt=$.archivedAt,O.archivedBySessionId=$.archivedBySessionId,O.updatedAt=new Date($.lastMessageTime)}async function tO(O){let $=await R.findSessionMetadata(O.id,O.projectPath);if($)X0(O,$)}function aO(O){let $=DO(O.currentRunId),x=$?.status==="waiting_permission"?"running":$?.status??O.taskStatus;return{sessionId:O.id,projectPath:O.projectPath,title:O.title,rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,status:void 0,taskStatus:x,taskStatusReason:O.taskStatusReason,taskFailure:O.taskFailure,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,taskPromptSummary:O.taskPromptSummary,taskPriority:O.taskPriority,taskKind:O.taskKind,taskDueAt:O.taskDueAt,taskModelId:O.taskModelId,selectedModelId:O.selectedModelId,permissionMode:O.permissionMode,reasoningEffort:O.reasoningEffort,serviceTier:O.serviceTier,responseVerbosity:O.responseVerbosity,communicationStyle:O.communicationStyle,communicationStyleDigest:O.communicationStyleDigest,projectInstructionsDigest:O.projectInstructionsDigest,taskRetryAvailable:O.taskRetryAvailable,taskRetriedFrom:O.taskRetriedFrom,taskDelivery:O.taskDelivery,taskIsolation:O.taskIsolation,taskSourceProjectPath:O.taskSourceProjectPath,taskWorktreePath:O.taskWorktreePath,taskWorktreeBranch:O.taskWorktreeBranch,taskBaseCommit:O.taskBaseCommit,taskDiffStat:O.taskDiffStat,taskQueuePosition:x==="queued"?O.taskQueuePosition:void 0,taskQueueDepth:x==="queued"?O.taskQueueDepth:void 0,taskConcurrencyLimit:O.taskConcurrencyLimit,archivedAt:O.archivedAt,archivedBySessionId:O.archivedBySessionId,pendingInteraction:$?.pendingPermission?{type:$.pendingPermission.details.type==="askUserQuestion"?"question":$.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:$.pendingPermission.permissionId}:O.pendingInteraction,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function KO(O,$){if(w1(O),$!==void 0){let Q=gO({sessionId:O,projectPath:R0($)});if(r.has(p(Q)))return Q;let Z=await R.findSessionMetadata(Q.sessionId,Q.projectPath);if(!Z)throw new f("Session",O);return gO({sessionId:Z.sessionId,projectPath:Z.projectPath})}let x=new Map;for(let Q of r.values()){if(Q.id!==O)continue;let Z=GO(Q);x.set(p(Z),Z)}for(let Q of await R.listSessions()){if(Q.sessionId!==O)continue;let Z=gO({sessionId:Q.sessionId,projectPath:Q.projectPath});x.set(p(Z),Z)}if(x.size===0)try{let Q=await R.findSessionMetadata(O);if(!Q)throw new f("Session",O);return gO({sessionId:Q.sessionId,projectPath:Q.projectPath})}catch(Q){if(Q instanceof f)throw Q;if(Q instanceof Error&&Q.message.startsWith("Ambiguous session ID:"))throw new LO;throw Q}if(x.size>1)throw new LO;return x.values().next().value}function A1(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
7
- `)}function w$(O,$){let x=($??[]).filter((Z)=>Z.type==="image"&&typeof Z.content==="string").map((Z)=>({type:"image_url",image_url:{url:Z.content}}));if(x.length===0)return O;let Q=[];if(O.trim())Q.push({type:"text",text:O});return Q.push(...x),Q}var s$=()=>{sx();let O=new gx;O.onError((J,K)=>{if(J instanceof J0){let Y=new kO("Session runtime capacity is full",{resource:J.resource,limit:J.limit});return K.json(Y.toObject(),429)}if(J instanceof xO)return K.json(J.toObject(),J.statusCode);return g.error("[SessionRoutes] Unhandled route error:",J),K.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,x=new Map,Q=new Map,Z=new Map,G=new K1,z=new K1,U=QO(),j=new n$({maxResident:U?.maxResidentSessionRuntimes??T$,idleMs:U?.sessionRuntimeIdleMs??j$}),L=new g$,b=setInterval(()=>{j.sweepIdle().catch((J)=>{g.warn("[SessionRoutes] Session Runtime idle sweep failed:",J)})},b$);b.unref?.();let w,F=async(J)=>{let K;try{K=L.enter()}catch{throw new qO}try{return await J()}finally{K.release()}};O.use("*",async(J,K)=>{if(J.req.method==="GET"||J.req.method==="HEAD")return K();return F(K)});let P=(J,K)=>G.runExclusive(p(J),K),ZO=(J,K)=>z.runExclusive(p(J),K),d=(J)=>[...CO.values()].some((K)=>K.sessionId===J.sessionId&&K.projectPath===J.projectPath&&_O(K)),C=async(J,K,Y)=>{let X=Q.get(K);if(!X)X=(async()=>{if($.get(K)===Y)$.delete(K);for(let[H,D]of $)if(D===Y)$.delete(H);let W=GO(J);if(r.get(K)===J&&!d(W)&&!IO.has(K)&&!bO.has(K))r.delete(K);if(await Y.dispose(),$.size===0)await UO.getInstance().disconnectAll()})().finally(()=>{if(Q.get(K)===X)Q.delete(K)}),Q.set(K,X);await X},e=async(J,K={})=>{let Y=GO(J),X=p(Y);await Q.get(X);let W=j.acquire(X);if(W){if($.get(X)!==W.value)throw W.release(),Error("Session Runtime residency identity is inconsistent");return W}if(j.owns(X))throw new J0(j.getStats().maxResident);let H=x.get(X);if(!H){let D=K.communicationStyle??J.communicationStyle;H=(async()=>{let B=await j.reserve(X,{surface:"web",allowEviction:!0});try{let A=await S0.create({sessionId:J.id,workspaceRoot:J.projectPath,...J.selectedModelId??J.taskModelId?{modelId:J.selectedModelId??J.taskModelId}:{},permissionMode:K.permissionMode??J.permissionMode??"default",...J.reasoningEffort?{reasoningEffort:J.reasoningEffort}:{},...J.serviceTier?{serviceTier:J.serviceTier}:{},...J.responseVerbosity?{responseVerbosity:J.responseVerbosity}:{},...D?{communicationStyle:D}:{},...D===J.communicationStyle&&J.communicationStyleDigest?{communicationStyleDigest:J.communicationStyleDigest}:{},...J.projectInstructionsDigest?{projectInstructionsDigest:J.projectInstructionsDigest}:{},...J.taskWorktree?{taskWorktree:J.taskWorktree}:{},...J.taskIsolation?{taskIsolation:J.taskIsolation}:{},...J.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:J.id}}:{}}),M=B.commit({key:X,surface:"web",value:A,canEvict:()=>!d(Y)&&!IO.has(X)&&!bO.has(X)&&!x.has(X)&&!Q.has(X)&&A.isIdleForResidency(),dispose:()=>C(J,X,A)});return $.set(X,A),{runtime:A,claimLease:()=>{if(M){let y=M;return M=void 0,y}let T=j.acquire(X);if(!T||T.value!==A)throw Error("Initialized Session Runtime lost residency");return T}}}catch(A){throw B.cancel(),A}})(),x.set(X,H)}try{return(await H).claimLease()}finally{if(x.get(X)===H)x.delete(X)}},u=async(J,K,Y={})=>{let X=await e(J,Y);try{return await K(X.value)}finally{X.release()}},YO=async(J,K)=>{let Y=p(GO(J)),X=x.get(Y);if(X)await X.catch(()=>{return});x.delete(Y);let W=K??$.get(Y);if(!W)return;if(!await j.remove(Y,W))throw Error(`Session Runtime is pinned and cannot be disposed: ${Y}`)},n=async(J)=>{let K=p(J),Y=r.get(K);if(Y)return Y;let X=Z.get(K);if(!X)X=(async()=>{let W=await R.findSessionMetadata(J.sessionId,J.projectPath);if(!W)throw new f("Session",J.sessionId);let[H,D]=await Promise.all([R.loadSession(J.sessionId,J.projectPath),R.findSessionTaskWorktree(J.sessionId,J.projectPath)]),B=E0(W,H,D);return r.set(K,B),B})(),Z.set(K,X);try{return await X}finally{if(Z.get(K)===X)Z.delete(K)}},$O=async(J,K)=>{let Y=await KO(J,K);try{await R.assertSessionWritable(Y.sessionId,Y.projectPath)}catch(X){if(X instanceof _1)throw new k(X.message);throw X}return n(Y)},PO=async(J,K)=>{if(J.permissionMode===K)return;let Y=await R.setSessionPermissionMode(J.id,J.projectPath,K);J.permissionMode=Y.permissionMode,J.updatedAt=new Date(Y.lastMessageTime),S.publish(GO(J),"session.updated",{permissionMode:K})},s=(J,K,Y,X={})=>{if(!L.stats().accepting)throw new qO;let W=Y0(12),H={id:W,sessionId:J.id,projectPath:J.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:J.taskIsolation!==void 0&&X.runtimeLease!==void 0,createdAt:new Date};if(J.taskIsolation&&X.runtimeLease){let D=X.runtimeLease.value,B=mO.admit({key:`${J.projectPath}\x00${J.id}`,...D.getTaskAdmissionLimits(),pendingBytes:u$({content:K,outputSchema:X.outputSchema,pendingMessages:D.getPendingSteeringMessages()}),signal:H.abortController.signal,onUpdate:(M)=>{H.status=M.state,J.taskStatus=M.state,J.taskQueuePosition=M.queuePosition,J.taskQueueDepth=M.queueDepth,J.taskConcurrencyLimit=M.maxConcurrent,H.taskAdmissionUpdate=(H.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await D.setTaskAdmission(M)}).catch((T)=>{g.warn(`[SessionRoutes] Failed to persist admission for ${J.id}:`,T)})}});H.taskAdmission=B;let A=B.getSnapshot();H.status=A.state,J.taskStatus=A.state,J.taskQueuePosition=A.queuePosition,J.taskQueueDepth=A.queueDepth,J.taskConcurrencyLimit=A.maxConcurrent}return CO.set(W,H),J.currentRunId=W,H.completion=$2(H,J,K,Y,e,{pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:H.taskAdmission,runtimeLease:X.runtimeLease,disposeRuntime:YO}).catch((D)=>{g.error(`[SessionRoutes] Run ${W} failed:`,D)}),H},lO=async(J)=>{let K;if(J.outputSchema)try{K=U1(J.outputSchema).schema}catch(h){throw new _(h instanceof Error?h.message:"Invalid output schema")}let Y=F1("task",12),X=R0(J.sourceProjectPath),W=J.modelId?.trim(),H=QO();if(!H)throw new _("Config not initialized");let[D,B]=await Promise.all([o0(X,H),jO(X)]);if(W&&!D.config.models.some((h)=>h.id===W))throw new _(`Task model not found: ${W}`);let A=W||D.config.models.find((h)=>h.id===D.config.currentModelId)?.id||D.config.models[0]?.id;if(!A)throw new _("No model is configured. Add or select a model before dispatching a task.");let M=D.config.models.find((h)=>h.id===A);if(!M)throw new _(`Task model not found: ${A}`);let T=J.reasoningEffort??"off",y=J.serviceTier??"auto",WO=J.responseVerbosity??"auto",yO=J.communicationStyle??"auto",TO,XO=B.projectRules?.staticRules(X),OO=XO&&XO.files.length>0?XO.provenanceSha256:void 0;try{let h=D.catalog.resolveConfig(M);C$(h,T),M$(h,y),A$(h,WO);let l=S$(yO,B.communicationStyles);TO=l.source==="built-in"?void 0:l.contentSha256}catch(h){throw new _(h instanceof Error?h.message:"Invalid reasoning effort")}let O0={version:1,prompt:J.prompt,...J.title?{title:J.title}:{},...J.taskPriority?{taskPriority:J.taskPriority}:{},...J.taskKind?{taskKind:J.taskKind}:{},...J.taskDueAt?{taskDueAt:J.taskDueAt}:{},sourceProjectPath:X,isolation:J.isolation,permissionMode:J.permissionMode,modelId:A,reasoningEffort:T,serviceTier:y,responseVerbosity:WO,communicationStyle:yO,...TO?{communicationStyleDigest:TO}:{},...OO?{projectInstructionsDigest:OO}:{},...J.attachments?{attachments:J.attachments.map((h)=>({...h}))}:{},...K?{outputSchema:K}:{}},E,m,I;try{let h=await v$.createSessionTask({sessionId:Y,prompt:J.prompt,title:J.title,taskPriority:J.taskPriority,taskKind:J.taskKind,taskDueAt:J.taskDueAt,sourceProjectPath:X,isolation:J.isolation,dispatch:O0,retriedFrom:J.retriedFrom}),{metadata:l}=h;E=h.taskWorktree,m=E0(l,[],E);let v=GO(m);r.set(p(v),m),S.publish(v,"task.status",{taskStatus:l.taskStatus,updatedAt:l.lastMessageTime});let i=w$(J.prompt,J.attachments);I=await e(m);let fO=I.value,a=K?await fO.prepareInputTurn(i,{outputSchema:K}):await fO.prepareInputTurn(i);if(!a.accepted)throw new k(`Task prompt was not accepted: ${a.reason}`);let zO=s(m,i,J.permissionMode,{preparedInputTurn:a,runtimeLease:I,outputSchema:K});return I=void 0,await zO.taskAdmissionUpdate,{session:aO(m),runId:zO.id,messageId:a.messageId,status:zO.status==="queued"?"queued":"running",queuePosition:m.taskQueuePosition,queueDepth:m.taskQueueDepth,maxConcurrentTasks:m.taskConcurrencyLimit}}catch(h){if(I?.release(),I=void 0,(h instanceof B1||h instanceof J0)&&m){let l=GO(m),v=p(l);if(E)await EO.exit({sessionId:m.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await YO(m).catch(()=>{return}),await R.deleteSession(m.id,m.projectPath).catch(()=>{return}),r.delete(v),new kO(h instanceof J0?"Session runtime capacity is full":"Task admission capacity is full",{resource:h.resource,limit:h.limit})}if(m){let l=await R.findSessionMetadata(m.id,m.projectPath).catch(()=>{return});if(!l||l.taskStatus==="queued"){let v=t0(h),i=await R.updateSessionMetadata(m.id,m.projectPath,{taskStatus:"failed",taskStatusReason:v.message,taskFailure:v,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});m.taskStatus=i?.taskStatus??"failed",m.taskStatusReason=i?.taskStatusReason??v.message,m.taskFailure=i?.taskFailure??v,m.taskCompletedAt=i?.taskCompletedAt}else m.taskStatus=l.taskStatus,m.taskStatusReason=l.taskStatusReason,m.taskFailure=l.taskFailure,m.taskCompletedAt=l.taskCompletedAt}throw h}},wO=(J)=>F(()=>lO(J)),N=async(J,K)=>{let Y=await KO(J,K),X=await R.findSessionMetadata(Y.sessionId,Y.projectPath);if(!X)throw new f("Session",Y.sessionId);if(!["failed","interrupted","cancelled"].includes(X.taskStatus))throw new k(`Task cannot be retried while status is ${X.taskStatus}`);let W=await R.findSessionTaskDispatch(Y.sessionId,Y.projectPath);if(!W)throw new k("Task retry payload is unavailable");return wO({prompt:W.prompt,title:X.title??W.title,taskPriority:X.taskPriority??W.taskPriority,taskKind:X.taskKind??W.taskKind,taskDueAt:X.taskDueAt,sourceProjectPath:W.sourceProjectPath,isolation:W.isolation,permissionMode:W.permissionMode,modelId:W.modelId,reasoningEffort:W.reasoningEffort,serviceTier:W.serviceTier,responseVerbosity:W.responseVerbosity,communicationStyle:W.communicationStyle,attachments:W.attachments,outputSchema:W.outputSchema,retriedFrom:Y})},NO=(J,K)=>F(()=>N(J,K)),u1=(J,K,Y)=>F(async()=>{let X=await KO(J,Y);if(!await R.findSessionMetadata(X.sessionId,X.projectPath))throw new f("Session",X.sessionId);let H=await R.updateSessionMetadata(X.sessionId,X.projectPath,K),D=r.get(p(X));if(D)X0(D,H);return S.publish(X,"session.updated",{...H.title?{title:H.title}:{},...H.taskPriority?{taskPriority:H.taskPriority}:{},...H.taskKind?{taskKind:H.taskKind}:{},taskDueAt:H.taskDueAt??null}),D?aO(D):{...H,isActive:!1}}),Q1=async(J,K)=>{let Y=await $O(J,K);if(!Y.taskWorktree)throw new _("Session does not have a task worktree");try{await EO.restoreSession(Y.taskWorktree);let X=await EO.getDiffArtifact(Y.id);if(!X)throw new k("Task diff artifact is unavailable");return{sessionId:Y.id,projectPath:Y.projectPath,...X}}catch(X){if(X instanceof k)throw X;throw g.error("[SessionRoutes] Failed to load task diff artifact:",X),new k("Task diff artifact is unavailable")}},L0=async(J,K,Y)=>{let X=await KO(J,Y);return ZO(X,async()=>{let W=await $O(X.sessionId,X.projectPath);if(["queued","running"].includes(W.taskStatus))throw new k(`Task artifacts cannot be delivered while status is ${W.taskStatus}`);if(W.taskDelivery?.status==="applied")throw new k("Task changes have already been applied");if(W.taskDelivery?.status==="discarded")throw new k("Task changes have already been discarded");if(!W.taskWorktree)throw new k("Task worktree is unavailable");let H=async(D,B=!1)=>{let A=await R.updateSessionMetadata(W.id,W.projectPath,{taskDelivery:D,...B?{taskWorktree:null}:{}});if(X0(W,A),B)W.taskWorktree=void 0;return S.publish(X,"task.delivery",{taskDelivery:D,...B?{taskWorktreeRemoved:!0}:{},updatedAt:A.lastMessageTime}),aO(W)};try{if(K==="discard"){try{await EO.restoreSession(W.taskWorktree)}catch(A){return g.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${W.id}:`,A),H({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:W.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let B=await EO.exit({sessionId:W.id,action:"remove",discardChanges:!0});return H({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:B.discardedFiles??0,message:"Task worktree removed"},!0)}try{await EO.restoreSession(W.taskWorktree)}catch(B){throw g.warn(`[SessionRoutes] Task worktree is unavailable for ${W.id}:`,B),new L1("artifact_unavailable","Task worktree is unavailable")}let D=await EO.apply(W.id);return H({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:D.sourceCommit,changedFiles:D.changedFiles,message:"Task changes applied to the source workspace"})}catch(D){if(D instanceof L1)throw await H({status:"conflicted",updatedAt:new Date().toISOString(),message:D.message}),new k(D.message);throw D}})},u0=(J,K,Y)=>F(()=>L0(J,K,Y)),p0=async(J)=>{let K=DO(J.currentRunId);if(_O(K))return;if(J.taskIsolation&&J.taskStatus!=="queued"&&J.taskStatus!=="running")return;let Y=await S0.hasPendingInbox(J.projectPath,J.id),X=!Y&&await S0.hasActiveGoal(J.projectPath,J.id);if(!Y&&!X)return;let W=await e(J),H=!1;try{let D=W.value,B=DO(J.currentRunId);if(_O(B))return;if(Y&&D.getPendingSteeringCount()===0)await D.reloadPendingInbox();let A=D.getPendingSteeringCount()>0,M=A?null:await D.getGoal(),T=M?.status==="active"||M?.status==="verifying";if(!A&&!T||D.hasTurnOwner())return;s(J,"",J.permissionMode??"default",{pendingInputOnly:A,goalContinuationOnly:T,runtimeLease:W}),H=!0}finally{if(!H)W.release()}},SO=async(J)=>{let K;try{K=L.enter()}catch{return}try{await p0(J)}finally{K.release()}};G0=SO;let Z1=async()=>{let J={scheduled:0,failed:0,deferred:0};if(!L.stats().accepting)return J;let K=(await R.listSessions({taskStatus:"queued"})).filter((Y)=>Y.taskIsolation!==void 0).sort((Y,X)=>Y.firstMessageTime.localeCompare(X.firstMessageTime)||Y.projectPath.localeCompare(X.projectPath)||Y.sessionId.localeCompare(X.sessionId));for(let[Y,X]of K.entries()){let W={sessionId:X.sessionId,projectPath:X.projectPath};try{if(!await S0.hasPendingInbox(X.projectPath,X.sessionId)){let D=t0("Queued task input is missing");await R.updateSessionMetadata(X.sessionId,X.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),J.failed++;continue}let H=await n(W);if(await SO(H),H.currentRunId)J.scheduled++}catch(H){if(H instanceof B1||H instanceof J0){J.deferred+=K.length-Y;break}g.warn(`[SessionRoutes] Failed to recover queued task ${X.sessionId}:`,H),J.deferred++}}return J};return O.get("/",async(J)=>{try{let K=await R.listSessions(),Y=new Set(K.filter((M)=>M.relationType==="subagent").map((M)=>p({sessionId:M.sessionId,projectPath:M.projectPath}))),X=Array.from(r.values()).filter((M)=>!Y.has(p(GO(M)))&&M.relationType!=="subagent").map((M)=>aO(M)),W=new Set(X.map((M)=>p({sessionId:M.sessionId,projectPath:M.projectPath}))),H=K.filter((M)=>{if(M.relationType==="subagent")return!1;return!W.has(p({sessionId:M.sessionId,projectPath:M.projectPath}))}),D=new Set(W),B=H.filter((M)=>{let T=p({sessionId:M.sessionId,projectPath:M.projectPath});if(D.has(T))return!1;return D.add(T),!0}),A=[...X,...B];return J.json(A)}catch(K){throw g.error("[SessionRoutes] Failed to list sessions:",K),new t("Failed to list sessions")}}),O.get("/catalog",async(J)=>{try{let K=J.req.query("limit"),Y=K===void 0?void 0:Number(K),X=J.req.query("cursor"),W=J.req.query("projectPath"),H=J.req.query("archived");if(H!==void 0&&H!=="true"&&H!=="false")throw new _("archived must be true or false");let D=H==="true",B=await R.listSessionPage({...W?{cwd:R0(W)}:{},...X?{cursor:X}:{},...Y===void 0?{}:{limit:Y},includeSubagents:!1,archived:D}),A=new Map((D?[]:Array.from(r.values())).filter((M)=>M.relationType!=="subagent").map((M)=>[p(GO(M)),aO(M)]));return J.json({sessions:B.sessions.map((M)=>A.get(p({sessionId:M.sessionId,projectPath:M.projectPath}))??M),...B.nextCursor?{nextCursor:B.nextCursor}:{}})}catch(K){if(K instanceof _)throw K;if(K instanceof Error&&(K.message.startsWith("Invalid session cursor")||K.message.startsWith("Session cursor scope")||K.message.startsWith("Session catalog")))throw new _(K.message);throw g.error("[SessionRoutes] Failed to list session catalog:",K),new t("Failed to list session catalog")}}),O.post("/",async(J)=>{try{let K=await J.req.json(),Y=q(vx,K);if(!Y.success)throw new _("Invalid request body");let{title:X,projectPath:W}=Y.data,H=F1("web",12),D=R0(W||J.get("directory")||c(),W?"projectPath":"directory"),B=await R.createSessionMetadata(H,D,{title:X,taskStatus:"completed"}),A=E0(B,[]),M=GO(A);return r.set(p(M),A),S.publish(M,"session.created",{}),J.json({...aO(A),status:void 0,agentType:void 0,model:void 0})}catch(K){if(g.error("[SessionRoutes] Failed to create session:",K),K instanceof _)throw K;throw new t("Failed to create session")}}),O.get("/:sessionId/export",async(J)=>{let K=J.req.param("sessionId");try{let Y=J.req.query("includeReasoning");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new _("includeReasoning must be true or false");let X=await KO(K,J.req.query("projectPath")),W=await R.exportSessionMarkdown(X.sessionId,X.projectPath,{includeReasoning:Y==="true"});return J.body(W.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${W.filename}"`,"Content-Length":String(Buffer.byteLength(W.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":W.contentSha256,"X-Blade-Export-Activities":String(W.activityCount),"X-Blade-Export-Messages":String(W.messageCount),"X-Blade-Export-Redactions":String(W.redactionCount)})}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;if(Y instanceof Error&&Y.message==="No conversation content to export")throw new k(Y.message);throw g.error("[SessionRoutes] Failed to export session:",Y),new t("Failed to export session")}}),O.post("/:sessionId/fork",async(J)=>{let K=J.req.param("sessionId");try{w1(K);let Y=await J.req.json(),X=q(ix,Y);if(!X.success)throw new _("Invalid request body");let W=R0(X.data.projectPath),H=await R.findSessionMetadata(K,W);if(!H)throw new f("Session",K);let D=await R.forkSession(K,{sourceProjectPath:H.projectPath,targetProjectPath:H.projectPath}),B=E0(D.metadata,D.messages),A=GO(B);return r.set(p(A),B),S.publish(A,"task.status",{taskStatus:D.metadata.taskStatus,...D.metadata.taskCompletedAt?{taskCompletedAt:D.metadata.taskCompletedAt}:{},updatedAt:D.metadata.lastMessageTime}),J.json({session:D.metadata,messages:N1(D.messages)},201)}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof k)throw Y;if(Y instanceof P$)throw new k("Session has no durable creation record");throw g.error("[SessionRoutes] Failed to fork session:",Y),new t("Failed to fork session")}}),O.get("/:sessionId",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=r.get(p(Y));if(X)return J.json(aO(X));let W=await R.findSessionMetadata(Y.sessionId,Y.projectPath);if(!W)throw new f("Session",K);return J.json(W)}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;throw g.error("[SessionRoutes] Failed to get session:",Y),new t("Failed to get session")}}),O.patch("/:sessionId",async(J)=>{let K=J.req.param("sessionId");try{let Y=await J.req.json(),X=q(lx,Y);if(!X.success)throw new _("Invalid request body");if(X.data.title===void 0)throw new _("title is required");let W=await KO(K,X.data.projectPath),H=await R.updateSessionMetadata(W.sessionId,W.projectPath,{title:X.data.title}),D=r.get(p(W));if(D)D.title=H.title??D.title,D.updatedAt=new Date(H.lastMessageTime);if(H.title)S.publish(W,"session.updated",{title:H.title});return J.json({success:!0,title:H.title})}catch(Y){if(g.error("[SessionRoutes] Failed to update session:",Y),Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;throw new t("Failed to update session")}}),O.get("/:sessionId/rewind",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath"));return u(K,async(Y)=>J.json({checkpoints:await Y.listRewindCheckpoints()}))}),O.post("/:sessionId/rewind",async(J)=>{let K=q(d$,await J.req.json());if(!K.success)throw new _("Invalid rewind request");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=DO(Y.currentRunId);if(_O(W))throw new k("Cannot rewind while a run is active");return u(Y,async(H)=>{let D;try{D=await H.rewindSession(K.data)}catch(A){if(A instanceof Error&&A.message.startsWith("Cannot rewind while"))throw new k(A.message);throw A}Y.messages=[...D.messages],Y.updatedAt=new Date;let B=N1(D.messages);return S.publish(X,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:B}),J.json({...D,messages:B})})})}),O.get("/:sessionId/review",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath")),X=await oO.list(Y.projectPath,Y.sessionId);return J.json({reviews:X.map((W)=>({...W,content:W.completion?E$(W.start,W.completion):void 0}))})}),O.post("/:sessionId/review",async(J)=>{let K=J.req.param("sessionId"),Y=q(o$,await J.req.json());if(!Y.success)throw new _("Invalid code review request");let X=await $O(K,Y.data.projectPath),W=GO(X),H=p(W);return P(W,async()=>{if(_O(DO(X.currentRunId)))throw new k("Cannot start a review during an active turn");if(bO.has(H))throw new k("Session already has an active review");return u(X,async(D)=>{if(await oO.recoverInterrupted(W.projectPath,W.sessionId,D),Y.data.modelId&&!D.getModelById(Y.data.modelId))throw new _(`Model not found: ${Y.data.modelId}`);if(Y.data.modelId&&D.getCurrentModelId()!==Y.data.modelId)await D.refresh({modelId:Y.data.modelId});if(Y.data.modelId&&X.selectedModelId!==Y.data.modelId){let T=await R.updateSessionMetadata(X.id,X.projectPath,{selectedModelId:Y.data.modelId});X0(X,T)}let B=new AbortController,A;try{A=await oO.start({sessionId:W.sessionId,projectPath:W.projectPath,runtime:D,request:{kind:Y.data.kind,...Y.data.ref?{ref:Y.data.ref}:{},...Y.data.instructions?{instructions:Y.data.instructions}:{}},signal:B.signal,onEvent:(T)=>{if(T.kind==="tool_start")S.publish(W,"review.tool.started",{reviewId:A?.reviewId,toolCallId:T.toolCall.id,toolName:T.toolCall.function.name});else if(T.kind==="tool_progress")S.publish(W,"review.tool.progress",{reviewId:A?.reviewId,toolCallId:T.toolCall.id,message:T.update.message.slice(0,1000)});else if(T.kind==="tool_result")S.publish(W,"review.tool.completed",{reviewId:A?.reviewId,toolCallId:T.toolCall.id,success:T.result.success})}})}catch(T){if(T instanceof Error&&(T.message.includes("active review")||T.message.includes("interrupted review")||T.message.includes("active turn")))throw new k(T.message);if(T instanceof Error&&(T.message.includes("review")||T.message.includes("Git")||T.message.includes("changes")||T.message.includes("ref")))throw new _(T.message);throw T}if(!A)throw new t("Code review failed to start");await tO(X),S.publish(W,"review.started",{reviewId:A.reviewId,kind:Y.data.kind}),S.publish(W,"task.status",{taskStatus:X.taskStatus,...X.taskStatusReason?{taskStatusReason:X.taskStatusReason}:{},...X.taskStartedAt?{taskStartedAt:X.taskStartedAt}:{},...X.taskPromptSummary?{taskPromptSummary:X.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let M=A.completion.then(async(T)=>{X.messages=await R.loadSession(W.sessionId,W.projectPath),await tO(X),S.publish(W,"task.status",{taskStatus:X.taskStatus,...X.taskStatusReason?{taskStatusReason:X.taskStatusReason}:{},...X.taskFailure?{taskFailure:X.taskFailure}:{},...X.taskStartedAt?{taskStartedAt:X.taskStartedAt}:{},...X.taskCompletedAt?{taskCompletedAt:X.taskCompletedAt}:{},...X.taskPromptSummary?{taskPromptSummary:X.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),S.publish(W,"review.completed",{reviewId:A.reviewId,status:T.status,findings:T.findings.length})}).catch((T)=>{g.error(`[SessionRoutes] Code review ${A.reviewId} failed:`,T)}).finally(()=>{if(bO.get(H)?.reviewId===A.reviewId)bO.delete(H)});return bO.set(H,{reviewId:A.reviewId,controller:B,completion:M}),J.json({reviewId:A.reviewId,status:"running"},202)})})}),O.get("/:sessionId/subagents",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath"));return u(K,(Y)=>J.json({subagents:Y.listSubagents().map(n0)}))}),O.post("/:sessionId/subagents/:agentId/resume",async(J)=>{w1(J.req.param("agentId"));let K=l$.safeParse(await J.req.json());if(!K.success)throw new _("Invalid subagent resume request");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=DO(Y.currentRunId);if(_O(W))throw new k("Cannot resume a subagent while a parent run is active");return u(Y,async(H)=>{let D=!1,B,A=(T)=>{S.publish(X,"subagent.complete",{subagentSessionId:T.id,success:T.status==="completed",status:T.status,summary:T.result?.message?.slice(0,500),type:T.subagentType,verificationVerdict:T.result?.verificationVerdict,resumedFrom:T.resumedFrom,rootAgentId:T.rootAgentId,resumeDepth:T.resumeDepth})},M;try{M=H.resumeSubagent({agentId:J.req.param("agentId"),prompt:K.data.prompt,onEvent:(T,y)=>{O2(X,y,T)},onCompleted:(T)=>{if(D)A(T);else B=T}})}catch(T){if(T instanceof Error&&(T.message.startsWith("Cannot resume")||T.message.startsWith("Subagent cannot")))throw new k(T.message);if(T instanceof Error&&T.message.startsWith("Subagent not found"))throw new f(T.message);throw T}if(S.publish(X,"subagent.start",{subagentSessionId:M.session.id,type:M.session.subagentType,description:M.session.description,resumedFrom:M.source.id,rootAgentId:M.session.rootAgentId,resumeDepth:M.session.resumeDepth}),D=!0,B)A(B);return J.json({source:n0(M.source),session:n0(M.session)})})})}),O.get("/:sessionId/goal",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath"));return J.json({goal:await new y$(K.projectPath,K.id).get()})}),O.put("/:sessionId/goal",async(J)=>{let K=q(cx,await J.req.json());if(!K.success)throw new _("Invalid goal request");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=DO(Y.currentRunId);if(_O(W))return J.json({status:"rejected",reason:"run_active"},409);let D=K.data.permissionMode??Y.permissionMode??"default";if(Y.permissionMode!==D)await PO(Y,D);let B=await e(Y),A=!1;try{let M=await B.value.createGoal(K.data);S.publish(X,"goal.updated",{goal:M});let T=s(Y,"",D,{goalContinuationOnly:!0,runtimeLease:B});return A=!0,await T.taskAdmissionUpdate,J.json({status:T.status==="queued"?"queued":"running",runId:T.id,goal:M,queuePosition:Y.taskQueuePosition,queueDepth:Y.taskQueueDepth,maxConcurrentTasks:Y.taskConcurrencyLimit},202)}finally{if(!A)B.release()}})}),O.patch("/:sessionId/goal",async(J)=>{let K=q(ax,await J.req.json());if(!K.success)throw new _("Invalid goal update");let Y=await $O(J.req.param("sessionId"),J.req.query("projectPath")),X=GO(Y);return P(X,async()=>{let W=await e(Y),H=!1;try{let D=W.value,B;if(K.data.action==="pause")B=await D.pauseGoal();else if(K.data.action==="edit")B=await D.editGoal(K.data.objective);else B=await D.resumeGoal();if(S.publish(X,"goal.updated",{goal:B}),B.status==="active"&&!_O(DO(Y.currentRunId))){let A=s(Y,"","default",{goalContinuationOnly:!0,runtimeLease:W});return H=!0,await A.taskAdmissionUpdate,J.json({status:A.status==="queued"?"queued":"running",runId:A.id,goal:B,queuePosition:Y.taskQueuePosition,queueDepth:Y.taskQueueDepth,maxConcurrentTasks:Y.taskConcurrencyLimit},202)}return J.json({status:B.status,goal:B})}finally{if(!H)W.release()}})}),O.delete("/:sessionId/goal",async(J)=>{let K=await $O(J.req.param("sessionId"),J.req.query("projectPath")),Y=GO(K);return u(K,async(X)=>{let W=await X.clearGoal();if(W)S.publish(Y,"goal.cleared",{});return J.json({cleared:W})})}),O.post("/:sessionId/archive",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=await R.listSessionArchiveMembers(Y.sessionId,Y.projectPath);for(let H of X){let D=gO({sessionId:H.sessionId,projectPath:H.projectPath}),B=r.get(p(D));if(_O(DO(B?.currentRunId)))throw new k(`Stop session ${H.sessionId} before archiving this session tree`)}for(let H of X){let D=gO({sessionId:H.sessionId,projectPath:H.projectPath}),B=r.get(p(D));if(B)await YO(B)}let W=await R.archiveSession(Y.sessionId,Y.projectPath);for(let H of X){let D=gO({sessionId:H.sessionId,projectPath:H.projectPath}),B=p(D);r.delete(B),Z.delete(B),x.delete(B),S.publish(D,"session.archived",{archiveRootId:Y.sessionId,archivedAt:W.archivedAt})}if($.size===0)await UO.getInstance().disconnectAll();return J.json({session:W,archivedSessionIds:X.map((H)=>H.sessionId)})}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO||Y instanceof k)throw Y;if(Y instanceof D1)throw new k(Y.message);throw g.error("[SessionRoutes] Failed to archive session:",Y),new t("Failed to archive session")}}),O.post("/:sessionId/unarchive",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=await R.listSessionArchiveMembers(Y.sessionId,Y.projectPath),W=await R.unarchiveSession(Y.sessionId,Y.projectPath),H=X.filter((D)=>D.sessionId===Y.sessionId||D.archivedBySessionId===Y.sessionId).map((D)=>D.sessionId);for(let D of H)S.publish({sessionId:D,projectPath:Y.projectPath},"session.unarchived",{archiveRootId:Y.sessionId});return J.json({session:W,restoredSessionIds:H})}catch(Y){if(Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;if(Y instanceof D1)throw new k(Y.message);throw g.error("[SessionRoutes] Failed to unarchive session:",Y),new t("Failed to unarchive session")}}),O.delete("/:sessionId",async(J)=>{let K=J.req.param("sessionId"),Y=J.req.query("projectPath");try{let X=await KO(K,Y),W=p(X),H=r.get(W),D=$.get(W),B=H?.taskWorktree??await R.findSessionTaskWorktree(X.sessionId,X.projectPath),A;if(H?.currentRunId){let y=DO(H.currentRunId);if(y)k0(y),await y.completion,A=y.id}let M=bO.get(W);if(M)M.controller.abort("session-delete"),await M.completion;if(D)await D.clearGoal().catch((y)=>{g.warn("[SessionRoutes] Failed to clear session goal:",y)});if(await R.deleteSession(X.sessionId,X.projectPath),S.publish(X,"session.deleted",{}),A)nx(A);r.delete(W),Z.delete(W),x.delete(W);let T=$.get(W);if(T){if(!await j.remove(W,T))throw new k("Session Runtime is still active and cannot be deleted")}if(B)try{await EO.restoreSession(B),await EO.exit({sessionId:X.sessionId,action:"remove",discardChanges:!0})}catch(y){g.warn(`[SessionRoutes] Failed to remove deleted task worktree ${X.sessionId}:`,y)}return J.json({success:!0})}catch(X){if(g.error("[SessionRoutes] Failed to delete session:",X),X instanceof _||X instanceof f||X instanceof LO)throw X;throw new t("Failed to delete session")}}),O.get("/:sessionId/message",async(J)=>{let K=J.req.param("sessionId");try{let Y=await KO(K,J.req.query("projectPath")),X=r.get(p(Y)),W=X?.messages?X.messages:await R.loadSession(Y.sessionId,Y.projectPath);return J.json(N1(W))}catch(Y){if(g.error("[SessionRoutes] Failed to get messages:",Y),Y instanceof _||Y instanceof f||Y instanceof LO)throw Y;throw new t("Failed to get messages")}}),O.get("/:sessionId/events",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath"));try{await R.assertSessionWritable(Y.sessionId,Y.projectPath)}catch(B){if(B instanceof _1)throw new k(B.message);throw B}let X=await n(Y),W=J.req.header("Last-Event-ID")??J.req.query("lastEventId"),H=W?Number.parseInt(W,10):Number.NaN,D=Number.isInteger(H)?H+1:void 0;return ux(J,async(B)=>{let M,T,y=!1,WO,yO,TO=new Promise((E)=>{yO=E}),XO=()=>{if(T!==void 0)clearInterval(T),T=void 0;M?.(),M=void 0},OO=(E)=>{if(y)return;y=!0,XO(),WO?.close(E),yO()},O0=new Set;B.onAbort(OO),WO=new A0({write:async(E)=>{await B.writeSSE(E)},onFailure:(E)=>{g.warn(`[SessionRoutes] SSE egress closed for ${Y.sessionId}: kind=${E.kind} pendingItems=${E.pendingItems??0} pendingBytes=${E.pendingBytes??0}`),OO(E)}}),M=S.subscribe((E)=>{if(E.sessionId!==Y.sessionId||E.projectPath!==Y.projectPath)return;let m=E.properties.requestId;if((E.type==="permission.asked"||E.type==="question.required"||E.type==="elicitation.required")&&typeof m==="string"){if(O0.has(m))return;O0.add(m)}if(E.type==="subagent.completion.queued")P(Y,()=>SO(X)).catch((I)=>{g.error(`[SessionRoutes] Failed to wake background completion for ${X.id}:`,I)});if(E.type==="team.message.received"&&typeof E.properties.teamName==="string"&&typeof E.properties.messageId==="string"&&typeof E.properties.content==="string"&&h$(E.properties.metadata,{messageId:E.properties.messageId,teamName:E.properties.teamName})){let I=E.properties.teamName,h=E.properties.messageId,l=E.properties.content,v=E.properties.metadata;P(Y,async()=>{let i=await e(X),fO=!1;try{let a=await i.value.enqueueSteering(l,{allowBeforeTurn:!0,messageId:h,origin:"team_message",metadata:v});if(!a.accepted)return;await new m$(I,s0()).markDelivered([h]),fO=a.delivery==="next_turn"}finally{i.release()}if(fO)await SO(X)}).catch((i)=>{g.error(`[SessionRoutes] Failed to deliver teammate message for ${X.id}:`,i)})}WO?.observe(tx(E),E.seq)});try{if(B.aborted||y)return;let E=DO(X.currentRunId),m=_O(E)?await e(X):void 0;try{let l=m?.value,v=l?.getPendingSteeringCount()??0;await WO.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:Y.sessionId,projectPath:Y.projectPath,timestamp:Date.now(),status:_O(E)?E.status:"idle",runId:_O(E)?E.id:void 0,queued:v,pendingInputDelivery:v>0?l?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:l?.getRecoveredSteeringCount()??0}})})}finally{m?.release()}if(B.aborted||y)return;if(D!==void 0){if(await f$.for(Y.sessionId,Y.projectPath).replay({onCommitted:async(v)=>{if(B.aborted||y)return;let i=ex(v);if(i.seq===void 0)return;await WO.writeReplay({...typeof v.seq==="number"?{id:String(v.seq)}:{},data:JSON.stringify({type:i.type,...i.seq!==void 0?{seq:i.seq}:{},properties:{...i.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})},i.seq)}},D),B.aborted||y)return}if(WO.finishInitialization({replayed:D!==void 0}),B.aborted||y)return;if(!E&&!bO.has(p(Y))){let v=(await oO.list(Y.projectPath,Y.sessionId)).some((i)=>i.completion===void 0)?await u(X,(i)=>oO.recoverInterrupted(Y.projectPath,Y.sessionId,i)):void 0;if(v)X.messages=await R.loadSession(Y.sessionId,Y.projectPath),await tO(X),S.publish(Y,"review.completed",{reviewId:v.reviewId,status:v.status,findings:0,recovered:!0})}if(B.aborted||y)return;if(!E)await nO.recoverResponded(Y.projectPath,Y.sessionId);if(B.aborted||y)return;let I=E?void 0:await nO.findPending(Y.projectPath,Y.sessionId),h=E?.pendingPermission??(I?{permissionId:I.request.requestId,details:nO.confirmationDetails(I),resolve:()=>{return}}:void 0);if(h){O0.add(h.permissionId);let l=t$(h,!0);WO.observe({data:JSON.stringify({type:l.type,properties:{...l.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})})}if(B.aborted||y)return;if(SO(X).catch((l)=>{g.error(`[SessionRoutes] Failed to resume pending input for ${K}:`,l)}),B.aborted||y)return;T=setInterval(()=>{if(B.aborted||y)return;WO?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await TO}finally{OO()}})}),O.post("/:sessionId/message",async(J)=>{let K=J.req.param("sessionId"),Y=await J.req.json(),X=q(dx,Y);if(!X.success)throw new _("Invalid message format");let{content:W,attachments:H,modelId:D,reasoningEffort:B,serviceTier:A,responseVerbosity:M,communicationStyle:T,permissionMode:y,projectPath:WO,outputSchema:yO}=X.data,TO;if(yO)try{TO=U1(yO).schema}catch(v){throw new _(v instanceof Error?v.message:"Invalid output schema")}let XO=T;if(Buffer.byteLength(W,"utf8")>W1)throw new _(`Message text exceeds the ${W1}-byte limit`);let OO=D?.trim();if((H??[]).reduce((v,i)=>v+(typeof i.content==="string"?Buffer.byteLength(i.content):0),0)>r0)throw new _("Message attachments exceed the 5 MiB limit");let E=y,m=w$(W,H),I=await $O(K,WO??J.req.query("projectPath")),h=E??I.permissionMode??"default",l=GO(I);return P(l,async()=>{let v=DO(I.currentRunId);if(_O(v)){if(TO)throw new k("Wait for the active turn to finish before setting an output schema");return u(I,async(a)=>{if(OO&&!a.getModelById(OO))throw new _(`Model not found: ${OO}`);if(OO&&a.getCurrentModelId()!==OO)throw new k("Wait for the active turn to finish before switching models");if(B&&a.getReasoningConfiguration().selection!==B)throw new k("Wait for the active turn to finish before switching reasoning effort");if(A&&a.getServiceTierConfiguration().selection!==A)throw new k("Wait for the active turn to finish before switching service tier");if(M&&a.getResponseVerbosityConfiguration().selection!==M)throw new k("Wait for the active turn to finish before switching response verbosity");if(XO&&a.getCommunicationStyleConfiguration().selection!==XO)throw new k("Wait for the active turn to finish before switching communication style");if(E&&I.permissionMode!==E)throw new k("Wait for the active turn to finish before switching permission mode");let zO=await a.enqueueSteering(m,{allowBeforeTurn:!0});if(!zO.accepted)return J.json({status:"rejected",reason:zO.reason??"turn_unavailable"},409);let iO=zO.messageId??Y0(12),B0=zO.queued;S.publish(l,"message.created",{messageId:iO,role:"user",content:A1(m)});let v0=zO.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(S.publish(l,v0,{runId:v.id,messageId:iO,queued:B0}),zO.delivery==="next_turn"&&v.status!=="running"&&v.status!=="waiting_permission")SO(I).catch((d0)=>{g.error(`[SessionRoutes] Failed to wake queued follow-up for ${K}:`,d0)});if(zO.delivery==="next_turn")v.pendingFollowUpRequested=!0;return J.json({runId:v.id,messageId:iO,status:zO.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:B0},202)})}if(I.permissionMode!==h)await PO(I,h);let i=await e(I,{permissionMode:h,...XO&&!XO.includes(":")?{communicationStyle:XO}:{}}),fO=!1;try{let a=i.value;if(OO&&!a.getModelById(OO))throw new _(`Model not found: ${OO}`);if(B)try{a.resolveReasoningConfiguration(B,OO)}catch(VO){throw new _(VO instanceof Error?VO.message:"Invalid reasoning effort")}if(A)try{a.resolveServiceTierConfiguration(A,OO)}catch(VO){throw new _(VO instanceof Error?VO.message:"Invalid service tier")}if(M)try{a.resolveResponseVerbosityConfiguration(M,OO)}catch(VO){throw new _(VO instanceof Error?VO.message:"Invalid response verbosity")}let zO=XO?a.resolveCommunicationStyleConfiguration(XO):void 0;if(zO?.source!==void 0&&zO.source!=="built-in"&&!zO.contentSha256)throw new _("Custom communication style has no provenance");let iO=a.getCurrentModelId(),B0=a.getReasoningConfiguration(),v0=a.getServiceTierConfiguration(),d0=a.getResponseVerbosityConfiguration(),v1=a.getCommunicationStyleConfiguration(),d1=Boolean(OO)&&iO!==OO,l1=Boolean(B)&&B0.selection!==B,i1=Boolean(A)&&v0.selection!==A,c1=Boolean(M)&&d0.selection!==M,a1=Boolean(XO)&&v1.selection!==XO;if(d1||l1||i1||c1||a1)await a.refresh({...OO?{modelId:OO}:{},...B?{reasoningEffort:B}:{},...A?{serviceTier:A}:{},...M?{responseVerbosity:M}:{},...XO?{communicationStyle:XO}:{}});let J1={...OO&&I.selectedModelId!==OO?{selectedModelId:OO}:{},...B&&I.reasoningEffort!==B?{reasoningEffort:B}:{},...A&&I.serviceTier!==A?{serviceTier:A}:{},...M&&I.responseVerbosity!==M?{responseVerbosity:M}:{},...zO&&(I.communicationStyle!==XO||I.communicationStyleDigest!==zO.contentSha256)?{communicationStyle:XO,communicationStyleDigest:zO.source==="built-in"?null:zO.contentSha256}:{}};if(Object.keys(J1).length>0)try{let VO=await R.updateSessionMetadata(I.id,I.projectPath,J1);I.permissionMode=VO.permissionMode,I.selectedModelId=VO.selectedModelId,I.reasoningEffort=VO.reasoningEffort,I.serviceTier=VO.serviceTier,I.responseVerbosity=VO.responseVerbosity,I.communicationStyle=VO.communicationStyle,I.communicationStyleDigest=VO.communicationStyleDigest,I.updatedAt=new Date(VO.lastMessageTime),S.publish(l,"session.updated",J1)}catch(VO){if(d1||l1||i1||c1||a1)await a.refresh({...iO?{modelId:iO}:{},reasoningEffort:B0.selection,serviceTier:v0.selection,responseVerbosity:d0.selection,communicationStyle:v1.selection}).catch((Vx)=>g.error("[SessionRoutes] Failed to roll back non-durable model settings:",Vx));throw VO}let w0=TO?await a.prepareInputTurn(m,{outputSchema:TO}):await a.prepareInputTurn(m);if(!w0.accepted)return J.json({status:"rejected",reason:w0.reason},w0.reason==="queue_full"?429:409);let Y1=s(I,m,h,{preparedInputTurn:w0,outputSchema:TO,runtimeLease:i});return fO=!0,await Y1.taskAdmissionUpdate,J.json({runId:Y1.id,messageId:w0.messageId,status:Y1.status==="queued"?"queued":"running",queuePosition:I.taskQueuePosition,queueDepth:I.taskQueueDepth,maxConcurrentTasks:I.taskConcurrencyLimit},202)}finally{if(!fO)i.release()}})}),O.post("/:sessionId/side-question",async(J)=>{let K=J.req.param("sessionId"),Y=q(a$,await J.req.json());if(!Y.success)throw new _("Invalid side conversation request");let X=await $O(K,Y.data.projectPath??J.req.query("projectPath"));return u(X,async(W)=>{let H=await W.askSideQuestion(Y.data.question,{signal:J.req.raw.signal});return J.json({...H,...W.getCurrentModelId()?{modelId:W.getCurrentModelId()}:{}})})}),O.post("/:sessionId/shell",async(J)=>{let K=J.req.param("sessionId"),Y=q(c$,await J.req.json());if(!Y.success)throw new _("Invalid user shell command");let X=await $O(K,Y.data.projectPath??J.req.query("projectPath")),W=GO(X),H=p(W);return P(W,async()=>{if(IO.has(H))throw new k("A user shell command is already running in this Session");let D=await e(X),B=D.value,A=new AbortController,M,T=new Promise((y)=>{M=y});IO.set(H,{controller:A,completion:T});try{let y=await B.executeUserShellCommand(Y.data.command,{signal:A.signal});X.messages=await R.loadSession(X.id,X.projectPath),X.updatedAt=new Date;let WO=DO(X.currentRunId);if(y.delivery==="next_turn"&&_O(WO))WO.pendingFollowUpRequested=!0;return J.json({executionId:y.executionId,messageId:y.messageId,record:y.record,auxiliary:y.auxiliary,...y.delivery?{delivery:y.delivery}:{},...y.queued!==void 0?{queued:y.queued}:{}})}finally{IO.delete(H),M(),D.release()}})}),O.post("/:sessionId/abort",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath")),X=r.get(p(Y));if(X?.currentRunId){let D=DO(X.currentRunId);if(D)k0(D),await D.completion}let W=IO.get(p(Y));if(W)W.controller.abort("user-cancel"),await W.completion;let H=bO.get(p(Y));if(H)H.controller.abort("user-cancel"),await H.completion;return J.json({success:!0})}),O.get("/:sessionId/status",async(J)=>{let K=J.req.param("sessionId"),Y=await KO(K,J.req.query("projectPath")),X=r.get(p(Y)),W=bO.get(p(Y));if(W)return J.json({sessionId:K,projectPath:Y.projectPath,reviewId:W.reviewId,status:"reviewing"});if(!X?.currentRunId)return J.json({sessionId:K,projectPath:Y.projectPath,status:"idle"});let H=DO(X.currentRunId);return J.json({sessionId:K,projectPath:Y.projectPath,runId:X.currentRunId,status:H?.status||"idle"})}),{app:O,dispatchTask:wO,retryTask:NO,updateTask:u1,getTaskDiff:Q1,deliverTask:u0,recoverQueuedTasks:Z1,getRuntimeResidencyStats:()=>j.getStats(),getCoordinationStats:()=>({messageSubmissions:G.getStats(),taskDeliveries:z.getStats()}),shutdown:(J="server-shutdown")=>{if(w)return w;return L.close(J),clearInterval(b),w=(async()=>{let K,Y=async(B)=>{let A=await Promise.allSettled(B);for(let M of A)if(M.status==="rejected")K??=M.reason},X=new Set,W=()=>{for(let B of CO.values()){if(B.completion)X.add(B.completion);if(_O(B))k0(B,J)}for(let B of IO.values())B.controller.abort(J),X.add(B.completion);for(let B of bO.values())B.controller.abort(J),X.add(B.completion)},H=L.waitForIdle(),D=!1;H.then(()=>{D=!0});while(!D)W(),await Promise.race([H,new Promise((B)=>setImmediate(B))]);if(await H,W(),await Y([...X]),await Y([...x.values()]),W(),await Y([...X]),await Y([j.disposeAll()]),$.clear(),await Y([...Q.values()]),await Y([UO.getInstance().disconnectAll()]),x.clear(),Q.clear(),Z.clear(),r.clear(),G0===SO)G0=void 0;if(K!==void 0)throw K})(),w}}};async function $2(O,$,x,Q,Z,G={}){let{abortController:z,sessionId:U,id:j}=O,L=G.preparedInputTurn?.messageId??Y0(12),w=G.pendingInputOnly===!0||G.preparedInputTurn?.mode==="pending"||G.goalContinuationOnly===!0?void 0:Y0(12),F=G.runtimeLease,P,ZO,d=GO($),C=(u,YO)=>{S.publish(d,u,YO)},e=async()=>{let u=String(z.signal.reason||"Task run cancelled");if($.taskIsolation){if(!F)F=await Z($).catch(()=>{return});let YO=P??F?.value;if(u==="user-cancel")await YO?.discardPendingInput().catch(($O)=>{g.warn(`[SessionRoutes] Failed to discard cancelled input for ${$.id}:`,$O)});let n=await YO?.setTaskStatus("cancelled",u).catch(()=>{return});if(n)X0($,n);else await tO($).catch(()=>{return})}$.taskStatus="cancelled",$.taskStatusReason=u,$.taskCompletedAt??=new Date().toISOString()};try{if(G.taskAdmission){if(await G.taskAdmission.ready,await O.taskAdmissionUpdate,z.signal.aborted)throw Error(String(z.signal.reason||"Task run cancelled"))}if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!G.pendingInputOnly&&!G.goalContinuationOnly)C("message.created",{messageId:L,role:"user",content:A1(x)});if(C("session.status",{status:"running"}),w)C("message.created",{messageId:w,role:"assistant",content:""});F??=await Z($),P=F.value;let u=P,YO=Boolean(G.outputSchema??u.getPendingSteeringMessages().find((N)=>N.outputSchema)?.outputSchema);ZO=await p$.createWithRuntime(u,{sessionId:U,...$.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let n=async(N)=>{let NO=N.interactionRequestId??Y0(12),u1=300000;O.status="waiting_permission";let Q1=new Promise((SO)=>{let Z1=setTimeout(()=>{g.warn(`[SessionRoutes] Permission ${NO} timed out after 300000ms`),C("permission.timeout",{requestId:NO}),SO({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:NO,resolve:(p1)=>{clearTimeout(Z1),SO(p1)},details:N}}),L0=O.pendingPermission;if(!L0)throw Error("Permission request was not registered");let u0=t$(L0);C(u0.type,u0.properties),g.info(`[SessionRoutes] Permission request created: ${NO}, runId: ${j}`);let p0=await Q1;if(g.info(`[SessionRoutes] Permission response received: ${NO}, approved: ${p0.approved}`),!z.signal.aborted)O.status="running";if(O.pendingPermission===L0)O.pendingPermission=void 0;return C("interaction.resolved",{requestId:NO}),p0},PO={messages:await R.loadSessionModelContext($.id,$.projectPath),userId:"web-user",sessionId:U,workspaceRoot:$.projectPath,signal:z.signal,permissionMode:Q,onPermissionModeChange:async(N)=>{$.permissionMode=N,$.updatedAt=new Date,C("session.updated",{permissionMode:N})},...$.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:n}},s=()=>{if(!w)w=Y0(12),C("message.created",{messageId:w,role:"assistant",content:""});return w},lO=async(N)=>{switch(N.kind){case"content_delta":if(YO)break;C("message.delta",{messageId:s(),delta:N.delta});break;case"structured_output":C("structured.output",{messageId:s(),output:N.output,schemaDigest:N.schemaDigest});break;case"thinking_delta":C("thinking.delta",{messageId:s(),delta:N.delta});break;case"tool_start":if("function"in N.toolCall){if(N.toolCall.function.name===z0)break;C("tool.start",{messageId:s(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,arguments:N.toolCall.function.arguments,toolKind:N.toolKind})}break;case"tool_result":if("function"in N.toolCall){if(N.toolCall.function.name===z0)break;C("tool.result",{messageId:s(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,success:N.result.success,summary:N.result.metadata?.summary,output:f0(P0(y0(N.toolCall.function.name,N.result),I0)),metadata:q0(N.toolCall.function.name,N.result.metadata)})}break;case"tool_progress":if("function"in N.toolCall){if(N.toolCall.function.name===z0)break;C("tool.progress",{messageId:s(),toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,...N.update})}break;case"token_usage":C("token.usage",{...N.usage});break;case"turn_start":C("turn.started",{turn:N.turn,maxTurns:N.maxTurns});break;case"provider_admission":C("provider.admission",{phase:N.phase,requestClass:N.requestClass,resource:N.resource,scope:N.scope,reason:N.reason,queuePosition:N.queuePosition,queueDepth:N.queueDepth,inFlight:N.inFlight,limit:N.limit,waitMs:N.waitMs,maxWaitMs:N.maxWaitMs,recoveryRemainingMs:N.recoveryRemainingMs});break;case"provider_circuit":C("provider.circuit",{phase:N.phase,reason:N.reason,statusCode:N.statusCode,retryAfterMs:N.retryAfterMs,nextProbeAt:N.nextProbeAt,openDurationMs:N.openDurationMs,sampleCount:N.sampleCount,failureCount:N.failureCount,recoveryRemainingMs:N.recoveryRemainingMs});break;case"provider_retry":C("provider.retry",{phase:N.phase,attempt:N.attempt,maxRetries:N.maxRetries,reason:N.reason,statusCode:N.statusCode,delayMs:N.delayMs,nextRetryAt:N.nextRetryAt,mode:N.mode,recoveryBudgetMs:N.recoveryBudgetMs,recoveryElapsedMs:N.recoveryElapsedMs,recoveryRemainingMs:N.recoveryRemainingMs,exhaustedBy:N.exhaustedBy});break;case"provider_stall":C("provider.stall",{phase:N.phase,stallCount:N.stallCount,durationMs:N.durationMs,warningAfterMs:N.warningAfterMs,timeoutMs:N.timeoutMs,outputStarted:N.outputStarted});break;case"action_stationarity":C("action.stationarity",{phase:N.phase,toolName:N.toolName,runLength:N.runLength,nudgeThreshold:N.nudgeThreshold,haltThreshold:N.haltThreshold,progressAware:N.progressAware});break;case"mcp_catalog_changed":C("mcp.catalog.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,added:N.added,removed:N.removed,updated:N.updated});break;case"mcp_content_changed":C("mcp.content.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,contentKind:N.contentKind,added:N.added,removed:N.removed,updated:N.updated});break;case"mcp_resource_updated":C("mcp.resource.updated",{messageId:s(),revision:N.revision,serverName:N.serverName,uri:N.uri});break;case"mcp_connection_changed":C("mcp.connection.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,phase:N.phase,reason:N.reason,attempt:N.attempt,maxAttempts:N.maxAttempts,nextRetryAt:N.nextRetryAt,error:N.error});break;case"mcp_log":C("mcp.log",{messageId:s(),revision:N.revision,serverName:N.serverName,level:N.level,logger:N.logger,message:N.message,projectedBytes:N.projectedBytes,dataSha256:N.dataSha256,truncated:N.truncated,detailsOmitted:N.detailsOmitted,timestamp:N.timestamp,synthetic:N.synthetic});break;case"mcp_instructions_changed":C("mcp.instructions.changed",{messageId:s(),revision:N.revision,serverName:N.serverName,action:N.action,reason:N.reason,text:N.text,sourceBytes:N.sourceBytes,projectedBytes:N.projectedBytes,sha256:N.sha256,truncated:N.truncated,detailsOmitted:N.detailsOmitted});break;case"mcp_task_changed":C("mcp.task.changed",{messageId:s(),revision:N.revision,taskId:N.taskId,serverName:N.serverName,toolName:N.toolName,status:N.status,statusMessage:N.statusMessage,createdAt:N.createdAt,updatedAt:N.updatedAt,completedAt:N.completedAt,hasResult:N.hasResult,error:N.error});break;case"project_rules_loaded":C("project.rules.loaded",{messageId:s(),files:N.files,triggerPaths:N.triggerPaths,blockedWrite:N.blockedWrite});break;case"steering_applied":C("steering.applied",{runId:j,messageIds:N.messageIds,count:N.count,recovered:N.recovered,delivery:N.delivery,queued:u.getPendingSteeringCount()});break;case"follow_up_started":{if(w)C("message.complete",{messageId:w}),w=void 0;for(let NO of N.messages){if(!NO.recovered||NO.persisted)continue;C("message.created",{messageId:NO.id,role:"user",content:A1(NO.content),recovered:!0})}C("follow_up.started",{runId:j,queued:N.queued,recovered:N.recovered}),s();break}case"goal_updated":C("goal.updated",{goal:N.goal});break;case"goal_continuation_started":C("goal.continuation.started",{goal:N.goal,continuation:N.continuation,...N.prematureStopPattern?{prematureStopPattern:N.prematureStopPattern}:{},...N.prematureStopCount!==void 0?{prematureStopCount:N.prematureStopCount}:{}}),s();break;case"compaction":C(N.phase==="start"?"compaction.started":"compaction.completed",{...N.reason?{reason:N.reason}:{},...N.strategy?{strategy:N.strategy}:{},...N.outcome?{outcome:N.outcome}:{},...N.preTokens!==void 0?{preTokens:N.preTokens}:{},...N.preTokenSource?{preTokenSource:N.preTokenSource}:{},...N.estimatedPendingTokens!==void 0?{estimatedPendingTokens:N.estimatedPendingTokens}:{},...N.postTokens!==void 0?{postTokens:N.postTokens}:{},...N.sampleAttempts!==void 0?{sampleAttempts:N.sampleAttempts}:{},...N.inputReductions!==void 0?{inputReductions:N.inputReductions}:{},...N.messagesOmitted!==void 0?{messagesOmitted:N.messagesOmitted}:{},...N.filesOmitted!==void 0?{filesOmitted:N.filesOmitted}:{},...N.imagesOmitted!==void 0?{imagesOmitted:N.imagesOmitted}:{},...N.fallbackTargetTokens!==void 0?{fallbackTargetTokens:N.fallbackTargetTokens}:{},...N.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:N.fallbackMessagesOmitted}:{},...N.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:N.fallbackMessagesTruncated}:{},...N.failureReason?{failureReason:N.failureReason}:{}});break;case"model_fallback":C("model.fallback",{});break;case"task_update":C("task.updated",{tasks:N.tasks});break;default:break}},wO=await H1(ZO.chatStream(x,PO,{stream:!0,pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly,outputSchema:G.outputSchema,taskAdmission:G.taskAdmission}),lO);if(!wO.success)throw Error(wO.error?.message??"Agent run failed");for(let N=0;N<20;N++){let NO=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,u.getPendingSteeringCount()===0){if(!NO)break;continue}if(z.signal.aborted)break;if(wO=await H1(ZO.chatStream("",PO,{stream:!0,pendingInputOnly:!0,taskAdmission:G.taskAdmission}),lO),!wO.success)throw Error(wO.error?.message??"Agent follow-up failed")}if($.messages=await R.loadSession($.id,$.projectPath),$.updatedAt=new Date,await tO($),z.signal.aborted||O.status==="cancelled"){await e(),C("session.status",{status:"idle"});return}if(w)C("message.complete",{messageId:w});C("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt??=new Date().toISOString(),C("session.completed",{runId:j,outputTruncated:wO.metadata?.outputTruncated??!1}),C("session.status",{status:"idle"})}catch(u){if(P&&G.preparedInputTurn)await P.finishTurn(G.preparedInputTurn.handle).catch(()=>{return});if(z.signal.aborted||O.status==="cancelled"){k0(O,"runtime-abort"),await e(),C("session.status",{status:"idle"});return}await tO($).catch(()=>{return}),g.error("[SessionRoutes] Agent execution error:",u),O.status="failed",$.taskStatus="failed",$.taskCompletedAt??=new Date().toISOString();let YO=t0(u);if(!$.taskFailure){let n=P?await P.setTaskStatus("failed",u).catch(()=>{return}):await R.updateSessionMetadata($.id,$.projectPath,{taskStatus:"failed",taskStatusReason:YO.message,taskFailure:YO,taskCompletedAt:$.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(n)X0($,n)}$.taskStatusReason??=YO.message,$.taskFailure??=YO,C("session.error",{error:$.taskFailure.message,taskFailure:$.taskFailure}),C("session.status",{status:"error"})}finally{if(G.taskAdmission?.release(),G.taskAdmission){let u=mO.getStats();C("task.status",{taskStatus:$.taskStatus,...$.taskStatusReason?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure?{taskFailure:$.taskFailure}:{},...$.taskStartedAt?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskDiffStat?{taskDiffStat:$.taskDiffStat}:{},taskQueueDepth:u.queued,taskConcurrencyLimit:u.maxConcurrent,taskInFlight:u.inFlight,taskAdmissionPaused:u.paused,updatedAt:new Date().toISOString()})}if(await ZO?.destroy().catch(()=>{return}),F?.release(),O.disposeRuntimeOnSettle&&G.disposeRuntime)await G.disposeRuntime($,P).catch((u)=>{g.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${$.id}:`,u)});ox(O)}}async function r$(O,$,x){g.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),g.info(`[SessionRoutes] Active runs: ${CO.size}`);for(let[G,z]of CO.entries())if(g.info(`[SessionRoutes] Checking run ${G}: sessionId=${z.sessionId}, projectPath=${z.projectPath}, pendingPermission=${z.pendingPermission?.permissionId}`),z.sessionId===O.sessionId&&z.projectPath===O.projectPath&&z.pendingPermission?.permissionId===$){if(z.pendingPermission.details.interactionRequestId)await nO.respond(O.projectPath,O.sessionId,$,x);return z.pendingPermission.resolve(x),g.info(`[SessionRoutes] Permission ${$} responded, runId: ${z.id}`),!0}let Q=await nO.findPending(O.projectPath,O.sessionId);if(!Q||Q.request.requestId!==$)return g.error(`[SessionRoutes] Permission not found: ${$}`),!1;await nO.respondAndRecover(O.projectPath,O.sessionId,$,x);let Z=r.get(p(O));if(!Z){let G=await R.findSessionMetadata(O.sessionId,O.projectPath);if(!G)return!1;let[z,U]=await Promise.all([R.loadSession(O.sessionId,O.projectPath),R.findSessionTaskWorktree(O.sessionId,O.projectPath)]);Z=E0(G,z,U),r.set(p(O),Z)}else await tO(Z);if(S.publish(O,"interaction.resolved",{requestId:$}),G0)G0(Z).catch((G)=>{g.error(`[SessionRoutes] Failed to resume recovered interaction ${$}:`,G)});return!0}var T1=o("Service"),Q2=V.Object({approved:V.Boolean(),remember:V.Optional(V.Boolean()),scope:V.Optional(JO(["once","session","project"])),targetMode:V.Optional(JO(["default","autoEdit","plan","yolo"])),feedback:V.Optional(V.String({maxLength:4000})),answers:V.Optional(V.Record(V.String({maxLength:80}),V.Union([V.String({maxLength:4000}),V.Array(V.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:V.Optional(V.Object({action:JO(["accept","decline","cancel"]),content:V.Optional(V.Record(V.String(),V.Union([V.String({maxLength:4000}),V.Number(),V.Boolean(),V.Array(V.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),e$=()=>{let O=new x2;return O.post("/:permissionId",async($)=>{let x=$.req.param("permissionId"),Q=$.req.query("sessionId"),Z=$.req.query("projectPath");T1.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${Q}`);try{let G=await $.req.json(),z=q(Q2,G);if(!z.success)throw new _("Invalid permission response format");let{approved:U,remember:j,scope:L,targetMode:b,feedback:w,answers:F,elicitation:P}=z.data;if(!Q)throw new _("sessionId query parameter is required");let ZO=await KO(Q,Z);if(!await r$(ZO,x,{approved:U,reason:w,scope:L,targetMode:b,feedback:w,answers:F,elicitation:P}))throw new f("Permission request",x);return T1.info(`[PermissionRoutes] Permission ${x} ${U?"approved":"denied"}`),$.json({success:!0,approved:U,remember:j})}catch(G){if(T1.error("[PermissionRoutes] Failed to respond to permission:",G),G instanceof _||G instanceof LO||G instanceof f||G instanceof xO)throw G;throw G}}),O};import O4 from"node:path";import{Hono as Z2}from"hono";var J2=V.Object({projectPath:V.String({minLength:1}),enabled:V.Boolean(),scope:V.Optional(JO(["local","project","global"]))}),Y2=V.Object({projectPath:V.String({minLength:1})}),z2=V.Object({projectPath:V.String({minLength:1}),source:V.String({minLength:1}),trust:V.Literal(!0),ref:V.Optional(V.String({minLength:1}))}),G2=V.Object({projectPath:V.String({minLength:1}),trust:V.Literal(!0)}),X2=V.Object({projectPath:V.String({minLength:1}),confirm:V.Literal(!0)}),V2=V.Object({projectPath:V.String({minLength:1}),source:V.String({minLength:1}),ref:V.Optional(V.String({minLength:1}))}),$4=V.Object({projectPath:V.String({minLength:1}),confirm:V.Optional(V.Literal(!0))}),N2=V.Object({projectPath:V.String({minLength:1}),scope:V.Optional(JO(["local","project","global"])),policy:V.Object({restrictToAllowedSources:V.Boolean(),requireGitCommitSha:V.Boolean(),allowedGitHosts:V.Array(V.String()),allowedMarketplaces:V.Array(V.String()),allowedLocalRoots:V.Array(V.String())})});function AO(O){if(!O||!O4.isAbsolute(O))throw new _("projectPath must be absolute");return O4.resolve(O)}async function x4(O){let[$,x]=await Promise.all([jO(O),T0.getInstance().loadWorkspacePluginSettingsResolution(O)]);return $.plugins.getAll().map((Q)=>({name:Q.manifest.name,description:Q.manifest.description,version:Q.manifest.version,source:Q.source,enabled:Q.status==="active",status:Q.status,commands:Q.commands.length,skills:Q.skills.length,agents:Q.agents.length,hooks:Q.hooks?Object.values(Q.hooks).reduce((Z,G)=>Z+(Array.isArray(G)?G.length:0),0):0,mcpServers:Object.keys(Q.mcpServers??{}).length,configurable:Q.source!=="cli",managed:Q.installation!==void 0,marketplace:Q.installation?.source.type==="marketplace"?Q.installation.source.marketplace:void 0,revision:Q.installation?.revision,installedAt:Q.installation?.installedAt,updatedAt:Q.installation?.updatedAt,compatibilityIssues:Q.compatibilityIssues??[],effectiveScope:Q.source==="cli"?"invocation":x.settings[Q.manifest.name]?.effectiveScope??"default",settingLayers:Q.source==="cli"?{invocation:!0}:x.settings[Q.manifest.name]?.layers??{}}))}async function K2(){let O=Q4(),[$,x]=await Promise.all([O.listCatalogs(),O.listInstallationRecords()]),Q=new Map(x.map((Z)=>[Z.name,Z]));return $.map(({marketplace:Z,manifest:G})=>({name:Z.name,description:G.description??G.metadata?.description??"",sourceType:Z.source.type,revision:Z.revision,updatedAt:Z.updatedAt,plugins:G.plugins.map((z)=>{let U=Q.get(z.name);return{name:z.name,description:z.description??"",version:z.version,category:z.category,tags:z.tags??[],installed:U!==void 0,installedVersion:U?.version}})}))}function V0(O,$){if(!O.success)throw new _(O.error??$)}var W4=()=>{let O=new Z2;return O.get("/",async($)=>{let x=AO($.req.query("projectPath"));return $.json(await x4(x))}),O.post("/refresh",async($)=>{let x=q(Y2,await $.req.json());if(!x.success)throw new _("Invalid plugin refresh request");let Q=AO(x.data.projectPath),Z=await J4(Q);return $.json({plugins:await x4(Q),errors:Z.discovery.errors.map((G)=>({code:G.code??"LOAD_ERROR",error:G.error}))})}),O.get("/catalog",async($)=>{return AO($.req.query("projectPath")),$.json(await K2())}),O.get("/policy",async($)=>{let x=AO($.req.query("projectPath")),Q=await T0.getInstance().loadWorkspacePluginSourcePolicy(x);return $.json({policy:Q,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),O.post("/policy",async($)=>{let x=q(N2,await $.req.json());if(!x.success)throw new _("Invalid plugin source policy request");let Q=AO(x.data.projectPath),Z=await Y4(Q,x.data.policy,x.data.scope??"global");return $.json({policy:Z})}),O.post("/install",async($)=>{let x=q(z2,await $.req.json());if(!x.success)throw new _("Invalid plugin install request; explicit source trust is required");let Q=AO(x.data.projectPath),{result:Z}=await z4(Q,x.data.source,{trusted:x.data.trust,ref:x.data.ref});return V0(Z,"Plugin installation failed"),$.json({name:Z.pluginName,version:Z.manifest?.version,revision:Z.installation?.revision,changed:Z.changed,installedDependencies:Z.installedDependencies??[]})}),O.post("/marketplaces",async($)=>{let x=q(V2,await $.req.json());if(!x.success)throw new _("Invalid marketplace add request");let Q=AO(x.data.projectPath),Z=await V4(Q,x.data.source,x.data.ref);return V0(Z,"Marketplace installation failed"),$.json({name:Z.marketplace?.name,plugins:Z.manifest?.plugins.length??0,revision:Z.marketplace?.revision,changed:Z.changed})}),O.post("/marketplaces/:name/refresh",async($)=>{let x=q($4,await $.req.json());if(!x.success)throw new _("Invalid marketplace refresh request");let Q=await N4(AO(x.data.projectPath),$.req.param("name"));return V0(Q,"Marketplace refresh failed"),$.json({name:Q.marketplace?.name,plugins:Q.manifest?.plugins.length??0,revision:Q.marketplace?.revision,changed:Q.changed})}),O.post("/marketplaces/:name/remove",async($)=>{let x=q($4,await $.req.json());if(!x.success||x.data.confirm!==!0)throw new _("Invalid marketplace removal request; explicit confirmation is required");AO(x.data.projectPath);let Q=await K4($.req.param("name"),!0);return V0(Q,"Marketplace removal failed"),$.json({name:Q.marketplace?.name,removed:!0})}),O.post("/:name/update",async($)=>{let x=q(G2,await $.req.json());if(!x.success)throw new _("Invalid plugin update request; explicit source trust is required");let Q=AO(x.data.projectPath),{result:Z}=await G4(Q,$.req.param("name"),{trusted:x.data.trust});return V0(Z,"Plugin update failed"),$.json({name:Z.pluginName,version:Z.manifest?.version,revision:Z.installation?.revision,changed:Z.changed,updatedDependencies:Z.updatedDependencies??[]})}),O.post("/:name/uninstall",async($)=>{let x=q(X2,await $.req.json());if(!x.success)throw new _("Invalid plugin uninstall request; explicit confirmation is required");let Q=AO(x.data.projectPath),{result:Z}=await X4(Q,$.req.param("name"),x.data.confirm);return V0(Z,"Plugin uninstall failed"),$.json({name:Z.pluginName,removed:!0})}),O.post("/:name/state",async($)=>{let x=q(J2,await $.req.json());if(!x.success)throw new _("Invalid plugin state request");let Q=AO(x.data.projectPath),Z=$.req.param("name"),z=(await jO(Q)).plugins.get(Z);if(!z)throw new f("Plugin",Z);if(z.source==="cli")throw new _(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);let U=await Z4(Q,Z,x.data.enabled,x.data.scope??"local");return $.json(U)}),O};import{Hono as D2}from"hono";import{execFile as W2}from"node:child_process";import F2 from"node:path";var C1="__BLADE_DIRECTORY_PICKER_CANCELLED__",U2=900000;function _2(O,$){return new Promise((x)=>{W2(O,[...$],{timeout:U2,maxBuffer:65536,windowsHide:!0},(Q,Z,G)=>{let z=Q?.code;x({stdout:Z,stderr:G,exitCode:typeof z==="number"?z:Q?1:0,...typeof z==="string"?{errorCode:z}:{}})})})}function j1(O){let $=O.replace(/[\r\n]+$/,"");if(!$||$===C1)return{cancelled:!0};if(!F2.isAbsolute($))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:$}}function b1(O){return O.exitCode!==0||Boolean(O.errorCode)}class F4{platform;runCommand;activeSelection=null;constructor(O={}){this.platform=O.platform??process.platform,this.runCommand=O.runCommand??_2}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 "${C1}"`,"end try"].join(`
8
- `),$=await this.runCommand("osascript",["-e",O]);if(b1($))throw Error("Unable to open the macOS folder picker");return j1($.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("${C1}")`,"}"].join("; "),$=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",O]);if(b1($))throw Error("Unable to open the Windows folder picker");return j1($.stdout)}async pickOnLinux(){let O=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let $ of O){let x=await this.runCommand($.command,$.args);if(x.errorCode==="ENOENT")continue;if(x.exitCode===1&&!x.stdout.trim()&&!x.stderr.trim())return{cancelled:!0};if(b1(x))throw Error("Unable to open the Linux folder picker");return j1(x.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var U4=new F4;var H2=V.Object({path:V.String({minLength:1})});function L2(O){if(!O)return!1;if(O==="tauri://localhost"||O==="http://tauri.localhost")return!0;try{let $=new URL(O).hostname;return $==="localhost"||$==="127.0.0.1"||$==="::1"||$==="[::1]"}catch{return!1}}var _4=(O={})=>{let $=new D2,x=O.pickDirectory??(()=>U4.pick()),Q=O.allowDirectoryPickerRequest??L2;return $.get("/",async(Z)=>{return Z.json(await O1.list(c()))}),$.post("/",async(Z)=>{let G;try{G=await Z.req.json()}catch{throw new _("A valid JSON body is required")}let z=q(H2,G);if(!z.success)throw new _("A project path is required");try{let U=await O1.bind(z.data.path,c());return Z.json(U,201)}catch(U){throw new _(U instanceof Error?U.message:"Failed to bind project")}}),$.post("/pick",async(Z)=>{if(!Q(Z.req.header("Origin")))throw new xO("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Z.json(await x())}catch(G){throw new _(G instanceof Error?G.message:"Failed to select a folder")}}),$.delete("/",async(Z)=>{let G=Z.req.query("path");if(!G)throw new _("A project path is required");try{let z=await O1.unbind(G);return Z.json({success:!0,removed:z})}catch(z){throw new _(z instanceof Error?z.message:"Failed to unbind project")}}),$};import{Hono as B2}from"hono";var D4=o("Service"),w4=()=>{let O=new B2;return O.get("/",async($)=>{try{let x=await L4();return $.json(x)}catch(x){return D4.error("[ProviderRoutes] Failed to list providers:",x),$.json([])}}),O.get("/:provider/models",async($)=>{let x=$.req.param("provider");try{let Q=await B4(x);return $.json(Q)}catch(Q){return D4.error("[ProviderRoutes] Failed to list models:",Q),$.json([])}}),O.put("/:provider/credential",async($)=>{let x=$.req.param("provider"),Q=await $.req.json();if(!Q.apiKey?.trim())throw new _("apiKey is required");return await cO().setApiKey(x,Q.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await cO().clearCredential($.req.param("provider")),$.json({success:!0})}),O.put("/:provider",async($)=>{let x=$.req.param("provider"),Q=QO(),Z=Q?.modelProviders[x];if(!Q||!Z)throw new f("Model provider",x);let G=await $.req.json();if(!G.name||!G.baseUrl||!G.wireApi)throw new _("name, baseUrl and wireApi are required");let z="apiKeyEnv"in G?G.apiKeyEnv?.trim():Z.apiKeyEnv,U={name:G.name,baseUrl:G.baseUrl,wireApi:G.wireApi,...z?{apiKeyEnv:z}:{}},j=cO(),L=G.apiKey?.trim()?await j.credentials.read(x):void 0;if(G.apiKey?.trim())await j.setApiKey(x,G.apiKey.trim());try{return await BO().updateModelProvider(x,U),$.json({success:!0})}catch(b){if(G.apiKey?.trim())if(L)await j.credentials.modify(x,async()=>L);else await j.credentials.delete(x);if(b instanceof Error&&(b.message.includes("modelProviders.")||b.message.includes("built-in provider")))throw new _(b.message);throw b}}),O.delete("/:provider",async($)=>{let x=$.req.param("provider");if(!QO()?.modelProviders[x])throw new f("Model provider",x);let Z=$.req.query("removeModels");if(Z!==void 0&&Z!=="true"&&Z!=="false")throw new _("removeModels must be true or false");try{let G=await BO().removeModelProvider(x,{removeModels:Z==="true"});return $.json({success:!0,...G})}catch(G){if(G instanceof Error&&(G.message.includes("still referenced")||G.message.includes("owns the only model")))throw new k(G.message);throw G}}),O.post("/:provider/probe",async($)=>{let x=$.req.param("provider"),Q=QO();if(!Q?.modelProviders[x])throw new f("Model provider",x);let Z=await $.req.json().catch(()=>({})),G=Q.models.filter((U)=>U.provider===x),z=Z.modelId?G.find((U)=>U.id===Z.modelId):G[0];if(!z)throw new _(Z.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return $.json(await H4(z,Q))}),O};import{Hono as w2}from"hono";var A2=o("Service"),j4=(O,$)=>{let x=new w2;return x.onError((Q,Z)=>{if(Q instanceof xO)return Z.json(Q.toObject(),Q.statusCode);return A2.error("[ScheduleRoutes] Unhandled route error:",Q),Z.json(new t("Schedule request failed").toObject(),500)}),x.get("/",async(Q)=>{let Z=await O.list();return Q.json(T4.parse({schedules:Z}))}),x.post("/",async(Q)=>{let Z;try{Z=await Q.req.json()}catch{throw new _("Invalid request body")}let G=q(A4,Z);if(!G.success)throw new _("Invalid schedule request");let z=G.data.projectPath||Q.get("directory")||c();try{let U=await O.create({...G.data,projectPath:z});return Q.json(sO.parse(U),201)}catch(U){throw new _(U instanceof Error?U.message:"Failed to create schedule")}}),x.get("/:id",async(Q)=>{let Z=await O.get(Q.req.param("id"));if(!Z)throw new f("Schedule not found");return Q.json(sO.parse(Z))}),x.patch("/:id",async(Q)=>{let Z;try{Z=await Q.req.json()}catch{throw new _("Invalid request body")}let G=q(M4,Z);if(!G.success)throw new _("Invalid schedule update");let{modelId:z,reasoningEffort:U,serviceTier:j,responseVerbosity:L,communicationStyle:b,isolation:w,permissionMode:F,...P}=G.data,ZO={...z!==void 0?{modelId:z}:{},...U!==void 0?{reasoningEffort:U}:{},...j!==void 0?{serviceTier:j}:{},...L!==void 0?{responseVerbosity:L}:{},...b!==void 0?{communicationStyle:b}:{},...w!==void 0?{isolation:w}:{},...F!==void 0?{permissionMode:F}:{}};try{let d=await O.update(Q.req.param("id"),{...P,...Object.keys(ZO).length>0?{dispatch:ZO}:{}});if(!d)throw new f("Schedule not found");return Q.json(sO.parse(d))}catch(d){if(d instanceof xO)throw d;throw new _(d instanceof Error?d.message:"Failed to update schedule")}}),x.delete("/:id",async(Q)=>{if(!await O.remove(Q.req.param("id")))throw new f("Schedule not found");return Q.json({ok:!0})}),x.post("/:id/enable",async(Q)=>{let Z=await O.setEnabled(Q.req.param("id"),!0);if(!Z)throw new f("Schedule not found");return Q.json(sO.parse(Z))}),x.post("/:id/disable",async(Q)=>{let Z=await O.setEnabled(Q.req.param("id"),!1);if(!Z)throw new f("Schedule not found");return Q.json(sO.parse(Z))}),x.post("/:id/run",async(Q)=>{let Z=await O.get(Q.req.param("id"));if(!Z)throw new f("Schedule not found");if(!$)throw new t("Scheduler is not running in this process");await $.fire(Z,new Date,{manual:!0});let G=await O.get(Z.id);return Q.json(sO.parse(G??Z),202)}),x};import*as pO from"node:fs/promises";import{homedir as S4}from"node:os";import*as MO from"node:path";import{Hono as M2}from"hono";var rO=o("Service"),b4=MO.join(S4(),".blade","skills"),S1=MO.join(S4(),".blade","skills-config.json");async function R4(){try{let O=await pO.readFile(S1,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function T2(O){await pO.mkdir(MO.dirname(S1),{recursive:!0}),await pO.writeFile(S1,JSON.stringify(O,null,2))}async function j2(O,$){let x=await R4();if($)x.disabled=x.disabled.filter((Q)=>Q!==O);else if(!x.disabled.includes(O))x.disabled.push(O);await T2(x)}var uO=null,b2=300000,C2=6;async function S2(){if(uO&&Date.now()-uO.timestamp<b2)return uO.data;try{let O=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!O.ok){if(rO.warn(`GitHub API returned ${O.status}`),uO)return uO.data;throw Error(`GitHub skills catalog returned ${O.status}`)}let x=(await O.json()).filter((z)=>z.type==="dir"),Q=Array(x.length),Z=0,G=Math.min(C2,x.length);return await Promise.all(Array.from({length:G},async()=>{while(Z<x.length){let z=Z++,U=x[z];if(!U)continue;let j=`Official ${U.name} skill`;try{let L=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${U.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(L.ok){let w=(await L.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(w)j=w[1].trim().slice(0,100)}}catch{}Q[z]={name:U.name,description:j,tag:"Official",author:"Anthropic"}}})),uO={data:Q,timestamp:Date.now()},Q}catch(O){if(rO.warn("Failed to fetch skills catalog from GitHub:",O),uO)return uO.data;throw O}}var E4=()=>{let O=new M2;return O.get("/",async($)=>{try{let x=$.get("directory")||c(),Z=(await jO(x)).skills.getAll(),G=await R4(),z=Z.map((U)=>({id:U.name,name:U.name,enabled:!G.disabled.includes(U.name),description:U.description||"",version:U.version||"1.0.0",provider:"Local",location:U.source==="builtin"?"Built-in":U.basePath,removable:U.source==="user"&&MO.dirname(MO.resolve(U.basePath))===MO.resolve(b4),capabilities:["prompts"],allowedTools:U.allowedTools||[]}));return $.json(z)}catch(x){return rO.error("[SkillsRoutes] Failed to get skills:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills"},500)}}),O.post("/:name/toggle",async($)=>{try{let x=$.req.param("name"),Q=await $.req.json();return await j2(x,Q.enabled),$.json({success:!0,enabled:Q.enabled})}catch(x){return rO.error("[SkillsRoutes] Failed to toggle skill:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name"),Q=$.get("directory")||c();return C0(Q,async(Z)=>{let G=Z.skills,z=G.get(x);if(!z)return $.json({success:!1,error:"Skill not found"},404);let U=MO.resolve(z.basePath),j=MO.resolve(b4);if(z.source!=="user"||MO.dirname(U)!==j)return $.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await pO.rm(U,{recursive:!0,force:!0}),await G.refresh(),b0(Q),await j0(Q),$.json({success:!0})})}catch(x){return rO.error("[SkillsRoutes] Failed to uninstall skill:",x),$.json({success:!1,error:x.message},500)}}),O.post("/install",async($)=>{try{let x=await $.req.json(),Q=C4(),Z=$.get("directory")||c();return C0(Z,async(G)=>{let z=G.skills,U=!1;if(x.source==="catalog"&&x.name){if(U=await Q.installOfficialSkill(x.name),!U)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(U=await Q.installFromRepo(x.url,x.name),!U)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(x.source==="local"&&x.path){if(U=await Q.installFromLocal(x.path,x.name),!U)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await z.refresh(),b0(Z),await j0(Z),$.json({success:!0})})}catch(x){return rO.error("[SkillsRoutes] Failed to install skill:",x),$.json({success:!1,error:x.message},500)}}),O.get("/catalog",async($)=>{try{let x=await S2();return $.json(x)}catch(x){return rO.error("[SkillsRoutes] Failed to get catalog:",x),$.json({error:x instanceof Error?x.message:"Failed to get skills catalog"},502)}}),O};import{execSync as R2}from"node:child_process";import{readdir as E2}from"node:fs/promises";import $1 from"node:path";import k2 from"fast-glob";import{Hono as q2}from"hono";var m0=o("Service"),I2=(O)=>{try{return R2("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},P2=[...N0.map((O)=>`${O}/**`),...N0,...N0.map((O)=>`**/${O}/**`),...N0.map((O)=>`**/${O}`),...R1.map((O)=>`**/${O}`)],y2=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),I4=()=>{let O=new q2;return O.get("/commands",async($)=>{try{let x=$.req.query("q")||"",Q=$.get("directory")||c(),Z=await jO(Q),G=q4(x,Q,Z).filter((z)=>!y2.has(z.command));return $.json(G)}catch(x){return m0.error("[SuggestionsRoutes] Failed to get command suggestions:",x),$.json([])}}),O.get("/files",async($)=>{try{let x=$.req.query("q")||"",Q=$.get("directory")||c(),Z=Math.min(Number($.req.query("limit"))||100,1000),G=$.req.query("type")==="file",U=(await k2("**/*",{cwd:Q,dot:!1,followSymbolicLinks:!1,onlyFiles:G,markDirectories:!0,unique:!0,ignore:P2})).map((b)=>b.replace(/\\/g,"/"));if(!x)return $.json(U.slice(0,Z));let j=x.toLowerCase(),L=U.filter((b)=>b.toLowerCase().includes(j)).slice(0,Z);return $.json(L)}catch(x){return m0.error("[SuggestionsRoutes] Failed to get file suggestions:",x),$.json([])}}),O.get("/files/tree",async($)=>{try{let x=$.get("directory")||c(),Q=$.req.query("path")||"",Z=Q?$1.join(x,Q):x,z=(await E2(Z,{withFileTypes:!0})).map((L)=>({name:L.name,path:Q?`${Q}/${L.name}`:L.name,type:L.isDirectory()?"dir":"file"}));z.sort((L,b)=>{if(L.type!==b.type)return L.type==="dir"?-1:1;return L.name.localeCompare(b.name)});let U=new Set(N0),j=z.filter((L)=>{let b=L.name;if(b.startsWith("."))return!1;if(U.has(b))return!1;for(let w of R1)if(b.match(new RegExp(w.replace("*",".*"))))return!1;return!0});return $.json(j)}catch(x){return m0.error("[SuggestionsRoutes] Failed to get file tree:",x),$.json([])}}),O.get("/files/content",async($)=>{try{let x=$.req.query("path");if(!x)return $.json({error:"Missing file path"},400);let Q=$.get("directory")||c(),Z=$1.resolve(Q,x),G=$1.relative(Q,Z);if(G.startsWith("..")||$1.isAbsolute(G))return $.json({error:"Invalid file path"},400);let z=k4(),U=await z.stat(Z);if(!U?.isFile)return $.json({error:"File not found"},404);let j=200000,L=await z.readTextFile(Z),b=L.length>j;return $.json({path:x,content:b?L.slice(0,j):L,truncated:b,size:U.size})}catch(x){return m0.error("[SuggestionsRoutes] Failed to get file content:",x),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{try{let x=$.get("directory")||c(),Q=I2(x);return $.json({branch:Q})}catch(x){return m0.error("[SuggestionsRoutes] Failed to get git info:",x),$.json({branch:null})}}),O};import{Hono as f2}from"hono";var K0=o("Service"),h4=(O)=>{let $=new f2;return $.onError((x,Q)=>{if(x instanceof xO)return Q.json(x.toObject(),x.statusCode);return K0.error("[TaskRoutes] Unhandled route error:",x),Q.json(new t("Failed to dispatch task").toObject(),500)}),$.post("/",async(x)=>{let Q;try{Q=await x.req.json()}catch{throw new _("Invalid request body")}let Z=q(y4,Q);if(!Z.success)throw new _("Invalid task request");if((Z.data.attachments??[]).reduce((z,U)=>z+(typeof U.content==="string"?Buffer.byteLength(U.content):0),0)>r0)throw new _("Task attachments exceed the 5 MiB limit");if(Z.data.taskDueAt&&!Number.isFinite(Date.parse(Z.data.taskDueAt)))throw new _("Invalid task due date");try{let z=await O.dispatchTask({prompt:Z.data.prompt,title:Z.data.title,taskPriority:Z.data.taskPriority,taskKind:Z.data.taskKind,taskDueAt:Z.data.taskDueAt?new Date(Z.data.taskDueAt).toISOString():void 0,sourceProjectPath:Z.data.projectPath||x.get("directory")||c(),isolation:Z.data.isolation,permissionMode:Z.data.permissionMode,modelId:Z.data.modelId,reasoningEffort:Z.data.reasoningEffort,serviceTier:Z.data.serviceTier,responseVerbosity:Z.data.responseVerbosity,communicationStyle:Z.data.communicationStyle,attachments:Z.data.attachments,outputSchema:Z.data.outputSchema});return x.json(k1.parse(z),202)}catch(z){if(z instanceof _||z instanceof k||z instanceof qO||z instanceof kO)throw z;throw K0.error("[TaskRoutes] Failed to dispatch task:",z),new t("Failed to dispatch task")}}),$.patch("/:sessionId",async(x)=>{let Q;try{Q=await x.req.json()}catch{throw new _("Invalid request body")}let Z=q(f4,Q);if(!Z.success)throw new _("Invalid task update");if(Z.data.title===void 0&&Z.data.taskPriority===void 0&&Z.data.taskKind===void 0&&Z.data.taskDueAt===void 0)throw new _("Task update must include at least one field");if(typeof Z.data.taskDueAt==="string"&&!Number.isFinite(Date.parse(Z.data.taskDueAt)))throw new _("Invalid task due date");try{let G=await O.updateTask(x.req.param("sessionId"),{...Z.data,...typeof Z.data.taskDueAt==="string"?{taskDueAt:new Date(Z.data.taskDueAt).toISOString()}:{}},x.req.query("projectPath"));return x.json(E1.parse(G))}catch(G){if(G instanceof _||G instanceof f||G instanceof k)throw G;throw K0.error("[TaskRoutes] Failed to update task:",G),new t("Failed to update task")}}),$.post("/:sessionId/retry",async(x)=>{try{let Q=await O.retryTask(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(k1.parse(Q),202)}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof k||Q instanceof qO||Q instanceof kO)throw Q;throw K0.error("[TaskRoutes] Failed to retry task:",Q),new t("Failed to retry task")}}),$.get("/:sessionId/diff",async(x)=>{try{let Q=await O.getTaskDiff(x.req.param("sessionId"),x.req.query("projectPath"));return x.json(P4.parse(Q))}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof k)throw Q;throw K0.error("[TaskRoutes] Failed to load task diff:",Q),new t("Failed to load task diff")}}),$.post("/:sessionId/delivery",async(x)=>{let Q;try{Q=await x.req.json()}catch{throw new _("Invalid request body")}let Z=q(m4,Q);if(!Z.success)throw new _("Invalid task delivery request");try{let G=await O.deliverTask(x.req.param("sessionId"),Z.data.action,x.req.query("projectPath"));return x.json(E1.parse(G))}catch(G){if(G instanceof _||G instanceof f||G instanceof k)throw G;throw K0.error("[TaskRoutes] Failed to deliver task:",G),new t("Failed to deliver task")}}),$};import v4 from"node:path";import{Hono as g2}from"hono";var m2=eO(V.Object({id:V.String(),name:V.String(),subagentType:V.String(),description:V.String(),agentId:V.Optional(V.String()),status:JO(["leader","running","completed","failed","cancelled","unknown"]),result:V.Optional(V.Unknown()),stats:V.Optional(V.Unknown()),worktreePath:V.Optional(V.String())})),h2=eO(V.Object({id:V.String(),subject:V.String(),description:V.String(),status:JO(["pending","blocked","running","completed"]),owner:V.Optional(V.String()),priority:JO(["high","medium","low"]),dependsOn:V.Array(V.String()),blocks:V.Array(V.String()),result:V.Optional(V.String()),createdAt:V.String(),startedAt:V.Optional(V.String()),completedAt:V.Optional(V.String())})),d9=eO(V.Object({name:V.String(),description:V.Optional(V.String()),status:JO(["idle","running","completed","failed","deleted"]),leadAgentId:V.String(),leadSessionId:V.Optional(V.String()),workspaceRoot:V.Optional(V.String()),peerMessagingEnabled:V.Boolean(),createdAt:V.Number(),updatedAt:V.Number(),deletedAt:V.Optional(V.Number()),members:V.Array(m2),tasks:V.Array(h2)})),g4=eO(V.Object({sessionId:V.String({minLength:1}),projectPath:V.String({minLength:1}),name:V.String({minLength:1}),description:V.Optional(V.String()),leadAgentType:V.Optional(V.String()),peerMessagingEnabled:V.Optional(V.Boolean()),members:V.Array(V.Object({name:V.String({minLength:1}),subagentType:V.String({minLength:1}),description:V.Optional(V.String()),prompt:V.String({minLength:10,maxLength:32768})}),{maxItems:32}),tasks:V.Optional(V.Array(V.Object({subject:V.String({minLength:1}),description:V.String({minLength:1}),dependsOn:V.Optional(V.Array(V.String())),assignedTo:V.Optional(V.String()),priority:V.Optional(JO(["high","medium","low"]))}),{maxItems:256}))})),u4=eO(V.Object({sessionId:V.String({minLength:1}),projectPath:V.String({minLength:1}),to:V.String({minLength:1}),message:V.String({minLength:1,maxLength:32768})})),p4=eO(V.Object({sessionId:V.String({minLength:1}),projectPath:V.String({minLength:1}),memberId:V.String({minLength:1})}));var u2=o("Service"),c4=()=>{let O=new g2;return O.onError(($,x)=>{if($ instanceof xO)return x.json($.toObject(),$.statusCode);return u2.error("[TeamRoutes] Unhandled route error:",$),x.json(new t("Team operation failed").toObject(),500)}),O.get("/",async($)=>{F0();let x=await U0($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await W0(x.projectPath).list(x))}),O.post("/",async($)=>{F0();let x=q(g4,await q1($.req));if(!x.success)throw new _("Invalid team request");let Q=await U0(x.data.sessionId,x.data.projectPath),Z=await R.findSessionMetadata(Q.sessionId,Q.projectPath);return $.json(await W0(Q.projectPath).create({name:x.data.name,description:x.data.description,leadAgentType:x.data.leadAgentType,owner:Q,modelId:Z?.selectedModelId,peerMessagingEnabled:x.data.peerMessagingEnabled,members:x.data.members,tasks:x.data.tasks}),201)}),O.get("/:teamName",async($)=>{F0();let x=await U0($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await W0(x.projectPath).getSnapshot($.req.param("teamName"),x))}),O.post("/:teamName/messages",async($)=>{F0();let x=q(u4,await q1($.req));if(!x.success)throw new _("Invalid team message");let Q=await U0(x.data.sessionId,x.data.projectPath),Z=await W0(Q.projectPath).sendMessage({name:$.req.param("teamName"),to:x.data.to,body:x.data.message,owner:Q});return $.json({messages:Z})}),O.post("/:teamName/tasks/claim",async($)=>{F0();let x=q(p4,await q1($.req));if(!x.success)throw new _("Invalid team task claim");let Q=await U0(x.data.sessionId,x.data.projectPath);return $.json({task:await W0(Q.projectPath).claimTask($.req.param("teamName"),x.data.memberId,Q)})}),O.delete("/:teamName",async($)=>{F0();let x=await U0($.req.query("sessionId"),$.req.query("projectPath"));return $.json(await W0(x.projectPath).delete($.req.param("teamName"),{owner:x,killRunning:!0}))}),O};function W0(O){return new i4({configDir:s0(),subagentRegistry:l4(O)})}function F0(){if(d4().config.config?.agentTeamsEnabled!==!0)throw new qO("Agent Teams are disabled")}async function U0(O,$){if(!O||!$||!v4.isAbsolute($))throw new _("sessionId and absolute projectPath are required");let x=v4.resolve($);if(!await R.findSessionMetadata(O,x))throw new f(`Session not found: ${O}`);return{sessionId:O,projectPath:x}}async function q1(O){try{return await O.json()}catch{throw new _("Invalid request body")}}import{Hono as p2}from"hono";var vO=o("Service"),_0=new Map,a4=2097152,o4=65536;function n4(){return typeof globalThis.Bun<"u"}async function v2(O,$,x){if(n4()){let{spawn:G}=await import("bun-pty"),z=G(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:z.pid,write:(U)=>z.write(U),resize:(U,j)=>z.resize(U,j),kill:()=>z.kill(),onData:(U)=>z.onData(U),onExit:(U)=>z.onExit(U)}}let Z=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:Z.pid,write:(G)=>Z.write(G),resize:(G,z)=>Z.resize(G,z),kill:()=>Z.kill(),onData:(G)=>{Z.onData(G)},onExit:(G)=>{Z.onExit(G)}}}var y1=void 0,P1;if(n4())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();P1=$.upgradeWebSocket,y1=$.websocket}catch(O){vO.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function t4(O,$){let x=`term-${Date.now()}`;vO.info(`[Terminal] New connection: ${x}, cwd: ${O}`);let Q=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Z=Q.endsWith("sh")?["-l"]:[],G=await v2(Q,Z,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),z={id:x,process:G,cwd:O,buffer:"",subscribers:new Set};if(_0.set(x,z),z.subscribers.add($),G.onData((U)=>{let j=!1;for(let L of z.subscribers)try{L.send(U),j=!0}catch{z.subscribers.delete(L)}if(j)return;if(z.buffer+=U,z.buffer.length>a4)z.buffer=z.buffer.slice(-a4)}),G.onExit(({exitCode:U})=>{vO.info(`[Terminal] Process exited: ${x}, code: ${U}`);for(let j of z.subscribers)try{j.close()}catch{}_0.delete(x)}),z.buffer){let U=z.buffer;z.buffer="";for(let j=0;j<U.length;j+=o4)$.send(U.slice(j,j+o4))}return{session:z,cleanup:()=>{if(vO.info(`[Terminal] Connection closed: ${x}`),z.subscribers.delete($),z.subscribers.size===0){try{z.process.kill()}catch{}_0.delete(x)}}}}function s4(O,$){O.on("connection",async(x,Q)=>{let Z=new URL(Q.url||"/",`http://${Q.headers.host}`);if(!Z.pathname.endsWith("/terminal/ws")){x.close();return}let G=Z.searchParams.get("cwd")||$()||c();try{let{session:z,cleanup:U}=await t4(G,{send:(j)=>x.send(j),close:()=>x.close()});x.on("message",(j)=>{try{z.process.write(String(j))}catch(L){vO.error("[Terminal] Failed to write to PTY:",L)}}),x.on("close",U),x.on("error",U)}catch(z){vO.error("[Terminal] Failed to spawn PTY:",z),x.close()}})}var r4=()=>{let O=new p2;if(O.get("/status",($)=>{let x=Array.from(_0.values()).map((Q)=>({id:Q.id,cwd:Q.cwd}));return $.json({active:x.length,terminals:x})}),O.post("/kill/:terminalId",($)=>{let x=$.req.param("terminalId"),Q=_0.get(x);if(Q){try{Q.process.kill()}catch{}for(let Z of Q.subscribers)Z.close();return _0.delete(x),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),P1)O.get("/ws",P1(($)=>{let x=$.req.query("cwd")||$.get("directory")||c(),Q;return{async onOpen(Z,G){try{Q=await t4(x,{send:(z)=>G.send(z),close:()=>G.close()})}catch(z){vO.error("[Terminal] Failed to spawn PTY:",z),G.close()}},onMessage(Z){if(!Q)return;try{Q.session.process.write(String(Z.data))}catch(G){vO.error("[Terminal] Failed to write to PTY:",G)}},onClose(){Q?.cleanup()}}}));else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};import d2 from"node:path";import{Hono as l2}from"hono";var i2=V.Object({projectPath:V.String({minLength:1}),action:JO(["trust","revoke"])});function e4(O){if(!d2.isAbsolute(O))throw new _("projectPath must be absolute")}var $x=()=>{let O=new l2;return O.get("/",async($)=>{let x=$.req.query("projectPath");if(!x)throw new _("projectPath query parameter is required");return e4(x),$.json(await f1.getInstance().getStatus(x))}),O.post("/",async($)=>{let x=q(i2,await $.req.json());if(!x.success)throw new _("Invalid workspace trust request");let{projectPath:Q,action:Z}=x.data;e4(Q);let G=f1.getInstance(),z=Z==="trust"?await G.trust(Q):await G.revoke(Q);return await Ox(),$.json({...z,reloadRequired:z.sensitiveSources>0})}),O};var FO=o("Service"),g1=[],x1,D0,H0,h0,xx=new Map,Qx=new Map,Q3=new Set([".css",".html",".js",".json",".svg"]),Z3=1024,J3=3600000;function Y3(O,$){if(!O)return 0;let x=O.split(",").map((Q)=>{let[Z,...G]=Q.trim().toLowerCase().split(";"),z=G.find((j)=>j.trim().startsWith("q=")),U=z?Number(z.trim().slice(2)):1;return{name:Z,quality:Number.isFinite(U)?Math.max(0,Math.min(1,U)):0}});return x.find((Q)=>Q.name===$)?.quality??x.find((Q)=>Q.name==="*")?.quality??0}function Zx(){if(H0)return;let O=()=>{R.collectStaleEmptySessions().then(($)=>{if($>0)FO.info(`[SessionGC] removed ${$} stale empty session(s)`)}).catch(($)=>{FO.warn("[SessionGC] failed to collect stale empty sessions:",$)})};O(),H0=setInterval(O,J3),H0.unref?.()}function z3(){if(!H0)return;clearInterval(H0),H0=void 0}function G3(O){return["br","gzip"].map((x)=>({encoding:x,quality:Y3(O,x)})).filter((x)=>x.quality>0).sort((x,Q)=>Q.quality-x.quality||(x.encoding==="br"?-1:1))[0]?.encoding}function X3(O){let $=xx.get(O);if($)return $;let x=g0(O);return xx.set(O,x),x}function V3(O,$,x){let Q=`${x}:${O}`,Z=Qx.get(Q);if(Z)return Z;let G=x==="br"?s2($,{params:{[e2.BROTLI_PARAM_QUALITY]:5}}):r2($,{level:6});return Qx.set(Q,G),G}function N3(){let O=o2(t2(import.meta.url)),$=[dO(O,"web"),dO(c(),"dist/web"),dO(c(),"packages/cli/dist/web")];for(let x of $){let Q=dO(x,"index.html");if(h1(Q)){if(g0(Q,"utf-8").includes("/assets/"))return FO.debug(`[Server] Found web dist at: ${x}`),x}}return null}function K3(){let O=new O3;O.onError((Q,Z)=>{if(FO.error("[Server] Request error:",Q),Q instanceof zx){let z=new kO(Q.message,{resource:"workspace_agent_resources",limit:Q.capacity});return Z.json(z.toObject(),429)}if(Q instanceof xO)return Z.json(Q.toObject(),Q.statusCode);let G=Q instanceof Error?Q.message:String(Q);return Z.json({error:{code:"INTERNAL_ERROR",message:G}},500)}),O.use(async(Q,Z)=>{let G=process.env.BLADE_SERVER_PASSWORD;if(!G)return Z();let z=Q.req.path;if(z==="/"||z==="/favicon.svg"||z.startsWith("/assets/")||z.endsWith(".html")||z.endsWith(".js")||z.endsWith(".css"))return Z();let U=Q.req.header("Authorization");if(!U?.startsWith("Basic "))return Q.header("WWW-Authenticate",'Basic realm="Blade Server"'),Q.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let j=Buffer.from(U.slice(6),"base64").toString(),[L,b]=j.split(":"),w=process.env.BLADE_SERVER_USERNAME??"blade";if(L!==w||b!==G)return Q.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Z()}),O.use(async(Q,Z)=>{let G=Q.req.path==="/health"||Q.req.path==="/global/health"||Q.req.path.startsWith("/assets/");if(!G)FO.debug(`[Server] ${Q.req.method} ${Q.req.path}`);let z=Date.now();if(await Z(),!G){let U=Date.now()-z;FO.debug(`[Server] ${Q.req.method} ${Q.req.path} - ${Q.res.status} (${U}ms)`)}}),O.use($3({origin(Q){if(!Q)return;if(Q.startsWith("http://localhost:"))return Q;if(Q.startsWith("http://127.0.0.1:"))return Q;if(Q==="tauri://localhost"||Q==="http://tauri.localhost")return Q;if(g1.includes(Q))return Q;return}})),O.use(async(Q,Z)=>{let G=Q.req.query("directory")||Q.req.header("x-blade-directory")||c();try{G=decodeURIComponent(G)}catch{}return Q.set("directory",G),Z()});let $=s$();h0=$,x1=$.recoverQueuedTasks,D0=new G1({dispatch:(Q)=>$.dispatchTask(Q),store:m1}),O.route("/global",Q$()),O.route("/events",$$()),O.route("/sessions",$.app),O.route("/tasks",h4($)),O.route("/teams",c4()),O.route("/schedules",j4(m1,D0)),O.route("/configs",n1()),O.route("/permissions",e$()),O.route("/plugins",W4()),O.route("/hooks",X$()),O.route("/workspace-trust",$x()),O.route("/providers",w4()),O.route("/models",H$()),O.route("/projects",_4()),O.route("/suggestions",I4()),O.route("/terminal",r4()),O.route("/mcp",K$()),O.route("/skills",E4()),O.get("/health",(Q)=>{return Q.json({healthy:!0,version:Q0()})});let x=N3();if(x)FO.info(`[Server] Serving static files from ${x}`),O.get("/favicon.svg",()=>{let Q=dO(x,"favicon.svg");if(!h1(Q))return new Response(null,{status:404});return new Response(g0(Q),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),O.get("/assets/*",(Q)=>{let Z=dO(x,Q.req.path);if(!h1(Z))return Q.json({error:{code:"NOT_FOUND",message:`File not found: ${Q.req.path}`}},404);let G=X3(Z),z=n2(Z).toLowerCase(),j={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[z]||"application/octet-stream",L=Q3.has(z)&&G.byteLength>=Z3?G3(Q.req.header("Accept-Encoding")):void 0,b=L?V3(Z,G,L):G;return new Response(new Uint8Array(b),{headers:{"Content-Type":j,"Content-Length":String(b.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...L?{"Content-Encoding":L}:{}}})}),O.get("/",(Q)=>{let Z=dO(x,"index.html"),G=g0(Z,"utf-8");return Q.html(G,200,{"Cache-Control":"no-cache"})}),O.get("*",(Q)=>{let Z=Q.req.path;if(Z.includes("."))return Q.json({error:{code:"NOT_FOUND",message:`File not found: ${Z}`}},404);let G=dO(x,"index.html"),z=g0(G,"utf-8");return Q.html(z,200,{"Cache-Control":"no-cache"})});else FO.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(Q)=>{return Q.json({message:"Blade API Server",version:Q0(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),O.all("*",(Q)=>{return Q.json({error:{code:"NOT_FOUND",message:`Route not found: ${Q.req.path}`}},404)});return O}function W3(){let O=a2(),$=[];for(let x of Object.keys(O)){let Q=O[x];if(!Q)continue;for(let Z of Q){if(Z.internal||Z.family!=="IPv4")continue;if(Z.address.startsWith("172."))continue;$.push(Z.address)}}return $}function Jx(){return typeof globalThis.Bun<"u"}function Yx(O,$){let x=globalThis.Bun,Q=(G)=>{try{return x.serve({hostname:$.hostname,port:G,fetch:O.fetch,idleTimeout:0,websocket:y1})}catch(z){FO.error("Failed to start Bun server:",z);return}},Z=$.port===0?Q(4096)??Q(0):Q($.port);if(!Z)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Z.url,port:Z.port,hostname:Z.hostname,stop:async()=>{Z.stop(!0)}}}function F3(O,$){return new Promise((x,Q)=>{let Z=c2(async(L,b)=>{let w=new URL(L.url||"/",`http://${L.headers.host}`),F=new Headers;for(let[d,C]of Object.entries(L.headers))if(C)if(Array.isArray(C))for(let e of C)F.append(d,e);else F.set(d,C);let P;if(L.method!=="GET"&&L.method!=="HEAD")P=(await new Promise((C)=>{let e=[];L.on("data",(u)=>e.push(u)),L.on("end",()=>C(Buffer.concat(e)))})).toString();let ZO=new Request(w.toString(),{method:L.method,headers:F,body:P});try{let d=await O.fetch(ZO);if(b.statusCode=d.status,d.headers.forEach((C,e)=>{b.setHeader(e,C)}),d.body){let C=d.body.getReader(),e=async()=>{let{done:u,value:YO}=await C.read();if(u){b.end();return}return b.write(YO),e()};await e()}else{let C=await d.text();b.end(C)}}catch(d){FO.error("[Server] Node request error:",d),b.statusCode=500,b.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),G=new x3({noServer:!0}),z=c();s4(G,()=>z),Z.on("upgrade",(L,b,w)=>{if(new URL(L.url||"/",`http://${L.headers.host}`).pathname==="/terminal/ws")G.handleUpgrade(L,b,w,(P)=>{G.emit("connection",P,L)});else b.destroy()});let U=(L)=>{return new Promise((b,w)=>{Z.once("error",(F)=>{if(F.code==="EADDRINUSE")w(F);else w(F)}),Z.listen(L,$.hostname,()=>{let F=Z.address();if(F&&typeof F==="object")b(F.port);else b(L)})})};(async()=>{let L;if($.port===0)try{L=await U(4096)}catch{L=await U(0)}else L=await U($.port);let b=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${L}`);x({url:b,port:L,hostname:$.hostname,stop:async()=>{return new Promise((w)=>{G.close(()=>{Z.close(()=>w())})})}})})().catch(Q)})}var Xx;((n7)=>{let O,$,x,Q=(L,b)=>{if(O!==L)return Promise.resolve();if(x)return x;let w=b?.shutdown("server-shutdown");return D0?.stop(),z3(),x=(async()=>{let F,P=async(ZO)=>{if(!ZO)return;try{await ZO()}catch(d){F??=d}};if(await P(()=>L.stop()),await P(w?()=>w:void 0),Gx(),O===L)O=void 0,$=void 0,h0=void 0,x1=void 0,D0=void 0;if(FO.info("[Server] Blade server stopped"),F!==void 0)throw F})(),x};function Z(){if(!$)$=K3();return $}n7.getApp=Z;function G(L){g1=L.cors??[];let b=Z();if(Jx())O=Yx(b,L),x=void 0,FO.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let w=O,F=h0;return x1?.().catch((P)=>{FO.warn("[Server] Failed to recover queued tasks:",P)}),D0?.start(),Zx(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>Q(w,F)}}n7.listen=G;async function z(L){g1=L.cors??[];let b=Z();if(Jx())O=Yx(b,L),FO.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await F3(b,L),FO.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);x=void 0;let w=O,F=h0;try{await x1?.()}catch(P){FO.warn("[Server] Failed to recover queued tasks:",P)}return D0?.start(),Zx(),{url:w.url,port:w.port,hostname:w.hostname,stop:()=>Q(w,F)}}n7.listenAsync=z;function U(){return O!==void 0}n7.isRunning=U;function j(){return h0?.getCoordinationStats()}n7.getSessionCoordinationStatsForTests=j})(Xx||={});export{U3 as f,_3 as g,W3 as h,Xx as i};
@@ -1 +0,0 @@
1
- import{f as a,g as i,h as l,i as m}from"./chunk-9erhm3gg.js";import"./chunk-gd2sw9zm.js";import"./chunk-01zar8q6.js";import"./chunk-9vmxd900.js";import"./chunk-gzjt969t.js";import"./chunk-00xsfm2j.js";import"./chunk-zpbbcdme.js";import"./chunk-b8p2mwq9.js";import"./chunk-tpxs85cg.js";import"./chunk-6n63ev2e.js";import"./chunk-r8wbvxn7.js";import"./chunk-gk79etn6.js";import"./chunk-d2pwwdab.js";import"./chunk-r77pcb0f.js";import{Bd as n}from"./chunk-x89n28mq.js";import"./chunk-skg520wq.js";import{Xd as s}from"./chunk-bthb5c55.js";import"./chunk-v508x7cg.js";import"./chunk-g9xjcfrf.js";import"./chunk-b2p9qm6j.js";import"./chunk-0q5bz3nm.js";import"./chunk-44dzrn0p.js";import"./chunk-deeh2eq1.js";import"./chunk-t5d4p0gc.js";import"./chunk-sr4zv59p.js";import"./chunk-ww51801m.js";import"./chunk-7rfhmbqw.js";import"./chunk-z21es9vg.js";import"./chunk-272swnyr.js";import"./chunk-zpryec89.js";import"./chunk-7m5q8vxf.js";import"./chunk-sk8h4m9m.js";import"./chunk-hg8d4vhj.js";import"./chunk-sb84vdcf.js";import"./chunk-hjr9r44k.js";import"./chunk-ffa6hhee.js";import"./chunk-t1633e8m.js";import"./chunk-m5f934fh.js";import"./chunk-p3jvzk1f.js";import"./chunk-rwvaapta.js";import"./chunk-83caxxbt.js";import"./chunk-shr5cg46.js";import"./chunk-6jsmac0q.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,2 +0,0 @@
1
- import{zh as o}from"./chunk-t1633e8m.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
2
- export{e as j,i as k};