blade-code 0.10.24 → 0.10.26

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 (112) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-01n8k1jj.js +1 -0
  3. package/dist/{chunk-1gkpjhts.js → chunk-0q4jbbm5.js} +1 -1
  4. package/dist/{chunk-9c3jjbgd.js → chunk-1g5h4zv6.js} +1 -1
  5. package/dist/{chunk-xzdpdwhz.js → chunk-1hzj6s0f.js} +2 -2
  6. package/dist/chunk-1mh2285d.js +200 -0
  7. package/dist/{chunk-26zhy301.js → chunk-20kg90zt.js} +2 -2
  8. package/dist/{chunk-18n15nn8.js → chunk-35d5gdgw.js} +1 -1
  9. package/dist/{chunk-f8zz4se0.js → chunk-46yg6dfr.js} +2 -2
  10. package/dist/{chunk-f4ksxskk.js → chunk-4aem0m2n.js} +1 -1
  11. package/dist/chunk-58tpe6nx.js +44 -0
  12. package/dist/{chunk-phzy5kqq.js → chunk-58yqrbey.js} +1 -1
  13. package/dist/{chunk-5xph8r1k.js → chunk-5mtryjjc.js} +1 -1
  14. package/dist/chunk-5yr2c8gz.js +25 -0
  15. package/dist/chunk-6axhk4r7.js +2 -0
  16. package/dist/chunk-6k74z0eb.js +2 -0
  17. package/dist/{chunk-yac1ga9w.js → chunk-6srz3q5d.js} +1 -1
  18. package/dist/{chunk-d2kzet1k.js → chunk-7jv8thn1.js} +2 -2
  19. package/dist/{chunk-3fkj59nv.js → chunk-89gswfb2.js} +1 -1
  20. package/dist/{chunk-w56y2pvk.js → chunk-8htfb5zn.js} +2 -2
  21. package/dist/{chunk-hpmxmkzc.js → chunk-9ka0bdry.js} +1 -1
  22. package/dist/{chunk-m13jrgp9.js → chunk-a4cyec1y.js} +2 -2
  23. package/dist/chunk-aa28p37g.js +2 -0
  24. package/dist/chunk-acf5v2fv.js +2 -0
  25. package/dist/chunk-b5fegjt7.js +6 -0
  26. package/dist/chunk-bbjtt28z.js +1 -0
  27. package/dist/{chunk-6vfe3409.js → chunk-ct2x59pr.js} +1 -1
  28. package/dist/chunk-d9jz1edf.js +100 -0
  29. package/dist/chunk-dxgzyy09.js +1 -0
  30. package/dist/{chunk-j8ggq1z4.js → chunk-ebffhjma.js} +2 -2
  31. package/dist/{chunk-bp886b8j.js → chunk-edyxa2jw.js} +1 -1
  32. package/dist/{chunk-k2b95m2p.js → chunk-eqa706gn.js} +2 -2
  33. package/dist/chunk-f88wkyfm.js +1 -0
  34. package/dist/{chunk-aw8s1sej.js → chunk-fbc5zfq7.js} +1 -1
  35. package/dist/chunk-fkwqgqsw.js +1 -0
  36. package/dist/{chunk-m27w377p.js → chunk-fnt1z0y8.js} +1 -1
  37. package/dist/chunk-gahvpbbs.js +1 -0
  38. package/dist/{chunk-57q5wn4g.js → chunk-gn37wxwg.js} +1 -1
  39. package/dist/chunk-h2npwqz9.js +10 -0
  40. package/dist/{chunk-c674mmtj.js → chunk-jt55ct49.js} +2 -2
  41. package/dist/{chunk-xjqcc0nt.js → chunk-k99rbzqw.js} +1 -1
  42. package/dist/{chunk-wjqctwyr.js → chunk-kskg7crs.js} +26 -41
  43. package/dist/{chunk-p1dp2xgq.js → chunk-kvd5nexw.js} +1 -1
  44. package/dist/chunk-kwe0a3xw.js +1 -0
  45. package/dist/chunk-m7x4ya6m.js +1 -0
  46. package/dist/chunk-mqsxghqb.js +1 -0
  47. package/dist/chunk-nar8qz5t.js +1 -0
  48. package/dist/{chunk-5sw8j9ae.js → chunk-nt6xmzk0.js} +1 -1
  49. package/dist/chunk-p6nhdbdw.js +116 -0
  50. package/dist/{chunk-67ekta7b.js → chunk-pja0tttq.js} +1 -1
  51. package/dist/{chunk-my2jwz6y.js → chunk-px3t1rxa.js} +2 -2
  52. package/dist/chunk-pyfag66h.js +1 -0
  53. package/dist/chunk-q1papzdc.js +1 -0
  54. package/dist/{chunk-pccn8ndq.js → chunk-r46ws0q8.js} +2 -2
  55. package/dist/{chunk-bw7vknjr.js → chunk-rgafk34p.js} +1 -1
  56. package/dist/chunk-rth3jfdq.js +2 -0
  57. package/dist/{chunk-nqpcwa0k.js → chunk-rtktz9v1.js} +233 -231
  58. package/dist/{chunk-s14wmzm3.js → chunk-s1khjfye.js} +2 -2
  59. package/dist/{chunk-vns8g2rv.js → chunk-sprjrvn6.js} +1 -1
  60. package/dist/chunk-ss449b56.js +1 -0
  61. package/dist/{chunk-yaxapgbm.js → chunk-tg1mf1tf.js} +1 -1
  62. package/dist/{chunk-x6tns9d8.js → chunk-tnrrnzzv.js} +1 -1
  63. package/dist/chunk-v508x7cg.js +0 -0
  64. package/dist/chunk-vc2c8wkx.js +2 -0
  65. package/dist/chunk-vp50e95n.js +3 -0
  66. package/dist/chunk-wg8p9g0z.js +1 -0
  67. package/dist/chunk-xkb48pvz.js +1 -0
  68. package/dist/{chunk-t327cwnb.js → chunk-xp44jtsd.js} +1 -1
  69. package/dist/chunk-y2en7qvs.js +6 -0
  70. package/dist/{chunk-86zsjamb.js → chunk-zs9mwd17.js} +3 -3
  71. package/dist/web/assets/{ChatView-CCxjYDmJ.js → ChatView-Crna6-ID.js} +2 -2
  72. package/dist/web/assets/{CodeBlockHighlighter-D9MqsrZP.js → CodeBlockHighlighter-coWjWCyT.js} +1 -1
  73. package/dist/web/assets/{FilePreview-Cn5HOlPw.js → FilePreview-BKcCbpvz.js} +2 -2
  74. package/dist/web/assets/{MarkdownRenderer-ALTOCdfi.js → MarkdownRenderer-BqV1nvf1.js} +3 -3
  75. package/dist/web/assets/{SettingsModal-Dk69F1bS.js → SettingsModal-BOMswk9P.js} +2 -2
  76. package/dist/web/assets/{TaskSwitcher-DRZZocE1.js → TaskSwitcher-BEW2DhW3.js} +1 -1
  77. package/dist/web/assets/{TerminalPanel-ByAqKZ47.js → TerminalPanel-BXzypTz6.js} +1 -1
  78. package/dist/web/assets/index-DqXKkjcp.js +11 -0
  79. package/dist/web/index.html +1 -1
  80. package/package.json +2 -1
  81. package/dist/chunk-014rwj5b.js +0 -1
  82. package/dist/chunk-0568ndm9.js +0 -200
  83. package/dist/chunk-1pkca2km.js +0 -3
  84. package/dist/chunk-2wpnzjme.js +0 -1
  85. package/dist/chunk-3ak60ndt.js +0 -1
  86. package/dist/chunk-3qmwt188.js +0 -100
  87. package/dist/chunk-4a02yjg9.js +0 -2
  88. package/dist/chunk-6pb6zs96.js +0 -2
  89. package/dist/chunk-7dqc10sc.js +0 -1
  90. package/dist/chunk-ag07wwer.js +0 -2
  91. package/dist/chunk-bpz0g8ej.js +0 -2
  92. package/dist/chunk-bvwq5wth.js +0 -6
  93. package/dist/chunk-c29y2s8g.js +0 -2
  94. package/dist/chunk-d70mtcp4.js +0 -1
  95. package/dist/chunk-e71qm105.js +0 -1
  96. package/dist/chunk-edqtngzr.js +0 -44
  97. package/dist/chunk-f0mt91sr.js +0 -1
  98. package/dist/chunk-gwe547ww.js +0 -1
  99. package/dist/chunk-m486vmtn.js +0 -1
  100. package/dist/chunk-n00mknme.js +0 -25
  101. package/dist/chunk-n54tp9wr.js +0 -1
  102. package/dist/chunk-pq7tk058.js +0 -6
  103. package/dist/chunk-q5sewfn5.js +0 -1
  104. package/dist/chunk-qg87zezq.js +0 -1
  105. package/dist/chunk-r14bz8va.js +0 -1
  106. package/dist/chunk-rtkhyp1g.js +0 -1
  107. package/dist/chunk-s4mqw4wa.js +0 -116
  108. package/dist/chunk-sgnjekfb.js +0 -1
  109. package/dist/chunk-tetxqw28.js +0 -1
  110. package/dist/chunk-vmzf4nvh.js +0 -2
  111. package/dist/chunk-zm3zn23k.js +0 -10
  112. package/dist/web/assets/index-CRCirUK7.js +0 -11
@@ -1,3 +0,0 @@
1
- import{j as T1,k as b1}from"./chunk-57q5wn4g.js";import{l as E$}from"./chunk-bp886b8j.js";import{r as b0}from"./chunk-9c3jjbgd.js";import{s as tO}from"./chunk-phzy5kqq.js";import{A as H$,B as h$,C as A0,D as g$,E as u0,F as Y$,I as u$,J as d$,L as nO,M as V1,N as N1,O as W1,P as F1,Q as U1,R as D1,S as _1,T as H1,U as B1,V as q1,Y as $4,ba as v1,u as g1,w as aO,x as n0,y as n$}from"./chunk-nqpcwa0k.js";import{ea as TO,ka as G0}from"./chunk-yaxapgbm.js";import{Aa as eO,Ba as $1,Ca as O1,Da as FO,Ea as OO,ma as C$,pa as u1,qa as d1,ra as sO,sa as rO,ta as l1,ua as t$,va as c1,wa as y0,xa as R1,ya as j1,za as k1}from"./chunk-3fkj59nv.js";import{$a as m$,Ka as C0,La as f,Ma as T,Na as oO,ib as f0}from"./chunk-0568ndm9.js";import{tb as uO}from"./chunk-4dnvydyv.js";import{Lb as dO,Nb as B$,Ub as lO,Vb as cO,Xb as a0,_b as f$,cc as iO,dc as P$,ec as y$,fc as j}from"./chunk-3qmwt188.js";import{_c as o,cd as jO,jd as N0}from"./chunk-n00mknme.js";import{ld as S$}from"./chunk-xjqcc0nt.js";import{xd as vO}from"./chunk-m27w377p.js";import{zd as _$}from"./chunk-d2kzet1k.js";import{Gd as f1,Hd as P1,Kd as K1,Od as J$,Pd as Z$,Td as x0}from"./chunk-wjqctwyr.js";import{be as kO,ce as pO}from"./chunk-5sw8j9ae.js";import{ge as AO,he as d0}from"./chunk-86zsjamb.js";import{pe as u}from"./chunk-w56y2pvk.js";import{Ee as qO,Te as MO,bf as O$}from"./chunk-edqtngzr.js";import{hf as S,jf as U,mf as Z0}from"./chunk-hpmxmkzc.js";import{of as A$}from"./chunk-bpz0g8ej.js";import{tf as g}from"./chunk-p1dp2xgq.js";import{yf as S0}from"./chunk-c674mmtj.js";import{Af as CO,Bf as hO,Df as RO,Ef as gO}from"./chunk-1gkpjhts.js";import{Gf as p0}from"./chunk-c29y2s8g.js";import{Lf as $O}from"./chunk-pccn8ndq.js";import{Qf as F$,Uf as _O}from"./chunk-s14wmzm3.js";import{Xf as s$}from"./chunk-vns8g2rv.js";var $5={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 O5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as JO,readFileSync as V$}from"node:fs";import{createServer as S2}from"node:http";import{networkInterfaces as f2}from"node:os";import{dirname as P2,extname as y2,join as I0}from"node:path";import{fileURLToPath as m2}from"node:url";import{brotliCompressSync as h2,gzipSync as g2,constants as v2}from"node:zlib";import{Hono as p2}from"hono";import{cors as u2}from"hono/cors";import{WebSocketServer as d2}from"ws";var g0=u("Service"),X4=30000,K4=new Set(["completed","failed","cancelled","interrupted"]);class R${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor($){this.dispatch=$.dispatch,this.store=$.store??FO.getInstance(),this.tickMs=$.tickMs??X4}start(){if(this.timer)return;g0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=T.subscribe(($)=>{if($.type!=="task.status")return;let O=$.properties.taskStatus;if(typeof O!=="string"||!K4.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,g0.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){g0.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}),g0.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??V4($),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}),G=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:C$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastRunSessionId:Y.session.sessionId,lastStatus:Y.status,lastError:void 0,runCount:$.runCount+1,nextRunAt:G?G.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled}),T.publish({sessionId:Y.session.sessionId,projectPath:$.projectPath},"schedule.fired",{scheduleId:$.id,firedAt:Z,sessionId:Y.session.sessionId,runId:Y.runId,status:Y.status}),g0.info(`[TaskScheduler] Fired schedule ${$.id} -> session ${Y.session.sessionId} (${Y.status})`)}catch(Y){let G=Y instanceof Error?Y.message:String(Y);g0.warn(`[TaskScheduler] Schedule ${$.id} dispatch failed:`,Y);let X=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:C$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastStatus:"error",lastError:G,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((G)=>G.lastRunSessionId===$);if(!Y)return;await this.store.update(Y.id,{lastStatus:O,...J?{lastError:J}:{lastError:void 0}})}}function V4($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class s 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 I extends s{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class _ extends s{constructor($){super("BAD_REQUEST",$,400)}}class R extends s{constructor($){super("CONFLICT",$,409)}}class v0 extends s{constructor($){super("TOO_MANY_REQUESTS",$,429)}}class V0 extends s{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class d extends s{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var X5=U.Object({error:U.Object({code:U.String(),message:U.String()})});import{Hono as N4}from"hono";var j$=u("Service"),W4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(Z0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function F4($){return{currentModelId:$.currentModelId,permissionMode:$.permissionMode,language:$.language,theme:$.theme,uiTheme:$.uiTheme,autoSaveSessions:$.autoSaveSessions,notifyBuild:$.notifyBuild,notifyErrors:$.notifyErrors,notifySounds:$.notifySounds,privacyTelemetry:$.privacyTelemetry,privacyCrash:$.privacyCrash,communicationStyle:$.communicationStyle,maxConcurrentTasks:$.maxConcurrentTasks,maxQueuedTasks:$.maxQueuedTasks}}var UO=()=>{let $=new N4;return $.get("/",async(O)=>{try{let J=o();return O.json(J?F4(J):{})}catch(J){return j$.error("[ConfigRoutes] Failed to get config:",J),O.json({})}}),$.put("/",async(O)=>{try{let J=await O.req.json(),Z=S(W4,J);if(!Z.success)throw new _("Invalid config update format");let{updates:Y,options:G}=Z.data;return await N0().updateConfig(Y,G),O.json({success:!0,updates:Y})}catch(J){throw j$.error("[ConfigRoutes] Failed to update config:",J),J}}),$.get("/permissions",async(O)=>{try{let J=o();return O.json(J?.permissions||{})}catch(J){return j$.error("[ConfigRoutes] Failed to get permissions:",J),O.json({})}}),$};import{Hono as U4}from"hono";import{streamSSE as D4}from"hono/streaming";var _4=15000,H4=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),B4=new Set(["queued","running","completed","failed","cancelled","interrupted"]);function L4($){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 $$($,O){return typeof $==="number"&&Number.isInteger($)&&$>=O?$:void 0}function w4($){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}:{},...$$(O.changedFiles,0)!==void 0?{changedFiles:O.changedFiles}:{},...typeof O.message==="string"?{message:O.message}:{}}}var DO=()=>{let $=new U4;return $.get("/",(O)=>D4(O,async(J)=>{let Z,Y,G=!1,X=()=>{if(Y!==void 0)clearInterval(Y),Y=void 0;Z?.(),Z=void 0},V=()=>{if(G)return;G=!0,X()};J.onAbort(V),Z=T.subscribe((W)=>{if(!H4.has(W.type))return;if(W.type==="permission.asked"||W.type==="question.required"||W.type==="elicitation.required"){let w=W.properties.requestId;if(typeof w!=="string"||!w)return;J.writeSSE({data:JSON.stringify({type:"interaction.pending",properties:{sessionId:W.sessionId,projectPath:W.projectPath,interactionType:W.type==="question.required"?"question":W.type==="elicitation.required"?"elicitation":"permission",requestId:w}})}).catch(V);return}if(W.type==="interaction.resolved"){let w=W.properties.requestId;if(typeof w!=="string"||!w)return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,requestId:w}})}).catch(V);return}if(W.type==="session.created"||W.type==="session.deleted"){J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath}})}).catch(V);return}if(W.type==="session.updated"){let w=W.properties.title;if(typeof w!=="string"||!w.trim())return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,title:w}})}).catch(V);return}if(W.type==="task.delivery"){let w=w4(W.properties.taskDelivery);if(!w)return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,taskDelivery:w,...W.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{}}})}).catch(V);return}if(W.type==="schedule.fired"){let w=W.properties.scheduleId,a=W.properties.firedAt;if(typeof w!=="string"||typeof a!=="string")return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{scheduleId:w,firedAt:a,sessionId:W.sessionId,projectPath:W.projectPath,...typeof W.properties.runId==="string"?{runId:W.properties.runId}:{},...typeof W.properties.status==="string"?{status:W.properties.status}:{}}})}).catch(V);return}let H=W.properties.taskStatus;if(typeof H!=="string"||!B4.has(H))return;let q=L4(W.properties.taskDiffStat),b=$$(W.properties.taskQueuePosition,1),C=$$(W.properties.taskQueueDepth,0),c=$$(W.properties.taskConcurrencyLimit,1),r=$$(W.properties.taskInFlight,0);J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,taskStatus:H,...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}:{},...q?{taskDiffStat:q}:{},...b!==void 0?{taskQueuePosition:b}:{},...C!==void 0?{taskQueueDepth:C}:{},...c!==void 0?{taskConcurrencyLimit:c}:{},...r!==void 0?{taskInFlight:r}:{}}})}).catch(V)});try{if(J.aborted||G)return;if(await J.writeSSE({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),J.aborted||G)return;Y=setInterval(()=>{if(J.aborted||G)return;J.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(V)},_4);while(!J.aborted&&!G)await new Promise((W)=>setTimeout(W,1000))}finally{V()}})),$};import{Hono as A4}from"hono";var HO=()=>{let $=new A4;return $.get("/health",(O)=>{return O.json({healthy:!0,version:p0()})}),$.get("/info",(O)=>{let J=g(),Z=o();if(Z)u0.configure(Z.maxConcurrentTasks,Z.maxQueuedTasks);return O.json({version:p0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:J,gitBranch:_O(J),taskAdmission:u0.getStats()})}),$};import BO from"node:path";import{Hono as M4}from"hono";var E4=U.Object({projectPath:U.String({minLength:1}),action:Z0(["trust","revoke"]),expectedDigest:U.Optional(U.String())}),q4=U.Object({projectPath:U.String({minLength:1}),sessionId:U.String({minLength:1}),enabled:U.Boolean()});function k$($){if(!$||!BO.isAbsolute($))throw new _("projectPath must be absolute");return BO.resolve($)}function LO($){if(!$)throw new _("sessionId is required");try{F$($)}catch(O){throw new _(O instanceof Error?O.message:"sessionId is invalid")}return $}async function W$($){let O=k$($),J=o()?.hooks??MO.hooks,Z=await O$.getInstance().loadWorkspaceHooks(O,J,{includeBaseForCurrentWorkspace:!1});await x0(O),Z$(O);let Y=d0.getInstance();return Y.loadConfig(Z,O),await J$(O),Y.getConfig(O)}function wO($,O){let J=d0.getInstance(),Z=J.getConfig(O).enabled,Y=J.isSessionPaused($,O);return{sessionId:$,projectPath:O,enabled:J.isSessionEnabled($,O),paused:Y,configEnabled:Z}}var EO=()=>{let $=new M4;return $.get("/trust",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return await W$(J),O.json(await d0.getInstance().getTrustStatus(J))}),$.post("/trust",async(O)=>{let J=S(E4,await O.req.json());if(!J.success)throw new _("Invalid hook trust request");let{projectPath:Z,action:Y,expectedDigest:G}=J.data;await W$(Z);let X=d0.getInstance(),V;try{V=Y==="trust"?await X.trustProject(Z,G):await X.revokeProjectTrust(Z)}catch(W){if(W instanceof AO)throw new R(W.message);throw W}return O.json(V)}),$.get("/session",async(O)=>{let J=k$(O.req.query("projectPath")),Z=LO(O.req.query("sessionId"));return await W$(J),O.json(wO(Z,J))}),$.post("/session",async(O)=>{let J=S(q4,await O.req.json());if(!J.success)throw new _("Invalid hook session request");let Z=k$(J.data.projectPath),Y=LO(J.data.sessionId);await W$(Z);let G=d0.getInstance();if(J.data.enabled)G.enableSession(Y,Z);else G.disableSession(Y,Z);return O.json(wO(Y,Z))}),$};import{Hono as T4}from"hono";var w0=u("Service");function b4($){try{return TO($)}catch{return[]}}function C4($){if(!U$($)||!U$($.reference)||!U$($.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(!U$($.context))throw Error("Invalid MCP completion context");Z=Object.create(null);for(let[Y,G]of Object.entries($.context)){if(typeof G!=="string")throw Error("Invalid MCP completion context");Z[Y]=G}}return{reference:J,argument:{name:$.argument.name,value:$.argument.value},...Z?{context:Z}:{}}}function U$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}async function q0($,O){let J=o()?.mcpServers??{};for(let[Z,Y]of Object.entries(J)){if(O&&Z!==O)continue;if(!$.getServerStatus(Z))await $.registerServer(Z,Y,{connect:!1})}}var bO=()=>{let $=new T4;return $.get("/",async(O)=>{try{let J=G0.getInstance();await q0(J);let Z=J.getAllServers(),Y=await Promise.all(Array.from(Z.entries()).map(async([G,X])=>({id:G,name:G,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: ${G}`,tools:X.tools.map((V)=>V.name),completionSupported:X.client.completionSupported,tasks:X.client.tasks,resources:X.contentCatalog.resources,resourceTemplates:X.contentCatalog.resourceTemplates.map((V)=>({...V,variables:b4(V.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 w0.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=G0.getInstance();return await q0(Z,J),await Z.connectServer(J),O.json({success:!0})}catch(J){return w0.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=G0.getInstance();return await q0(Z,J),await Z.disconnectServer(J),O.json({success:!0})}catch(J){return w0.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 G=G0.getInstance();return await q0(G,J),O.json(G.getLogSnapshot(J,{limit:Z,afterRevision:Y}))}catch(J){return w0.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(!qO(Z.level))return O.json({success:!1,error:"Invalid MCP logging level"},400);let Y=G0.getInstance();return await q0(Y,J),await Y.setServerLoggingLevel(J,Z.level),O.json({success:!0,level:Z.level})}catch(J){return w0.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=C4(await O.req.json()),Y=G0.getInstance();await q0(Y,J);let G=await Y.complete(J,Z);return O.json(G)}catch(J){return w0.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=G0.getInstance();await q0(Z,J);let Y=await Z.beginOAuthLogin(J);return O.json({success:!0,flowId:Y.flowId,authorizationUrl:Y.authorizationUrl},202)}catch(J){return w0.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=G0.getInstance();return await q0(Z,J),await Z.logoutOAuth(J),O.json({success:!0})}catch(J){return w0.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 G0.getInstance().unregisterServer(J);let Y=o();if(Y?.mcpServers){let{[J]:G,...X}=Y.mcpServers;await N0().updateConfig({mcpServers:X})}return O.json({success:!0})}catch(J){return w0.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 G0.getInstance().registerServer(Z,Y);let X=o();return await N0().updateConfig({mcpServers:{...X?.mcpServers,[Z]:Y}}),O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to add MCP server:",J),O.json({success:!1,error:J.message},500)}}),$};import{getSupportedThinkingLevels as R4}from"@earendil-works/pi-ai";import{Hono as j4}from"hono";var D$=u("Service");function k4($,O,J=kO.list()){return{id:$.id,displayName:$.displayName,provider:$.provider,model:$.model,overrides:$.overrides,fallbackModels:$.fallbackModels,contextWindow:O.contextWindow,maxTokens:O.maxTokens,reasoning:O.reasoning,supportedReasoningEfforts:R4(O),supportedServiceTiers:RO(O),supportedResponseVerbosities:CO(O),communicationStyles:J,input:O.input}}function I4($){IO($.overrides);let O={displayName:$.displayName||void 0,overrides:$.overrides||void 0};if($.model)O.model=$.model;return O}function IO($){let O=$?.streamIdleTimeout;if(O!==void 0&&(!Number.isFinite(O)||O<1000))throw new _("streamIdleTimeout must be at least 1000ms")}var SO=()=>{let $=new j4;return $.get("/",async(O)=>{try{let J=o();if(!J)throw Error("Config not initialized");let Z=O.get("directory")||g(),[Y,G]=await Promise.all([_$(Z,J),x0(Z)]),X=Y.config.models,V=X.find((b)=>b.id===Y.config.currentModelId)??X[0],W=Y.catalog,H=G.communicationStyles.list(),q=(b)=>k4(b,W.resolveConfig(b),H);return O.json({configured:X.map(q),current:V?q(V):null})}catch(J){D$.error("[ModelsRoutes] Failed to get models:",J);let Z=new d("Failed to get models");return O.json(Z.toObject(),500)}}),$.post("/",async(O)=>{let J=S0(),Z,Y;try{let G=await O.req.json(),{provider:X,displayName:V,model:W,overrides:H,apiKey:q,modelProvider:b}=G;if(!X||!W)throw new _("provider and model are required");IO(H);let C;if(b){if(b.id!==X)throw new _("modelProvider.id must match the model provider");if(o()?.modelProviders[X])throw new _(`model provider already exists: ${X}`);C={name:b.name,baseUrl:b.baseUrl,wireApi:b.wireApi,...b.apiKeyEnv?{apiKeyEnv:b.apiKeyEnv}:{}};try{J.registerModelProvider(X,C,[W]),Y=X}catch(w){throw new _(w instanceof Error?w.message:"Invalid model provider")}}else J.getModel(X,W);if(q?.trim()){if(await J.setApiKey(X,q.trim()),C)Z=X}let c={provider:X,displayName:V||void 0,model:W,overrides:H||void 0},r=C?await N0().addModelWithProvider(c,C):await N0().addModel(c);return O.json({success:!0,model:r})}catch(G){if(Z)await J.credentials.delete(Z);if(Y){let X=o();J.configureModelProviders(X?.modelProviders??{},X?.models??[])}throw D$.error("[ModelsRoutes] Failed to add model:",G),G}}),$.put("/:modelId",async(O)=>{try{let J=O.req.param("modelId"),Z=await O.req.json(),{displayName:Y,overrides:G,model:X}=Z,V=jO(J);if(!V)throw new _("model config not found");if(X)S0().getModel(V.provider,X);return await N0().updateModel(J,I4({displayName:Y,overrides:G,model:X})),O.json({success:!0})}catch(J){throw D$.error("[ModelsRoutes] Failed to update model:",J),J}}),$.delete("/:modelId",async(O)=>{try{let J=O.req.param("modelId");return await N0().removeModel(J),O.json({success:!0})}catch(J){throw D$.error("[ModelsRoutes] Failed to delete model:",J),J}}),$};import{Hono as a4}from"hono";import fO from"node:path";import{Mutex as PO}from"async-mutex";import{Hono as S4}from"hono";import{streamSSE as f4}from"hono/streaming";import{LRUCache as P4}from"lru-cache";import{nanoid as c0}from"nanoid";var P=u("Service"),y4=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),m4=eO,h4=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),g4=U.Object({projectPath:U.String()}),v4=U.Object({objective:U.String({minLength:1}),tokenBudget:U.Optional(U.Integer({minimum:1})),permissionMode:U.Optional(Z0(["default","autoEdit","plan","yolo"]))}),p4=U.Union([U.Object({action:U.Literal("pause")}),U.Object({action:U.Literal("resume")}),U.Object({action:U.Literal("edit"),objective:U.String({minLength:1})})]),l=new Map,L$,M0=new Map,i0=new Map,T0=new Map,M$=new P4({max:100,ttl:1800000});function yO($){return{sessionId:$.sessionId,projectPath:$.projectPath}}function Y0($){if(!$)return;return M0.get($)??M$.get($)}function u4($){if(M0.get($.id)!==$)return;M0.delete($.id),M$.set($.id,$)}function d4($){M0.delete($),M$.delete($)}function W0($){return $?.status==="queued"||$?.status==="running"||$?.status==="waiting_permission"}function w$($,O="user-cancel"){if($.status==="cancelled"||$.status==="completed"||$.status==="failed")return!1;let J=$.pendingPermission;if($.pendingPermission=void 0,J?.resolve({approved:!1,reason:uO}),J)T.publish(yO($),"interaction.resolved",{requestId:J.permissionId});return $.abortController.abort(O),$.status="cancelled",T.publish(yO($),"run.cancelled",{runId:$.id}),!0}function J1($,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 l4(){for(let $ of M0.values())w$($,"route-reset");M0.clear();for(let $ of i0.values())$.controller.abort("route-reset");i0.clear(),M$.clear(),L$=void 0,l.clear()}var Z1=($)=>{if(!$||typeof $!=="object")return $;let O={...$},J=200000,Z=(Y,G)=>typeof Y==="number"&&Number.isSafeInteger(Y)&&Y>=0&&Y<=G?Y:0;if(typeof O.oldContent==="string"&&O.oldContent.length>J)delete O.oldContent;if(typeof O.newContent==="string"&&O.newContent.length>J)delete O.newContent;if(O.mcpResult&&typeof O.mcpResult==="object"&&!Array.isArray(O.mcpResult)){let Y=O.mcpResult,G=Array.isArray(Y.artifacts)?Y.artifacts.slice(0,64).flatMap((X)=>{if(!X||typeof X!=="object"||Array.isArray(X))return[];let V=X,W=new Set(["text","image","audio","resource"]);if(typeof V.id!=="string"||!/^[a-f0-9]{64}$/.test(V.id)||typeof V.sha256!=="string"||V.sha256!==V.id||typeof V.kind!=="string"||!W.has(V.kind)||Z(V.size,67108864)!==V.size||typeof V.persisted!=="boolean")return[];return[{id:V.id.slice(0,128),sha256:V.sha256.slice(0,128),kind:V.kind,size:V.size,persisted:V.persisted,...typeof V.mimeType==="string"?{mimeType:V.mimeType.slice(0,256)}:{},...typeof V.sourceUri==="string"?{sourceUri:V.sourceUri.slice(0,8192)}:{},...typeof V.path==="string"?{path:V.path.slice(0,8192)}:{}}]}):[];O.mcpResult={isError:Y.isError===!0,contentCount:Z(Y.contentCount,64),textBytes:Z(Y.textBytes,4194304),structuredBytes:Z(Y.structuredBytes,4194304),artifactCount:Z(Y.artifactCount,64),truncated:Y.truncated===!0,binaryOmitted:Y.binaryOmitted===!0,artifacts:G}}else delete O.mcpResult;return O};function c4($,O,J){switch(J.kind){case"tool_start":if("function"in J.toolCall)T.publish($,"subagent.update",{subagentSessionId:O,toolName:J.toolCall.function.name}),T.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)T.publish($,"subagent.tool.result",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,success:!J.result.error,summary:J.result.metadata?.summary,output:d$(u$(J.toolCall.function.name,J.result)),metadata:Z1(J.result.metadata)});break;case"tool_progress":if("function"in J.toolCall)T.publish($,"subagent.tool.progress",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,...J.update});break;case"content_delta":T.publish($,"subagent.delta",{subagentSessionId:O,delta:J.delta});break;case"thinking_delta":T.publish($,"subagent.thinking.delta",{subagentSessionId:O,delta:J.delta});break;case"stream_end":T.publish($,"subagent.stream.end",{subagentSessionId:O});break;case"provider_retry":T.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});break;case"provider_stall":T.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"mcp_catalog_changed":T.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":T.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":T.publish($,"subagent.mcp.resource.updated",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,uri:J.uri});break;case"mcp_connection_changed":T.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":T.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":T.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":T.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":T.publish($,"subagent.project.rules.loaded",{subagentSessionId:O,files:J.files,triggerPaths:J.triggerPaths,blockedWrite:J.blockedWrite});break;default:break}}function z$($,O="projectPath"){if(!fO.isAbsolute($))throw new _(`${O} must be absolute`);return fO.resolve($)}function v$($){try{F$($)}catch(O){throw new _(O instanceof Error?O.message:`Invalid session ID: ${$}`)}}function e($){return{sessionId:$.id,projectPath:$.projectPath}}function Q$($,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 I$($){return $.flatMap((O)=>{if(O.role==="system"||O.role==="tool"&&O.name===a0)return[];let J=O.tool_calls?.filter((X)=>!("function"in X)||X.function.name!==a0),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}:{}},G=cO(O.metadata);return[G?{...Y,content:lO(G)}:Y]})}function x$($,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 P0($){let O=await j.findSessionMetadata($.id,$.projectPath);if(O)x$($,O)}function l0($){let O=Y0($.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 J0($,O){if(v$($),O!==void 0){let Z=C0({sessionId:$,projectPath:z$(O)});if(l.has(f(Z)))return Z;let Y=await j.findSessionMetadata(Z.sessionId,Z.projectPath);if(!Y)throw new I("Session",$);return C0({sessionId:Y.sessionId,projectPath:Y.projectPath})}let J=new Map;for(let Z of l.values()){if(Z.id!==$)continue;let Y=e(Z);J.set(f(Y),Y)}for(let Z of await j.listSessions()){if(Z.sessionId!==$)continue;let Y=C0({sessionId:Z.sessionId,projectPath:Z.projectPath});J.set(f(Y),Y)}if(J.size===0)try{let Z=await j.findSessionMetadata($);if(!Z)throw new I("Session",$);return C0({sessionId:Z.sessionId,projectPath:Z.projectPath})}catch(Z){if(Z instanceof I)throw Z;if(Z instanceof Error&&Z.message.startsWith("Ambiguous session ID:"))throw new V0;throw Z}if(J.size>1)throw new V0;return J.values().next().value}function p$($){if(typeof $==="string")return $;return $.filter((O)=>O.type==="text").map((O)=>O.text).join(`
2
- `)}function mO($,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 Y1=()=>{l4();let $=new S4;$.onError((x,N)=>{if(x instanceof s)return N.json(x.toObject(),x.statusCode);return P.error("[SessionRoutes] Unhandled route error:",x),N.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let O=new Map,J=new Map,Z=new Map,Y=new Map,G=new Map,X=new Map,V=(x)=>{let N=f(x),Q=G.get(N);if(!Q)Q=new PO,G.set(N,Q);return Q},W=(x)=>{let N=f(x),Q=X.get(N);if(!Q)Q=new PO,X.set(N,Q);return Q},H=async(x,N={})=>{let Q=f(e(x));await Z.get(Q);let K=O.get(Q);if(K)return K;let z=J.get(Q);if(!z){let F=N.communicationStyle??x.communicationStyle;z=Y$.create({sessionId:x.id,workspaceRoot:x.projectPath,...x.selectedModelId??x.taskModelId?{modelId:x.selectedModelId??x.taskModelId}:{},permissionMode:N.permissionMode??x.permissionMode??"default",...x.reasoningEffort?{reasoningEffort:x.reasoningEffort}:{},...x.serviceTier?{serviceTier:x.serviceTier}:{},...x.responseVerbosity?{responseVerbosity:x.responseVerbosity}:{},...F?{communicationStyle:F}:{},...F===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,z)}try{let F=await z;return O.set(Q,F),F}finally{if(J.get(Q)===z)J.delete(Q)}},q=async(x,N)=>{let Q=f(e(x)),K=Z.get(Q);if(!K)K=(async()=>{let z=J.get(Q);if(z)await z.catch(()=>{return});J.delete(Q);let F=N??O.get(Q);if(O.delete(Q),F){for(let[D,L]of O)if(L===F)O.delete(D)}await F?.dispose()})().finally(()=>{if(Z.get(Q)===K)Z.delete(Q)}),Z.set(Q,K);await K},b=async(x)=>{let N=f(x),Q=l.get(N);if(Q)return Q;let K=Y.get(N);if(!K)K=(async()=>{let z=await j.findSessionMetadata(x.sessionId,x.projectPath);if(!z)throw new I("Session",x.sessionId);let[F,D]=await Promise.all([j.loadSession(x.sessionId,x.projectPath),j.findSessionTaskWorktree(x.sessionId,x.projectPath)]),L=Q$(z,F,D);return l.set(N,L),L})(),Y.set(N,K);try{return await K}finally{if(Y.get(N)===K)Y.delete(N)}},C=async(x,N)=>{let Q=await J0(x,N);try{await j.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(K){if(K instanceof P$)throw new R(K.message);throw K}return b(Q)},c=async(x,N)=>{if(x.permissionMode===N)return;let Q=await j.setSessionPermissionMode(x.id,x.projectPath,N);x.permissionMode=Q.permissionMode,x.updatedAt=new Date(Q.lastMessageTime),T.publish(e(x),"session.updated",{permissionMode:N})},r=(x,N,Q,K={})=>{let z=c0(12),F={id:z,sessionId:x.id,projectPath:x.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:K.taskRuntime!==void 0,createdAt:new Date};if(K.taskRuntime){let D=K.taskRuntime,L=u0.admit({key:`${x.projectPath}\x00${x.id}`,...D.getTaskAdmissionLimits(),signal:F.abortController.signal,onUpdate:(A)=>{F.status=A.state,F.taskQueuePosition=A.queuePosition,F.taskQueueDepth=A.queueDepth,F.taskConcurrencyLimit=A.maxConcurrent,x.taskStatus=A.state,x.taskQueuePosition=A.queuePosition,x.taskQueueDepth=A.queueDepth,x.taskConcurrencyLimit=A.maxConcurrent,F.taskAdmissionUpdate=(F.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await D.setTaskAdmission(A)}).catch((B)=>{P.warn(`[SessionRoutes] Failed to persist admission for ${x.id}:`,B)})}});F.taskAdmission=L;let M=L.getSnapshot();F.status=M.state,F.taskQueuePosition=M.queuePosition,F.taskQueueDepth=M.queueDepth,F.taskConcurrencyLimit=M.maxConcurrent}return M0.set(z,F),x.currentRunId=z,F.completion=i4(F,x,N,Q,H,{pendingInputOnly:K.pendingInputOnly,preparedInputTurn:K.preparedInputTurn,goalContinuationOnly:K.goalContinuationOnly,outputSchema:K.outputSchema,taskAdmission:F.taskAdmission,disposeRuntime:q}).catch((D)=>{P.error(`[SessionRoutes] Run ${z} failed:`,D)}),F},w=async(x)=>{let N;if(x.outputSchema)try{N=f$(x.outputSchema).schema}catch(E){throw new _(E instanceof Error?E.message:"Invalid output schema")}let Q=S$("task",12),K=z$(x.sourceProjectPath),z=x.modelId?.trim(),F=o();if(!F)throw new _("Config not initialized");let[D,L]=await Promise.all([_$(K,F),x0(K)]);if(z&&!D.config.models.some((E)=>E.id===z))throw new _(`Task model not found: ${z}`);let M=z||D.config.models.find((E)=>E.id===D.config.currentModelId)?.id||D.config.models[0]?.id;if(!M)throw new _("No model is configured. Add or select a model before dispatching a task.");let A=D.config.models.find((E)=>E.id===M);if(!A)throw new _(`Task model not found: ${M}`);let B=x.reasoningEffort??"off",n=x.serviceTier??"auto",E0=x.responseVerbosity??"auto",X0=x.communicationStyle??"auto",K0,k=L.projectRules?.staticRules(K),v=k&&k.files.length>0?k.provenanceSha256:void 0;try{let E=D.catalog.resolveConfig(A);vO(E,B),gO(E,n),hO(E,E0);let h=pO(X0,L.communicationStyles);K0=h.source==="built-in"?void 0:h.contentSha256}catch(E){throw new _(E instanceof Error?E.message:"Invalid reasoning effort")}let r0={version:1,prompt:x.prompt,...x.title?{title:x.title}:{},sourceProjectPath:K,isolation:x.isolation,permissionMode:x.permissionMode,modelId:M,reasoningEffort:B,serviceTier:n,responseVerbosity:E0,communicationStyle:X0,...K0?{communicationStyleDigest:K0}:{},...v?{projectInstructionsDigest:v}:{},...x.attachments?{attachments:x.attachments.map((E)=>({...E}))}:{},...N?{outputSchema:N}:{}},H0,y;try{let E=await tO.createSessionTask({sessionId:Q,prompt:x.prompt,title:x.title,sourceProjectPath:K,isolation:x.isolation,dispatch:r0,retriedFrom:x.retriedFrom}),{metadata:h}=E;H0=E.taskWorktree,y=Q$(h,[],H0);let $0=e(y);l.set(f($0),y),T.publish($0,"task.status",{taskStatus:h.taskStatus,updatedAt:h.lastMessageTime});let t=mO(x.prompt,x.attachments),i=await H(y),F0=N?await i.prepareInputTurn(t,{outputSchema:N}):await i.prepareInputTurn(t);if(!F0.accepted)throw new R(`Task prompt was not accepted: ${F0.reason}`);let B0=r(y,t,x.permissionMode,{preparedInputTurn:F0,taskRuntime:i,outputSchema:N});return await B0.taskAdmissionUpdate,{session:l0(y),runId:B0.id,messageId:F0.messageId,status:B0.status==="queued"?"queued":"running",queuePosition:B0.taskQueuePosition,queueDepth:B0.taskQueueDepth,maxConcurrentTasks:B0.taskConcurrencyLimit}}catch(E){if(E instanceof g$&&y){let h=e(y),$0=f(h);if(H0)await A0.exit({sessionId:y.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await O.get($0)?.dispose().catch(()=>{return}),O.delete($0),await j.deleteSession(y.id,y.projectPath).catch(()=>{return}),l.delete($0),new v0("Task admission queue is full")}if(y){let h=await j.findSessionMetadata(y.id,y.projectPath).catch(()=>{return});if(!h||h.taskStatus==="queued"){let $0=B$(E),t=await j.updateSessionMetadata(y.id,y.projectPath,{taskStatus:"failed",taskStatusReason:$0.message,taskFailure:$0,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});y.taskStatus=t?.taskStatus??"failed",y.taskStatusReason=t?.taskStatusReason??$0.message,y.taskFailure=t?.taskFailure??$0,y.taskCompletedAt=t?.taskCompletedAt}else y.taskStatus=h.taskStatus,y.taskStatusReason=h.taskStatusReason,y.taskFailure=h.taskFailure,y.taskCompletedAt=h.taskCompletedAt}throw E}},a=async(x,N)=>{let Q=await J0(x,N),K=await j.findSessionMetadata(Q.sessionId,Q.projectPath);if(!K)throw new I("Session",Q.sessionId);if(!["failed","interrupted","cancelled"].includes(K.taskStatus))throw new R(`Task cannot be retried while status is ${K.taskStatus}`);let z=await j.findSessionTaskDispatch(Q.sessionId,Q.projectPath);if(!z)throw new R("Task retry payload is unavailable");return w({prompt:z.prompt,title:z.title,sourceProjectPath:z.sourceProjectPath,isolation:z.isolation,permissionMode:z.permissionMode,modelId:z.modelId,reasoningEffort:z.reasoningEffort,serviceTier:z.serviceTier,responseVerbosity:z.responseVerbosity,communicationStyle:z.communicationStyle,attachments:z.attachments,outputSchema:z.outputSchema,retriedFrom:Q})},m=async(x,N)=>{let Q=await C(x,N);if(!Q.taskWorktree)throw new _("Session does not have a task worktree");try{await A0.restoreSession(Q.taskWorktree);let K=await A0.getDiffArtifact(Q.id);if(!K)throw new R("Task diff artifact is unavailable");return{sessionId:Q.id,projectPath:Q.projectPath,...K}}catch(K){if(K instanceof R)throw K;throw P.error("[SessionRoutes] Failed to load task diff artifact:",K),new R("Task diff artifact is unavailable")}},O0=async(x,N,Q)=>{let K=await J0(x,Q);return W(K).runExclusive(async()=>{let z=await C(K.sessionId,K.projectPath);if(["queued","running"].includes(z.taskStatus))throw new R(`Task artifacts cannot be delivered while status is ${z.taskStatus}`);if(z.taskDelivery?.status==="applied")throw new R("Task changes have already been applied");if(z.taskDelivery?.status==="discarded")throw new R("Task changes have already been discarded");if(!z.taskWorktree)throw new R("Task worktree is unavailable");let F=async(D,L=!1)=>{let M=await j.updateSessionMetadata(z.id,z.projectPath,{taskDelivery:D,...L?{taskWorktree:null}:{}});if(x$(z,M),L)z.taskWorktree=void 0;return T.publish(K,"task.delivery",{taskDelivery:D,...L?{taskWorktreeRemoved:!0}:{},updatedAt:M.lastMessageTime}),l0(z)};try{if(N==="discard"){try{await A0.restoreSession(z.taskWorktree)}catch(M){return P.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${z.id}:`,M),F({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:z.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let L=await A0.exit({sessionId:z.id,action:"remove",discardChanges:!0});return F({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:L.discardedFiles??0,message:"Task worktree removed"},!0)}try{await A0.restoreSession(z.taskWorktree)}catch(L){throw P.warn(`[SessionRoutes] Task worktree is unavailable for ${z.id}:`,L),new h$("artifact_unavailable","Task worktree is unavailable")}let D=await A0.apply(z.id);return F({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:D.sourceCommit,changedFiles:D.changedFiles,message:"Task changes applied to the source workspace"})}catch(D){if(D instanceof h$)throw await F({status:"conflicted",updatedAt:new Date().toISOString(),message:D.message}),new R(D.message);throw D}})},Q0=async(x)=>{let N=Y0(x.currentRunId);if(W0(N))return;if(x.taskIsolation&&x.taskStatus!=="queued"&&x.taskStatus!=="running")return;let Q=await Y$.hasPendingInbox(x.projectPath,x.id),K=!Q&&await Y$.hasActiveGoal(x.projectPath,x.id);if(!Q&&!K)return;let z=await H(x),F=Y0(x.currentRunId);if(W0(F))return;if(Q&&z.getPendingSteeringCount()===0)await z.reloadPendingInbox();let D=z.getPendingSteeringCount()>0,M=(D?null:await z.getGoal())?.status==="active"||K;if(!D&&!M||z.hasTurnOwner())return;r(x,"",x.permissionMode??"default",{pendingInputOnly:D,goalContinuationOnly:M,...x.taskIsolation?{taskRuntime:z}:{}})};L$=Q0;let N$=async()=>{let x={scheduled:0,failed:0,deferred:0},N=(await j.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 N.entries()){let z={sessionId:K.sessionId,projectPath:K.projectPath};try{if(!await Y$.hasPendingInbox(K.projectPath,K.sessionId)){let D=B$("Queued task input is missing");await j.updateSessionMetadata(K.sessionId,K.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),x.failed++;continue}let F=await b(z);if(await Q0(F),F.currentRunId)x.scheduled++}catch(F){if(F instanceof g$){x.deferred+=N.length-Q;break}P.warn(`[SessionRoutes] Failed to recover queued task ${K.sessionId}:`,F),x.deferred++}}return x};return $.get("/",async(x)=>{try{let N=await j.listSessions(),Q=new Set(N.filter((A)=>A.relationType==="subagent").map((A)=>f({sessionId:A.sessionId,projectPath:A.projectPath}))),K=Array.from(l.values()).filter((A)=>!Q.has(f(e(A)))&&A.relationType!=="subagent").map((A)=>l0(A)),z=new Set(K.map((A)=>f({sessionId:A.sessionId,projectPath:A.projectPath}))),F=N.filter((A)=>{if(A.relationType==="subagent")return!1;return!z.has(f({sessionId:A.sessionId,projectPath:A.projectPath}))}),D=new Set(z),L=F.filter((A)=>{let B=f({sessionId:A.sessionId,projectPath:A.projectPath});if(D.has(B))return!1;return D.add(B),!0}),M=[...K,...L];return x.json(M)}catch(N){throw P.error("[SessionRoutes] Failed to list sessions:",N),new d("Failed to list sessions")}}),$.get("/catalog",async(x)=>{try{let N=x.req.query("limit"),Q=N===void 0?void 0:Number(N),K=x.req.query("cursor"),z=x.req.query("projectPath"),F=x.req.query("archived");if(F!==void 0&&F!=="true"&&F!=="false")throw new _("archived must be true or false");let D=F==="true",L=await j.listSessionPage({...z?{cwd:z$(z)}:{},...K?{cursor:K}:{},...Q===void 0?{}:{limit:Q},includeSubagents:!1,archived:D}),M=new Map((D?[]:Array.from(l.values())).filter((A)=>A.relationType!=="subagent").map((A)=>[f(e(A)),l0(A)]));return x.json({sessions:L.sessions.map((A)=>M.get(f({sessionId:A.sessionId,projectPath:A.projectPath}))??A),...L.nextCursor?{nextCursor:L.nextCursor}:{}})}catch(N){if(N instanceof _)throw N;if(N instanceof Error&&(N.message.startsWith("Invalid session cursor")||N.message.startsWith("Session cursor scope")||N.message.startsWith("Session catalog")))throw new _(N.message);throw P.error("[SessionRoutes] Failed to list session catalog:",N),new d("Failed to list session catalog")}}),$.post("/",async(x)=>{try{let N=await x.req.json(),Q=S(y4,N);if(!Q.success)throw new _("Invalid request body");let{title:K,projectPath:z}=Q.data,F=S$("web",12),D=z$(z||x.get("directory")||g(),z?"projectPath":"directory"),L=await j.createSessionMetadata(F,D,{title:K,taskStatus:"completed"}),M=Q$(L,[]),A=e(M);return l.set(f(A),M),T.publish(A,"session.created",{}),x.json({...l0(M),status:void 0,agentType:void 0,model:void 0})}catch(N){if(P.error("[SessionRoutes] Failed to create session:",N),N instanceof _)throw N;throw new d("Failed to create session")}}),$.get("/:sessionId/export",async(x)=>{let N=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 J0(N,x.req.query("projectPath")),z=await j.exportSessionMarkdown(K.sessionId,K.projectPath,{includeReasoning:Q==="true"});return x.body(z.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${z.filename}"`,"Content-Length":String(Buffer.byteLength(z.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":z.contentSha256,"X-Blade-Export-Activities":String(z.activityCount),"X-Blade-Export-Messages":String(z.messageCount),"X-Blade-Export-Redactions":String(z.redactionCount)})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof V0)throw Q;if(Q instanceof Error&&Q.message==="No conversation content to export")throw new R(Q.message);throw P.error("[SessionRoutes] Failed to export session:",Q),new d("Failed to export session")}}),$.post("/:sessionId/fork",async(x)=>{let N=x.req.param("sessionId");try{v$(N);let Q=await x.req.json(),K=S(g4,Q);if(!K.success)throw new _("Invalid request body");let z=z$(K.data.projectPath),F=await j.findSessionMetadata(N,z);if(!F)throw new I("Session",N);let D=await j.forkSession(N,{sourceProjectPath:F.projectPath,targetProjectPath:F.projectPath}),L=Q$(D.metadata,D.messages),M=e(L);return l.set(f(M),L),T.publish(M,"task.status",{taskStatus:D.metadata.taskStatus,...D.metadata.taskCompletedAt?{taskCompletedAt:D.metadata.taskCompletedAt}:{},updatedAt:D.metadata.lastMessageTime}),x.json({session:D.metadata,messages:I$(D.messages)},201)}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof R)throw Q;if(Q instanceof iO)throw new R("Session has no durable creation record");throw P.error("[SessionRoutes] Failed to fork session:",Q),new d("Failed to fork session")}}),$.get("/:sessionId",async(x)=>{let N=x.req.param("sessionId");try{let Q=await J0(N,x.req.query("projectPath")),K=l.get(f(Q));if(K)return x.json(l0(K));let z=await j.findSessionMetadata(Q.sessionId,Q.projectPath);if(!z)throw new I("Session",N);return x.json(z)}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof V0)throw Q;throw P.error("[SessionRoutes] Failed to get session:",Q),new d("Failed to get session")}}),$.patch("/:sessionId",async(x)=>{let N=x.req.param("sessionId");try{let Q=await x.req.json(),K=S(h4,Q);if(!K.success)throw new _("Invalid request body");if(K.data.title===void 0)throw new _("title is required");let z=await J0(N,K.data.projectPath),F=await j.updateSessionMetadata(z.sessionId,z.projectPath,{title:K.data.title}),D=l.get(f(z));if(D)D.title=F.title??D.title,D.updatedAt=new Date(F.lastMessageTime);if(F.title)T.publish(z,"session.updated",{title:F.title});return x.json({success:!0,title:F.title})}catch(Q){if(P.error("[SessionRoutes] Failed to update session:",Q),Q instanceof _||Q instanceof I||Q instanceof V0)throw Q;throw new d("Failed to update session")}}),$.get("/:sessionId/rewind",async(x)=>{let N=await C(x.req.param("sessionId"),x.req.query("projectPath")),Q=await H(N);return x.json({checkpoints:await Q.listRewindCheckpoints()})}),$.post("/:sessionId/rewind",async(x)=>{let N=S(sO,await x.req.json());if(!N.success)throw new _("Invalid rewind request");let Q=await C(x.req.param("sessionId"),x.req.query("projectPath")),K=e(Q);return V(K).runExclusive(async()=>{let z=Y0(Q.currentRunId);if(W0(z))throw new R("Cannot rewind while a run is active");let F=await H(Q),D;try{D=await F.rewindSession(N.data)}catch(M){if(M instanceof Error&&M.message.startsWith("Cannot rewind while"))throw new R(M.message);throw M}Q.messages=[...D.messages],Q.updatedAt=new Date;let L=I$(D.messages);return T.publish(K,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:L}),x.json({...D,messages:L})})}),$.get("/:sessionId/review",async(x)=>{let N=x.req.param("sessionId"),Q=await J0(N,x.req.query("projectPath")),K=await b0.list(Q.projectPath,Q.sessionId);return x.json({reviews:K.map((z)=>({...z,content:z.completion?dO(z.start,z.completion):void 0}))})}),$.post("/:sessionId/review",async(x)=>{let N=x.req.param("sessionId"),Q=S(O1,await x.req.json());if(!Q.success)throw new _("Invalid code review request");let K=await C(N,Q.data.projectPath),z=e(K),F=f(z);return V(z).runExclusive(async()=>{if(W0(Y0(K.currentRunId)))throw new R("Cannot start a review during an active turn");if(T0.has(F))throw new R("Session already has an active review");let D=await H(K);if(await b0.recoverInterrupted(z.projectPath,z.sessionId,D),Q.data.modelId&&!D.getModelById(Q.data.modelId))throw new _(`Model not found: ${Q.data.modelId}`);if(Q.data.modelId&&D.getCurrentModelId()!==Q.data.modelId)await D.refresh({modelId:Q.data.modelId});if(Q.data.modelId&&K.selectedModelId!==Q.data.modelId){let B=await j.updateSessionMetadata(K.id,K.projectPath,{selectedModelId:Q.data.modelId});x$(K,B)}let L=new AbortController,M;try{M=await b0.start({sessionId:z.sessionId,projectPath:z.projectPath,runtime:D,request:{kind:Q.data.kind,...Q.data.ref?{ref:Q.data.ref}:{},...Q.data.instructions?{instructions:Q.data.instructions}:{}},signal:L.signal,onEvent:(B)=>{if(B.kind==="tool_start")T.publish(z,"review.tool.started",{reviewId:M?.reviewId,toolCallId:B.toolCall.id,toolName:B.toolCall.function.name});else if(B.kind==="tool_progress")T.publish(z,"review.tool.progress",{reviewId:M?.reviewId,toolCallId:B.toolCall.id,message:B.update.message.slice(0,1000)});else if(B.kind==="tool_result")T.publish(z,"review.tool.completed",{reviewId:M?.reviewId,toolCallId:B.toolCall.id,success:B.result.success})}})}catch(B){if(B instanceof Error&&(B.message.includes("active review")||B.message.includes("interrupted review")||B.message.includes("active turn")))throw new R(B.message);if(B instanceof Error&&(B.message.includes("review")||B.message.includes("Git")||B.message.includes("changes")||B.message.includes("ref")))throw new _(B.message);throw B}if(!M)throw new d("Code review failed to start");await P0(K),T.publish(z,"review.started",{reviewId:M.reviewId,kind:Q.data.kind}),T.publish(z,"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 A=M.completion.then(async(B)=>{K.messages=await j.loadSession(z.sessionId,z.projectPath),await P0(K),T.publish(z,"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()}),T.publish(z,"review.completed",{reviewId:M.reviewId,status:B.status,findings:B.findings.length})}).catch((B)=>{P.error(`[SessionRoutes] Code review ${M.reviewId} failed:`,B)}).finally(()=>{if(T0.get(F)?.reviewId===M.reviewId)T0.delete(F)});return T0.set(F,{reviewId:M.reviewId,controller:L,completion:A}),x.json({reviewId:M.reviewId,status:"running"},202)})}),$.get("/:sessionId/subagents",async(x)=>{let N=await C(x.req.param("sessionId"),x.req.query("projectPath")),Q=await H(N);return x.json({subagents:Q.listSubagents().map(H$)})}),$.post("/:sessionId/subagents/:agentId/resume",async(x)=>{v$(x.req.param("agentId"));let N=rO.safeParse(await x.req.json());if(!N.success)throw new _("Invalid subagent resume request");let Q=await C(x.req.param("sessionId"),x.req.query("projectPath")),K=e(Q);return V(K).runExclusive(async()=>{let z=Y0(Q.currentRunId);if(W0(z))throw new R("Cannot resume a subagent while a parent run is active");let F=await H(Q),D=!1,L,M=(B)=>{T.publish(K,"subagent.complete",{subagentSessionId:B.id,success:B.status==="completed",status:B.status,summary:B.result?.message?.slice(0,500),type:B.subagentType,verificationVerdict:B.result?.verificationVerdict,resumedFrom:B.resumedFrom,rootAgentId:B.rootAgentId,resumeDepth:B.resumeDepth})},A;try{A=F.resumeSubagent({agentId:x.req.param("agentId"),prompt:N.data.prompt,onEvent:(B,n)=>{c4(K,n,B)},onCompleted:(B)=>{if(D)M(B);else L=B}})}catch(B){if(B instanceof Error&&(B.message.startsWith("Cannot resume")||B.message.startsWith("Subagent cannot")))throw new R(B.message);if(B instanceof Error&&B.message.startsWith("Subagent not found"))throw new I(B.message);throw B}if(T.publish(K,"subagent.start",{subagentSessionId:A.session.id,type:A.session.subagentType,description:A.session.description,resumedFrom:A.source.id,rootAgentId:A.session.rootAgentId,resumeDepth:A.session.resumeDepth}),D=!0,L)M(L);return x.json({source:H$(A.source),session:H$(A.session)})})}),$.get("/:sessionId/goal",async(x)=>{let N=await C(x.req.param("sessionId"),x.req.query("projectPath"));return x.json({goal:await new aO(N.projectPath,N.id).get()})}),$.put("/:sessionId/goal",async(x)=>{let N=S(v4,await x.req.json());if(!N.success)throw new _("Invalid goal request");let Q=await C(x.req.param("sessionId"),x.req.query("projectPath")),K=e(Q);return V(K).runExclusive(async()=>{let z=Y0(Q.currentRunId);if(W0(z))return x.json({status:"rejected",reason:"run_active"},409);let D=N.data.permissionMode??Q.permissionMode??"default";if(Q.permissionMode!==D)await c(Q,D);let L=await H(Q),M=await L.createGoal(N.data);T.publish(K,"goal.updated",{goal:M});let A=r(Q,"",D,{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:L}:{}});return await A.taskAdmissionUpdate,x.json({status:A.status==="queued"?"queued":"running",runId:A.id,goal:M,queuePosition:A.taskQueuePosition,queueDepth:A.taskQueueDepth,maxConcurrentTasks:A.taskConcurrencyLimit},202)})}),$.patch("/:sessionId/goal",async(x)=>{let N=S(p4,await x.req.json());if(!N.success)throw new _("Invalid goal update");let Q=await C(x.req.param("sessionId"),x.req.query("projectPath")),K=e(Q);return V(K).runExclusive(async()=>{let z=await H(Q),F;if(N.data.action==="pause")F=await z.pauseGoal();else if(N.data.action==="edit")F=await z.editGoal(N.data.objective);else F=await z.resumeGoal();if(T.publish(K,"goal.updated",{goal:F}),F.status==="active"&&!W0(Y0(Q.currentRunId))){let D=r(Q,"","default",{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:z}:{}});return await D.taskAdmissionUpdate,x.json({status:D.status==="queued"?"queued":"running",runId:D.id,goal:F,queuePosition:D.taskQueuePosition,queueDepth:D.taskQueueDepth,maxConcurrentTasks:D.taskConcurrencyLimit},202)}return x.json({status:F.status,goal:F})})}),$.delete("/:sessionId/goal",async(x)=>{let N=await C(x.req.param("sessionId"),x.req.query("projectPath")),Q=e(N),z=await(await H(N)).clearGoal();if(z)T.publish(Q,"goal.cleared",{});return x.json({cleared:z})}),$.post("/:sessionId/archive",async(x)=>{let N=x.req.param("sessionId");try{let Q=await J0(N,x.req.query("projectPath")),K=await j.listSessionArchiveMembers(Q.sessionId,Q.projectPath);for(let F of K){let D=C0({sessionId:F.sessionId,projectPath:F.projectPath}),L=l.get(f(D));if(W0(Y0(L?.currentRunId)))throw new R(`Stop session ${F.sessionId} before archiving this session tree`)}for(let F of K){let D=C0({sessionId:F.sessionId,projectPath:F.projectPath}),L=l.get(f(D));if(L)await q(L)}let z=await j.archiveSession(Q.sessionId,Q.projectPath);for(let F of K){let D=C0({sessionId:F.sessionId,projectPath:F.projectPath}),L=f(D);l.delete(L),Y.delete(L),J.delete(L),G.delete(L),T.publish(D,"session.archived",{archiveRootId:Q.sessionId,archivedAt:z.archivedAt})}if(O.size===0)await G0.getInstance().disconnectAll();return x.json({session:z,archivedSessionIds:K.map((F)=>F.sessionId)})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof V0||Q instanceof R)throw Q;if(Q instanceof y$)throw new R(Q.message);throw P.error("[SessionRoutes] Failed to archive session:",Q),new d("Failed to archive session")}}),$.post("/:sessionId/unarchive",async(x)=>{let N=x.req.param("sessionId");try{let Q=await J0(N,x.req.query("projectPath")),K=await j.listSessionArchiveMembers(Q.sessionId,Q.projectPath),z=await j.unarchiveSession(Q.sessionId,Q.projectPath),F=K.filter((D)=>D.sessionId===Q.sessionId||D.archivedBySessionId===Q.sessionId).map((D)=>D.sessionId);for(let D of F)T.publish({sessionId:D,projectPath:Q.projectPath},"session.unarchived",{archiveRootId:Q.sessionId});return x.json({session:z,restoredSessionIds:F})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof V0)throw Q;if(Q instanceof y$)throw new R(Q.message);throw P.error("[SessionRoutes] Failed to unarchive session:",Q),new d("Failed to unarchive session")}}),$.delete("/:sessionId",async(x)=>{let N=x.req.param("sessionId"),Q=x.req.query("projectPath");try{let K=await J0(N,Q),z=f(K),F=l.get(z),D=O.get(z),L=F?.taskWorktree??await j.findSessionTaskWorktree(K.sessionId,K.projectPath),M;if(F?.currentRunId){let B=Y0(F.currentRunId);if(B)w$(B),await B.completion,M=B.id}let A=T0.get(z);if(A)A.controller.abort("session-delete"),await A.completion;if(D)await D.clearGoal().catch((B)=>{P.warn("[SessionRoutes] Failed to clear session goal:",B)});if(await j.deleteSession(K.sessionId,K.projectPath),T.publish(K,"session.deleted",{}),M)d4(M);if(l.delete(z),Y.delete(z),J.delete(z),G.delete(z),D){if(await D.dispose(),O.delete(z),O.size===0)await G0.getInstance().disconnectAll()}if(L)try{await A0.restoreSession(L),await A0.exit({sessionId:K.sessionId,action:"remove",discardChanges:!0})}catch(B){P.warn(`[SessionRoutes] Failed to remove deleted task worktree ${K.sessionId}:`,B)}return x.json({success:!0})}catch(K){if(P.error("[SessionRoutes] Failed to delete session:",K),K instanceof _||K instanceof I||K instanceof V0)throw K;throw new d("Failed to delete session")}}),$.get("/:sessionId/message",async(x)=>{let N=x.req.param("sessionId");try{let Q=await J0(N,x.req.query("projectPath")),K=l.get(f(Q)),z=K?.messages?K.messages:await j.loadSession(Q.sessionId,Q.projectPath);return x.json(I$(z))}catch(Q){if(P.error("[SessionRoutes] Failed to get messages:",Q),Q instanceof _||Q instanceof I||Q instanceof V0)throw Q;throw new d("Failed to get messages")}}),$.get("/:sessionId/events",async(x)=>{let N=x.req.param("sessionId"),Q=await J0(N,x.req.query("projectPath"));try{await j.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(L){if(L instanceof P$)throw new R(L.message);throw L}let K=await b(Q),z=x.req.header("Last-Event-ID")??x.req.query("lastEventId"),F=z?Number.parseInt(z,10):Number.NaN,D=Number.isInteger(F)?F+1:void 0;return f4(x,async(L)=>{let A,B,n=!1,E0=()=>{if(B!==void 0)clearInterval(B),B=void 0;A?.(),A=void 0},X0=()=>{if(n)return;n=!0,E0()},K0=new Set;L.onAbort(X0),A=T.subscribe((k)=>{if(k.sessionId!==Q.sessionId||k.projectPath!==Q.projectPath)return;let v=k.properties.requestId;if((k.type==="permission.asked"||k.type==="question.required"||k.type==="elicitation.required")&&typeof v==="string"){if(K0.has(v))return;K0.add(v)}L.writeSSE({...typeof k.seq==="number"?{id:String(k.seq)}:{},data:JSON.stringify({type:k.type,...typeof k.seq==="number"?{seq:k.seq}:{},properties:{...k.properties,sessionId:k.sessionId,projectPath:k.projectPath}})}).catch(X0)});try{if(L.aborted||n)return;let k=Y0(K.currentRunId),v=W0(k)?await H(K):void 0,r0=v?.getPendingSteeringCount()??0;if(await L.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:Q.sessionId,projectPath:Q.projectPath,timestamp:Date.now(),status:W0(k)?k.status:"idle",runId:W0(k)?k.id:void 0,queued:r0,pendingInputDelivery:r0>0?v?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:v?.getRecoveredSteeringCount()??0}})}).catch((E)=>{throw X0(),E}),L.aborted||n)return;if(D!==void 0){if(await oO.for(Q.sessionId,Q.projectPath).replay({onCommitted:(h)=>{if(L.aborted||n)return;L.writeSSE({...typeof h.seq==="number"?{id:String(h.seq)}:{},data:JSON.stringify({type:`committed.${h.type}`,...typeof h.seq==="number"?{seq:h.seq}:{},properties:{event:h,sessionId:Q.sessionId,projectPath:Q.projectPath}})})}},D),L.aborted||n)return}if(!k&&!T0.has(f(Q))){let h=(await b0.list(Q.projectPath,Q.sessionId)).some(($0)=>$0.completion===void 0)?await b0.recoverInterrupted(Q.projectPath,Q.sessionId,await H(K)):void 0;if(h)K.messages=await j.loadSession(Q.sessionId,Q.projectPath),await P0(K),T.publish(Q,"review.completed",{reviewId:h.reviewId,status:h.status,findings:0,recovered:!0})}if(!k)await f0.recoverResponded(Q.projectPath,Q.sessionId);let H0=k?void 0:await f0.findPending(Q.projectPath,Q.sessionId),y=k?.pendingPermission??(H0?{permissionId:H0.request.requestId,details:f0.confirmationDetails(H0),resolve:()=>{return}}:void 0);if(y){K0.add(y.permissionId);let E=J1(y,!0);await L.writeSSE({data:JSON.stringify({type:E.type,properties:{...E.properties,sessionId:Q.sessionId,projectPath:Q.projectPath}})})}Q0(K).catch((E)=>{P.error(`[SessionRoutes] Failed to resume pending input for ${N}:`,E)}),B=setInterval(()=>{if(!L.aborted)L.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(X0)},15000);while(!L.aborted&&!n)await new Promise((E)=>setTimeout(E,1000))}finally{X0()}})}),$.post("/:sessionId/message",async(x)=>{let N=x.req.param("sessionId"),Q=await x.req.json(),K=S(m4,Q);if(!K.success)throw new _("Invalid message format");let{content:z,attachments:F,modelId:D,reasoningEffort:L,serviceTier:M,responseVerbosity:A,communicationStyle:B,permissionMode:n,projectPath:E0,outputSchema:X0}=K.data,K0;if(X0)try{K0=f$(X0).schema}catch(t){throw new _(t instanceof Error?t.message:"Invalid output schema")}let k=B,v=D?.trim();if((F??[]).reduce((t,i)=>t+(typeof i.content==="string"?Buffer.byteLength(i.content):0),0)>A$)throw new _("Message attachments exceed the 5 MiB limit");let H0=n,y=mO(z,F),E=await C(N,E0??x.req.query("projectPath")),h=H0??E.permissionMode??"default",$0=e(E);return V($0).runExclusive(async()=>{let t=Y0(E.currentRunId);if(W0(t)){if(K0)throw new R("Wait for the active turn to finish before setting an output schema");let p=await H(E);if(v&&!p.getModelById(v))throw new _(`Model not found: ${v}`);if(v&&p.getCurrentModelId()!==v)throw new R("Wait for the active turn to finish before switching models");if(L&&p.getReasoningConfiguration().selection!==L)throw new R("Wait for the active turn to finish before switching reasoning effort");if(M&&p.getServiceTierConfiguration().selection!==M)throw new R("Wait for the active turn to finish before switching service tier");if(A&&p.getResponseVerbosityConfiguration().selection!==A)throw new R("Wait for the active turn to finish before switching response verbosity");if(k&&p.getCommunicationStyleConfiguration().selection!==k)throw new R("Wait for the active turn to finish before switching communication style");if(H0&&E.permissionMode!==H0)throw new R("Wait for the active turn to finish before switching permission mode");let L0=await p.enqueueSteering(y,{allowBeforeTurn:!0});if(!L0.accepted)return x.json({status:"rejected",reason:L0.reason??"turn_unavailable"},409);let b$=L0.messageId??c0(12),WO=L0.queued;T.publish($0,"message.created",{messageId:b$,role:"user",content:p$(y)});let x4=L0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(T.publish($0,x4,{runId:t.id,messageId:b$,queued:WO}),L0.delivery==="next_turn"&&t.status!=="running"&&t.status!=="waiting_permission")Q0(E).catch((G4)=>{P.error(`[SessionRoutes] Failed to wake queued follow-up for ${N}:`,G4)});if(L0.delivery==="next_turn")t.pendingFollowUpRequested=!0;return x.json({runId:t.id,messageId:b$,status:L0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:WO},202)}if(E.permissionMode!==h)await c(E,h);let i=await H(E,{permissionMode:h,...k&&!k.includes(":")?{communicationStyle:k}:{}});if(v&&!i.getModelById(v))throw new _(`Model not found: ${v}`);if(L)try{i.resolveReasoningConfiguration(L,v)}catch(p){throw new _(p instanceof Error?p.message:"Invalid reasoning effort")}if(M)try{i.resolveServiceTierConfiguration(M,v)}catch(p){throw new _(p instanceof Error?p.message:"Invalid service tier")}if(A)try{i.resolveResponseVerbosityConfiguration(A,v)}catch(p){throw new _(p instanceof Error?p.message:"Invalid response verbosity")}let F0=k?i.resolveCommunicationStyleConfiguration(k):void 0;if(F0?.source!==void 0&&F0.source!=="built-in"&&!F0.contentSha256)throw new _("Custom communication style has no provenance");let B0=i.getCurrentModelId(),YO=i.getReasoningConfiguration(),zO=i.getServiceTierConfiguration(),QO=i.getResponseVerbosityConfiguration(),xO=i.getCommunicationStyleConfiguration(),GO=Boolean(v)&&B0!==v,XO=Boolean(L)&&YO.selection!==L,KO=Boolean(M)&&zO.selection!==M,VO=Boolean(A)&&QO.selection!==A,NO=Boolean(k)&&xO.selection!==k;if(GO||XO||KO||VO||NO)await i.refresh({...v?{modelId:v}:{},...L?{reasoningEffort:L}:{},...M?{serviceTier:M}:{},...A?{responseVerbosity:A}:{},...k?{communicationStyle:k}:{}});let T$={...v&&E.selectedModelId!==v?{selectedModelId:v}:{},...L&&E.reasoningEffort!==L?{reasoningEffort:L}:{},...M&&E.serviceTier!==M?{serviceTier:M}:{},...A&&E.responseVerbosity!==A?{responseVerbosity:A}:{},...F0&&(E.communicationStyle!==k||E.communicationStyleDigest!==F0.contentSha256)?{communicationStyle:k,communicationStyleDigest:F0.source==="built-in"?null:F0.contentSha256}:{}};if(Object.keys(T$).length>0)try{let p=await j.updateSessionMetadata(E.id,E.projectPath,T$);E.permissionMode=p.permissionMode,E.selectedModelId=p.selectedModelId,E.reasoningEffort=p.reasoningEffort,E.serviceTier=p.serviceTier,E.responseVerbosity=p.responseVerbosity,E.communicationStyle=p.communicationStyle,E.communicationStyleDigest=p.communicationStyleDigest,E.updatedAt=new Date(p.lastMessageTime),T.publish($0,"session.updated",T$)}catch(p){if(GO||XO||KO||VO||NO)await i.refresh({...B0?{modelId:B0}:{},reasoningEffort:YO.selection,serviceTier:zO.selection,responseVerbosity:QO.selection,communicationStyle:xO.selection}).catch((L0)=>P.error("[SessionRoutes] Failed to roll back non-durable model settings:",L0));throw p}let e0=K0?await i.prepareInputTurn(y,{outputSchema:K0}):await i.prepareInputTurn(y);if(!e0.accepted)return x.json({status:"rejected",reason:e0.reason},e0.reason==="queue_full"?429:409);let h0=r(E,y,h,{preparedInputTurn:e0,outputSchema:K0,...E.taskIsolation?{taskRuntime:i}:{}});return await h0.taskAdmissionUpdate,x.json({runId:h0.id,messageId:e0.messageId,status:h0.status==="queued"?"queued":"running",queuePosition:h0.taskQueuePosition,queueDepth:h0.taskQueueDepth,maxConcurrentTasks:h0.taskConcurrencyLimit},202)})}),$.post("/:sessionId/shell",async(x)=>{let N=x.req.param("sessionId"),Q=S($1,await x.req.json());if(!Q.success)throw new _("Invalid user shell command");let K=await C(N,Q.data.projectPath??x.req.query("projectPath")),z=e(K),F=f(z);return V(z).runExclusive(async()=>{if(i0.has(F))throw new R("A user shell command is already running in this Session");let D=await H(K),L=new AbortController,M,A=new Promise((B)=>{M=B});i0.set(F,{controller:L,completion:A});try{let B=await D.executeUserShellCommand(Q.data.command,{signal:L.signal});K.messages=await j.loadSession(K.id,K.projectPath),K.updatedAt=new Date;let n=Y0(K.currentRunId);if(B.delivery==="next_turn"&&W0(n))n.pendingFollowUpRequested=!0;return x.json({executionId:B.executionId,messageId:B.messageId,record:B.record,auxiliary:B.auxiliary,...B.delivery?{delivery:B.delivery}:{},...B.queued!==void 0?{queued:B.queued}:{}})}finally{i0.delete(F),M()}})}),$.post("/:sessionId/abort",async(x)=>{let N=x.req.param("sessionId"),Q=await J0(N,x.req.query("projectPath")),K=l.get(f(Q));if(K?.currentRunId){let D=Y0(K.currentRunId);if(D)w$(D),await D.completion}let z=i0.get(f(Q));if(z)z.controller.abort("user-cancel"),await z.completion;let F=T0.get(f(Q));if(F)F.controller.abort("user-cancel"),await F.completion;return x.json({success:!0})}),$.get("/:sessionId/status",async(x)=>{let N=x.req.param("sessionId"),Q=await J0(N,x.req.query("projectPath")),K=l.get(f(Q)),z=T0.get(f(Q));if(z)return x.json({sessionId:N,projectPath:Q.projectPath,reviewId:z.reviewId,status:"reviewing"});if(!K?.currentRunId)return x.json({sessionId:N,projectPath:Q.projectPath,status:"idle"});let F=Y0(K.currentRunId);return x.json({sessionId:N,projectPath:Q.projectPath,runId:K.currentRunId,status:F?.status||"idle"})}),{app:$,dispatchTask:w,retryTask:a,getTaskDiff:m,deliverTask:O0,recoverQueuedTasks:N$}};async function i4($,O,J,Z,Y,G={}){let{abortController:X,sessionId:V,id:W}=$,H=G.preparedInputTurn?.messageId??c0(12),b=G.pendingInputOnly===!0||G.preparedInputTurn?.mode==="pending"||G.goalContinuationOnly===!0?void 0:c0(12),C,c,r=e(O),w=(m,O0)=>{T.publish(r,m,O0)},a=async()=>{let m=String(X.signal.reason||"Task run cancelled");if(O.taskIsolation){let O0=C??await Y(O).catch(()=>{return});if(m==="user-cancel")await O0?.discardPendingInput().catch((N$)=>{P.warn(`[SessionRoutes] Failed to discard cancelled input for ${O.id}:`,N$)});let Q0=await O0?.setTaskStatus("cancelled",m).catch(()=>{return});if(Q0)x$(O,Q0);else await P0(O).catch(()=>{return})}O.taskStatus="cancelled",O.taskStatusReason=m,O.taskCompletedAt??=new Date().toISOString()};try{if(G.taskAdmission){if(await G.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,!G.pendingInputOnly&&!G.goalContinuationOnly)w("message.created",{messageId:H,role:"user",content:p$(J)});if(w("session.status",{status:"running"}),b)w("message.created",{messageId:b,role:"assistant",content:""});C=await Y(O);let m=C,O0=Boolean(G.outputSchema??m.getPendingSteeringMessages().find((z)=>z.outputSchema)?.outputSchema);c=await nO.createWithRuntime(m,{sessionId:V,...O.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let Q0=async(z)=>{let F=z.interactionRequestId??c0(12),D=300000;$.status="waiting_permission";let L=new Promise((n)=>{let E0=setTimeout(()=>{P.warn(`[SessionRoutes] Permission ${F} timed out after 300000ms`),w("permission.timeout",{requestId:F}),n({approved:!1,reason:"timeout"})},300000);$.pendingPermission={permissionId:F,resolve:(X0)=>{clearTimeout(E0),n(X0)},details:z}}),M=$.pendingPermission;if(!M)throw Error("Permission request was not registered");let A=J1(M);w(A.type,A.properties),P.info(`[SessionRoutes] Permission request created: ${F}, runId: ${W}`);let B=await L;if(P.info(`[SessionRoutes] Permission response received: ${F}, approved: ${B.approved}`),!X.signal.aborted)$.status="running";if($.pendingPermission===M)$.pendingPermission=void 0;return w("interaction.resolved",{requestId:F}),B},x={messages:await j.loadSessionModelContext(O.id,O.projectPath),userId:"web-user",sessionId:V,workspaceRoot:O.projectPath,signal:X.signal,permissionMode:Z,onPermissionModeChange:async(z)=>{O.permissionMode=z,O.updatedAt=new Date,w("session.updated",{permissionMode:z})},...O.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:Q0}},N=()=>{if(!b)b=c0(12),w("message.created",{messageId:b,role:"assistant",content:""});return b},Q=async(z)=>{switch(z.kind){case"content_delta":if(O0)break;w("message.delta",{messageId:N(),delta:z.delta});break;case"structured_output":w("structured.output",{messageId:N(),output:z.output,schemaDigest:z.schemaDigest});break;case"thinking_delta":w("thinking.delta",{messageId:N(),delta:z.delta});break;case"tool_start":if("function"in z.toolCall){if(z.toolCall.function.name===a0)break;w("tool.start",{messageId:N(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,arguments:z.toolCall.function.arguments,toolKind:z.toolKind})}break;case"tool_result":if("function"in z.toolCall){if(z.toolCall.function.name===a0)break;w("tool.result",{messageId:N(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,success:z.result.success,summary:z.result.metadata?.summary,output:d$(u$(z.toolCall.function.name,z.result)),metadata:Z1(z.result.metadata)})}break;case"tool_progress":if("function"in z.toolCall){if(z.toolCall.function.name===a0)break;w("tool.progress",{messageId:N(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,...z.update})}break;case"token_usage":w("token.usage",{...z.usage});break;case"turn_start":w("turn.started",{turn:z.turn,maxTurns:z.maxTurns});break;case"provider_retry":w("provider.retry",{phase:z.phase,attempt:z.attempt,maxRetries:z.maxRetries,reason:z.reason,statusCode:z.statusCode,delayMs:z.delayMs,nextRetryAt:z.nextRetryAt});break;case"provider_stall":w("provider.stall",{phase:z.phase,stallCount:z.stallCount,durationMs:z.durationMs,warningAfterMs:z.warningAfterMs,timeoutMs:z.timeoutMs,outputStarted:z.outputStarted});break;case"mcp_catalog_changed":w("mcp.catalog.changed",{messageId:N(),revision:z.revision,serverName:z.serverName,added:z.added,removed:z.removed,updated:z.updated});break;case"mcp_content_changed":w("mcp.content.changed",{messageId:N(),revision:z.revision,serverName:z.serverName,contentKind:z.contentKind,added:z.added,removed:z.removed,updated:z.updated});break;case"mcp_resource_updated":w("mcp.resource.updated",{messageId:N(),revision:z.revision,serverName:z.serverName,uri:z.uri});break;case"mcp_connection_changed":w("mcp.connection.changed",{messageId:N(),revision:z.revision,serverName:z.serverName,phase:z.phase,reason:z.reason,attempt:z.attempt,maxAttempts:z.maxAttempts,nextRetryAt:z.nextRetryAt,error:z.error});break;case"mcp_log":w("mcp.log",{messageId:N(),revision:z.revision,serverName:z.serverName,level:z.level,logger:z.logger,message:z.message,projectedBytes:z.projectedBytes,dataSha256:z.dataSha256,truncated:z.truncated,detailsOmitted:z.detailsOmitted,timestamp:z.timestamp,synthetic:z.synthetic});break;case"mcp_instructions_changed":w("mcp.instructions.changed",{messageId:N(),revision:z.revision,serverName:z.serverName,action:z.action,reason:z.reason,text:z.text,sourceBytes:z.sourceBytes,projectedBytes:z.projectedBytes,sha256:z.sha256,truncated:z.truncated,detailsOmitted:z.detailsOmitted});break;case"mcp_task_changed":w("mcp.task.changed",{messageId:N(),revision:z.revision,taskId:z.taskId,serverName:z.serverName,toolName:z.toolName,status:z.status,statusMessage:z.statusMessage,createdAt:z.createdAt,updatedAt:z.updatedAt,completedAt:z.completedAt,hasResult:z.hasResult,error:z.error});break;case"project_rules_loaded":w("project.rules.loaded",{messageId:N(),files:z.files,triggerPaths:z.triggerPaths,blockedWrite:z.blockedWrite});break;case"steering_applied":w("steering.applied",{runId:W,messageIds:z.messageIds,count:z.count,recovered:z.recovered,delivery:z.delivery,queued:m.getPendingSteeringCount()});break;case"follow_up_started":{if(b)w("message.complete",{messageId:b}),b=void 0;for(let F of z.messages){if(!F.recovered||F.persisted)continue;w("message.created",{messageId:F.id,role:"user",content:p$(F.content),recovered:!0})}w("follow_up.started",{runId:W,queued:z.queued,recovered:z.recovered}),N();break}case"goal_updated":w("goal.updated",{goal:z.goal});break;case"goal_continuation_started":w("goal.continuation.started",{goal:z.goal,continuation:z.continuation}),N();break;case"compaction":w(z.phase==="start"?"compaction.started":"compaction.completed",{...z.reason?{reason:z.reason}:{},...z.strategy?{strategy:z.strategy}:{},...z.outcome?{outcome:z.outcome}:{},...z.preTokens!==void 0?{preTokens:z.preTokens}:{},...z.postTokens!==void 0?{postTokens:z.postTokens}:{}});break;case"model_fallback":w("model.fallback",{});break;case"task_update":w("task.updated",{tasks:z.tasks});break;default:break}},K=await m$(c.chatStream(J,x,{stream:!0,pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly,outputSchema:G.outputSchema,taskAdmission:G.taskAdmission}),Q);if(!K.success)throw Error(K.error?.message??"Agent run failed");for(let z=0;z<20;z++){let F=$.pendingFollowUpRequested===!0;if($.pendingFollowUpRequested=!1,m.getPendingSteeringCount()===0){if(!F)break;continue}if(X.signal.aborted)break;if(K=await m$(c.chatStream("",x,{stream:!0,pendingInputOnly:!0,taskAdmission:G.taskAdmission}),Q),!K.success)throw Error(K.error?.message??"Agent follow-up failed")}if(O.messages=await j.loadSession(O.id,O.projectPath),O.updatedAt=new Date,await P0(O),X.signal.aborted||$.status==="cancelled"){await a(),w("session.status",{status:"idle"});return}if(b)w("message.complete",{messageId:b});w("thinking.completed",{}),$.status="completed",O.taskStatus="completed",O.taskCompletedAt??=new Date().toISOString(),w("session.completed",{runId:W,outputTruncated:K.metadata?.outputTruncated??!1}),w("session.status",{status:"idle"})}catch(m){if(C&&G.preparedInputTurn)await C.finishTurn(G.preparedInputTurn.handle).catch(()=>{return});if(X.signal.aborted||$.status==="cancelled"){w$($,"runtime-abort"),await a(),w("session.status",{status:"idle"});return}await P0(O).catch(()=>{return}),P.error("[SessionRoutes] Agent execution error:",m),$.status="failed",O.taskStatus="failed",O.taskCompletedAt??=new Date().toISOString();let O0=B$(m);if(!O.taskFailure){let Q0=C?await C.setTaskStatus("failed",m).catch(()=>{return}):await j.updateSessionMetadata(O.id,O.projectPath,{taskStatus:"failed",taskStatusReason:O0.message,taskFailure:O0,taskCompletedAt:O.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(Q0)x$(O,Q0)}O.taskStatusReason??=O0.message,O.taskFailure??=O0,w("session.error",{error:O.taskFailure.message,taskFailure:O.taskFailure}),w("session.status",{status:"error"})}finally{if(G.taskAdmission?.release(),G.taskAdmission){let m=u0.getStats();w("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:m.queued,taskConcurrencyLimit:m.maxConcurrent,taskInFlight:m.inFlight,updatedAt:new Date().toISOString()})}if(await c?.destroy().catch(()=>{return}),$.disposeRuntimeOnSettle&&G.disposeRuntime)await G.disposeRuntime(O,C).catch((m)=>{P.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${O.id}:`,m)});u4($)}}async function z1($,O,J){P.info(`[SessionRoutes] Looking for permission ${O} in session ${$.sessionId}`),P.info(`[SessionRoutes] Active runs: ${M0.size}`);for(let[G,X]of M0.entries())if(P.info(`[SessionRoutes] Checking run ${G}: 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 f0.respond($.projectPath,$.sessionId,O,J);return X.pendingPermission.resolve(J),P.info(`[SessionRoutes] Permission ${O} responded, runId: ${X.id}`),!0}let Z=await f0.findPending($.projectPath,$.sessionId);if(!Z||Z.request.requestId!==O)return P.error(`[SessionRoutes] Permission not found: ${O}`),!1;await f0.respondAndRecover($.projectPath,$.sessionId,O,J);let Y=l.get(f($));if(!Y){let G=await j.findSessionMetadata($.sessionId,$.projectPath);if(!G)return!1;let[X,V]=await Promise.all([j.loadSession($.sessionId,$.projectPath),j.findSessionTaskWorktree($.sessionId,$.projectPath)]);Y=Q$(G,X,V),l.set(f($),Y)}else await P0(Y);if(T.publish($,"interaction.resolved",{requestId:O}),L$)L$(Y).catch((G)=>{P.error(`[SessionRoutes] Failed to resume recovered interaction ${O}:`,G)});return!0}var l$=u("Service"),o4=U.Object({approved:U.Boolean(),remember:U.Optional(U.Boolean()),scope:U.Optional(Z0(["once","session","project"])),targetMode:U.Optional(Z0(["default","autoEdit","plan","yolo"])),feedback:U.Optional(U.String({maxLength:4000})),answers:U.Optional(U.Record(U.String({maxLength:80}),U.Union([U.String({maxLength:4000}),U.Array(U.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:U.Optional(U.Object({action:Z0(["accept","decline","cancel"]),content:U.Optional(U.Record(U.String(),U.Union([U.String({maxLength:4000}),U.Number(),U.Boolean(),U.Array(U.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),Q1=()=>{let $=new a4;return $.post("/:permissionId",async(O)=>{let J=O.req.param("permissionId"),Z=O.req.query("sessionId"),Y=O.req.query("projectPath");l$.info(`[PermissionRoutes] Received permission response: permissionId=${J}, sessionId=${Z}`);try{let G=await O.req.json(),X=S(o4,G);if(!X.success)throw new _("Invalid permission response format");let{approved:V,remember:W,scope:H,targetMode:q,feedback:b,answers:C,elicitation:c}=X.data;if(!Z)throw new _("sessionId query parameter is required");let r=await J0(Z,Y);if(!await z1(r,J,{approved:V,reason:b,scope:H,targetMode:q,feedback:b,answers:C,elicitation:c}))throw new I("Permission request",J);return l$.info(`[PermissionRoutes] Permission ${J} ${V?"approved":"denied"}`),O.json({success:!0,approved:V,remember:W})}catch(G){if(l$.error("[PermissionRoutes] Failed to respond to permission:",G),G instanceof _||G instanceof V0||G instanceof I||G instanceof s)throw G;throw G}}),$};import x1 from"node:path";import{Hono as n4}from"hono";var t4=U.Object({projectPath:U.String({minLength:1}),enabled:U.Boolean(),scope:U.Optional(Z0(["local","project","global"]))}),s4=U.Object({projectPath:U.String({minLength:1})}),r4=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),trust:U.Literal(!0),ref:U.Optional(U.String({minLength:1}))}),e4=U.Object({projectPath:U.String({minLength:1}),trust:U.Literal(!0)}),$2=U.Object({projectPath:U.String({minLength:1}),confirm:U.Literal(!0)}),O2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),ref:U.Optional(U.String({minLength:1}))}),G1=U.Object({projectPath:U.String({minLength:1}),confirm:U.Optional(U.Literal(!0))}),J2=U.Object({projectPath:U.String({minLength:1}),scope:U.Optional(Z0(["local","project","global"])),policy:U.Object({restrictToAllowedSources:U.Boolean(),requireGitCommitSha:U.Boolean(),allowedGitHosts:U.Array(U.String()),allowedMarketplaces:U.Array(U.String()),allowedLocalRoots:U.Array(U.String())})});function D0($){if(!$||!x1.isAbsolute($))throw new _("projectPath must be absolute");return x1.resolve($)}async function X1($){let[O,J]=await Promise.all([x0($),O$.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,G)=>Y+(Array.isArray(G)?G.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 Z2(){let $=K1(),[O,J]=await Promise.all([$.listCatalogs(),$.listInstallationRecords()]),Z=new Map(J.map((Y)=>[Y.name,Y]));return O.map(({marketplace:Y,manifest:G})=>({name:Y.name,description:G.description??G.metadata?.description??"",sourceType:Y.source.type,revision:Y.revision,updatedAt:Y.updatedAt,plugins:G.plugins.map((X)=>{let V=Z.get(X.name);return{name:X.name,description:X.description??"",version:X.version,category:X.category,tags:X.tags??[],installed:V!==void 0,installedVersion:V?.version}})}))}function o0($,O){if(!$.success)throw new _($.error??O)}var L1=()=>{let $=new n4;return $.get("/",async(O)=>{let J=D0(O.req.query("projectPath"));return O.json(await X1(J))}),$.post("/refresh",async(O)=>{let J=S(s4,await O.req.json());if(!J.success)throw new _("Invalid plugin refresh request");let Z=D0(J.data.projectPath),Y=await N1(Z);return O.json({plugins:await X1(Z),errors:Y.discovery.errors.map((G)=>({code:G.code??"LOAD_ERROR",error:G.error}))})}),$.get("/catalog",async(O)=>{return D0(O.req.query("projectPath")),O.json(await Z2())}),$.get("/policy",async(O)=>{let J=D0(O.req.query("projectPath")),Z=await O$.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=S(J2,await O.req.json());if(!J.success)throw new _("Invalid plugin source policy request");let Z=D0(J.data.projectPath),Y=await W1(Z,J.data.policy,J.data.scope??"global");return O.json({policy:Y})}),$.post("/install",async(O)=>{let J=S(r4,await O.req.json());if(!J.success)throw new _("Invalid plugin install request; explicit source trust is required");let Z=D0(J.data.projectPath),{result:Y}=await F1(Z,J.data.source,{trusted:J.data.trust,ref:J.data.ref});return o0(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=S(O2,await O.req.json());if(!J.success)throw new _("Invalid marketplace add request");let Z=D0(J.data.projectPath),Y=await _1(Z,J.data.source,J.data.ref);return o0(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=S(G1,await O.req.json());if(!J.success)throw new _("Invalid marketplace refresh request");let Z=await H1(D0(J.data.projectPath),O.req.param("name"));return o0(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=S(G1,await O.req.json());if(!J.success||J.data.confirm!==!0)throw new _("Invalid marketplace removal request; explicit confirmation is required");D0(J.data.projectPath);let Z=await B1(O.req.param("name"),!0);return o0(Z,"Marketplace removal failed"),O.json({name:Z.marketplace?.name,removed:!0})}),$.post("/:name/update",async(O)=>{let J=S(e4,await O.req.json());if(!J.success)throw new _("Invalid plugin update request; explicit source trust is required");let Z=D0(J.data.projectPath),{result:Y}=await U1(Z,O.req.param("name"),{trusted:J.data.trust});return o0(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=S($2,await O.req.json());if(!J.success)throw new _("Invalid plugin uninstall request; explicit confirmation is required");let Z=D0(J.data.projectPath),{result:Y}=await D1(Z,O.req.param("name"),J.data.confirm);return o0(Y,"Plugin uninstall failed"),O.json({name:Y.pluginName,removed:!0})}),$.post("/:name/state",async(O)=>{let J=S(t4,await O.req.json());if(!J.success)throw new _("Invalid plugin state request");let Z=D0(J.data.projectPath),Y=O.req.param("name"),X=(await x0(Z)).plugins.get(Y);if(!X)throw new I("Plugin",Y);if(X.source==="cli")throw new _(`Plugin "${Y}" was loaded with --plugin-dir and is invocation-scoped`);let V=await V1(Z,Y,J.data.enabled,J.data.scope??"local");return O.json(V)}),$};import{Hono as G2}from"hono";import{execFile as Y2}from"node:child_process";import z2 from"node:path";var a$="__BLADE_DIRECTORY_PICKER_CANCELLED__",Q2=900000;function x2($,O){return new Promise((J)=>{Y2($,[...O],{timeout:Q2,maxBuffer:65536,windowsHide:!0},(Z,Y,G)=>{let X=Z?.code;J({stdout:Y,stderr:G,exitCode:typeof X==="number"?X:Z?1:0,...typeof X==="string"?{errorCode:X}:{}})})})}function c$($){let O=$.replace(/[\r\n]+$/,"");if(!O||O===a$)return{cancelled:!0};if(!z2.isAbsolute(O))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:O}}function i$($){return $.exitCode!==0||Boolean($.errorCode)}class w1{platform;runCommand;activeSelection=null;constructor($={}){this.platform=$.platform??process.platform,this.runCommand=$.runCommand??x2}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 "${a$}"`,"end try"].join(`
3
- `),O=await this.runCommand("osascript",["-e",$]);if(i$(O))throw Error("Unable to open the macOS folder picker");return c$(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("${a$}")`,"}"].join("; "),O=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",$]);if(i$(O))throw Error("Unable to open the Windows folder picker");return c$(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(i$(J))throw Error("Unable to open the Linux folder picker");return c$(J.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var A1=new w1;var X2=U.Object({path:U.String({minLength:1})});function K2($){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 M1=($={})=>{let O=new G2,J=$.pickDirectory??(()=>A1.pick()),Z=$.allowDirectoryPickerRequest??K2;return O.get("/",async(Y)=>{return Y.json(await E$.list(g()))}),O.post("/",async(Y)=>{let G;try{G=await Y.req.json()}catch{throw new _("A valid JSON body is required")}let X=S(X2,G);if(!X.success)throw new _("A project path is required");try{let V=await E$.bind(X.data.path,g());return Y.json(V,201)}catch(V){throw new _(V instanceof Error?V.message:"Failed to bind project")}}),O.post("/pick",async(Y)=>{if(!Z(Y.req.header("Origin")))throw new s("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Y.json(await J())}catch(G){throw new _(G instanceof Error?G.message:"Failed to select a folder")}}),O.delete("/",async(Y)=>{let G=Y.req.query("path");if(!G)throw new _("A project path is required");try{let X=await E$.unbind(G);return Y.json({success:!0,removed:X})}catch(X){throw new _(X instanceof Error?X.message:"Failed to unbind project")}}),O};import{Hono as V2}from"hono";var E1=u("Service"),C1=()=>{let $=new V2;return $.get("/",async(O)=>{try{let J=await T1();return O.json(J)}catch(J){return E1.error("[ProviderRoutes] Failed to list providers:",J),O.json([])}}),$.get("/:provider/models",async(O)=>{let J=O.req.param("provider");try{let Z=await b1(J);return O.json(Z)}catch(Z){return E1.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 S0().setApiKey(J,Z.apiKey.trim()),O.json({success:!0})}),$.delete("/:provider/credential",async(O)=>{return await S0().clearCredential(O.req.param("provider")),O.json({success:!0})}),$.put("/:provider",async(O)=>{let J=O.req.param("provider"),Z=o(),Y=Z?.modelProviders[J];if(!Z||!Y)throw new I("Model provider",J);let G=await O.req.json();if(!G.name||!G.baseUrl||!G.wireApi)throw new _("name, baseUrl and wireApi are required");let X="apiKeyEnv"in G?G.apiKeyEnv?.trim():Y.apiKeyEnv,V={name:G.name,baseUrl:G.baseUrl,wireApi:G.wireApi,...X?{apiKeyEnv:X}:{}},W=S0(),H=G.apiKey?.trim()?await W.credentials.read(J):void 0;if(G.apiKey?.trim())await W.setApiKey(J,G.apiKey.trim());try{return await N0().updateModelProvider(J,V),O.json({success:!0})}catch(q){if(G.apiKey?.trim())if(H)await W.credentials.modify(J,async()=>H);else await W.credentials.delete(J);if(q instanceof Error&&(q.message.includes("modelProviders.")||q.message.includes("built-in provider")))throw new _(q.message);throw q}}),$.delete("/:provider",async(O)=>{let J=O.req.param("provider");if(!o()?.modelProviders[J])throw new I("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 G=await N0().removeModelProvider(J,{removeModels:Y==="true"});return O.json({success:!0,...G})}catch(G){if(G instanceof Error&&(G.message.includes("still referenced")||G.message.includes("owns the only model")))throw new R(G.message);throw G}}),$.post("/:provider/probe",async(O)=>{let J=O.req.param("provider"),Z=o();if(!Z?.modelProviders[J])throw new I("Model provider",J);let Y=await O.req.json().catch(()=>({})),G=Z.models.filter((V)=>V.provider===J),X=Y.modelId?G.find((V)=>V.id===Y.modelId):G[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 q1(X,Z))}),$};import{Hono as N2}from"hono";var W2=u("Service"),I1=($,O)=>{let J=new N2;return J.onError((Z,Y)=>{if(Z instanceof s)return Y.json(Z.toObject(),Z.statusCode);return W2.error("[ScheduleRoutes] Unhandled route error:",Z),Y.json(new d("Schedule request failed").toObject(),500)}),J.get("/",async(Z)=>{let Y=await $.list();return Z.json(k1.parse({schedules:Y}))}),J.post("/",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let G=S(R1,Y);if(!G.success)throw new _("Invalid schedule request");let X=G.data.projectPath||Z.get("directory")||g();try{let V=await $.create({...G.data,projectPath:X});return Z.json(y0.parse(V),201)}catch(V){throw new _(V instanceof Error?V.message:"Failed to create schedule")}}),J.get("/:id",async(Z)=>{let Y=await $.get(Z.req.param("id"));if(!Y)throw new I("Schedule not found");return Z.json(y0.parse(Y))}),J.patch("/:id",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let G=S(j1,Y);if(!G.success)throw new _("Invalid schedule update");let{modelId:X,reasoningEffort:V,serviceTier:W,responseVerbosity:H,communicationStyle:q,isolation:b,permissionMode:C,...c}=G.data,r={...X!==void 0?{modelId:X}:{},...V!==void 0?{reasoningEffort:V}:{},...W!==void 0?{serviceTier:W}:{},...H!==void 0?{responseVerbosity:H}:{},...q!==void 0?{communicationStyle:q}:{},...b!==void 0?{isolation:b}:{},...C!==void 0?{permissionMode:C}:{}};try{let w=await $.update(Z.req.param("id"),{...c,...Object.keys(r).length>0?{dispatch:r}:{}});if(!w)throw new I("Schedule not found");return Z.json(y0.parse(w))}catch(w){if(w instanceof s)throw w;throw new _(w instanceof Error?w.message:"Failed to update schedule")}}),J.delete("/:id",async(Z)=>{if(!await $.remove(Z.req.param("id")))throw new I("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 I("Schedule not found");return Z.json(y0.parse(Y))}),J.post("/:id/disable",async(Z)=>{let Y=await $.setEnabled(Z.req.param("id"),!1);if(!Y)throw new I("Schedule not found");return Z.json(y0.parse(Y))}),J.post("/:id/run",async(Z)=>{let Y=await $.get(Z.req.param("id"));if(!Y)throw new I("Schedule not found");if(!O)throw new d("Scheduler is not running in this process");await O.fire(Y,new Date,{manual:!0});let G=await $.get(Y.id);return Z.json(y0.parse(G??Y),202)}),J};import*as j0 from"node:fs/promises";import{homedir as y1}from"node:os";import*as _0 from"node:path";import{Hono as F2}from"hono";var m0=u("Service"),S1=_0.join(y1(),".blade","skills"),o$=_0.join(y1(),".blade","skills-config.json");async function m1(){try{let $=await j0.readFile(o$,"utf-8");return JSON.parse($)}catch{return{disabled:[]}}}async function U2($){await j0.mkdir(_0.dirname(o$),{recursive:!0}),await j0.writeFile(o$,JSON.stringify($,null,2))}async function D2($,O){let J=await m1();if(O)J.disabled=J.disabled.filter((Z)=>Z!==$);else if(!J.disabled.includes($))J.disabled.push($);await U2(J)}var R0=null,_2=300000,H2=6;async function B2(){if(R0&&Date.now()-R0.timestamp<_2)return R0.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(m0.warn(`GitHub API returned ${$.status}`),R0)return R0.data;throw Error(`GitHub skills catalog returned ${$.status}`)}let J=(await $.json()).filter((X)=>X.type==="dir"),Z=Array(J.length),Y=0,G=Math.min(H2,J.length);return await Promise.all(Array.from({length:G},async()=>{while(Y<J.length){let X=Y++,V=J[X];if(!V)continue;let W=`Official ${V.name} skill`;try{let H=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${V.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(H.ok){let b=(await H.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(b)W=b[1].trim().slice(0,100)}}catch{}Z[X]={name:V.name,description:W,tag:"Official",author:"Anthropic"}}})),R0={data:Z,timestamp:Date.now()},Z}catch($){if(m0.warn("Failed to fetch skills catalog from GitHub:",$),R0)return R0.data;throw $}}var h1=()=>{let $=new F2;return $.get("/",async(O)=>{try{let J=O.get("directory")||g(),Y=(await x0(J)).skills.getAll(),G=await m1(),X=Y.map((V)=>({id:V.name,name:V.name,enabled:!G.disabled.includes(V.name),description:V.description||"",version:V.version||"1.0.0",provider:"Local",location:V.source==="builtin"?"Built-in":V.basePath,removable:V.source==="user"&&_0.dirname(_0.resolve(V.basePath))===_0.resolve(S1),capabilities:["prompts"],allowedTools:V.allowedTools||[]}));return O.json(X)}catch(J){return m0.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 D2(J,Z.enabled),O.json({success:!0,enabled:Z.enabled})}catch(J){return m0.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 x0(Z)).skills,G=Y.get(J);if(!G)return O.json({success:!1,error:"Skill not found"},404);let X=_0.resolve(G.basePath),V=_0.resolve(S1);if(G.source!=="user"||_0.dirname(X)!==V)return O.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await j0.rm(X,{recursive:!0,force:!0}),await Y.refresh(),Z$(Z),await J$(Z),O.json({success:!0})}catch(J){return m0.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=f1(),Y=O.get("directory")||g(),G=P1({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 G.refresh(),Z$(Y),await J$(Y),O.json({success:!0})}catch(J){return m0.error("[SkillsRoutes] Failed to install skill:",J),O.json({success:!1,error:J.message},500)}}),$.get("/catalog",async(O)=>{try{let J=await B2();return O.json(J)}catch(J){return m0.error("[SkillsRoutes] Failed to get catalog:",J),O.json({error:J instanceof Error?J.message:"Failed to get skills catalog"},502)}}),$};import{execSync as L2}from"node:child_process";import{readdir as w2}from"node:fs/promises";import q$ from"node:path";import A2 from"fast-glob";import{Hono as M2}from"hono";var G$=u("Service"),E2=($)=>{try{return L2("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},q2=[...n0.map(($)=>`${$}/**`),...n0,...n0.map(($)=>`**/${$}/**`),...n0.map(($)=>`**/${$}`),...n$.map(($)=>`**/${$}`)],T2=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),p1=()=>{let $=new M2;return $.get("/commands",async(O)=>{try{let J=O.req.query("q")||"",Z=O.get("directory")||g();await x0(Z);let Y=v1(J,Z).filter((G)=>!T2.has(G.command));return O.json(Y)}catch(J){return G$.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),G=O.req.query("type")==="file",V=(await A2("**/*",{cwd:Z,dot:!1,followSymbolicLinks:!1,onlyFiles:G,markDirectories:!0,unique:!0,ignore:q2})).map((q)=>q.replace(/\\/g,"/"));if(!J)return O.json(V.slice(0,Y));let W=J.toLowerCase(),H=V.filter((q)=>q.toLowerCase().includes(W)).slice(0,Y);return O.json(H)}catch(J){return G$.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?q$.join(J,Z):J,X=(await w2(Y,{withFileTypes:!0})).map((H)=>({name:H.name,path:Z?`${Z}/${H.name}`:H.name,type:H.isDirectory()?"dir":"file"}));X.sort((H,q)=>{if(H.type!==q.type)return H.type==="dir"?-1:1;return H.name.localeCompare(q.name)});let V=new Set(n0),W=X.filter((H)=>{let q=H.name;if(q.startsWith("."))return!1;if(V.has(q))return!1;for(let b of n$)if(q.match(new RegExp(b.replace("*",".*"))))return!1;return!0});return O.json(W)}catch(J){return G$.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=q$.resolve(Z,J),G=q$.relative(Z,Y);if(G.startsWith("..")||q$.isAbsolute(G))return O.json({error:"Invalid file path"},400);let X=g1(),V=await X.stat(Y);if(!V?.isFile)return O.json({error:"File not found"},404);let W=200000,H=await X.readTextFile(Y),q=H.length>W;return O.json({path:J,content:q?H.slice(0,W):H,truncated:q,size:V.size})}catch(J){return G$.error("[SuggestionsRoutes] Failed to get file content:",J),O.json({error:"Failed to read file"},500)}}),$.get("/git-info",async(O)=>{try{let J=O.get("directory")||g(),Z=E2(J);return O.json({branch:Z})}catch(J){return G$.error("[SuggestionsRoutes] Failed to get git info:",J),O.json({branch:null})}}),$};import{Hono as b2}from"hono";var X$=u("Service"),i1=($)=>{let O=new b2;return O.onError((J,Z)=>{if(J instanceof s)return Z.json(J.toObject(),J.statusCode);return X$.error("[TaskRoutes] Unhandled route error:",J),Z.json(new d("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=S(l1,Z);if(!Y.success)throw new _("Invalid task request");if((Y.data.attachments??[]).reduce((X,V)=>X+(typeof V.content==="string"?Buffer.byteLength(V.content):0),0)>A$)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(t$.parse(X),202)}catch(X){if(X instanceof _||X instanceof R||X instanceof v0)throw X;throw X$.error("[TaskRoutes] Failed to dispatch task:",X),new d("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(t$.parse(Z),202)}catch(Z){if(Z instanceof _||Z instanceof I||Z instanceof R||Z instanceof v0)throw Z;throw X$.error("[TaskRoutes] Failed to retry task:",Z),new d("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(u1.parse(Z))}catch(Z){if(Z instanceof _||Z instanceof I||Z instanceof R)throw Z;throw X$.error("[TaskRoutes] Failed to load task diff:",Z),new d("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=S(c1,Z);if(!Y.success)throw new _("Invalid task delivery request");try{let G=await $.deliverTask(J.req.param("sessionId"),Y.data.action,J.req.query("projectPath"));return J.json(d1.parse(G))}catch(G){if(G instanceof _||G instanceof I||G instanceof R)throw G;throw X$.error("[TaskRoutes] Failed to deliver task:",G),new d("Failed to deliver task")}}),O};import{Hono as C2}from"hono";var k0=u("Service"),t0=new Map,a1=2097152,o1=65536;function n1(){return typeof globalThis.Bun<"u"}async function R2($,O,J){if(n1()){let{spawn:G}=await import("bun-pty"),X=G($,O,{name:"xterm-256color",cwd:J.cwd,env:J.env});return{pid:X.pid,write:(V)=>X.write(V),resize:(V,W)=>X.resize(V,W),kill:()=>X.kill(),onData:(V)=>X.onData(V),onExit:(V)=>X.onExit(V)}}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:(G)=>Y.write(G),resize:(G,X)=>Y.resize(G,X),kill:()=>Y.kill(),onData:(G)=>{Y.onData(G)},onExit:(G)=>{Y.onExit(G)}}}var e$=void 0,r$;if(n1())try{let{createBunWebSocket:$}=await import("hono/bun"),O=$();r$=O.upgradeWebSocket,e$=O.websocket}catch($){k0.warn("[Terminal] Failed to initialize Bun WebSocket support:",$)}async function t1($,O){let J=`term-${Date.now()}`;k0.info(`[Terminal] New connection: ${J}, cwd: ${$}`);let Z=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=Z.endsWith("sh")?["-l"]:[],G=await R2(Z,Y,{cwd:$,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),X={id:J,process:G,cwd:$,buffer:"",subscribers:new Set};if(t0.set(J,X),X.subscribers.add(O),G.onData((V)=>{let W=!1;for(let H of X.subscribers)try{H.send(V),W=!0}catch{X.subscribers.delete(H)}if(W)return;if(X.buffer+=V,X.buffer.length>a1)X.buffer=X.buffer.slice(-a1)}),G.onExit(({exitCode:V})=>{k0.info(`[Terminal] Process exited: ${J}, code: ${V}`);for(let W of X.subscribers)try{W.close()}catch{}t0.delete(J)}),X.buffer){let V=X.buffer;X.buffer="";for(let W=0;W<V.length;W+=o1)O.send(V.slice(W,W+o1))}return{session:X,cleanup:()=>{if(k0.info(`[Terminal] Connection closed: ${J}`),X.subscribers.delete(O),X.subscribers.size===0){try{X.process.kill()}catch{}t0.delete(J)}}}}function s1($,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 G=Y.searchParams.get("cwd")||O()||g();try{let{session:X,cleanup:V}=await t1(G,{send:(W)=>J.send(W),close:()=>J.close()});J.on("message",(W)=>{try{X.process.write(String(W))}catch(H){k0.error("[Terminal] Failed to write to PTY:",H)}}),J.on("close",V),J.on("error",V)}catch(X){k0.error("[Terminal] Failed to spawn PTY:",X),J.close()}})}var r1=()=>{let $=new C2;if($.get("/status",(O)=>{let J=Array.from(t0.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=t0.get(J);if(Z){try{Z.process.kill()}catch{}for(let Y of Z.subscribers)Y.close();return t0.delete(J),O.json({success:!0})}return O.json({success:!1,error:"Terminal not found"},404)}),r$)$.get("/ws",r$((O)=>{let J=O.req.query("cwd")||O.get("directory")||g(),Z;return{async onOpen(Y,G){try{Z=await t1(J,{send:(X)=>G.send(X),close:()=>G.close()})}catch(X){k0.error("[Terminal] Failed to spawn PTY:",X),G.close()}},onMessage(Y){if(!Z)return;try{Z.session.process.write(String(Y.data))}catch(G){k0.error("[Terminal] Failed to write to PTY:",G)}},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 j2 from"node:path";import{Hono as k2}from"hono";var I2=U.Object({projectPath:U.String({minLength:1}),action:Z0(["trust","revoke"])});function e1($){if(!j2.isAbsolute($))throw new _("projectPath must be absolute")}var O4=()=>{let $=new k2;return $.get("/",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return e1(J),O.json(await $O.getInstance().getStatus(J))}),$.post("/",async(O)=>{let J=S(I2,await O.req.json());if(!J.success)throw new _("Invalid workspace trust request");let{projectPath:Z,action:Y}=J.data;e1(Z);let G=$O.getInstance(),X=Y==="trust"?await G.trust(Z):await G.revoke(Z);return await $4(),O.json({...X,reloadRequired:X.sensitiveSources>0})}),$};var z0=u("Service"),ZO=[],K$,s0,J4=new Map,Z4=new Map,l2=new Set([".css",".html",".js",".json",".svg"]),c2=1024;function i2($,O){if(!$)return 0;let J=$.split(",").map((Z)=>{let[Y,...G]=Z.trim().toLowerCase().split(";"),X=G.find((W)=>W.trim().startsWith("q=")),V=X?Number(X.trim().slice(2)):1;return{name:Y,quality:Number.isFinite(V)?Math.max(0,Math.min(1,V)):0}});return J.find((Z)=>Z.name===O)?.quality??J.find((Z)=>Z.name==="*")?.quality??0}function a2($){return["br","gzip"].map((J)=>({encoding:J,quality:i2($,J)})).filter((J)=>J.quality>0).sort((J,Z)=>Z.quality-J.quality||(J.encoding==="br"?-1:1))[0]?.encoding}function o2($){let O=J4.get($);if(O)return O;let J=V$($);return J4.set($,J),J}function n2($,O,J){let Z=`${J}:${$}`,Y=Z4.get(Z);if(Y)return Y;let G=J==="br"?h2(O,{params:{[v2.BROTLI_PARAM_QUALITY]:5}}):g2(O,{level:6});return Z4.set(Z,G),G}function t2(){let $=P2(m2(import.meta.url)),O=[I0($,"web"),I0(g(),"dist/web"),I0(g(),"packages/cli/dist/web")];for(let J of O){let Z=I0(J,"index.html");if(JO(Z)){if(V$(Z,"utf-8").includes("/assets/"))return z0.debug(`[Server] Found web dist at: ${J}`),J}}return null}function s2(){let $=new p2;$.onError((Z,Y)=>{if(z0.error("[Server] Request error:",Z),Z instanceof s)return Y.json(Z.toObject(),Z.statusCode);let G=Z instanceof Error?Z.message:String(Z);return Y.json({error:{code:"INTERNAL_ERROR",message:G}},500)}),$.use(async(Z,Y)=>{let G=process.env.BLADE_SERVER_PASSWORD;if(!G)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 V=Z.req.header("Authorization");if(!V?.startsWith("Basic "))return Z.header("WWW-Authenticate",'Basic realm="Blade Server"'),Z.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let W=Buffer.from(V.slice(6),"base64").toString(),[H,q]=W.split(":"),b=process.env.BLADE_SERVER_USERNAME??"blade";if(H!==b||q!==G)return Z.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Y()}),$.use(async(Z,Y)=>{let G=Z.req.path==="/health"||Z.req.path==="/global/health"||Z.req.path.startsWith("/assets/");if(!G)z0.debug(`[Server] ${Z.req.method} ${Z.req.path}`);let X=Date.now();if(await Y(),!G){let V=Date.now()-X;z0.debug(`[Server] ${Z.req.method} ${Z.req.path} - ${Z.res.status} (${V}ms)`)}}),$.use(u2({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(ZO.includes(Z))return Z;return}})),$.use(async(Z,Y)=>{let G=Z.req.query("directory")||Z.req.header("x-blade-directory")||g();try{G=decodeURIComponent(G)}catch{}return Z.set("directory",G),Y()});let O=Y1();K$=O.recoverQueuedTasks,s0=new R$({dispatch:(Z)=>O.dispatchTask(Z),store:OO}),$.route("/global",HO()),$.route("/events",DO()),$.route("/sessions",O.app),$.route("/tasks",i1(O)),$.route("/schedules",I1(OO,s0)),$.route("/configs",UO()),$.route("/permissions",Q1()),$.route("/plugins",L1()),$.route("/hooks",EO()),$.route("/workspace-trust",O4()),$.route("/providers",C1()),$.route("/models",SO()),$.route("/projects",M1()),$.route("/suggestions",p1()),$.route("/terminal",r1()),$.route("/mcp",bO()),$.route("/skills",h1()),$.get("/health",(Z)=>{return Z.json({healthy:!0,version:p0()})});let J=t2();if(J)z0.info(`[Server] Serving static files from ${J}`),$.get("/favicon.svg",()=>{let Z=I0(J,"favicon.svg");if(!JO(Z))return new Response(null,{status:404});return new Response(V$(Z),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),$.get("/assets/*",(Z)=>{let Y=I0(J,Z.req.path);if(!JO(Y))return Z.json({error:{code:"NOT_FOUND",message:`File not found: ${Z.req.path}`}},404);let G=o2(Y),X=y2(Y).toLowerCase(),W={".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",H=l2.has(X)&&G.byteLength>=c2?a2(Z.req.header("Accept-Encoding")):void 0,q=H?n2(Y,G,H):G;return new Response(new Uint8Array(q),{headers:{"Content-Type":W,"Content-Length":String(q.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...H?{"Content-Encoding":H}:{}}})}),$.get("/",(Z)=>{let Y=I0(J,"index.html"),G=V$(Y,"utf-8");return Z.html(G,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 G=I0(J,"index.html"),X=V$(G,"utf-8");return Z.html(X,200,{"Cache-Control":"no-cache"})});else z0.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:p0(),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 r2(){let $=f2(),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 Y4(){return typeof globalThis.Bun<"u"}function z4($,O){let J=globalThis.Bun,Z=(G)=>{try{return J.serve({hostname:O.hostname,port:G,fetch:$.fetch,idleTimeout:0,websocket:e$})}catch(X){z0.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 e2($,O){return new Promise((J,Z)=>{let Y=S2(async(H,q)=>{let b=new URL(H.url||"/",`http://${H.headers.host}`),C=new Headers;for(let[w,a]of Object.entries(H.headers))if(a)if(Array.isArray(a))for(let m of a)C.append(w,m);else C.set(w,a);let c;if(H.method!=="GET"&&H.method!=="HEAD")c=(await new Promise((a)=>{let m=[];H.on("data",(O0)=>m.push(O0)),H.on("end",()=>a(Buffer.concat(m)))})).toString();let r=new Request(b.toString(),{method:H.method,headers:C,body:c});try{let w=await $.fetch(r);if(q.statusCode=w.status,w.headers.forEach((a,m)=>{q.setHeader(m,a)}),w.body){let a=w.body.getReader(),m=async()=>{let{done:O0,value:Q0}=await a.read();if(O0){q.end();return}return q.write(Q0),m()};await m()}else{let a=await w.text();q.end(a)}}catch(w){z0.error("[Server] Node request error:",w),q.statusCode=500,q.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),G=new d2({noServer:!0}),X=g();s1(G,()=>X),Y.on("upgrade",(H,q,b)=>{if(new URL(H.url||"/",`http://${H.headers.host}`).pathname==="/terminal/ws")G.handleUpgrade(H,q,b,(c)=>{G.emit("connection",c,H)});else q.destroy()});let V=(H)=>{return new Promise((q,b)=>{Y.once("error",(C)=>{if(C.code==="EADDRINUSE")b(C);else b(C)}),Y.listen(H,O.hostname,()=>{let C=Y.address();if(C&&typeof C==="object")q(C.port);else q(H)})})};(async()=>{let H;if(O.port===0)try{H=await V(4096)}catch{H=await V(0)}else H=await V(O.port);let q=new URL(`http://${O.hostname==="0.0.0.0"?"localhost":O.hostname}:${H}`);J({url:q,port:H,hostname:O.hostname,stop:async()=>{return new Promise((b)=>{G.close(()=>{Y.close(()=>b())})})}})})().catch(Z)})}var Q4;((Z6)=>{let $,O;function J(){if(!O)O=s2();return O}Z6.getApp=J;function Z(X){ZO=X.cors??[];let V=J();if(Y4())$=z4(V,X),z0.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 W=$;return K$?.().catch((H)=>{z0.warn("[Server] Failed to recover queued tasks:",H)}),s0?.start(),{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if($)s0?.stop(),await $.stop(),$=void 0,O=void 0,K$=void 0,z0.info("[Server] Blade server stopped")}}}Z6.listen=Z;async function Y(X){ZO=X.cors??[];let V=J();if(Y4())$=z4(V,X),z0.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else $=await e2(V,X),z0.info(`[Server] Blade server listening on ${$.url} (Node.js runtime)`);let W=$;try{await K$?.()}catch(H){z0.warn("[Server] Failed to recover queued tasks:",H)}return s0?.start(),{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if($)s0?.stop(),await $.stop(),$=void 0,O=void 0,K$=void 0,z0.info("[Server] Blade server stopped")}}}Z6.listenAsync=Y;function G(){return $!==void 0}Z6.isRunning=G})(Q4||={});export{$5 as f,O5 as g,r2 as h,Q4 as i};
@@ -1 +0,0 @@
1
- import{Ac as a,Bc as b,Cc as c}from"./chunk-bvwq5wth.js";import"./chunk-ag07wwer.js";import"./chunk-n00mknme.js";import"./chunk-qg87zezq.js";import"./chunk-xjqcc0nt.js";import"./chunk-18n15nn8.js";import"./chunk-w56y2pvk.js";import"./chunk-edqtngzr.js";import"./chunk-vmzf4nvh.js";import"./chunk-hpmxmkzc.js";import"./chunk-bpz0g8ej.js";import"./chunk-p1dp2xgq.js";import"./chunk-c674mmtj.js";import"./chunk-1gkpjhts.js";import"./chunk-c29y2s8g.js";import"./chunk-pccn8ndq.js";import"./chunk-x6tns9d8.js";import"./chunk-s14wmzm3.js";import"./chunk-vns8g2rv.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1 +0,0 @@
1
- import{td as a,ud as b,vd as c}from"./chunk-xzdpdwhz.js";import"./chunk-m27w377p.js";import"./chunk-c674mmtj.js";import"./chunk-1gkpjhts.js";import"./chunk-s14wmzm3.js";import"./chunk-vns8g2rv.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};