blade-code 0.10.42 → 0.10.44

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 (105) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-dx7xefys.js → chunk-0qsssahq.js} +1 -1
  3. package/dist/{chunk-xkg84094.js → chunk-1vydfzvy.js} +2 -2
  4. package/dist/{chunk-ecw74d2s.js → chunk-26wse17p.js} +2 -2
  5. package/dist/{chunk-3xx2ebr7.js → chunk-2eddqgnh.js} +1 -1
  6. package/dist/{chunk-hypq4t4z.js → chunk-2yvte5a7.js} +1 -1
  7. package/dist/chunk-3nfse1ps.js +1 -0
  8. package/dist/chunk-3y784b9c.js +1 -0
  9. package/dist/{chunk-7gjb405q.js → chunk-50a5xx45.js} +1 -1
  10. package/dist/{chunk-1yjzj2d0.js → chunk-56qew7w0.js} +2 -2
  11. package/dist/{chunk-jz2gkqdt.js → chunk-583kv07t.js} +7 -7
  12. package/dist/chunk-619q1w65.js +1 -0
  13. package/dist/{chunk-qb49rm5q.js → chunk-63p5mj97.js} +1 -1
  14. package/dist/chunk-6cx4t8r6.js +1 -0
  15. package/dist/{chunk-mt7fn8cv.js → chunk-706zda55.js} +3 -3
  16. package/dist/{chunk-d2fce0vk.js → chunk-74hcqcn7.js} +2 -2
  17. package/dist/{chunk-kfv4mdcm.js → chunk-7fqsgdee.js} +2 -2
  18. package/dist/{chunk-5zr3w30g.js → chunk-7sna3js9.js} +1 -1
  19. package/dist/chunk-7z5t63ke.js +10 -0
  20. package/dist/chunk-86tba7p4.js +1 -0
  21. package/dist/{chunk-020hgyg7.js → chunk-8vtyatd6.js} +1 -1
  22. package/dist/chunk-99nka030.js +1 -0
  23. package/dist/{chunk-f90ybvrs.js → chunk-9rrced3b.js} +1 -1
  24. package/dist/chunk-a68fws4p.js +1 -0
  25. package/dist/chunk-agbyfdvw.js +1 -0
  26. package/dist/{chunk-sw3p1ygn.js → chunk-aw7w91f0.js} +68 -68
  27. package/dist/{chunk-0qf7h4n2.js → chunk-bvf9syb2.js} +2 -2
  28. package/dist/{chunk-dr4et3gj.js → chunk-c9s4n31b.js} +1 -1
  29. package/dist/{chunk-q6n6rqzs.js → chunk-cf2541w5.js} +2 -2
  30. package/dist/{chunk-4rmdfme3.js → chunk-ckqj0pxz.js} +1 -1
  31. package/dist/{chunk-f542fh7g.js → chunk-cxzx7j0p.js} +1 -1
  32. package/dist/chunk-d18mw6d1.js +2 -0
  33. package/dist/{chunk-1e9866ye.js → chunk-egczvfsv.js} +2 -2
  34. package/dist/{chunk-anwm8rp3.js → chunk-f4sp074f.js} +1 -1
  35. package/dist/chunk-fer18bbe.js +1 -0
  36. package/dist/{chunk-t2mc97k7.js → chunk-fhnkyqfb.js} +2 -2
  37. package/dist/chunk-fk0q25dp.js +8 -0
  38. package/dist/{chunk-3v2sgvzt.js → chunk-fk4wbmv6.js} +2 -2
  39. package/dist/{chunk-wm944thh.js → chunk-g96t2yrz.js} +22 -22
  40. package/dist/{chunk-pm9kt54d.js → chunk-hcm55r3d.js} +1 -1
  41. package/dist/{chunk-m8s208g3.js → chunk-hfrcwkc8.js} +1 -1
  42. package/dist/{chunk-yqxyy3w2.js → chunk-j0k3mbkd.js} +2 -2
  43. package/dist/chunk-j7edwwg1.js +2 -0
  44. package/dist/{chunk-jv9zg1fw.js → chunk-kfpzrmq7.js} +1 -1
  45. package/dist/{chunk-8csfb83y.js → chunk-m1b6v1zn.js} +2 -2
  46. package/dist/{chunk-18wnstzp.js → chunk-m8ss9rmx.js} +1 -1
  47. package/dist/{chunk-te95z52n.js → chunk-mrsc4a55.js} +1 -1
  48. package/dist/{chunk-fye8eghq.js → chunk-mzq3ps9j.js} +2 -2
  49. package/dist/chunk-n4ywszmn.js +6 -0
  50. package/dist/chunk-p4egmgt6.js +2 -0
  51. package/dist/chunk-pk9peyzp.js +1 -0
  52. package/dist/{chunk-mpymjr7j.js → chunk-q78s028m.js} +1 -1
  53. package/dist/{chunk-m3dvta6k.js → chunk-qb0sqh29.js} +2 -2
  54. package/dist/{chunk-0jsy9eav.js → chunk-qp2z1r7y.js} +1 -1
  55. package/dist/chunk-qzd9d0p8.js +22 -0
  56. package/dist/{chunk-mp637mb6.js → chunk-r085zhqr.js} +2 -2
  57. package/dist/{chunk-1whfdz08.js → chunk-s4denzh4.js} +1 -1
  58. package/dist/{chunk-6d0hphtd.js → chunk-sqd5ge5s.js} +1 -1
  59. package/dist/{chunk-brwdd5kp.js → chunk-svj24r6g.js} +2 -2
  60. package/dist/{chunk-jf6mkx0j.js → chunk-synjj8b3.js} +1 -1
  61. package/dist/chunk-t33njg4e.js +1 -0
  62. package/dist/{chunk-vc32qrmq.js → chunk-tpa75y39.js} +1 -1
  63. package/dist/chunk-tzp486wc.js +1 -0
  64. package/dist/{chunk-y75y911b.js → chunk-v9tzhe90.js} +2 -2
  65. package/dist/{chunk-ex21hxqf.js → chunk-vx5tjahq.js} +1 -1
  66. package/dist/chunk-wr2rkg9t.js +1 -0
  67. package/dist/{chunk-7pmpm5yq.js → chunk-wwvb6znp.js} +1 -1
  68. package/dist/chunk-wx5nj2s2.js +44 -0
  69. package/dist/{chunk-8b2bpfnt.js → chunk-x3cyg9pe.js} +3 -3
  70. package/dist/chunk-y6tkxqjx.js +2 -0
  71. package/dist/{chunk-4k37vmxh.js → chunk-yk9pxkc1.js} +1 -1
  72. package/dist/chunk-z1aqe7ms.js +1 -0
  73. package/dist/{chunk-z60w7p8a.js → chunk-z9absgab.js} +1 -1
  74. package/dist/web/assets/{ChatView-DBgMoUrW.js → ChatView-CyxiCTbL.js} +3 -3
  75. package/dist/web/assets/{CodeBlockHighlighter-DLFQUVD6.js → CodeBlockHighlighter-Bb3gIeQv.js} +1 -1
  76. package/dist/web/assets/{FilePreview--1qHdJP_.js → FilePreview-BXg9VaTv.js} +1 -1
  77. package/dist/web/assets/{MarkdownRenderer-DcVHyjtl.js → MarkdownRenderer-vxpqGt4L.js} +3 -3
  78. package/dist/web/assets/{SettingsModal-BM6SPUXW.js → SettingsModal-4L1nPkh0.js} +1 -1
  79. package/dist/web/assets/{TaskSwitcher-B5VYY_QG.js → TaskSwitcher-DKSqTLK1.js} +1 -1
  80. package/dist/web/assets/{TerminalPanel-XWA1jGs8.js → TerminalPanel-Bv9PDclr.js} +1 -1
  81. package/dist/web/assets/{index-B8y5_J0i.js → index-Bz4W1-8a.js} +3 -3
  82. package/dist/web/index.html +1 -1
  83. package/package.json +1 -1
  84. package/dist/chunk-5hbm5e24.js +0 -44
  85. package/dist/chunk-74sxsd1h.js +0 -1
  86. package/dist/chunk-78jy2kby.js +0 -1
  87. package/dist/chunk-7qd6xqjs.js +0 -1
  88. package/dist/chunk-8wg7g98v.js +0 -10
  89. package/dist/chunk-c53hc8ze.js +0 -1
  90. package/dist/chunk-dgs04r04.js +0 -2
  91. package/dist/chunk-h9fkttf1.js +0 -2
  92. package/dist/chunk-hkmgrdxc.js +0 -1
  93. package/dist/chunk-katrmbxc.js +0 -1
  94. package/dist/chunk-m4ya7qqd.js +0 -1
  95. package/dist/chunk-n6c6k87j.js +0 -1
  96. package/dist/chunk-ppxn94za.js +0 -1
  97. package/dist/chunk-rf7hdke7.js +0 -1
  98. package/dist/chunk-rjjjgcw4.js +0 -1
  99. package/dist/chunk-vsaqjbm2.js +0 -6
  100. package/dist/chunk-wcxsm922.js +0 -2
  101. package/dist/chunk-wn23bvs0.js +0 -1
  102. package/dist/chunk-wtczk025.js +0 -22
  103. package/dist/chunk-yatvtpft.js +0 -1
  104. package/dist/chunk-za6zyd82.js +0 -8
  105. package/dist/chunk-zhrc510s.js +0 -1
@@ -1,8 +0,0 @@
1
- import{j as t4,k as r4}from"./chunk-020hgyg7.js";import{l as h$}from"./chunk-anwm8rp3.js";import{s as k0}from"./chunk-brwdd5kp.js";import{t as w4,u as S1,v as f1,w as y1,x as n0,y as m1}from"./chunk-wcxsm922.js";import{$ as u4,A as KO,D as D4,E as Y$,F as V1,G as S$,H as $1,I as T0,J as O1,K as r0,L as U$,O as A$,P as M$,R as _4,S as B4,T as L4,U as f4,V as y4,W as m4,X as h4,Y as g4,Z as v4,_ as p4,aa as d4,ba as n4,ea as EO,ja as VO}from"./chunk-sw3p1ygn.js";import{ma as o1,sa as N0}from"./chunk-jz2gkqdt.js";import{Aa as M4,Ba as UO,Ca as N1,Da as FO,Ea as d0,Fa as e4,Ga as $O,Ha as OO,Ia as E4,Ja as T4,Ka as b4,La as k1,Ma as D1,ua as l$,xa as GO,ya as WO,za as A4}from"./chunk-h9fkttf1.js";import{Ta as I0,Ua as h,Wa as j,Xa as H4,jb as e$,sb as p0}from"./chunk-8b2bpfnt.js";import{Bb as V4}from"./chunk-te95z52n.js";import{Ub as N4,Wb as f$,ac as L$,bc as Y1,cc as w$,ec as G4,kc as W4,lc as U4,nc as O$,qc as t$,vc as F4,wc as r$,xc as s$,yc as C}from"./chunk-wm944thh.js";import{Gd as _0,vd as $0,zd as s1}from"./chunk-mp637mb6.js";import{Hd as n$}from"./chunk-7pmpm5yq.js";import{Vd as z4}from"./chunk-0jsy9eav.js";import{Xd as P$}from"./chunk-d2fce0vk.js";import{ee as YO,fe as QO,ie as S4,me as G$,ne as W$,re as W0}from"./chunk-8csfb83y.js";import{Be as e1,Ce as K4}from"./chunk-hypq4t4z.js";import{Ge as l1,He as s0}from"./chunk-mt7fn8cv.js";import{Af as c1,Ff as N$,Ze as a1}from"./chunk-5hbm5e24.js";import{If as m,Kf as F,Nf as V0}from"./chunk-18wnstzp.js";import{Pf as y$}from"./chunk-dgs04r04.js";import{Uf as g}from"./chunk-jv9zg1fw.js";import{tg as d}from"./chunk-t2mc97k7.js";import{zg as g0}from"./chunk-ecw74d2s.js";import{Bg as t1,Cg as x4,Eg as r1,Fg as X4}from"./chunk-pm9kt54d.js";import{Hg as t0}from"./chunk-yqxyy3w2.js";import{Mg as F1}from"./chunk-0qf7h4n2.js";import{Rg as C$,Vg as g1}from"./chunk-m3dvta6k.js";import{Yg as G1}from"./chunk-m8s208g3.js";var k5={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 I5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as H1,readFileSync as b$}from"node:fs";import{createServer as z5}from"node:http";import{networkInterfaces as K5}from"node:os";import{dirname as V5,extname as N5,join as y0}from"node:path";import{fileURLToPath as G5}from"node:url";import{brotliCompressSync as W5,gzipSync as U5,constants as F5}from"node:zlib";import{Hono as D5}from"hono";import{cors as H5}from"hono/cors";import{WebSocketServer as _5}from"ws";var a0=d("Service"),SO=30000,fO=new Set(["completed","failed","cancelled","interrupted"]);class c${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor($){this.dispatch=$.dispatch,this.store=$.store??k1.getInstance(),this.tickMs=$.tickMs??SO}start(){if(this.timer)return;a0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=j.subscribe(($)=>{if($.type!=="task.status")return;let O=$.properties.taskStatus;if(typeof O!=="string"||!fO.has(O))return;this.recordTerminalStatus($.sessionId,O,typeof $.properties.taskStatusReason==="string"?$.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,a0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick($=new Date){if(this.ticking)return;this.ticking=!0;try{let O=await this.store.list();for(let J of O)await this.evaluate(J,$)}catch(O){a0.warn("[TaskScheduler] Tick failed:",O)}finally{this.ticking=!1}}async evaluate($,O){if(!$.enabled)return;if(this.inFlight.has($.id))return;if($.expiresAt&&new Date($.expiresAt).getTime()<=O.getTime()){await this.store.update($.id,{enabled:!1,nextRunAt:null}),a0.info(`[TaskScheduler] Schedule ${$.id} expired; disabled`);return}if(!$.nextRunAt)return;if(!(new Date($.nextRunAt).getTime()<=O.getTime()))return;await this.fire($,O)}async fire($,O=new Date,J={}){if(this.inFlight.has($.id))throw Error(`Schedule ${$.id} is already dispatching`);this.inFlight.add($.id);let Z=O.toISOString();try{let Y=await this.dispatch({prompt:$.prompt,title:$.title??yO($),sourceProjectPath:$.projectPath,isolation:$.dispatch.isolation??"worktree",permissionMode:$.dispatch.permissionMode??"default",modelId:$.dispatch.modelId,reasoningEffort:$.dispatch.reasoningEffort,serviceTier:$.dispatch.serviceTier,responseVerbosity:$.dispatch.responseVerbosity,communicationStyle:$.dispatch.communicationStyle}),z=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:l$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastRunSessionId:Y.session.sessionId,lastStatus:Y.status,lastError:void 0,runCount:$.runCount+1,nextRunAt:z?z.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled}),j.publish({sessionId:Y.session.sessionId,projectPath:$.projectPath},"schedule.fired",{scheduleId:$.id,firedAt:Z,sessionId:Y.session.sessionId,runId:Y.runId,status:Y.status}),a0.info(`[TaskScheduler] Fired schedule ${$.id} -> session ${Y.session.sessionId} (${Y.status})`)}catch(Y){let z=Y instanceof Error?Y.message:String(Y);a0.warn(`[TaskScheduler] Schedule ${$.id} dispatch failed:`,Y);let X=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:l$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastStatus:"error",lastError:z,nextRunAt:X?X.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled})}finally{this.inFlight.delete($.id)}}async recordTerminalStatus($,O,J){let Y=(await this.store.list()).find((z)=>z.lastRunSessionId===$);if(!Y)return;await this.store.update(Y.id,{lastStatus:O,...J?{lastError:J}:{lastError:void 0}})}}function yO($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class e extends Error{code;statusCode;details;constructor($,O,J=500,Z){super(O);this.code=$;this.statusCode=J;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class f extends e{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class _ extends e{constructor($){super("BAD_REQUEST",$,400)}}class k extends e{constructor($){super("CONFLICT",$,409)}}class o0 extends e{constructor($,O){super("TOO_MANY_REQUESTS",$,429,O)}}class h0 extends e{constructor($="Server is shutting down"){super("SERVICE_UNAVAILABLE",$,503)}}class H0 extends e{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class a extends e{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var v5=F.Object({error:F.Object({code:F.String(),message:F.String(),details:F.Optional(F.Record(F.String(),F.Unknown()))})});import{Hono as mO}from"hono";var i$=d("Service"),hO=F.Object({updates:F.Record(F.String(),F.Any()),options:F.Optional(F.Object({scope:F.Optional(V0(["local","project","global"])),immediate:F.Optional(F.Boolean())}))});function gO($){return{currentModelId:$.currentModelId,permissionMode:$.permissionMode,language:$.language,codeTheme:$.codeTheme,uiTheme:$.uiTheme,autoSaveSessions:$.autoSaveSessions,notifyBuild:$.notifyBuild,notifyErrors:$.notifyErrors,notifySounds:$.notifySounds,privacyTelemetry:$.privacyTelemetry,privacyCrash:$.privacyCrash,communicationStyle:$.communicationStyle,maxConcurrentTasks:$.maxConcurrentTasks,maxQueuedTasks:$.maxQueuedTasks,maxQueuedTaskBytes:$.maxQueuedTaskBytes}}var I1=()=>{let $=new mO;return $.get("/",async(O)=>{try{let J=$0();return O.json(J?gO(J):{})}catch(J){return i$.error("[ConfigRoutes] Failed to get config:",J),O.json({})}}),$.put("/",async(O)=>{try{let J=await O.req.json(),Z=m(hO,J);if(!Z.success)throw new _("Invalid config update format");let{updates:Y,options:z}=Z.data;return await _0().updateConfig(Y,z),O.json({success:!0,updates:Y})}catch(J){throw i$.error("[ConfigRoutes] Failed to update config:",J),J}}),$.get("/permissions",async(O)=>{try{let J=$0();return O.json(J?.permissions||{})}catch(J){return i$.error("[ConfigRoutes] Failed to get permissions:",J),O.json({})}}),$};import{Hono as vO}from"hono";import{streamSSE as pO}from"hono/streaming";function P1($){let O="";if($.id!==void 0)O+=`id: ${$.id}
2
- `;if($.event!==void 0)O+=`event: ${$.event}
3
- `;for(let J of $.data.split(/\r\n|\r|\n/))O+=`data: ${J}
4
- `;if($.retry!==void 0)O+=`retry: ${$.retry}
5
- `;return O+=`
6
- `,Buffer.byteLength(O)}class K${serial;buffered=[];bufferedBytes=0;nextOrder=0;phase="buffering";highestDeliveredSequence=0;highestReplaySequence=0;failure;maxPendingItems;maxPendingBytes;constructor($){this.maxPendingItems=$.maxPendingItems??S1,this.maxPendingBytes=$.maxPendingBytes??f1,this.serial=new m1({maxPendingItems:this.maxPendingItems,maxPendingBytes:this.maxPendingBytes,writeTimeoutMs:$.writeTimeoutMs??y1,sizeOf:P1,write:$.write,onFailure:(O)=>{this.failure=O,this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,$.onFailure?.(O)}})}async writeInitial($){await this.offerDirect($)}observe($,O){if(this.phase==="closed")return;if(this.phase==="buffering"){this.buffer($,O);return}this.offerLive($,O)}async writeReplay($,O){if(!Number.isSafeInteger(O)||O<=0)throw this.fail(new n0("invalid_size","SSE committed sequence must be a positive safe integer")),this.currentFailure();if(O<=this.highestReplaySequence)return;await this.offerDirect($),this.highestReplaySequence=O,this.highestDeliveredSequence=O}finishInitialization($){if(this.phase!=="buffering")return;let O=this.buffered.splice(0);this.bufferedBytes=0,this.phase="live";let J=$.replayed?O.filter((Y)=>Y.sequence!==void 0&&Y.sequence>this.highestReplaySequence).sort((Y,z)=>Y.sequence-z.sequence||Y.order-z.order):O.sort((Y,z)=>Y.order-z.order),Z;for(let Y of J){if($.replayed&&Y.sequence!==void 0&&Y.sequence===Z)continue;if(this.offerLive(Y.message,Y.sequence),this.serial.stats().closed)return;Z=Y.sequence}}offerHeartbeat($){if(this.phase!=="live"||this.buffered.length>0||this.serial.stats().pendingItems>0)return!1;return this.offerLive($),!this.serial.stats().closed}async flush(){await this.serial.flush()}close($){if(this.phase==="closed")return;this.phase="closed",this.buffered.length=0,this.bufferedBytes=0,this.serial.close($)}stats(){let $=this.serial.stats();return{closed:this.phase==="closed",pendingItems:$.pendingItems+this.buffered.length,pendingBytes:$.pendingBytes+this.bufferedBytes,bufferedItems:this.buffered.length,bufferedBytes:this.bufferedBytes}}buffer($,O){let J=P1($),Z=this.serial.stats();if(J>this.maxPendingBytes){this.fail(new n0("oversized",`SSE frame requires ${J} bytes; limit is ${this.maxPendingBytes}`,{pendingItems:Z.pendingItems+this.buffered.length,pendingBytes:Z.pendingBytes+this.bufferedBytes}));return}if(Z.pendingItems+this.buffered.length>=this.maxPendingItems||Z.pendingBytes+this.bufferedBytes+J>this.maxPendingBytes){this.fail(new n0("overflow","SSE initialization buffer limit exceeded",{pendingItems:Z.pendingItems+this.buffered.length,pendingBytes:Z.pendingBytes+this.bufferedBytes}));return}this.nextOrder+=1,this.buffered.push({message:$,bytes:J,sequence:O,order:this.nextOrder}),this.bufferedBytes+=J}offerLive($,O){if(O!==void 0){if(O<=this.highestReplaySequence)return;if(O<=this.highestDeliveredSequence){this.fail(new n0("write_failed","SSE committed sequence regressed"));return}this.highestDeliveredSequence=O}if(!this.serial.offer($).accepted)this.phase="closed"}async offerDirect($){if(this.phase==="closed")throw this.currentFailure();let O=this.serial.offer($);if(!O.accepted)throw this.phase="closed",O.error;await O.completion}fail($){this.serial.close($)}currentFailure(){return this.failure??new n0("closed","SSE egress is closed")}}var uO=15000,dO=d("Service"),lO=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),cO=new Set(["queued","running","completed","failed","cancelled","interrupted"]);function iO($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$,J=["changedFiles","additions","deletions","commits"];if(J.some((Z)=>typeof O[Z]!=="number"||!Number.isInteger(O[Z])||O[Z]<0))return;return Object.fromEntries(J.map((Z)=>[Z,O[Z]]))}function V$($,O){return typeof $==="number"&&Number.isInteger($)&&$>=O?$:void 0}function aO($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$;if(!["applied","discarded","conflicted"].includes(String(O.status))||typeof O.updatedAt!=="string")return;return{status:O.status,updatedAt:O.updatedAt,...typeof O.sourceCommit==="string"?{sourceCommit:O.sourceCommit}:{},...V$(O.changedFiles,0)!==void 0?{changedFiles:O.changedFiles}:{},...typeof O.message==="string"?{message:O.message}:{}}}var h1=()=>{let $=new vO;return $.get("/",(O)=>pO(O,async(J)=>{let Z,Y,z=!1,X,U,q=new Promise((W)=>{U=W}),B=()=>{if(Y!==void 0)clearInterval(Y),Y=void 0;Z?.(),Z=void 0},M=(W)=>{if(z)return;z=!0,B(),X?.close(W),U()};J.onAbort(M),X=new K$({write:async(W)=>{await J.writeSSE(W)},onFailure:(W)=>{dO.warn(`[EventRoutes] SSE egress closed: kind=${W.kind} pendingItems=${W.pendingItems??0} pendingBytes=${W.pendingBytes??0}`),M(W)}});let T=(W,u)=>{X?.observe({data:JSON.stringify({type:W,properties:u})})};Z=j.subscribe((W)=>{if(!lO.has(W.type))return;if(W.type==="permission.asked"||W.type==="question.required"||W.type==="elicitation.required"){let v=W.properties.requestId;if(typeof v!=="string"||!v)return;T("interaction.pending",{sessionId:W.sessionId,projectPath:W.projectPath,interactionType:W.type==="question.required"?"question":W.type==="elicitation.required"?"elicitation":"permission",requestId:v});return}if(W.type==="interaction.resolved"){let v=W.properties.requestId;if(typeof v!=="string"||!v)return;T(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,requestId:v});return}if(W.type==="session.created"||W.type==="session.deleted"){T(W.type,{sessionId:W.sessionId,projectPath:W.projectPath});return}if(W.type==="session.updated"){let v=W.properties.title;if(typeof v!=="string"||!v.trim())return;T(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,title:v});return}if(W.type==="task.delivery"){let v=aO(W.properties.taskDelivery);if(!v)return;T(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,taskDelivery:v,...W.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{}});return}if(W.type==="schedule.fired"){let v=W.properties.scheduleId,m0=W.properties.firedAt;if(typeof v!=="string"||typeof m0!=="string")return;T(W.type,{scheduleId:v,firedAt:m0,sessionId:W.sessionId,projectPath:W.projectPath,...typeof W.properties.runId==="string"?{runId:W.properties.runId}:{},...typeof W.properties.status==="string"?{status:W.properties.status}:{}});return}let u=W.properties.taskStatus;if(typeof u!=="string"||!cO.has(u))return;let Y0=iO(W.properties.taskDiffStat),E=V$(W.properties.taskQueuePosition,1),t=V$(W.properties.taskQueueDepth,0),I=V$(W.properties.taskConcurrencyLimit,1),O0=V$(W.properties.taskInFlight,0);T(W.type,{sessionId:W.sessionId,projectPath:W.projectPath,taskStatus:u,...typeof W.properties.taskStatusReason==="string"?{taskStatusReason:W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{taskFailure:W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{taskStartedAt:W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{taskCompletedAt:W.properties.taskCompletedAt}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{},...Y0?{taskDiffStat:Y0}:{},...E!==void 0?{taskQueuePosition:E}:{},...t!==void 0?{taskQueueDepth:t}:{},...I!==void 0?{taskConcurrencyLimit:I}:{},...O0!==void 0?{taskInFlight:O0}:{}})});try{if(J.aborted||z)return;if(await X.writeInitial({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),J.aborted||z)return;if(X.finishInitialization({replayed:!1}),J.aborted||z)return;Y=setInterval(()=>{if(J.aborted||z)return;X?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},uO),await q}finally{M()}})),$};import{Hono as oO}from"hono";var v1=()=>{let $=new oO;return $.get("/health",(O)=>{return O.json({healthy:!0,version:t0()})}),$.get("/info",(O)=>{let J=g(),Z=$0();if(Z)r0.configure(Z.maxConcurrentTasks,Z.maxQueuedTasks,Z.maxQueuedTaskBytes);let Y=r0.getStats();return O.json({version:t0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:J,gitBranch:g1(J),taskAdmission:{inFlight:Y.inFlight,queued:Y.queued,maxConcurrent:Y.maxConcurrent,maxQueued:Y.maxQueued}})}),$};import p1 from"node:path";import{Hono as nO}from"hono";var tO=F.Object({projectPath:F.String({minLength:1}),action:V0(["trust","revoke"]),expectedDigest:F.Optional(F.String())}),rO=F.Object({projectPath:F.String({minLength:1}),sessionId:F.String({minLength:1}),enabled:F.Boolean()});function a$($){if(!$||!p1.isAbsolute($))throw new _("projectPath must be absolute");return p1.resolve($)}function u1($){if(!$)throw new _("sessionId is required");try{C$($)}catch(O){throw new _(O instanceof Error?O.message:"sessionId is invalid")}return $}async function j$($){let O=a$($),J=$0()?.hooks??c1.hooks,Z=await N$.getInstance().loadWorkspaceHooks(O,J,{includeBaseForCurrentWorkspace:!1});await W0(O),W$(O);let Y=s0.getInstance();return Y.loadConfig(Z,O),await G$(O),Y.getConfig(O)}function d1($,O){let J=s0.getInstance(),Z=J.getConfig(O).enabled,Y=J.isSessionPaused($,O);return{sessionId:$,projectPath:O,enabled:J.isSessionEnabled($,O),paused:Y,configEnabled:Z}}var i1=()=>{let $=new nO;return $.get("/trust",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return await j$(J),O.json(await s0.getInstance().getTrustStatus(J))}),$.post("/trust",async(O)=>{let J=m(tO,await O.req.json());if(!J.success)throw new _("Invalid hook trust request");let{projectPath:Z,action:Y,expectedDigest:z}=J.data;await j$(Z);let X=s0.getInstance(),U;try{U=Y==="trust"?await X.trustProject(Z,z):await X.revokeProjectTrust(Z)}catch(q){if(q instanceof l1)throw new k(q.message);throw q}return O.json(U)}),$.get("/session",async(O)=>{let J=a$(O.req.query("projectPath")),Z=u1(O.req.query("sessionId"));return await j$(J),O.json(d1(Z,J))}),$.post("/session",async(O)=>{let J=m(rO,await O.req.json());if(!J.success)throw new _("Invalid hook session request");let Z=a$(J.data.projectPath),Y=u1(J.data.sessionId);await j$(Z);let z=s0.getInstance();if(J.data.enabled)z.enableSession(Y,Z);else z.disableSession(Y,Z);return O.json(d1(Y,Z))}),$};import{Hono as sO}from"hono";var E0=d("Service");function eO($){try{return o1($)}catch{return[]}}function $2($){if(!k$($)||!k$($.reference)||!k$($.argument))throw Error("Invalid MCP completion request");let O=$.reference.type,J=O==="prompt"&&typeof $.reference.name==="string"?{type:"prompt",name:$.reference.name}:O==="resource"&&typeof $.reference.uri==="string"?{type:"resource",uri:$.reference.uri}:void 0;if(!J||typeof $.argument.name!=="string"||typeof $.argument.value!=="string")throw Error("Invalid MCP completion request");let Z;if($.context!==void 0){if(!k$($.context))throw Error("Invalid MCP completion context");Z=Object.create(null);for(let[Y,z]of Object.entries($.context)){if(typeof z!=="string")throw Error("Invalid MCP completion context");Z[Y]=z}}return{reference:J,argument:{name:$.argument.name,value:$.argument.value},...Z?{context:Z}:{}}}function k$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}async function C0($,O){let J=$0()?.mcpServers??{};for(let[Z,Y]of Object.entries(J)){if(O&&Z!==O)continue;if(!$.getServerStatus(Z))await $.registerServer(Z,Y,{connect:!1})}}var n1=()=>{let $=new sO;return $.get("/",async(O)=>{try{let J=N0.getInstance();await C0(J);let Z=J.getAllServers(),Y=await Promise.all(Array.from(Z.entries()).map(async([z,X])=>({id:z,name:z,status:X.status==="connected"?"connected":X.status==="reconnecting"?"reconnecting":X.status==="connecting"?"connecting":X.lastError?"error":"offline",endpoint:X.config.command?`${X.config.command} ${(X.config.args||[]).join(" ")}`.trim():X.config.url||"Unknown",description:`MCP server: ${z}`,tools:X.tools.map((U)=>U.name),completionSupported:X.client.completionSupported,tasks:X.client.tasks,resources:X.contentCatalog.resources,resourceTemplates:X.contentCatalog.resourceTemplates.map((U)=>({...U,variables:eO(U.uriTemplate)})),prompts:X.contentCatalog.prompts,connectedAt:X.connectedAt?.toISOString(),error:X.lastError?.message,recovery:X.recovery,logging:X.logging,instructions:X.instructions,oauthEnabled:X.client.oauthEnabled,oauthStatus:await X.client.getOAuthStatus()})));return O.json(Y)}catch(J){return E0.error("[McpRoutes] Failed to get MCP servers:",J),O.json({error:J instanceof Error?J.message:"Failed to get MCP servers"},500)}}),$.post("/:name/connect",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();return await C0(Z,J),await Z.connectServer(J),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to connect MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.post("/:name/disconnect",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();return await C0(Z,J),await Z.disconnectServer(J),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to disconnect MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.get("/:name/logs",async(O)=>{try{let J=O.req.param("name"),Z=Number(O.req.query("limit")??20),Y=Number(O.req.query("afterRevision")??0);if(!Number.isSafeInteger(Z)||Z<1||Z>100||!Number.isSafeInteger(Y)||Y<0)return O.json({error:"Invalid MCP log pagination"},400);let z=N0.getInstance();return await C0(z,J),O.json(z.getLogSnapshot(J,{limit:Z,afterRevision:Y}))}catch(J){return E0.error("[McpRoutes] Failed to get MCP logs:",J),O.json({error:J.message},500)}}),$.post("/:name/logging-level",async(O)=>{try{let J=O.req.param("name"),Z=await O.req.json();if(!a1(Z.level))return O.json({success:!1,error:"Invalid MCP logging level"},400);let Y=N0.getInstance();return await C0(Y,J),await Y.setServerLoggingLevel(J,Z.level),O.json({success:!0,level:Z.level})}catch(J){return E0.error("[McpRoutes] Failed to set MCP logging level:",J),O.json({success:!1,error:J.message},400)}}),$.post("/:name/complete",async(O)=>{try{let J=O.req.param("name"),Z=$2(await O.req.json()),Y=N0.getInstance();await C0(Y,J);let z=await Y.complete(J,Z);return O.json(z)}catch(J){return E0.error("[McpRoutes] Failed to complete MCP argument:",J),O.json({error:J.message},400)}}),$.post("/:name/oauth/login",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();await C0(Z,J);let Y=await Z.beginOAuthLogin(J);return O.json({success:!0,flowId:Y.flowId,authorizationUrl:Y.authorizationUrl},202)}catch(J){return E0.error("[McpRoutes] Failed to start MCP OAuth login:",J),O.json({success:!1,error:J.message},400)}}),$.post("/:name/oauth/logout",async(O)=>{try{let J=O.req.param("name"),Z=N0.getInstance();return await C0(Z,J),await Z.logoutOAuth(J),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to log out MCP OAuth:",J),O.json({success:!1,error:J.message},400)}}),$.delete("/:name",async(O)=>{try{let J=O.req.param("name");await N0.getInstance().unregisterServer(J);let Y=$0();if(Y?.mcpServers){let{[J]:z,...X}=Y.mcpServers;await _0().updateConfig({mcpServers:X})}return O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to delete MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.post("/",async(O)=>{try{let J=await O.req.json(),{name:Z,config:Y}=J;if(!Z||!Y)return O.json({success:!1,error:"Missing name or config"},400);await N0.getInstance().registerServer(Z,Y);let X=$0();return await _0().updateConfig({mcpServers:{...X?.mcpServers,[Z]:Y}}),O.json({success:!0})}catch(J){return E0.error("[McpRoutes] Failed to add MCP server:",J),O.json({success:!1,error:J.message},500)}}),$};import{getSupportedThinkingLevels as O2}from"@earendil-works/pi-ai";import{Hono as J2}from"hono";var I$=d("Service");function Z2($,O,J=e1.list()){return{id:$.id,displayName:$.displayName,provider:$.provider,model:$.model,overrides:$.overrides,fallbackModels:$.fallbackModels,contextWindow:O.contextWindow,maxTokens:O.maxTokens,reasoning:O.reasoning,supportedReasoningEfforts:O2(O),supportedServiceTiers:r1(O),supportedResponseVerbosities:t1(O),communicationStyles:J,input:O.input}}function Y2($){$4($.overrides);let O={displayName:$.displayName||void 0,overrides:$.overrides||void 0};if($.model)O.model=$.model;return O}function $4($){let O=$?.streamIdleTimeout;if(O!==void 0&&(!Number.isFinite(O)||O<1000))throw new _("streamIdleTimeout must be at least 1000ms")}var O4=()=>{let $=new J2;return $.get("/",async(O)=>{try{let J=$0();if(!J)throw Error("Config not initialized");let Z=O.get("directory")||g(),[Y,z]=await Promise.all([P$(Z,J),W0(Z)]),X=Y.config.models,U=X.find((T)=>T.id===Y.config.currentModelId)??X[0],q=Y.catalog,B=z.communicationStyles.list(),M=(T)=>Z2(T,q.resolveConfig(T),B);return O.json({configured:X.map(M),current:U?M(U):null})}catch(J){I$.error("[ModelsRoutes] Failed to get models:",J);let Z=new a("Failed to get models");return O.json(Z.toObject(),500)}}),$.post("/",async(O)=>{let J=g0(),Z,Y;try{let z=await O.req.json(),{provider:X,displayName:U,model:q,overrides:B,apiKey:M,modelProvider:T}=z;if(!X||!q)throw new _("provider and model are required");$4(B);let W;if(T){if(T.id!==X)throw new _("modelProvider.id must match the model provider");if($0()?.modelProviders[X])throw new _(`model provider already exists: ${X}`);W={name:T.name,baseUrl:T.baseUrl,wireApi:T.wireApi,...T.apiKeyEnv?{apiKeyEnv:T.apiKeyEnv}:{}};try{J.registerModelProvider(X,W,[q]),Y=X}catch(E){throw new _(E instanceof Error?E.message:"Invalid model provider")}}else J.getModel(X,q);if(M?.trim()){if(await J.setApiKey(X,M.trim()),W)Z=X}let u={provider:X,displayName:U||void 0,model:q,overrides:B||void 0},Y0=W?await _0().addModelWithProvider(u,W):await _0().addModel(u);return O.json({success:!0,model:Y0})}catch(z){if(Z)await J.credentials.delete(Z);if(Y){let X=$0();J.configureModelProviders(X?.modelProviders??{},X?.models??[])}throw I$.error("[ModelsRoutes] Failed to add model:",z),z}}),$.put("/:modelId",async(O)=>{try{let J=O.req.param("modelId"),Z=await O.req.json(),{displayName:Y,overrides:z,model:X}=Z,U=s1(J);if(!U)throw new _("model config not found");if(X)g0().getModel(U.provider,X);return await _0().updateModel(J,Y2({displayName:Y,overrides:z,model:X})),O.json({success:!0})}catch(J){throw I$.error("[ModelsRoutes] Failed to update model:",J),J}}),$.delete("/:modelId",async(O)=>{try{let J=O.req.param("modelId");return await _0().removeModel(J),O.json({success:!0})}catch(J){throw I$.error("[ModelsRoutes] Failed to delete model:",J),J}}),$};import{Hono as A2}from"hono";import J4 from"node:path";import{Mutex as Z4}from"async-mutex";import{Hono as Q2}from"hono";import{streamSSE as x2}from"hono/streaming";import{LRUCache as X2}from"lru-cache";import{nanoid as $$}from"nanoid";var y=d("Service"),z2=F.Object({title:F.Optional(F.String()),projectPath:F.Optional(F.String())}),K2=E4,V2=F.Object({title:F.Optional(F.String()),projectPath:F.Optional(F.String())}),N2=F.Object({projectPath:F.String()}),G2=F.Object({objective:F.String({minLength:1}),tokenBudget:F.Optional(F.Integer({minimum:1})),permissionMode:F.Optional(V0(["default","autoEdit","plan","yolo"]))}),W2=F.Union([F.Object({action:F.Literal("pause")}),F.Object({action:F.Literal("resume")}),F.Object({action:F.Literal("edit"),objective:F.String({minLength:1})})]),n=new Map,J$,b0=new Map,v0=new Map,q0=new Map,m$=new X2({max:100,ttl:1800000});function Y4($){return{sessionId:$.sessionId,projectPath:$.projectPath}}function G0($){if(!$)return;return b0.get($)??m$.get($)}function U2($){if(b0.get($.id)!==$)return;b0.delete($.id),m$.set($.id,$)}function F2($){b0.delete($),m$.delete($)}function U0($){return $?.status==="queued"||$?.status==="running"||$?.status==="waiting_permission"}function H$($,O="user-cancel"){if($.status==="cancelled"||$.status==="completed"||$.status==="failed")return!1;let J=$.pendingPermission;if($.pendingPermission=void 0,J?.resolve({approved:!1,reason:V4}),J)j.publish(Y4($),"interaction.resolved",{requestId:J.permissionId});return $.abortController.abort(O),$.status="cancelled",j.publish(Y4($),"run.cancelled",{runId:$.id}),!0}function q4($,O=!1){let{permissionId:J,details:Z}=$;if(Z.type==="askUserQuestion"&&Z.questions)return{type:"question.required",properties:{requestId:J,toolCallId:Z.toolCallId??J,questions:Z.questions,details:Z,...O?{replayed:!0}:{}}};if(Z.type==="mcpElicitation"&&Z.mcpElicitation)return{type:"elicitation.required",properties:{requestId:J,toolCallId:Z.toolCallId??J,elicitation:Z.mcpElicitation,...O?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:J,toolName:Z.toolName,description:Z.message,args:Z.args,details:Z,...O?{replayed:!0}:{}}}}function D2($){return{...typeof $.seq==="number"?{id:String($.seq)}:{},data:JSON.stringify({type:$.type,...typeof $.seq==="number"?{seq:$.seq}:{},properties:{...$.properties,sessionId:$.sessionId,projectPath:$.projectPath}})}}function H2(){for(let $ of b0.values())H$($,"route-reset");b0.clear();for(let $ of v0.values())$.controller.abort("route-reset");v0.clear(),m$.clear(),J$=void 0,n.clear()}function _2($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$,J=O.code,Z=O.reason,Y=O.scope,z=O.kind,X=O.limit;if(J!=="tool_busy"&&J!=="tool_batch_full"||Z!=="queue_full"&&Z!=="wait_timeout"&&Z!=="turn_limit"||Y!=="global"&&Y!=="session"||typeof O.retryable!=="boolean"||!Number.isSafeInteger(X)||X<=0||z!==void 0&&z!=="readonly"&&z!=="write"&&z!=="execute")return;return{code:J,reason:Z,scope:Y,retryable:O.retryable,...z===void 0?{}:{kind:z},limit:X}}var _$=($,O)=>{if(!O||typeof O!=="object")return O;let J={...O},Z=_2(J.tool_admission);if(Z)J.tool_admission=Z;else delete J.tool_admission;if($==="Bash"){let X={},U=["message","signal","status","summary"],q=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],B=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let T of U){let W=J[T];if(typeof W==="string")X[T]=W.slice(0,8192)}for(let T of q){let W=J[T];if(typeof W==="boolean")X[T]=W}for(let T of B){let W=J[T];if(typeof W==="number"&&Number.isSafeInteger(W)&&W>=0)X[T]=W}if(J.exit_code===null||typeof J.exit_code==="number"&&Number.isSafeInteger(J.exit_code))X.exit_code=J.exit_code;if(J.terminal_transport==="local"||J.terminal_transport==="acp"||J.terminal_transport==="local_fallback")X.terminal_transport=J.terminal_transport;if(J.background_reason==="explicit"||J.background_reason==="foreground_budget")X.background_reason=J.background_reason;for(let T of["bash_id","shell_id"]){let W=J[T];if(typeof W==="string"&&W.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(W))X[T]=W}if(Z)X.tool_admission=Z;let M=J.background_shell_admission;if(M&&typeof M==="object"&&!Array.isArray(M)){let T=M;if(T.code==="background_shell_busy"&&(T.scope==="session"||T.scope==="global")&&T.retryable===!0&&Number.isSafeInteger(T.limit)&&T.limit>0)X.background_shell_admission={code:T.code,scope:T.scope,retryable:T.retryable,limit:T.limit}}return X}let Y=200000,z=(X,U)=>typeof X==="number"&&Number.isSafeInteger(X)&&X>=0&&X<=U?X:0;if(typeof J.oldContent==="string"&&J.oldContent.length>Y)delete J.oldContent;if(typeof J.newContent==="string"&&J.newContent.length>Y)delete J.newContent;if(J.mcpResult&&typeof J.mcpResult==="object"&&!Array.isArray(J.mcpResult)){let X=J.mcpResult,U=Array.isArray(X.artifacts)?X.artifacts.slice(0,64).flatMap((q)=>{if(!q||typeof q!=="object"||Array.isArray(q))return[];let B=q,M=new Set(["text","image","audio","resource"]);if(typeof B.id!=="string"||!/^[a-f0-9]{64}$/.test(B.id)||typeof B.sha256!=="string"||B.sha256!==B.id||typeof B.kind!=="string"||!M.has(B.kind)||z(B.size,67108864)!==B.size||typeof B.persisted!=="boolean")return[];return[{id:B.id.slice(0,128),sha256:B.sha256.slice(0,128),kind:B.kind,size:B.size,persisted:B.persisted,...typeof B.mimeType==="string"?{mimeType:B.mimeType.slice(0,256)}:{},...typeof B.sourceUri==="string"?{sourceUri:B.sourceUri.slice(0,8192)}:{},...typeof B.path==="string"?{path:B.path.slice(0,8192)}:{}}]}):[];J.mcpResult={isError:X.isError===!0,contentCount:z(X.contentCount,64),textBytes:z(X.textBytes,4194304),structuredBytes:z(X.structuredBytes,4194304),artifactCount:z(X.artifactCount,64),truncated:X.truncated===!0,binaryOmitted:X.binaryOmitted===!0,artifacts:U}}else delete J.mcpResult;return J};function B2($){let O=typeof $.seq==="number"?{seq:$.seq}:{};if($.type==="part_created"&&$.data.partType==="tool_call"){let J=$.data.payload;return{type:"tool.start",...O,properties:{messageId:$.data.messageId,toolCallId:J.toolCallId??$.data.partId,toolName:J.toolName??"unknown",arguments:JSON.stringify(J.input??{})}}}if($.type==="part_created"&&$.data.partType==="tool_result"){let J=$.data.payload,Z=J.toolName??"unknown",Y=Y1(J),z=w$(A$(Z,Y),L$);return{type:"tool.result",...O,properties:{messageId:$.data.messageId,toolCallId:J.toolCallId??$.data.partId,toolName:Z,success:Y.success,status:Y.success?"completed":"failed",summary:Y.metadata?.summary,output:M$(z),metadata:_$(Z,Y.metadata)}}}return{type:`committed.${$.type}`,...O,properties:{event:$}}}function L2($,O,J){switch(J.kind){case"tool_start":if("function"in J.toolCall)j.publish($,"subagent.update",{subagentSessionId:O,toolName:J.toolCall.function.name}),j.publish($,"subagent.tool.start",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,arguments:J.toolCall.function.arguments,toolKind:J.toolKind});break;case"tool_result":if("function"in J.toolCall)j.publish($,"subagent.tool.result",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,success:J.result.success,summary:J.result.metadata?.summary,output:M$(w$(A$(J.toolCall.function.name,J.result),L$)),metadata:_$(J.toolCall.function.name,J.result.metadata)});break;case"tool_progress":if("function"in J.toolCall)j.publish($,"subagent.tool.progress",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,...J.update});break;case"content_delta":j.publish($,"subagent.delta",{subagentSessionId:O,delta:J.delta});break;case"thinking_delta":j.publish($,"subagent.thinking.delta",{subagentSessionId:O,delta:J.delta});break;case"stream_end":j.publish($,"subagent.stream.end",{subagentSessionId:O});break;case"provider_admission":j.publish($,"subagent.provider.admission",{subagentSessionId:O,phase:J.phase,requestClass:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queuePosition:J.queuePosition,queueDepth:J.queueDepth,inFlight:J.inFlight,limit:J.limit,waitMs:J.waitMs,maxWaitMs:J.maxWaitMs,recoveryRemainingMs:J.recoveryRemainingMs});break;case"provider_circuit":j.publish($,"subagent.provider.circuit",{subagentSessionId:O,phase:J.phase,reason:J.reason,statusCode:J.statusCode,retryAfterMs:J.retryAfterMs,nextProbeAt:J.nextProbeAt,openDurationMs:J.openDurationMs,sampleCount:J.sampleCount,failureCount:J.failureCount,recoveryRemainingMs:J.recoveryRemainingMs});break;case"provider_retry":j.publish($,"subagent.provider.retry",{subagentSessionId:O,phase:J.phase,attempt:J.attempt,maxRetries:J.maxRetries,reason:J.reason,statusCode:J.statusCode,delayMs:J.delayMs,nextRetryAt:J.nextRetryAt,mode:J.mode,recoveryBudgetMs:J.recoveryBudgetMs,recoveryElapsedMs:J.recoveryElapsedMs,recoveryRemainingMs:J.recoveryRemainingMs,exhaustedBy:J.exhaustedBy});break;case"provider_stall":j.publish($,"subagent.provider.stall",{subagentSessionId:O,phase:J.phase,stallCount:J.stallCount,durationMs:J.durationMs,warningAfterMs:J.warningAfterMs,timeoutMs:J.timeoutMs,outputStarted:J.outputStarted});break;case"action_stationarity":j.publish($,"subagent.action.stationarity",{subagentSessionId:O,phase:J.phase,toolName:J.toolName,runLength:J.runLength,nudgeThreshold:J.nudgeThreshold,haltThreshold:J.haltThreshold,progressAware:J.progressAware});break;case"mcp_catalog_changed":j.publish($,"subagent.mcp.catalog.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,added:J.added,removed:J.removed,updated:J.updated});break;case"mcp_content_changed":j.publish($,"subagent.mcp.content.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,contentKind:J.contentKind,added:J.added,removed:J.removed,updated:J.updated});break;case"mcp_resource_updated":j.publish($,"subagent.mcp.resource.updated",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,uri:J.uri});break;case"mcp_connection_changed":j.publish($,"subagent.mcp.connection.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,maxAttempts:J.maxAttempts,nextRetryAt:J.nextRetryAt,error:J.error});break;case"mcp_log":j.publish($,"subagent.mcp.log",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,level:J.level,logger:J.logger,message:J.message,projectedBytes:J.projectedBytes,dataSha256:J.dataSha256,truncated:J.truncated,detailsOmitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});break;case"mcp_instructions_changed":j.publish($,"subagent.mcp.instructions.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,action:J.action,reason:J.reason,text:J.text,sourceBytes:J.sourceBytes,projectedBytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,detailsOmitted:J.detailsOmitted});break;case"mcp_task_changed":j.publish($,"subagent.mcp.task.changed",{subagentSessionId:O,revision:J.revision,taskId:J.taskId,serverName:J.serverName,toolName:J.toolName,status:J.status,statusMessage:J.statusMessage,createdAt:J.createdAt,updatedAt:J.updatedAt,completedAt:J.completedAt,hasResult:J.hasResult,error:J.error});break;case"project_rules_loaded":j.publish($,"subagent.project.rules.loaded",{subagentSessionId:O,files:J.files,triggerPaths:J.triggerPaths,blockedWrite:J.blockedWrite});break;default:break}}function F$($,O="projectPath"){if(!J4.isAbsolute($))throw new _(`${O} must be absolute`);return J4.resolve($)}function J1($){try{C$($)}catch(O){throw new _(O instanceof Error?O.message:`Invalid session ID: ${$}`)}}function x0($){return{sessionId:$.id,projectPath:$.projectPath}}function D$($,O,J){return{id:$.sessionId,projectPath:$.projectPath,title:$.title??`Session ${$.sessionId.slice(0,6)}`,createdAt:new Date($.firstMessageTime),updatedAt:new Date($.lastMessageTime),rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,taskStatus:$.taskStatus,taskStatusReason:$.taskStatusReason,taskFailure:$.taskFailure,taskStartedAt:$.taskStartedAt,taskCompletedAt:$.taskCompletedAt,taskPromptSummary:$.taskPromptSummary,taskModelId:$.taskModelId,selectedModelId:$.selectedModelId,permissionMode:$.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,communicationStyleDigest:$.communicationStyleDigest,projectInstructionsDigest:$.projectInstructionsDigest,pendingInteraction:$.pendingInteraction,taskRetryAvailable:$.taskRetryAvailable,taskRetriedFrom:$.taskRetriedFrom,taskDelivery:$.taskDelivery,taskIsolation:$.taskIsolation,taskSourceProjectPath:$.taskSourceProjectPath,taskWorktreePath:$.taskWorktreePath,taskWorktreeBranch:$.taskWorktreeBranch,taskBaseCommit:$.taskBaseCommit,taskDiffStat:$.taskDiffStat,taskQueuePosition:$.taskQueuePosition,taskQueueDepth:$.taskQueueDepth,taskConcurrencyLimit:$.taskConcurrencyLimit,archivedAt:$.archivedAt,archivedBySessionId:$.archivedBySessionId,taskWorktree:J,messages:O}}function o$($){return $.flatMap((O)=>{if(!G4(O)||O.role==="system"||O.role==="tool"&&O.name===O$)return[];let J=O.tool_calls?.filter((X)=>!("function"in X)||X.function.name!==O$),Z=typeof O.content==="string"?O.content.trim():"";if(O.role==="assistant"&&O.tool_calls?.length&&!J?.length&&!Z&&!O.reasoningContent&&!O.metadata)return[];let Y={...O,...O.tool_calls?{tool_calls:J&&J.length>0?J:void 0}:{}};if(O.role==="tool"){let X=O.metadata&&typeof O.metadata==="object"&&!Array.isArray(O.metadata)?O.metadata:void 0,U=O.name??(typeof X?.toolName==="string"?X.toolName:"unknown");if(X!==void 0&&(Object.hasOwn(X,"output")||Object.hasOwn(X,"error"))){let B=Y1(X),M=w$(A$(U,B),L$);return[{...Y,name:U,content:M$(M),metadata:_$(U,{...B.metadata,status:B.success?"completed":"failed"})}]}return[{...Y,name:U,metadata:_$(U,X)}]}let z=U4(O.metadata);return[z?{...Y,content:W4(z)}:Y]})}function B$($,O){$.taskStatus=O.taskStatus,$.taskStatusReason=O.taskStatusReason,$.taskFailure=O.taskFailure,$.taskStartedAt=O.taskStartedAt,$.taskCompletedAt=O.taskCompletedAt,$.taskPromptSummary=O.taskPromptSummary,$.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,$.updatedAt=new Date(O.lastMessageTime)}async function u0($){let O=await C.findSessionMetadata($.id,$.projectPath);if(O)B$($,O)}function e0($){let O=G0($.currentRunId),J=O?.status==="waiting_permission"?"running":O?.status??$.taskStatus;return{sessionId:$.id,projectPath:$.projectPath,title:$.title,rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,status:void 0,taskStatus:J,taskStatusReason:$.taskStatusReason,taskFailure:$.taskFailure,taskStartedAt:$.taskStartedAt,taskCompletedAt:$.taskCompletedAt,taskPromptSummary:$.taskPromptSummary,taskModelId:$.taskModelId,selectedModelId:$.selectedModelId,permissionMode:$.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,communicationStyleDigest:$.communicationStyleDigest,projectInstructionsDigest:$.projectInstructionsDigest,taskRetryAvailable:$.taskRetryAvailable,taskRetriedFrom:$.taskRetriedFrom,taskDelivery:$.taskDelivery,taskIsolation:$.taskIsolation,taskSourceProjectPath:$.taskSourceProjectPath,taskWorktreePath:$.taskWorktreePath,taskWorktreeBranch:$.taskWorktreeBranch,taskBaseCommit:$.taskBaseCommit,taskDiffStat:$.taskDiffStat,taskQueuePosition:O?.status==="queued"?O.taskQueuePosition:J==="queued"?$.taskQueuePosition:void 0,taskQueueDepth:O?.status==="queued"?O.taskQueueDepth:J==="queued"?$.taskQueueDepth:void 0,taskConcurrencyLimit:O?.taskConcurrencyLimit??$.taskConcurrencyLimit,archivedAt:$.archivedAt,archivedBySessionId:$.archivedBySessionId,pendingInteraction:O?.pendingPermission?{type:O.pendingPermission.details.type==="askUserQuestion"?"question":O.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:O.pendingPermission.permissionId}:$.pendingInteraction,agentType:void 0,model:void 0,messageCount:$.messages.length,firstMessageTime:$.createdAt.toISOString(),lastMessageTime:$.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function z0($,O){if(J1($),O!==void 0){let Z=I0({sessionId:$,projectPath:F$(O)});if(n.has(h(Z)))return Z;let Y=await C.findSessionMetadata(Z.sessionId,Z.projectPath);if(!Y)throw new f("Session",$);return I0({sessionId:Y.sessionId,projectPath:Y.projectPath})}let J=new Map;for(let Z of n.values()){if(Z.id!==$)continue;let Y=x0(Z);J.set(h(Y),Y)}for(let Z of await C.listSessions()){if(Z.sessionId!==$)continue;let Y=I0({sessionId:Z.sessionId,projectPath:Z.projectPath});J.set(h(Y),Y)}if(J.size===0)try{let Z=await C.findSessionMetadata($);if(!Z)throw new f("Session",$);return I0({sessionId:Z.sessionId,projectPath:Z.projectPath})}catch(Z){if(Z instanceof f)throw Z;if(Z instanceof Error&&Z.message.startsWith("Ambiguous session ID:"))throw new H0;throw Z}if(J.size>1)throw new H0;return J.values().next().value}function Z1($){if(typeof $==="string")return $;return $.filter((O)=>O.type==="text").map((O)=>O.text).join(`
7
- `)}function Q4($,O){let J=(O??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(J.length===0)return $;let Z=[];if($.trim())Z.push({type:"text",text:$});return Z.push(...J),Z}var R4=()=>{H2();let $=new Q2;$.onError((x,G)=>{if(x instanceof e)return G.json(x.toObject(),x.statusCode);return y.error("[SessionRoutes] Unhandled route error:",x),G.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let O=new Map,J=new Map,Z=new Map,Y=new Map,z=new Map,X=new Map,U=new _4,q,B=async(x)=>{let G;try{G=U.enter()}catch{throw new h0}try{return await x()}finally{G.release()}};$.use("*",async(x,G)=>{if(x.req.method==="GET"||x.req.method==="HEAD")return G();return B(G)});let M=(x)=>{let G=h(x),Q=z.get(G);if(!Q)Q=new Z4,z.set(G,Q);return Q},T=(x)=>{let G=h(x),Q=X.get(G);if(!Q)Q=new Z4,X.set(G,Q);return Q},W=async(x,G={})=>{let Q=h(x0(x));await Z.get(Q);let K=O.get(Q);if(K)return K;let N=J.get(Q);if(!N){let D=G.communicationStyle??x.communicationStyle;N=U$.create({sessionId:x.id,workspaceRoot:x.projectPath,...x.selectedModelId??x.taskModelId?{modelId:x.selectedModelId??x.taskModelId}:{},permissionMode:G.permissionMode??x.permissionMode??"default",...x.reasoningEffort?{reasoningEffort:x.reasoningEffort}:{},...x.serviceTier?{serviceTier:x.serviceTier}:{},...x.responseVerbosity?{responseVerbosity:x.responseVerbosity}:{},...D?{communicationStyle:D}:{},...D===x.communicationStyle&&x.communicationStyleDigest?{communicationStyleDigest:x.communicationStyleDigest}:{},...x.projectInstructionsDigest?{projectInstructionsDigest:x.projectInstructionsDigest}:{},...x.taskWorktree?{taskWorktree:x.taskWorktree}:{},...x.taskIsolation?{taskIsolation:x.taskIsolation}:{},...x.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:x.id}}:{}}),J.set(Q,N)}try{let D=await N;return O.set(Q,D),D}finally{if(J.get(Q)===N)J.delete(Q)}},u=async(x,G)=>{let Q=h(x0(x)),K=Z.get(Q);if(!K)K=(async()=>{let N=J.get(Q);if(N)await N.catch(()=>{return});J.delete(Q);let D=G??O.get(Q);if(O.delete(Q),D){for(let[H,L]of O)if(L===D)O.delete(H)}await D?.dispose()})().finally(()=>{if(Z.get(Q)===K)Z.delete(Q)}),Z.set(Q,K);await K},Y0=async(x)=>{let G=h(x),Q=n.get(G);if(Q)return Q;let K=Y.get(G);if(!K)K=(async()=>{let N=await C.findSessionMetadata(x.sessionId,x.projectPath);if(!N)throw new f("Session",x.sessionId);let[D,H]=await Promise.all([C.loadSession(x.sessionId,x.projectPath),C.findSessionTaskWorktree(x.sessionId,x.projectPath)]),L=D$(N,D,H);return n.set(G,L),L})(),Y.set(G,K);try{return await K}finally{if(Y.get(G)===K)Y.delete(G)}},E=async(x,G)=>{let Q=await z0(x,G);try{await C.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(K){if(K instanceof r$)throw new k(K.message);throw K}return Y0(Q)},t=async(x,G)=>{if(x.permissionMode===G)return;let Q=await C.setSessionPermissionMode(x.id,x.projectPath,G);x.permissionMode=Q.permissionMode,x.updatedAt=new Date(Q.lastMessageTime),j.publish(x0(x),"session.updated",{permissionMode:G})},I=(x,G,Q,K={})=>{if(!U.stats().accepting)throw new h0;let N=$$(12),D={id:N,sessionId:x.id,projectPath:x.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:K.taskRuntime!==void 0,createdAt:new Date};if(K.taskRuntime){let H=K.taskRuntime,L=r0.admit({key:`${x.projectPath}\x00${x.id}`,...H.getTaskAdmissionLimits(),pendingBytes:B4({content:G,outputSchema:K.outputSchema,pendingMessages:H.getPendingSteeringMessages()}),signal:D.abortController.signal,onUpdate:(b)=>{D.status=b.state,D.taskQueuePosition=b.queuePosition,D.taskQueueDepth=b.queueDepth,D.taskConcurrencyLimit=b.maxConcurrent,x.taskStatus=b.state,x.taskQueuePosition=b.queuePosition,x.taskQueueDepth=b.queueDepth,x.taskConcurrencyLimit=b.maxConcurrent,D.taskAdmissionUpdate=(D.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await H.setTaskAdmission(b)}).catch((w)=>{y.warn(`[SessionRoutes] Failed to persist admission for ${x.id}:`,w)})}});D.taskAdmission=L;let A=L.getSnapshot();D.status=A.state,D.taskQueuePosition=A.queuePosition,D.taskQueueDepth=A.queueDepth,D.taskConcurrencyLimit=A.maxConcurrent}return b0.set(N,D),x.currentRunId=N,D.completion=w2(D,x,G,Q,W,{pendingInputOnly:K.pendingInputOnly,preparedInputTurn:K.preparedInputTurn,goalContinuationOnly:K.goalContinuationOnly,outputSchema:K.outputSchema,taskAdmission:D.taskAdmission,disposeRuntime:u}).catch((H)=>{y.error(`[SessionRoutes] Run ${N} failed:`,H)}),D},O0=async(x)=>{let G;if(x.outputSchema)try{G=t$(x.outputSchema).schema}catch(R){throw new _(R instanceof Error?R.message:"Invalid output schema")}let Q=n$("task",12),K=F$(x.sourceProjectPath),N=x.modelId?.trim(),D=$0();if(!D)throw new _("Config not initialized");let[H,L]=await Promise.all([P$(K,D),W0(K)]);if(N&&!H.config.models.some((R)=>R.id===N))throw new _(`Task model not found: ${N}`);let A=N||H.config.models.find((R)=>R.id===H.config.currentModelId)?.id||H.config.models[0]?.id;if(!A)throw new _("No model is configured. Add or select a model before dispatching a task.");let b=H.config.models.find((R)=>R.id===A);if(!b)throw new _(`Task model not found: ${A}`);let w=x.reasoningEffort??"off",r=x.serviceTier??"auto",F0=x.responseVerbosity??"auto",j0=x.communicationStyle??"auto",w0,Q0=L.projectRules?.staticRules(K),i=Q0&&Q0.files.length>0?Q0.provenanceSha256:void 0;try{let R=H.catalog.resolveConfig(b);z4(R,w),X4(R,r),x4(R,F0);let o=K4(j0,L.communicationStyles);w0=o.source==="built-in"?void 0:o.contentSha256}catch(R){throw new _(R instanceof Error?R.message:"Invalid reasoning effort")}let c0={version:1,prompt:x.prompt,...x.title?{title:x.title}:{},sourceProjectPath:K,isolation:x.isolation,permissionMode:x.permissionMode,modelId:A,reasoningEffort:w,serviceTier:r,responseVerbosity:F0,communicationStyle:j0,...w0?{communicationStyleDigest:w0}:{},...i?{projectInstructionsDigest:i}:{},...x.attachments?{attachments:x.attachments.map((R)=>({...R}))}:{},...G?{outputSchema:G}:{}},P,S;try{let R=await w4.createSessionTask({sessionId:Q,prompt:x.prompt,title:x.title,sourceProjectPath:K,isolation:x.isolation,dispatch:c0,retriedFrom:x.retriedFrom}),{metadata:o}=R;P=R.taskWorktree,S=D$(o,[],P);let Z0=x0(S);n.set(h(Z0),S),j.publish(Z0,"task.status",{taskStatus:o.taskStatus,updatedAt:o.lastMessageTime});let l=Q4(x.prompt,x.attachments),p=await W(S),s=G?await p.prepareInputTurn(l,{outputSchema:G}):await p.prepareInputTurn(l);if(!s.accepted)throw new k(`Task prompt was not accepted: ${s.reason}`);let A0=I(S,l,x.permissionMode,{preparedInputTurn:s,taskRuntime:p,outputSchema:G});return await A0.taskAdmissionUpdate,{session:e0(S),runId:A0.id,messageId:s.messageId,status:A0.status==="queued"?"queued":"running",queuePosition:A0.taskQueuePosition,queueDepth:A0.taskQueueDepth,maxConcurrentTasks:A0.taskConcurrencyLimit}}catch(R){if(R instanceof O1&&S){let o=x0(S),Z0=h(o);if(P)await T0.exit({sessionId:S.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await O.get(Z0)?.dispose().catch(()=>{return}),O.delete(Z0),await C.deleteSession(S.id,S.projectPath).catch(()=>{return}),n.delete(Z0),new o0("Task admission capacity is full",{resource:R.resource})}if(S){let o=await C.findSessionMetadata(S.id,S.projectPath).catch(()=>{return});if(!o||o.taskStatus==="queued"){let Z0=f$(R),l=await C.updateSessionMetadata(S.id,S.projectPath,{taskStatus:"failed",taskStatusReason:Z0.message,taskFailure:Z0,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});S.taskStatus=l?.taskStatus??"failed",S.taskStatusReason=l?.taskStatusReason??Z0.message,S.taskFailure=l?.taskFailure??Z0,S.taskCompletedAt=l?.taskCompletedAt}else S.taskStatus=o.taskStatus,S.taskStatusReason=o.taskStatusReason,S.taskFailure=o.taskFailure,S.taskCompletedAt=o.taskCompletedAt}throw R}},v=(x)=>B(()=>O0(x)),m0=async(x,G)=>{let Q=await z0(x,G),K=await C.findSessionMetadata(Q.sessionId,Q.projectPath);if(!K)throw new f("Session",Q.sessionId);if(!["failed","interrupted","cancelled"].includes(K.taskStatus))throw new k(`Task cannot be retried while status is ${K.taskStatus}`);let N=await C.findSessionTaskDispatch(Q.sessionId,Q.projectPath);if(!N)throw new k("Task retry payload is unavailable");return v({prompt:N.prompt,title:N.title,sourceProjectPath:N.sourceProjectPath,isolation:N.isolation,permissionMode:N.permissionMode,modelId:N.modelId,reasoningEffort:N.reasoningEffort,serviceTier:N.serviceTier,responseVerbosity:N.responseVerbosity,communicationStyle:N.communicationStyle,attachments:N.attachments,outputSchema:N.outputSchema,retriedFrom:Q})},q$=(x,G)=>B(()=>m0(x,G)),X0=async(x,G)=>{let Q=await E(x,G);if(!Q.taskWorktree)throw new _("Session does not have a task worktree");try{await T0.restoreSession(Q.taskWorktree);let K=await T0.getDiffArtifact(Q.id);if(!K)throw new k("Task diff artifact is unavailable");return{sessionId:Q.id,projectPath:Q.projectPath,...K}}catch(K){if(K instanceof k)throw K;throw y.error("[SessionRoutes] Failed to load task diff artifact:",K),new k("Task diff artifact is unavailable")}},R$=async(x,G,Q)=>{let K=await z0(x,Q);return T(K).runExclusive(async()=>{let N=await E(K.sessionId,K.projectPath);if(["queued","running"].includes(N.taskStatus))throw new k(`Task artifacts cannot be delivered while status is ${N.taskStatus}`);if(N.taskDelivery?.status==="applied")throw new k("Task changes have already been applied");if(N.taskDelivery?.status==="discarded")throw new k("Task changes have already been discarded");if(!N.taskWorktree)throw new k("Task worktree is unavailable");let D=async(H,L=!1)=>{let A=await C.updateSessionMetadata(N.id,N.projectPath,{taskDelivery:H,...L?{taskWorktree:null}:{}});if(B$(N,A),L)N.taskWorktree=void 0;return j.publish(K,"task.delivery",{taskDelivery:H,...L?{taskWorktreeRemoved:!0}:{},updatedAt:A.lastMessageTime}),e0(N)};try{if(G==="discard"){try{await T0.restoreSession(N.taskWorktree)}catch(A){return y.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${N.id}:`,A),D({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:N.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let L=await T0.exit({sessionId:N.id,action:"remove",discardChanges:!0});return D({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:L.discardedFiles??0,message:"Task worktree removed"},!0)}try{await T0.restoreSession(N.taskWorktree)}catch(L){throw y.warn(`[SessionRoutes] Task worktree is unavailable for ${N.id}:`,L),new $1("artifact_unavailable","Task worktree is unavailable")}let H=await T0.apply(N.id);return D({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:H.sourceCommit,changedFiles:H.changedFiles,message:"Task changes applied to the source workspace"})}catch(H){if(H instanceof $1)throw await D({status:"conflicted",updatedAt:new Date().toISOString(),message:H.message}),new k(H.message);throw H}})},R0=(x,G,Q)=>B(()=>R$(x,G,Q)),V=async(x)=>{let G=G0(x.currentRunId);if(U0(G))return;if(x.taskIsolation&&x.taskStatus!=="queued"&&x.taskStatus!=="running")return;let Q=await U$.hasPendingInbox(x.projectPath,x.id),K=!Q&&await U$.hasActiveGoal(x.projectPath,x.id);if(!Q&&!K)return;let N=await W(x),D=G0(x.currentRunId);if(U0(D))return;if(Q&&N.getPendingSteeringCount()===0)await N.reloadPendingInbox();let H=N.getPendingSteeringCount()>0,L=H?null:await N.getGoal(),A=L?.status==="active"||L?.status==="verifying";if(!H&&!A||N.hasTurnOwner())return;I(x,"",x.permissionMode??"default",{pendingInputOnly:H,goalContinuationOnly:A,...x.taskIsolation?{taskRuntime:N}:{}})},J0=async(x)=>{let G;try{G=U.enter()}catch{return}try{await V(x)}finally{G.release()}};J$=J0;let B1=async()=>{let x={scheduled:0,failed:0,deferred:0};if(!U.stats().accepting)return x;let G=(await C.listSessions()).filter((Q)=>Q.taskStatus==="queued"&&Q.taskIsolation!==void 0).sort((Q,K)=>Q.firstMessageTime.localeCompare(K.firstMessageTime)||Q.projectPath.localeCompare(K.projectPath)||Q.sessionId.localeCompare(K.sessionId));for(let[Q,K]of G.entries()){let N={sessionId:K.sessionId,projectPath:K.projectPath};try{if(!await U$.hasPendingInbox(K.projectPath,K.sessionId)){let H=f$("Queued task input is missing");await C.updateSessionMetadata(K.sessionId,K.projectPath,{taskStatus:"failed",taskStatusReason:H.message,taskFailure:H,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),x.failed++;continue}let D=await Y0(N);if(await J0(D),D.currentRunId)x.scheduled++}catch(D){if(D instanceof O1){x.deferred+=G.length-Q;break}y.warn(`[SessionRoutes] Failed to recover queued task ${K.sessionId}:`,D),x.deferred++}}return x};return $.get("/",async(x)=>{try{let G=await C.listSessions(),Q=new Set(G.filter((b)=>b.relationType==="subagent").map((b)=>h({sessionId:b.sessionId,projectPath:b.projectPath}))),K=Array.from(n.values()).filter((b)=>!Q.has(h(x0(b)))&&b.relationType!=="subagent").map((b)=>e0(b)),N=new Set(K.map((b)=>h({sessionId:b.sessionId,projectPath:b.projectPath}))),D=G.filter((b)=>{if(b.relationType==="subagent")return!1;return!N.has(h({sessionId:b.sessionId,projectPath:b.projectPath}))}),H=new Set(N),L=D.filter((b)=>{let w=h({sessionId:b.sessionId,projectPath:b.projectPath});if(H.has(w))return!1;return H.add(w),!0}),A=[...K,...L];return x.json(A)}catch(G){throw y.error("[SessionRoutes] Failed to list sessions:",G),new a("Failed to list sessions")}}),$.get("/catalog",async(x)=>{try{let G=x.req.query("limit"),Q=G===void 0?void 0:Number(G),K=x.req.query("cursor"),N=x.req.query("projectPath"),D=x.req.query("archived");if(D!==void 0&&D!=="true"&&D!=="false")throw new _("archived must be true or false");let H=D==="true",L=await C.listSessionPage({...N?{cwd:F$(N)}:{},...K?{cursor:K}:{},...Q===void 0?{}:{limit:Q},includeSubagents:!1,archived:H}),A=new Map((H?[]:Array.from(n.values())).filter((b)=>b.relationType!=="subagent").map((b)=>[h(x0(b)),e0(b)]));return x.json({sessions:L.sessions.map((b)=>A.get(h({sessionId:b.sessionId,projectPath:b.projectPath}))??b),...L.nextCursor?{nextCursor:L.nextCursor}:{}})}catch(G){if(G instanceof _)throw G;if(G instanceof Error&&(G.message.startsWith("Invalid session cursor")||G.message.startsWith("Session cursor scope")||G.message.startsWith("Session catalog")))throw new _(G.message);throw y.error("[SessionRoutes] Failed to list session catalog:",G),new a("Failed to list session catalog")}}),$.post("/",async(x)=>{try{let G=await x.req.json(),Q=m(z2,G);if(!Q.success)throw new _("Invalid request body");let{title:K,projectPath:N}=Q.data,D=n$("web",12),H=F$(N||x.get("directory")||g(),N?"projectPath":"directory"),L=await C.createSessionMetadata(D,H,{title:K,taskStatus:"completed"}),A=D$(L,[]),b=x0(A);return n.set(h(b),A),j.publish(b,"session.created",{}),x.json({...e0(A),status:void 0,agentType:void 0,model:void 0})}catch(G){if(y.error("[SessionRoutes] Failed to create session:",G),G instanceof _)throw G;throw new a("Failed to create session")}}),$.get("/:sessionId/export",async(x)=>{let G=x.req.param("sessionId");try{let Q=x.req.query("includeReasoning");if(Q!==void 0&&Q!=="true"&&Q!=="false")throw new _("includeReasoning must be true or false");let K=await z0(G,x.req.query("projectPath")),N=await C.exportSessionMarkdown(K.sessionId,K.projectPath,{includeReasoning:Q==="true"});return x.body(N.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${N.filename}"`,"Content-Length":String(Buffer.byteLength(N.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":N.contentSha256,"X-Blade-Export-Activities":String(N.activityCount),"X-Blade-Export-Messages":String(N.messageCount),"X-Blade-Export-Redactions":String(N.redactionCount)})}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;if(Q instanceof Error&&Q.message==="No conversation content to export")throw new k(Q.message);throw y.error("[SessionRoutes] Failed to export session:",Q),new a("Failed to export session")}}),$.post("/:sessionId/fork",async(x)=>{let G=x.req.param("sessionId");try{J1(G);let Q=await x.req.json(),K=m(N2,Q);if(!K.success)throw new _("Invalid request body");let N=F$(K.data.projectPath),D=await C.findSessionMetadata(G,N);if(!D)throw new f("Session",G);let H=await C.forkSession(G,{sourceProjectPath:D.projectPath,targetProjectPath:D.projectPath}),L=D$(H.metadata,H.messages),A=x0(L);return n.set(h(A),L),j.publish(A,"task.status",{taskStatus:H.metadata.taskStatus,...H.metadata.taskCompletedAt?{taskCompletedAt:H.metadata.taskCompletedAt}:{},updatedAt:H.metadata.lastMessageTime}),x.json({session:H.metadata,messages:o$(H.messages)},201)}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof k)throw Q;if(Q instanceof F4)throw new k("Session has no durable creation record");throw y.error("[SessionRoutes] Failed to fork session:",Q),new a("Failed to fork session")}}),$.get("/:sessionId",async(x)=>{let G=x.req.param("sessionId");try{let Q=await z0(G,x.req.query("projectPath")),K=n.get(h(Q));if(K)return x.json(e0(K));let N=await C.findSessionMetadata(Q.sessionId,Q.projectPath);if(!N)throw new f("Session",G);return x.json(N)}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;throw y.error("[SessionRoutes] Failed to get session:",Q),new a("Failed to get session")}}),$.patch("/:sessionId",async(x)=>{let G=x.req.param("sessionId");try{let Q=await x.req.json(),K=m(V2,Q);if(!K.success)throw new _("Invalid request body");if(K.data.title===void 0)throw new _("title is required");let N=await z0(G,K.data.projectPath),D=await C.updateSessionMetadata(N.sessionId,N.projectPath,{title:K.data.title}),H=n.get(h(N));if(H)H.title=D.title??H.title,H.updatedAt=new Date(D.lastMessageTime);if(D.title)j.publish(N,"session.updated",{title:D.title});return x.json({success:!0,title:D.title})}catch(Q){if(y.error("[SessionRoutes] Failed to update session:",Q),Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;throw new a("Failed to update session")}}),$.get("/:sessionId/rewind",async(x)=>{let G=await E(x.req.param("sessionId"),x.req.query("projectPath")),Q=await W(G);return x.json({checkpoints:await Q.listRewindCheckpoints()})}),$.post("/:sessionId/rewind",async(x)=>{let G=m(A4,await x.req.json());if(!G.success)throw new _("Invalid rewind request");let Q=await E(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let N=G0(Q.currentRunId);if(U0(N))throw new k("Cannot rewind while a run is active");let D=await W(Q),H;try{H=await D.rewindSession(G.data)}catch(A){if(A instanceof Error&&A.message.startsWith("Cannot rewind while"))throw new k(A.message);throw A}Q.messages=[...H.messages],Q.updatedAt=new Date;let L=o$(H.messages);return j.publish(K,"session.rewound",{targetMessageId:H.checkpoint.messageId,mode:H.mode,removedTurns:H.removedTurns,restoredFiles:H.restoredFiles,messages:L}),x.json({...H,messages:L})})}),$.get("/:sessionId/review",async(x)=>{let G=x.req.param("sessionId"),Q=await z0(G,x.req.query("projectPath")),K=await k0.list(Q.projectPath,Q.sessionId);return x.json({reviews:K.map((N)=>({...N,content:N.completion?N4(N.start,N.completion):void 0}))})}),$.post("/:sessionId/review",async(x)=>{let G=x.req.param("sessionId"),Q=m(b4,await x.req.json());if(!Q.success)throw new _("Invalid code review request");let K=await E(G,Q.data.projectPath),N=x0(K),D=h(N);return M(N).runExclusive(async()=>{if(U0(G0(K.currentRunId)))throw new k("Cannot start a review during an active turn");if(q0.has(D))throw new k("Session already has an active review");let H=await W(K);if(await k0.recoverInterrupted(N.projectPath,N.sessionId,H),Q.data.modelId&&!H.getModelById(Q.data.modelId))throw new _(`Model not found: ${Q.data.modelId}`);if(Q.data.modelId&&H.getCurrentModelId()!==Q.data.modelId)await H.refresh({modelId:Q.data.modelId});if(Q.data.modelId&&K.selectedModelId!==Q.data.modelId){let w=await C.updateSessionMetadata(K.id,K.projectPath,{selectedModelId:Q.data.modelId});B$(K,w)}let L=new AbortController,A;try{A=await k0.start({sessionId:N.sessionId,projectPath:N.projectPath,runtime:H,request:{kind:Q.data.kind,...Q.data.ref?{ref:Q.data.ref}:{},...Q.data.instructions?{instructions:Q.data.instructions}:{}},signal:L.signal,onEvent:(w)=>{if(w.kind==="tool_start")j.publish(N,"review.tool.started",{reviewId:A?.reviewId,toolCallId:w.toolCall.id,toolName:w.toolCall.function.name});else if(w.kind==="tool_progress")j.publish(N,"review.tool.progress",{reviewId:A?.reviewId,toolCallId:w.toolCall.id,message:w.update.message.slice(0,1000)});else if(w.kind==="tool_result")j.publish(N,"review.tool.completed",{reviewId:A?.reviewId,toolCallId:w.toolCall.id,success:w.result.success})}})}catch(w){if(w instanceof Error&&(w.message.includes("active review")||w.message.includes("interrupted review")||w.message.includes("active turn")))throw new k(w.message);if(w instanceof Error&&(w.message.includes("review")||w.message.includes("Git")||w.message.includes("changes")||w.message.includes("ref")))throw new _(w.message);throw w}if(!A)throw new a("Code review failed to start");await u0(K),j.publish(N,"review.started",{reviewId:A.reviewId,kind:Q.data.kind}),j.publish(N,"task.status",{taskStatus:K.taskStatus,...K.taskStatusReason?{taskStatusReason:K.taskStatusReason}:{},...K.taskStartedAt?{taskStartedAt:K.taskStartedAt}:{},...K.taskPromptSummary?{taskPromptSummary:K.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let b=A.completion.then(async(w)=>{K.messages=await C.loadSession(N.sessionId,N.projectPath),await u0(K),j.publish(N,"task.status",{taskStatus:K.taskStatus,...K.taskStatusReason?{taskStatusReason:K.taskStatusReason}:{},...K.taskFailure?{taskFailure:K.taskFailure}:{},...K.taskStartedAt?{taskStartedAt:K.taskStartedAt}:{},...K.taskCompletedAt?{taskCompletedAt:K.taskCompletedAt}:{},...K.taskPromptSummary?{taskPromptSummary:K.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),j.publish(N,"review.completed",{reviewId:A.reviewId,status:w.status,findings:w.findings.length})}).catch((w)=>{y.error(`[SessionRoutes] Code review ${A.reviewId} failed:`,w)}).finally(()=>{if(q0.get(D)?.reviewId===A.reviewId)q0.delete(D)});return q0.set(D,{reviewId:A.reviewId,controller:L,completion:b}),x.json({reviewId:A.reviewId,status:"running"},202)})}),$.get("/:sessionId/subagents",async(x)=>{let G=await E(x.req.param("sessionId"),x.req.query("projectPath")),Q=await W(G);return x.json({subagents:Q.listSubagents().map(S$)})}),$.post("/:sessionId/subagents/:agentId/resume",async(x)=>{J1(x.req.param("agentId"));let G=M4.safeParse(await x.req.json());if(!G.success)throw new _("Invalid subagent resume request");let Q=await E(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let N=G0(Q.currentRunId);if(U0(N))throw new k("Cannot resume a subagent while a parent run is active");let D=await W(Q),H=!1,L,A=(w)=>{j.publish(K,"subagent.complete",{subagentSessionId:w.id,success:w.status==="completed",status:w.status,summary:w.result?.message?.slice(0,500),type:w.subagentType,verificationVerdict:w.result?.verificationVerdict,resumedFrom:w.resumedFrom,rootAgentId:w.rootAgentId,resumeDepth:w.resumeDepth})},b;try{b=D.resumeSubagent({agentId:x.req.param("agentId"),prompt:G.data.prompt,onEvent:(w,r)=>{L2(K,r,w)},onCompleted:(w)=>{if(H)A(w);else L=w}})}catch(w){if(w instanceof Error&&(w.message.startsWith("Cannot resume")||w.message.startsWith("Subagent cannot")))throw new k(w.message);if(w instanceof Error&&w.message.startsWith("Subagent not found"))throw new f(w.message);throw w}if(j.publish(K,"subagent.start",{subagentSessionId:b.session.id,type:b.session.subagentType,description:b.session.description,resumedFrom:b.source.id,rootAgentId:b.session.rootAgentId,resumeDepth:b.session.resumeDepth}),H=!0,L)A(L);return x.json({source:S$(b.source),session:S$(b.session)})})}),$.get("/:sessionId/goal",async(x)=>{let G=await E(x.req.param("sessionId"),x.req.query("projectPath"));return x.json({goal:await new D4(G.projectPath,G.id).get()})}),$.put("/:sessionId/goal",async(x)=>{let G=m(G2,await x.req.json());if(!G.success)throw new _("Invalid goal request");let Q=await E(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let N=G0(Q.currentRunId);if(U0(N))return x.json({status:"rejected",reason:"run_active"},409);let H=G.data.permissionMode??Q.permissionMode??"default";if(Q.permissionMode!==H)await t(Q,H);let L=await W(Q),A=await L.createGoal(G.data);j.publish(K,"goal.updated",{goal:A});let b=I(Q,"",H,{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:L}:{}});return await b.taskAdmissionUpdate,x.json({status:b.status==="queued"?"queued":"running",runId:b.id,goal:A,queuePosition:b.taskQueuePosition,queueDepth:b.taskQueueDepth,maxConcurrentTasks:b.taskConcurrencyLimit},202)})}),$.patch("/:sessionId/goal",async(x)=>{let G=m(W2,await x.req.json());if(!G.success)throw new _("Invalid goal update");let Q=await E(x.req.param("sessionId"),x.req.query("projectPath")),K=x0(Q);return M(K).runExclusive(async()=>{let N=await W(Q),D;if(G.data.action==="pause")D=await N.pauseGoal();else if(G.data.action==="edit")D=await N.editGoal(G.data.objective);else D=await N.resumeGoal();if(j.publish(K,"goal.updated",{goal:D}),D.status==="active"&&!U0(G0(Q.currentRunId))){let H=I(Q,"","default",{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:N}:{}});return await H.taskAdmissionUpdate,x.json({status:H.status==="queued"?"queued":"running",runId:H.id,goal:D,queuePosition:H.taskQueuePosition,queueDepth:H.taskQueueDepth,maxConcurrentTasks:H.taskConcurrencyLimit},202)}return x.json({status:D.status,goal:D})})}),$.delete("/:sessionId/goal",async(x)=>{let G=await E(x.req.param("sessionId"),x.req.query("projectPath")),Q=x0(G),N=await(await W(G)).clearGoal();if(N)j.publish(Q,"goal.cleared",{});return x.json({cleared:N})}),$.post("/:sessionId/archive",async(x)=>{let G=x.req.param("sessionId");try{let Q=await z0(G,x.req.query("projectPath")),K=await C.listSessionArchiveMembers(Q.sessionId,Q.projectPath);for(let D of K){let H=I0({sessionId:D.sessionId,projectPath:D.projectPath}),L=n.get(h(H));if(U0(G0(L?.currentRunId)))throw new k(`Stop session ${D.sessionId} before archiving this session tree`)}for(let D of K){let H=I0({sessionId:D.sessionId,projectPath:D.projectPath}),L=n.get(h(H));if(L)await u(L)}let N=await C.archiveSession(Q.sessionId,Q.projectPath);for(let D of K){let H=I0({sessionId:D.sessionId,projectPath:D.projectPath}),L=h(H);n.delete(L),Y.delete(L),J.delete(L),z.delete(L),j.publish(H,"session.archived",{archiveRootId:Q.sessionId,archivedAt:N.archivedAt})}if(O.size===0)await N0.getInstance().disconnectAll();return x.json({session:N,archivedSessionIds:K.map((D)=>D.sessionId)})}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0||Q instanceof k)throw Q;if(Q instanceof s$)throw new k(Q.message);throw y.error("[SessionRoutes] Failed to archive session:",Q),new a("Failed to archive session")}}),$.post("/:sessionId/unarchive",async(x)=>{let G=x.req.param("sessionId");try{let Q=await z0(G,x.req.query("projectPath")),K=await C.listSessionArchiveMembers(Q.sessionId,Q.projectPath),N=await C.unarchiveSession(Q.sessionId,Q.projectPath),D=K.filter((H)=>H.sessionId===Q.sessionId||H.archivedBySessionId===Q.sessionId).map((H)=>H.sessionId);for(let H of D)j.publish({sessionId:H,projectPath:Q.projectPath},"session.unarchived",{archiveRootId:Q.sessionId});return x.json({session:N,restoredSessionIds:D})}catch(Q){if(Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;if(Q instanceof s$)throw new k(Q.message);throw y.error("[SessionRoutes] Failed to unarchive session:",Q),new a("Failed to unarchive session")}}),$.delete("/:sessionId",async(x)=>{let G=x.req.param("sessionId"),Q=x.req.query("projectPath");try{let K=await z0(G,Q),N=h(K),D=n.get(N),H=O.get(N),L=D?.taskWorktree??await C.findSessionTaskWorktree(K.sessionId,K.projectPath),A;if(D?.currentRunId){let w=G0(D.currentRunId);if(w)H$(w),await w.completion,A=w.id}let b=q0.get(N);if(b)b.controller.abort("session-delete"),await b.completion;if(H)await H.clearGoal().catch((w)=>{y.warn("[SessionRoutes] Failed to clear session goal:",w)});if(await C.deleteSession(K.sessionId,K.projectPath),j.publish(K,"session.deleted",{}),A)F2(A);if(n.delete(N),Y.delete(N),J.delete(N),z.delete(N),H){if(await H.dispose(),O.delete(N),O.size===0)await N0.getInstance().disconnectAll()}if(L)try{await T0.restoreSession(L),await T0.exit({sessionId:K.sessionId,action:"remove",discardChanges:!0})}catch(w){y.warn(`[SessionRoutes] Failed to remove deleted task worktree ${K.sessionId}:`,w)}return x.json({success:!0})}catch(K){if(y.error("[SessionRoutes] Failed to delete session:",K),K instanceof _||K instanceof f||K instanceof H0)throw K;throw new a("Failed to delete session")}}),$.get("/:sessionId/message",async(x)=>{let G=x.req.param("sessionId");try{let Q=await z0(G,x.req.query("projectPath")),K=n.get(h(Q)),N=K?.messages?K.messages:await C.loadSession(Q.sessionId,Q.projectPath);return x.json(o$(N))}catch(Q){if(y.error("[SessionRoutes] Failed to get messages:",Q),Q instanceof _||Q instanceof f||Q instanceof H0)throw Q;throw new a("Failed to get messages")}}),$.get("/:sessionId/events",async(x)=>{let G=x.req.param("sessionId"),Q=await z0(G,x.req.query("projectPath"));try{await C.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(L){if(L instanceof r$)throw new k(L.message);throw L}let K=await Y0(Q),N=x.req.header("Last-Event-ID")??x.req.query("lastEventId"),D=N?Number.parseInt(N,10):Number.NaN,H=Number.isInteger(D)?D+1:void 0;return x2(x,async(L)=>{let b,w,r=!1,F0,j0,w0=new Promise((P)=>{j0=P}),Q0=()=>{if(w!==void 0)clearInterval(w),w=void 0;b?.(),b=void 0},i=(P)=>{if(r)return;r=!0,Q0(),F0?.close(P),j0()},c0=new Set;L.onAbort(i),F0=new K$({write:async(P)=>{await L.writeSSE(P)},onFailure:(P)=>{y.warn(`[SessionRoutes] SSE egress closed for ${Q.sessionId}: kind=${P.kind} pendingItems=${P.pendingItems??0} pendingBytes=${P.pendingBytes??0}`),i(P)}}),b=j.subscribe((P)=>{if(P.sessionId!==Q.sessionId||P.projectPath!==Q.projectPath)return;let S=P.properties.requestId;if((P.type==="permission.asked"||P.type==="question.required"||P.type==="elicitation.required")&&typeof S==="string"){if(c0.has(S))return;c0.add(S)}if(P.type==="subagent.completion.queued")M(Q).runExclusive(()=>J0(K)).catch((R)=>{y.error(`[SessionRoutes] Failed to wake background completion for ${K.id}:`,R)});F0?.observe(D2(P),P.seq)});try{if(L.aborted||r)return;let P=G0(K.currentRunId),S=U0(P)?await W(K):void 0,R=S?.getPendingSteeringCount()??0;if(await F0.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:Q.sessionId,projectPath:Q.projectPath,timestamp:Date.now(),status:U0(P)?P.status:"idle",runId:U0(P)?P.id:void 0,queued:R,pendingInputDelivery:R>0?S?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:S?.getRecoveredSteeringCount()??0}})}),L.aborted||r)return;if(H!==void 0){if(await H4.for(Q.sessionId,Q.projectPath).replay({onCommitted:async(p)=>{if(L.aborted||r)return;let s=B2(p);if(s.seq===void 0)return;await F0.writeReplay({...typeof p.seq==="number"?{id:String(p.seq)}:{},data:JSON.stringify({type:s.type,...s.seq!==void 0?{seq:s.seq}:{},properties:{...s.properties,sessionId:Q.sessionId,projectPath:Q.projectPath}})},s.seq)}},H),L.aborted||r)return}if(F0.finishInitialization({replayed:H!==void 0}),L.aborted||r)return;if(!P&&!q0.has(h(Q))){let p=(await k0.list(Q.projectPath,Q.sessionId)).some((s)=>s.completion===void 0)?await k0.recoverInterrupted(Q.projectPath,Q.sessionId,await W(K)):void 0;if(p)K.messages=await C.loadSession(Q.sessionId,Q.projectPath),await u0(K),j.publish(Q,"review.completed",{reviewId:p.reviewId,status:p.status,findings:0,recovered:!0})}if(L.aborted||r)return;if(!P)await p0.recoverResponded(Q.projectPath,Q.sessionId);if(L.aborted||r)return;let o=P?void 0:await p0.findPending(Q.projectPath,Q.sessionId),Z0=P?.pendingPermission??(o?{permissionId:o.request.requestId,details:p0.confirmationDetails(o),resolve:()=>{return}}:void 0);if(Z0){c0.add(Z0.permissionId);let l=q4(Z0,!0);F0.observe({data:JSON.stringify({type:l.type,properties:{...l.properties,sessionId:Q.sessionId,projectPath:Q.projectPath}})})}if(L.aborted||r)return;if(J0(K).catch((l)=>{y.error(`[SessionRoutes] Failed to resume pending input for ${G}:`,l)}),L.aborted||r)return;w=setInterval(()=>{if(L.aborted||r)return;F0?.offerHeartbeat({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})})},15000),await w0}finally{i()}})}),$.post("/:sessionId/message",async(x)=>{let G=x.req.param("sessionId"),Q=await x.req.json(),K=m(K2,Q);if(!K.success)throw new _("Invalid message format");let{content:N,attachments:D,modelId:H,reasoningEffort:L,serviceTier:A,responseVerbosity:b,communicationStyle:w,permissionMode:r,projectPath:F0,outputSchema:j0}=K.data,w0;if(j0)try{w0=t$(j0).schema}catch(l){throw new _(l instanceof Error?l.message:"Invalid output schema")}let Q0=w,i=H?.trim();if((D??[]).reduce((l,p)=>l+(typeof p.content==="string"?Buffer.byteLength(p.content):0),0)>y$)throw new _("Message attachments exceed the 5 MiB limit");let P=r,S=Q4(N,D),R=await E(G,F0??x.req.query("projectPath")),o=P??R.permissionMode??"default",Z0=x0(R);return M(Z0).runExclusive(async()=>{let l=G0(R.currentRunId);if(U0(l)){if(w0)throw new k("Wait for the active turn to finish before setting an output schema");let c=await W(R);if(i&&!c.getModelById(i))throw new _(`Model not found: ${i}`);if(i&&c.getCurrentModelId()!==i)throw new k("Wait for the active turn to finish before switching models");if(L&&c.getReasoningConfiguration().selection!==L)throw new k("Wait for the active turn to finish before switching reasoning effort");if(A&&c.getServiceTierConfiguration().selection!==A)throw new k("Wait for the active turn to finish before switching service tier");if(b&&c.getResponseVerbosityConfiguration().selection!==b)throw new k("Wait for the active turn to finish before switching response verbosity");if(Q0&&c.getCommunicationStyleConfiguration().selection!==Q0)throw new k("Wait for the active turn to finish before switching communication style");if(P&&R.permissionMode!==P)throw new k("Wait for the active turn to finish before switching permission mode");let M0=await c.enqueueSteering(S,{allowBeforeTurn:!0});if(!M0.accepted)return x.json({status:"rejected",reason:M0.reason??"turn_unavailable"},409);let d$=M0.messageId??$$(12),C1=M0.queued;j.publish(Z0,"message.created",{messageId:d$,role:"user",content:Z1(S)});let IO=M0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(j.publish(Z0,IO,{runId:l.id,messageId:d$,queued:C1}),M0.delivery==="next_turn"&&l.status!=="running"&&l.status!=="waiting_permission")J0(R).catch((PO)=>{y.error(`[SessionRoutes] Failed to wake queued follow-up for ${G}:`,PO)});if(M0.delivery==="next_turn")l.pendingFollowUpRequested=!0;return x.json({runId:l.id,messageId:d$,status:M0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:C1},202)}if(R.permissionMode!==o)await t(R,o);let p=await W(R,{permissionMode:o,...Q0&&!Q0.includes(":")?{communicationStyle:Q0}:{}});if(i&&!p.getModelById(i))throw new _(`Model not found: ${i}`);if(L)try{p.resolveReasoningConfiguration(L,i)}catch(c){throw new _(c instanceof Error?c.message:"Invalid reasoning effort")}if(A)try{p.resolveServiceTierConfiguration(A,i)}catch(c){throw new _(c instanceof Error?c.message:"Invalid service tier")}if(b)try{p.resolveResponseVerbosityConfiguration(b,i)}catch(c){throw new _(c instanceof Error?c.message:"Invalid response verbosity")}let s=Q0?p.resolveCommunicationStyleConfiguration(Q0):void 0;if(s?.source!==void 0&&s.source!=="built-in"&&!s.contentSha256)throw new _("Custom communication style has no provenance");let A0=p.getCurrentModelId(),w1=p.getReasoningConfiguration(),A1=p.getServiceTierConfiguration(),M1=p.getResponseVerbosityConfiguration(),E1=p.getCommunicationStyleConfiguration(),T1=Boolean(i)&&A0!==i,b1=Boolean(L)&&w1.selection!==L,q1=Boolean(A)&&A1.selection!==A,R1=Boolean(b)&&M1.selection!==b,j1=Boolean(Q0)&&E1.selection!==Q0;if(T1||b1||q1||R1||j1)await p.refresh({...i?{modelId:i}:{},...L?{reasoningEffort:L}:{},...A?{serviceTier:A}:{},...b?{responseVerbosity:b}:{},...Q0?{communicationStyle:Q0}:{}});let u$={...i&&R.selectedModelId!==i?{selectedModelId:i}:{},...L&&R.reasoningEffort!==L?{reasoningEffort:L}:{},...A&&R.serviceTier!==A?{serviceTier:A}:{},...b&&R.responseVerbosity!==b?{responseVerbosity:b}:{},...s&&(R.communicationStyle!==Q0||R.communicationStyleDigest!==s.contentSha256)?{communicationStyle:Q0,communicationStyleDigest:s.source==="built-in"?null:s.contentSha256}:{}};if(Object.keys(u$).length>0)try{let c=await C.updateSessionMetadata(R.id,R.projectPath,u$);R.permissionMode=c.permissionMode,R.selectedModelId=c.selectedModelId,R.reasoningEffort=c.reasoningEffort,R.serviceTier=c.serviceTier,R.responseVerbosity=c.responseVerbosity,R.communicationStyle=c.communicationStyle,R.communicationStyleDigest=c.communicationStyleDigest,R.updatedAt=new Date(c.lastMessageTime),j.publish(Z0,"session.updated",u$)}catch(c){if(T1||b1||q1||R1||j1)await p.refresh({...A0?{modelId:A0}:{},reasoningEffort:w1.selection,serviceTier:A1.selection,responseVerbosity:M1.selection,communicationStyle:E1.selection}).catch((M0)=>y.error("[SessionRoutes] Failed to roll back non-durable model settings:",M0));throw c}let z$=w0?await p.prepareInputTurn(S,{outputSchema:w0}):await p.prepareInputTurn(S);if(!z$.accepted)return x.json({status:"rejected",reason:z$.reason},z$.reason==="queue_full"?429:409);let i0=I(R,S,o,{preparedInputTurn:z$,outputSchema:w0,...R.taskIsolation?{taskRuntime:p}:{}});return await i0.taskAdmissionUpdate,x.json({runId:i0.id,messageId:z$.messageId,status:i0.status==="queued"?"queued":"running",queuePosition:i0.taskQueuePosition,queueDepth:i0.taskQueueDepth,maxConcurrentTasks:i0.taskConcurrencyLimit},202)})}),$.post("/:sessionId/shell",async(x)=>{let G=x.req.param("sessionId"),Q=m(T4,await x.req.json());if(!Q.success)throw new _("Invalid user shell command");let K=await E(G,Q.data.projectPath??x.req.query("projectPath")),N=x0(K),D=h(N);return M(N).runExclusive(async()=>{if(v0.has(D))throw new k("A user shell command is already running in this Session");let H=await W(K),L=new AbortController,A,b=new Promise((w)=>{A=w});v0.set(D,{controller:L,completion:b});try{let w=await H.executeUserShellCommand(Q.data.command,{signal:L.signal});K.messages=await C.loadSession(K.id,K.projectPath),K.updatedAt=new Date;let r=G0(K.currentRunId);if(w.delivery==="next_turn"&&U0(r))r.pendingFollowUpRequested=!0;return x.json({executionId:w.executionId,messageId:w.messageId,record:w.record,auxiliary:w.auxiliary,...w.delivery?{delivery:w.delivery}:{},...w.queued!==void 0?{queued:w.queued}:{}})}finally{v0.delete(D),A()}})}),$.post("/:sessionId/abort",async(x)=>{let G=x.req.param("sessionId"),Q=await z0(G,x.req.query("projectPath")),K=n.get(h(Q));if(K?.currentRunId){let H=G0(K.currentRunId);if(H)H$(H),await H.completion}let N=v0.get(h(Q));if(N)N.controller.abort("user-cancel"),await N.completion;let D=q0.get(h(Q));if(D)D.controller.abort("user-cancel"),await D.completion;return x.json({success:!0})}),$.get("/:sessionId/status",async(x)=>{let G=x.req.param("sessionId"),Q=await z0(G,x.req.query("projectPath")),K=n.get(h(Q)),N=q0.get(h(Q));if(N)return x.json({sessionId:G,projectPath:Q.projectPath,reviewId:N.reviewId,status:"reviewing"});if(!K?.currentRunId)return x.json({sessionId:G,projectPath:Q.projectPath,status:"idle"});let D=G0(K.currentRunId);return x.json({sessionId:G,projectPath:Q.projectPath,runId:K.currentRunId,status:D?.status||"idle"})}),{app:$,dispatchTask:v,retryTask:q$,getTaskDiff:X0,deliverTask:R0,recoverQueuedTasks:B1,shutdown:(x="server-shutdown")=>{if(q)return q;return U.close(x),q=(async()=>{let G,Q=async(A)=>{let b=await Promise.allSettled(A);for(let w of b)if(w.status==="rejected")G??=w.reason},K=new Set,N=()=>{for(let A of b0.values()){if(A.completion)K.add(A.completion);if(U0(A))H$(A,x)}for(let A of v0.values())A.controller.abort(x),K.add(A.completion);for(let A of q0.values())A.controller.abort(x),K.add(A.completion)},D=U.waitForIdle(),H=!1;D.then(()=>{H=!0});while(!H)N(),await Promise.race([D,new Promise((A)=>setImmediate(A))]);await D,N(),await Q([...K]),await Q([...J.values()]),N(),await Q([...K]);let L=new Set(O.values());if(O.clear(),await Q([...L].map((A)=>A.dispose())),await Q([...Z.values()]),await Q([N0.getInstance().disconnectAll()]),J.clear(),Z.clear(),Y.clear(),z.clear(),X.clear(),n.clear(),J$===J0)J$=void 0;if(G!==void 0)throw G})(),q}}};async function w2($,O,J,Z,Y,z={}){let{abortController:X,sessionId:U,id:q}=$,B=z.preparedInputTurn?.messageId??$$(12),T=z.pendingInputOnly===!0||z.preparedInputTurn?.mode==="pending"||z.goalContinuationOnly===!0?void 0:$$(12),W,u,Y0=x0(O),E=(I,O0)=>{j.publish(Y0,I,O0)},t=async()=>{let I=String(X.signal.reason||"Task run cancelled");if(O.taskIsolation){let O0=W??await Y(O).catch(()=>{return});if(I==="user-cancel")await O0?.discardPendingInput().catch((m0)=>{y.warn(`[SessionRoutes] Failed to discard cancelled input for ${O.id}:`,m0)});let v=await O0?.setTaskStatus("cancelled",I).catch(()=>{return});if(v)B$(O,v);else await u0(O).catch(()=>{return})}O.taskStatus="cancelled",O.taskStatusReason=I,O.taskCompletedAt??=new Date().toISOString()};try{if(z.taskAdmission){if(await z.taskAdmission.ready,await $.taskAdmissionUpdate,X.signal.aborted)throw Error(String(X.signal.reason||"Task run cancelled"))}if(O.taskStatus="running",O.taskStatusReason=void 0,O.taskStartedAt=new Date().toISOString(),O.taskCompletedAt=void 0,!z.pendingInputOnly&&!z.goalContinuationOnly)E("message.created",{messageId:B,role:"user",content:Z1(J)});if(E("session.status",{status:"running"}),T)E("message.created",{messageId:T,role:"assistant",content:""});W=await Y(O);let I=W,O0=Boolean(z.outputSchema??I.getPendingSteeringMessages().find((V)=>V.outputSchema)?.outputSchema);u=await L4.createWithRuntime(I,{sessionId:U,...O.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let v=async(V)=>{let J0=V.interactionRequestId??$$(12),B1=300000;$.status="waiting_permission";let L1=new Promise((K)=>{let N=setTimeout(()=>{y.warn(`[SessionRoutes] Permission ${J0} timed out after 300000ms`),E("permission.timeout",{requestId:J0}),K({approved:!1,reason:"timeout"})},300000);$.pendingPermission={permissionId:J0,resolve:(D)=>{clearTimeout(N),K(D)},details:V}}),x=$.pendingPermission;if(!x)throw Error("Permission request was not registered");let G=q4(x);E(G.type,G.properties),y.info(`[SessionRoutes] Permission request created: ${J0}, runId: ${q}`);let Q=await L1;if(y.info(`[SessionRoutes] Permission response received: ${J0}, approved: ${Q.approved}`),!X.signal.aborted)$.status="running";if($.pendingPermission===x)$.pendingPermission=void 0;return E("interaction.resolved",{requestId:J0}),Q},q$={messages:await C.loadSessionModelContext(O.id,O.projectPath),userId:"web-user",sessionId:U,workspaceRoot:O.projectPath,signal:X.signal,permissionMode:Z,onPermissionModeChange:async(V)=>{O.permissionMode=V,O.updatedAt=new Date,E("session.updated",{permissionMode:V})},...O.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:v}},X0=()=>{if(!T)T=$$(12),E("message.created",{messageId:T,role:"assistant",content:""});return T},R$=async(V)=>{switch(V.kind){case"content_delta":if(O0)break;E("message.delta",{messageId:X0(),delta:V.delta});break;case"structured_output":E("structured.output",{messageId:X0(),output:V.output,schemaDigest:V.schemaDigest});break;case"thinking_delta":E("thinking.delta",{messageId:X0(),delta:V.delta});break;case"tool_start":if("function"in V.toolCall){if(V.toolCall.function.name===O$)break;E("tool.start",{messageId:X0(),toolName:V.toolCall.function.name,toolCallId:V.toolCall.id,arguments:V.toolCall.function.arguments,toolKind:V.toolKind})}break;case"tool_result":if("function"in V.toolCall){if(V.toolCall.function.name===O$)break;E("tool.result",{messageId:X0(),toolName:V.toolCall.function.name,toolCallId:V.toolCall.id,success:V.result.success,summary:V.result.metadata?.summary,output:M$(w$(A$(V.toolCall.function.name,V.result),L$)),metadata:_$(V.toolCall.function.name,V.result.metadata)})}break;case"tool_progress":if("function"in V.toolCall){if(V.toolCall.function.name===O$)break;E("tool.progress",{messageId:X0(),toolName:V.toolCall.function.name,toolCallId:V.toolCall.id,...V.update})}break;case"token_usage":E("token.usage",{...V.usage});break;case"turn_start":E("turn.started",{turn:V.turn,maxTurns:V.maxTurns});break;case"provider_admission":E("provider.admission",{phase:V.phase,requestClass:V.requestClass,resource:V.resource,scope:V.scope,reason:V.reason,queuePosition:V.queuePosition,queueDepth:V.queueDepth,inFlight:V.inFlight,limit:V.limit,waitMs:V.waitMs,maxWaitMs:V.maxWaitMs,recoveryRemainingMs:V.recoveryRemainingMs});break;case"provider_circuit":E("provider.circuit",{phase:V.phase,reason:V.reason,statusCode:V.statusCode,retryAfterMs:V.retryAfterMs,nextProbeAt:V.nextProbeAt,openDurationMs:V.openDurationMs,sampleCount:V.sampleCount,failureCount:V.failureCount,recoveryRemainingMs:V.recoveryRemainingMs});break;case"provider_retry":E("provider.retry",{phase:V.phase,attempt:V.attempt,maxRetries:V.maxRetries,reason:V.reason,statusCode:V.statusCode,delayMs:V.delayMs,nextRetryAt:V.nextRetryAt,mode:V.mode,recoveryBudgetMs:V.recoveryBudgetMs,recoveryElapsedMs:V.recoveryElapsedMs,recoveryRemainingMs:V.recoveryRemainingMs,exhaustedBy:V.exhaustedBy});break;case"provider_stall":E("provider.stall",{phase:V.phase,stallCount:V.stallCount,durationMs:V.durationMs,warningAfterMs:V.warningAfterMs,timeoutMs:V.timeoutMs,outputStarted:V.outputStarted});break;case"action_stationarity":E("action.stationarity",{phase:V.phase,toolName:V.toolName,runLength:V.runLength,nudgeThreshold:V.nudgeThreshold,haltThreshold:V.haltThreshold,progressAware:V.progressAware});break;case"mcp_catalog_changed":E("mcp.catalog.changed",{messageId:X0(),revision:V.revision,serverName:V.serverName,added:V.added,removed:V.removed,updated:V.updated});break;case"mcp_content_changed":E("mcp.content.changed",{messageId:X0(),revision:V.revision,serverName:V.serverName,contentKind:V.contentKind,added:V.added,removed:V.removed,updated:V.updated});break;case"mcp_resource_updated":E("mcp.resource.updated",{messageId:X0(),revision:V.revision,serverName:V.serverName,uri:V.uri});break;case"mcp_connection_changed":E("mcp.connection.changed",{messageId:X0(),revision:V.revision,serverName:V.serverName,phase:V.phase,reason:V.reason,attempt:V.attempt,maxAttempts:V.maxAttempts,nextRetryAt:V.nextRetryAt,error:V.error});break;case"mcp_log":E("mcp.log",{messageId:X0(),revision:V.revision,serverName:V.serverName,level:V.level,logger:V.logger,message:V.message,projectedBytes:V.projectedBytes,dataSha256:V.dataSha256,truncated:V.truncated,detailsOmitted:V.detailsOmitted,timestamp:V.timestamp,synthetic:V.synthetic});break;case"mcp_instructions_changed":E("mcp.instructions.changed",{messageId:X0(),revision:V.revision,serverName:V.serverName,action:V.action,reason:V.reason,text:V.text,sourceBytes:V.sourceBytes,projectedBytes:V.projectedBytes,sha256:V.sha256,truncated:V.truncated,detailsOmitted:V.detailsOmitted});break;case"mcp_task_changed":E("mcp.task.changed",{messageId:X0(),revision:V.revision,taskId:V.taskId,serverName:V.serverName,toolName:V.toolName,status:V.status,statusMessage:V.statusMessage,createdAt:V.createdAt,updatedAt:V.updatedAt,completedAt:V.completedAt,hasResult:V.hasResult,error:V.error});break;case"project_rules_loaded":E("project.rules.loaded",{messageId:X0(),files:V.files,triggerPaths:V.triggerPaths,blockedWrite:V.blockedWrite});break;case"steering_applied":E("steering.applied",{runId:q,messageIds:V.messageIds,count:V.count,recovered:V.recovered,delivery:V.delivery,queued:I.getPendingSteeringCount()});break;case"follow_up_started":{if(T)E("message.complete",{messageId:T}),T=void 0;for(let J0 of V.messages){if(!J0.recovered||J0.persisted)continue;E("message.created",{messageId:J0.id,role:"user",content:Z1(J0.content),recovered:!0})}E("follow_up.started",{runId:q,queued:V.queued,recovered:V.recovered}),X0();break}case"goal_updated":E("goal.updated",{goal:V.goal});break;case"goal_continuation_started":E("goal.continuation.started",{goal:V.goal,continuation:V.continuation}),X0();break;case"compaction":E(V.phase==="start"?"compaction.started":"compaction.completed",{...V.reason?{reason:V.reason}:{},...V.strategy?{strategy:V.strategy}:{},...V.outcome?{outcome:V.outcome}:{},...V.preTokens!==void 0?{preTokens:V.preTokens}:{},...V.postTokens!==void 0?{postTokens:V.postTokens}:{}});break;case"model_fallback":E("model.fallback",{});break;case"task_update":E("task.updated",{tasks:V.tasks});break;default:break}},R0=await e$(u.chatStream(J,q$,{stream:!0,pendingInputOnly:z.pendingInputOnly,preparedInputTurn:z.preparedInputTurn,goalContinuationOnly:z.goalContinuationOnly,outputSchema:z.outputSchema,taskAdmission:z.taskAdmission}),R$);if(!R0.success)throw Error(R0.error?.message??"Agent run failed");for(let V=0;V<20;V++){let J0=$.pendingFollowUpRequested===!0;if($.pendingFollowUpRequested=!1,I.getPendingSteeringCount()===0){if(!J0)break;continue}if(X.signal.aborted)break;if(R0=await e$(u.chatStream("",q$,{stream:!0,pendingInputOnly:!0,taskAdmission:z.taskAdmission}),R$),!R0.success)throw Error(R0.error?.message??"Agent follow-up failed")}if(O.messages=await C.loadSession(O.id,O.projectPath),O.updatedAt=new Date,await u0(O),X.signal.aborted||$.status==="cancelled"){await t(),E("session.status",{status:"idle"});return}if(T)E("message.complete",{messageId:T});E("thinking.completed",{}),$.status="completed",O.taskStatus="completed",O.taskCompletedAt??=new Date().toISOString(),E("session.completed",{runId:q,outputTruncated:R0.metadata?.outputTruncated??!1}),E("session.status",{status:"idle"})}catch(I){if(W&&z.preparedInputTurn)await W.finishTurn(z.preparedInputTurn.handle).catch(()=>{return});if(X.signal.aborted||$.status==="cancelled"){H$($,"runtime-abort"),await t(),E("session.status",{status:"idle"});return}await u0(O).catch(()=>{return}),y.error("[SessionRoutes] Agent execution error:",I),$.status="failed",O.taskStatus="failed",O.taskCompletedAt??=new Date().toISOString();let O0=f$(I);if(!O.taskFailure){let v=W?await W.setTaskStatus("failed",I).catch(()=>{return}):await C.updateSessionMetadata(O.id,O.projectPath,{taskStatus:"failed",taskStatusReason:O0.message,taskFailure:O0,taskCompletedAt:O.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(v)B$(O,v)}O.taskStatusReason??=O0.message,O.taskFailure??=O0,E("session.error",{error:O.taskFailure.message,taskFailure:O.taskFailure}),E("session.status",{status:"error"})}finally{if(z.taskAdmission?.release(),z.taskAdmission){let I=r0.getStats();E("task.status",{taskStatus:O.taskStatus,...O.taskStatusReason?{taskStatusReason:O.taskStatusReason}:{},...O.taskFailure?{taskFailure:O.taskFailure}:{},...O.taskStartedAt?{taskStartedAt:O.taskStartedAt}:{},...O.taskCompletedAt?{taskCompletedAt:O.taskCompletedAt}:{},...O.taskDiffStat?{taskDiffStat:O.taskDiffStat}:{},taskQueueDepth:I.queued,taskConcurrencyLimit:I.maxConcurrent,taskInFlight:I.inFlight,updatedAt:new Date().toISOString()})}if(await u?.destroy().catch(()=>{return}),$.disposeRuntimeOnSettle&&z.disposeRuntime)await z.disposeRuntime(O,W).catch((I)=>{y.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${O.id}:`,I)});U2($)}}async function j4($,O,J){y.info(`[SessionRoutes] Looking for permission ${O} in session ${$.sessionId}`),y.info(`[SessionRoutes] Active runs: ${b0.size}`);for(let[z,X]of b0.entries())if(y.info(`[SessionRoutes] Checking run ${z}: sessionId=${X.sessionId}, projectPath=${X.projectPath}, pendingPermission=${X.pendingPermission?.permissionId}`),X.sessionId===$.sessionId&&X.projectPath===$.projectPath&&X.pendingPermission?.permissionId===O){if(X.pendingPermission.details.interactionRequestId)await p0.respond($.projectPath,$.sessionId,O,J);return X.pendingPermission.resolve(J),y.info(`[SessionRoutes] Permission ${O} responded, runId: ${X.id}`),!0}let Z=await p0.findPending($.projectPath,$.sessionId);if(!Z||Z.request.requestId!==O)return y.error(`[SessionRoutes] Permission not found: ${O}`),!1;await p0.respondAndRecover($.projectPath,$.sessionId,O,J);let Y=n.get(h($));if(!Y){let z=await C.findSessionMetadata($.sessionId,$.projectPath);if(!z)return!1;let[X,U]=await Promise.all([C.loadSession($.sessionId,$.projectPath),C.findSessionTaskWorktree($.sessionId,$.projectPath)]);Y=D$(z,X,U),n.set(h($),Y)}else await u0(Y);if(j.publish($,"interaction.resolved",{requestId:O}),J$)J$(Y).catch((z)=>{y.error(`[SessionRoutes] Failed to resume recovered interaction ${O}:`,z)});return!0}var Q1=d("Service"),M2=F.Object({approved:F.Boolean(),remember:F.Optional(F.Boolean()),scope:F.Optional(V0(["once","session","project"])),targetMode:F.Optional(V0(["default","autoEdit","plan","yolo"])),feedback:F.Optional(F.String({maxLength:4000})),answers:F.Optional(F.Record(F.String({maxLength:80}),F.Union([F.String({maxLength:4000}),F.Array(F.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:F.Optional(F.Object({action:V0(["accept","decline","cancel"]),content:F.Optional(F.Record(F.String(),F.Union([F.String({maxLength:4000}),F.Number(),F.Boolean(),F.Array(F.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),C4=()=>{let $=new A2;return $.post("/:permissionId",async(O)=>{let J=O.req.param("permissionId"),Z=O.req.query("sessionId"),Y=O.req.query("projectPath");Q1.info(`[PermissionRoutes] Received permission response: permissionId=${J}, sessionId=${Z}`);try{let z=await O.req.json(),X=m(M2,z);if(!X.success)throw new _("Invalid permission response format");let{approved:U,remember:q,scope:B,targetMode:M,feedback:T,answers:W,elicitation:u}=X.data;if(!Z)throw new _("sessionId query parameter is required");let Y0=await z0(Z,Y);if(!await j4(Y0,J,{approved:U,reason:T,scope:B,targetMode:M,feedback:T,answers:W,elicitation:u}))throw new f("Permission request",J);return Q1.info(`[PermissionRoutes] Permission ${J} ${U?"approved":"denied"}`),O.json({success:!0,approved:U,remember:q})}catch(z){if(Q1.error("[PermissionRoutes] Failed to respond to permission:",z),z instanceof _||z instanceof H0||z instanceof f||z instanceof e)throw z;throw z}}),$};import k4 from"node:path";import{Hono as E2}from"hono";var T2=F.Object({projectPath:F.String({minLength:1}),enabled:F.Boolean(),scope:F.Optional(V0(["local","project","global"]))}),b2=F.Object({projectPath:F.String({minLength:1})}),q2=F.Object({projectPath:F.String({minLength:1}),source:F.String({minLength:1}),trust:F.Literal(!0),ref:F.Optional(F.String({minLength:1}))}),R2=F.Object({projectPath:F.String({minLength:1}),trust:F.Literal(!0)}),j2=F.Object({projectPath:F.String({minLength:1}),confirm:F.Literal(!0)}),C2=F.Object({projectPath:F.String({minLength:1}),source:F.String({minLength:1}),ref:F.Optional(F.String({minLength:1}))}),I4=F.Object({projectPath:F.String({minLength:1}),confirm:F.Optional(F.Literal(!0))}),k2=F.Object({projectPath:F.String({minLength:1}),scope:F.Optional(V0(["local","project","global"])),policy:F.Object({restrictToAllowedSources:F.Boolean(),requireGitCommitSha:F.Boolean(),allowedGitHosts:F.Array(F.String()),allowedMarketplaces:F.Array(F.String()),allowedLocalRoots:F.Array(F.String())})});function B0($){if(!$||!k4.isAbsolute($))throw new _("projectPath must be absolute");return k4.resolve($)}async function P4($){let[O,J]=await Promise.all([W0($),N$.getInstance().loadWorkspacePluginSettingsResolution($)]);return O.plugins.getAll().map((Z)=>({name:Z.manifest.name,description:Z.manifest.description,version:Z.manifest.version,source:Z.source,enabled:Z.status==="active",status:Z.status,commands:Z.commands.length,skills:Z.skills.length,agents:Z.agents.length,hooks:Z.hooks?Object.values(Z.hooks).reduce((Y,z)=>Y+(Array.isArray(z)?z.length:0),0):0,mcpServers:Object.keys(Z.mcpServers??{}).length,configurable:Z.source!=="cli",managed:Z.installation!==void 0,marketplace:Z.installation?.source.type==="marketplace"?Z.installation.source.marketplace:void 0,revision:Z.installation?.revision,installedAt:Z.installation?.installedAt,updatedAt:Z.installation?.updatedAt,compatibilityIssues:Z.compatibilityIssues??[],effectiveScope:Z.source==="cli"?"invocation":J.settings[Z.manifest.name]?.effectiveScope??"default",settingLayers:Z.source==="cli"?{invocation:!0}:J.settings[Z.manifest.name]?.layers??{}}))}async function I2(){let $=S4(),[O,J]=await Promise.all([$.listCatalogs(),$.listInstallationRecords()]),Z=new Map(J.map((Y)=>[Y.name,Y]));return O.map(({marketplace:Y,manifest:z})=>({name:Y.name,description:z.description??z.metadata?.description??"",sourceType:Y.source.type,revision:Y.revision,updatedAt:Y.updatedAt,plugins:z.plugins.map((X)=>{let U=Z.get(X.name);return{name:X.name,description:X.description??"",version:X.version,category:X.category,tags:X.tags??[],installed:U!==void 0,installedVersion:U?.version}})}))}function Z$($,O){if(!$.success)throw new _($.error??O)}var l4=()=>{let $=new E2;return $.get("/",async(O)=>{let J=B0(O.req.query("projectPath"));return O.json(await P4(J))}),$.post("/refresh",async(O)=>{let J=m(b2,await O.req.json());if(!J.success)throw new _("Invalid plugin refresh request");let Z=B0(J.data.projectPath),Y=await y4(Z);return O.json({plugins:await P4(Z),errors:Y.discovery.errors.map((z)=>({code:z.code??"LOAD_ERROR",error:z.error}))})}),$.get("/catalog",async(O)=>{return B0(O.req.query("projectPath")),O.json(await I2())}),$.get("/policy",async(O)=>{let J=B0(O.req.query("projectPath")),Z=await N$.getInstance().loadWorkspacePluginSourcePolicy(J);return O.json({policy:Z,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),$.post("/policy",async(O)=>{let J=m(k2,await O.req.json());if(!J.success)throw new _("Invalid plugin source policy request");let Z=B0(J.data.projectPath),Y=await m4(Z,J.data.policy,J.data.scope??"global");return O.json({policy:Y})}),$.post("/install",async(O)=>{let J=m(q2,await O.req.json());if(!J.success)throw new _("Invalid plugin install request; explicit source trust is required");let Z=B0(J.data.projectPath),{result:Y}=await h4(Z,J.data.source,{trusted:J.data.trust,ref:J.data.ref});return Z$(Y,"Plugin installation failed"),O.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,installedDependencies:Y.installedDependencies??[]})}),$.post("/marketplaces",async(O)=>{let J=m(C2,await O.req.json());if(!J.success)throw new _("Invalid marketplace add request");let Z=B0(J.data.projectPath),Y=await p4(Z,J.data.source,J.data.ref);return Z$(Y,"Marketplace installation failed"),O.json({name:Y.marketplace?.name,plugins:Y.manifest?.plugins.length??0,revision:Y.marketplace?.revision,changed:Y.changed})}),$.post("/marketplaces/:name/refresh",async(O)=>{let J=m(I4,await O.req.json());if(!J.success)throw new _("Invalid marketplace refresh request");let Z=await u4(B0(J.data.projectPath),O.req.param("name"));return Z$(Z,"Marketplace refresh failed"),O.json({name:Z.marketplace?.name,plugins:Z.manifest?.plugins.length??0,revision:Z.marketplace?.revision,changed:Z.changed})}),$.post("/marketplaces/:name/remove",async(O)=>{let J=m(I4,await O.req.json());if(!J.success||J.data.confirm!==!0)throw new _("Invalid marketplace removal request; explicit confirmation is required");B0(J.data.projectPath);let Z=await d4(O.req.param("name"),!0);return Z$(Z,"Marketplace removal failed"),O.json({name:Z.marketplace?.name,removed:!0})}),$.post("/:name/update",async(O)=>{let J=m(R2,await O.req.json());if(!J.success)throw new _("Invalid plugin update request; explicit source trust is required");let Z=B0(J.data.projectPath),{result:Y}=await g4(Z,O.req.param("name"),{trusted:J.data.trust});return Z$(Y,"Plugin update failed"),O.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,updatedDependencies:Y.updatedDependencies??[]})}),$.post("/:name/uninstall",async(O)=>{let J=m(j2,await O.req.json());if(!J.success)throw new _("Invalid plugin uninstall request; explicit confirmation is required");let Z=B0(J.data.projectPath),{result:Y}=await v4(Z,O.req.param("name"),J.data.confirm);return Z$(Y,"Plugin uninstall failed"),O.json({name:Y.pluginName,removed:!0})}),$.post("/:name/state",async(O)=>{let J=m(T2,await O.req.json());if(!J.success)throw new _("Invalid plugin state request");let Z=B0(J.data.projectPath),Y=O.req.param("name"),X=(await W0(Z)).plugins.get(Y);if(!X)throw new f("Plugin",Y);if(X.source==="cli")throw new _(`Plugin "${Y}" was loaded with --plugin-dir and is invocation-scoped`);let U=await f4(Z,Y,J.data.enabled,J.data.scope??"local");return O.json(U)}),$};import{Hono as m2}from"hono";import{execFile as P2}from"node:child_process";import S2 from"node:path";var z1="__BLADE_DIRECTORY_PICKER_CANCELLED__",f2=900000;function y2($,O){return new Promise((J)=>{P2($,[...O],{timeout:f2,maxBuffer:65536,windowsHide:!0},(Z,Y,z)=>{let X=Z?.code;J({stdout:Y,stderr:z,exitCode:typeof X==="number"?X:Z?1:0,...typeof X==="string"?{errorCode:X}:{}})})})}function x1($){let O=$.replace(/[\r\n]+$/,"");if(!O||O===z1)return{cancelled:!0};if(!S2.isAbsolute(O))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:O}}function X1($){return $.exitCode!==0||Boolean($.errorCode)}class c4{platform;runCommand;activeSelection=null;constructor($={}){this.platform=$.platform??process.platform,this.runCommand=$.runCommand??y2}pick(){if(this.activeSelection)return this.activeSelection;let $=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=$,$}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 $=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${z1}"`,"end try"].join(`
8
- `),O=await this.runCommand("osascript",["-e",$]);if(X1(O))throw Error("Unable to open the macOS folder picker");return x1(O.stdout)}async pickOnWindows(){let $=["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("${z1}")`,"}"].join("; "),O=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",$]);if(X1(O))throw Error("Unable to open the Windows folder picker");return x1(O.stdout)}async pickOnLinux(){let $=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let O of $){let J=await this.runCommand(O.command,O.args);if(J.errorCode==="ENOENT")continue;if(J.exitCode===1&&!J.stdout.trim()&&!J.stderr.trim())return{cancelled:!0};if(X1(J))throw Error("Unable to open the Linux folder picker");return x1(J.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var i4=new c4;var h2=F.Object({path:F.String({minLength:1})});function g2($){if(!$)return!1;if($==="tauri://localhost"||$==="http://tauri.localhost")return!0;try{let O=new URL($).hostname;return O==="localhost"||O==="127.0.0.1"||O==="::1"||O==="[::1]"}catch{return!1}}var a4=($={})=>{let O=new m2,J=$.pickDirectory??(()=>i4.pick()),Z=$.allowDirectoryPickerRequest??g2;return O.get("/",async(Y)=>{return Y.json(await h$.list(g()))}),O.post("/",async(Y)=>{let z;try{z=await Y.req.json()}catch{throw new _("A valid JSON body is required")}let X=m(h2,z);if(!X.success)throw new _("A project path is required");try{let U=await h$.bind(X.data.path,g());return Y.json(U,201)}catch(U){throw new _(U instanceof Error?U.message:"Failed to bind project")}}),O.post("/pick",async(Y)=>{if(!Z(Y.req.header("Origin")))throw new e("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Y.json(await J())}catch(z){throw new _(z instanceof Error?z.message:"Failed to select a folder")}}),O.delete("/",async(Y)=>{let z=Y.req.query("path");if(!z)throw new _("A project path is required");try{let X=await h$.unbind(z);return Y.json({success:!0,removed:X})}catch(X){throw new _(X instanceof Error?X.message:"Failed to unbind project")}}),O};import{Hono as v2}from"hono";var o4=d("Service"),s4=()=>{let $=new v2;return $.get("/",async(O)=>{try{let J=await t4();return O.json(J)}catch(J){return o4.error("[ProviderRoutes] Failed to list providers:",J),O.json([])}}),$.get("/:provider/models",async(O)=>{let J=O.req.param("provider");try{let Z=await r4(J);return O.json(Z)}catch(Z){return o4.error("[ProviderRoutes] Failed to list models:",Z),O.json([])}}),$.put("/:provider/credential",async(O)=>{let J=O.req.param("provider"),Z=await O.req.json();if(!Z.apiKey?.trim())throw new _("apiKey is required");return await g0().setApiKey(J,Z.apiKey.trim()),O.json({success:!0})}),$.delete("/:provider/credential",async(O)=>{return await g0().clearCredential(O.req.param("provider")),O.json({success:!0})}),$.put("/:provider",async(O)=>{let J=O.req.param("provider"),Z=$0(),Y=Z?.modelProviders[J];if(!Z||!Y)throw new f("Model provider",J);let z=await O.req.json();if(!z.name||!z.baseUrl||!z.wireApi)throw new _("name, baseUrl and wireApi are required");let X="apiKeyEnv"in z?z.apiKeyEnv?.trim():Y.apiKeyEnv,U={name:z.name,baseUrl:z.baseUrl,wireApi:z.wireApi,...X?{apiKeyEnv:X}:{}},q=g0(),B=z.apiKey?.trim()?await q.credentials.read(J):void 0;if(z.apiKey?.trim())await q.setApiKey(J,z.apiKey.trim());try{return await _0().updateModelProvider(J,U),O.json({success:!0})}catch(M){if(z.apiKey?.trim())if(B)await q.credentials.modify(J,async()=>B);else await q.credentials.delete(J);if(M instanceof Error&&(M.message.includes("modelProviders.")||M.message.includes("built-in provider")))throw new _(M.message);throw M}}),$.delete("/:provider",async(O)=>{let J=O.req.param("provider");if(!$0()?.modelProviders[J])throw new f("Model provider",J);let Y=O.req.query("removeModels");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new _("removeModels must be true or false");try{let z=await _0().removeModelProvider(J,{removeModels:Y==="true"});return O.json({success:!0,...z})}catch(z){if(z instanceof Error&&(z.message.includes("still referenced")||z.message.includes("owns the only model")))throw new k(z.message);throw z}}),$.post("/:provider/probe",async(O)=>{let J=O.req.param("provider"),Z=$0();if(!Z?.modelProviders[J])throw new f("Model provider",J);let Y=await O.req.json().catch(()=>({})),z=Z.models.filter((U)=>U.provider===J),X=Y.modelId?z.find((U)=>U.id===Y.modelId):z[0];if(!X)throw new _(Y.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return O.json(await n4(X,Z))}),$};import{Hono as p2}from"hono";var u2=d("Service"),JO=($,O)=>{let J=new p2;return J.onError((Z,Y)=>{if(Z instanceof e)return Y.json(Z.toObject(),Z.statusCode);return u2.error("[ScheduleRoutes] Unhandled route error:",Z),Y.json(new a("Schedule request failed").toObject(),500)}),J.get("/",async(Z)=>{let Y=await $.list();return Z.json(OO.parse({schedules:Y}))}),J.post("/",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let z=m(e4,Y);if(!z.success)throw new _("Invalid schedule request");let X=z.data.projectPath||Z.get("directory")||g();try{let U=await $.create({...z.data,projectPath:X});return Z.json(d0.parse(U),201)}catch(U){throw new _(U instanceof Error?U.message:"Failed to create schedule")}}),J.get("/:id",async(Z)=>{let Y=await $.get(Z.req.param("id"));if(!Y)throw new f("Schedule not found");return Z.json(d0.parse(Y))}),J.patch("/:id",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let z=m($O,Y);if(!z.success)throw new _("Invalid schedule update");let{modelId:X,reasoningEffort:U,serviceTier:q,responseVerbosity:B,communicationStyle:M,isolation:T,permissionMode:W,...u}=z.data,Y0={...X!==void 0?{modelId:X}:{},...U!==void 0?{reasoningEffort:U}:{},...q!==void 0?{serviceTier:q}:{},...B!==void 0?{responseVerbosity:B}:{},...M!==void 0?{communicationStyle:M}:{},...T!==void 0?{isolation:T}:{},...W!==void 0?{permissionMode:W}:{}};try{let E=await $.update(Z.req.param("id"),{...u,...Object.keys(Y0).length>0?{dispatch:Y0}:{}});if(!E)throw new f("Schedule not found");return Z.json(d0.parse(E))}catch(E){if(E instanceof e)throw E;throw new _(E instanceof Error?E.message:"Failed to update schedule")}}),J.delete("/:id",async(Z)=>{if(!await $.remove(Z.req.param("id")))throw new f("Schedule not found");return Z.json({ok:!0})}),J.post("/:id/enable",async(Z)=>{let Y=await $.setEnabled(Z.req.param("id"),!0);if(!Y)throw new f("Schedule not found");return Z.json(d0.parse(Y))}),J.post("/:id/disable",async(Z)=>{let Y=await $.setEnabled(Z.req.param("id"),!1);if(!Y)throw new f("Schedule not found");return Z.json(d0.parse(Y))}),J.post("/:id/run",async(Z)=>{let Y=await $.get(Z.req.param("id"));if(!Y)throw new f("Schedule not found");if(!O)throw new a("Scheduler is not running in this process");await O.fire(Y,new Date,{manual:!0});let z=await $.get(Y.id);return Z.json(d0.parse(z??Y),202)}),J};import*as S0 from"node:fs/promises";import{homedir as xO}from"node:os";import*as L0 from"node:path";import{Hono as d2}from"hono";var l0=d("Service"),ZO=L0.join(xO(),".blade","skills"),K1=L0.join(xO(),".blade","skills-config.json");async function XO(){try{let $=await S0.readFile(K1,"utf-8");return JSON.parse($)}catch{return{disabled:[]}}}async function l2($){await S0.mkdir(L0.dirname(K1),{recursive:!0}),await S0.writeFile(K1,JSON.stringify($,null,2))}async function c2($,O){let J=await XO();if(O)J.disabled=J.disabled.filter((Z)=>Z!==$);else if(!J.disabled.includes($))J.disabled.push($);await l2(J)}var P0=null,i2=300000,a2=6;async function o2(){if(P0&&Date.now()-P0.timestamp<i2)return P0.data;try{let $=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!$.ok){if(l0.warn(`GitHub API returned ${$.status}`),P0)return P0.data;throw Error(`GitHub skills catalog returned ${$.status}`)}let J=(await $.json()).filter((X)=>X.type==="dir"),Z=Array(J.length),Y=0,z=Math.min(a2,J.length);return await Promise.all(Array.from({length:z},async()=>{while(Y<J.length){let X=Y++,U=J[X];if(!U)continue;let q=`Official ${U.name} skill`;try{let B=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${U.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(B.ok){let T=(await B.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(T)q=T[1].trim().slice(0,100)}}catch{}Z[X]={name:U.name,description:q,tag:"Official",author:"Anthropic"}}})),P0={data:Z,timestamp:Date.now()},Z}catch($){if(l0.warn("Failed to fetch skills catalog from GitHub:",$),P0)return P0.data;throw $}}var zO=()=>{let $=new d2;return $.get("/",async(O)=>{try{let J=O.get("directory")||g(),Y=(await W0(J)).skills.getAll(),z=await XO(),X=Y.map((U)=>({id:U.name,name:U.name,enabled:!z.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"&&L0.dirname(L0.resolve(U.basePath))===L0.resolve(ZO),capabilities:["prompts"],allowedTools:U.allowedTools||[]}));return O.json(X)}catch(J){return l0.error("[SkillsRoutes] Failed to get skills:",J),O.json({error:J instanceof Error?J.message:"Failed to get skills"},500)}}),$.post("/:name/toggle",async(O)=>{try{let J=O.req.param("name"),Z=await O.req.json();return await c2(J,Z.enabled),O.json({success:!0,enabled:Z.enabled})}catch(J){return l0.error("[SkillsRoutes] Failed to toggle skill:",J),O.json({success:!1,error:J.message},500)}}),$.delete("/:name",async(O)=>{try{let J=O.req.param("name"),Z=O.get("directory")||g(),Y=(await W0(Z)).skills,z=Y.get(J);if(!z)return O.json({success:!1,error:"Skill not found"},404);let X=L0.resolve(z.basePath),U=L0.resolve(ZO);if(z.source!=="user"||L0.dirname(X)!==U)return O.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await S0.rm(X,{recursive:!0,force:!0}),await Y.refresh(),W$(Z),await G$(Z),O.json({success:!0})}catch(J){return l0.error("[SkillsRoutes] Failed to uninstall skill:",J),O.json({success:!1,error:J.message},500)}}),$.post("/install",async(O)=>{try{let J=await O.req.json(),Z=YO(),Y=O.get("directory")||g(),z=QO({cwd:Y}),X=!1;if(J.source==="catalog"&&J.name){if(X=await Z.installOfficialSkill(J.name),!X)return O.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(J.source==="repo"&&J.url){if(X=await Z.installFromRepo(J.url,J.name),!X)return O.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(J.source==="local"&&J.path){if(X=await Z.installFromLocal(J.path,J.name),!X)return O.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 O.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await z.refresh(),W$(Y),await G$(Y),O.json({success:!0})}catch(J){return l0.error("[SkillsRoutes] Failed to install skill:",J),O.json({success:!1,error:J.message},500)}}),$.get("/catalog",async(O)=>{try{let J=await o2();return O.json(J)}catch(J){return l0.error("[SkillsRoutes] Failed to get catalog:",J),O.json({error:J instanceof Error?J.message:"Failed to get skills catalog"},502)}}),$};import{execSync as n2}from"node:child_process";import{readdir as t2}from"node:fs/promises";import g$ from"node:path";import r2 from"fast-glob";import{Hono as s2}from"hono";var E$=d("Service"),e2=($)=>{try{return n2("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},$5=[...Y$.map(($)=>`${$}/**`),...Y$,...Y$.map(($)=>`**/${$}/**`),...Y$.map(($)=>`**/${$}`),...V1.map(($)=>`**/${$}`)],O5=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),NO=()=>{let $=new s2;return $.get("/commands",async(O)=>{try{let J=O.req.query("q")||"",Z=O.get("directory")||g();await W0(Z);let Y=VO(J,Z).filter((z)=>!O5.has(z.command));return O.json(Y)}catch(J){return E$.error("[SuggestionsRoutes] Failed to get command suggestions:",J),O.json([])}}),$.get("/files",async(O)=>{try{let J=O.req.query("q")||"",Z=O.get("directory")||g(),Y=Math.min(Number(O.req.query("limit"))||100,1000),z=O.req.query("type")==="file",U=(await r2("**/*",{cwd:Z,dot:!1,followSymbolicLinks:!1,onlyFiles:z,markDirectories:!0,unique:!0,ignore:$5})).map((M)=>M.replace(/\\/g,"/"));if(!J)return O.json(U.slice(0,Y));let q=J.toLowerCase(),B=U.filter((M)=>M.toLowerCase().includes(q)).slice(0,Y);return O.json(B)}catch(J){return E$.error("[SuggestionsRoutes] Failed to get file suggestions:",J),O.json([])}}),$.get("/files/tree",async(O)=>{try{let J=O.get("directory")||g(),Z=O.req.query("path")||"",Y=Z?g$.join(J,Z):J,X=(await t2(Y,{withFileTypes:!0})).map((B)=>({name:B.name,path:Z?`${Z}/${B.name}`:B.name,type:B.isDirectory()?"dir":"file"}));X.sort((B,M)=>{if(B.type!==M.type)return B.type==="dir"?-1:1;return B.name.localeCompare(M.name)});let U=new Set(Y$),q=X.filter((B)=>{let M=B.name;if(M.startsWith("."))return!1;if(U.has(M))return!1;for(let T of V1)if(M.match(new RegExp(T.replace("*",".*"))))return!1;return!0});return O.json(q)}catch(J){return E$.error("[SuggestionsRoutes] Failed to get file tree:",J),O.json([])}}),$.get("/files/content",async(O)=>{try{let J=O.req.query("path");if(!J)return O.json({error:"Missing file path"},400);let Z=O.get("directory")||g(),Y=g$.resolve(Z,J),z=g$.relative(Z,Y);if(z.startsWith("..")||g$.isAbsolute(z))return O.json({error:"Invalid file path"},400);let X=KO(),U=await X.stat(Y);if(!U?.isFile)return O.json({error:"File not found"},404);let q=200000,B=await X.readTextFile(Y),M=B.length>q;return O.json({path:J,content:M?B.slice(0,q):B,truncated:M,size:U.size})}catch(J){return E$.error("[SuggestionsRoutes] Failed to get file content:",J),O.json({error:"Failed to read file"},500)}}),$.get("/git-info",async(O)=>{try{let J=O.get("directory")||g(),Z=e2(J);return O.json({branch:Z})}catch(J){return E$.error("[SuggestionsRoutes] Failed to get git info:",J),O.json({branch:null})}}),$};import{Hono as J5}from"hono";var T$=d("Service"),DO=($)=>{let O=new J5;return O.onError((J,Z)=>{if(J instanceof e)return Z.json(J.toObject(),J.statusCode);return T$.error("[TaskRoutes] Unhandled route error:",J),Z.json(new a("Failed to dispatch task").toObject(),500)}),O.post("/",async(J)=>{let Z;try{Z=await J.req.json()}catch{throw new _("Invalid request body")}let Y=m(UO,Z);if(!Y.success)throw new _("Invalid task request");if((Y.data.attachments??[]).reduce((X,U)=>X+(typeof U.content==="string"?Buffer.byteLength(U.content):0),0)>y$)throw new _("Task attachments exceed the 5 MiB limit");try{let X=await $.dispatchTask({prompt:Y.data.prompt,title:Y.data.title,sourceProjectPath:Y.data.projectPath||J.get("directory")||g(),isolation:Y.data.isolation,permissionMode:Y.data.permissionMode,modelId:Y.data.modelId,reasoningEffort:Y.data.reasoningEffort,serviceTier:Y.data.serviceTier,responseVerbosity:Y.data.responseVerbosity,communicationStyle:Y.data.communicationStyle,attachments:Y.data.attachments,outputSchema:Y.data.outputSchema});return J.json(N1.parse(X),202)}catch(X){if(X instanceof _||X instanceof k||X instanceof h0||X instanceof o0)throw X;throw T$.error("[TaskRoutes] Failed to dispatch task:",X),new a("Failed to dispatch task")}}),O.post("/:sessionId/retry",async(J)=>{try{let Z=await $.retryTask(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(N1.parse(Z),202)}catch(Z){if(Z instanceof _||Z instanceof f||Z instanceof k||Z instanceof h0||Z instanceof o0)throw Z;throw T$.error("[TaskRoutes] Failed to retry task:",Z),new a("Failed to retry task")}}),O.get("/:sessionId/diff",async(J)=>{try{let Z=await $.getTaskDiff(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(GO.parse(Z))}catch(Z){if(Z instanceof _||Z instanceof f||Z instanceof k)throw Z;throw T$.error("[TaskRoutes] Failed to load task diff:",Z),new a("Failed to load task diff")}}),O.post("/:sessionId/delivery",async(J)=>{let Z;try{Z=await J.req.json()}catch{throw new _("Invalid request body")}let Y=m(FO,Z);if(!Y.success)throw new _("Invalid task delivery request");try{let z=await $.deliverTask(J.req.param("sessionId"),Y.data.action,J.req.query("projectPath"));return J.json(WO.parse(z))}catch(z){if(z instanceof _||z instanceof f||z instanceof k)throw z;throw T$.error("[TaskRoutes] Failed to deliver task:",z),new a("Failed to deliver task")}}),O};import{Hono as Z5}from"hono";var f0=d("Service"),Q$=new Map,HO=2097152,_O=65536;function BO(){return typeof globalThis.Bun<"u"}async function Y5($,O,J){if(BO()){let{spawn:z}=await import("bun-pty"),X=z($,O,{name:"xterm-256color",cwd:J.cwd,env:J.env});return{pid:X.pid,write:(U)=>X.write(U),resize:(U,q)=>X.resize(U,q),kill:()=>X.kill(),onData:(U)=>X.onData(U),onExit:(U)=>X.onExit(U)}}let Y=(await import("node-pty")).spawn($,O,{name:"xterm-256color",cwd:J.cwd,env:J.env,cols:80,rows:24});return{pid:Y.pid,write:(z)=>Y.write(z),resize:(z,X)=>Y.resize(z,X),kill:()=>Y.kill(),onData:(z)=>{Y.onData(z)},onExit:(z)=>{Y.onExit(z)}}}var U1=void 0,W1;if(BO())try{let{createBunWebSocket:$}=await import("hono/bun"),O=$();W1=O.upgradeWebSocket,U1=O.websocket}catch($){f0.warn("[Terminal] Failed to initialize Bun WebSocket support:",$)}async function LO($,O){let J=`term-${Date.now()}`;f0.info(`[Terminal] New connection: ${J}, cwd: ${$}`);let Z=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=Z.endsWith("sh")?["-l"]:[],z=await Y5(Z,Y,{cwd:$,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),X={id:J,process:z,cwd:$,buffer:"",subscribers:new Set};if(Q$.set(J,X),X.subscribers.add(O),z.onData((U)=>{let q=!1;for(let B of X.subscribers)try{B.send(U),q=!0}catch{X.subscribers.delete(B)}if(q)return;if(X.buffer+=U,X.buffer.length>HO)X.buffer=X.buffer.slice(-HO)}),z.onExit(({exitCode:U})=>{f0.info(`[Terminal] Process exited: ${J}, code: ${U}`);for(let q of X.subscribers)try{q.close()}catch{}Q$.delete(J)}),X.buffer){let U=X.buffer;X.buffer="";for(let q=0;q<U.length;q+=_O)O.send(U.slice(q,q+_O))}return{session:X,cleanup:()=>{if(f0.info(`[Terminal] Connection closed: ${J}`),X.subscribers.delete(O),X.subscribers.size===0){try{X.process.kill()}catch{}Q$.delete(J)}}}}function wO($,O){$.on("connection",async(J,Z)=>{let Y=new URL(Z.url||"/",`http://${Z.headers.host}`);if(!Y.pathname.endsWith("/terminal/ws")){J.close();return}let z=Y.searchParams.get("cwd")||O()||g();try{let{session:X,cleanup:U}=await LO(z,{send:(q)=>J.send(q),close:()=>J.close()});J.on("message",(q)=>{try{X.process.write(String(q))}catch(B){f0.error("[Terminal] Failed to write to PTY:",B)}}),J.on("close",U),J.on("error",U)}catch(X){f0.error("[Terminal] Failed to spawn PTY:",X),J.close()}})}var AO=()=>{let $=new Z5;if($.get("/status",(O)=>{let J=Array.from(Q$.values()).map((Z)=>({id:Z.id,cwd:Z.cwd}));return O.json({active:J.length,terminals:J})}),$.post("/kill/:terminalId",(O)=>{let J=O.req.param("terminalId"),Z=Q$.get(J);if(Z){try{Z.process.kill()}catch{}for(let Y of Z.subscribers)Y.close();return Q$.delete(J),O.json({success:!0})}return O.json({success:!1,error:"Terminal not found"},404)}),W1)$.get("/ws",W1((O)=>{let J=O.req.query("cwd")||O.get("directory")||g(),Z;return{async onOpen(Y,z){try{Z=await LO(J,{send:(X)=>z.send(X),close:()=>z.close()})}catch(X){f0.error("[Terminal] Failed to spawn PTY:",X),z.close()}},onMessage(Y){if(!Z)return;try{Z.session.process.write(String(Y.data))}catch(z){f0.error("[Terminal] Failed to write to PTY:",z)}},onClose(){Z?.cleanup()}}}));else $.get("/ws",(O)=>{return O.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return $};import Q5 from"node:path";import{Hono as x5}from"hono";var X5=F.Object({projectPath:F.String({minLength:1}),action:V0(["trust","revoke"])});function MO($){if(!Q5.isAbsolute($))throw new _("projectPath must be absolute")}var TO=()=>{let $=new x5;return $.get("/",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return MO(J),O.json(await F1.getInstance().getStatus(J))}),$.post("/",async(O)=>{let J=m(X5,await O.req.json());if(!J.success)throw new _("Invalid workspace trust request");let{projectPath:Z,action:Y}=J.data;MO(Z);let z=F1.getInstance(),X=Y==="trust"?await z.trust(Z):await z.revoke(Z);return await EO(),O.json({...X,reloadRequired:X.sensitiveSources>0})}),$};var K0=d("Service"),_1=[],v$,x$,X$,p$,bO=new Map,qO=new Map,B5=new Set([".css",".html",".js",".json",".svg"]),L5=1024,w5=3600000;function A5($,O){if(!$)return 0;let J=$.split(",").map((Z)=>{let[Y,...z]=Z.trim().toLowerCase().split(";"),X=z.find((q)=>q.trim().startsWith("q=")),U=X?Number(X.trim().slice(2)):1;return{name:Y,quality:Number.isFinite(U)?Math.max(0,Math.min(1,U)):0}});return J.find((Z)=>Z.name===O)?.quality??J.find((Z)=>Z.name==="*")?.quality??0}function RO(){if(X$)return;let $=()=>{C.collectStaleEmptySessions().then((O)=>{if(O>0)K0.info(`[SessionGC] removed ${O} stale empty session(s)`)}).catch((O)=>{K0.warn("[SessionGC] failed to collect stale empty sessions:",O)})};$(),X$=setInterval($,w5),X$.unref?.()}function M5(){if(!X$)return;clearInterval(X$),X$=void 0}function E5($){return["br","gzip"].map((J)=>({encoding:J,quality:A5($,J)})).filter((J)=>J.quality>0).sort((J,Z)=>Z.quality-J.quality||(J.encoding==="br"?-1:1))[0]?.encoding}function T5($){let O=bO.get($);if(O)return O;let J=b$($);return bO.set($,J),J}function b5($,O,J){let Z=`${J}:${$}`,Y=qO.get(Z);if(Y)return Y;let z=J==="br"?W5(O,{params:{[F5.BROTLI_PARAM_QUALITY]:5}}):U5(O,{level:6});return qO.set(Z,z),z}function q5(){let $=V5(G5(import.meta.url)),O=[y0($,"web"),y0(g(),"dist/web"),y0(g(),"packages/cli/dist/web")];for(let J of O){let Z=y0(J,"index.html");if(H1(Z)){if(b$(Z,"utf-8").includes("/assets/"))return K0.debug(`[Server] Found web dist at: ${J}`),J}}return null}function R5(){let $=new D5;$.onError((Z,Y)=>{if(K0.error("[Server] Request error:",Z),Z instanceof e)return Y.json(Z.toObject(),Z.statusCode);let z=Z instanceof Error?Z.message:String(Z);return Y.json({error:{code:"INTERNAL_ERROR",message:z}},500)}),$.use(async(Z,Y)=>{let z=process.env.BLADE_SERVER_PASSWORD;if(!z)return Y();let X=Z.req.path;if(X==="/"||X==="/favicon.svg"||X.startsWith("/assets/")||X.endsWith(".html")||X.endsWith(".js")||X.endsWith(".css"))return Y();let U=Z.req.header("Authorization");if(!U?.startsWith("Basic "))return Z.header("WWW-Authenticate",'Basic realm="Blade Server"'),Z.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let q=Buffer.from(U.slice(6),"base64").toString(),[B,M]=q.split(":"),T=process.env.BLADE_SERVER_USERNAME??"blade";if(B!==T||M!==z)return Z.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Y()}),$.use(async(Z,Y)=>{let z=Z.req.path==="/health"||Z.req.path==="/global/health"||Z.req.path.startsWith("/assets/");if(!z)K0.debug(`[Server] ${Z.req.method} ${Z.req.path}`);let X=Date.now();if(await Y(),!z){let U=Date.now()-X;K0.debug(`[Server] ${Z.req.method} ${Z.req.path} - ${Z.res.status} (${U}ms)`)}}),$.use(H5({origin(Z){if(!Z)return;if(Z.startsWith("http://localhost:"))return Z;if(Z.startsWith("http://127.0.0.1:"))return Z;if(Z==="tauri://localhost"||Z==="http://tauri.localhost")return Z;if(_1.includes(Z))return Z;return}})),$.use(async(Z,Y)=>{let z=Z.req.query("directory")||Z.req.header("x-blade-directory")||g();try{z=decodeURIComponent(z)}catch{}return Z.set("directory",z),Y()});let O=R4();p$=O,v$=O.recoverQueuedTasks,x$=new c$({dispatch:(Z)=>O.dispatchTask(Z),store:D1}),$.route("/global",v1()),$.route("/events",h1()),$.route("/sessions",O.app),$.route("/tasks",DO(O)),$.route("/schedules",JO(D1,x$)),$.route("/configs",I1()),$.route("/permissions",C4()),$.route("/plugins",l4()),$.route("/hooks",i1()),$.route("/workspace-trust",TO()),$.route("/providers",s4()),$.route("/models",O4()),$.route("/projects",a4()),$.route("/suggestions",NO()),$.route("/terminal",AO()),$.route("/mcp",n1()),$.route("/skills",zO()),$.get("/health",(Z)=>{return Z.json({healthy:!0,version:t0()})});let J=q5();if(J)K0.info(`[Server] Serving static files from ${J}`),$.get("/favicon.svg",()=>{let Z=y0(J,"favicon.svg");if(!H1(Z))return new Response(null,{status:404});return new Response(b$(Z),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),$.get("/assets/*",(Z)=>{let Y=y0(J,Z.req.path);if(!H1(Y))return Z.json({error:{code:"NOT_FOUND",message:`File not found: ${Z.req.path}`}},404);let z=T5(Y),X=N5(Y).toLowerCase(),q={".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"}[X]||"application/octet-stream",B=B5.has(X)&&z.byteLength>=L5?E5(Z.req.header("Accept-Encoding")):void 0,M=B?b5(Y,z,B):z;return new Response(new Uint8Array(M),{headers:{"Content-Type":q,"Content-Length":String(M.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...B?{"Content-Encoding":B}:{}}})}),$.get("/",(Z)=>{let Y=y0(J,"index.html"),z=b$(Y,"utf-8");return Z.html(z,200,{"Cache-Control":"no-cache"})}),$.get("*",(Z)=>{let Y=Z.req.path;if(Y.includes("."))return Z.json({error:{code:"NOT_FOUND",message:`File not found: ${Y}`}},404);let z=y0(J,"index.html"),X=b$(z,"utf-8");return Z.html(X,200,{"Cache-Control":"no-cache"})});else K0.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),$.get("/",(Z)=>{return Z.json({message:"Blade API Server",version:t0(),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"}})}),$.all("*",(Z)=>{return Z.json({error:{code:"NOT_FOUND",message:`Route not found: ${Z.req.path}`}},404)});return $}function j5(){let $=K5(),O=[];for(let J of Object.keys($)){let Z=$[J];if(!Z)continue;for(let Y of Z){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;O.push(Y.address)}}return O}function jO(){return typeof globalThis.Bun<"u"}function CO($,O){let J=globalThis.Bun,Z=(z)=>{try{return J.serve({hostname:O.hostname,port:z,fetch:$.fetch,idleTimeout:0,websocket:U1})}catch(X){K0.error("Failed to start Bun server:",X);return}},Y=O.port===0?Z(4096)??Z(0):Z(O.port);if(!Y)throw Error(`Failed to start Bun server on port ${O.port}`);return{url:Y.url,port:Y.port,hostname:Y.hostname,stop:async()=>{Y.stop(!0)}}}function C5($,O){return new Promise((J,Z)=>{let Y=z5(async(B,M)=>{let T=new URL(B.url||"/",`http://${B.headers.host}`),W=new Headers;for(let[E,t]of Object.entries(B.headers))if(t)if(Array.isArray(t))for(let I of t)W.append(E,I);else W.set(E,t);let u;if(B.method!=="GET"&&B.method!=="HEAD")u=(await new Promise((t)=>{let I=[];B.on("data",(O0)=>I.push(O0)),B.on("end",()=>t(Buffer.concat(I)))})).toString();let Y0=new Request(T.toString(),{method:B.method,headers:W,body:u});try{let E=await $.fetch(Y0);if(M.statusCode=E.status,E.headers.forEach((t,I)=>{M.setHeader(I,t)}),E.body){let t=E.body.getReader(),I=async()=>{let{done:O0,value:v}=await t.read();if(O0){M.end();return}return M.write(v),I()};await I()}else{let t=await E.text();M.end(t)}}catch(E){K0.error("[Server] Node request error:",E),M.statusCode=500,M.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),z=new _5({noServer:!0}),X=g();wO(z,()=>X),Y.on("upgrade",(B,M,T)=>{if(new URL(B.url||"/",`http://${B.headers.host}`).pathname==="/terminal/ws")z.handleUpgrade(B,M,T,(u)=>{z.emit("connection",u,B)});else M.destroy()});let U=(B)=>{return new Promise((M,T)=>{Y.once("error",(W)=>{if(W.code==="EADDRINUSE")T(W);else T(W)}),Y.listen(B,O.hostname,()=>{let W=Y.address();if(W&&typeof W==="object")M(W.port);else M(B)})})};(async()=>{let B;if(O.port===0)try{B=await U(4096)}catch{B=await U(0)}else B=await U(O.port);let M=new URL(`http://${O.hostname==="0.0.0.0"?"localhost":O.hostname}:${B}`);J({url:M,port:B,hostname:O.hostname,stop:async()=>{return new Promise((T)=>{z.close(()=>{Y.close(()=>T())})})}})})().catch(Z)})}var kO;((l6)=>{let $,O,J,Z=(q,B)=>{if($!==q)return Promise.resolve();if(J)return J;let M=B?.shutdown("server-shutdown");return x$?.stop(),M5(),J=(async()=>{let T,W=async(u)=>{if(!u)return;try{await u()}catch(Y0){T??=Y0}};if(await W(()=>q.stop()),await W(M?()=>M:void 0),$===q)$=void 0,O=void 0,p$=void 0,v$=void 0,x$=void 0;if(K0.info("[Server] Blade server stopped"),T!==void 0)throw T})(),J};function Y(){if(!O)O=R5();return O}l6.getApp=Y;function z(q){_1=q.cors??[];let B=Y();if(jO())$=CO(B,q),J=void 0,K0.info(`[Server] Blade server listening on ${$.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 M=$,T=p$;return v$?.().catch((W)=>{K0.warn("[Server] Failed to recover queued tasks:",W)}),x$?.start(),RO(),{url:M.url,port:M.port,hostname:M.hostname,stop:()=>Z(M,T)}}l6.listen=z;async function X(q){_1=q.cors??[];let B=Y();if(jO())$=CO(B,q),K0.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else $=await C5(B,q),K0.info(`[Server] Blade server listening on ${$.url} (Node.js runtime)`);J=void 0;let M=$,T=p$;try{await v$?.()}catch(W){K0.warn("[Server] Failed to recover queued tasks:",W)}return x$?.start(),RO(),{url:M.url,port:M.port,hostname:M.hostname,stop:()=>Z(M,T)}}l6.listenAsync=X;function U(){return $!==void 0}l6.isRunning=U})(kO||={});export{k5 as f,I5 as g,j5 as h,kO as i};
@@ -1 +0,0 @@
1
- import{Rd as a,Sd as b,Td as c}from"./chunk-kfv4mdcm.js";import"./chunk-0jsy9eav.js";import"./chunk-ecw74d2s.js";import"./chunk-pm9kt54d.js";import"./chunk-m3dvta6k.js";import"./chunk-m8s208g3.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};