blade-code 0.10.12 → 0.10.13
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.
- package/dist/blade.js +2 -2
- package/dist/{chunk-cscm57tr.js → chunk-097zrzyy.js} +1 -1
- package/dist/{chunk-2wkt2w3f.js → chunk-0q7pvmvz.js} +1 -1
- package/dist/{chunk-2mmbqha8.js → chunk-45wpygt9.js} +1 -1
- package/dist/{chunk-vwwf7p7x.js → chunk-4em4jxj5.js} +1 -1
- package/dist/{chunk-86shv4yp.js → chunk-5vgjhqk9.js} +1 -1
- package/dist/{chunk-pz21tcah.js → chunk-5wnxafpf.js} +1 -1
- package/dist/{chunk-tadbcnwr.js → chunk-74wm5qnw.js} +1 -1
- package/dist/{chunk-zd3qxc5p.js → chunk-7s99zkve.js} +1 -1
- package/dist/{chunk-p5zstj8j.js → chunk-820ek28g.js} +1 -1
- package/dist/{chunk-4faz5tkt.js → chunk-8p5a371t.js} +1 -1
- package/dist/{chunk-vszmbnjh.js → chunk-8yypkbew.js} +1 -1
- package/dist/{chunk-e65vyfj7.js → chunk-97fyx4hr.js} +1 -1
- package/dist/{chunk-pmvfkre2.js → chunk-9ac3eajy.js} +1 -1
- package/dist/{chunk-vpz57h5x.js → chunk-a3mwn9zj.js} +1 -1
- package/dist/{chunk-86w8fd67.js → chunk-ab4sp3m4.js} +2 -2
- package/dist/{chunk-9e8fyt60.js → chunk-c477j84k.js} +1 -1
- package/dist/{chunk-jh4571hm.js → chunk-c9m16hqc.js} +1 -1
- package/dist/{chunk-evn886hs.js → chunk-cx0tdprs.js} +1 -1
- package/dist/{chunk-eqr25kxv.js → chunk-cy6emyt9.js} +1 -1
- package/dist/{chunk-vdgskayb.js → chunk-hf3dwmfa.js} +1 -1
- package/dist/{chunk-k7caqeew.js → chunk-j4rfyz81.js} +1 -1
- package/dist/{chunk-670th5hb.js → chunk-j8fkhkan.js} +1 -1
- package/dist/{chunk-63rg3mhn.js → chunk-k653znk8.js} +1 -1
- package/dist/{chunk-y2j96b3t.js → chunk-ke4n1nv5.js} +1 -1
- package/dist/{chunk-e2s6czgg.js → chunk-kfgv64hg.js} +1 -1
- package/dist/chunk-m6sg36pw.js +1 -0
- package/dist/{chunk-04wd6zez.js → chunk-nsxkd8bq.js} +1 -1
- package/dist/{chunk-pqgw6t9b.js → chunk-nysyp11q.js} +3 -3
- package/dist/{chunk-21zwc98r.js → chunk-p42cz164.js} +1 -1
- package/dist/{chunk-hb8krnp5.js → chunk-pmz455nq.js} +1 -1
- package/dist/{chunk-95zwz4q8.js → chunk-x9t4ryyf.js} +1 -1
- package/dist/{chunk-z24sj1r8.js → chunk-xjyctv33.js} +1 -1
- package/dist/{chunk-vaxcmm72.js → chunk-zgg0y0sy.js} +1 -1
- package/dist/web/assets/{ChatView-DG6MMrFK.js → ChatView-ucu62nNl.js} +6 -6
- package/dist/web/assets/{CodeBlockHighlighter-Cf3DBUGk.js → CodeBlockHighlighter-GS19h8wb.js} +1 -1
- package/dist/web/assets/{FilePreview-LvuYnyjv.js → FilePreview-BIjFuDdg.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-CkSbe36j.js → MarkdownRenderer-D-NrQgb1.js} +3 -3
- package/dist/web/assets/{SettingsModal-DBsb7E9J.js → SettingsModal-BNz9vyER.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-Z0KWY8g9.js → TaskSwitcher-HnRA3Mj8.js} +1 -1
- package/dist/web/assets/{TerminalPanel-DVWTlxtd.js → TerminalPanel-Df2CK9n_.js} +1 -1
- package/dist/web/assets/{index-DWtXGF3o.js → index-DWTihvUI.js} +3 -3
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-14rzj7js.js +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{j as T1,k as b1}from"./chunk-r76wc1cn.js";import{l as E$}from"./chunk-z8c5rhdh.js";import{r as b0}from"./chunk-tadbcnwr.js";import{s as tO}from"./chunk-vszmbnjh.js";import{A as H$,B as h$,C as A0,D as v$,E as d0,F as z$,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 g1,u as v1,w as aO,x as t0,y as n$}from"./chunk-pqgw6t9b.js";import{ea as TO,ka as G0}from"./chunk-9e8fyt60.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 m0,xa as R1,ya as j1,za as k1}from"./chunk-p4zt7ts9.js";import{Va as m$,Wa as C0,Xa as f,Ya as b,fb as oO,hb as P0}from"./chunk-21zwc98r.js";import{sb as uO}from"./chunk-095x2ykj.js";import{$b as j,Fb as dO,Hb as B$,Kb as o0,Nb as f$,Tb as lO,Ub as cO,Yb as iO,Zb as P$,_b as y$}from"./chunk-e65vyfj7.js";import{Uc as o,Yc as jO,dd as V0}from"./chunk-z24sj1r8.js";import{fd as S$}from"./chunk-ybvdac8k.js";import{pd as gO}from"./chunk-8j01ssaf.js";import{rd as _$}from"./chunk-63rg3mhn.js";import{Cd as K1,Gd as Z$,Hd as Y$,Ld as x0,yd as f1,zd as P1}from"./chunk-evn886hs.js";import{Vd as kO,Wd as pO}from"./chunk-heqs3xan.js";import{$d as l0,_d as AO}from"./chunk-e2s6czgg.js";import{ee as u}from"./chunk-4dq9y7zn.js";import{Ie as MO,Se as J$,te as qO}from"./chunk-pz21tcah.js";import{Ye as S,_e as F,bf as Z0}from"./chunk-kvx3sb3z.js";import{df as A$}from"./chunk-f4z3gkbs.js";import{if as v}from"./chunk-5s123nbs.js";import{nf as f0}from"./chunk-s5666ta0.js";import{pf as CO,qf as hO,sf as RO,tf as vO}from"./chunk-dsj62dcg.js";import{vf as u0}from"./chunk-eqr25kxv.js";import{Af as $O}from"./chunk-gav4hxcv.js";import{Ff as F$,Jf as _O}from"./chunk-363pgv1e.js";import{Mf as s$}from"./chunk-g11hq0e5.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 N$}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 v2,constants as g2}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=b.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}),b.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 t 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 t{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class _ extends t{constructor($){super("BAD_REQUEST",$,400)}}class R extends t{constructor($){super("CONFLICT",$,409)}}class p0 extends t{constructor($){super("TOO_MANY_REQUESTS",$,429)}}class K0 extends t{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class d extends t{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var X5=F.Object({error:F.Object({code:F.String(),message:F.String()})});import{Hono as N4}from"hono";var j$=u("Service"),W4=F.Object({updates:F.Record(F.String(),F.Any()),options:F.Optional(F.Object({scope:F.Optional(Z0(["local","project","global"])),immediate:F.Optional(F.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 V0().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$($,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$(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=b.subscribe((W)=>{if(!H4.has(W.type))return;if(W.type==="permission.asked"||W.type==="question.required"||W.type==="elicitation.required"){let A=W.properties.requestId;if(typeof A!=="string"||!A)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:A}})}).catch(V);return}if(W.type==="interaction.resolved"){let A=W.properties.requestId;if(typeof A!=="string"||!A)return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,requestId:A}})}).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 A=W.properties.title;if(typeof A!=="string"||!A.trim())return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,title:A}})}).catch(V);return}if(W.type==="task.delivery"){let A=w4(W.properties.taskDelivery);if(!A)return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,taskDelivery:A,...W.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{}}})}).catch(V);return}if(W.type==="schedule.fired"){let A=W.properties.scheduleId,a=W.properties.firedAt;if(typeof A!=="string"||typeof a!=="string")return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{scheduleId:A,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),T=O$(W.properties.taskQueuePosition,1),C=O$(W.properties.taskQueueDepth,0),c=O$(W.properties.taskConcurrencyLimit,1),s=O$(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}:{},...T!==void 0?{taskQueuePosition:T}:{},...C!==void 0?{taskQueueDepth:C}:{},...c!==void 0?{taskConcurrencyLimit:c}:{},...s!==void 0?{taskInFlight:s}:{}}})}).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:u0()})}),$.get("/info",(O)=>{let J=v(),Z=o();if(Z)d0.configure(Z.maxConcurrentTasks,Z.maxQueuedTasks);return O.json({version:u0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:J,gitBranch:_O(J),taskAdmission:d0.getStats()})}),$};import BO from"node:path";import{Hono as M4}from"hono";var E4=F.Object({projectPath:F.String({minLength:1}),action:Z0(["trust","revoke"]),expectedDigest:F.Optional(F.String())}),q4=F.Object({projectPath:F.String({minLength:1}),sessionId:F.String({minLength:1}),enabled:F.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 J$.getInstance().loadWorkspaceHooks(O,J,{includeBaseForCurrentWorkspace:!1});await x0(O),Y$(O);let Y=l0.getInstance();return Y.loadConfig(Z,O),await Z$(O),Y.getConfig(O)}function wO($,O){let J=l0.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 l0.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=l0.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=l0.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 V0().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 V0().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")||v(),[Y,G]=await Promise.all([_$(Z,J),x0(Z)]),X=Y.config.models,V=X.find((T)=>T.id===Y.config.currentModelId)??X[0],W=Y.catalog,H=G.communicationStyles.list(),q=(T)=>k4(T,W.resolveConfig(T),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=f0(),Z,Y;try{let G=await O.req.json(),{provider:X,displayName:V,model:W,overrides:H,apiKey:q,modelProvider:T}=G;if(!X||!W)throw new _("provider and model are required");IO(H);let C;if(T){if(T.id!==X)throw new _("modelProvider.id must match the model provider");if(o()?.modelProviders[X])throw new _(`model provider already exists: ${X}`);C={name:T.name,baseUrl:T.baseUrl,wireApi:T.wireApi,...T.apiKeyEnv?{apiKeyEnv:T.apiKeyEnv}:{}};try{J.registerModelProvider(X,C,[W]),Y=X}catch(A){throw new _(A instanceof Error?A.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},s=C?await V0().addModelWithProvider(c,C):await V0().addModel(c);return O.json({success:!0,model:s})}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)f0().getModel(V.provider,X);return await V0().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 V0().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{Mutex as fO}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 i0}from"nanoid";import PO from"node:path";var P=u("Service"),y4=F.Object({title:F.Optional(F.String()),projectPath:F.Optional(F.String())}),m4=eO,h4=F.Object({title:F.Optional(F.String()),projectPath:F.Optional(F.String())}),v4=F.Object({projectPath:F.String()}),g4=F.Object({objective:F.String({minLength:1}),tokenBudget:F.Optional(F.Integer({minimum:1})),permissionMode:F.Optional(Z0(["default","autoEdit","plan","yolo"]))}),p4=F.Union([F.Object({action:F.Literal("pause")}),F.Object({action:F.Literal("resume")}),F.Object({action:F.Literal("edit"),objective:F.String({minLength:1})})]),l=new Map,L$,M0=new Map,a0=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 N0($){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)b.publish(yO($),"interaction.resolved",{requestId:J.permissionId});return $.abortController.abort(O),$.status="cancelled",b.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 a0.values())$.controller.abort("route-reset");a0.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)b.publish($,"subagent.update",{subagentSessionId:O,toolName:J.toolCall.function.name}),b.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)b.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)b.publish($,"subagent.tool.progress",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,...J.update});break;case"content_delta":b.publish($,"subagent.delta",{subagentSessionId:O,delta:J.delta});break;case"thinking_delta":b.publish($,"subagent.thinking.delta",{subagentSessionId:O,delta:J.delta});break;case"stream_end":b.publish($,"subagent.stream.end",{subagentSessionId:O});break;case"mcp_catalog_changed":b.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":b.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":b.publish($,"subagent.mcp.resource.updated",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,uri:J.uri});break;case"mcp_connection_changed":b.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":b.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":b.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":b.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":b.publish($,"subagent.project.rules.loaded",{subagentSessionId:O,files:J.files,triggerPaths:J.triggerPaths,blockedWrite:J.blockedWrite});break;default:break}}function Q$($,O="projectPath"){if(!PO.isAbsolute($))throw new _(`${O} must be absolute`);return PO.resolve($)}function g$($){try{F$($)}catch(O){throw new _(O instanceof Error?O.message:`Invalid session ID: ${$}`)}}function e($){return{sessionId:$.id,projectPath:$.projectPath}}function x$($,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===o0)return[];let J=O.tool_calls?.filter((X)=>!("function"in X)||X.function.name!==o0),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 G$($,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 y0($){let O=await j.findSessionMetadata($.id,$.projectPath);if(O)G$($,O)}function c0($){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(g$($),O!==void 0){let Z=C0({sessionId:$,projectPath:Q$(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 K0;throw Z}if(J.size>1)throw new K0;return J.values().next().value}function p$($){if(typeof $==="string")return $;return $.filter((O)=>O.type==="text").map((O)=>O.text).join(`
|
|
1
|
+
import{j as T1,k as b1}from"./chunk-r76wc1cn.js";import{l as E$}from"./chunk-z8c5rhdh.js";import{r as b0}from"./chunk-74wm5qnw.js";import{s as tO}from"./chunk-8yypkbew.js";import{A as H$,B as h$,C as A0,D as v$,E as d0,F as z$,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 g1,u as v1,w as aO,x as t0,y as n$}from"./chunk-nysyp11q.js";import{ea as TO,ka as G0}from"./chunk-c477j84k.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 m0,xa as R1,ya as j1,za as k1}from"./chunk-p4zt7ts9.js";import{Va as m$,Wa as C0,Xa as f,Ya as b,fb as oO,hb as P0}from"./chunk-p42cz164.js";import{sb as uO}from"./chunk-095x2ykj.js";import{$b as j,Fb as dO,Hb as B$,Kb as o0,Nb as f$,Tb as lO,Ub as cO,Yb as iO,Zb as P$,_b as y$}from"./chunk-97fyx4hr.js";import{Uc as o,Yc as jO,dd as V0}from"./chunk-xjyctv33.js";import{fd as S$}from"./chunk-ybvdac8k.js";import{pd as gO}from"./chunk-8j01ssaf.js";import{rd as _$}from"./chunk-k653znk8.js";import{Cd as K1,Gd as Z$,Hd as Y$,Ld as x0,yd as f1,zd as P1}from"./chunk-cx0tdprs.js";import{Vd as kO,Wd as pO}from"./chunk-heqs3xan.js";import{$d as l0,_d as AO}from"./chunk-kfgv64hg.js";import{ee as u}from"./chunk-4dq9y7zn.js";import{Ie as MO,Se as J$,te as qO}from"./chunk-5wnxafpf.js";import{Ye as S,_e as F,bf as Z0}from"./chunk-kvx3sb3z.js";import{df as A$}from"./chunk-f4z3gkbs.js";import{if as v}from"./chunk-5s123nbs.js";import{nf as f0}from"./chunk-s5666ta0.js";import{pf as CO,qf as hO,sf as RO,tf as vO}from"./chunk-dsj62dcg.js";import{vf as u0}from"./chunk-cy6emyt9.js";import{Af as $O}from"./chunk-gav4hxcv.js";import{Ff as F$,Jf as _O}from"./chunk-363pgv1e.js";import{Mf as s$}from"./chunk-g11hq0e5.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 N$}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 v2,constants as g2}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=b.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}),b.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 t 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 t{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class _ extends t{constructor($){super("BAD_REQUEST",$,400)}}class R extends t{constructor($){super("CONFLICT",$,409)}}class p0 extends t{constructor($){super("TOO_MANY_REQUESTS",$,429)}}class K0 extends t{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class d extends t{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var X5=F.Object({error:F.Object({code:F.String(),message:F.String()})});import{Hono as N4}from"hono";var j$=u("Service"),W4=F.Object({updates:F.Record(F.String(),F.Any()),options:F.Optional(F.Object({scope:F.Optional(Z0(["local","project","global"])),immediate:F.Optional(F.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 V0().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$($,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$(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=b.subscribe((W)=>{if(!H4.has(W.type))return;if(W.type==="permission.asked"||W.type==="question.required"||W.type==="elicitation.required"){let A=W.properties.requestId;if(typeof A!=="string"||!A)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:A}})}).catch(V);return}if(W.type==="interaction.resolved"){let A=W.properties.requestId;if(typeof A!=="string"||!A)return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,requestId:A}})}).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 A=W.properties.title;if(typeof A!=="string"||!A.trim())return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,title:A}})}).catch(V);return}if(W.type==="task.delivery"){let A=w4(W.properties.taskDelivery);if(!A)return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,taskDelivery:A,...W.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{}}})}).catch(V);return}if(W.type==="schedule.fired"){let A=W.properties.scheduleId,a=W.properties.firedAt;if(typeof A!=="string"||typeof a!=="string")return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{scheduleId:A,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),T=O$(W.properties.taskQueuePosition,1),C=O$(W.properties.taskQueueDepth,0),c=O$(W.properties.taskConcurrencyLimit,1),s=O$(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}:{},...T!==void 0?{taskQueuePosition:T}:{},...C!==void 0?{taskQueueDepth:C}:{},...c!==void 0?{taskConcurrencyLimit:c}:{},...s!==void 0?{taskInFlight:s}:{}}})}).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:u0()})}),$.get("/info",(O)=>{let J=v(),Z=o();if(Z)d0.configure(Z.maxConcurrentTasks,Z.maxQueuedTasks);return O.json({version:u0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:J,gitBranch:_O(J),taskAdmission:d0.getStats()})}),$};import BO from"node:path";import{Hono as M4}from"hono";var E4=F.Object({projectPath:F.String({minLength:1}),action:Z0(["trust","revoke"]),expectedDigest:F.Optional(F.String())}),q4=F.Object({projectPath:F.String({minLength:1}),sessionId:F.String({minLength:1}),enabled:F.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 J$.getInstance().loadWorkspaceHooks(O,J,{includeBaseForCurrentWorkspace:!1});await x0(O),Y$(O);let Y=l0.getInstance();return Y.loadConfig(Z,O),await Z$(O),Y.getConfig(O)}function wO($,O){let J=l0.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 l0.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=l0.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=l0.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 V0().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 V0().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")||v(),[Y,G]=await Promise.all([_$(Z,J),x0(Z)]),X=Y.config.models,V=X.find((T)=>T.id===Y.config.currentModelId)??X[0],W=Y.catalog,H=G.communicationStyles.list(),q=(T)=>k4(T,W.resolveConfig(T),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=f0(),Z,Y;try{let G=await O.req.json(),{provider:X,displayName:V,model:W,overrides:H,apiKey:q,modelProvider:T}=G;if(!X||!W)throw new _("provider and model are required");IO(H);let C;if(T){if(T.id!==X)throw new _("modelProvider.id must match the model provider");if(o()?.modelProviders[X])throw new _(`model provider already exists: ${X}`);C={name:T.name,baseUrl:T.baseUrl,wireApi:T.wireApi,...T.apiKeyEnv?{apiKeyEnv:T.apiKeyEnv}:{}};try{J.registerModelProvider(X,C,[W]),Y=X}catch(A){throw new _(A instanceof Error?A.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},s=C?await V0().addModelWithProvider(c,C):await V0().addModel(c);return O.json({success:!0,model:s})}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)f0().getModel(V.provider,X);return await V0().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 V0().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{Mutex as fO}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 i0}from"nanoid";import PO from"node:path";var P=u("Service"),y4=F.Object({title:F.Optional(F.String()),projectPath:F.Optional(F.String())}),m4=eO,h4=F.Object({title:F.Optional(F.String()),projectPath:F.Optional(F.String())}),v4=F.Object({projectPath:F.String()}),g4=F.Object({objective:F.String({minLength:1}),tokenBudget:F.Optional(F.Integer({minimum:1})),permissionMode:F.Optional(Z0(["default","autoEdit","plan","yolo"]))}),p4=F.Union([F.Object({action:F.Literal("pause")}),F.Object({action:F.Literal("resume")}),F.Object({action:F.Literal("edit"),objective:F.String({minLength:1})})]),l=new Map,L$,M0=new Map,a0=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 N0($){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)b.publish(yO($),"interaction.resolved",{requestId:J.permissionId});return $.abortController.abort(O),$.status="cancelled",b.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 a0.values())$.controller.abort("route-reset");a0.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)b.publish($,"subagent.update",{subagentSessionId:O,toolName:J.toolCall.function.name}),b.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)b.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)b.publish($,"subagent.tool.progress",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,...J.update});break;case"content_delta":b.publish($,"subagent.delta",{subagentSessionId:O,delta:J.delta});break;case"thinking_delta":b.publish($,"subagent.thinking.delta",{subagentSessionId:O,delta:J.delta});break;case"stream_end":b.publish($,"subagent.stream.end",{subagentSessionId:O});break;case"mcp_catalog_changed":b.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":b.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":b.publish($,"subagent.mcp.resource.updated",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,uri:J.uri});break;case"mcp_connection_changed":b.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":b.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":b.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":b.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":b.publish($,"subagent.project.rules.loaded",{subagentSessionId:O,files:J.files,triggerPaths:J.triggerPaths,blockedWrite:J.blockedWrite});break;default:break}}function Q$($,O="projectPath"){if(!PO.isAbsolute($))throw new _(`${O} must be absolute`);return PO.resolve($)}function g$($){try{F$($)}catch(O){throw new _(O instanceof Error?O.message:`Invalid session ID: ${$}`)}}function e($){return{sessionId:$.id,projectPath:$.projectPath}}function x$($,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===o0)return[];let J=O.tool_calls?.filter((X)=>!("function"in X)||X.function.name!==o0),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 G$($,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 y0($){let O=await j.findSessionMetadata($.id,$.projectPath);if(O)G$($,O)}function c0($){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(g$($),O!==void 0){let Z=C0({sessionId:$,projectPath:Q$(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 K0;throw Z}if(J.size>1)throw new K0;return J.values().next().value}function p$($){if(typeof $==="string")return $;return $.filter((O)=>O.type==="text").map((O)=>O.text).join(`
|
|
2
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 t)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 fO,G.set(N,Q);return Q},W=(x)=>{let N=f(x),Q=X.get(N);if(!Q)Q=new fO,X.set(N,Q);return Q},H=async(x,N={})=>{let Q=f(e(x));await Z.get(Q);let z=O.get(Q);if(z)return z;let K=J.get(Q);if(!K){let U=N.communicationStyle??x.communicationStyle;K=z$.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}:{},...U?{communicationStyle:U}:{},...U===x.communicationStyle&&x.communicationStyleDigest?{communicationStyleDigest:x.communicationStyleDigest}:{},...x.projectInstructionsDigest?{projectInstructionsDigest:x.projectInstructionsDigest}:{},...x.taskWorktree?{taskWorktree:x.taskWorktree}:{},...x.taskIsolation?{taskIsolation:x.taskIsolation}:{},...x.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:x.id}}:{}}),J.set(Q,K)}try{let U=await K;return O.set(Q,U),U}finally{if(J.get(Q)===K)J.delete(Q)}},q=async(x,N)=>{let Q=f(e(x)),z=Z.get(Q);if(!z)z=(async()=>{let K=J.get(Q);if(K)await K.catch(()=>{return});J.delete(Q);let U=N??O.get(Q);if(O.delete(Q),U){for(let[D,B]of O)if(B===U)O.delete(D)}await U?.dispose()})().finally(()=>{if(Z.get(Q)===z)Z.delete(Q)}),Z.set(Q,z);await z},T=async(x)=>{let N=f(x),Q=l.get(N);if(Q)return Q;let z=Y.get(N);if(!z)z=(async()=>{let K=await j.findSessionMetadata(x.sessionId,x.projectPath);if(!K)throw new I("Session",x.sessionId);let[U,D]=await Promise.all([j.loadSession(x.sessionId,x.projectPath),j.findSessionTaskWorktree(x.sessionId,x.projectPath)]),B=x$(K,U,D);return l.set(N,B),B})(),Y.set(N,z);try{return await z}finally{if(Y.get(N)===z)Y.delete(N)}},C=async(x,N)=>{let Q=await J0(x,N);try{await j.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(z){if(z instanceof P$)throw new R(z.message);throw z}return T(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),b.publish(e(x),"session.updated",{permissionMode:N})},s=(x,N,Q,z={})=>{let K=i0(12),U={id:K,sessionId:x.id,projectPath:x.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:z.taskRuntime!==void 0,createdAt:new Date};if(z.taskRuntime){let D=z.taskRuntime,B=d0.admit({key:`${x.projectPath}\x00${x.id}`,...D.getTaskAdmissionLimits(),signal:U.abortController.signal,onUpdate:(w)=>{U.status=w.state,U.taskQueuePosition=w.queuePosition,U.taskQueueDepth=w.queueDepth,U.taskConcurrencyLimit=w.maxConcurrent,x.taskStatus=w.state,x.taskQueuePosition=w.queuePosition,x.taskQueueDepth=w.queueDepth,x.taskConcurrencyLimit=w.maxConcurrent,U.taskAdmissionUpdate=(U.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await D.setTaskAdmission(w)}).catch((L)=>{P.warn(`[SessionRoutes] Failed to persist admission for ${x.id}:`,L)})}});U.taskAdmission=B;let M=B.getSnapshot();U.status=M.state,U.taskQueuePosition=M.queuePosition,U.taskQueueDepth=M.queueDepth,U.taskConcurrencyLimit=M.maxConcurrent}return M0.set(K,U),x.currentRunId=K,U.completion=i4(U,x,N,Q,H,{pendingInputOnly:z.pendingInputOnly,preparedInputTurn:z.preparedInputTurn,goalContinuationOnly:z.goalContinuationOnly,outputSchema:z.outputSchema,taskAdmission:U.taskAdmission,disposeRuntime:q}).catch((D)=>{P.error(`[SessionRoutes] Run ${K} failed:`,D)}),U},A=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),z=Q$(x.sourceProjectPath),K=x.modelId?.trim(),U=o();if(!U)throw new _("Config not initialized");let[D,B]=await Promise.all([_$(z,U),x0(z)]);if(K&&!D.config.models.some((E)=>E.id===K))throw new _(`Task model not found: ${K}`);let M=K||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 w=D.config.models.find((E)=>E.id===M);if(!w)throw new _(`Task model not found: ${M}`);let L=x.reasoningEffort??"off",r=x.serviceTier??"auto",E0=x.responseVerbosity??"auto",_0=x.communicationStyle??"auto",X0,k=B.projectRules?.staticRules(z),g=k&&k.files.length>0?k.provenanceSha256:void 0;try{let E=D.catalog.resolveConfig(w);gO(E,L),vO(E,r),hO(E,E0);let h=pO(_0,B.communicationStyles);X0=h.source==="built-in"?void 0:h.contentSha256}catch(E){throw new _(E instanceof Error?E.message:"Invalid reasoning effort")}let e0={version:1,prompt:x.prompt,...x.title?{title:x.title}:{},sourceProjectPath:z,isolation:x.isolation,permissionMode:x.permissionMode,modelId:M,reasoningEffort:L,serviceTier:r,responseVerbosity:E0,communicationStyle:_0,...X0?{communicationStyleDigest:X0}:{},...g?{projectInstructionsDigest:g}:{},...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:z,isolation:x.isolation,dispatch:e0,retriedFrom:x.retriedFrom}),{metadata:h}=E;H0=E.taskWorktree,y=x$(h,[],H0);let $0=e(y);l.set(f($0),y),b.publish($0,"task.status",{taskStatus:h.taskStatus,updatedAt:h.lastMessageTime});let n=mO(x.prompt,x.attachments),i=await H(y),W0=N?await i.prepareInputTurn(n,{outputSchema:N}):await i.prepareInputTurn(n);if(!W0.accepted)throw new R(`Task prompt was not accepted: ${W0.reason}`);let B0=s(y,n,x.permissionMode,{preparedInputTurn:W0,taskRuntime:i,outputSchema:N});return await B0.taskAdmissionUpdate,{session:c0(y),runId:B0.id,messageId:W0.messageId,status:B0.status==="queued"?"queued":"running",queuePosition:B0.taskQueuePosition,queueDepth:B0.taskQueueDepth,maxConcurrentTasks:B0.taskConcurrencyLimit}}catch(E){if(E instanceof v$&&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 p0("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),n=await j.updateSessionMetadata(y.id,y.projectPath,{taskStatus:"failed",taskStatusReason:$0.message,taskFailure:$0,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});y.taskStatus=n?.taskStatus??"failed",y.taskStatusReason=n?.taskStatusReason??$0.message,y.taskFailure=n?.taskFailure??$0,y.taskCompletedAt=n?.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),z=await j.findSessionMetadata(Q.sessionId,Q.projectPath);if(!z)throw new I("Session",Q.sessionId);if(!["failed","interrupted","cancelled"].includes(z.taskStatus))throw new R(`Task cannot be retried while status is ${z.taskStatus}`);let K=await j.findSessionTaskDispatch(Q.sessionId,Q.projectPath);if(!K)throw new R("Task retry payload is unavailable");return A({prompt:K.prompt,title:K.title,sourceProjectPath:K.sourceProjectPath,isolation:K.isolation,permissionMode:K.permissionMode,modelId:K.modelId,reasoningEffort:K.reasoningEffort,serviceTier:K.serviceTier,responseVerbosity:K.responseVerbosity,communicationStyle:K.communicationStyle,attachments:K.attachments,outputSchema:K.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 z=await A0.getDiffArtifact(Q.id);if(!z)throw new R("Task diff artifact is unavailable");return{sessionId:Q.id,projectPath:Q.projectPath,...z}}catch(z){if(z instanceof R)throw z;throw P.error("[SessionRoutes] Failed to load task diff artifact:",z),new R("Task diff artifact is unavailable")}},O0=async(x,N,Q)=>{let z=await J0(x,Q);return W(z).runExclusive(async()=>{let K=await C(z.sessionId,z.projectPath);if(["queued","running"].includes(K.taskStatus))throw new R(`Task artifacts cannot be delivered while status is ${K.taskStatus}`);if(K.taskDelivery?.status==="applied")throw new R("Task changes have already been applied");if(K.taskDelivery?.status==="discarded")throw new R("Task changes have already been discarded");if(!K.taskWorktree)throw new R("Task worktree is unavailable");let U=async(D,B=!1)=>{let M=await j.updateSessionMetadata(K.id,K.projectPath,{taskDelivery:D,...B?{taskWorktree:null}:{}});if(G$(K,M),B)K.taskWorktree=void 0;return b.publish(z,"task.delivery",{taskDelivery:D,...B?{taskWorktreeRemoved:!0}:{},updatedAt:M.lastMessageTime}),c0(K)};try{if(N==="discard"){try{await A0.restoreSession(K.taskWorktree)}catch(M){return P.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${K.id}:`,M),U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:K.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let B=await A0.exit({sessionId:K.id,action:"remove",discardChanges:!0});return U({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:B.discardedFiles??0,message:"Task worktree removed"},!0)}try{await A0.restoreSession(K.taskWorktree)}catch(B){throw P.warn(`[SessionRoutes] Task worktree is unavailable for ${K.id}:`,B),new h$("artifact_unavailable","Task worktree is unavailable")}let D=await A0.apply(K.id);return U({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 U({status:"conflicted",updatedAt:new Date().toISOString(),message:D.message}),new R(D.message);throw D}})},Q0=async(x)=>{let N=Y0(x.currentRunId);if(N0(N))return;if(x.taskIsolation&&x.taskStatus!=="queued"&&x.taskStatus!=="running")return;let Q=await z$.hasPendingInbox(x.projectPath,x.id),z=!Q&&await z$.hasActiveGoal(x.projectPath,x.id);if(!Q&&!z)return;let K=await H(x),U=Y0(x.currentRunId);if(N0(U))return;if(Q&&K.getPendingSteeringCount()===0)await K.reloadPendingInbox();let D=K.getPendingSteeringCount()>0,M=(D?null:await K.getGoal())?.status==="active"||z;if(!D&&!M||K.hasTurnOwner())return;s(x,"",x.permissionMode??"default",{pendingInputOnly:D,goalContinuationOnly:M,...x.taskIsolation?{taskRuntime:K}:{}})};L$=Q0;let S0=async()=>{let x={scheduled:0,failed:0,deferred:0},N=(await j.listSessions()).filter((Q)=>Q.taskStatus==="queued"&&Q.taskIsolation!==void 0).sort((Q,z)=>Q.firstMessageTime.localeCompare(z.firstMessageTime)||Q.projectPath.localeCompare(z.projectPath)||Q.sessionId.localeCompare(z.sessionId));for(let[Q,z]of N.entries()){let K={sessionId:z.sessionId,projectPath:z.projectPath};try{if(!await z$.hasPendingInbox(z.projectPath,z.sessionId)){let D=B$("Queued task input is missing");await j.updateSessionMetadata(z.sessionId,z.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),x.failed++;continue}let U=await T(K);if(await Q0(U),U.currentRunId)x.scheduled++}catch(U){if(U instanceof v$){x.deferred+=N.length-Q;break}P.warn(`[SessionRoutes] Failed to recover queued task ${z.sessionId}:`,U),x.deferred++}}return x};return $.get("/",async(x)=>{try{let N=await j.listSessions(),Q=new Set(N.filter((w)=>w.relationType==="subagent").map((w)=>f({sessionId:w.sessionId,projectPath:w.projectPath}))),z=Array.from(l.values()).filter((w)=>!Q.has(f(e(w)))&&w.relationType!=="subagent").map((w)=>c0(w)),K=new Set(z.map((w)=>f({sessionId:w.sessionId,projectPath:w.projectPath}))),U=N.filter((w)=>{if(w.relationType==="subagent")return!1;return!K.has(f({sessionId:w.sessionId,projectPath:w.projectPath}))}),D=new Set(K),B=U.filter((w)=>{let L=f({sessionId:w.sessionId,projectPath:w.projectPath});if(D.has(L))return!1;return D.add(L),!0}),M=[...z,...B];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),z=x.req.query("cursor"),K=x.req.query("projectPath"),U=x.req.query("archived");if(U!==void 0&&U!=="true"&&U!=="false")throw new _("archived must be true or false");let D=U==="true",B=await j.listSessionPage({...K?{cwd:Q$(K)}:{},...z?{cursor:z}:{},...Q===void 0?{}:{limit:Q},includeSubagents:!1,archived:D}),M=new Map((D?[]:Array.from(l.values())).filter((w)=>w.relationType!=="subagent").map((w)=>[f(e(w)),c0(w)]));return x.json({sessions:B.sessions.map((w)=>M.get(f({sessionId:w.sessionId,projectPath:w.projectPath}))??w),...B.nextCursor?{nextCursor:B.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:z,projectPath:K}=Q.data,U=S$("web",12),D=Q$(K||x.get("directory")||v(),K?"projectPath":"directory"),B=await j.createSessionMetadata(U,D,{title:z,taskStatus:"completed"}),M=x$(B,[]),w=e(M);return l.set(f(w),M),b.publish(w,"session.created",{}),x.json({...c0(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 z=await J0(N,x.req.query("projectPath")),K=await j.exportSessionMarkdown(z.sessionId,z.projectPath,{includeReasoning:Q==="true"});return x.body(K.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${K.filename}"`,"Content-Length":String(Buffer.byteLength(K.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":K.contentSha256,"X-Blade-Export-Activities":String(K.activityCount),"X-Blade-Export-Messages":String(K.messageCount),"X-Blade-Export-Redactions":String(K.redactionCount)})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof K0)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{g$(N);let Q=await x.req.json(),z=S(v4,Q);if(!z.success)throw new _("Invalid request body");let K=Q$(z.data.projectPath),U=await j.findSessionMetadata(N,K);if(!U)throw new I("Session",N);let D=await j.forkSession(N,{sourceProjectPath:U.projectPath,targetProjectPath:U.projectPath}),B=x$(D.metadata,D.messages),M=e(B);return l.set(f(M),B),b.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")),z=l.get(f(Q));if(z)return x.json(c0(z));let K=await j.findSessionMetadata(Q.sessionId,Q.projectPath);if(!K)throw new I("Session",N);return x.json(K)}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof K0)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(),z=S(h4,Q);if(!z.success)throw new _("Invalid request body");if(z.data.title===void 0)throw new _("title is required");let K=await J0(N,z.data.projectPath),U=await j.updateSessionMetadata(K.sessionId,K.projectPath,{title:z.data.title}),D=l.get(f(K));if(D)D.title=U.title??D.title,D.updatedAt=new Date(U.lastMessageTime);if(U.title)b.publish(K,"session.updated",{title:U.title});return x.json({success:!0,title:U.title})}catch(Q){if(P.error("[SessionRoutes] Failed to update session:",Q),Q instanceof _||Q instanceof I||Q instanceof K0)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")),z=e(Q);return V(z).runExclusive(async()=>{let K=Y0(Q.currentRunId);if(N0(K))throw new R("Cannot rewind while a run is active");let U=await H(Q),D;try{D=await U.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 B=I$(D.messages);return b.publish(z,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:B}),x.json({...D,messages:B})})}),$.get("/:sessionId/review",async(x)=>{let N=x.req.param("sessionId"),Q=await J0(N,x.req.query("projectPath")),z=await b0.list(Q.projectPath,Q.sessionId);return x.json({reviews:z.map((K)=>({...K,content:K.completion?dO(K.start,K.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 z=await C(N,Q.data.projectPath),K=e(z),U=f(K);return V(K).runExclusive(async()=>{if(N0(Y0(z.currentRunId)))throw new R("Cannot start a review during an active turn");if(T0.has(U))throw new R("Session already has an active review");let D=await H(z);if(await b0.recoverInterrupted(K.projectPath,K.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&&z.selectedModelId!==Q.data.modelId){let L=await j.updateSessionMetadata(z.id,z.projectPath,{selectedModelId:Q.data.modelId});G$(z,L)}let B=new AbortController,M;try{M=await b0.start({sessionId:K.sessionId,projectPath:K.projectPath,runtime:D,request:{kind:Q.data.kind,...Q.data.ref?{ref:Q.data.ref}:{},...Q.data.instructions?{instructions:Q.data.instructions}:{}},signal:B.signal,onEvent:(L)=>{if(L.kind==="tool_start")b.publish(K,"review.tool.started",{reviewId:M?.reviewId,toolCallId:L.toolCall.id,toolName:L.toolCall.function.name});else if(L.kind==="tool_progress")b.publish(K,"review.tool.progress",{reviewId:M?.reviewId,toolCallId:L.toolCall.id,message:L.update.message.slice(0,1000)});else if(L.kind==="tool_result")b.publish(K,"review.tool.completed",{reviewId:M?.reviewId,toolCallId:L.toolCall.id,success:L.result.success})}})}catch(L){if(L instanceof Error&&(L.message.includes("active review")||L.message.includes("interrupted review")||L.message.includes("active turn")))throw new R(L.message);if(L instanceof Error&&(L.message.includes("review")||L.message.includes("Git")||L.message.includes("changes")||L.message.includes("ref")))throw new _(L.message);throw L}if(!M)throw new d("Code review failed to start");await y0(z),b.publish(K,"review.started",{reviewId:M.reviewId,kind:Q.data.kind}),b.publish(K,"task.status",{taskStatus:z.taskStatus,...z.taskStatusReason?{taskStatusReason:z.taskStatusReason}:{},...z.taskStartedAt?{taskStartedAt:z.taskStartedAt}:{},...z.taskPromptSummary?{taskPromptSummary:z.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let w=M.completion.then(async(L)=>{z.messages=await j.loadSession(K.sessionId,K.projectPath),await y0(z),b.publish(K,"task.status",{taskStatus:z.taskStatus,...z.taskStatusReason?{taskStatusReason:z.taskStatusReason}:{},...z.taskFailure?{taskFailure:z.taskFailure}:{},...z.taskStartedAt?{taskStartedAt:z.taskStartedAt}:{},...z.taskCompletedAt?{taskCompletedAt:z.taskCompletedAt}:{},...z.taskPromptSummary?{taskPromptSummary:z.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),b.publish(K,"review.completed",{reviewId:M.reviewId,status:L.status,findings:L.findings.length})}).catch((L)=>{P.error(`[SessionRoutes] Code review ${M.reviewId} failed:`,L)}).finally(()=>{if(T0.get(U)?.reviewId===M.reviewId)T0.delete(U)});return T0.set(U,{reviewId:M.reviewId,controller:B,completion:w}),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)=>{g$(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")),z=e(Q);return V(z).runExclusive(async()=>{let K=Y0(Q.currentRunId);if(N0(K))throw new R("Cannot resume a subagent while a parent run is active");let U=await H(Q),D=!1,B,M=(L)=>{b.publish(z,"subagent.complete",{subagentSessionId:L.id,success:L.status==="completed",status:L.status,summary:L.result?.message?.slice(0,500),type:L.subagentType,verificationVerdict:L.result?.verificationVerdict,resumedFrom:L.resumedFrom,rootAgentId:L.rootAgentId,resumeDepth:L.resumeDepth})},w;try{w=U.resumeSubagent({agentId:x.req.param("agentId"),prompt:N.data.prompt,onEvent:(L,r)=>{c4(z,r,L)},onCompleted:(L)=>{if(D)M(L);else B=L}})}catch(L){if(L instanceof Error&&(L.message.startsWith("Cannot resume")||L.message.startsWith("Subagent cannot")))throw new R(L.message);if(L instanceof Error&&L.message.startsWith("Subagent not found"))throw new I(L.message);throw L}if(b.publish(z,"subagent.start",{subagentSessionId:w.session.id,type:w.session.subagentType,description:w.session.description,resumedFrom:w.source.id,rootAgentId:w.session.rootAgentId,resumeDepth:w.session.resumeDepth}),D=!0,B)M(B);return x.json({source:H$(w.source),session:H$(w.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(g4,await x.req.json());if(!N.success)throw new _("Invalid goal request");let Q=await C(x.req.param("sessionId"),x.req.query("projectPath")),z=e(Q);return V(z).runExclusive(async()=>{let K=Y0(Q.currentRunId);if(N0(K))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 B=await H(Q),M=await B.createGoal(N.data);b.publish(z,"goal.updated",{goal:M});let w=s(Q,"",D,{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:B}:{}});return await w.taskAdmissionUpdate,x.json({status:w.status==="queued"?"queued":"running",runId:w.id,goal:M,queuePosition:w.taskQueuePosition,queueDepth:w.taskQueueDepth,maxConcurrentTasks:w.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")),z=e(Q);return V(z).runExclusive(async()=>{let K=await H(Q),U;if(N.data.action==="pause")U=await K.pauseGoal();else if(N.data.action==="edit")U=await K.editGoal(N.data.objective);else U=await K.resumeGoal();if(b.publish(z,"goal.updated",{goal:U}),U.status==="active"&&!N0(Y0(Q.currentRunId))){let D=s(Q,"","default",{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:K}:{}});return await D.taskAdmissionUpdate,x.json({status:D.status==="queued"?"queued":"running",runId:D.id,goal:U,queuePosition:D.taskQueuePosition,queueDepth:D.taskQueueDepth,maxConcurrentTasks:D.taskConcurrencyLimit},202)}return x.json({status:U.status,goal:U})})}),$.delete("/:sessionId/goal",async(x)=>{let N=await C(x.req.param("sessionId"),x.req.query("projectPath")),Q=e(N),K=await(await H(N)).clearGoal();if(K)b.publish(Q,"goal.cleared",{});return x.json({cleared:K})}),$.post("/:sessionId/archive",async(x)=>{let N=x.req.param("sessionId");try{let Q=await J0(N,x.req.query("projectPath")),z=await j.listSessionArchiveMembers(Q.sessionId,Q.projectPath);for(let U of z){let D=C0({sessionId:U.sessionId,projectPath:U.projectPath}),B=l.get(f(D));if(N0(Y0(B?.currentRunId)))throw new R(`Stop session ${U.sessionId} before archiving this session tree`)}for(let U of z){let D=C0({sessionId:U.sessionId,projectPath:U.projectPath}),B=l.get(f(D));if(B)await q(B)}let K=await j.archiveSession(Q.sessionId,Q.projectPath);for(let U of z){let D=C0({sessionId:U.sessionId,projectPath:U.projectPath}),B=f(D);l.delete(B),Y.delete(B),J.delete(B),G.delete(B),b.publish(D,"session.archived",{archiveRootId:Q.sessionId,archivedAt:K.archivedAt})}if(O.size===0)await G0.getInstance().disconnectAll();return x.json({session:K,archivedSessionIds:z.map((U)=>U.sessionId)})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof K0||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")),z=await j.listSessionArchiveMembers(Q.sessionId,Q.projectPath),K=await j.unarchiveSession(Q.sessionId,Q.projectPath),U=z.filter((D)=>D.sessionId===Q.sessionId||D.archivedBySessionId===Q.sessionId).map((D)=>D.sessionId);for(let D of U)b.publish({sessionId:D,projectPath:Q.projectPath},"session.unarchived",{archiveRootId:Q.sessionId});return x.json({session:K,restoredSessionIds:U})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof K0)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 z=await J0(N,Q),K=f(z),U=l.get(K),D=O.get(K),B=U?.taskWorktree??await j.findSessionTaskWorktree(z.sessionId,z.projectPath),M;if(U?.currentRunId){let L=Y0(U.currentRunId);if(L)w$(L),await L.completion,M=L.id}let w=T0.get(K);if(w)w.controller.abort("session-delete"),await w.completion;if(D)await D.clearGoal().catch((L)=>{P.warn("[SessionRoutes] Failed to clear session goal:",L)});if(await j.deleteSession(z.sessionId,z.projectPath),b.publish(z,"session.deleted",{}),M)d4(M);if(l.delete(K),Y.delete(K),J.delete(K),G.delete(K),D){if(await D.dispose(),O.delete(K),O.size===0)await G0.getInstance().disconnectAll()}if(B)try{await A0.restoreSession(B),await A0.exit({sessionId:z.sessionId,action:"remove",discardChanges:!0})}catch(L){P.warn(`[SessionRoutes] Failed to remove deleted task worktree ${z.sessionId}:`,L)}return x.json({success:!0})}catch(z){if(P.error("[SessionRoutes] Failed to delete session:",z),z instanceof _||z instanceof I||z instanceof K0)throw z;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")),z=l.get(f(Q)),K=z?.messages?z.messages:await j.loadSession(Q.sessionId,Q.projectPath);return x.json(I$(K))}catch(Q){if(P.error("[SessionRoutes] Failed to get messages:",Q),Q instanceof _||Q instanceof I||Q instanceof K0)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(B){if(B instanceof P$)throw new R(B.message);throw B}let z=await T(Q),K=x.req.header("Last-Event-ID")??x.req.query("lastEventId"),U=K?Number.parseInt(K,10):Number.NaN,D=Number.isInteger(U)?U+1:void 0;return f4(x,async(B)=>{let w,L,r=!1,E0=()=>{if(L!==void 0)clearInterval(L),L=void 0;w?.(),w=void 0},_0=()=>{if(r)return;r=!0,E0()},X0=new Set;B.onAbort(_0),w=b.subscribe((k)=>{if(k.sessionId!==Q.sessionId||k.projectPath!==Q.projectPath)return;let g=k.properties.requestId;if((k.type==="permission.asked"||k.type==="question.required"||k.type==="elicitation.required")&&typeof g==="string"){if(X0.has(g))return;X0.add(g)}B.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(_0)});try{if(B.aborted||r)return;let k=Y0(z.currentRunId),g=N0(k)?await H(z):void 0,e0=g?.getPendingSteeringCount()??0;if(await B.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:Q.sessionId,projectPath:Q.projectPath,timestamp:Date.now(),status:N0(k)?k.status:"idle",runId:N0(k)?k.id:void 0,queued:e0,pendingInputDelivery:e0>0?g?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:g?.getRecoveredSteeringCount()??0}})}).catch((E)=>{throw _0(),E}),B.aborted||r)return;if(D!==void 0){if(await oO.for(Q.sessionId,Q.projectPath).replay({onCommitted:(h)=>{if(B.aborted||r)return;B.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),B.aborted||r)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(z)):void 0;if(h)z.messages=await j.loadSession(Q.sessionId,Q.projectPath),await y0(z),b.publish(Q,"review.completed",{reviewId:h.reviewId,status:h.status,findings:0,recovered:!0})}if(!k)await P0.recoverResponded(Q.projectPath,Q.sessionId);let H0=k?void 0:await P0.findPending(Q.projectPath,Q.sessionId),y=k?.pendingPermission??(H0?{permissionId:H0.request.requestId,details:P0.confirmationDetails(H0),resolve:()=>{return}}:void 0);if(y){X0.add(y.permissionId);let E=J1(y,!0);await B.writeSSE({data:JSON.stringify({type:E.type,properties:{...E.properties,sessionId:Q.sessionId,projectPath:Q.projectPath}})})}Q0(z).catch((E)=>{P.error(`[SessionRoutes] Failed to resume pending input for ${N}:`,E)}),L=setInterval(()=>{if(!B.aborted)B.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(_0)},15000);while(!B.aborted&&!r)await new Promise((E)=>setTimeout(E,1000))}finally{_0()}})}),$.post("/:sessionId/message",async(x)=>{let N=x.req.param("sessionId"),Q=await x.req.json(),z=S(m4,Q);if(!z.success)throw new _("Invalid message format");let{content:K,attachments:U,modelId:D,reasoningEffort:B,serviceTier:M,responseVerbosity:w,communicationStyle:L,permissionMode:r,projectPath:E0,outputSchema:_0}=z.data,X0;if(_0)try{X0=f$(_0).schema}catch(n){throw new _(n instanceof Error?n.message:"Invalid output schema")}let k=L,g=D?.trim();if((U??[]).reduce((n,i)=>n+(typeof i.content==="string"?Buffer.byteLength(i.content):0),0)>A$)throw new _("Message attachments exceed the 5 MiB limit");let H0=r,y=mO(K,U),E=await C(N,E0??x.req.query("projectPath")),h=H0??E.permissionMode??"default",$0=e(E);return V($0).runExclusive(async()=>{let n=Y0(E.currentRunId);if(N0(n)){if(X0)throw new R("Wait for the active turn to finish before setting an output schema");let p=await H(E);if(g&&!p.getModelById(g))throw new _(`Model not found: ${g}`);if(g&&p.getCurrentModelId()!==g)throw new R("Wait for the active turn to finish before switching models");if(B&&p.getReasoningConfiguration().selection!==B)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(w&&p.getResponseVerbosityConfiguration().selection!==w)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??i0(12),WO=L0.queued;b.publish($0,"message.created",{messageId:b$,role:"user",content:p$(y)});let x4=L0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(b.publish($0,x4,{runId:n.id,messageId:b$,queued:WO}),L0.delivery==="next_turn"&&n.status!=="running"&&n.status!=="waiting_permission")Q0(E).catch((G4)=>{P.error(`[SessionRoutes] Failed to wake queued follow-up for ${N}:`,G4)});if(L0.delivery==="next_turn")n.pendingFollowUpRequested=!0;return x.json({runId:n.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(g&&!i.getModelById(g))throw new _(`Model not found: ${g}`);if(B)try{i.resolveReasoningConfiguration(B,g)}catch(p){throw new _(p instanceof Error?p.message:"Invalid reasoning effort")}if(M)try{i.resolveServiceTierConfiguration(M,g)}catch(p){throw new _(p instanceof Error?p.message:"Invalid service tier")}if(w)try{i.resolveResponseVerbosityConfiguration(w,g)}catch(p){throw new _(p instanceof Error?p.message:"Invalid response verbosity")}let W0=k?i.resolveCommunicationStyleConfiguration(k):void 0;if(W0?.source!==void 0&&W0.source!=="built-in"&&!W0.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(g)&&B0!==g,XO=Boolean(B)&&YO.selection!==B,KO=Boolean(M)&&zO.selection!==M,VO=Boolean(w)&&QO.selection!==w,NO=Boolean(k)&&xO.selection!==k;if(GO||XO||KO||VO||NO)await i.refresh({...g?{modelId:g}:{},...B?{reasoningEffort:B}:{},...M?{serviceTier:M}:{},...w?{responseVerbosity:w}:{},...k?{communicationStyle:k}:{}});let T$={...g&&E.selectedModelId!==g?{selectedModelId:g}:{},...B&&E.reasoningEffort!==B?{reasoningEffort:B}:{},...M&&E.serviceTier!==M?{serviceTier:M}:{},...w&&E.responseVerbosity!==w?{responseVerbosity:w}:{},...W0&&(E.communicationStyle!==k||E.communicationStyleDigest!==W0.contentSha256)?{communicationStyle:k,communicationStyleDigest:W0.source==="built-in"?null:W0.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),b.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 $$=X0?await i.prepareInputTurn(y,{outputSchema:X0}):await i.prepareInputTurn(y);if(!$$.accepted)return x.json({status:"rejected",reason:$$.reason},$$.reason==="queue_full"?429:409);let v0=s(E,y,h,{preparedInputTurn:$$,outputSchema:X0,...E.taskIsolation?{taskRuntime:i}:{}});return await v0.taskAdmissionUpdate,x.json({runId:v0.id,messageId:$$.messageId,status:v0.status==="queued"?"queued":"running",queuePosition:v0.taskQueuePosition,queueDepth:v0.taskQueueDepth,maxConcurrentTasks:v0.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 z=await C(N,Q.data.projectPath??x.req.query("projectPath")),K=e(z),U=f(K);return V(K).runExclusive(async()=>{if(a0.has(U))throw new R("A user shell command is already running in this Session");let D=await H(z),B=new AbortController,M,w=new Promise((L)=>{M=L});a0.set(U,{controller:B,completion:w});try{let L=await D.executeUserShellCommand(Q.data.command,{signal:B.signal});z.messages=await j.loadSession(z.id,z.projectPath),z.updatedAt=new Date;let r=Y0(z.currentRunId);if(L.delivery==="next_turn"&&N0(r))r.pendingFollowUpRequested=!0;return x.json({executionId:L.executionId,messageId:L.messageId,record:L.record,auxiliary:L.auxiliary,...L.delivery?{delivery:L.delivery}:{},...L.queued!==void 0?{queued:L.queued}:{}})}finally{a0.delete(U),M()}})}),$.post("/:sessionId/abort",async(x)=>{let N=x.req.param("sessionId"),Q=await J0(N,x.req.query("projectPath")),z=l.get(f(Q));if(z?.currentRunId){let D=Y0(z.currentRunId);if(D)w$(D),await D.completion}let K=a0.get(f(Q));if(K)K.controller.abort("user-cancel"),await K.completion;let U=T0.get(f(Q));if(U)U.controller.abort("user-cancel"),await U.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")),z=l.get(f(Q)),K=T0.get(f(Q));if(K)return x.json({sessionId:N,projectPath:Q.projectPath,reviewId:K.reviewId,status:"reviewing"});if(!z?.currentRunId)return x.json({sessionId:N,projectPath:Q.projectPath,status:"idle"});let U=Y0(z.currentRunId);return x.json({sessionId:N,projectPath:Q.projectPath,runId:z.currentRunId,status:U?.status||"idle"})}),{app:$,dispatchTask:A,retryTask:a,getTaskDiff:m,deliverTask:O0,recoverQueuedTasks:S0}};async function i4($,O,J,Z,Y,G={}){let{abortController:X,sessionId:V,id:W}=$,H=G.preparedInputTurn?.messageId??i0(12),T=G.pendingInputOnly===!0||G.preparedInputTurn?.mode==="pending"||G.goalContinuationOnly===!0?void 0:i0(12),C,c,s=e(O),A=(m,O0)=>{b.publish(s,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((S0)=>{P.warn(`[SessionRoutes] Failed to discard cancelled input for ${O.id}:`,S0)});let Q0=await O0?.setTaskStatus("cancelled",m).catch(()=>{return});if(Q0)G$(O,Q0);else await y0(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)A("message.created",{messageId:H,role:"user",content:p$(J)});if(A("session.status",{status:"running"}),T)A("message.created",{messageId:T,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 K=z.interactionRequestId??i0(12),U=300000;$.status="waiting_permission";let D=new Promise((L)=>{let r=setTimeout(()=>{P.warn(`[SessionRoutes] Permission ${K} timed out after 300000ms`),A("permission.timeout",{requestId:K}),L({approved:!1,reason:"timeout"})},300000);$.pendingPermission={permissionId:K,resolve:(E0)=>{clearTimeout(r),L(E0)},details:z}}),B=$.pendingPermission;if(!B)throw Error("Permission request was not registered");let M=J1(B);A(M.type,M.properties),P.info(`[SessionRoutes] Permission request created: ${K}, runId: ${W}`);let w=await D;if(P.info(`[SessionRoutes] Permission response received: ${K}, approved: ${w.approved}`),!X.signal.aborted)$.status="running";if($.pendingPermission===B)$.pendingPermission=void 0;return A("interaction.resolved",{requestId:K}),w},S0={messages:[...O.messages],userId:"web-user",sessionId:V,workspaceRoot:O.projectPath,signal:X.signal,permissionMode:Z,onPermissionModeChange:async(z)=>{O.permissionMode=z,O.updatedAt=new Date,A("session.updated",{permissionMode:z})},...O.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:Q0}},x=()=>{if(!T)T=i0(12),A("message.created",{messageId:T,role:"assistant",content:""});return T},N=async(z)=>{switch(z.kind){case"content_delta":if(O0)break;A("message.delta",{messageId:x(),delta:z.delta});break;case"structured_output":A("structured.output",{messageId:x(),output:z.output,schemaDigest:z.schemaDigest});break;case"thinking_delta":A("thinking.delta",{messageId:x(),delta:z.delta});break;case"tool_start":if("function"in z.toolCall){if(z.toolCall.function.name===o0)break;A("tool.start",{messageId:x(),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===o0)break;A("tool.result",{messageId:x(),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===o0)break;A("tool.progress",{messageId:x(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,...z.update})}break;case"token_usage":A("token.usage",{...z.usage});break;case"turn_start":A("turn.started",{turn:z.turn,maxTurns:z.maxTurns});break;case"mcp_catalog_changed":A("mcp.catalog.changed",{messageId:x(),revision:z.revision,serverName:z.serverName,added:z.added,removed:z.removed,updated:z.updated});break;case"mcp_content_changed":A("mcp.content.changed",{messageId:x(),revision:z.revision,serverName:z.serverName,contentKind:z.contentKind,added:z.added,removed:z.removed,updated:z.updated});break;case"mcp_resource_updated":A("mcp.resource.updated",{messageId:x(),revision:z.revision,serverName:z.serverName,uri:z.uri});break;case"mcp_connection_changed":A("mcp.connection.changed",{messageId:x(),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":A("mcp.log",{messageId:x(),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":A("mcp.instructions.changed",{messageId:x(),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":A("mcp.task.changed",{messageId:x(),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":A("project.rules.loaded",{messageId:x(),files:z.files,triggerPaths:z.triggerPaths,blockedWrite:z.blockedWrite});break;case"steering_applied":A("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(T)A("message.complete",{messageId:T}),T=void 0;for(let K of z.messages){if(!K.recovered||K.persisted)continue;A("message.created",{messageId:K.id,role:"user",content:p$(K.content),recovered:!0})}A("follow_up.started",{runId:W,queued:z.queued,recovered:z.recovered}),x();break}case"goal_updated":A("goal.updated",{goal:z.goal});break;case"goal_continuation_started":A("goal.continuation.started",{goal:z.goal,continuation:z.continuation}),x();break;case"compaction":A(z.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":A("model.fallback",{});break;case"task_update":A("task.updated",{tasks:z.tasks});break;default:break}},Q=await m$(c.chatStream(J,S0,{stream:!0,pendingInputOnly:G.pendingInputOnly,preparedInputTurn:G.preparedInputTurn,goalContinuationOnly:G.goalContinuationOnly,outputSchema:G.outputSchema,taskAdmission:G.taskAdmission}),N);if(!Q.success)throw Error(Q.error?.message??"Agent run failed");for(let z=0;z<20;z++){let K=$.pendingFollowUpRequested===!0;if($.pendingFollowUpRequested=!1,m.getPendingSteeringCount()===0){if(!K)break;continue}if(X.signal.aborted)break;if(Q=await m$(c.chatStream("",S0,{stream:!0,pendingInputOnly:!0,taskAdmission:G.taskAdmission}),N),!Q.success)throw Error(Q.error?.message??"Agent follow-up failed")}if(O.messages=[...S0.messages],O.updatedAt=new Date,await y0(O),X.signal.aborted||$.status==="cancelled"){await a(),A("session.status",{status:"idle"});return}if(T)A("message.complete",{messageId:T});A("thinking.completed",{}),$.status="completed",O.taskStatus="completed",O.taskCompletedAt??=new Date().toISOString(),A("session.completed",{runId:W,outputTruncated:Q.metadata?.outputTruncated??!1}),A("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(),A("session.status",{status:"idle"});return}await y0(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)G$(O,Q0)}O.taskStatusReason??=O0.message,O.taskFailure??=O0,A("session.error",{error:O.taskFailure.message,taskFailure:O.taskFailure}),A("session.status",{status:"error"})}finally{if(G.taskAdmission?.release(),G.taskAdmission){let m=d0.getStats();A("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 P0.respond($.projectPath,$.sessionId,O,J);return X.pendingPermission.resolve(J),P.info(`[SessionRoutes] Permission ${O} responded, runId: ${X.id}`),!0}let Z=await P0.findPending($.projectPath,$.sessionId);if(!Z||Z.request.requestId!==O)return P.error(`[SessionRoutes] Permission not found: ${O}`),!1;await P0.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=x$(G,X,V),l.set(f($),Y)}else await y0(Y);if(b.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=F.Object({approved:F.Boolean(),remember:F.Optional(F.Boolean()),scope:F.Optional(Z0(["once","session","project"])),targetMode:F.Optional(Z0(["default","autoEdit","plan","yolo"])),feedback:F.Optional(F.String({maxLength:4000})),answers:F.Optional(F.Record(F.String({maxLength:80}),F.Union([F.String({maxLength:4000}),F.Array(F.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:F.Optional(F.Object({action:Z0(["accept","decline","cancel"]),content:F.Optional(F.Record(F.String(),F.Union([F.String({maxLength:4000}),F.Number(),F.Boolean(),F.Array(F.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),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:T,answers:C,elicitation:c}=X.data;if(!Z)throw new _("sessionId query parameter is required");let s=await J0(Z,Y);if(!await z1(s,J,{approved:V,reason:T,scope:H,targetMode:q,feedback:T,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 K0||G instanceof I||G instanceof t)throw G;throw G}}),$};import x1 from"node:path";import{Hono as n4}from"hono";var t4=F.Object({projectPath:F.String({minLength:1}),enabled:F.Boolean(),scope:F.Optional(Z0(["local","project","global"]))}),s4=F.Object({projectPath:F.String({minLength:1})}),r4=F.Object({projectPath:F.String({minLength:1}),source:F.String({minLength:1}),trust:F.Literal(!0),ref:F.Optional(F.String({minLength:1}))}),e4=F.Object({projectPath:F.String({minLength:1}),trust:F.Literal(!0)}),$2=F.Object({projectPath:F.String({minLength:1}),confirm:F.Literal(!0)}),O2=F.Object({projectPath:F.String({minLength:1}),source:F.String({minLength:1}),ref:F.Optional(F.String({minLength:1}))}),G1=F.Object({projectPath:F.String({minLength:1}),confirm:F.Optional(F.Literal(!0))}),J2=F.Object({projectPath:F.String({minLength:1}),scope:F.Optional(Z0(["local","project","global"])),policy:F.Object({restrictToAllowedSources:F.Boolean(),requireGitCommitSha:F.Boolean(),allowedGitHosts:F.Array(F.String()),allowedMarketplaces:F.Array(F.String()),allowedLocalRoots:F.Array(F.String())})});function U0($){if(!$||!x1.isAbsolute($))throw new _("projectPath must be absolute");return x1.resolve($)}async function X1($){let[O,J]=await Promise.all([x0($),J$.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 n0($,O){if(!$.success)throw new _($.error??O)}var L1=()=>{let $=new n4;return $.get("/",async(O)=>{let J=U0(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=U0(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 U0(O.req.query("projectPath")),O.json(await Z2())}),$.get("/policy",async(O)=>{let J=U0(O.req.query("projectPath")),Z=await J$.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=U0(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=U0(J.data.projectPath),{result:Y}=await F1(Z,J.data.source,{trusted:J.data.trust,ref:J.data.ref});return n0(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=U0(J.data.projectPath),Y=await _1(Z,J.data.source,J.data.ref);return n0(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(U0(J.data.projectPath),O.req.param("name"));return n0(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");U0(J.data.projectPath);let Z=await B1(O.req.param("name"),!0);return n0(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=U0(J.data.projectPath),{result:Y}=await U1(Z,O.req.param("name"),{trusted:J.data.trust});return n0(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=U0(J.data.projectPath),{result:Y}=await D1(Z,O.req.param("name"),J.data.confirm);return n0(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=U0(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
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=F.Object({path:F.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(v()))}),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,v());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 t("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 f0().setApiKey(J,Z.apiKey.trim()),O.json({success:!0})}),$.delete("/:provider/credential",async(O)=>{return await f0().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=f0(),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 V0().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 V0().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 t)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")||v();try{let V=await $.create({...G.data,projectPath:X});return Z.json(m0.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(m0.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:T,permissionMode:C,...c}=G.data,s={...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}:{},...T!==void 0?{isolation:T}:{},...C!==void 0?{permissionMode:C}:{}};try{let A=await $.update(Z.req.param("id"),{...c,...Object.keys(s).length>0?{dispatch:s}:{}});if(!A)throw new I("Schedule not found");return Z.json(m0.parse(A))}catch(A){if(A instanceof t)throw A;throw new _(A instanceof Error?A.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(m0.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(m0.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(m0.parse(G??Y),202)}),J};import*as j0 from"node:fs/promises";import{homedir as y1}from"node:os";import*as D0 from"node:path";import{Hono as F2}from"hono";var h0=u("Service"),S1=D0.join(y1(),".blade","skills"),o$=D0.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(D0.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(h0.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 T=(await H.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(T)W=T[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(h0.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")||v(),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"&&D0.dirname(D0.resolve(V.basePath))===D0.resolve(S1),capabilities:["prompts"],allowedTools:V.allowedTools||[]}));return O.json(X)}catch(J){return h0.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 h0.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")||v(),Y=(await x0(Z)).skills,G=Y.get(J);if(!G)return O.json({success:!1,error:"Skill not found"},404);let X=D0.resolve(G.basePath),V=D0.resolve(S1);if(G.source!=="user"||D0.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(),Y$(Z),await Z$(Z),O.json({success:!0})}catch(J){return h0.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")||v(),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(),Y$(Y),await Z$(Y),O.json({success:!0})}catch(J){return h0.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 h0.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 X$=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=[...t0.map(($)=>`${$}/**`),...t0,...t0.map(($)=>`**/${$}/**`),...t0.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")||v();await x0(Z);let Y=g1(J,Z).filter((G)=>!T2.has(G.command));return O.json(Y)}catch(J){return X$.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")||v(),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 X$.error("[SuggestionsRoutes] Failed to get file suggestions:",J),O.json([])}}),$.get("/files/tree",async(O)=>{try{let J=O.get("directory")||v(),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(t0),W=X.filter((H)=>{let q=H.name;if(q.startsWith("."))return!1;if(V.has(q))return!1;for(let T of n$)if(q.match(new RegExp(T.replace("*",".*"))))return!1;return!0});return O.json(W)}catch(J){return X$.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")||v(),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=v1(),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 X$.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")||v(),Z=E2(J);return O.json({branch:Z})}catch(J){return X$.error("[SuggestionsRoutes] Failed to get git info:",J),O.json({branch:null})}}),$};import{Hono as b2}from"hono";var K$=u("Service"),i1=($)=>{let O=new b2;return O.onError((J,Z)=>{if(J instanceof t)return Z.json(J.toObject(),J.statusCode);return K$.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")||v(),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 p0)throw X;throw K$.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 p0)throw Z;throw K$.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 K$.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 K$.error("[TaskRoutes] Failed to deliver task:",G),new d("Failed to deliver task")}}),O};import{Hono as C2}from"hono";var k0=u("Service"),s0=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(s0.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{}s0.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{}s0.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()||v();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(s0.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=s0.get(J);if(Z){try{Z.process.kill()}catch{}for(let Y of Z.subscribers)Y.close();return s0.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")||v(),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=F.Object({projectPath:F.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=[],V$,r0,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=N$($);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:{[g2.BROTLI_PARAM_QUALITY]:5}}):v2(O,{level:6});return Z4.set(Z,G),G}function t2(){let $=P2(m2(import.meta.url)),O=[I0($,"web"),I0(v(),"dist/web"),I0(v(),"packages/cli/dist/web")];for(let J of O){let Z=I0(J,"index.html");if(JO(Z)){if(N$(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 t)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(":"),T=process.env.BLADE_SERVER_USERNAME??"blade";if(H!==T||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")||v();try{G=decodeURIComponent(G)}catch{}return Z.set("directory",G),Y()});let O=Y1();V$=O.recoverQueuedTasks,r0=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,r0)),$.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:u0()})});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(N$(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=N$(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=N$(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:u0(),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 T=new URL(H.url||"/",`http://${H.headers.host}`),C=new Headers;for(let[A,a]of Object.entries(H.headers))if(a)if(Array.isArray(a))for(let m of a)C.append(A,m);else C.set(A,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 s=new Request(T.toString(),{method:H.method,headers:C,body:c});try{let A=await $.fetch(s);if(q.statusCode=A.status,A.headers.forEach((a,m)=>{q.setHeader(m,a)}),A.body){let a=A.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 A.text();q.end(a)}}catch(A){z0.error("[Server] Node request error:",A),q.statusCode=500,q.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),G=new d2({noServer:!0}),X=v();s1(G,()=>X),Y.on("upgrade",(H,q,T)=>{if(new URL(H.url||"/",`http://${H.headers.host}`).pathname==="/terminal/ws")G.handleUpgrade(H,q,T,(c)=>{G.emit("connection",c,H)});else q.destroy()});let V=(H)=>{return new Promise((q,T)=>{Y.once("error",(C)=>{if(C.code==="EADDRINUSE")T(C);else T(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((T)=>{G.close(()=>{Y.close(()=>T())})})}})})().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 V$?.().catch((H)=>{z0.warn("[Server] Failed to recover queued tasks:",H)}),r0?.start(),{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if($)r0?.stop(),await $.stop(),$=void 0,O=void 0,V$=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 V$?.()}catch(H){z0.warn("[Server] Failed to recover queued tasks:",H)}return r0?.start(),{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if($)r0?.stop(),await $.stop(),$=void 0,O=void 0,V$=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 +1 @@
|
|
|
1
|
-
import{$a as i,Ma as a,Na as b,Pa as c,Ta as d,Ua as e,Va as f,Za as g,_a as h,ab as j,bb as k,ib as l,jb as m,kb as n,lb as o,mb as p,nb as q,ob as r}from"./chunk-
|
|
1
|
+
import{$a as i,Ma as a,Na as b,Pa as c,Ta as d,Ua as e,Va as f,Za as g,_a as h,ab as j,bb as k,ib as l,jb as m,kb as n,lb as o,mb as p,nb as q,ob as r}from"./chunk-p42cz164.js";import"./chunk-095x2ykj.js";import"./chunk-97fyx4hr.js";import"./chunk-4hawehmd.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-8j01ssaf.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-kfgv64hg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{C as o}from"./chunk-
|
|
1
|
+
import{C as o}from"./chunk-nysyp11q.js";import{$b as i}from"./chunk-97fyx4hr.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
|
|
2
2
|
export{m as s};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ac as u,bc as qq,cc as e0,dc as Gq,ec as v,fc as $$,gc as Lq,hc as q$,ic as G$,jc as L$,lc as f0,oc as Z$,pc as Zq}from"./chunk-4hawehmd.js";import{od as K0}from"./chunk-8j01ssaf.js";import{Td as B0}from"./chunk-heqs3xan.js";import{ae as I$}from"./chunk-7wjy6kgt.js";import{ee as U0}from"./chunk-4dq9y7zn.js";import{cf as e$,df as $q}from"./chunk-f4z3gkbs.js";import{if as H$}from"./chunk-5s123nbs.js";import{of as V0,rf as x0}from"./chunk-dsj62dcg.js";import{vf as l}from"./chunk-
|
|
1
|
+
import{ac as u,bc as qq,cc as e0,dc as Gq,ec as v,fc as $$,gc as Lq,hc as q$,ic as G$,jc as L$,lc as f0,oc as Z$,pc as Zq}from"./chunk-4hawehmd.js";import{od as K0}from"./chunk-8j01ssaf.js";import{Td as B0}from"./chunk-heqs3xan.js";import{ae as I$}from"./chunk-7wjy6kgt.js";import{ee as U0}from"./chunk-4dq9y7zn.js";import{cf as e$,df as $q}from"./chunk-f4z3gkbs.js";import{if as H$}from"./chunk-5s123nbs.js";import{of as V0,rf as x0}from"./chunk-dsj62dcg.js";import{vf as l}from"./chunk-cy6emyt9.js";import{Cf as s$,Df as H0,Ff as f,Gf as m,If as s0,Jf as c,Kf as J0}from"./chunk-363pgv1e.js";import{readdir as l$,readFile as e,rm as R0,stat as oq}from"node:fs/promises";import*as F from"node:path";import{nanoid as S}from"nanoid";import{createHash as Kq,randomUUID as Bq}from"node:crypto";import*as I from"node:fs/promises";import*as X0 from"node:path";var X$=1;function Yq($,q){let G=Kq("sha256").update(q).digest("hex");return X0.join(H0($),".locks",`${G}.lock`)}function F0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function S0($){try{let q=JSON.parse(await I.readFile($,"utf8"));if(q.version!==X$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function N$($){let q=await S0($);if(q)return q;return await new Promise((G)=>setTimeout(G,10)),S0($)}function Nq($){try{return process.kill($,0),!0}catch(q){return F0(q,"EPERM")}}async function F$($,q){let G;try{return G=await I.open($,"wx",384),await G.writeFile(`${JSON.stringify(q)}
|
|
2
2
|
`,"utf8"),!0}catch(L){if(F0(L,"EEXIST"))return!1;if(G)await I.unlink($).catch(()=>{return});throw L}finally{await G?.close().catch(()=>{return})}}class n extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class i{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=H$()){let G=Yq(q,$),L={version:X$,sessionId:$,ownerId:Bq(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await I.mkdir(X0.dirname(G),{recursive:!0,mode:448}),await F$(G,L))return new i(G,L);let J=await N$(G);if(J&&Nq(J.pid))throw new n(J.pid);if(await I.unlink(G).catch((Z)=>{if(!F0(Z,"ENOENT"))throw Z}),await F$(G,L))return new i(G,L);throw new n((await N$(G))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await S0(this.filePath))?.ownerId!==this.record.ownerId)return;await I.unlink(this.filePath).catch((q)=>{if(!F0(q,"ENOENT"))throw q})}}function Fq($,q){for(let G of $){if(G.type!=="part_created"||G.data.partType!=="tool_result")continue;let L=G.data.payload;if(!L||typeof L!=="object"||Array.isArray(L))continue;let J=L;if(J.toolCallId===q||G.data.partId===q||G.data.messageId===q)return J}return}function W$($){let q=u($),G=new Map;for(let L of q){if(L.type==="interaction_requested"){G.set(L.data.requestId,{request:L.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(L.type==="interaction_responded"){let J=G.get(L.data.requestId);if(J)J.response=L.data;continue}if(L.type==="interaction_recovered"){let J=G.get(L.data.requestId);if(J)J.recovery=L.data}}for(let L of G.values()){let J=Fq(q,L.request.toolCallId);L.hasToolResult=J!==void 0;let Z=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;L.hasRecoveryToolResult=Z?.interactionRecovery===!0&&Z.requestId===L.request.requestId}return[...G.values()]}function T$($){return W$($).reverse().find((q)=>!q.response&&!q.recovery)}function z1($){let q=new Map;for(let G of W$($))q.set(G.request.toolCallId,G);return[...q.values()].filter((G)=>G.response&&!G.recovery&&(!G.hasToolResult||G.hasRecoveryToolResult))}function U$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function W0($){let q=new Map,G=[];for(let L of $){if(L.type==="review_started"){if(!q.has(L.data.reviewId))G.push(L.data.reviewId),q.set(L.data.reviewId,{start:L.data});continue}if(L.type!=="review_completed")continue;let J=q.get(L.data.reviewId);if(J&&J.completion===void 0)J.completion=L.data}return G.map((L)=>q.get(L)).filter((L)=>L!==void 0)}function _1($){return W0($).reverse().find((q)=>q.completion===void 0)}function m0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function O$($,q){let G=["## Code Review","",`Target: ${$.target.label}`,`Status: ${m0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)G.push("","No actionable findings.");else{G.push("","### Findings");for(let[L,J]of q.findings.entries()){let Z=J.codeLocation.lineStart===J.codeLocation.lineEnd?`${J.codeLocation.lineStart}`:`${J.codeLocation.lineStart}-${J.codeLocation.lineEnd}`;G.push("",`${L+1}. ${J.title}`,` ${J.codeLocation.path}:L${Z} · confidence ${J.confidenceScore.toFixed(2)}`,` ${J.body}`)}}if(q.error)G.push("",`Error: ${q.error}`);return G.join(`
|
|
3
3
|
`)}function C$($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((G)=>({title:G.title,body:G.body,priority:G.priority,confidenceScore:G.confidenceScore,codeLocation:{...G.codeLocation}})),...q.error?{error:q.error}:{}}}var I0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function Hq($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function Xq($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";return"runtime"}function Wq($){return{code:$,...I0[$]}}function v0($){return Wq(Xq(Hq($)))}function P0($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in I0))return!1;let G=I0[q.code];return q.message===G.message&&q.retryable===G.retryable}import{promises as G0,realpathSync as Uq}from"node:fs";import T0 from"node:path";import*as o from"fs/promises";import*as O from"path";var z$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class u0{static normalize($,q){let G=O.isAbsolute($)?$:O.resolve(q,$),L=O.normalize(G),J=O.normalize(q);if(!this.isWithinWorkspace(L,J))throw new d(`Path outside workspace: ${$} (resolved to ${L}, workspace: ${J})`,"PATH_OUTSIDE_WORKSPACE");return L}static checkRestricted($){let q=$.split(O.sep);for(let G of z$)if(q.includes(G))throw new d(`Access denied: "${G}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let G=this.normalize($,q);this.checkRestricted(G);try{await o.access(G)}catch(L){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return G}static async resolveSymlink($,q){try{let G=await o.realpath($),L=await o.realpath(q);if(!this.isWithinWorkspace(G,L))throw new d(`Symlink points outside workspace: ${$} -> ${G}`,"SYMLINK_OUTSIDE_WORKSPACE");return G}catch(G){if(G instanceof d)throw G;return $}}static getRelativePath($,q){return O.relative(q,$)}static isWithinWorkspace($,q){let G=O.resolve($),L=O.resolve(q),J=O.relative(L,G);return J===""||J!==".."&&!J.startsWith(`..${O.sep}`)&&!O.isAbsolute(J)}static async isWithinWorkspaceResolved($,q){let G=O.resolve(q),L=O.isAbsolute($)?O.resolve($):O.resolve(G,$);if(!this.isWithinWorkspace(L,G))return!1;let J;try{J=await o.realpath(G)}catch{return!1}let Z=L;while(!0){try{let V=await o.realpath(Z);return this.isWithinWorkspace(V,J)}catch(V){let B=V.code;if(B!=="ENOENT"&&B!=="ENOTDIR")return!1}let Q=O.dirname(Z);if(Q===Z)return!1;Z=Q}}static isRestricted($){let q=$.split(O.sep);return z$.some((G)=>q.includes(G))}}var L0=U0("Tool");class h{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}async recordFileRead($,q){try{let G=await G0.stat($),L={filePath:T0.resolve($),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(L),await this.recordAliases($,L.filePath),L0.debug(`记录文件读取: ${$}`)}catch(G){L0.warn(`记录文件读取失败: ${$}`,G)}}async recordFileEdit($,q,G="edit"){try{let L=await G0.stat($),J={filePath:T0.resolve($),accessTime:Date.now(),mtime:L.mtimeMs,sessionId:q,lastOperation:G};this.setRecord(J),await this.recordAliases($,J.filePath),L0.debug(`记录文件${G==="edit"?"编辑":"写入"}: ${$}`)}catch(L){L0.warn(`记录文件${G==="edit"?"编辑":"写入"}失败: ${$}`,L)}}hasFileBeenRead($,q){let G=this.accessedFiles.get(this.resolveTrackedPath($));if(!G)return!1;return q?G.has(q):G.size>0}async checkFileModification($,q){let G=this.getFileRecord($,q);if(!G)return{modified:!1,message:"文件未被跟踪"};try{let L=await G0.stat($);if(Math.abs(L.mtimeMs-G.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(G.accessTime).toISOString()}, 当前修改时间: ${L.mtime.toISOString()})`};return{modified:!1}}catch(L){let J=L;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification($,q){let G=this.getFileRecord($,q);if(!G)return{isExternal:!1,message:"文件未被跟踪"};try{let L=await G0.stat($);if(L.mtimeMs-G.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(G.accessTime).toISOString()} (${G.lastOperation}) 之后被外部程序修改(当前修改时间: ${L.mtime.toISOString()})`};return{isExternal:!1}}catch(L){let J=L;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return L0.warn(`检查文件外部修改失败: ${$}`,L),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord($,q){let G=this.accessedFiles.get(this.resolveTrackedPath($));if(!G)return;if(q)return G.get(q);return[...G.values()].sort((L,J)=>J.accessTime-L.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let G=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(G),this.removeAliases(G);return}let L=this.accessedFiles.get(G);if(L?.delete(q),L?.size===0)this.accessedFiles.delete(G),this.removeAliases(G)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[G,L]of this.accessedFiles.entries()){if(q&&!u0.isWithinWorkspace(G,q))continue;if(L.delete($),L.size===0)this.accessedFiles.delete(G),this.removeAliases(G)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){h.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(T0.resolve($),q);let G=await G0.realpath($).catch(()=>{return});if(G)this.pathAliases.set(G,q)}resolveTrackedPath($){let q=T0.resolve($);if(this.accessedFiles.has(q))return q;let G=this.pathAliases.get(q);if(G)return G;try{let L=Uq.native(q);return this.pathAliases.get(L)??L}catch{return q}}removeAliases($){for(let[q,G]of this.pathAliases)if(G===$)this.pathAliases.delete(q)}}import*as Z0 from"node:crypto";import{promises as X}from"node:fs";import*as T from"node:path";import h0 from"write-file-atomic";var D$="missing";class O0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(f($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!T.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?T.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=J0();this.snapshotDir=T.join(q,"file-history",this.sessionId),this.manifestPath=T.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await X.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=J0(),q=await X.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),G=Z0.createHash("sha256").update(q).digest("hex").slice(0,24),L=T.join($,"file-history",this.sessionId),J=T.join($,"file-history","workspaces",G,this.sessionId),Z=T.join(J,"manifest.json");try{await X.access(Z)}catch{await this.migrateLegacySnapshotDir(L,J,q)}this.snapshotDir=J,this.manifestPath=Z}async migrateLegacySnapshotDir($,q,G){let L;try{L=JSON.parse(await X.readFile(T.join($,"manifest.json"),"utf8"))}catch{return}if(L.schemaVersion!==1||!Array.isArray(L.snapshots)||!L.snapshots.every((J)=>this.isWithinWorkspace(J.filePath,G)))return;await X.mkdir(T.dirname(q),{recursive:!0,mode:493});try{await X.rename($,q)}catch(J){let Z=J.code;if(Z!=="ENOENT"&&Z!=="EEXIST"&&Z!=="ENOTEMPTY")throw J}}isWithinWorkspace($,q){if(!T.isAbsolute($))return!1;let G=T.relative(q,T.resolve($));return G===""||G!==".."&&!G.startsWith(`..${T.sep}`)&&!T.isAbsolute(G)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let G=await this.resolveFileIdentity($),L=!0;try{await X.access(G)}catch{L=!1}let J=this.trackedFileBackups.get(G),Z=J?J.version+1:1,Q=this.generateFileHash(G,Z),V=this.getSnapshotPath(Q,Z),B=new Date;if(L){let K=await X.readFile(G);await X.writeFile(V,K)}let x={backupFileName:Q,version:Z,backupTime:B};return this.trackedFileBackups.set(G,x),this.snapshots.push({messageId:q,backupFileName:Q,timestamp:B,filePath:G,version:Z,existedBefore:L}),await this.cleanupOldSnapshots(G),await this.persistManifest(),x}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let G=await this.resolveFileIdentity($),L=this.snapshots.find((J)=>J.filePath===G&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!L)throw Error(`未找到待完成的快照: ${G}`);L.postEditHash=await this.hashFile(G),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let G=await this.resolveFileIdentity($),L=this.snapshots.find((J)=>J.filePath===G&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!L)return;this.removeSnapshot(L),await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),G=this.snapshots.slice().reverse().find((Z)=>Z.filePath===q&&Z.postEditHash!==void 0);if(!G?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==G.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let J=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let Z=await X.readFile(J);await X.mkdir(T.dirname(q),{recursive:!0}),await X.writeFile(q,Z)}else await X.rm(q,{force:!0});return this.removeSnapshot(G),await X.rm(J,{force:!0}),await this.persistManifest(),G}async restoreSnapshot($,q){let G=await this.resolveFileIdentity($),L=this.snapshots.slice().reverse().find((Z)=>Z.messageId===q&&Z.filePath===G);if(!L)throw Error(`未找到快照: messageId=${q}, filePath=${G}`);let J=this.getSnapshotPath(L.backupFileName,L.version);if(L.existedBefore){let Z=await X.readFile(J);await X.mkdir(T.dirname(G),{recursive:!0}),await X.writeFile(G,Z)}else await X.rm(G,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((G)=>G.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((G)=>G.filePath),snapshotCount:q.reduce((G,L)=>G+L.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let G=new Map;for(let J of q){let Z,Q=!0;try{Z=await X.readFile(J.filePath)}catch(B){if(B.code!=="ENOENT")throw B;Q=!1}if((Z?Z0.createHash("sha256").update(Z).digest("hex"):D$)!==J.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${J.filePath}`);if(G.set(J.filePath,{existed:Q,content:Z}),J.target.existedBefore)await X.access(this.getSnapshotPath(J.target.backupFileName,J.target.version))}let L=[...this.snapshots];try{for(let Z of q)if(Z.target.existedBefore){let Q=await X.readFile(this.getSnapshotPath(Z.target.backupFileName,Z.target.version));await X.mkdir(T.dirname(Z.filePath),{recursive:!0}),await h0(Z.filePath,Q)}else await X.rm(Z.filePath,{force:!0});let J=new Set(q.flatMap((Z)=>Z.selected));this.snapshots=this.snapshots.filter((Z)=>!J.has(Z)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...J].map((Z)=>X.rm(this.getSnapshotPath(Z.backupFileName,Z.version),{force:!0}).catch(()=>{return})))}catch(J){this.snapshots=L,this.rebuildTrackedFileBackups();let Z=[];for(let[Q,V]of G)try{if(V.existed&&V.content)await h0(Q,V.content);else await X.rm(Q,{force:!0})}catch(B){Z.push(B)}if(Z.length>0)throw AggregateError([J,...Z],"快照回退失败且无法完整恢复回退前状态");throw J}return{files:q.map((J)=>J.filePath),snapshotCount:q.reduce((J,Z)=>J+Z.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),G=new Set(q.flatMap((J)=>J.selected));if(G.size===0)return{files:[],snapshotCount:0};let L=[...this.snapshots];this.snapshots=this.snapshots.filter((J)=>!G.has(J)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(J){throw this.snapshots=L,this.rebuildTrackedFileBackups(),J}return await Promise.all([...G].map((J)=>X.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return}))),{files:q.map((J)=>J.filePath),snapshotCount:G.size}}buildRewindPlan($){let q=new Set($),G=this.snapshots.filter((Z)=>Z.postEditHash!==void 0),L=G.filter((Z)=>q.has(Z.messageId));return[...new Set(L.map((Z)=>Z.filePath))].sort().map((Z)=>{let Q=G.filter((K)=>K.filePath===Z),V=Q.filter((K)=>q.has(K.messageId)),B=Q.indexOf(V[0]),x=Q.slice(B);if(x.length!==V.length||x.some((K)=>!q.has(K.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${Z}`);return{filePath:Z,selected:V,target:V[0],latest:V.at(-1)}})}async loadManifest(){try{let $=await X.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(G)=>({...G,filePath:await this.resolveFileIdentity(G.filePath),timestamp:new Date(G.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await X.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await h0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let G=this.snapshots.filter((L)=>L.filePath===$).slice(0,-this.maxSnapshots);for(let L of G)await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),this.removeSnapshot(L)}async cleanup($=0){let q=this.snapshots.slice().sort((L,J)=>J.timestamp.getTime()-L.timestamp.getTime()),G=new Set(q.slice(0,$));for(let L of this.snapshots)if(!G.has(L))await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return T.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=T.resolve($),G=[],L=q;while(!0){try{let Z=await X.realpath(L);return T.join(Z,...G.reverse())}catch(Z){let Q=Z.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")throw Z}let J=T.dirname(L);if(J===L)return q;G.push(T.basename(L)),L=J}}async hashFile($){try{let q=await X.readFile($);return Z0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return D$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let G=Z0.createHash("md5");return G.update(`${$}:${q}`),G.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}import{createHash as Oq}from"node:crypto";import Cq from"ajv";var E$="StructuredOutput",_$=65536,R$=131072,v1=2,f$=20,M$=1000,A$=200;function r($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function b$($,q){if(!r($))throw Error(`${q} must be a JSON object`);let G;try{G=JSON.stringify($)}catch(J){throw Error(`${q} must be JSON-serializable`,{cause:J})}if(G===void 0)throw Error(`${q} must be JSON-serializable`);let L=JSON.parse(G);if(!r(L))throw Error(`${q} must be a JSON object`);return L}function zq($){let q=0,G=0,L=(J,Z)=>{if(q++,q>M$)throw Error(`Output schema exceeds the ${M$} node complexity limit`);if(Z>f$)throw Error(`Output schema exceeds the ${f$} level depth limit`);if(Array.isArray(J)){for(let Q of J)L(Q,Z+1);return}if(!r(J))return;if("$ref"in J){let Q=J.$ref;if(typeof Q!=="string"||!(Q==="#"||Q.startsWith("#/$defs/")||Q.startsWith("#/definitions/")))throw Error("Output schema only supports self-contained local $ref values")}if("properties"in J&&r(J.properties)){if(G+=Object.keys(J.properties).length,G>A$)throw Error(`Output schema exceeds the ${A$} property limit`)}for(let Q of Object.values(J))L(Q,Z+1)};L($,0)}function Dq($){if(!$||$.length===0)return"Structured output does not match the requested schema";return $.slice(0,8).map((q)=>{return`${q.instancePath||"root"}: ${q.message??q.keyword}`}).join("; ")}function _q($){let q=new Cq({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return q.compile($)}catch(G){throw Error(`Invalid output schema: ${G instanceof Error?G.message:String(G)}`)}}function k$($){let q=b$($,"Output schema"),G=JSON.stringify(q);if(Buffer.byteLength(G)>_$)throw Error(`Output schema exceeds ${_$} bytes`);if(q.type!=="object")throw Error('Output schema root type must be "object"');zq(q);let J=_q(q),Z=Oq("sha256").update(G).digest("hex");return{schema:q,schemaDigest:Z,declaration:{name:E$,description:"Submit the final response as an object matching the requested JSON Schema. Call this exactly once after all requested work and verification are complete.",parameters:q,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(Q){let V;try{V=b$(Q,"Structured output")}catch(x){return{success:!1,message:x instanceof Error?x.message:String(x)}}let B=JSON.stringify(V);if(Buffer.byteLength(B)>R$)return{success:!1,message:`Structured output exceeds ${R$} bytes`};if(!J(V))return{success:!1,message:Dq(J.errors)};return{success:!0,output:V}}}}function w$($,q){if(!r($))return;let G=r($.structuredOutput)?$.structuredOutput:$;if(G.schemaDigest!==q.schemaDigest||!("output"in G))return;let L=q.validate(G.output);return L.success?L.output:void 0}function P1($,q){for(let G=$.length-1;G>=0;G--){let L=$[G];if(!L)continue;if(L.role==="user")return;if(L.role==="assistant"){let Q=w$(L.metadata,q);if(Q)return{output:Q,completed:!0};continue}if(L.role!=="tool"||L.name!==E$)continue;let J=r(L.metadata)?L.metadata:void 0,Z=w$(J?.metadata,q);if(Z)return{output:Z,completed:!1}}return}import{createHash as mq}from"node:crypto";import u$ from"node:path";import{StringDecoder as Aq}from"node:string_decoder";function Rq($,q){let G=q;while(G<$.length&&($[G]&192)===128)G+=1;return G}class c0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?Buffer.from($):Buffer.from($);if(q.length===0)return;this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),omittedBytes:this.omittedBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}trimToLimit(){while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let q=this.retainedBytes-this.maxBytes;if($.length<=q){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length;continue}let G=Rq($,q);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G}}}var C0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},a={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},g$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},fq={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},Mq=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:C0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:C0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:a,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:g$},{pattern:/^git\s+(status|branch|remote)/i,config:a},{pattern:/^git\s+(log|diff|show)/i,config:g$},{pattern:/^(ls|dir|tree)\s+/i,config:a,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:a,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:a,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:C0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:C0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:a,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:a,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class l0{static getConfigForCommand($){for(let{pattern:q,config:G,summaryTemplate:L}of Mq)if(q.test($))return{config:G,summaryTemplate:L};return{config:fq}}static truncate($,q){let{config:G,summaryTemplate:L}=this.getConfigForCommand(q);return this.truncateWithConfig($,G,L)}static truncateWithConfig($,q,G){let L=$.length,J=$.split(`
|
|
4
4
|
`),Z=J.length;if(Z<=q.maxLines&&L<=q.maxChars)return{content:$,truncated:!1,originalLines:Z,originalChars:L};let Q=J.slice(0,q.keepHead),V=J.slice(-q.keepTail),B=Z-q.keepHead-q.keepTail,x=Q.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as R,n as I,o as C,p as v,q as S}from"./chunk-
|
|
1
|
+
import{m as R,n as I,o as C,p as v,q as S}from"./chunk-c9m16hqc.js";import{F as y,L as w}from"./chunk-nysyp11q.js";import"./chunk-c477j84k.js";import"./chunk-p4zt7ts9.js";import{Va as x,hb as U}from"./chunk-p42cz164.js";import"./chunk-095x2ykj.js";import{$b as b,Tb as k}from"./chunk-97fyx4hr.js";import"./chunk-4hawehmd.js";import{sc as P}from"./chunk-x9t4ryyf.js";import{uc as h,vc as O,wc as M}from"./chunk-pmz455nq.js";import{xc as z}from"./chunk-632rgzcf.js";import"./chunk-ktf3bpmw.js";import{Uc as N}from"./chunk-xjyctv33.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-k653znk8.js";import"./chunk-cx0tdprs.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-kfgv64hg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-5wnxafpf.js";import{Ue as D}from"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as E}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import g from"yargs";import{hideBin as c}from"yargs/helpers";var m=new Set(Object.values(D));function d(j){if(j&&m.has(j))return j;return}function l(j){return j.command("* [message]","Print response and exit (useful for pipes)",(q)=>q.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(q)=>{if(!q.p)return;let B=await u(q);process.exit(B)})}async function u(j,q=process){let B;try{await R();let T=await I({message:j.message,_:j._,defaultMessage:"Hello"}),J=await C(T);if(J.mode==="output"){if(J.content)q.stdout.write(`${J.content}
|
|
2
2
|
`);return J.exitCode??0}let K=J.content,X=await v(j),Y=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(Y!==void 0&&X)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:G,messages:F,metadata:V}=await S({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),W=V?.projectPath??E(),Z=d(j.permissionMode)??V?.permissionMode??N()?.permissionMode??"default";await b.setSessionPermissionMode(G,W,Z);let _=await U.cancelPendingNonInteractive(W,G)?await b.loadSession(G,W):F;if(B=await y.create({sessionId:G,workspaceRoot:W,modelId:j.model,permissionMode:Z,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?z(j.agents):void 0,..._.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}}),Y!==void 0){let H=await B.executeUserShellCommand(Y);if(j.outputFormat==="json")q.stdout.write(`${JSON.stringify(H,null,2)}
|
|
3
3
|
`);else if(j.outputFormat==="stream-json")q.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:H.executionId,record:H.record})}
|
|
4
4
|
`);else q.stdout.write(`${k(H.record)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Qc as W}from"./chunk-
|
|
1
|
+
import{Qc as W}from"./chunk-xjyctv33.js";import{$d as X}from"./chunk-kfgv64hg.js";import{ce as Q,ee as U}from"./chunk-4dq9y7zn.js";import{if as V}from"./chunk-5s123nbs.js";function _(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=U("Service");function $(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class F{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!F.instance)F.instance=new F;return F.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await Q()}catch(z){}try{let z=X.getInstance(),J=W(),N=J.session?.sessionId||"unknown",O=J.session?.workspaceRoot||V();if(z.isEnabled(O,N)){let Z=J.config?.config?.permissionMode||"default";await z.executeSessionEndHooks($(b),{projectDir:O,sessionId:N,permissionMode:Z})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,Y=new Promise((z,J)=>{setTimeout(()=>{J(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,Y])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{_(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var K=()=>{return F.getInstance()},P=(b)=>{return K().registerCleanup(b)},L=()=>{K().initialize()},k=(b=0)=>{K().shutdown("normal",b)};
|
|
4
4
|
export{K as yc,P as zc,L as Ac,k as Bc};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-vmq248m7.js";import"./chunk-4dq9y7zn.js";import{Se as Q}from"./chunk-
|
|
2
|
-
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-h6w3ggx9.js"),{SessionService:B}=await import("./chunk-
|
|
1
|
+
import"./chunk-vmq248m7.js";import"./chunk-4dq9y7zn.js";import{Se as Q}from"./chunk-5wnxafpf.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as L}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import{Mf as F}from"./chunk-g11hq0e5.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
|
|
2
|
+
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-h6w3ggx9.js"),{SessionService:B}=await import("./chunk-097zrzyy.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
|
|
3
3
|
`);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
|
|
4
4
|
Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
|