blade-code 0.10.41 → 0.10.42

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 (106) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-t80e2bms.js → chunk-020hgyg7.js} +1 -1
  3. package/dist/{chunk-fxw1q5j5.js → chunk-0jsy9eav.js} +1 -1
  4. package/dist/{chunk-5sbewyjn.js → chunk-0qf7h4n2.js} +2 -2
  5. package/dist/{chunk-b5b8fb9y.js → chunk-18wnstzp.js} +1 -1
  6. package/dist/chunk-1e9866ye.js +5 -0
  7. package/dist/{chunk-q87nwpsb.js → chunk-1whfdz08.js} +1 -1
  8. package/dist/{chunk-bdxaz350.js → chunk-1yjzj2d0.js} +2 -2
  9. package/dist/{chunk-y30kw6gj.js → chunk-3v2sgvzt.js} +2 -2
  10. package/dist/{chunk-eg5sz4bw.js → chunk-3xx2ebr7.js} +1 -1
  11. package/dist/{chunk-nhzdkxnx.js → chunk-4k37vmxh.js} +1 -1
  12. package/dist/{chunk-xs7w13na.js → chunk-4rmdfme3.js} +1 -1
  13. package/dist/chunk-5hbm5e24.js +44 -0
  14. package/dist/{chunk-gbbnjzy8.js → chunk-5zr3w30g.js} +1 -1
  15. package/dist/{chunk-ens8nsge.js → chunk-6d0hphtd.js} +1 -1
  16. package/dist/chunk-74sxsd1h.js +1 -0
  17. package/dist/chunk-78jy2kby.js +1 -0
  18. package/dist/{chunk-djr17h80.js → chunk-7gjb405q.js} +1 -1
  19. package/dist/{chunk-atsw605q.js → chunk-7pmpm5yq.js} +1 -1
  20. package/dist/chunk-7qd6xqjs.js +1 -0
  21. package/dist/{chunk-adgx9vd7.js → chunk-8b2bpfnt.js} +3 -3
  22. package/dist/{chunk-6dma8han.js → chunk-8csfb83y.js} +2 -2
  23. package/dist/chunk-8wg7g98v.js +10 -0
  24. package/dist/{chunk-5zf8204m.js → chunk-anwm8rp3.js} +1 -1
  25. package/dist/{chunk-yxwargqc.js → chunk-brwdd5kp.js} +1 -1
  26. package/dist/chunk-c53hc8ze.js +1 -0
  27. package/dist/{chunk-yhw0pvyt.js → chunk-d2fce0vk.js} +2 -2
  28. package/dist/chunk-dgs04r04.js +2 -0
  29. package/dist/{chunk-dp9xzsja.js → chunk-dr4et3gj.js} +1 -1
  30. package/dist/{chunk-qgez5vw6.js → chunk-dx7xefys.js} +1 -1
  31. package/dist/{chunk-5ygv33qe.js → chunk-ecw74d2s.js} +2 -2
  32. package/dist/{chunk-w07gb3h0.js → chunk-ex21hxqf.js} +1 -1
  33. package/dist/{chunk-tsskar00.js → chunk-f542fh7g.js} +1 -1
  34. package/dist/{chunk-0hqsdbkr.js → chunk-f90ybvrs.js} +1 -1
  35. package/dist/{chunk-2bm55evt.js → chunk-fye8eghq.js} +2 -2
  36. package/dist/chunk-h9fkttf1.js +2 -0
  37. package/dist/chunk-hkmgrdxc.js +1 -0
  38. package/dist/{chunk-01jt0mpr.js → chunk-hypq4t4z.js} +1 -1
  39. package/dist/{chunk-8xfzbv9v.js → chunk-jf6mkx0j.js} +1 -1
  40. package/dist/{chunk-g9re8v25.js → chunk-jv9zg1fw.js} +1 -1
  41. package/dist/{chunk-wvc6bx0t.js → chunk-jz2gkqdt.js} +2 -2
  42. package/dist/chunk-katrmbxc.js +1 -0
  43. package/dist/{chunk-4ekrbk2w.js → chunk-kfv4mdcm.js} +2 -2
  44. package/dist/{chunk-9neq5xrb.js → chunk-m3dvta6k.js} +2 -2
  45. package/dist/chunk-m4ya7qqd.js +1 -0
  46. package/dist/{chunk-22h5kh4z.js → chunk-m8s208g3.js} +1 -1
  47. package/dist/{chunk-27w2k6t7.js → chunk-mp637mb6.js} +2 -2
  48. package/dist/{chunk-npgt73cg.js → chunk-mpymjr7j.js} +1 -1
  49. package/dist/{chunk-f4bx2n1y.js → chunk-mt7fn8cv.js} +3 -3
  50. package/dist/chunk-n6c6k87j.js +1 -0
  51. package/dist/{chunk-x04xb9g3.js → chunk-pm9kt54d.js} +1 -1
  52. package/dist/chunk-ppxn94za.js +1 -0
  53. package/dist/{chunk-hjkdc185.js → chunk-q6n6rqzs.js} +2 -2
  54. package/dist/{chunk-4mdy9d43.js → chunk-qb49rm5q.js} +1 -1
  55. package/dist/chunk-rf7hdke7.js +1 -0
  56. package/dist/chunk-rjjjgcw4.js +1 -0
  57. package/dist/{chunk-wk0vpgwk.js → chunk-sw3p1ygn.js} +396 -396
  58. package/dist/{chunk-fz55cnws.js → chunk-t2mc97k7.js} +2 -2
  59. package/dist/{chunk-5cgyevqj.js → chunk-te95z52n.js} +1 -1
  60. package/dist/{chunk-n0ebpwxd.js → chunk-vc32qrmq.js} +1 -1
  61. package/dist/chunk-vsaqjbm2.js +6 -0
  62. package/dist/{chunk-nsawkccy.js → chunk-wcxsm922.js} +1 -1
  63. package/dist/chunk-wm944thh.js +111 -0
  64. package/dist/chunk-wn23bvs0.js +1 -0
  65. package/dist/{chunk-62jaf7ej.js → chunk-wtczk025.js} +1 -1
  66. package/dist/{chunk-ck8sw2zp.js → chunk-xkg84094.js} +2 -2
  67. package/dist/{chunk-3p32k12g.js → chunk-y75y911b.js} +2 -2
  68. package/dist/chunk-yatvtpft.js +1 -0
  69. package/dist/{chunk-358zaryv.js → chunk-yqxyy3w2.js} +2 -2
  70. package/dist/{chunk-sfbprf9r.js → chunk-z60w7p8a.js} +1 -1
  71. package/dist/chunk-za6zyd82.js +8 -0
  72. package/dist/chunk-zhrc510s.js +1 -0
  73. package/dist/web/assets/{ChatView-BP89vdT_.js → ChatView-DBgMoUrW.js} +2 -2
  74. package/dist/web/assets/{CodeBlockHighlighter-UnjC3KVk.js → CodeBlockHighlighter-DLFQUVD6.js} +1 -1
  75. package/dist/web/assets/{FilePreview-D0BiZowf.js → FilePreview--1qHdJP_.js} +1 -1
  76. package/dist/web/assets/{MarkdownRenderer-CPu_rkPT.js → MarkdownRenderer-DcVHyjtl.js} +3 -3
  77. package/dist/web/assets/{SettingsModal-CM9pcJas.js → SettingsModal-BM6SPUXW.js} +1 -1
  78. package/dist/web/assets/{TaskSwitcher-BOCm7kPO.js → TaskSwitcher-B5VYY_QG.js} +1 -1
  79. package/dist/web/assets/{TerminalPanel-CUZ4slSS.js → TerminalPanel-XWA1jGs8.js} +1 -1
  80. package/dist/web/assets/index-B8y5_J0i.js +11 -0
  81. package/dist/web/assets/{session-events-109FkhOM.js → session-events-DJh6SZcl.js} +5 -5
  82. package/dist/web/index.html +2 -2
  83. package/package.json +1 -1
  84. package/dist/chunk-1j2sf8mc.js +0 -1
  85. package/dist/chunk-1kwm2m6t.js +0 -1
  86. package/dist/chunk-5w8edqbt.js +0 -1
  87. package/dist/chunk-6a3c496e.js +0 -1
  88. package/dist/chunk-6fe9kq17.js +0 -1
  89. package/dist/chunk-asnzpfzh.js +0 -10
  90. package/dist/chunk-atdeg922.js +0 -2
  91. package/dist/chunk-bw7fgs2n.js +0 -1
  92. package/dist/chunk-d61673v7.js +0 -5
  93. package/dist/chunk-f7y4m3y0.js +0 -1
  94. package/dist/chunk-fnz5g9ac.js +0 -1
  95. package/dist/chunk-kjn0yaqw.js +0 -1
  96. package/dist/chunk-m883e8d4.js +0 -1
  97. package/dist/chunk-mx5s93np.js +0 -6
  98. package/dist/chunk-p54vmne8.js +0 -1
  99. package/dist/chunk-qy9qkvwe.js +0 -1
  100. package/dist/chunk-s8f8amvg.js +0 -1
  101. package/dist/chunk-v80xem15.js +0 -2
  102. package/dist/chunk-w1vcjwbx.js +0 -8
  103. package/dist/chunk-x5s68axq.js +0 -44
  104. package/dist/chunk-z15h0370.js +0 -1
  105. package/dist/chunk-zracmha2.js +0 -111
  106. package/dist/web/assets/index-CthLsVgC.js +0 -11
@@ -1,8 +0,0 @@
1
- import{j as n4,k as t4}from"./chunk-t80e2bms.js";import{l as h$}from"./chunk-5zf8204m.js";import{s as k0}from"./chunk-yxwargqc.js";import{t as L4,u as S1,v as f1,w as y1,x as n0,y as m1}from"./chunk-nsawkccy.js";import{$ as u4,A as zO,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 F$,O as A$,P as M$,R as _4,S as B4,T as S4,U as f4,V as y4,W as m4,X as h4,Y as g4,Z as v4,_ as p4,aa as o4,da as MO,ia as KO}from"./chunk-wk0vpgwk.js";import{la as o1,ra as N0}from"./chunk-wvc6bx0t.js";import{Aa as WO,Ba as N1,Ca as FO,Da as d0,Ea as s4,Fa as e4,Ga as $O,Ha as M4,Ia as E4,Ja as T4,Ka as k1,La as D1,ta as l$,wa as NO,xa as GO,ya as w4,za as A4}from"./chunk-v80xem15.js";import{Sa as I0,Ta as h,Va as j,Wa as H4,ib as e$,rb as p0}from"./chunk-adgx9vd7.js";import{Ab as V4}from"./chunk-5cgyevqj.js";import{$b as L$,Tb as N4,Vb as f$,ac as Y1,bc as w$,dc as G4,jc as W4,kc as F4,mc as O$,pc as t$,uc as U4,vc as r$,wc as s$,xc as C}from"./chunk-zracmha2.js";import{Fd as _0,ud as $0,yd as s1}from"./chunk-27w2k6t7.js";import{Gd as n$}from"./chunk-atsw605q.js";import{Td as z4}from"./chunk-fxw1q5j5.js";import{Vd as P$}from"./chunk-yhw0pvyt.js";import{ce as ZO,de as YO,ge as P4,ke as G$,le as W$,pe as W0}from"./chunk-6dma8han.js";import{Ae as K4,ze as e1}from"./chunk-01jt0mpr.js";import{Ee as l1,Fe as s0}from"./chunk-f4bx2n1y.js";import{Xe as a1,of as c1,zf as N$}from"./chunk-x5s68axq.js";import{Cf as m,Ef as D,Hf as V0}from"./chunk-b5b8fb9y.js";import{Jf as y$}from"./chunk-atdeg922.js";import{Of as g}from"./chunk-g9re8v25.js";import{ng as d}from"./chunk-fz55cnws.js";import{tg as g0}from"./chunk-5ygv33qe.js";import{vg as t1,wg as x4,yg as r1,zg as X4}from"./chunk-x04xb9g3.js";import{Bg as t0}from"./chunk-358zaryv.js";import{Gg as U1}from"./chunk-5sbewyjn.js";import{Lg as C$,Pg as g1}from"./chunk-9neq5xrb.js";import{Sg as G1}from"./chunk-22h5kh4z.js";var C5={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 k5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as H1,readFileSync as q$}from"node:fs";import{createServer as X5}from"node:http";import{networkInterfaces as z5}from"node:os";import{dirname as K5,extname as V5,join as y0}from"node:path";import{fileURLToPath as N5}from"node:url";import{brotliCompressSync as G5,gzipSync as W5,constants as F5}from"node:zlib";import{Hono as U5}from"hono";import{cors as D5}from"hono/cors";import{WebSocketServer as H5}from"ws";var a0=d("Service"),PO=30000,SO=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??PO}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"||!SO.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??fO($),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 fO($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class e extends Error{code;statusCode;constructor($,O,J=500){super(O);this.code=$;this.statusCode=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}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($){super("TOO_MANY_REQUESTS",$,429)}}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 g5=D.Object({error:D.Object({code:D.String(),message:D.String()})});import{Hono as yO}from"hono";var i$=d("Service"),mO=D.Object({updates:D.Record(D.String(),D.Any()),options:D.Optional(D.Object({scope:D.Optional(V0(["local","project","global"])),immediate:D.Optional(D.Boolean())}))});function hO($){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}}var I1=()=>{let $=new yO;return $.get("/",async(O)=>{try{let J=$0();return O.json(J?hO(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(mO,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 gO}from"hono";import{streamSSE as vO}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 pO=15000,uO=d("Service"),dO=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),lO=new Set(["queued","running","completed","failed","cancelled","interrupted"]);function cO($){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 iO($){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 gO;return $.get("/",(O)=>vO(O,async(J)=>{let Z,Y,z=!1,X,F,b=new Promise((W)=>{F=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),F()};J.onAbort(M),X=new K$({write:async(W)=>{await J.writeSSE(W)},onFailure:(W)=>{uO.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(!dO.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=iO(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"||!lO.has(u))return;let Y0=cO(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()}})})},pO),await b}finally{M()}})),$};import{Hono as aO}from"hono";var v1=()=>{let $=new aO;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);return O.json({version:t0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:J,gitBranch:g1(J),taskAdmission:r0.getStats()})}),$};import p1 from"node:path";import{Hono as oO}from"hono";var nO=D.Object({projectPath:D.String({minLength:1}),action:V0(["trust","revoke"]),expectedDigest:D.Optional(D.String())}),tO=D.Object({projectPath:D.String({minLength:1}),sessionId:D.String({minLength:1}),enabled:D.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 oO;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(nO,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(),F;try{F=Y==="trust"?await X.trustProject(Z,z):await X.revokeProjectTrust(Z)}catch(b){if(b instanceof l1)throw new k(b.message);throw b}return O.json(F)}),$.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(tO,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 rO}from"hono";var E0=d("Service");function sO($){try{return o1($)}catch{return[]}}function eO($){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 rO;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((F)=>F.name),completionSupported:X.client.completionSupported,tasks:X.client.tasks,resources:X.contentCatalog.resources,resourceTemplates:X.contentCatalog.resourceTemplates.map((F)=>({...F,variables:sO(F.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=eO(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 $2}from"@earendil-works/pi-ai";import{Hono as O2}from"hono";var I$=d("Service");function J2($,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:$2(O),supportedServiceTiers:r1(O),supportedResponseVerbosities:t1(O),communicationStyles:J,input:O.input}}function Z2($){$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 O2;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,F=X.find((T)=>T.id===Y.config.currentModelId)??X[0],b=Y.catalog,B=z.communicationStyles.list(),M=(T)=>J2(T,b.resolveConfig(T),B);return O.json({configured:X.map(M),current:F?M(F):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:F,model:b,overrides:B,apiKey:M,modelProvider:T}=z;if(!X||!b)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,[b]),Y=X}catch(E){throw new _(E instanceof Error?E.message:"Invalid model provider")}}else J.getModel(X,b);if(M?.trim()){if(await J.setApiKey(X,M.trim()),W)Z=X}let u={provider:X,displayName:F||void 0,model:b,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,F=s1(J);if(!F)throw new _("model config not found");if(X)g0().getModel(F.provider,X);return await _0().updateModel(J,Z2({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 w2}from"hono";import J4 from"node:path";import{Mutex as Z4}from"async-mutex";import{Hono as Y2}from"hono";import{streamSSE as Q2}from"hono/streaming";import{LRUCache as x2}from"lru-cache";import{nanoid as $$}from"nanoid";var y=d("Service"),X2=D.Object({title:D.Optional(D.String()),projectPath:D.Optional(D.String())}),z2=M4,K2=D.Object({title:D.Optional(D.String()),projectPath:D.Optional(D.String())}),V2=D.Object({projectPath:D.String()}),N2=D.Object({objective:D.String({minLength:1}),tokenBudget:D.Optional(D.Integer({minimum:1})),permissionMode:D.Optional(V0(["default","autoEdit","plan","yolo"]))}),G2=D.Union([D.Object({action:D.Literal("pause")}),D.Object({action:D.Literal("resume")}),D.Object({action:D.Literal("edit"),objective:D.String({minLength:1})})]),n=new Map,J$,q0=new Map,v0=new Map,b0=new Map,m$=new x2({max:100,ttl:1800000});function Y4($){return{sessionId:$.sessionId,projectPath:$.projectPath}}function G0($){if(!$)return;return q0.get($)??m$.get($)}function W2($){if(q0.get($.id)!==$)return;q0.delete($.id),m$.set($.id,$)}function F2($){q0.delete($),m$.delete($)}function F0($){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 U2($){return{...typeof $.seq==="number"?{id:String($.seq)}:{},data:JSON.stringify({type:$.type,...typeof $.seq==="number"?{seq:$.seq}:{},properties:{...$.properties,sessionId:$.sessionId,projectPath:$.projectPath}})}}function D2(){for(let $ of q0.values())H$($,"route-reset");q0.clear();for(let $ of v0.values())$.controller.abort("route-reset");v0.clear(),m$.clear(),J$=void 0,n.clear()}function H2($){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=H2(J.tool_admission);if(Z)J.tool_admission=Z;else delete J.tool_admission;if($==="Bash"){let X={},F=["message","signal","status","summary"],b=["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 F){let W=J[T];if(typeof W==="string")X[T]=W.slice(0,8192)}for(let T of b){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,F)=>typeof X==="number"&&Number.isSafeInteger(X)&&X>=0&&X<=F?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,F=Array.isArray(X.artifacts)?X.artifacts.slice(0,64).flatMap((b)=>{if(!b||typeof b!=="object"||Array.isArray(b))return[];let B=b,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:F}}else delete J.mcpResult;return J};function _2($){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 B2($,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 U$($,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,F=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$(F,B),L$);return[{...Y,name:F,content:M$(M),metadata:_$(F,{...B.metadata,status:B.success?"completed":"failed"})}]}return[{...Y,name:F,metadata:_$(F,X)}]}let z=F4(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:U$(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 b4=()=>{D2();let $=new Y2;$.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,F=new _4,b,B=async(x)=>{let G;try{G=F.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 U=G.communicationStyle??x.communicationStyle;N=F$.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}:{},...U?{communicationStyle:U}:{},...U===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 U=await N;return O.set(Q,U),U}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 U=G??O.get(Q);if(O.delete(Q),U){for(let[H,L]of O)if(L===U)O.delete(H)}await U?.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[U,H]=await Promise.all([C.loadSession(x.sessionId,x.projectPath),C.findSessionTaskWorktree(x.sessionId,x.projectPath)]),L=D$(N,U,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(!F.stats().accepting)throw new h0;let N=$$(12),U={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(),signal:U.abortController.signal,onUpdate:(q)=>{U.status=q.state,U.taskQueuePosition=q.queuePosition,U.taskQueueDepth=q.queueDepth,U.taskConcurrencyLimit=q.maxConcurrent,x.taskStatus=q.state,x.taskQueuePosition=q.queuePosition,x.taskQueueDepth=q.queueDepth,x.taskConcurrencyLimit=q.maxConcurrent,U.taskAdmissionUpdate=(U.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await H.setTaskAdmission(q)}).catch((w)=>{y.warn(`[SessionRoutes] Failed to persist admission for ${x.id}:`,w)})}});U.taskAdmission=L;let A=L.getSnapshot();U.status=A.state,U.taskQueuePosition=A.queuePosition,U.taskQueueDepth=A.queueDepth,U.taskConcurrencyLimit=A.maxConcurrent}return q0.set(N,U),x.currentRunId=N,U.completion=L2(U,x,G,Q,W,{pendingInputOnly:K.pendingInputOnly,preparedInputTurn:K.preparedInputTurn,goalContinuationOnly:K.goalContinuationOnly,outputSchema:K.outputSchema,taskAdmission:U.taskAdmission,disposeRuntime:u}).catch((H)=>{y.error(`[SessionRoutes] Run ${N} failed:`,H)}),U},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=U$(x.sourceProjectPath),N=x.modelId?.trim(),U=$0();if(!U)throw new _("Config not initialized");let[H,L]=await Promise.all([P$(K,U),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 q=H.config.models.find((R)=>R.id===A);if(!q)throw new _(`Task model not found: ${A}`);let w=x.reasoningEffort??"off",r=x.serviceTier??"auto",U0=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(q);z4(R,w),X4(R,r),x4(R,U0);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:U0,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 L4.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 queue is full")}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})},b$=(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 U=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),U({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 U({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 U({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 U({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(F0(G))return;if(x.taskIsolation&&x.taskStatus!=="queued"&&x.taskStatus!=="running")return;let Q=await F$.hasPendingInbox(x.projectPath,x.id),K=!Q&&await F$.hasActiveGoal(x.projectPath,x.id);if(!Q&&!K)return;let N=await W(x),U=G0(x.currentRunId);if(F0(U))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=F.enter()}catch{return}try{await V(x)}finally{G.release()}};J$=J0;let B1=async()=>{let x={scheduled:0,failed:0,deferred:0};if(!F.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 F$.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 U=await Y0(N);if(await J0(U),U.currentRunId)x.scheduled++}catch(U){if(U instanceof O1){x.deferred+=G.length-Q;break}y.warn(`[SessionRoutes] Failed to recover queued task ${K.sessionId}:`,U),x.deferred++}}return x};return $.get("/",async(x)=>{try{let G=await C.listSessions(),Q=new Set(G.filter((q)=>q.relationType==="subagent").map((q)=>h({sessionId:q.sessionId,projectPath:q.projectPath}))),K=Array.from(n.values()).filter((q)=>!Q.has(h(x0(q)))&&q.relationType!=="subagent").map((q)=>e0(q)),N=new Set(K.map((q)=>h({sessionId:q.sessionId,projectPath:q.projectPath}))),U=G.filter((q)=>{if(q.relationType==="subagent")return!1;return!N.has(h({sessionId:q.sessionId,projectPath:q.projectPath}))}),H=new Set(N),L=U.filter((q)=>{let w=h({sessionId:q.sessionId,projectPath:q.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"),U=x.req.query("archived");if(U!==void 0&&U!=="true"&&U!=="false")throw new _("archived must be true or false");let H=U==="true",L=await C.listSessionPage({...N?{cwd:U$(N)}:{},...K?{cursor:K}:{},...Q===void 0?{}:{limit:Q},includeSubagents:!1,archived:H}),A=new Map((H?[]:Array.from(n.values())).filter((q)=>q.relationType!=="subagent").map((q)=>[h(x0(q)),e0(q)]));return x.json({sessions:L.sessions.map((q)=>A.get(h({sessionId:q.sessionId,projectPath:q.projectPath}))??q),...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(X2,G);if(!Q.success)throw new _("Invalid request body");let{title:K,projectPath:N}=Q.data,U=n$("web",12),H=U$(N||x.get("directory")||g(),N?"projectPath":"directory"),L=await C.createSessionMetadata(U,H,{title:K,taskStatus:"completed"}),A=D$(L,[]),q=x0(A);return n.set(h(q),A),j.publish(q,"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(V2,Q);if(!K.success)throw new _("Invalid request body");let N=U$(K.data.projectPath),U=await C.findSessionMetadata(G,N);if(!U)throw new f("Session",G);let H=await C.forkSession(G,{sourceProjectPath:U.projectPath,targetProjectPath:U.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 U4)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(K2,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),U=await C.updateSessionMetadata(N.sessionId,N.projectPath,{title:K.data.title}),H=n.get(h(N));if(H)H.title=U.title??H.title,H.updatedAt=new Date(U.lastMessageTime);if(U.title)j.publish(N,"session.updated",{title:U.title});return x.json({success:!0,title:U.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(w4,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(F0(N))throw new k("Cannot rewind while a run is active");let U=await W(Q),H;try{H=await U.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(T4,await x.req.json());if(!Q.success)throw new _("Invalid code review request");let K=await E(G,Q.data.projectPath),N=x0(K),U=h(N);return M(N).runExclusive(async()=>{if(F0(G0(K.currentRunId)))throw new k("Cannot start a review during an active turn");if(b0.has(U))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 q=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(b0.get(U)?.reviewId===A.reviewId)b0.delete(U)});return b0.set(U,{reviewId:A.reviewId,controller:L,completion:q}),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=A4.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(F0(N))throw new k("Cannot resume a subagent while a parent run is active");let U=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})},q;try{q=U.resumeSubagent({agentId:x.req.param("agentId"),prompt:G.data.prompt,onEvent:(w,r)=>{B2(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:q.session.id,type:q.session.subagentType,description:q.session.description,resumedFrom:q.source.id,rootAgentId:q.session.rootAgentId,resumeDepth:q.session.resumeDepth}),H=!0,L)A(L);return x.json({source:S$(q.source),session:S$(q.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(N2,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(F0(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 q=I(Q,"",H,{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:L}:{}});return await q.taskAdmissionUpdate,x.json({status:q.status==="queued"?"queued":"running",runId:q.id,goal:A,queuePosition:q.taskQueuePosition,queueDepth:q.taskQueueDepth,maxConcurrentTasks:q.taskConcurrencyLimit},202)})}),$.patch("/:sessionId/goal",async(x)=>{let G=m(G2,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),U;if(G.data.action==="pause")U=await N.pauseGoal();else if(G.data.action==="edit")U=await N.editGoal(G.data.objective);else U=await N.resumeGoal();if(j.publish(K,"goal.updated",{goal:U}),U.status==="active"&&!F0(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:U,queuePosition:H.taskQueuePosition,queueDepth:H.taskQueueDepth,maxConcurrentTasks:H.taskConcurrencyLimit},202)}return x.json({status:U.status,goal:U})})}),$.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 U of K){let H=I0({sessionId:U.sessionId,projectPath:U.projectPath}),L=n.get(h(H));if(F0(G0(L?.currentRunId)))throw new k(`Stop session ${U.sessionId} before archiving this session tree`)}for(let U of K){let H=I0({sessionId:U.sessionId,projectPath:U.projectPath}),L=n.get(h(H));if(L)await u(L)}let N=await C.archiveSession(Q.sessionId,Q.projectPath);for(let U of K){let H=I0({sessionId:U.sessionId,projectPath:U.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((U)=>U.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),U=K.filter((H)=>H.sessionId===Q.sessionId||H.archivedBySessionId===Q.sessionId).map((H)=>H.sessionId);for(let H of U)j.publish({sessionId:H,projectPath:Q.projectPath},"session.unarchived",{archiveRootId:Q.sessionId});return x.json({session:N,restoredSessionIds:U})}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),U=n.get(N),H=O.get(N),L=U?.taskWorktree??await C.findSessionTaskWorktree(K.sessionId,K.projectPath),A;if(U?.currentRunId){let w=G0(U.currentRunId);if(w)H$(w),await w.completion,A=w.id}let q=b0.get(N);if(q)q.controller.abort("session-delete"),await q.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"),U=N?Number.parseInt(N,10):Number.NaN,H=Number.isInteger(U)?U+1:void 0;return Q2(x,async(L)=>{let q,w,r=!1,U0,j0,w0=new Promise((P)=>{j0=P}),Q0=()=>{if(w!==void 0)clearInterval(w),w=void 0;q?.(),q=void 0},i=(P)=>{if(r)return;r=!0,Q0(),U0?.close(P),j0()},c0=new Set;L.onAbort(i),U0=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)}}),q=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)});U0?.observe(U2(P),P.seq)});try{if(L.aborted||r)return;let P=G0(K.currentRunId),S=F0(P)?await W(K):void 0,R=S?.getPendingSteeringCount()??0;if(await U0.writeInitial({data:JSON.stringify({type:"connected",properties:{sessionId:Q.sessionId,projectPath:Q.projectPath,timestamp:Date.now(),status:F0(P)?P.status:"idle",runId:F0(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=_2(p);if(s.seq===void 0)return;await U0.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(U0.finishInitialization({replayed:H!==void 0}),L.aborted||r)return;if(!P&&!b0.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);U0.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;U0?.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(z2,Q);if(!K.success)throw new _("Invalid message format");let{content:N,attachments:U,modelId:H,reasoningEffort:L,serviceTier:A,responseVerbosity:q,communicationStyle:w,permissionMode:r,projectPath:U0,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((U??[]).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,U),R=await E(G,U0??x.req.query("projectPath")),o=P??R.permissionMode??"default",Z0=x0(R);return M(Z0).runExclusive(async()=>{let l=G0(R.currentRunId);if(F0(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(q&&c.getResponseVerbosityConfiguration().selection!==q)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 kO=M0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(j.publish(Z0,kO,{runId:l.id,messageId:d$,queued:C1}),M0.delivery==="next_turn"&&l.status!=="running"&&l.status!=="waiting_permission")J0(R).catch((IO)=>{y.error(`[SessionRoutes] Failed to wake queued follow-up for ${G}:`,IO)});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(q)try{p.resolveResponseVerbosityConfiguration(q,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,q1=Boolean(L)&&w1.selection!==L,b1=Boolean(A)&&A1.selection!==A,R1=Boolean(q)&&M1.selection!==q,j1=Boolean(Q0)&&E1.selection!==Q0;if(T1||q1||b1||R1||j1)await p.refresh({...i?{modelId:i}:{},...L?{reasoningEffort:L}:{},...A?{serviceTier:A}:{},...q?{responseVerbosity:q}:{},...Q0?{communicationStyle:Q0}:{}});let u$={...i&&R.selectedModelId!==i?{selectedModelId:i}:{},...L&&R.reasoningEffort!==L?{reasoningEffort:L}:{},...A&&R.serviceTier!==A?{serviceTier:A}:{},...q&&R.responseVerbosity!==q?{responseVerbosity:q}:{},...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||q1||b1||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(E4,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),U=h(N);return M(N).runExclusive(async()=>{if(v0.has(U))throw new k("A user shell command is already running in this Session");let H=await W(K),L=new AbortController,A,q=new Promise((w)=>{A=w});v0.set(U,{controller:L,completion:q});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"&&F0(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(U),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 U=b0.get(h(Q));if(U)U.controller.abort("user-cancel"),await U.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=b0.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 U=G0(K.currentRunId);return x.json({sessionId:G,projectPath:Q.projectPath,runId:K.currentRunId,status:U?.status||"idle"})}),{app:$,dispatchTask:v,retryTask:b$,getTaskDiff:X0,deliverTask:R0,recoverQueuedTasks:B1,shutdown:(x="server-shutdown")=>{if(b)return b;return F.close(x),b=(async()=>{let G,Q=async(A)=>{let q=await Promise.allSettled(A);for(let w of q)if(w.status==="rejected")G??=w.reason},K=new Set,N=()=>{for(let A of q0.values()){if(A.completion)K.add(A.completion);if(F0(A))H$(A,x)}for(let A of v0.values())A.controller.abort(x),K.add(A.completion);for(let A of b0.values())A.controller.abort(x),K.add(A.completion)},U=F.waitForIdle(),H=!1;U.then(()=>{H=!0});while(!H)N(),await Promise.race([U,new Promise((A)=>setImmediate(A))]);await U,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})(),b}}};async function L2($,O,J,Z,Y,z={}){let{abortController:X,sessionId:F,id:b}=$,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 B4.createWithRuntime(I,{sessionId:F,...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:(U)=>{clearTimeout(N),K(U)},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: ${b}`);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},b$={messages:await C.loadSessionModelContext(O.id,O.projectPath),userId:"web-user",sessionId:F,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:b,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:b,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,b$,{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("",b$,{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:b,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)});W2($)}}async function R4($,O,J){y.info(`[SessionRoutes] Looking for permission ${O} in session ${$.sessionId}`),y.info(`[SessionRoutes] Active runs: ${q0.size}`);for(let[z,X]of q0.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,F]=await Promise.all([C.loadSession($.sessionId,$.projectPath),C.findSessionTaskWorktree($.sessionId,$.projectPath)]);Y=D$(z,X,F),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"),A2=D.Object({approved:D.Boolean(),remember:D.Optional(D.Boolean()),scope:D.Optional(V0(["once","session","project"])),targetMode:D.Optional(V0(["default","autoEdit","plan","yolo"])),feedback:D.Optional(D.String({maxLength:4000})),answers:D.Optional(D.Record(D.String({maxLength:80}),D.Union([D.String({maxLength:4000}),D.Array(D.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:D.Optional(D.Object({action:V0(["accept","decline","cancel"]),content:D.Optional(D.Record(D.String(),D.Union([D.String({maxLength:4000}),D.Number(),D.Boolean(),D.Array(D.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),j4=()=>{let $=new w2;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(A2,z);if(!X.success)throw new _("Invalid permission response format");let{approved:F,remember:b,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 R4(Y0,J,{approved:F,reason:T,scope:B,targetMode:M,feedback:T,answers:W,elicitation:u}))throw new f("Permission request",J);return Q1.info(`[PermissionRoutes] Permission ${J} ${F?"approved":"denied"}`),O.json({success:!0,approved:F,remember:b})}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 C4 from"node:path";import{Hono as M2}from"hono";var E2=D.Object({projectPath:D.String({minLength:1}),enabled:D.Boolean(),scope:D.Optional(V0(["local","project","global"]))}),T2=D.Object({projectPath:D.String({minLength:1})}),q2=D.Object({projectPath:D.String({minLength:1}),source:D.String({minLength:1}),trust:D.Literal(!0),ref:D.Optional(D.String({minLength:1}))}),b2=D.Object({projectPath:D.String({minLength:1}),trust:D.Literal(!0)}),R2=D.Object({projectPath:D.String({minLength:1}),confirm:D.Literal(!0)}),j2=D.Object({projectPath:D.String({minLength:1}),source:D.String({minLength:1}),ref:D.Optional(D.String({minLength:1}))}),k4=D.Object({projectPath:D.String({minLength:1}),confirm:D.Optional(D.Literal(!0))}),C2=D.Object({projectPath:D.String({minLength:1}),scope:D.Optional(V0(["local","project","global"])),policy:D.Object({restrictToAllowedSources:D.Boolean(),requireGitCommitSha:D.Boolean(),allowedGitHosts:D.Array(D.String()),allowedMarketplaces:D.Array(D.String()),allowedLocalRoots:D.Array(D.String())})});function B0($){if(!$||!C4.isAbsolute($))throw new _("projectPath must be absolute");return C4.resolve($)}async function I4($){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 k2(){let $=P4(),[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 F=Z.get(X.name);return{name:X.name,description:X.description??"",version:X.version,category:X.category,tags:X.tags??[],installed:F!==void 0,installedVersion:F?.version}})}))}function Z$($,O){if(!$.success)throw new _($.error??O)}var d4=()=>{let $=new M2;return $.get("/",async(O)=>{let J=B0(O.req.query("projectPath"));return O.json(await I4(J))}),$.post("/refresh",async(O)=>{let J=m(T2,await O.req.json());if(!J.success)throw new _("Invalid plugin refresh request");let Z=B0(J.data.projectPath),Y=await f4(Z);return O.json({plugins:await I4(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 k2())}),$.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(C2,await O.req.json());if(!J.success)throw new _("Invalid plugin source policy request");let Z=B0(J.data.projectPath),Y=await y4(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 m4(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(j2,await O.req.json());if(!J.success)throw new _("Invalid marketplace add request");let Z=B0(J.data.projectPath),Y=await v4(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(k4,await O.req.json());if(!J.success)throw new _("Invalid marketplace refresh request");let Z=await p4(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(k4,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 u4(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(b2,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 h4(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(R2,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 g4(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(E2,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 F=await S4(Z,Y,J.data.enabled,J.data.scope??"local");return O.json(F)}),$};import{Hono as y2}from"hono";import{execFile as I2}from"node:child_process";import P2 from"node:path";var z1="__BLADE_DIRECTORY_PICKER_CANCELLED__",S2=900000;function f2($,O){return new Promise((J)=>{I2($,[...O],{timeout:S2,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(!P2.isAbsolute(O))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:O}}function X1($){return $.exitCode!==0||Boolean($.errorCode)}class l4{platform;runCommand;activeSelection=null;constructor($={}){this.platform=$.platform??process.platform,this.runCommand=$.runCommand??f2}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 c4=new l4;var m2=D.Object({path:D.String({minLength:1})});function h2($){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 i4=($={})=>{let O=new y2,J=$.pickDirectory??(()=>c4.pick()),Z=$.allowDirectoryPickerRequest??h2;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(m2,z);if(!X.success)throw new _("A project path is required");try{let F=await h$.bind(X.data.path,g());return Y.json(F,201)}catch(F){throw new _(F instanceof Error?F.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 g2}from"hono";var a4=d("Service"),r4=()=>{let $=new g2;return $.get("/",async(O)=>{try{let J=await n4();return O.json(J)}catch(J){return a4.error("[ProviderRoutes] Failed to list providers:",J),O.json([])}}),$.get("/:provider/models",async(O)=>{let J=O.req.param("provider");try{let Z=await t4(J);return O.json(Z)}catch(Z){return a4.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,F={name:z.name,baseUrl:z.baseUrl,wireApi:z.wireApi,...X?{apiKeyEnv:X}:{}},b=g0(),B=z.apiKey?.trim()?await b.credentials.read(J):void 0;if(z.apiKey?.trim())await b.setApiKey(J,z.apiKey.trim());try{return await _0().updateModelProvider(J,F),O.json({success:!0})}catch(M){if(z.apiKey?.trim())if(B)await b.credentials.modify(J,async()=>B);else await b.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((F)=>F.provider===J),X=Y.modelId?z.find((F)=>F.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 o4(X,Z))}),$};import{Hono as v2}from"hono";var p2=d("Service"),OO=($,O)=>{let J=new v2;return J.onError((Z,Y)=>{if(Z instanceof e)return Y.json(Z.toObject(),Z.statusCode);return p2.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($O.parse({schedules:Y}))}),J.post("/",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let z=m(s4,Y);if(!z.success)throw new _("Invalid schedule request");let X=z.data.projectPath||Z.get("directory")||g();try{let F=await $.create({...z.data,projectPath:X});return Z.json(d0.parse(F),201)}catch(F){throw new _(F instanceof Error?F.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(e4,Y);if(!z.success)throw new _("Invalid schedule update");let{modelId:X,reasoningEffort:F,serviceTier:b,responseVerbosity:B,communicationStyle:M,isolation:T,permissionMode:W,...u}=z.data,Y0={...X!==void 0?{modelId:X}:{},...F!==void 0?{reasoningEffort:F}:{},...b!==void 0?{serviceTier:b}:{},...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 QO}from"node:os";import*as L0 from"node:path";import{Hono as u2}from"hono";var l0=d("Service"),JO=L0.join(QO(),".blade","skills"),K1=L0.join(QO(),".blade","skills-config.json");async function xO(){try{let $=await S0.readFile(K1,"utf-8");return JSON.parse($)}catch{return{disabled:[]}}}async function d2($){await S0.mkdir(L0.dirname(K1),{recursive:!0}),await S0.writeFile(K1,JSON.stringify($,null,2))}async function l2($,O){let J=await xO();if(O)J.disabled=J.disabled.filter((Z)=>Z!==$);else if(!J.disabled.includes($))J.disabled.push($);await d2(J)}var P0=null,c2=300000,i2=6;async function a2(){if(P0&&Date.now()-P0.timestamp<c2)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(i2,J.length);return await Promise.all(Array.from({length:z},async()=>{while(Y<J.length){let X=Y++,F=J[X];if(!F)continue;let b=`Official ${F.name} skill`;try{let B=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${F.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(B.ok){let T=(await B.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(T)b=T[1].trim().slice(0,100)}}catch{}Z[X]={name:F.name,description:b,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 XO=()=>{let $=new u2;return $.get("/",async(O)=>{try{let J=O.get("directory")||g(),Y=(await W0(J)).skills.getAll(),z=await xO(),X=Y.map((F)=>({id:F.name,name:F.name,enabled:!z.disabled.includes(F.name),description:F.description||"",version:F.version||"1.0.0",provider:"Local",location:F.source==="builtin"?"Built-in":F.basePath,removable:F.source==="user"&&L0.dirname(L0.resolve(F.basePath))===L0.resolve(JO),capabilities:["prompts"],allowedTools:F.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 l2(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),F=L0.resolve(JO);if(z.source!=="user"||L0.dirname(X)!==F)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=ZO(),Y=O.get("directory")||g(),z=YO({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 a2();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 o2}from"node:child_process";import{readdir as n2}from"node:fs/promises";import g$ from"node:path";import t2 from"fast-glob";import{Hono as r2}from"hono";var E$=d("Service"),s2=($)=>{try{return o2("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},e2=[...Y$.map(($)=>`${$}/**`),...Y$,...Y$.map(($)=>`**/${$}/**`),...Y$.map(($)=>`**/${$}`),...V1.map(($)=>`**/${$}`)],$5=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),VO=()=>{let $=new r2;return $.get("/commands",async(O)=>{try{let J=O.req.query("q")||"",Z=O.get("directory")||g();await W0(Z);let Y=KO(J,Z).filter((z)=>!$5.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",F=(await t2("**/*",{cwd:Z,dot:!1,followSymbolicLinks:!1,onlyFiles:z,markDirectories:!0,unique:!0,ignore:e2})).map((M)=>M.replace(/\\/g,"/"));if(!J)return O.json(F.slice(0,Y));let b=J.toLowerCase(),B=F.filter((M)=>M.toLowerCase().includes(b)).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 n2(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 F=new Set(Y$),b=X.filter((B)=>{let M=B.name;if(M.startsWith("."))return!1;if(F.has(M))return!1;for(let T of V1)if(M.match(new RegExp(T.replace("*",".*"))))return!1;return!0});return O.json(b)}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=zO(),F=await X.stat(Y);if(!F?.isFile)return O.json({error:"File not found"},404);let b=200000,B=await X.readTextFile(Y),M=B.length>b;return O.json({path:J,content:M?B.slice(0,b):B,truncated:M,size:F.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=s2(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 O5}from"hono";var T$=d("Service"),UO=($)=>{let O=new O5;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(WO,Z);if(!Y.success)throw new _("Invalid task request");if((Y.data.attachments??[]).reduce((X,F)=>X+(typeof F.content==="string"?Buffer.byteLength(F.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(NO.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(GO.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 J5}from"hono";var f0=d("Service"),Q$=new Map,DO=2097152,HO=65536;function _O(){return typeof globalThis.Bun<"u"}async function Z5($,O,J){if(_O()){let{spawn:z}=await import("bun-pty"),X=z($,O,{name:"xterm-256color",cwd:J.cwd,env:J.env});return{pid:X.pid,write:(F)=>X.write(F),resize:(F,b)=>X.resize(F,b),kill:()=>X.kill(),onData:(F)=>X.onData(F),onExit:(F)=>X.onExit(F)}}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 F1=void 0,W1;if(_O())try{let{createBunWebSocket:$}=await import("hono/bun"),O=$();W1=O.upgradeWebSocket,F1=O.websocket}catch($){f0.warn("[Terminal] Failed to initialize Bun WebSocket support:",$)}async function BO($,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 Z5(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((F)=>{let b=!1;for(let B of X.subscribers)try{B.send(F),b=!0}catch{X.subscribers.delete(B)}if(b)return;if(X.buffer+=F,X.buffer.length>DO)X.buffer=X.buffer.slice(-DO)}),z.onExit(({exitCode:F})=>{f0.info(`[Terminal] Process exited: ${J}, code: ${F}`);for(let b of X.subscribers)try{b.close()}catch{}Q$.delete(J)}),X.buffer){let F=X.buffer;X.buffer="";for(let b=0;b<F.length;b+=HO)O.send(F.slice(b,b+HO))}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 LO($,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:F}=await BO(z,{send:(b)=>J.send(b),close:()=>J.close()});J.on("message",(b)=>{try{X.process.write(String(b))}catch(B){f0.error("[Terminal] Failed to write to PTY:",B)}}),J.on("close",F),J.on("error",F)}catch(X){f0.error("[Terminal] Failed to spawn PTY:",X),J.close()}})}var wO=()=>{let $=new J5;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 BO(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 Y5 from"node:path";import{Hono as Q5}from"hono";var x5=D.Object({projectPath:D.String({minLength:1}),action:V0(["trust","revoke"])});function AO($){if(!Y5.isAbsolute($))throw new _("projectPath must be absolute")}var EO=()=>{let $=new Q5;return $.get("/",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return AO(J),O.json(await U1.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;AO(Z);let z=U1.getInstance(),X=Y==="trust"?await z.trust(Z):await z.revoke(Z);return await MO(),O.json({...X,reloadRequired:X.sensitiveSources>0})}),$};var K0=d("Service"),_1=[],v$,x$,X$,p$,TO=new Map,qO=new Map,_5=new Set([".css",".html",".js",".json",".svg"]),B5=1024,L5=3600000;function w5($,O){if(!$)return 0;let J=$.split(",").map((Z)=>{let[Y,...z]=Z.trim().toLowerCase().split(";"),X=z.find((b)=>b.trim().startsWith("q=")),F=X?Number(X.trim().slice(2)):1;return{name:Y,quality:Number.isFinite(F)?Math.max(0,Math.min(1,F)):0}});return J.find((Z)=>Z.name===O)?.quality??J.find((Z)=>Z.name==="*")?.quality??0}function bO(){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($,L5),X$.unref?.()}function A5(){if(!X$)return;clearInterval(X$),X$=void 0}function M5($){return["br","gzip"].map((J)=>({encoding:J,quality:w5($,J)})).filter((J)=>J.quality>0).sort((J,Z)=>Z.quality-J.quality||(J.encoding==="br"?-1:1))[0]?.encoding}function E5($){let O=TO.get($);if(O)return O;let J=q$($);return TO.set($,J),J}function T5($,O,J){let Z=`${J}:${$}`,Y=qO.get(Z);if(Y)return Y;let z=J==="br"?G5(O,{params:{[F5.BROTLI_PARAM_QUALITY]:5}}):W5(O,{level:6});return qO.set(Z,z),z}function q5(){let $=K5(N5(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(q$(Z,"utf-8").includes("/assets/"))return K0.debug(`[Server] Found web dist at: ${J}`),J}}return null}function b5(){let $=new U5;$.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 F=Z.req.header("Authorization");if(!F?.startsWith("Basic "))return Z.header("WWW-Authenticate",'Basic realm="Blade Server"'),Z.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let b=Buffer.from(F.slice(6),"base64").toString(),[B,M]=b.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 F=Date.now()-X;K0.debug(`[Server] ${Z.req.method} ${Z.req.path} - ${Z.res.status} (${F}ms)`)}}),$.use(D5({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=b4();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",UO(O)),$.route("/schedules",OO(D1,x$)),$.route("/configs",I1()),$.route("/permissions",j4()),$.route("/plugins",d4()),$.route("/hooks",i1()),$.route("/workspace-trust",EO()),$.route("/providers",r4()),$.route("/models",O4()),$.route("/projects",i4()),$.route("/suggestions",VO()),$.route("/terminal",wO()),$.route("/mcp",n1()),$.route("/skills",XO()),$.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(q$(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=E5(Y),X=V5(Y).toLowerCase(),b={".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=_5.has(X)&&z.byteLength>=B5?M5(Z.req.header("Accept-Encoding")):void 0,M=B?T5(Y,z,B):z;return new Response(new Uint8Array(M),{headers:{"Content-Type":b,"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=q$(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=q$(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 R5(){let $=z5(),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 RO(){return typeof globalThis.Bun<"u"}function jO($,O){let J=globalThis.Bun,Z=(z)=>{try{return J.serve({hostname:O.hostname,port:z,fetch:$.fetch,idleTimeout:0,websocket:F1})}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 j5($,O){return new Promise((J,Z)=>{let Y=X5(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 H5({noServer:!0}),X=g();LO(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 F=(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 F(4096)}catch{B=await F(0)}else B=await F(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 CO;((u6)=>{let $,O,J,Z=(b,B)=>{if($!==b)return Promise.resolve();if(J)return J;let M=B?.shutdown("server-shutdown");return x$?.stop(),A5(),J=(async()=>{let T,W=async(u)=>{if(!u)return;try{await u()}catch(Y0){T??=Y0}};if(await W(()=>b.stop()),await W(M?()=>M:void 0),$===b)$=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=b5();return O}u6.getApp=Y;function z(b){_1=b.cors??[];let B=Y();if(RO())$=jO(B,b),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(),bO(),{url:M.url,port:M.port,hostname:M.hostname,stop:()=>Z(M,T)}}u6.listen=z;async function X(b){_1=b.cors??[];let B=Y();if(RO())$=jO(B,b),K0.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else $=await j5(B,b),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(),bO(),{url:M.url,port:M.port,hostname:M.hostname,stop:()=>Z(M,T)}}u6.listenAsync=X;function F(){return $!==void 0}u6.isRunning=F})(CO||={});export{C5 as f,k5 as g,R5 as h,CO as i};
@@ -1,44 +0,0 @@
1
- import{Cf as En,Df as j,Ef as o}from"./chunk-b5b8fb9y.js";import{If as jn,Jf as ln}from"./chunk-atdeg922.js";import{Of as a}from"./chunk-g9re8v25.js";import{$f as dt,Pf as Xn,Qf as bt,Rf as wt,Vf as at,Wf as pn,Xf as Pt,Yf as Lt,Zf as xt,_f as Cn,ag as ht,bg as Nn,cg as ft,dg as $t,eg as In,fg as it,gg as gt,hg as Xt,ig as pt,jg as Ct}from"./chunk-nhzdkxnx.js";import{ng as hn}from"./chunk-fz55cnws.js";import{qg as ct,tg as J}from"./chunk-5ygv33qe.js";import{Bg as wn,Cg as an}from"./chunk-358zaryv.js";import{Gg as d}from"./chunk-5sbewyjn.js";import{Qg as mn}from"./chunk-9neq5xrb.js";var Nt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function It(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&It(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var H=async(n,t)=>{I(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function Q(n){let t=n.oauth;if(!t)return;let M=t;for(let S of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[S]!==void 0)throw Error(`MCP OAuth "${S}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((S)=>S.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let e=t.clientId?.trim();if(e&&e.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let _=t.scopes?.map((S)=>S.trim());if(_){if(_.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(_.some((S)=>!S||S.length>128||!Nt.test(S)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(_).size!==_.length)throw Error("MCP OAuth scopes must not contain duplicates")}let u=t.callbackPort;if(u!==void 0&&(!Number.isInteger(u)||u<1024||u>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...e?{clientId:e}:{},..._?.length?{scopes:_}:{},...u!==void 0?{callbackPort:u}:{}}}import{randomUUID as F}from"node:crypto";import Wt from"node:http";import{auth as Tn}from"@modelcontextprotocol/sdk/client/auth.js";import Jt from"open";import{createHash as Rt,randomUUID as zt}from"node:crypto";import{constants as k,promises as L}from"node:fs";import y from"node:path";import{Mutex as Bt}from"async-mutex";import Kt from"write-file-atomic";var sn=1,Ht=1048576,qt=5000,Ut=50,Yt=/^[a-f0-9]{64}$/,Vt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Gt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),Ot=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(Vt),tokens:o.Optional(Gt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(Ot),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),_n=o.Object({version:o.Literal(sn),credentials:o.Record(o.String(),on)},{additionalProperties:!1});function q(n,t){return n instanceof Error&&"code"in n&&n.code===t}function Zt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return q(t,"EPERM")}}function D(n){return structuredClone(n)}function Sn(n){if(Object.keys(n.credentials).some((t)=>!Yt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function U(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Rt("sha256").update(JSON.stringify({serverUrl:U(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class i{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=mn()){this.stateRoot=y.join(n,"mcp"),this.tokenFilePath=y.join(this.stateRoot,"oauth-credentials.json");let t=i.mutexes.get(this.tokenFilePath);if(!t)t=new Bt,i.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?D(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let r=M.credentials[n],e=await t(r?D(r):null);if(e)M.credentials[n]=j(on,e);else delete M.credentials[n];return e?D(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),r=await n(M);return await this.writeStore(M),r}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await L.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ht)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=En(_n,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return Sn(M.data),M.data}catch(n){if(q(n,"ENOENT"))return{version:sn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(_n,n);Sn(t),await Kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
- `,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=y.join(this.stateRoot,".oauth-credentials.lock"),t=zt(),M=Date.now()+qt;while(Date.now()<M)try{let r=await L.open(n,k.O_CREAT|k.O_EXCL|k.O_WRONLY,384);return await r.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
- `,"utf8"),await r.close(),async()=>{try{if(JSON.parse(await L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(e){if(!q(e,"ENOENT"))throw e}}}catch(r){if(!q(r,"EEXIST"))throw r;await this.removeDeadLock(n),await new Promise((e)=>setTimeout(e,Ut))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await L.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!Zt(M.pid))await L.unlink(n)}}var An="127.0.0.1",cn=7777,bn="/oauth/callback",Qt=300000;class v extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Pn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function kt(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
- <html lang="en">
5
- <head>
6
- <meta charset="utf-8">
7
- <meta name="viewport" content="width=device-width,initial-scale=1">
8
- <title>${t}</title>
9
- </head>
10
- <body>
11
- <main>
12
- <h1>${t}</h1>
13
- <p>${n?"You can close this window and return to Blade.":"Return to Blade and retry the OAuth login."}</p>
14
- </main>
15
- </body>
16
- </html>`}function R(n,t,M){n.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer"}),n.end(kt(M))}class g{serverName;config;static activeFlowIdentity;tokenStorage;serverUrl;identity;callbackUrl;openAuthorizationUrl;codeVerifierValue;activeFlow;lastError;constructor(n,t,M,r={}){this.serverName=n;this.config=M;this.serverUrl=U(t),this.identity=l(this.serverUrl,M.clientId,M.scopes),this.tokenStorage=r.tokenStorage??new i;let e=M.callbackPort??cn;this.callbackUrl=`http://${An}:${e}${bn}`,this.openAuthorizationUrl=r.openAuthorizationUrl??(async(_)=>{await Jt(_,{wait:!1})})}get redirectUrl(){return this.callbackUrl}get clientMetadata(){return{redirect_uris:[this.callbackUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:`${an()} ${wn()}`,...this.config.scopes?.length?{scope:this.config.scopes.join(" ")}:{}}}async state(){return this.activeFlow?.state??F()}async clientInformation(){if(this.config.clientId)return{client_id:this.config.clientId};return(await this.readCredential())?.clientInformation}async saveClientInformation(n){await this.updateCredential((t)=>({...this.baseCredential(t),clientInformation:n}))}async tokens(){let n=await this.readCredential();if(!n?.tokens)return;if(n.tokenExpiresAt!==void 0&&n.tokenExpiresAt<=Date.now()&&!n.tokens.refresh_token)return;return structuredClone(n.tokens)}async saveTokens(n){let t=n.expires_in===void 0?void 0:Date.now()+n.expires_in*1000;await this.updateCredential((M)=>({...this.baseCredential(M),tokens:structuredClone(n),...t===void 0?{}:{tokenExpiresAt:t}})),this.lastError=void 0}async redirectToAuthorization(n){let t=this.activeFlow;if(!t)throw new v(this.serverName);t.authorizationUrl=I(n,"MCP OAuth authorization URL").toString()}async saveCodeVerifier(n){this.codeVerifierValue=n}async codeVerifier(){if(!this.codeVerifierValue)throw Error("MCP OAuth PKCE verifier is unavailable");return this.codeVerifierValue}async saveDiscoveryState(n){await this.updateCredential((t)=>({...this.baseCredential(t),discoveryState:structuredClone(n)}))}async discoveryState(){let n=(await this.readCredential())?.discoveryState;return n?structuredClone(n):void 0}async invalidateCredentials(n){if(n==="verifier"){this.codeVerifierValue=void 0;return}if(n==="all"){await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0;return}await this.updateCredential((t)=>{if(!t)return null;let M={...t};if(n==="client")delete M.clientInformation,delete M.tokens,delete M.tokenExpiresAt;else if(n==="tokens")delete M.tokens,delete M.tokenExpiresAt;else if(n==="discovery")delete M.discoveryState;return{...M,updatedAt:new Date().toISOString()}})}async getStatus(){if(this.activeFlow)return"authorizing";if(this.lastError)return"error";return await this.hasUsableCredentials()?"authenticated":"unauthenticated"}async hasUsableCredentials(){let n=await this.readCredential();if(!n?.tokens?.access_token)return!1;if(n.tokenExpiresAt===void 0||n.tokenExpiresAt>Date.now())return!0;return Boolean(n.tokens.refresh_token)}async beginAuthorization(){if(this.activeFlow)return this.toHandle(this.activeFlow);if(await this.hasUsableCredentials())throw Error(`MCP server "${this.serverName}" already has OAuth credentials`);if(g.activeFlowIdentity)throw Error("Another MCP OAuth authorization is already in progress");g.activeFlowIdentity=this.identity,this.lastError=void 0,this.codeVerifierValue=void 0;try{let n=await this.createFlow();if(this.activeFlow=n,await Tn(this,{serverUrl:this.serverUrl,fetchFn:H})!=="REDIRECT"||!n.authorizationUrl)throw Error("MCP OAuth server did not start an authorization redirect");return this.toHandle(n)}catch(n){let t=n instanceof Error?n:Error(String(n));throw await this.failActiveFlow(t),t}}async openAuthorization(){let n=await this.beginAuthorization();return await this.openAuthorizationUrl(n.authorizationUrl),n}async logout(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"));await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0,this.lastError=void 0}async dispose(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"))}async createFlow(){let n,t,M=new Promise((u,S)=>{n=u,t=S});M.catch(()=>{return});let r=F(),e=Wt.createServer((u,S)=>{this.handleCallback(u,S)});e.on("clientError",(u,S)=>{S.end(`HTTP/1.1 400 Bad Request\r
17
- Connection: close\r
18
- \r
19
- `)}),await new Promise((u,S)=>{let m=(s)=>S(s);e.once("error",m),e.listen(this.config.callbackPort??cn,An,()=>{e.off("error",m),u()})});let _={flowId:F(),state:r,callbackUrl:this.callbackUrl,server:e,timeout:setTimeout(()=>{this.failActiveFlow(Error("MCP OAuth authorization timed out"))},Qt),completion:M,resolve:n,reject:t,settled:!1};return _.timeout.unref(),_}async handleCallback(n,t){let M=this.activeFlow;if(!M){R(t,410,!1);return}try{if(n.method!=="GET"){t.setHeader("Allow","GET"),R(t,405,!1);return}let r=new URL(n.url??"/",M.callbackUrl);if(r.pathname!==bn){R(t,404,!1);return}let e=r.searchParams.get("state"),_=r.searchParams.get("code");if(r.searchParams.get("error"))throw Error("MCP OAuth authorization was denied");if(!e||e!==M.state)throw Error("MCP OAuth state mismatch");if(!_)throw Error("MCP OAuth callback is missing the authorization code");if(await Tn(this,{serverUrl:this.serverUrl,authorizationCode:_,fetchFn:H})!=="AUTHORIZED")throw Error("MCP OAuth token exchange did not complete");R(t,200,!0),await this.completeActiveFlow()}catch(r){R(t,400,!1),await this.failActiveFlow(r instanceof Error?r:Error(String(r)))}}async completeActiveFlow(){let n=this.activeFlow;if(!n||n.settled)return;n.settled=!0,clearTimeout(n.timeout),await new Promise((t)=>n.server.close(()=>t())),this.activeFlow=void 0,g.activeFlowIdentity=void 0,this.codeVerifierValue=void 0,this.lastError=void 0,n.resolve()}async failActiveFlow(n){let t=this.activeFlow;if(this.lastError=n,this.codeVerifierValue=void 0,g.activeFlowIdentity=void 0,!t||t.settled){this.activeFlow=void 0;return}t.settled=!0,clearTimeout(t.timeout),await new Promise((M)=>t.server.close(()=>M())),this.activeFlow=void 0,t.reject(n)}toHandle(n){if(!n.authorizationUrl)throw Error("MCP OAuth authorization URL is unavailable");return{flowId:n.flowId,authorizationUrl:n.authorizationUrl,callbackUrl:n.callbackUrl,completion:n.completion}}readCredential(){return this.tokenStorage.getCredential(this.identity)}updateCredential(n){return this.tokenStorage.updateCredential(this.identity,n)}baseCredential(n){return{...n??{},serverUrl:this.serverUrl,...this.config.clientId?{clientId:this.config.clientId}:{},updatedAt:new Date().toISOString()}}}import{promises as Y}from"node:fs";import Ln from"node:os";import f from"node:path";import{Mutex as xn}from"async-mutex";import{merge as yt}from"lodash-es";import Dt from"write-file-atomic";var dn=hn("Service"),X={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},modelProviders:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},bashForegroundHandoffMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerForegroundRecoveryMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerCircuitBreakerOpenMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestConcurrency:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestAdmissionMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestPendingBytes:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},codeTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},communicationStyle:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},enabledPlugins:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},pluginSourcePolicy:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxConcurrentTasks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxQueuedTasks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},lspServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},vM=new Set(Object.entries(X).filter(([n,t])=>t.persistable).map(([n])=>n)),nr=new Set(Object.entries(X).filter(([n,t])=>!t.persistable).map(([n])=>n));class x{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){if(x.instance)for(let n of x.instance.timers.values())clearTimeout(n);x.instance=null}async save(n,t={}){this.validatePersistableFields(n);let M=this.groupUpdatesByTarget(n,t.scope,t.projectDir);if(t.immediate)await Promise.all(Array.from(M.entries()).map(([r,e])=>this.flushTarget(r,e)));else for(let[r,e]of M)this.scheduleSave(r,e)}async flush(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear();let n=Array.from(this.pendingUpdates.entries()).map(([t,M])=>this.flushTarget(t,M));this.pendingUpdates.clear(),await Promise.all(n)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(n,t={}){await this.appendPermissionRuleForDecision(n,"allow",t)}async appendPermissionDenyRule(n,t={}){await this.appendPermissionRuleForDecision(n,"deny",t)}async appendPermissionRuleForDecision(n,t,M){let r=M.scope??"local",e=this.resolveFilePath("settings",r,M.projectDir);await this.flushTargetWithModifier(e,(_)=>{let u=_.permissions??{allow:[],ask:[],deny:[]},S={allow:t==="allow"?this.dedupeArray([...u.allow||[],n]):u.allow||[],ask:u.ask||[],deny:t==="deny"?this.dedupeArray([...u.deny||[],n]):u.deny||[]};return{..._,permissions:S}})}async appendLocalPermissionRule(n,t={}){await this.appendPermissionRule(n,{...t,scope:"local"})}async appendLocalPermissionDenyRule(n,t={}){await this.appendPermissionDenyRule(n,{...t,scope:"local"})}async removePluginSetting(n,t={}){let M=t.scope??"local",r=this.resolveFilePath("settings",M,t.projectDir);await this.flushTargetWithModifier(r,(e)=>{let _={...e.enabledPlugins??{}};delete _[n];let u={...e};if(Object.keys(_).length>0)u.enabledPlugins=_;else delete u.enabledPlugins;return u})}validatePersistableFields(n){for(let t of Object.keys(n)){let M=X[t];if(!M)throw Error(`Unknown config field: ${t}`);if(!M.persistable)throw Error(`Field "${t}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(n,t,M){let r=new Map;for(let[e,_]of Object.entries(n)){let u=X[e];if(!u)continue;let S=t??u.defaultScope,m=this.resolveFilePath(u.target,S,M);if(!r.has(m))r.set(m,{});r.get(m)[e]=_}return r}resolveFilePath(n,t,M){let r=M??a();if(n==="config")return t==="global"?f.join(Ln.homedir(),".blade","config.json"):f.join(r,".blade","config.json");switch(t){case"local":return f.join(r,".blade","settings.local.json");case"project":return f.join(r,".blade","settings.json");case"global":return f.join(Ln.homedir(),".blade","settings.json");default:return f.join(r,".blade","settings.local.json")}}scheduleSave(n,t){let M=this.pendingUpdates.get(n)??{},r=this.mergePendingUpdates(M,t);this.pendingUpdates.set(n,r);let e=this.timers.get(n);if(e)clearTimeout(e);let _=setTimeout(async()=>{let u=this.pendingUpdates.get(n);if(u){this.pendingUpdates.delete(n),this.timers.delete(n);try{await this.flushTarget(n,u),this.lastSaveError=null}catch(S){let m=S instanceof Error?S:Error(String(S));this.lastSaveError=m,dn.error(`Failed to save config to ${n}:`,m.message),dn.error("Stack trace:",m.stack)}}},this.debounceDelay);this.timers.set(n,_)}mergePendingUpdates(n,t){let M={...n};for(let[r,e]of Object.entries(t)){let _=X[r];if(!_){M[r]=e;continue}switch(_.mergeStrategy){case"replace":M[r]=e;break;case"append-dedupe":this.applyAppendDedupe(M,r,e);break;case"deep-merge":this.applyDeepMerge(M,r,e);break}}return M}async flushTarget(n,t){let M=this.fileLocks.get(n);if(!M)M=new xn,this.fileLocks.set(n,M);await M.runExclusive(async()=>{await this.performWrite(n,t)})}async flushTargetWithModifier(n,t){let M=this.fileLocks.get(n);if(!M)M=new xn,this.fileLocks.set(n,M);await M.runExclusive(async()=>{await Y.mkdir(f.dirname(n),{recursive:!0,mode:493});let r={};try{let _=await Y.readFile(n,"utf-8");r=JSON.parse(_)}catch{r={}}let e=t(r);await this.atomicWrite(n,e)})}async performWrite(n,t){await Y.mkdir(f.dirname(n),{recursive:!0,mode:493});let M={};try{let e=await Y.readFile(n,"utf-8");M=JSON.parse(e)}catch{M={}}let r={...M};if(typeof r.theme==="string"&&r.codeTheme===void 0)r.codeTheme=r.theme;delete r.theme;for(let[e,_]of Object.entries(t)){let u=X[e];if(!u){r[e]=_;continue}switch(u.mergeStrategy){case"replace":r[e]=_;break;case"append-dedupe":this.applyAppendDedupe(r,e,_);break;case"deep-merge":this.applyDeepMerge(r,e,_);break}}await this.atomicWrite(n,r)}applyAppendDedupe(n,t,M){if(t==="permissions"&&typeof M==="object"&&M!==null){let r=n[t]??{allow:[],ask:[],deny:[]},e=M;n[t]={allow:this.dedupeArray([...r.allow||[],...e.allow||[]]),ask:this.dedupeArray([...r.ask||[],...e.ask||[]]),deny:this.dedupeArray([...r.deny||[],...e.deny||[]])}}else if(Array.isArray(M)){let r=Array.isArray(n[t])?n[t]:[];n[t]=this.dedupeArray([...r,...M])}else n[t]=M}applyDeepMerge(n,t,M){if(typeof M==="object"&&M!==null&&!Array.isArray(M)){let r=typeof n[t]==="object"&&n[t]!==null?n[t]:{};n[t]=yt({},r,M)}else n[t]=M}dedupeArray(n){return Array.from(new Set(n))}async atomicWrite(n,t){await Dt(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}}function tr(){return x.getInstance()}var fn=15000,$n=1000,gn=300000;function nn(n){return n===0||typeof n==="number"&&Number.isSafeInteger(n)&&n>=1000&&n<=300000}function rr(n,t=15000){return nn(n)?n:t}var T={currentModelId:"",models:[],modelProviders:{},temperature:0,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,bashForegroundHandoffMs:fn,providerForegroundRecoveryMs:Xn,providerCircuitBreakerOpenMs:pn,providerRequestConcurrency:Cn,providerRequestAdmissionMs:Nn,providerRequestPendingBytes:In,codeTheme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},lspServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},enabledPlugins:{},pluginSourcePolicy:{restrictToAllowedSources:!1,requireGitCommitSha:!1,allowedGitHosts:[],allowedMarketplaces:[],allowedLocalRoots:[]},env:{},disableAllHooks:!1,maxTurns:-1,maxConcurrentTasks:3,maxQueuedTasks:100};var Rn=/^[A-Za-z0-9_-]{21}$/;function zn(n){return n.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[._-]+|[._-]+$/g,"").slice(0,80)||"model"}function lt(n,t){let M=new Set(t.map((u)=>u.id)),r=zn(n.model);if(!M.has(r))return r;let e=`${zn(n.provider)}-${r}`.slice(0,120);if(!M.has(e))return e;let _=2;while(M.has(`${e}-${_}`))_++;return`${e}-${_}`}function Bn(n,t){let M=n.filter((_)=>!Rn.test(_.id)).map((_)=>({id:_.id})),r=new Map;return{models:n.map((_)=>{if(!Rn.test(_.id))return{..._};let{id:u,...S}=_,m=lt(S,M);return M.push({id:m}),r.set(u,m),{..._,id:m}}),currentModelId:r.get(t)??t,changed:r.size>0}}import{promises as At}from"fs";import{merge as K}from"lodash-es";import b from"os";import E from"path";function Hn(n){let t=Kn(n.timeout??300000,"MCP timeout"),M=Kn(n.idleTimeout??Math.min(60000,t),"MCP idleTimeout");if(M>t)throw Error("MCP idleTimeout must not exceed timeout");return{totalTimeoutMs:t,idleTimeoutMs:M,maxProgressEvents:128}}function Ar(n,t,M){if(t.count>=M.maxProgressEvents)return;if(!Number.isFinite(n.progress)||n.progress<0)return;if(n.total!==void 0&&(!Number.isFinite(n.total)||n.total<=0))return;if(t.lastProgress!==void 0&&n.progress<t.lastProgress)return;t.count++,t.lastProgress=n.progress;let r=n.message?.replace(/\0/g,"").trim().slice(0,1000);return{progress:n.progress,...n.total!==void 0?{total:n.total}:{},message:r||Ft(n.progress,n.total)}}function Kn(n,t){if(!Number.isSafeInteger(n)||n<1000||n>1800000)throw Error(`${t} must be an integer between 1000 and 1800000 milliseconds`);return n}function Ft(n,t){if(t!==void 0)return`MCP progress ${Math.max(0,Math.min(100,n/t*100)).toFixed(0)}%`;return`MCP progress ${n}`}import{createHash as vt}from"node:crypto";var V=["debug","info","notice","warning","error","critical","alert","emergency"],wr=64,ar=64,Pr=256,nM=8192,Vn=16384,tM=256,MM=6,rM=128,qn=64,Un=64,eM=128,uM=/authorization|api[-_]?key|cookie|credential|password|secret|token/i;function Gn(n){let t=n.logging;if(t!==void 0&&(t===null||typeof t!=="object"||Array.isArray(t)))throw Error("MCP logging configuration must be an object");let M=t?.enabled??!0;if(typeof M!=="boolean")throw Error("MCP logging enabled must be a boolean");let r=t?.level??"warning";if(!_M(r))throw Error(`MCP logging level must be one of: ${V.join(", ")}`);return{enabled:M,level:r}}function _M(n){return typeof n==="string"&&V.includes(n)}function Lr(n,t){return V.indexOf(n)>=V.indexOf(t)}function SM(n,t={}){let M=mM(n.data),r=typeof M.value==="string"?M.value:JSON.stringify(M.value),e=Yn(r,Vn),_=e.value,u=Buffer.byteLength(_),S=vt("sha256").update(_).digest("hex"),m=t.exposeDetails!==!1,s=m?Yn(_,nM):{value:`[MCP log details omitted; sha256=${S}]`,truncated:!1},A=m&&n.logger?G(Mn(n.logger),tM):void 0;return{level:n.level,...A?{logger:A}:{},message:s.value||"[empty MCP log message]",projectedBytes:u,dataSha256:S,truncated:M.truncated||e.truncated||s.truncated,detailsOmitted:!m,timestamp:t.now??Date.now()}}function xr(n,t={}){return{...SM({level:"warning",logger:"blade.mcp.logging",data:`MCP log rate exceeded; dropped at least ${Math.max(1,n)} message(s)`},t),synthetic:!0}}function mM(n){let t={nodes:0,remainingStringBytes:Vn,truncated:!1,seen:new WeakSet};return{value:tn(n,0,t),truncated:t.truncated}}function tn(n,t,M){if(M.nodes++,M.nodes>rM)return M.truncated=!0,"[node limit reached]";if(n===null||typeof n==="boolean")return n;if(typeof n==="number")return Number.isFinite(n)?n:String(n);if(typeof n==="bigint")return n.toString();if(typeof n==="string"){let r=Mn(n),e=Math.max(0,M.remainingStringBytes),_=G(r,e),u=Buffer.byteLength(_);if(M.remainingStringBytes-=u,u<Buffer.byteLength(r))M.truncated=!0;return _}if(typeof n>"u")return"[undefined]";if(typeof n==="symbol"||typeof n==="function")return`[${typeof n}]`;if(t>=MM)return M.truncated=!0,"[depth limit reached]";if(M.seen.has(n))return M.truncated=!0,"[circular]";M.seen.add(n);try{if(Array.isArray(n)){if(n.length>qn)M.truncated=!0;return n.slice(0,qn).map((_)=>tn(_,t+1,M))}let r=Object.create(null),e=Object.entries(n);if(e.length>Un)M.truncated=!0;for(let[_,u]of e.slice(0,Un)){let S=G(Mn(_),eM)||"[empty-key]";if(_==="_meta"||uM.test(_))r[S]="[redacted]";else r[S]=tn(u,t+1,M)}return r}finally{M.seen.delete(n)}}function Mn(n){return[...n.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")].filter((M)=>{let r=M.charCodeAt(0);return(r===9||r===10||r===13||r>=32)&&r!==127}).join("")}function G(n,t){if(t<=0)return"";if(Buffer.byteLength(n)<=t)return n;let M=Buffer.from(n).subarray(0,t).toString("utf8");while(Buffer.byteLength(M)>t)M=M.slice(0,-1);return M}function Yn(n,t){if(Buffer.byteLength(n)<=t)return{value:n,truncated:!1};let M=`
20
- ...[MCP log truncated]`;return{value:G(n,t-Buffer.byteLength(M))+M,truncated:!0}}var On=1024,EM=4096,Zn=2,sM=8,Wn=65536,oM=1048576,Jn=50,Qn=16000,kn=4,TM=100,yn=1048576,AM=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Fn(n){if(!n)return{enabled:!1,maxTokens:On,maxRequestsPerToolCall:Zn,maxInputBytes:Wn};if(typeof n.enabled!=="boolean")throw Error("MCP sampling.enabled must be a boolean");return{enabled:n.enabled,maxTokens:O(n.maxTokens??On,1,EM,"MCP sampling.maxTokens"),maxRequestsPerToolCall:O(n.maxRequestsPerToolCall??Zn,1,sM,"MCP sampling.maxRequestsPerToolCall"),maxInputBytes:O(n.maxInputBytes??Wn,1,oM,"MCP sampling.maxInputBytes")}}function fr(n,t){if(!t.enabled)throw Error("MCP sampling is disabled");if(n.task)throw Error("Task-based MCP sampling is not supported");if(n.tools?.length)throw Error("MCP sampling tools were not negotiated");if(n.includeContext&&n.includeContext!=="none")throw Error("MCP sampling server context was not negotiated");if(n.messages.length===0||n.messages.length>Jn)throw Error(`MCP sampling messages must contain 1-${Jn} entries`);if(n.systemPrompt!==void 0&&n.systemPrompt.length>Qn)throw Error(`MCP sampling system prompt exceeds ${Qn} characters`);if(n.temperature!==void 0&&(!Number.isFinite(n.temperature)||n.temperature<0||n.temperature>2))throw Error("MCP sampling temperature must be between 0 and 2");let M=n.stopSequences??[];if(M.length>kn||M.some((s)=>!s||s.length>TM||s.includes("\x00")))throw Error(`MCP sampling stop sequences must contain at most ${kn} non-empty bounded values`);let r=[],e=0,_=0,u=0,S=[];if(n.systemPrompt)e+=Buffer.byteLength(n.systemPrompt,"utf8"),r.push({role:"system",content:n.systemPrompt}),S.push(`System: ${Dn(n.systemPrompt)}`);for(let s of n.messages){let A=Array.isArray(s.content)?s.content:[s.content],P=[],w=[];for(let c of A){if(c.type==="text"){e+=Buffer.byteLength(c.text,"utf8"),P.push({type:"text",text:c.text}),w.push(Dn(c.text));continue}if(c.type==="image"){if(s.role!=="user")throw Error("MCP sampling images are only supported in user messages");if(!AM.has(c.mimeType))throw Error(`Unsupported MCP sampling image type: ${c.mimeType}`);let N=cM(c.data);_+=N,u++,P.push({type:"image_url",image_url:{url:`data:${c.mimeType};base64,${c.data}`}}),w.push(`[${c.mimeType} image, ${N} bytes]`);continue}throw Error(`Unsupported MCP sampling content type: ${c.type}`)}if(P.length===0)throw Error("MCP sampling message has no supported content");r.push({role:s.role,content:P.length===1&&P[0]?.type==="text"?P[0].text:P}),S.push(`${s.role==="user"?"User":"Assistant"}: ${w.join(" ")}`)}if(e+_>t.maxInputBytes)throw Error(`MCP sampling input exceeds ${t.maxInputBytes} bytes`);if(u>jn||_>ln)throw Error("MCP sampling image input exceeds the shared attachment budget");let m=O(n.maxTokens,1,Number.MAX_SAFE_INTEGER,"MCP sampling maxTokens");return{messages:r,maxTokens:Math.min(m,t.maxTokens),...n.temperature!==void 0?{temperature:n.temperature}:{},stopSequences:[...M],preview:S.join(`
21
- `).slice(0,8000)}}function $r(n,t,M){if(n.toolCalls?.length)throw Error("Model returned tools for basic MCP sampling");let r=n.content,e=n.finishReason==="length"||n.finishReason==="max_tokens"?"maxTokens":"endTurn",_=-1;for(let u of M.stopSequences){let S=r.indexOf(u);if(S>=0&&(_===-1||S<_))_=S}if(_>=0)r=r.slice(0,_),e="stopSequence";if(Buffer.byteLength(r,"utf8")>yn)throw Error(`MCP sampling response exceeds ${yn} bytes`);return{model:t,role:"assistant",content:{type:"text",text:r},stopReason:e}}function O(n,t,M,r){if(!Number.isSafeInteger(n)||n<t||n>M)throw Error(`${r} must be an integer between ${t} and ${M}`);return n}function cM(n){if(!n||n.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(n))throw Error("MCP sampling image contains invalid base64 data");return Buffer.from(n,"base64").byteLength}function Dn(n){return n.replace(/\s+/g," ").trim().slice(0,1000)}var gr=256,Xr=1e4,pr=86400000;var bM=/[\p{Cf}\p{Co}\p{Cn}]/u;function nt(n){if(!n)return{enabled:!1,defaultTtlMs:600000,pollIntervalMs:500,maxTasksPerSession:32,maxLifetimeMs:1800000};if(typeof n.enabled!=="boolean")throw Error("MCP tasks.enabled must be a boolean");let t=$(n.defaultTtlMs??600000,1e4,86400000,"MCP tasks.defaultTtlMs"),M=$(n.maxLifetimeMs??1800000,1e4,86400000,"MCP tasks.maxLifetimeMs");if(t>M)throw Error("MCP tasks.defaultTtlMs must not exceed tasks.maxLifetimeMs");return{enabled:n.enabled,defaultTtlMs:t,pollIntervalMs:$(n.pollIntervalMs??500,100,1e4,"MCP tasks.pollIntervalMs"),maxTasksPerSession:$(n.maxTasksPerSession??32,1,32,"MCP tasks.maxTasksPerSession"),maxLifetimeMs:M}}function Cr(n,t){return $(n??t.defaultTtlMs,1e4,Math.min(86400000,t.maxLifetimeMs),"MCP task ttl")}function Nr(n,t,M){let r=aM(n.taskId,"task ID",512),e=vn(n.createdAt,"createdAt"),_=vn(n.lastUpdatedAt,"lastUpdatedAt");if(Date.parse(_)<Date.parse(e))throw Error("MCP task lastUpdatedAt precedes createdAt");if(M&&(r!==M.taskId||e!==M.createdAt))throw Error("MCP task identity changed across connection generation");let u=n.ttl===null?null:$(n.ttl,0,86400000,"MCP task ttl"),S=n.pollInterval===void 0?t.pollIntervalMs:$(n.pollInterval,0,Number.MAX_SAFE_INTEGER,"MCP task pollInterval"),m=Math.min(1e4,Math.max(100,S)),s=n.statusMessage?wM(n.statusMessage,r):void 0;return{taskId:r,status:n.status,createdAt:e,lastUpdatedAt:_,ttl:u,pollIntervalMs:m,...s?{statusMessage:s}:{}}}function Ir(n){return["completed","failed","cancelled"].includes(n)}function Rr(n){let t=n instanceof Error?n.message:String(n);return tt(rn(t.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")),1024)}function wM(n,t){return tt(rn(n.replaceAll(t,"[redacted-task-id]")),1024)}function rn(n){return[...n.normalize("NFKC")].filter((t)=>{let M=t.codePointAt(0)??0;if(M===0||M>=1&&M<=8||M===11||M===12||M>=14&&M<=31||M===127)return!1;return!bM.test(t)}).join("").trim()}function vn(n,t){let M=Date.parse(n);if(!Number.isFinite(M))throw Error(`MCP task ${t} is invalid`);return new Date(M).toISOString()}function aM(n,t,M){if(!n||Buffer.byteLength(n)>M||rn(n)!==n)throw Error(`MCP ${t} is invalid`);return n}function $(n,t,M,r){if(!Number.isSafeInteger(n)||n<t||n>M)throw Error(`${r} must be an integer between ${t} and ${M}`);return n}function tt(n,t){let M=Buffer.from(n);if(M.length<=t)return n;let r=M.subarray(0,t).toString("utf8");while(Buffer.byteLength(r)>t)r=r.slice(0,-1);return r}var PM={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function en(n){let t=n.toLowerCase().trim();return PM[t]??n}var LM=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/,xM=/^\.[A-Za-z0-9_+-]{1,32}$/;function Z(n){return n!==null&&typeof n==="object"&&!Array.isArray(n)}function p(n,t,M,r,e){if(n===void 0)return e;if(!Number.isInteger(n)||Number(n)<M||Number(n)>r)throw Error(`${t} must be an integer between ${M} and ${r}`);return Number(n)}function Mt(n,t){if(n===void 0)return;let M;try{M=JSON.stringify(n)}catch{throw Error(`${t} must be JSON serializable`)}if(M===void 0||Buffer.byteLength(M)>262144)throw Error(`${t} exceeds the 256 KiB limit`);return structuredClone(n)}function dM(n,t){if(n===void 0)return{};if(!Z(n))throw Error(`${t} must be an object`);let M={};for(let[r,e]of Object.entries(n)){if(!r||typeof e!=="string"||e.includes("\x00"))throw Error(`${t} must contain non-empty string values`);M[r]=e}return M}function h(n){if(n===void 0)return{};if(!Z(n))throw Error("lspServers must be an object");let t=Object.entries(n);if(t.length>32)throw Error("lspServers exceeds the 32-server limit");let M={};for(let[r,e]of t){if(!LM.test(r))throw Error(`Invalid LSP server name: ${r}`);if(!Z(e))throw Error(`lspServers.${r} must be an object`);let _=new Set(["command","args","extensionToLanguage","env","initializationOptions","settings","enabled","priority","startupTimeout","shutdownTimeout","requestTimeout","diagnosticWaitTimeout","maxRestarts"]),u=Object.keys(e).filter((w)=>!_.has(w));if(u.length>0)throw Error(`Unknown LSP server field: ${r}.${u[0]}`);if(typeof e.command!=="string"||!e.command.trim()||e.command.includes("\x00")||e.command.includes(`
22
- `))throw Error(`lspServers.${r}.command must be a non-empty command`);if(e.args!==void 0&&!Array.isArray(e.args))throw Error(`lspServers.${r}.args must be an array`);let S=(e.args??[]).map((w,c)=>{if(typeof w!=="string"||w.includes("\x00"))throw Error(`lspServers.${r}.args.${c} must be a string`);return w});if(S.length>128)throw Error(`lspServers.${r}.args exceeds the 128-item limit`);if(!Z(e.extensionToLanguage))throw Error(`lspServers.${r}.extensionToLanguage must be an object`);let m=Object.entries(e.extensionToLanguage);if(m.length===0||m.length>64)throw Error(`lspServers.${r}.extensionToLanguage must contain 1-64 entries`);let s={};for(let[w,c]of m){let N=w.startsWith(".")?w.toLowerCase():`.${w.toLowerCase()}`;if(!xM.test(N)||typeof c!=="string"||!c.trim())throw Error(`Invalid lspServers.${r}.extensionToLanguage entry: ${w}`);s[N]=c.trim()}if(e.enabled!==void 0&&typeof e.enabled!=="boolean")throw Error(`lspServers.${r}.enabled must be a boolean`);let A=Mt(e.initializationOptions,`lspServers.${r}.initializationOptions`),P=Mt(e.settings,`lspServers.${r}.settings`);M[r]={command:e.command.trim(),...S.length>0?{args:S}:{},extensionToLanguage:s,...e.env!==void 0?{env:dM(e.env,`lspServers.${r}.env`)}:{},...A!==void 0?{initializationOptions:A}:{},...P!==void 0?{settings:P}:{},...e.enabled!==void 0?{enabled:e.enabled}:{},priority:p(e.priority,`lspServers.${r}.priority`,-1000,1000,0),startupTimeout:p(e.startupTimeout,`lspServers.${r}.startupTimeout`,100,60000,1e4),shutdownTimeout:p(e.shutdownTimeout,`lspServers.${r}.shutdownTimeout`,100,1e4,2000),requestTimeout:p(e.requestTimeout,`lspServers.${r}.requestTimeout`,100,60000,1e4),diagnosticWaitTimeout:p(e.diagnosticWaitTimeout,`lspServers.${r}.diagnosticWaitTimeout`,0,5000,750),maxRestarts:p(e.maxRestarts,`lspServers.${r}.maxRestarts`,0,10,3)}}return M}function rt(n){return Number.isInteger(n)&&(n===-1||n>=0)}function et(){return"-1 (unlimited), 0 (disabled), or any positive integer"}import ut from"node:path";var _t=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,hM=/^(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;function z(n){let t=[];for(let[M,r]of Object.entries(n)){if(!_t.test(M))throw Error(`Invalid plugin name in enabledPlugins: ${M}`);if(typeof r!=="boolean")throw Error(`Invalid enabledPlugins value for ${M}`);t.push([M,r])}return Object.fromEntries(t)}function un(n,t,M){if(!Array.isArray(n))throw Error(`${t} must be an array`);return[...new Set(n.map((r,e)=>{if(typeof r!=="string"||!r.trim())throw Error(`${t}[${e}] must be a non-empty string`);return M(r.trim())}))].sort()}function B(n){let t=new Set(["restrictToAllowedSources","requireGitCommitSha","allowedGitHosts","allowedMarketplaces","allowedLocalRoots"]),M=Object.keys(n).filter((e)=>!t.has(e));if(M.length>0)throw Error(`Unknown pluginSourcePolicy fields: ${M.join(", ")}`);let r={};for(let e of["restrictToAllowedSources","requireGitCommitSha"]){if(n[e]===void 0)continue;if(typeof n[e]!=="boolean")throw Error(`pluginSourcePolicy.${e} must be boolean`);r[e]=n[e]}if(n.allowedGitHosts!==void 0)r.allowedGitHosts=un(n.allowedGitHosts,"pluginSourcePolicy.allowedGitHosts",(e)=>{let _=e.toLowerCase();if(!hM.test(_))throw Error(`Invalid plugin Git host pattern: ${e}`);return _});if(n.allowedMarketplaces!==void 0)r.allowedMarketplaces=un(n.allowedMarketplaces,"pluginSourcePolicy.allowedMarketplaces",(e)=>{if(!_t.test(e))throw Error(`Invalid allowed Marketplace name: ${e}`);return e});if(n.allowedLocalRoots!==void 0)r.allowedLocalRoots=un(n.allowedLocalRoots,"pluginSourcePolicy.allowedLocalRoots",(e)=>{if(!ut.isAbsolute(e))throw Error(`Plugin local allowlist root must be absolute: ${e}`);return ut.resolve(e)});return r}function W(n){let t=[];for(let[M,r]of Object.entries(n)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(M))throw Error(`Invalid environment variable name: ${M}`);if(typeof r!=="string"||r.includes("\x00"))throw Error(`Invalid environment variable value: ${M}`);t.push([M,r])}return Object.fromEntries(t)}var St=1,mt=64,Et=1,st=1e4;function ot(n){return Number.isInteger(n)&&n>=1&&n<=64}function Tt(n){return Number.isInteger(n)&&n>=1&&n<=1e4}class C{static instance=null;runtimePermissionOverrides;lastAdditionalSettings;constructor(){}static getInstance(){if(!C.instance)C.instance=new C;return C.instance}static resetInstance(){C.instance=null}async initialize(n){try{this.lastAdditionalSettings=n,this.runtimePermissionOverrides=n?.permissions;let M=(await d.getInstance().getStatus(a())).state==="trusted",r=await this.loadConfigFiles(M),e=await this.loadSettingsFiles(M),_={...r,...e,enabledPlugins:{...r.enabledPlugins||{},...e.enabledPlugins||{}}};if(n)_=this.mergeSettings(_,n);let u=this.normalizeConfig(_),S={...T,...u};if(S.enabledPlugins=z(S.enabledPlugins),S.lspServers=h(S.lspServers),S.pluginSourcePolicy={...T.pluginSourcePolicy,...B(S.pluginSourcePolicy)},this.resolveEnvInterpolation(S),process.env.BLADE_MODEL&&S.models?.length>0){let m=en(process.env.BLADE_MODEL),s=S.models.find((A)=>A.id===m||A.model===m||A.id===process.env.BLADE_MODEL||A.model===process.env.BLADE_MODEL);if(s)S.currentModelId=s.id}if(process.env.BLADE_DEBUG)S.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(J().configureModelProviders(S.modelProviders,S.models),S.models.length>0)this.validateConfig(S);if(S.debug)console.log("[ConfigManager] Configuration loaded successfully");return S}catch(t){return console.error("[ConfigManager] Failed to initialize:",t),J().configureModelProviders({},[]),T}}async reload(){return this.initialize(this.lastAdditionalSettings)}async loadConfigFiles(n){let t=E.join(b.homedir(),".blade","config.json"),M=E.join(a(),".blade","config.json"),r={},e=await this.loadJsonFile(t),_=e?await this.migrateLegacyUserConfig(e):null;if(_)r={...r,..._};let u=await this.loadJsonFile(M);if(u&&n){let S={...r.mcpServers||{},...u.mcpServers||{}},m={...r.lspServers||{},...u.lspServers||{}},s={...r.modelProviders||{},...u.modelProviders||{}},A={...r.enabledPlugins||{},...u.enabledPlugins||{}};if(r={...r,...u},Object.keys(S).length>0)r.mcpServers=S;if(Object.keys(m).length>0)r.lspServers=h(m);if(Object.keys(s).length>0)r.modelProviders=s;if(Object.keys(A).length>0)r.enabledPlugins=z(A)}else if(u?.hooks)r.hooks=u.hooks;return r}async migrateLegacyUserConfig(n){let t=n,M={...n},r={};if(M.codeTheme===void 0&&typeof t.theme==="string")M.codeTheme=t.theme,r.codeTheme=t.theme;if(Array.isArray(M.models)){let e=Bn(M.models,M.currentModelId??"");if(e.changed)M.models=e.models,M.currentModelId=e.currentModelId,r.models=e.models,r.currentModelId=e.currentModelId}if(delete M.theme,Object.keys(r).length>0)try{await x.getInstance().save(r,{scope:"global",immediate:!0})}catch{console.warn("[ConfigManager] Could not persist legacy config migration")}return M}async loadSettingsFiles(n){let t=E.join(b.homedir(),".blade","settings.json"),M=E.join(a(),".blade","settings.json"),r=E.join(a(),".blade","settings.local.json"),e={},_=await this.loadJsonFile(t);if(_)e=this.mergeSettings(e,_);let u=await this.loadJsonFile(M);if(u&&n)e=this.mergeSettings(e,u);else if(u?.hooks)e=this.mergeSettings(e,{hooks:u.hooks});let S=await this.loadJsonFile(r);if(S&&n)e=this.mergeSettings(e,S);else if(S?.hooks)e=this.mergeSettings(e,{hooks:S.hooks});return e}async loadWorkspacePermissions(n,t){let M={allow:[...t.allow],ask:[...t.ask],deny:[...t.deny]};if(E.resolve(n)!==E.resolve(a())){let e=await this.loadWorkspacePermissionOverrides(a(),{includeUntrusted:!0}),_=await this.loadJsonFile(E.join(b.homedir(),".blade","settings.json")),u={allow:Array.from(new Set([...T.permissions.allow,..._?.permissions?.allow||[],...this.runtimePermissionOverrides?.allow||[]])),ask:Array.from(new Set([...T.permissions.ask,..._?.permissions?.ask||[],...this.runtimePermissionOverrides?.ask||[]])),deny:Array.from(new Set([...T.permissions.deny,..._?.permissions?.deny||[],...this.runtimePermissionOverrides?.deny||[]]))};for(let S of["allow","ask","deny"]){let m=new Set(e[S].filter((s)=>!u[S].includes(s)));M[S]=M[S].filter((s)=>!m.has(s))}}let r=await this.loadWorkspacePermissionOverrides(n);for(let e of["allow","ask","deny"])M[e]=Array.from(new Set([...M[e],...r[e]]));return M}async loadWorkspaceMcpServers(n,t){if(E.resolve(n)===E.resolve(a()))return{...t};let M=await d.getInstance().getStatus(n),r=M.state==="trusted",e=M.projectPath,_={},u=async(m)=>{let s=await this.loadJsonFile(m);if(s?.mcpServers)_={..._,...s.mcpServers}};if(await u(E.join(b.homedir(),".blade","config.json")),await u(E.join(b.homedir(),".blade","settings.json")),r)await u(E.join(e,".blade","config.json")),await u(E.join(e,".blade","settings.json")),await u(E.join(e,".blade","settings.local.json"));if(this.lastAdditionalSettings?.mcpServers)_={..._,...this.lastAdditionalSettings.mcpServers};let S={mcpServers:_};return this.resolveEnvInterpolation(S),S.mcpServers}async loadWorkspaceLspServers(n,t){if(E.resolve(n)===E.resolve(a()))return h(t);let M=await d.getInstance().getStatus(n),r={},e=async(u)=>{let S=await this.loadJsonFile(u);if(S?.lspServers)r={...r,...h(S.lspServers)}};if(await e(E.join(b.homedir(),".blade","config.json")),await e(E.join(b.homedir(),".blade","settings.json")),M.state==="trusted")for(let u of["config.json","settings.json","settings.local.json"])await e(E.join(M.projectPath,".blade",u));if(this.lastAdditionalSettings?.lspServers)r={...r,...h(this.lastAdditionalSettings.lspServers)};let _={lspServers:r};return this.resolveEnvInterpolation(_),h(_.lspServers)}async loadWorkspaceModelConfig(n,t){if(E.resolve(n)===E.resolve(a()))return{currentModelId:t.currentModelId,models:t.models.map((u)=>structuredClone(u)),modelProviders:structuredClone(t.modelProviders),temperature:t.temperature,...t.maxOutputTokens!==void 0?{maxOutputTokens:t.maxOutputTokens}:{},timeout:t.timeout,...t.providerCircuitBreakerOpenMs!==void 0?{providerCircuitBreakerOpenMs:t.providerCircuitBreakerOpenMs}:{},...t.providerRequestConcurrency!==void 0?{providerRequestConcurrency:t.providerRequestConcurrency}:{},...t.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:t.providerRequestAdmissionMs}:{},...t.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:t.providerRequestPendingBytes}:{}};let M=await d.getInstance().getStatus(n),r=M.projectPath,e={currentModelId:T.currentModelId,models:T.models.map((u)=>structuredClone(u)),modelProviders:structuredClone(T.modelProviders),temperature:T.temperature,...T.maxOutputTokens!==void 0?{maxOutputTokens:T.maxOutputTokens}:{},timeout:T.timeout,...T.providerCircuitBreakerOpenMs!==void 0?{providerCircuitBreakerOpenMs:T.providerCircuitBreakerOpenMs}:{},...T.providerRequestConcurrency!==void 0?{providerRequestConcurrency:T.providerRequestConcurrency}:{},...T.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:T.providerRequestAdmissionMs}:{},...T.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:T.providerRequestPendingBytes}:{}},_=(u)=>{if(!u)return;if(u.modelProviders)e.modelProviders={...e.modelProviders,...structuredClone(u.modelProviders)};if(u.models)e.models=u.models.map((S)=>structuredClone(S));if(u.currentModelId!==void 0)e.currentModelId=u.currentModelId;if(u.temperature!==void 0)e.temperature=u.temperature;if(u.maxOutputTokens!==void 0)e.maxOutputTokens=u.maxOutputTokens;if(u.timeout!==void 0)e.timeout=u.timeout;if(u.providerCircuitBreakerOpenMs!==void 0)e.providerCircuitBreakerOpenMs=u.providerCircuitBreakerOpenMs;if(u.providerRequestConcurrency!==void 0)e.providerRequestConcurrency=u.providerRequestConcurrency;if(u.providerRequestAdmissionMs!==void 0)e.providerRequestAdmissionMs=u.providerRequestAdmissionMs;if(u.providerRequestPendingBytes!==void 0)e.providerRequestPendingBytes=u.providerRequestPendingBytes};if(_(await this.loadJsonFile(E.join(b.homedir(),".blade","config.json"))),_(await this.loadJsonFile(E.join(b.homedir(),".blade","settings.json"))),M.state==="trusted")_(await this.loadJsonFile(E.join(r,".blade","config.json"))),_(await this.loadJsonFile(E.join(r,".blade","settings.json"))),_(await this.loadJsonFile(E.join(r,".blade","settings.local.json")));if(_(this.lastAdditionalSettings),e=this.normalizeConfig(e),this.resolveEnvInterpolation(e),process.env.BLADE_MODEL&&e.models.length>0){let u=process.env.BLADE_MODEL,S=en(u),m=e.models.find((s)=>s.id===S||s.model===S||s.id===u||s.model===u);if(m)e.currentModelId=m.id}if(!e.models.some((u)=>u.id===e.currentModelId))e.currentModelId=e.models[0]?.id??"";return e}async loadWorkspaceRuntimeSettings(n,t){if(E.resolve(n)===E.resolve(a()))return{env:W(t.env),disableAllHooks:t.disableAllHooks,maxTurns:t.maxTurns,permissionMode:t.permissionMode};let M=await d.getInstance().getStatus(n),r=M.projectPath,e={env:{},disableAllHooks:T.disableAllHooks,maxTurns:T.maxTurns,permissionMode:T.permissionMode},_=(m,s)=>{if(!m)return;if(s.allowExecutionSettings){if(m.env)e.env={...e.env,...W(m.env)};if(m.maxTurns!==void 0)e.maxTurns=m.maxTurns;if(m.permissionMode!==void 0)e.permissionMode=m.permissionMode;if(m.disableAllHooks!==void 0)e.disableAllHooks=m.disableAllHooks}else if(m.disableAllHooks===!0)e.disableAllHooks=!0};_(await this.loadJsonFile(E.join(b.homedir(),".blade","config.json")),{allowExecutionSettings:!0}),_(await this.loadJsonFile(E.join(b.homedir(),".blade","settings.json")),{allowExecutionSettings:!0});let u=await Promise.all([this.loadJsonFile(E.join(r,".blade","config.json")),this.loadJsonFile(E.join(r,".blade","settings.json")),this.loadJsonFile(E.join(r,".blade","settings.local.json"))]);for(let m of u)_(m,{allowExecutionSettings:M.state==="trusted"});_(this.lastAdditionalSettings,{allowExecutionSettings:!0});let S={env:e.env};return this.resolveEnvInterpolation(S),e.env=W(S.env),e}async loadWorkspacePluginSettings(n){return(await this.loadWorkspacePluginSettingsResolution(n)).effective}async loadWorkspacePluginSettingsResolution(n){let t=await d.getInstance().getStatus(n),M={},r={},e=(_,u,S)=>{if(!_?.enabledPlugins)return;let m=z(_.enabledPlugins);for(let[s,A]of Object.entries(m)){if(!S&&A!==!1)continue;let P=r[s];M[s]=A,r[s]={effective:A,effectiveScope:u,layers:{...P?.layers??{},[u]:A}}}};e(await this.loadJsonFile(E.join(b.homedir(),".blade","config.json")),"global",!0),e(await this.loadJsonFile(E.join(b.homedir(),".blade","settings.json")),"global",!0);for(let _ of["config.json","settings.json"])e(await this.loadJsonFile(E.join(t.projectPath,".blade",_)),"project",t.state==="trusted");return e(await this.loadJsonFile(E.join(t.projectPath,".blade","settings.local.json")),"local",t.state==="trusted"),e(this.lastAdditionalSettings,"invocation",!0),{effective:M,settings:r,workspaceTrusted:t.state==="trusted"}}async loadWorkspacePluginSourcePolicy(n){let t=await d.getInstance().getStatus(n),M={...T.pluginSourcePolicy,allowedGitHosts:[...T.pluginSourcePolicy.allowedGitHosts],allowedMarketplaces:[...T.pluginSourcePolicy.allowedMarketplaces],allowedLocalRoots:[...T.pluginSourcePolicy.allowedLocalRoots]},r=(u)=>{if(!u?.pluginSourcePolicy)return;Object.assign(M,B(u.pluginSourcePolicy))},e=(u,S)=>{if(!S)return u;if(u.length===0&&!M.restrictToAllowedSources)return S;let m=new Set(S);return u.filter((s)=>m.has(s))},_=(u)=>{if(!u?.pluginSourcePolicy)return;let S=B(u.pluginSourcePolicy);M.allowedGitHosts=e(M.allowedGitHosts,S.allowedGitHosts),M.allowedMarketplaces=e(M.allowedMarketplaces,S.allowedMarketplaces),M.allowedLocalRoots=e(M.allowedLocalRoots,S.allowedLocalRoots),M.restrictToAllowedSources=M.restrictToAllowedSources||S.restrictToAllowedSources===!0,M.requireGitCommitSha=M.requireGitCommitSha||S.requireGitCommitSha===!0};r(await this.loadJsonFile(E.join(b.homedir(),".blade","config.json"))),r(await this.loadJsonFile(E.join(b.homedir(),".blade","settings.json")));for(let u of["config.json","settings.json","settings.local.json"])_(await this.loadJsonFile(E.join(t.projectPath,".blade",u)));if(_(this.lastAdditionalSettings),process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true")M.requireGitCommitSha=!0;return M}async loadWorkspaceHooks(n,t,M={}){if(E.resolve(n)===E.resolve(a())&&M.includeBaseForCurrentWorkspace!==!1)return K({},t);let r=K({},T.hooks),e=[E.join(b.homedir(),".blade","settings.json"),E.join(n,".blade","settings.json"),E.join(n,".blade","settings.local.json")];for(let _ of e){let u=await this.loadJsonFile(_);if(u?.hooks)r=K({},r,u.hooks)}return r}async loadWorkspacePermissionOverrides(n,t={}){let M={allow:[],ask:[],deny:[]},r=(await d.getInstance().getStatus(n)).state==="trusted",e=[...r||t.includeUntrusted?[E.join(n,".blade","settings.json")]:[],...r||t.includeUntrusted?[E.join(n,".blade","settings.local.json")]:[]];for(let _ of e){let u=await this.loadJsonFile(_);if(!u?.permissions)continue;for(let S of["allow","ask","deny"])M[S]=Array.from(new Set([...M[S],...u.permissions[S]||[]]))}return M}mergeSettings(n,t){let M={...JSON.parse(JSON.stringify(n)),...JSON.parse(JSON.stringify(t))};if(t.permissions)M.permissions={allow:Array.from(new Set([...n.permissions?.allow||[],...t.permissions.allow||[]])),ask:Array.from(new Set([...n.permissions?.ask||[],...t.permissions.ask||[]])),deny:Array.from(new Set([...n.permissions?.deny||[],...t.permissions.deny||[]]))};if(t.hooks)M.hooks=K({},M.hooks,t.hooks);if(t.enabledPlugins)M.enabledPlugins={...n.enabledPlugins||{},...z(t.enabledPlugins)};if(t.pluginSourcePolicy)M.pluginSourcePolicy={...n.pluginSourcePolicy??T.pluginSourcePolicy,...B(t.pluginSourcePolicy)};if(t.env)M.env=K({},M.env,t.env);if(t.mcpServers)M.mcpServers={...M.mcpServers||{},...t.mcpServers};if(t.lspServers)M.lspServers={...M.lspServers||{},...h(t.lspServers)};if(t.disableAllHooks!==void 0)M.disableAllHooks=t.disableAllHooks;if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;return M}resolveEnvInterpolation(n){let t=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,M=(e)=>{if(typeof e==="string")return e.replace(t,(_,u,S,m)=>{return process.env[u]||m||_});if(Array.isArray(e))return e.map(M);if(typeof e==="object"&&e!==null){let _=e;for(let[u,S]of Object.entries(_))_[u]=M(S);return _}return e},r=n;for(let[e,_]of Object.entries(r))r[e]=M(_)}async loadJsonFile(n){try{if(await this.fileExists(n)){let t=await At.readFile(n,"utf-8");return JSON.parse(t)}}catch(t){console.warn(`[ConfigManager] Failed to load ${n}:`,t)}return null}async fileExists(n){try{return await At.access(n),!0}catch{return!1}}normalizeConfig(n){let t=JSON.parse(JSON.stringify(n));if(t.codeTheme===void 0&&typeof t.theme==="string")t.codeTheme=t.theme;delete t.theme;let M=(e)=>e.trim().replace(/^`|`$/g,""),r=(e)=>{for(let[_,u]of Object.entries(e))if(typeof u==="string")e[_]=M(u);else if(Array.isArray(u))u.forEach((S,m)=>{if(typeof S==="string")u[m]=M(S);else if(typeof S==="object"&&S!==null)r(S)});else if(typeof u==="object"&&u!==null)r(u)};return r(t),t}validateConfig(n,t=J()){let M=[];try{n.lspServers=h(n.lspServers)}catch(r){M.push(r instanceof Error?r.message:"Invalid LSP server configuration")}for(let[r,e]of Object.entries(n.mcpServers||{}))try{Hn(e),e.oauth=Q(e);let _=Gn(e);if(e.logging!==void 0)e.logging=_;if(e.sampling)e.sampling=Fn(e.sampling);if(e.tasks)e.tasks=nt(e.tasks)}catch(_){M.push(`MCP server "${r}": ${_ instanceof Error?_.message:"invalid sampling policy"}`)}for(let[r,e]of Object.entries(n.modelProviders||{}))if(M.push(...ct(r,e)),t.isReservedProviderId(r))M.push(`modelProviders.${r}: built-in provider ids cannot be overridden`);if(M.length===0)try{t.configureModelProviders(n.modelProviders||{},n.models)}catch(r){M.push(r instanceof Error?r.message:"Failed to configure custom model providers")}if(!n.models||n.models.length===0)M.push("没有可用的模型配置");if(!rt(n.maxTurns))M.push(`maxTurns 必须是 ${et()}`);if(!ot(n.maxConcurrentTasks))M.push(`maxConcurrentTasks 必须是 ${St}-${mt} 之间的整数`);if(!Tt(n.maxQueuedTasks))M.push(`maxQueuedTasks 必须是 ${Et}-${st} 之间的整数`);if(n.bashForegroundHandoffMs!==void 0&&!nn(n.bashForegroundHandoffMs))M.push("bashForegroundHandoffMs 必须是 0,或 "+`${$n}-${gn} 之间的整数`);if(n.providerForegroundRecoveryMs!==void 0&&!at(n.providerForegroundRecoveryMs))M.push("providerForegroundRecoveryMs 必须是 0,或 "+`${bt}-${wt} 之间的整数`);if(n.providerCircuitBreakerOpenMs!==void 0&&!xt(n.providerCircuitBreakerOpenMs))M.push("providerCircuitBreakerOpenMs 必须是 0,或 "+`${Pt}-${Lt} 之间的整数`);if(n.providerRequestConcurrency!==void 0&&!Xt(n.providerRequestConcurrency))M.push("providerRequestConcurrency 必须是 "+`${dt}-${ht} 之间的整数`);if(n.providerRequestAdmissionMs!==void 0&&!pt(n.providerRequestAdmissionMs))M.push("providerRequestAdmissionMs 必须是 0,或 "+`${ft}-${$t} 之间的整数`);if(n.providerRequestPendingBytes!==void 0&&!Ct(n.providerRequestPendingBytes))M.push("providerRequestPendingBytes 必须是 "+`${it}-${gt} 之间的整数`);if(n.models&&n.models.length>0){if(!n.currentModelId)M.push("未设置当前模型 ID");else if(!n.models.find((e)=>e.id===n.currentModelId))M.push(`当前模型 ID "${n.currentModelId}" 在 models 列表中不存在`);for(let r of n.models){let e=`模型 "${r.displayName||r.id}"`,_=["name","apiKey","baseUrl","maxContextTokens","maxOutputTokens","supportsThinking","thinkingBudget","thinkingMode"].filter((S)=>(S in r));if(_.length>0)M.push(`${e}: 不再支持旧字段 ${_.join(", ")};请重新配置模型`);if(!r.model)M.push(`${e}: model 字段必填`);if(!r.provider)M.push(`${e}: provider 字段必填`);if(r.overrides?.baseUrl&&!r.overrides.baseUrl.startsWith("http"))M.push(`${e}: overrides.baseUrl "${r.overrides.baseUrl}" 不是有效的 HTTP URL`);let u=r.overrides?.streamIdleTimeout;if(u!==void 0&&(!Number.isFinite(u)||u<1000))M.push(`${e}: overrides.streamIdleTimeout 必须至少为 1000ms`);try{t.getModel(r.provider,r.model)}catch{M.push(`${e}: 内置 catalog 中不存在 ${r.provider}/${r.model}`)}}}if(M.length>0)throw Error(`配置验证失败:
23
- ${M.map((r)=>` - ${r}`).join(`
24
- `)}
25
-
26
- `+`请通过以下方式之一提供配置:
27
- `+` 1. 首次启动: 运行 blade,系统会自动引导配置
28
- `+` 2. 添加模型: blade 后输入 /model add
29
- `+` 3. 初始化向导: 输入 /init
30
-
31
- `+`配置文件示例 (~/.blade/config.json):
32
- `+`{
33
- "currentModelId": "model-id-123",
34
- "models": [
35
- {
36
- "id": "model-id-123",
37
- `+` "displayName": "默认模型",
38
- `+` "provider": "deepseek",
39
- "model": "deepseek-v4-pro"
40
- }
41
- ]
42
- }
43
- `)}}function we(n,t={}){let M={...n};if(t.debug!==void 0)M.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((e)=>e.id===t.model))throw Error(`模型配置未找到: ${t.model}`);M.currentModelId=t.model}if(t.yolo===!0)M.permissionMode="yolo";else if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)M.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)M.maxQueuedTasks=t.maxQueuedTasks;return M.systemPrompt=t.systemPrompt,M.appendSystemPrompt=t.appendSystemPrompt,M.model=t.model,M.resumeSessionId=t.sessionId,M.forkSession=t.forkSession,M.allowedTools=t.allowedTools,M.disallowedTools=t.disallowedTools,M.mcpConfigPaths=t.mcpConfig,M.strictMcpConfig=t.strictMcpConfig,M.addDirs=t.addDir,M.outputFormat=t.outputFormat,M.inputFormat=t.inputFormat,M.print=t.print,M.includePartialMessages=t.includePartialMessages,M.replayUserMessages=t.replayUserMessages,M.agentsConfig=t.agents,M.settingSources=t.settingSources,M}
44
- export{H as Ke,Q as Le,i as Me,v as Ne,Pn as Oe,g as Pe,Hn as Qe,Ar as Re,V as Se,wr as Te,ar as Ue,Pr as Ve,Gn as We,_M as Xe,Lr as Ye,SM as Ze,xr as _e,Fn as $e,fr as af,$r as bf,gr as cf,Xr as df,pr as ef,nt as ff,Cr as gf,Nr as hf,Ir as if,Rr as jf,tr as kf,$n as lf,gn as mf,rr as nf,T as of,h as pf,lt as qf,B as rf,W as sf,St as tf,mt as uf,Et as vf,st as wf,ot as xf,Tt as yf,C as zf,we as Af};
@@ -1 +0,0 @@
1
- import{Ud as a,Vd as b,Wd as c}from"./chunk-yhw0pvyt.js";import"./chunk-x5s68axq.js";import"./chunk-gbbnjzy8.js";import"./chunk-b5b8fb9y.js";import"./chunk-atdeg922.js";import"./chunk-g9re8v25.js";import"./chunk-nhzdkxnx.js";import"./chunk-fz55cnws.js";import"./chunk-5ygv33qe.js";import"./chunk-x04xb9g3.js";import"./chunk-358zaryv.js";import"./chunk-5sbewyjn.js";import"./chunk-npgt73cg.js";import"./chunk-9neq5xrb.js";import"./chunk-22h5kh4z.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};