blade-code 0.7.4 → 0.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-10q3krvh.js +6 -0
  3. package/dist/chunk-1tzcptyb.js +3 -0
  4. package/dist/{chunk-erpgkabk.js → chunk-1y33d6xh.js} +1 -1
  5. package/dist/chunk-5accz8n9.js +1 -0
  6. package/dist/{chunk-kfg3vx5z.js → chunk-64x50qbc.js} +1 -1
  7. package/dist/chunk-8raa4q9y.js +1564 -0
  8. package/dist/chunk-ad19yrq6.js +1 -0
  9. package/dist/{chunk-4e2fzyf2.js → chunk-arwynrtf.js} +2 -2
  10. package/dist/chunk-bvn4e2vq.js +1 -0
  11. package/dist/{chunk-63dzf6hr.js → chunk-cadngkwr.js} +1 -1
  12. package/dist/{chunk-98jpdmgc.js → chunk-cdx3hp1r.js} +5 -5
  13. package/dist/{chunk-373pmz70.js → chunk-d9qh7bat.js} +1 -1
  14. package/dist/chunk-ebynn53v.js +26 -0
  15. package/dist/{chunk-cyxb6fxe.js → chunk-ezkbqmvd.js} +1 -1
  16. package/dist/{chunk-7mnefph6.js → chunk-fceeqn6k.js} +2 -2
  17. package/dist/{chunk-egavbybx.js → chunk-g60w2r7f.js} +2 -2
  18. package/dist/{chunk-k4behavv.js → chunk-h7qab07x.js} +1 -1
  19. package/dist/{chunk-bmcc85nj.js → chunk-jhzf05kz.js} +1 -1
  20. package/dist/chunk-k76q8cyc.js +151 -0
  21. package/dist/chunk-krrm6bjr.js +1 -0
  22. package/dist/{chunk-gjf2d2yg.js → chunk-m3hsaaq5.js} +1 -1
  23. package/dist/chunk-n2yq1wn8.js +9 -0
  24. package/dist/{chunk-rtn0rb16.js → chunk-npaj13y3.js} +2 -2
  25. package/dist/{chunk-byxazdwv.js → chunk-pf45ctn7.js} +1 -1
  26. package/dist/{chunk-cw125vv3.js → chunk-q6sj33v8.js} +1 -1
  27. package/dist/chunk-qedtzcp2.js +1 -0
  28. package/dist/{chunk-e21htmg4.js → chunk-qyfdt8h1.js} +1 -1
  29. package/dist/{chunk-38h3yh6z.js → chunk-r0hc7wad.js} +1 -1
  30. package/dist/chunk-rhvxr82g.js +2 -0
  31. package/dist/chunk-t6qek6xk.js +1 -0
  32. package/dist/{chunk-jf48kahn.js → chunk-ttf06k8y.js} +3 -3
  33. package/dist/chunk-tyjns370.js +1 -0
  34. package/dist/{chunk-3mhbped9.js → chunk-ve6bvba4.js} +36 -36
  35. package/dist/chunk-wdxbjvd5.js +2 -0
  36. package/dist/{chunk-b1d49byc.js → chunk-wg5nxtb2.js} +1 -1
  37. package/dist/{chunk-qxvp127d.js → chunk-wstkn75a.js} +1 -1
  38. package/dist/chunk-x4fx52e7.js +24 -0
  39. package/dist/chunk-xj63cr29.js +1 -0
  40. package/dist/{chunk-by93yn92.js → chunk-zmndvdgb.js} +1 -1
  41. package/dist/{chunk-pvxp2gzr.js → chunk-zr71r1z1.js} +1 -1
  42. package/dist/web/assets/{FilePreview-evNzCuVx.js → FilePreview-CbtOITD1.js} +1 -1
  43. package/dist/web/assets/{MarkdownRenderer-BQoiQTDd.js → MarkdownRenderer-CW8WpEw1.js} +1 -1
  44. package/dist/web/assets/McpModal-DnqrgBON.js +5 -0
  45. package/dist/web/assets/SettingsModal-CRNT-LCq.js +1 -0
  46. package/dist/web/assets/{SettingsStore-CfDjhOkS.js → SettingsStore-B2GIhfKs.js} +1 -1
  47. package/dist/web/assets/SkillsModal-COQMbIdT.js +1 -0
  48. package/dist/web/assets/{TerminalPanel-Cs16_6ew.js → TerminalPanel-dCMUvQaH.js} +1 -1
  49. package/dist/web/assets/index-21gV5nOE.css +1 -0
  50. package/dist/web/assets/index-Cnz-_jPt.js +10 -0
  51. package/dist/web/assets/{useRequest-BJp539HQ.js → useRequest-C7k7cDPD.js} +1 -1
  52. package/dist/web/assets/{vendor-icons-DlzC8I7m.js → vendor-icons-BKXQ7ALf.js} +75 -30
  53. package/dist/web/assets/{vendor-radix-CfxBc_4-.js → vendor-radix-2yBsoRqx.js} +2 -2
  54. package/dist/web/index.html +2 -2
  55. package/package.json +1 -1
  56. package/dist/chunk-1vngdr7p.js +0 -1
  57. package/dist/chunk-501my8nh.js +0 -6
  58. package/dist/chunk-5smacbk0.js +0 -24
  59. package/dist/chunk-6rszb7xd.js +0 -1534
  60. package/dist/chunk-aevyre2t.js +0 -1
  61. package/dist/chunk-b4hmtjec.js +0 -1
  62. package/dist/chunk-cqrg2pp7.js +0 -1
  63. package/dist/chunk-ctbhcw8h.js +0 -1
  64. package/dist/chunk-dftaxwg9.js +0 -1
  65. package/dist/chunk-gzc9n5d6.js +0 -2
  66. package/dist/chunk-jpry8h07.js +0 -1
  67. package/dist/chunk-n5rg9dbv.js +0 -151
  68. package/dist/chunk-pa364yr9.js +0 -1
  69. package/dist/chunk-rkhhzc4r.js +0 -26
  70. package/dist/chunk-w1zb8zac.js +0 -3
  71. package/dist/chunk-z7x21493.js +0 -7
  72. package/dist/web/assets/McpModal-BT9OivhK.js +0 -5
  73. package/dist/web/assets/SettingsModal-CDRcorCS.js +0 -1
  74. package/dist/web/assets/SkillsModal-DCPaqoOe.js +0 -1
  75. package/dist/web/assets/dialog-C8VDk-ma.js +0 -1
  76. package/dist/web/assets/index-9t-WxRrl.js +0 -10
  77. package/dist/web/assets/index-Bu13aXyE.css +0 -1
@@ -1 +0,0 @@
1
- import{v as a,w as b,x as c}from"./chunk-cw125vv3.js";import"./chunk-k4behavv.js";import"./chunk-e21htmg4.js";import"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-63dzf6hr.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1 +0,0 @@
1
- import{ma as a,na as b,oa as c,pa as d,qa as e,ra as f,sa as g,ta as h,ua as i,va as j,wa as k,xa as l,ya as m}from"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-63dzf6hr.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,h as getAllModels,g as ensureStoreInitialized,m as configActions,d as appActions};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e}from"./chunk-gjf2d2yg.js";import"./chunk-kfg3vx5z.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +0,0 @@
1
- import{f as y,g as A,h as C,i as D}from"./chunk-gzc9n5d6.js";import"./chunk-pvxp2gzr.js";import"./chunk-6rszb7xd.js";import"./chunk-e21htmg4.js";import"./chunk-7mnefph6.js";import"./chunk-rtn0rb16.js";import{sa as q}from"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-4e2fzyf2.js";import"./chunk-3mhbped9.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-b1d49byc.js";import"./chunk-4e2fzyf2.js";import"./chunk-kfg3vx5z.js";export{a as globalOptions,b as cliConfig};
@@ -1,2 +0,0 @@
1
- import{j as mf,k as Lf}from"./chunk-pvxp2gzr.js";import{A as hf,C as Jf,D as Mf,H as Gf,I as h,K as _f,L as Cf,N as zf,Q as S,X as If}from"./chunk-6rszb7xd.js";import{_ as y}from"./chunk-7mnefph6.js";import{ra as d,ta as Af,ua as Tf,ya as L}from"./chunk-5smacbk0.js";import{Ea as l}from"./chunk-4e2fzyf2.js";import{Ka as Pf,Ma as ff,Va as Of}from"./chunk-3mhbped9.js";import{tb as W}from"./chunk-63dzf6hr.js";import{Lb as B}from"./chunk-w1zb8zac.js";import{Nb as Ef}from"./chunk-kfg3vx5z.js";var g0={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 d0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as R0}from"hono";import{cors as m0}from"hono/cors";import{existsSync as af,readFileSync as Qf}from"node:fs";import{createServer as L0}from"node:http";import{networkInterfaces as y0}from"node:os";import{dirname as P0,extname as k0,join as u}from"node:path";import{fileURLToPath as S0}from"node:url";import{WebSocketServer as h0}from"ws";import{z as e}from"zod";class t extends Error{code;statusCode;constructor(V,$,f=500){super($);this.code=V;this.statusCode=f;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class p extends t{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class z extends t{constructor(V){super("BAD_REQUEST",V,400)}}var o0=e.object({error:e.object({code:e.string(),message:e.string()})});import{Hono as ef}from"hono";import{z as g}from"zod";var Kf=B("Service"),sf=g.object({updates:g.record(g.any()),options:g.object({scope:g.enum(["local","project","global"]).optional(),immediate:g.boolean().optional()}).optional()}),Bf=()=>{let V=new ef;return V.get("/",async($)=>{try{let f=d();return $.json(f||{})}catch(f){return Kf.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),J=sf.safeParse(f);if(!J.success)throw new z("Invalid config update format");let{updates:Y,options:j}=J.data;return await L().updateConfig(Y,j),$.json({success:!0,updates:Y})}catch(f){throw Kf.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=d();return $.json(f?.permissions||{})}catch(f){return Kf.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as f0}from"hono";var Wf=()=>{let V=new f0;return V.get("/health",($)=>{return $.json({healthy:!0,version:l()})}),V.get("/info",($)=>{return $.json({version:l(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:W()})}),V};import{Hono as $0}from"hono";var n=B("Service"),qf=()=>{let V=new $0;return V.get("/",async($)=>{try{let J=y.getInstance().getAllServers(),Y=Array.from(J.entries()).map(([j,K])=>({id:j,name:j,status:K.status==="connected"?"connected":K.status==="connecting"?"connecting":K.lastError?"error":"offline",endpoint:K.config.command?`${K.config.command} ${(K.config.args||[]).join(" ")}`.trim():K.config.url||"Unknown",description:`MCP server: ${j}`,tools:K.tools.map((X)=>X.name),connectedAt:K.connectedAt?.toISOString(),error:K.lastError?.message}));return $.json(Y)}catch(f){return n.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await y.getInstance().connectServer(f),$.json({success:!0})}catch(f){return n.error("[McpRoutes] Failed to connect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/:name/disconnect",async($)=>{try{let f=$.req.param("name");return await y.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return n.error("[McpRoutes] Failed to disconnect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name");await y.getInstance().unregisterServer(f);let Y=d();if(Y?.mcpServers){let{[f]:j,...K}=Y.mcpServers;await L().updateConfig({mcpServers:K})}return $.json({success:!0})}catch(f){return n.error("[McpRoutes] Failed to delete MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/",async($)=>{try{let f=await $.req.json(),{name:J,config:Y}=f;if(!J||!Y)return $.json({success:!1,error:"Missing name or config"},400);await y.getInstance().registerServer(J,Y);let K=d();return await L().updateConfig({mcpServers:{...K?.mcpServers,[J]:Y}}),$.json({success:!0})}catch(f){return n.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as V0}from"hono";var s=B("Service"),Hf=()=>{let V=new V0;return V.get("/",async($)=>{try{let f=Af(),J=Tf();return $.json({configured:f,current:J})}catch(f){return s.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:J,name:Y,model:j,baseUrl:K,apiKey:X}=f;if(!j)throw new z("model is required");let Q=await L().addModel({provider:J||"openai-compatible",name:Y||j,model:j,baseUrl:K||void 0,apiKey:X||void 0});return $.json({success:!0,model:Q})}catch(f){throw s.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),J=await $.req.json(),{baseUrl:Y,apiKey:j,model:K}=J;return await L().updateModel(f,{baseUrl:Y||void 0,apiKey:j||void 0,model:K||void 0}),$.json({success:!0})}catch(f){throw s.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await L().removeModel(f),$.json({success:!0})}catch(f){throw s.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as X0}from"hono";import{z as w}from"zod";import{Hono as J0}from"hono";import{streamSSE as Q0}from"hono/streaming";import{LRUCache as Y0}from"lru-cache";import{nanoid as I}from"nanoid";import{z as T}from"zod";var q=B("Service"),Z0=T.object({title:T.string().optional(),projectPath:T.string().optional()}),K0=T.object({content:T.string(),attachments:T.array(T.object({type:T.enum(["file","image","url"]),path:T.string().optional(),url:T.string().optional(),content:T.string().optional(),mimeType:T.string().optional(),name:T.string().optional()})).optional(),permissionMode:T.enum(["default","autoEdit","plan","yolo"]).optional()}),O0=T.object({title:T.string().optional()}),b=new Map,D=new Y0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),q.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),G0=(V)=>{if(!V||typeof V!=="object")return V;let $={...V},f=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>f)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>f)delete $.newContent;return $};function jf(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
2
- `)}function j0(V,$){let f=($??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(f.length===0)return V;let J=[];if(V.trim())J.push({type:"text",text:V});return J.push(...f),J}var bf=()=>{let V=new J0,$=new Map,f=new Map,J=new Map,Y=async(Q)=>{let Z=$.get(Q.id);if(Z)return Z;let O=f.get(Q.id);if(!O)O=Gf.create({sessionId:Q.id,workspaceRoot:Q.projectPath}),f.set(Q.id,O);try{let G=await O;return $.set(Q.id,G),G}finally{if(f.get(Q.id)===O)f.delete(Q.id)}},j=async(Q,Z)=>{let O=b.get(Q);if(O)return O;let G=J.get(Q);if(!G)G=(async()=>{let N=(await S.listSessions()).find((U)=>U.sessionId===Q),x=N?.projectPath??Z,A=N?await S.loadSession(Q,x).catch(()=>[]):[],F={id:Q,projectPath:x,title:`Session ${Q.slice(0,6)}`,createdAt:N?new Date(N.firstMessageTime):new Date,messages:A,relationType:N?.relationType};return b.set(Q,F),F})(),J.set(Q,G);try{return await G}finally{if(J.get(Q)===G)J.delete(Q)}},K=(Q,Z,O,G=!1)=>{let N=I(12),x={id:N,sessionId:Q.id,status:"running",abortController:new AbortController,createdAt:new Date};return D.set(N,x),Q.currentRunId=N,N0(x,Q,Z,O,Y,{pendingInputOnly:G}).catch((A)=>{q.error(`[SessionRoutes] Run ${N} failed:`,A)}),x},X=async(Q)=>{let Z=Q.currentRunId?D.get(Q.currentRunId):void 0;if(Z&&(Z.status==="running"||Z.status==="waiting_permission"))return;if(!await Gf.hasPendingInbox(Q.projectPath,Q.id))return;let O=await Y(Q),G=Q.currentRunId?D.get(Q.currentRunId):void 0;if(G&&(G.status==="running"||G.status==="waiting_permission"))return;if(O.getPendingSteeringCount()===0||O.hasTurnOwner())return;K(Q,"","default",!0)};return V.get("/",async(Q)=>{try{let Z=await S.listSessions(),O=new Set(Z.filter((E)=>E.relationType==="subagent").map((E)=>E.sessionId)),G=Array.from(b.values()).filter((E)=>!O.has(E.id)&&E.relationType!=="subagent").map((E)=>({sessionId:E.id,projectPath:E.projectPath,title:E.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:E.messages.length,firstMessageTime:E.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0})),N=new Set(G.map((E)=>E.sessionId)),x=Z.filter((E)=>!b.has(E.sessionId)&&!N.has(E.sessionId)&&E.relationType!=="subagent"),A=new Set(N),F=x.filter((E)=>{if(A.has(E.sessionId))return!1;return A.add(E.sessionId),!0}),U=[...G,...F];return Q.json(U)}catch(Z){return q.error("[SessionRoutes] Failed to list sessions:",Z),Q.json([])}}),V.post("/",async(Q)=>{try{let Z=await Q.req.json(),O=Z0.safeParse(Z);if(!O.success)throw new z("Invalid request body");let{title:G,projectPath:N}=O.data,x=I(12),A=N||Q.get("directory")||W(),F={id:x,projectPath:A,title:G||`Session ${x.slice(0,6)}`,createdAt:new Date,messages:[]};return b.set(x,F),Q.json({sessionId:x,projectPath:A,title:F.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:0,firstMessageTime:F.createdAt.toISOString(),lastMessageTime:F.createdAt.toISOString(),hasErrors:!1})}catch(Z){throw q.error("[SessionRoutes] Failed to create session:",Z),Z}}),V.get("/:sessionId",async(Q)=>{let Z=Q.req.param("sessionId"),O=b.get(Z);if(O)return Q.json({sessionId:O.id,projectPath:O.projectPath,title:O.title,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0});try{let N=(await S.listSessions()).find((x)=>x.sessionId===Z);if(!N)throw new p("Session",Z);return Q.json(N)}catch(G){if(G instanceof p)throw G;throw q.error("[SessionRoutes] Failed to get session:",G),G}}),V.patch("/:sessionId",async(Q)=>{let Z=Q.req.param("sessionId");try{let O=await Q.req.json(),G=O0.safeParse(O);if(!G.success)throw new z("Invalid request body");let{title:N}=G.data,x=b.get(Z);if(x&&N)x.title=N;return Q.json({success:!0,title:N})}catch(O){throw q.error("[SessionRoutes] Failed to update session:",O),O}}),V.delete("/:sessionId",async(Q)=>{let Z=Q.req.param("sessionId"),O=b.get(Z);if(O?.currentRunId){let N=D.get(O.currentRunId);if(N)N.abortController.abort(),h.publish(Z,"run.cancelled",{runId:N.id}),D.delete(O.currentRunId)}try{await S.deleteSession(Z)}catch(N){q.warn("[SessionRoutes] Failed to delete session file:",N)}b.delete(Z),J.delete(Z),f.delete(Z);let G=$.get(Z);if(G){if(await G.dispose(),$.delete(Z),$.size===0)await y.getInstance().disconnectAll()}return Q.json({success:!0})}),V.get("/:sessionId/message",async(Q)=>{let Z=Q.req.param("sessionId");try{let O=await S.loadSession(Z);return Q.json(O)}catch(O){return q.error("[SessionRoutes] Failed to get messages:",O),Q.json([])}}),V.get("/:sessionId/events",async(Q)=>{let Z=Q.req.param("sessionId"),O=await j(Z,Q.get("directory")||W());return Q0(Q,async(G)=>{await G.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:Z,timestamp:Date.now()}})});let x=h.subscribe((F)=>{if(F.sessionId!==Z)return;G.writeSSE({data:JSON.stringify({type:F.type,properties:{sessionId:F.sessionId,...F.properties}})}).catch(()=>{})});X(O).catch((F)=>{q.error(`[SessionRoutes] Failed to resume pending input for ${Z}:`,F)});let A=setInterval(()=>{if(!G.aborted)G.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(()=>{})},15000);G.onAbort(()=>{clearInterval(A),x()});while(!0)if(await new Promise((F)=>setTimeout(F,1000)),G.aborted)break})}),V.post("/:sessionId/message",async(Q)=>{let Z=Q.req.param("sessionId"),O=await Q.req.json(),G=K0.safeParse(O);if(!G.success)throw new z("Invalid message format");let{content:N,attachments:x,permissionMode:A}=G.data,F=A||"default",U=Q.get("directory")||W(),E=j0(N,x),C=await j(Z,U),M=C.currentRunId?D.get(C.currentRunId):void 0;if(M&&(M.status==="running"||M.status==="waiting_permission")){let R=await(await Y(C)).enqueueSteering(E,{allowBeforeTurn:!0});if(!R.accepted)return Q.json({status:"rejected",reason:R.reason??"turn_unavailable"},409);let r=I(12),a=R.queued;h.publish(Z,"message.created",{messageId:r,role:"user",content:jf(E)});let Yf=R.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(h.publish(Z,Yf,{runId:M.id,messageId:r,queued:a}),R.delivery==="next_turn"&&M.status!=="running"&&M.status!=="waiting_permission")X(C).catch((Zf)=>{q.error(`[SessionRoutes] Failed to wake queued follow-up for ${Z}:`,Zf)});if(R.delivery==="next_turn")M.pendingFollowUpRequested=!0;return Q.json({runId:M.id,status:R.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:a},202)}let H=K(C,E,F);return Q.json({runId:H.id,status:"running"},202)}),V.post("/:sessionId/abort",async(Q)=>{let Z=Q.req.param("sessionId"),O=b.get(Z);if(O?.currentRunId){let G=D.get(O.currentRunId);if(G)G.abortController.abort(),G.status="cancelled",h.publish(Z,"run.cancelled",{runId:G.id})}return Q.json({success:!0})}),V.get("/:sessionId/status",async(Q)=>{let Z=Q.req.param("sessionId"),O=b.get(Z);if(!O?.currentRunId)return Q.json({sessionId:Z,status:"idle"});let G=D.get(O.currentRunId);return Q.json({sessionId:Z,runId:O.currentRunId,status:G?.status||"idle"})}),V};async function N0(V,$,f,J,Y,j={}){let{abortController:K,sessionId:X,id:Q}=V,Z=I(12),O=j.pendingInputOnly?void 0:I(12),G=(N,x)=>{h.publish(X,N,x)};try{if(!j.pendingInputOnly)G("message.created",{messageId:Z,role:"user",content:jf(f)});if(G("session.status",{status:"running"}),O)G("message.created",{messageId:O,role:"assistant",content:""});let N=await Y($),x=await zf.createWithRuntime(N,{sessionId:X}),A=async(M)=>{let H=I(12),nf=300000;V.status="waiting_permission";let R=new Promise((a)=>{let Yf=setTimeout(()=>{q.warn(`[SessionRoutes] Permission ${H} timed out after 300000ms`),G("permission.timeout",{requestId:H}),a({approved:!1,reason:"timeout"})},300000);V.pendingPermission={permissionId:H,resolve:(Zf)=>{clearTimeout(Yf),a(Zf)},details:M}});G("permission.asked",{requestId:H,toolName:M.toolName,description:M.message,args:M.args,details:M}),q.info(`[SessionRoutes] Permission request created: ${H}, runId: ${Q}`);let r=await R;return q.info(`[SessionRoutes] Permission response received: ${H}, approved: ${r.approved}`),V.status="running",V.pendingPermission=void 0,r},F={messages:[...$.messages],userId:"web-user",sessionId:X,workspaceRoot:$.projectPath,signal:K.signal,permissionMode:J,confirmationHandler:{requestConfirmation:A}},U=()=>{if(!O)O=I(12),G("message.created",{messageId:O,role:"assistant",content:""});return O},E=async(M)=>{switch(M.kind){case"content_delta":G("message.delta",{messageId:U(),delta:M.delta});break;case"thinking_delta":G("thinking.delta",{delta:M.delta});break;case"tool_start":if("function"in M.toolCall)G("tool.start",{messageId:U(),toolName:M.toolCall.function.name,toolCallId:M.toolCall.id,arguments:M.toolCall.function.arguments,toolKind:M.toolKind});break;case"tool_result":if("function"in M.toolCall)G("tool.result",{messageId:U(),toolName:M.toolCall.function.name,toolCallId:M.toolCall.id,success:M.result.success,summary:M.result.metadata?.summary,output:Cf(_f(M.toolCall.function.name,M.result)),metadata:G0(M.result.metadata)});break;case"token_usage":G("token.usage",{...M.usage});break;case"turn_start":G("turn.started",{turn:M.turn,maxTurns:M.maxTurns});break;case"steering_applied":G("steering.applied",{runId:Q,messageIds:M.messageIds,count:M.count,recovered:M.recovered,delivery:M.delivery,queued:N.getPendingSteeringCount()});break;case"follow_up_started":{if(O)G("message.complete",{messageId:O}),O=void 0;for(let H of M.messages){if(!H.recovered||H.persisted)continue;G("message.created",{messageId:H.id,role:"user",content:jf(H.content),recovered:!0})}G("follow_up.started",{runId:Q,queued:M.queued,recovered:M.recovered}),U();break}case"compaction":G(M.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":G("model.fallback",{});break;case"task_update":G("task.updated",{tasks:M.tasks});break;default:break}},C=await Of(x.chatStream(f,F,{stream:!0,pendingInputOnly:j.pendingInputOnly}),E);for(let M=0;M<20;M++){let H=V.pendingFollowUpRequested===!0;if(V.pendingFollowUpRequested=!1,N.getPendingSteeringCount()===0){if(!H)break;continue}if(K.signal.aborted)break;C=await Of(x.chatStream("",F,{stream:!0,pendingInputOnly:!0}),E)}if($.messages=[...F.messages],O)G("message.complete",{messageId:O});G("thinking.completed",{}),V.status="completed",G("session.completed",{runId:Q,outputTruncated:C.metadata?.outputTruncated??!1}),G("session.status",{status:"idle"})}catch(N){q.error("[SessionRoutes] Agent execution error:",N),V.status="failed",G("session.error",{error:N instanceof Error?N.message:"Unknown error"}),G("session.status",{status:"error"})}}function wf(V,$,f){q.info(`[SessionRoutes] Looking for permission ${$} in session ${V}`),q.info(`[SessionRoutes] Active runs: ${D.size}`);for(let[J,Y]of D.entries())if(q.info(`[SessionRoutes] Checking run ${J}: sessionId=${Y.sessionId}, pendingPermission=${Y.pendingPermission?.permissionId}`),Y.sessionId===V&&Y.pendingPermission?.permissionId===$)return Y.pendingPermission.resolve(f),q.info(`[SessionRoutes] Permission ${$} responded, runId: ${Y.id}`),!0;return q.error(`[SessionRoutes] Permission not found: ${$}`),!1}var Nf=B("Service"),M0=w.object({approved:w.boolean(),remember:w.boolean().optional(),scope:w.enum(["once","session"]).optional(),targetMode:w.enum(["default","autoEdit","plan","yolo"]).optional(),feedback:w.string().optional(),answers:w.record(w.union([w.string(),w.array(w.string())])).optional()}),Df=()=>{let V=new X0;return V.post("/:permissionId",async($)=>{let f=$.req.param("permissionId"),J=$.req.query("sessionId");Nf.info(`[PermissionRoutes] Received permission response: permissionId=${f}, sessionId=${J}`);try{let Y=await $.req.json(),j=M0.safeParse(Y);if(!j.success)throw new z("Invalid permission response format");let{approved:K,remember:X,scope:Q,targetMode:Z,feedback:O,answers:G}=j.data;if(!J)throw new z("sessionId query parameter is required");if(!wf(J,f,{approved:K,reason:O,scope:Q,targetMode:Z,feedback:O,answers:G}))throw new p("Permission request",f);return Nf.info(`[PermissionRoutes] Permission ${f} ${K?"approved":"denied"}`),$.json({success:!0,approved:K,remember:X})}catch(Y){throw Nf.error("[PermissionRoutes] Failed to respond to permission:",Y),Y}}),V};import{Hono as E0}from"hono";var Rf=B("Service"),yf=()=>{let V=new E0;return V.get("/",async($)=>{try{let f=await mf();return $.json(f)}catch(f){return Rf.error("[ProviderRoutes] Failed to list providers:",f),$.json([])}}),V.get("/:provider/models",async($)=>{let f=$.req.param("provider");try{let J=await Lf(f);return $.json(J)}catch(J){return Rf.error("[ProviderRoutes] Failed to list models:",J),$.json([])}}),V};import{Hono as F0}from"hono";import*as P from"node:fs/promises";import{homedir as x0}from"node:os";import*as $f from"node:path";var v=B("Service"),Xf=$f.join(x0(),".blade","skills-config.json");async function kf(){try{let V=await P.readFile(Xf,"utf-8");return JSON.parse(V)}catch{return{disabled:[]}}}async function U0(V){await P.mkdir($f.dirname(Xf),{recursive:!0}),await P.writeFile(Xf,JSON.stringify(V,null,2))}async function B0(V,$){let f=await kf();if($)f.disabled=f.disabled.filter((J)=>J!==V);else if(!f.disabled.includes(V))f.disabled.push(V);await U0(f)}var c=null,W0=300000;async function q0(){if(c&&Date.now()-c.timestamp<W0)return c.data;try{let V=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!V.ok)return v.warn(`GitHub API returned ${V.status}`),c?.data||[];let $=await V.json(),f=[];for(let J of $){if(J.type!=="dir")continue;let Y=`Official ${J.name} skill`;try{let j=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${J.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(j.ok){let X=(await j.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(X)Y=X[1].trim().slice(0,100)}}catch{}f.push({name:J.name,description:Y,tag:"Official",author:"Anthropic"})}return c={data:f,timestamp:Date.now()},f}catch(V){return v.warn("Failed to fetch skills catalog from GitHub:",V),c?.data||[]}}var Sf=()=>{let V=new F0;return V.get("/",async($)=>{try{let f=ff();await f.initialize();let J=f.getAll(),Y=await kf(),j=J.map((K)=>({id:K.name,name:K.name,enabled:!Y.disabled.includes(K.name),description:K.description||"",version:K.version||"1.0.0",provider:"Local",location:K.source==="builtin"?"Built-in":K.basePath,capabilities:["prompts"],allowedTools:K.allowedTools||[]}));return $.json(j)}catch(f){return v.error("[SkillsRoutes] Failed to get skills:",f),$.json([])}}),V.post("/:name/toggle",async($)=>{try{let f=$.req.param("name"),J=await $.req.json();return await B0(f,J.enabled),$.json({success:!0,enabled:J.enabled})}catch(f){return v.error("[SkillsRoutes] Failed to toggle skill:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name"),J=`${process.env.HOME}/.blade/skills/${f}`;return await P.rm(J,{recursive:!0,force:!0}),await ff().refresh(),$.json({success:!0})}catch(f){return v.error("[SkillsRoutes] Failed to uninstall skill:",f),$.json({success:!1,error:f.message},500)}}),V.post("/install",async($)=>{try{let f=await $.req.json(),J=Pf(),Y=ff(),j=!1;if(f.source==="catalog"&&f.name){if(j=await J.installOfficialSkill(f.name),!j)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(f.source==="repo"&&f.url){if(j=await J.installFromRepo(f.url,f.name),!j)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(f.source==="local"&&f.path){if(j=await J.installFromLocal(f.path,f.name),!j)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await Y.refresh(),$.json({success:!0})}catch(f){return v.error("[SkillsRoutes] Failed to install skill:",f),$.json({success:!1,error:f.message},500)}}),V.get("/catalog",async($)=>{try{let f=await q0();return $.json(f)}catch(f){return v.error("[SkillsRoutes] Failed to get catalog:",f),$.json([])}}),V};import A0 from"fast-glob";import{Hono as T0}from"hono";import{execSync as H0}from"node:child_process";import{readdir as _0}from"node:fs/promises";import Vf from"node:path";var i=B("Service"),C0=(V)=>{try{return H0("git rev-parse --abbrev-ref HEAD",{cwd:V,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},z0=[...Jf.map((V)=>`${V}/**`),...Jf,...Mf.map((V)=>`**/${V}`)],b0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),vf=()=>{let V=new T0;return V.get("/commands",async($)=>{try{let f=$.req.query("q")||"",J=If(f).filter((Y)=>!b0.has(Y.command));return $.json(J)}catch(f){return i.error("[SuggestionsRoutes] Failed to get command suggestions:",f),$.json([])}}),V.get("/files",async($)=>{try{let f=$.req.query("q")||"",J=$.get("directory")||W(),Y=Math.min(Number($.req.query("limit"))||100,1000),K=(await A0("**/*",{cwd:J,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:z0})).map((Z)=>Z.replace(/\\/g,"/"));if(!f)return $.json(K.slice(0,Y));let X=f.toLowerCase(),Q=K.filter((Z)=>Z.toLowerCase().includes(X)).slice(0,Y);return $.json(Q)}catch(f){return i.error("[SuggestionsRoutes] Failed to get file suggestions:",f),$.json([])}}),V.get("/files/tree",async($)=>{try{let f=$.get("directory")||W(),J=$.req.query("path")||"",Y=J?Vf.join(f,J):f,K=(await _0(Y,{withFileTypes:!0})).map((Z)=>({name:Z.name,path:J?`${J}/${Z.name}`:Z.name,type:Z.isDirectory()?"dir":"file"}));K.sort((Z,O)=>{if(Z.type!==O.type)return Z.type==="dir"?-1:1;return Z.name.localeCompare(O.name)});let X=new Set(Jf),Q=K.filter((Z)=>{let O=Z.name;if(O.startsWith("."))return!1;if(X.has(O))return!1;for(let G of Mf)if(O.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(Q)}catch(f){return i.error("[SuggestionsRoutes] Failed to get file tree:",f),$.json([])}}),V.get("/files/content",async($)=>{try{let f=$.req.query("path");if(!f)return $.json({error:"Missing file path"},400);let J=$.get("directory")||W(),Y=Vf.resolve(J,f),j=Vf.relative(J,Y);if(j.startsWith("..")||Vf.isAbsolute(j))return $.json({error:"Invalid file path"},400);let K=hf(),X=await K.stat(Y);if(!X?.isFile)return $.json({error:"File not found"},404);let Q=200000,Z=await K.readTextFile(Y),O=Z.length>Q;return $.json({path:f,content:O?Z.slice(0,Q):Z,truncated:O,size:X.size})}catch(f){return i.error("[SuggestionsRoutes] Failed to get file content:",f),$.json({error:"Failed to read file"},500)}}),V.get("/git-info",async($)=>{try{let f=$.get("directory")||W(),J=C0(f);return $.json({branch:J})}catch(f){return i.error("[SuggestionsRoutes] Failed to get git info:",f),$.json({branch:null})}}),V};import{Hono as w0}from"hono";var k=B("Service"),o=new Map,uf=2097152,pf=65536;function gf(){return typeof globalThis.Bun<"u"}async function D0(V,$,f){if(gf()){let{spawn:j}=await import("bun-pty"),K=j(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env});return{pid:K.pid,write:(X)=>K.write(X),resize:(X,Q)=>K.resize(X,Q),kill:()=>K.kill(),onData:(X)=>K.onData(X),onExit:(X)=>K.onExit(X)}}let Y=(await import("node-pty")).spawn(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env,cols:80,rows:24});return{pid:Y.pid,write:(j)=>Y.write(j),resize:(j,K)=>Y.resize(j,K),kill:()=>Y.kill(),onData:(j)=>{Y.onData(j)},onExit:(j)=>{Y.onExit(j)}}}var xf=void 0,Ff;if(gf())try{let{createBunWebSocket:V}=await import("hono/bun"),$=V();Ff=$.upgradeWebSocket,xf=$.websocket}catch(V){k.warn("[Terminal] Failed to initialize Bun WebSocket support:",V)}async function df(V,$){let f=`term-${Date.now()}`;k.info(`[Terminal] New connection: ${f}, cwd: ${V}`);let J=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=J.endsWith("sh")?["-l"]:[],j=await D0(J,Y,{cwd:V,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),K={id:f,process:j,cwd:V,buffer:"",subscribers:new Set};if(o.set(f,K),K.subscribers.add($),j.onData((X)=>{let Q=!1;for(let Z of K.subscribers)try{Z.send(X),Q=!0}catch{K.subscribers.delete(Z)}if(Q)return;if(K.buffer+=X,K.buffer.length>uf)K.buffer=K.buffer.slice(-uf)}),j.onExit(({exitCode:X})=>{k.info(`[Terminal] Process exited: ${f}, code: ${X}`);for(let Q of K.subscribers)try{Q.close()}catch{}o.delete(f)}),K.buffer){let X=K.buffer;K.buffer="";for(let Q=0;Q<X.length;Q+=pf)$.send(X.slice(Q,Q+pf))}return{session:K,cleanup:()=>{if(k.info(`[Terminal] Connection closed: ${f}`),K.subscribers.delete($),K.subscribers.size===0){try{K.process.kill()}catch{}o.delete(f)}}}}function lf(V,$){V.on("connection",async(f,J)=>{let Y=new URL(J.url||"/",`http://${J.headers.host}`);if(!Y.pathname.endsWith("/terminal/ws")){f.close();return}let j=Y.searchParams.get("cwd")||$()||W();try{let{session:K,cleanup:X}=await df(j,{send:(Q)=>f.send(Q),close:()=>f.close()});f.on("message",(Q)=>{try{K.process.write(String(Q))}catch(Z){k.error("[Terminal] Failed to write to PTY:",Z)}}),f.on("close",X),f.on("error",X)}catch(K){k.error("[Terminal] Failed to spawn PTY:",K),f.close()}})}var cf=()=>{let V=new w0;if(V.get("/status",($)=>{let f=Array.from(o.values()).map((J)=>({id:J.id,cwd:J.cwd}));return $.json({active:f.length,terminals:f})}),V.post("/kill/:terminalId",($)=>{let f=$.req.param("terminalId"),J=o.get(f);if(J){try{J.process.kill()}catch{}for(let Y of J.subscribers)Y.close();return o.delete(f),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),Ff)V.get("/ws",Ff(($)=>{let f=$.req.query("cwd")||$.get("directory")||W(),J;return{async onOpen(Y,j){try{J=await df(f,{send:(K)=>j.send(K),close:()=>j.close()})}catch(K){k.error("[Terminal] Failed to spawn PTY:",K),j.close()}},onMessage(Y){if(!J)return;try{J.session.process.write(String(Y.data))}catch(j){k.error("[Terminal] Failed to write to PTY:",j)}},onClose(){J?.cleanup()}}}));else V.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return V};var _=B("Service"),Uf=[];function I0(){let V=P0(S0(import.meta.url)),$=[u(V,"web"),u(W(),"dist/web"),u(W(),"packages/cli/dist/web")];for(let f of $){let J=u(f,"index.html");if(af(J)){if(Qf(J,"utf-8").includes("/assets/"))return _.debug(`[Server] Found web dist at: ${f}`),f}}return null}function v0(){let V=new R0;V.onError((f,J)=>{if(_.error("[Server] Request error:",f),f instanceof t)return J.json(f.toObject(),f.statusCode);let Y=f instanceof Error?f.message:String(f);return J.json({error:{code:"INTERNAL_ERROR",message:Y}},500)}),V.use(async(f,J)=>{let Y=process.env.BLADE_SERVER_PASSWORD;if(!Y)return J();let j=f.req.path;if(j==="/"||j.startsWith("/assets/")||j.endsWith(".html")||j.endsWith(".js")||j.endsWith(".css"))return J();let K=f.req.header("Authorization");if(!K?.startsWith("Basic "))return f.header("WWW-Authenticate",'Basic realm="Blade Server"'),f.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let X=Buffer.from(K.slice(6),"base64").toString(),[Q,Z]=X.split(":"),O=process.env.BLADE_SERVER_USERNAME??"blade";if(Q!==O||Z!==Y)return f.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return J()}),V.use(async(f,J)=>{let Y=f.req.path==="/health"||f.req.path==="/global/health"||f.req.path.startsWith("/assets/");if(!Y)_.debug(`[Server] ${f.req.method} ${f.req.path}`);let j=Date.now();if(await J(),!Y){let K=Date.now()-j;_.debug(`[Server] ${f.req.method} ${f.req.path} - ${f.res.status} (${K}ms)`)}}),V.use(m0({origin(f){if(!f)return;if(f.startsWith("http://localhost:"))return f;if(f.startsWith("http://127.0.0.1:"))return f;if(f==="tauri://localhost"||f==="http://tauri.localhost")return f;if(Uf.includes(f))return f;return}})),V.use(async(f,J)=>{let Y=f.req.query("directory")||f.req.header("x-blade-directory")||W();try{Y=decodeURIComponent(Y)}catch{}return f.set("directory",Y),J()}),V.route("/global",Wf()),V.route("/sessions",bf()),V.route("/configs",Bf()),V.route("/permissions",Df()),V.route("/providers",yf()),V.route("/models",Hf()),V.route("/suggestions",vf()),V.route("/terminal",cf()),V.route("/mcp",qf()),V.route("/skills",Sf()),V.get("/health",(f)=>{return f.json({healthy:!0,version:l()})});let $=I0();if($)_.info(`[Server] Serving static files from ${$}`),V.get("/assets/*",(f)=>{let J=u($,f.req.path);if(!af(J))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${f.req.path}`}},404);let Y=Qf(J),j=k0(J).toLowerCase(),X={".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"}[j]||"application/octet-stream";return new Response(Y,{headers:{"Content-Type":X,"Cache-Control":"public, max-age=31536000, immutable"}})}),V.get("/",(f)=>{let J=u($,"index.html"),Y=Qf(J,"utf-8");return f.html(Y)}),V.get("*",(f)=>{let J=f.req.path;if(J.includes("."))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${J}`}},404);let Y=u($,"index.html"),j=Qf(Y,"utf-8");return f.html(j)});else _.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),V.get("/",(f)=>{return f.json({message:"Blade API Server",version:l(),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"}})}),V.all("*",(f)=>{return f.json({error:{code:"NOT_FOUND",message:`Route not found: ${f.req.path}`}},404)});return V}function u0(){let V=y0(),$=[];for(let f of Object.keys(V)){let J=V[f];if(!J)continue;for(let Y of J){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;$.push(Y.address)}}return $}function of(){return typeof globalThis.Bun<"u"}function rf(V,$){let f=globalThis.Bun,J=(j)=>{try{return f.serve({hostname:$.hostname,port:j,fetch:V.fetch,idleTimeout:0,websocket:xf})}catch(K){_.error("Failed to start Bun server:",K);return}},Y=$.port===0?J(4096)??J(0):J($.port);if(!Y)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:Y.url,port:Y.port,hostname:Y.hostname,stop:async()=>{Y.stop(!0)}}}function p0(V,$){return new Promise((f,J)=>{let Y=L0(async(Z,O)=>{let G=new URL(Z.url||"/",`http://${Z.headers.host}`),N=new Headers;for(let[F,U]of Object.entries(Z.headers))if(U)if(Array.isArray(U))for(let E of U)N.append(F,E);else N.set(F,U);let x;if(Z.method!=="GET"&&Z.method!=="HEAD")x=(await new Promise((U)=>{let E=[];Z.on("data",(C)=>E.push(C)),Z.on("end",()=>U(Buffer.concat(E)))})).toString();let A=new Request(G.toString(),{method:Z.method,headers:N,body:x});try{let F=await V.fetch(A);if(O.statusCode=F.status,F.headers.forEach((U,E)=>{O.setHeader(E,U)}),F.body){let U=F.body.getReader(),E=async()=>{let{done:C,value:M}=await U.read();if(C){O.end();return}return O.write(M),E()};await E()}else{let U=await F.text();O.end(U)}}catch(F){_.error("[Server] Node request error:",F),O.statusCode=500,O.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),j=new h0({noServer:!0}),K=W();lf(j,()=>K),Y.on("upgrade",(Z,O,G)=>{if(new URL(Z.url||"/",`http://${Z.headers.host}`).pathname==="/terminal/ws")j.handleUpgrade(Z,O,G,(x)=>{j.emit("connection",x,Z)});else O.destroy()});let X=(Z)=>{return new Promise((O,G)=>{Y.once("error",(N)=>{if(N.code==="EADDRINUSE")G(N);else G(N)}),Y.listen(Z,$.hostname,()=>{let N=Y.address();if(N&&typeof N==="object")O(N.port);else O(Z)})})};(async()=>{let Z;if($.port===0)try{Z=await X(4096)}catch{Z=await X(0)}else Z=await X($.port);let O=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${Z}`);f({url:O,port:Z,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{j.close(()=>{Y.close(()=>G())})})}})})().catch(J)})}var tf;((yV)=>{let V,$;function f(){if(!$)$=v0();return $}yV.getApp=f;function J(K){Uf=K.cors??[];let X=f();if(of())V=rf(X,K),_.info(`[Server] Blade server listening on ${V.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 Q=V;return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,_.info("[Server] Blade server stopped")}}}yV.listen=J;async function Y(K){Uf=K.cors??[];let X=f();if(of())V=rf(X,K),_.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else V=await p0(X,K),_.info(`[Server] Blade server listening on ${V.url} (Node.js runtime)`);let Q=V;return{url:Q.url,port:Q.port,hostname:Q.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,_.info("[Server] Blade server stopped")}}}yV.listenAsync=Y;function j(){return V!==void 0}yV.isRunning=j})(tf||={});export{g0 as f,d0 as g,u0 as h,tf as i};
@@ -1 +0,0 @@
1
- import{$a as l,Pa as a,Qa as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o,fb as p,gb as q,hb as r}from"./chunk-3mhbped9.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,e as ConversationState};