blade-code 0.7.7 → 0.8.0

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 (83) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-0b3m5qn6.js → chunk-06h100e2.js} +1 -1
  3. package/dist/chunk-07jvw0kn.js +1 -0
  4. package/dist/chunk-0dj326ms.js +5 -0
  5. package/dist/chunk-14erxdhd.js +1 -0
  6. package/dist/chunk-1pt090dg.js +615 -0
  7. package/dist/{chunk-2qckpa16.js → chunk-1smf2dj3.js} +2 -2
  8. package/dist/chunk-34pdtz4q.js +3 -0
  9. package/dist/chunk-3gw66r7a.js +2 -0
  10. package/dist/chunk-49g067ek.js +41 -0
  11. package/dist/chunk-6es6av6j.js +2 -0
  12. package/dist/{chunk-6y58y4rx.js → chunk-9xkjb87h.js} +1 -1
  13. package/dist/chunk-a12tmmfr.js +1 -0
  14. package/dist/chunk-bggvft3z.js +1 -0
  15. package/dist/{chunk-60se4kxq.js → chunk-bm8vwfez.js} +1 -1
  16. package/dist/chunk-bxbagv76.js +9 -0
  17. package/dist/chunk-ctqf59q1.js +2 -0
  18. package/dist/chunk-d08wbxjr.js +1 -0
  19. package/dist/chunk-d4ex0qvs.js +2 -0
  20. package/dist/{chunk-zet4zjc3.js → chunk-dr06x0cw.js} +1 -1
  21. package/dist/chunk-e4a240t7.js +34 -0
  22. package/dist/{chunk-v61bja34.js → chunk-gsfkrr25.js} +1 -1
  23. package/dist/chunk-gytwh5y1.js +6 -0
  24. package/dist/chunk-hjx5n3dw.js +3 -0
  25. package/dist/chunk-hrnd3wjg.js +6 -0
  26. package/dist/chunk-j39q2kx7.js +1 -0
  27. package/dist/chunk-jakzknh3.js +1570 -0
  28. package/dist/chunk-jqr2pknb.js +151 -0
  29. package/dist/{chunk-2n8a87ds.js → chunk-jt62ctz7.js} +1 -1
  30. package/dist/{chunk-5xjj88wd.js → chunk-kawv31m3.js} +1 -1
  31. package/dist/chunk-n8ymp6nd.js +1 -0
  32. package/dist/{chunk-yyw9bbfd.js → chunk-nned222j.js} +1 -1
  33. package/dist/chunk-qwdbqjh7.js +22 -0
  34. package/dist/chunk-syj3anec.js +6 -0
  35. package/dist/chunk-tv4r86ez.js +24 -0
  36. package/dist/chunk-twem6p0g.js +2 -0
  37. package/dist/chunk-v3ctg84r.js +1 -0
  38. package/dist/chunk-v5rn5r1h.js +1 -0
  39. package/dist/{chunk-w1m1ehs1.js → chunk-wmes2tt9.js} +1 -1
  40. package/dist/chunk-xhnyy54e.js +2 -0
  41. package/dist/{chunk-6087cgst.js → chunk-ychj0e5q.js} +1 -1
  42. package/dist/{chunk-7e5hzpmp.js → chunk-ydb9myhe.js} +1 -1
  43. package/dist/{chunk-p7rf3zp8.js → chunk-yhpm9azy.js} +1 -1
  44. package/dist/{chunk-c6rtexw1.js → chunk-yqxw7zz4.js} +1 -1
  45. package/dist/web/assets/{FilePreview-B2anY2d1.js → FilePreview-DvgnEspB.js} +1 -1
  46. package/dist/web/assets/{MarkdownRenderer-BVfRG88x.js → MarkdownRenderer-e1ZUy6jV.js} +1 -1
  47. package/dist/web/assets/{McpModal-BVvb-dzr.js → McpModal-Raois2g1.js} +1 -1
  48. package/dist/web/assets/SettingsModal-Dzuatoea.js +1 -0
  49. package/dist/web/assets/{SettingsStore-B87y64B4.js → SettingsStore-BxDA0Usw.js} +1 -1
  50. package/dist/web/assets/{SkillsModal-BXYaF2KK.js → SkillsModal-Cg2-befH.js} +1 -1
  51. package/dist/web/assets/{TerminalPanel-B-NRhOXN.js → TerminalPanel-CEoQI9Lu.js} +1 -1
  52. package/dist/web/assets/index-BvGeIa_-.js +16 -0
  53. package/dist/web/assets/index-DDJnZJcp.css +1 -0
  54. package/dist/web/index.html +2 -2
  55. package/package.json +4 -11
  56. package/dist/chunk-0y895nft.js +0 -9
  57. package/dist/chunk-2j3tb2dm.js +0 -1
  58. package/dist/chunk-3fcze972.js +0 -1
  59. package/dist/chunk-4n7fsts0.js +0 -2
  60. package/dist/chunk-54vk4tw8.js +0 -615
  61. package/dist/chunk-6cry51vb.js +0 -9
  62. package/dist/chunk-778h8815.js +0 -26
  63. package/dist/chunk-89j9pm90.js +0 -24
  64. package/dist/chunk-8e0rv3j5.js +0 -41
  65. package/dist/chunk-8p98nt9v.js +0 -151
  66. package/dist/chunk-94vj1hjp.js +0 -1
  67. package/dist/chunk-c8cxeve8.js +0 -1
  68. package/dist/chunk-d61d6m07.js +0 -2
  69. package/dist/chunk-ebcmqx1k.js +0 -2
  70. package/dist/chunk-gsn659hw.js +0 -1
  71. package/dist/chunk-h79044h0.js +0 -3
  72. package/dist/chunk-kppxkh33.js +0 -1
  73. package/dist/chunk-ptt8s7nd.js +0 -6
  74. package/dist/chunk-qnh7np1s.js +0 -6
  75. package/dist/chunk-ran4gsmy.js +0 -1
  76. package/dist/chunk-swyvd7hd.js +0 -1
  77. package/dist/chunk-t9zdypqp.js +0 -2
  78. package/dist/chunk-x1khkevy.js +0 -1563
  79. package/dist/chunk-x24ddbhs.js +0 -6
  80. package/dist/chunk-x466sb8s.js +0 -34
  81. package/dist/web/assets/SettingsModal-aseVv-gp.js +0 -1
  82. package/dist/web/assets/index-9kl44E8k.js +0 -9
  83. package/dist/web/assets/index-CUVe9dGs.css +0 -1
@@ -1,2 +1,2 @@
1
- import{_b as y}from"./chunk-zet4zjc3.js";import*as j from"fs/promises";import*as $ from"path";import b from"semver";import{fileURLToPath as N}from"url";import{ProxyAgent as G,fetch as H}from"undici";function T(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function R(){let q=T();if(q)try{return new G(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function K(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=R(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),w=()=>X.abort();Q?.addEventListener("abort",w);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await H(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",w)}}var D="blade-code",f="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",M=$.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),S=$.join(M,"version-cache.json"),k=3600000,L=`https://registry.npmjs.org/${D}/latest`;async function x(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;let q=N(import.meta.url),z=$.dirname(q),W=[$.join(z,"..","..","package.json"),$.join(z,"..","package.json")];for(let Q of W)try{let B=await j.readFile(Q,"utf-8"),J=JSON.parse(B);if(J.name===D&&J.version)return J.version}catch{}return"unknown"}catch{return"unknown"}}async function I(){try{let q=await j.readFile(S,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<k)return z;return{...z,checkedAt:0}}catch{return null}}async function O(q){try{await j.mkdir(M,{recursive:!0,mode:493}),await j.writeFile(S,JSON.stringify(q,null,2))}catch{}}async function P(){try{let q=await K(L,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function v(q=!1){let z=await x(),W=f;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await I(),B=Q?.skipUntilVersion,J=null;if(!q&&Q&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await P(),J)await O({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});if(!J)return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};let X=b.gt(J,z),Y=X;if(X&&B)Y=b.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await I();await O({latestVersion:z?.latestVersion||q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${D}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function d(){try{let q=await v();return q.shouldPrompt?q:null}catch{return null}}
2
- export{v as a,u as b,g as c,C as d,d as e};
1
+ import{ec as y}from"./chunk-dr06x0cw.js";import*as j from"fs/promises";import*as $ from"path";import b from"semver";import{fileURLToPath as N}from"url";import{ProxyAgent as G,fetch as H}from"undici";function T(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function R(){let q=T();if(q)try{return new G(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function K(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=R(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),w=()=>X.abort();Q?.addEventListener("abort",w);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await H(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",w)}}var D="blade-code",f="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",M=$.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),S=$.join(M,"version-cache.json"),k=3600000,L=`https://registry.npmjs.org/${D}/latest`;async function x(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;let q=N(import.meta.url),z=$.dirname(q),W=[$.join(z,"..","..","package.json"),$.join(z,"..","package.json")];for(let Q of W)try{let B=await j.readFile(Q,"utf-8"),J=JSON.parse(B);if(J.name===D&&J.version)return J.version}catch{}return"unknown"}catch{return"unknown"}}async function I(){try{let q=await j.readFile(S,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<k)return z;return{...z,checkedAt:0}}catch{return null}}async function O(q){try{await j.mkdir(M,{recursive:!0,mode:493}),await j.writeFile(S,JSON.stringify(q,null,2))}catch{}}async function P(){try{let q=await K(L,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function v(q=!1){let z=await x(),W=f;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await I(),B=Q?.skipUntilVersion,J=null;if(!q&&Q&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await P(),J)await O({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});if(!J)return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};let X=b.gt(J,z),Y=X;if(X&&B)Y=b.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await I();await O({latestVersion:z?.latestVersion||q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${D}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function d(){try{let q=await v();return q.shouldPrompt?q:null}catch{return null}}
2
+ export{v as g,u as h,g as i,C as j,d as k};
@@ -0,0 +1,3 @@
1
+ import{bc as j}from"./chunk-hjx5n3dw.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
2
+ `)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
3
+ export{m as Qb,I as Rb,M as Sb,V as Tb,h as Ub};
@@ -0,0 +1,2 @@
1
+ import{e as Ax,f as Wx}from"./chunk-xhnyy54e.js";import{$ as zx,A as Dx,C as Yx,D as HO,E as kO,G as _O,H as Jx,I as p,K as Nx,L as ZO,M as C,N as y,P as yO,Q as mO,S as Qx}from"./chunk-jakzknh3.js";import{ca as n}from"./chunk-e4a240t7.js";import{Ca as o,va as $O,xa as lO,ya as cO,za as dO}from"./chunk-tv4r86ez.js";import{Ka as VO}from"./chunk-6es6av6j.js";import{Qa as Hx,Sa as AO,ab as FO}from"./chunk-1pt090dg.js";import{sb as Gx}from"./chunk-9xkjb87h.js";import{Ab as oO,Bb as E,wb as g,yb as S,zb as q}from"./chunk-ctqf59q1.js";import{Cb as Vx}from"./chunk-jt62ctz7.js";import{Ib as h}from"./chunk-gsfkrr25.js";import{Tb as L}from"./chunk-34pdtz4q.js";import{Yb as $x,dc as r}from"./chunk-hjx5n3dw.js";import{ec as PO}from"./chunk-dr06x0cw.js";var v0={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 u0(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{Hono as C0}from"hono";import{cors as E0}from"hono/cors";import{existsSync as hx,readFileSync as wO}from"node:fs";import{createServer as y0}from"node:http";import{networkInterfaces as m0}from"node:os";import{dirname as h0,extname as f0,join as xO}from"node:path";import{fileURLToPath as k0}from"node:url";import{WebSocketServer as P0}from"ws";class I extends Error{code;statusCode;constructor(O,$,x=500){super($);this.code=O;this.statusCode=x;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class m extends I{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class b extends I{constructor(O){super("BAD_REQUEST",O,400)}}class i extends I{constructor(O){super("CONFLICT",O,409)}}class l extends I{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class t extends I{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var d0=S.Object({error:S.Object({code:S.String(),message:S.String()})});import{Hono as Px}from"hono";var zO=L("Service"),px=S.Object({updates:S.Record(S.String(),S.Any()),options:S.Optional(S.Object({scope:S.Optional(E(["local","project","global"])),immediate:S.Optional(S.Boolean())}))});function Rx(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,theme:O.theme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash}}var gO=()=>{let O=new Px;return O.get("/",async($)=>{try{let x=$O();return $.json(x?Rx(x):{})}catch(x){return zO.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),V=g(px,x);if(!V.success)throw new b("Invalid config update format");let{updates:Y,options:j}=V.data;return await o().updateConfig(Y,j),$.json({success:!0,updates:Y})}catch(x){throw zO.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=$O();return $.json(x?.permissions||{})}catch(x){return zO.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as Ix}from"hono";var vO=()=>{let O=new Ix;return O.get("/health",($)=>{return $.json({healthy:!0,version:VO()})}),O.get("/info",($)=>{return $.json({version:VO(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:h()})}),O};import{Hono as gx}from"hono";var QO=L("Service"),uO=()=>{let O=new gx;return O.get("/",async($)=>{try{let V=n.getInstance().getAllServers(),Y=Array.from(V.entries()).map(([j,N])=>({id:j,name:j,status:N.status==="connected"?"connected":N.status==="connecting"?"connecting":N.lastError?"error":"offline",endpoint:N.config.command?`${N.config.command} ${(N.config.args||[]).join(" ")}`.trim():N.config.url||"Unknown",description:`MCP server: ${j}`,tools:N.tools.map((X)=>X.name),connectedAt:N.connectedAt?.toISOString(),error:N.lastError?.message}));return $.json(Y)}catch(x){return QO.error("[McpRoutes] Failed to get MCP servers:",x),$.json([])}}),O.post("/:name/connect",async($)=>{try{let x=$.req.param("name");return await n.getInstance().connectServer(x),$.json({success:!0})}catch(x){return QO.error("[McpRoutes] Failed to connect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let x=$.req.param("name");return await n.getInstance().disconnectServer(x),$.json({success:!0})}catch(x){return QO.error("[McpRoutes] Failed to disconnect MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name");await n.getInstance().unregisterServer(x);let Y=$O();if(Y?.mcpServers){let{[x]:j,...N}=Y.mcpServers;await o().updateConfig({mcpServers:N})}return $.json({success:!0})}catch(x){return QO.error("[McpRoutes] Failed to delete MCP server:",x),$.json({success:!1,error:x.message},500)}}),O.post("/",async($)=>{try{let x=await $.req.json(),{name:V,config:Y}=x;if(!V||!Y)return $.json({success:!1,error:"Missing name or config"},400);await n.getInstance().registerServer(V,Y);let N=$O();return await o().updateConfig({mcpServers:{...N?.mcpServers,[V]:Y}}),$.json({success:!0})}catch(x){return QO.error("[McpRoutes] Failed to add MCP server:",x),$.json({success:!1,error:x.message},500)}}),O};import{Hono as vx}from"hono";var XO=L("Service");function ux(O,$){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,input:$.input}}function lx(O){let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}var tO=()=>{let O=new vx;return O.get("/",async($)=>{try{let x=lO(),V=cO(),Y=r(),j=(N)=>ux(N,Y.resolveConfig(N));return $.json({configured:x.map(j),current:V?j(V):null})}catch(x){return XO.error("[ModelsRoutes] Failed to get models:",x),$.json({configured:[],current:null})}}),O.post("/",async($)=>{try{let x=await $.req.json(),{provider:V,displayName:Y,model:j,overrides:N,apiKey:X}=x;if(!V||!j)throw new b("provider and model are required");if(r().getModel(V,j),X?.trim())await r().setApiKey(V,X.trim());let W=await o().addModel({provider:V,displayName:Y||void 0,model:j,overrides:N||void 0});return $.json({success:!0,model:W})}catch(x){throw XO.error("[ModelsRoutes] Failed to add model:",x),x}}),O.put("/:modelId",async($)=>{try{let x=$.req.param("modelId"),V=await $.req.json(),{displayName:Y,overrides:j,model:N}=V,X=dO(x);if(!X)throw new b("model config not found");if(N)r().getModel(X.provider,N);return await o().updateModel(x,lx({displayName:Y,overrides:j,model:N})),$.json({success:!0})}catch(x){throw XO.error("[ModelsRoutes] Failed to update model:",x),x}}),O.delete("/:modelId",async($)=>{try{let x=$.req.param("modelId");return await o().removeModel(x),$.json({success:!0})}catch(x){throw XO.error("[ModelsRoutes] Failed to delete model:",x),x}}),O};import{Hono as j0}from"hono";import Sx from"node:path";import{Mutex as nx}from"async-mutex";import{Hono as rx}from"hono";import{streamSSE as sx}from"hono/streaming";import{LRUCache as ex}from"lru-cache";import{nanoid as GO}from"nanoid";var iO=q(E(["default","autoEdit","yolo","plan"]));var TO=q(E(["user","assistant","system","tool"])),cx=q(S.Union([S.Object({type:S.Literal("text"),text:S.String()}),S.Object({type:S.Literal("image_url"),image_url:S.Object({url:S.String()})})])),nO=S.Union([S.String(),S.Array(cx)]),BS=q(S.Object({id:S.String(),role:TO,content:nO,timestamp:S.Number(),metadata:S.Optional(S.Record(S.String(),S.Unknown())),thinkingContent:S.Optional(S.String()),tool_call_id:S.Optional(S.String()),name:S.Optional(S.String()),tool_calls:S.Optional(S.Unknown())})),dx=q(S.Object({sessionId:S.String(),projectPath:S.String(),title:S.Optional(S.String()),gitBranch:S.Optional(S.String()),rootId:S.String(),parentId:S.Optional(S.String()),relationType:S.Optional(E(["subagent","fork"])),resumedFrom:S.Optional(S.String()),rootAgentId:S.Optional(S.String()),resumeDepth:S.Optional(S.Integer({minimum:0})),messageCount:S.Number(),firstMessageTime:S.String(),lastMessageTime:S.String(),hasErrors:S.Boolean()})),HS=q(S.Object({version:S.Literal(1),sessionId:S.String(),goalId:S.String(),objective:S.String(),status:E(["active","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:S.Optional(S.Number()),tokensUsed:S.Number(),timeUsedSeconds:S.Number(),continuationCount:S.Number(),statusReason:S.Optional(S.String()),createdAt:S.String(),updatedAt:S.String()})),rO=q(S.Object({role:TO,content:nO,metadata:S.Optional(S.Unknown()),reasoningContent:S.Optional(S.String()),thinkingContent:S.Optional(S.String()),tool_call_id:S.Optional(S.String()),name:S.Optional(S.String()),tool_calls:S.Optional(S.Unknown())})),wS=q(S.Object({session:dx,messages:S.Array(rO)})),sO=q(E(["conversation","code","both"])),tx=q(S.Object({messageId:S.String(),preview:S.String(),createdAt:S.String(),fileCount:S.Integer({minimum:0})})),eO=q(S.Object({targetMessageId:S.String({minLength:1}),mode:oO(sO,"conversation")})),KS=q(S.Object({checkpoint:tx,mode:sO,removedTurns:S.Integer({minimum:1}),restoredFiles:S.Array(S.String()),messages:S.Array(rO)})),ax=E(["running","completed","failed","cancelled"]),aO=q(S.Object({id:S.String(),subagentType:S.String(),description:S.String(),status:ax,rootAgentId:S.String(),resumedFrom:S.Optional(S.String()),resumeDepth:S.Integer({minimum:0}),createdAt:S.Number(),lastActiveAt:S.Number(),completedAt:S.Optional(S.Number()),result:S.Optional(S.Object({success:S.Boolean(),message:S.String(),error:S.Optional(S.String()),verificationCommands:S.Optional(S.Array(S.String()))})),stats:S.Optional(S.Object({tokens:S.Optional(S.Number()),toolCalls:S.Optional(S.Number()),duration:S.Optional(S.Number())}))})),Ox=q(S.Object({prompt:S.String({minLength:1,maxLength:32000})})),DS=q(S.Object({source:aO,session:aO})),zS=q(S.Object({sessionId:S.String(),projectPath:S.String()})),TS=q(S.Object({type:S.String(),properties:S.Record(S.String(),S.Unknown())})),xx=q(S.Object({content:S.String(),projectPath:S.Optional(S.String()),permissionMode:S.Optional(iO),attachments:S.Optional(S.Array(S.Object({type:E(["file","image","url"]),path:S.Optional(S.String()),url:S.Optional(S.String()),content:S.Optional(S.String()),mimeType:S.Optional(S.String()),name:S.Optional(S.String())})))})),bS=q(S.Object({messageId:S.String(),role:TO,content:S.String(),timestamp:S.String()})),qS=q(S.Object({approved:S.Boolean(),remember:S.Optional(S.Boolean()),scope:S.Optional(E(["once","session","project"])),targetMode:S.Optional(iO),feedback:S.Optional(S.String()),answers:S.Optional(S.Record(S.String(),S.Union([S.String(),S.Array(S.String())])))})),FS=q(S.Object({id:S.String(),displayName:S.Optional(S.String()),provider:S.String(),model:S.String(),contextWindow:S.Optional(S.Number()),maxTokens:S.Optional(S.Number()),reasoning:S.Optional(S.Boolean()),input:S.Optional(S.Array(E(["text","image"]))),overrides:S.Optional(S.Object({baseUrl:S.Optional(S.String()),temperature:S.Optional(S.Number()),maxOutputTokens:S.Optional(S.Number()),timeout:S.Optional(S.Number())}))})),LS=q(E(["vs-dark","vs-light","hc-black"])),ox=q(E(["light","dark","system"])),ix=q(S.Object({language:S.String(),theme:S.String(),uiTheme:ox,autoSaveSessions:S.Boolean(),notifyBuild:S.Boolean(),notifyErrors:S.Boolean(),notifySounds:S.Boolean(),privacyTelemetry:S.Boolean(),privacyCrash:S.Boolean()})),CS=q(S.Partial(ix));var F=L("Service"),O0=S.Object({title:S.Optional(S.String()),projectPath:S.Optional(S.String())}),x0=xx,S0=S.Object({title:S.Optional(S.String()),projectPath:S.Optional(S.String())}),$0=S.Object({projectPath:S.String()}),V0=S.Object({objective:S.String({minLength:1}),tokenBudget:S.Optional(S.Integer({minimum:1})),permissionMode:S.Optional(E(["default","autoEdit","plan","yolo"]))}),G0=S.Union([S.Object({action:S.Literal("pause")}),S.Object({action:S.Literal("resume")}),S.Object({action:S.Literal("edit"),objective:S.String({minLength:1})})]),P=new Map,f=new ex({max:100,ttl:1800000,dispose:(O,$)=>{if(O.status==="running"||O.status==="waiting_permission")O.abortController.abort(),F.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}});function Y0(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function MO(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let x=O.pendingPermission;return O.pendingPermission=void 0,x?.resolve({approved:!1,reason:Gx}),O.abortController.abort($),O.status="cancelled",y.publish(Y0(O),"run.cancelled",{runId:O.id}),!0}function Zx(O,$=!1){let{permissionId:x,details:V}=O;if(V.type==="askUserQuestion"&&V.questions)return{type:"question.required",properties:{requestId:x,toolCallId:x,questions:V.questions,details:V,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:x,toolName:V.toolName,description:V.message,args:V.args,details:V,...$?{replayed:!0}:{}}}}function J0(){for(let O of f.values())MO(O,"route-reset");f.clear(),P.clear()}var jx=(O)=>{if(!O||typeof O!=="object")return O;let $={...O},x=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>x)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>x)delete $.newContent;return $};function N0(O,$,x){switch(x.kind){case"tool_start":if("function"in x.toolCall)y.publish(O,"subagent.update",{subagentSessionId:$,toolName:x.toolCall.function.name}),y.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,arguments:x.toolCall.function.arguments,toolKind:x.toolKind});break;case"tool_result":if("function"in x.toolCall)y.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:x.toolCall.id,toolName:x.toolCall.function.name,success:!x.result.error,summary:x.result.metadata?.summary,output:mO(yO(x.toolCall.function.name,x.result)),metadata:jx(x.result.metadata)});break;case"content_delta":y.publish(O,"subagent.delta",{subagentSessionId:$,delta:x.delta});break;case"thinking_delta":y.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:x.delta});break;case"stream_end":y.publish(O,"subagent.stream.end",{subagentSessionId:$});break;default:break}}function LO(O,$="projectPath"){if(!Sx.isAbsolute(O))throw new b(`${$} must be absolute`);return Sx.resolve(O)}function CO(O){try{$x(O)}catch($){throw new b($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function v(O){return{sessionId:O.id,projectPath:O.projectPath}}function bO(O,$){return{id:O.sessionId,projectPath:O.projectPath,title:O.title??`Session ${O.sessionId.slice(0,6)}`,createdAt:new Date(O.firstMessageTime),updatedAt:new Date(O.lastMessageTime),rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,messages:$}}function qO(O){return{sessionId:O.id,projectPath:O.projectPath,title:O.title,rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,status:void 0,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function c(O,$){if(CO(O),$!==void 0){let V=ZO({sessionId:O,projectPath:LO($)});if(P.has(C(V)))return V;let Y=await p.findSessionMetadata(V.sessionId,V.projectPath);if(!Y)throw new m("Session",O);return ZO({sessionId:Y.sessionId,projectPath:Y.projectPath})}let x=new Map;for(let V of P.values()){if(V.id!==O)continue;let Y=v(V);x.set(C(Y),Y)}for(let V of await p.listSessions()){if(V.sessionId!==O)continue;let Y=ZO({sessionId:V.sessionId,projectPath:V.projectPath});x.set(C(Y),Y)}if(x.size===0)try{let V=await p.findSessionMetadata(O);if(!V)throw new m("Session",O);return ZO({sessionId:V.sessionId,projectPath:V.projectPath})}catch(V){if(V instanceof m)throw V;if(V instanceof Error&&V.message.startsWith("Ambiguous session ID:"))throw new l;throw V}if(x.size>1)throw new l;return x.values().next().value}function EO(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
2
+ `)}function Q0(O,$){let x=($??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(x.length===0)return O;let V=[];if(O.trim())V.push({type:"text",text:O});return V.push(...x),V}var Ux=()=>{J0();let O=new rx;O.onError((G,Z)=>{if(G instanceof I)return Z.json(G.toObject(),G.statusCode);return F.error("[SessionRoutes] Unhandled route error:",G),Z.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,x=new Map,V=new Map,Y=new Map,j=(G)=>{let Z=C(G),J=Y.get(Z);if(!J)J=new nx,Y.set(Z,J);return J},N=async(G)=>{let Z=C(v(G)),J=$.get(Z);if(J)return J;let Q=x.get(Z);if(!Q)Q=Nx.create({sessionId:G.id,workspaceRoot:G.projectPath}),x.set(Z,Q);try{let U=await Q;return $.set(Z,U),U}finally{if(x.get(Z)===Q)x.delete(Z)}},X=async(G)=>{let Z=C(G),J=P.get(Z);if(J)return J;let Q=V.get(Z);if(!Q)Q=(async()=>{let U=await p.findSessionMetadata(G.sessionId,G.projectPath);if(!U)throw new m("Session",G.sessionId);let M=bO(U,await p.loadSession(G.sessionId,G.projectPath));return P.set(Z,M),M})(),V.set(Z,Q);try{return await Q}finally{if(V.get(Z)===Q)V.delete(Z)}},W=async(G,Z)=>{return X(await c(G,Z))},A=(G,Z,J,Q={})=>{let U=GO(12),M={id:U,sessionId:G.id,projectPath:G.projectPath,status:"running",abortController:new AbortController,createdAt:new Date};return f.set(U,M),G.currentRunId=U,M.completion=Z0(M,G,Z,J,N,{pendingInputOnly:Q.pendingInputOnly,preparedInputTurn:Q.preparedInputTurn,goalContinuationOnly:Q.goalContinuationOnly}).catch((_)=>{F.error(`[SessionRoutes] Run ${U} failed:`,_)}),M},D=async(G)=>{let Z=G.currentRunId?f.get(G.currentRunId):void 0;if(Z&&(Z.status==="running"||Z.status==="waiting_permission"))return;let J=await N(G),Q=G.currentRunId?f.get(G.currentRunId):void 0;if(Q&&(Q.status==="running"||Q.status==="waiting_permission"))return;let U=J.getPendingSteeringCount()>0,_=(U?null:await J.getGoal())?.status==="active";if(!U&&!_||J.hasTurnOwner())return;A(G,"","default",{pendingInputOnly:U,goalContinuationOnly:_})};return O.get("/",async(G)=>{try{let Z=await p.listSessions(),J=new Set(Z.filter((w)=>w.relationType==="subagent").map((w)=>C({sessionId:w.sessionId,projectPath:w.projectPath}))),Q=Array.from(P.values()).filter((w)=>!J.has(C(v(w)))&&w.relationType!=="subagent").map((w)=>qO(w)),U=new Set(Q.map((w)=>C({sessionId:w.sessionId,projectPath:w.projectPath}))),M=Z.filter((w)=>{if(w.relationType==="subagent")return!1;return!U.has(C({sessionId:w.sessionId,projectPath:w.projectPath}))}),_=new Set(U),K=M.filter((w)=>{let H=C({sessionId:w.sessionId,projectPath:w.projectPath});if(_.has(H))return!1;return _.add(H),!0}),z=[...Q,...K];return G.json(z)}catch(Z){throw F.error("[SessionRoutes] Failed to list sessions:",Z),new t("Failed to list sessions")}}),O.post("/",async(G)=>{try{let Z=await G.req.json(),J=g(O0,Z);if(!J.success)throw new b("Invalid request body");let{title:Q,projectPath:U}=J.data,M=Vx("web",12),_=LO(U||G.get("directory")||h(),U?"projectPath":"directory"),K=await p.createSessionMetadata(M,_,{title:Q}),z=bO(K,[]);return P.set(C(v(z)),z),G.json({...qO(z),status:void 0,agentType:void 0,model:void 0})}catch(Z){if(F.error("[SessionRoutes] Failed to create session:",Z),Z instanceof b)throw Z;throw new t("Failed to create session")}}),O.post("/:sessionId/fork",async(G)=>{let Z=G.req.param("sessionId");try{CO(Z);let J=await G.req.json(),Q=g($0,J);if(!Q.success)throw new b("Invalid request body");let U=LO(Q.data.projectPath),M=await p.findSessionMetadata(Z,U);if(!M)throw new m("Session",Z);let _=await p.forkSession(Z,{sourceProjectPath:M.projectPath,targetProjectPath:M.projectPath}),K=bO(_.metadata,_.messages);return P.set(C(v(K)),K),G.json({session:_.metadata,messages:_.messages},201)}catch(J){if(J instanceof b||J instanceof m||J instanceof i)throw J;if(J instanceof Jx)throw new i("Session has no durable creation record");throw F.error("[SessionRoutes] Failed to fork session:",J),new t("Failed to fork session")}}),O.get("/:sessionId",async(G)=>{let Z=G.req.param("sessionId");try{let J=await c(Z,G.req.query("projectPath")),Q=P.get(C(J));if(Q)return G.json(qO(Q));let U=await p.findSessionMetadata(J.sessionId,J.projectPath);if(!U)throw new m("Session",Z);return G.json(U)}catch(J){if(J instanceof b||J instanceof m||J instanceof l)throw J;throw F.error("[SessionRoutes] Failed to get session:",J),new t("Failed to get session")}}),O.patch("/:sessionId",async(G)=>{let Z=G.req.param("sessionId");try{let J=await G.req.json(),Q=g(S0,J);if(!Q.success)throw new b("Invalid request body");if(Q.data.title===void 0)throw new b("title is required");let U=await c(Z,Q.data.projectPath),M=await p.updateSessionMetadata(U.sessionId,U.projectPath,{title:Q.data.title}),_=P.get(C(U));if(_)_.title=M.title??_.title,_.updatedAt=new Date(M.lastMessageTime);return G.json({success:!0,title:M.title})}catch(J){if(F.error("[SessionRoutes] Failed to update session:",J),J instanceof b||J instanceof m||J instanceof l)throw J;throw new t("Failed to update session")}}),O.get("/:sessionId/rewind",async(G)=>{let Z=await W(G.req.param("sessionId"),G.req.query("projectPath")),J=await N(Z);return G.json({checkpoints:await J.listRewindCheckpoints()})}),O.post("/:sessionId/rewind",async(G)=>{let Z=g(eO,await G.req.json());if(!Z.success)throw new b("Invalid rewind request");let J=await W(G.req.param("sessionId"),G.req.query("projectPath")),Q=v(J);return j(Q).runExclusive(async()=>{let U=J.currentRunId?f.get(J.currentRunId):void 0;if(U&&(U.status==="running"||U.status==="waiting_permission"))throw new i("Cannot rewind while a run is active");let M=await N(J),_;try{_=await M.rewindSession(Z.data)}catch(K){if(K instanceof Error&&K.message.startsWith("Cannot rewind while"))throw new i(K.message);throw K}return J.messages=[..._.messages],J.updatedAt=new Date,y.publish(Q,"session.rewound",{targetMessageId:_.checkpoint.messageId,mode:_.mode,removedTurns:_.removedTurns,restoredFiles:_.restoredFiles,messages:_.messages}),G.json(_)})}),O.get("/:sessionId/subagents",async(G)=>{let Z=await W(G.req.param("sessionId"),G.req.query("projectPath")),J=await N(Z);return G.json({subagents:J.listSubagents().map(_O)})}),O.post("/:sessionId/subagents/:agentId/resume",async(G)=>{CO(G.req.param("agentId"));let Z=Ox.safeParse(await G.req.json());if(!Z.success)throw new b("Invalid subagent resume request");let J=await W(G.req.param("sessionId"),G.req.query("projectPath")),Q=v(J);return j(Q).runExclusive(async()=>{let U=J.currentRunId?f.get(J.currentRunId):void 0;if(U&&(U.status==="running"||U.status==="waiting_permission"))throw new i("Cannot resume a subagent while a parent run is active");let M=await N(J),_=!1,K,z=(H)=>{y.publish(Q,"subagent.complete",{subagentSessionId:H.id,success:H.status==="completed",status:H.status,summary:H.result?.message?.slice(0,500),resumedFrom:H.resumedFrom,rootAgentId:H.rootAgentId,resumeDepth:H.resumeDepth})},w;try{w=M.resumeSubagent({agentId:G.req.param("agentId"),prompt:Z.data.prompt,onEvent:(H,B)=>{N0(Q,B,H)},onCompleted:(H)=>{if(_)z(H);else K=H}})}catch(H){if(H instanceof Error&&(H.message.startsWith("Cannot resume")||H.message.startsWith("Subagent cannot")))throw new i(H.message);if(H instanceof Error&&H.message.startsWith("Subagent not found"))throw new m(H.message);throw H}if(y.publish(Q,"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}),_=!0,K)z(K);return G.json({source:_O(w.source),session:_O(w.session)})})}),O.get("/:sessionId/goal",async(G)=>{let Z=await W(G.req.param("sessionId"),G.req.query("projectPath"));return G.json({goal:await new Yx(Z.projectPath,Z.id).get()})}),O.put("/:sessionId/goal",async(G)=>{let Z=g(V0,await G.req.json());if(!Z.success)throw new b("Invalid goal request");let J=await W(G.req.param("sessionId"),G.req.query("projectPath")),Q=v(J);return j(Q).runExclusive(async()=>{let U=J.currentRunId?f.get(J.currentRunId):void 0;if(U&&(U.status==="running"||U.status==="waiting_permission"))return G.json({status:"rejected",reason:"run_active"},409);let _=await(await N(J)).createGoal(Z.data);y.publish(Q,"goal.updated",{goal:_});let K=Z.data.permissionMode??"default",z=A(J,"",K,{goalContinuationOnly:!0});return G.json({status:"running",runId:z.id,goal:_},202)})}),O.patch("/:sessionId/goal",async(G)=>{let Z=g(G0,await G.req.json());if(!Z.success)throw new b("Invalid goal update");let J=await W(G.req.param("sessionId"),G.req.query("projectPath")),Q=v(J);return j(Q).runExclusive(async()=>{let U=await N(J),M;if(Z.data.action==="pause")M=await U.pauseGoal();else if(Z.data.action==="edit")M=await U.editGoal(Z.data.objective);else M=await U.resumeGoal();if(y.publish(Q,"goal.updated",{goal:M}),M.status==="active"&&(!J.currentRunId||!["running","waiting_permission"].includes(f.get(J.currentRunId)?.status??""))){let _=A(J,"","default",{goalContinuationOnly:!0});return G.json({status:"running",runId:_.id,goal:M},202)}return G.json({status:M.status,goal:M})})}),O.delete("/:sessionId/goal",async(G)=>{let Z=await W(G.req.param("sessionId"),G.req.query("projectPath")),J=v(Z),U=await(await N(Z)).clearGoal();if(U)y.publish(J,"goal.cleared",{});return G.json({cleared:U})}),O.delete("/:sessionId",async(G)=>{let Z=G.req.param("sessionId"),J=G.req.query("projectPath");try{let Q=await c(Z,J),U=C(Q),M=P.get(U),_=$.get(U),K;if(M?.currentRunId){let z=f.get(M.currentRunId);if(z)MO(z),await z.completion,K=z.id}if(_)await _.clearGoal().catch((z)=>{F.warn("[SessionRoutes] Failed to clear session goal:",z)});if(await p.deleteSession(Q.sessionId,Q.projectPath),K)f.delete(K);if(P.delete(U),V.delete(U),x.delete(U),Y.delete(U),_){if(await _.dispose(),$.delete(U),$.size===0)await n.getInstance().disconnectAll()}return G.json({success:!0})}catch(Q){if(F.error("[SessionRoutes] Failed to delete session:",Q),Q instanceof b||Q instanceof m||Q instanceof l)throw Q;throw new t("Failed to delete session")}}),O.get("/:sessionId/message",async(G)=>{let Z=G.req.param("sessionId");try{let J=await c(Z,G.req.query("projectPath")),Q=P.get(C(J)),U=Q?.messages?Q.messages:await p.loadSession(J.sessionId,J.projectPath);return G.json(U)}catch(J){if(F.error("[SessionRoutes] Failed to get messages:",J),J instanceof b||J instanceof m||J instanceof l)throw J;throw new t("Failed to get messages")}}),O.get("/:sessionId/events",async(G)=>{let Z=G.req.param("sessionId"),J=await c(Z,G.req.query("projectPath")),Q=await X(J);return sx(G,async(U)=>{let _,K,z=!1,w=()=>{if(K!==void 0)clearInterval(K),K=void 0;_?.(),_=void 0},H=()=>{if(z)return;z=!0,w()},B=new Set;U.onAbort(H),_=y.subscribe((T)=>{if(T.sessionId!==J.sessionId||T.projectPath!==J.projectPath)return;let d=T.properties.requestId;if((T.type==="permission.asked"||T.type==="question.required")&&typeof d==="string"){if(B.has(d))return;B.add(d)}U.writeSSE({data:JSON.stringify({type:T.type,properties:{...T.properties,sessionId:T.sessionId,projectPath:T.projectPath}})}).catch(H)});try{if(U.aborted||z)return;if(await U.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:J.sessionId,projectPath:J.projectPath,timestamp:Date.now()}})}).catch((k)=>{throw H(),k}),U.aborted||z)return;let d=(Q.currentRunId?f.get(Q.currentRunId):void 0)?.pendingPermission;if(d){B.add(d.permissionId);let k=Zx(d,!0);await U.writeSSE({data:JSON.stringify({type:k.type,properties:{...k.properties,sessionId:J.sessionId,projectPath:J.projectPath}})})}D(Q).catch((k)=>{F.error(`[SessionRoutes] Failed to resume pending input for ${Z}:`,k)}),K=setInterval(()=>{if(!U.aborted)U.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(H)},15000);while(!U.aborted&&!z)await new Promise((k)=>setTimeout(k,1000))}finally{H()}})}),O.post("/:sessionId/message",async(G)=>{let Z=G.req.param("sessionId"),J=await G.req.json(),Q=g(x0,J);if(!Q.success)throw new b("Invalid message format");let{content:U,attachments:M,permissionMode:_,projectPath:K}=Q.data,z=_||"default",w=Q0(U,M),H=await W(Z,K??G.req.query("projectPath")),B=v(H);return j(B).runExclusive(async()=>{let T=H.currentRunId?f.get(H.currentRunId):void 0;if(T&&(T.status==="running"||T.status==="waiting_permission")){let u=await(await N(H)).enqueueSteering(w,{allowBeforeTurn:!0});if(!u.accepted)return G.json({status:"rejected",reason:u.reason??"turn_unavailable"},409);let SO=u.messageId??GO(12),UO=u.queued;y.publish(B,"message.created",{messageId:SO,role:"user",content:EO(w)});let DO=u.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(y.publish(B,DO,{runId:T.id,messageId:SO,queued:UO}),u.delivery==="next_turn"&&T.status!=="running"&&T.status!=="waiting_permission")D(H).catch((kx)=>{F.error(`[SessionRoutes] Failed to wake queued follow-up for ${Z}:`,kx)});if(u.delivery==="next_turn")T.pendingFollowUpRequested=!0;return G.json({runId:T.id,messageId:SO,status:u.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:UO},202)}let k=await(await N(H)).prepareInputTurn(w);if(!k.accepted)return G.json({status:"rejected",reason:k.reason},k.reason==="queue_full"?429:409);let NO=A(H,w,z,{preparedInputTurn:k});return G.json({runId:NO.id,messageId:k.messageId,status:"running"},202)})}),O.post("/:sessionId/abort",async(G)=>{let Z=G.req.param("sessionId"),J=await c(Z,G.req.query("projectPath")),Q=P.get(C(J));if(Q?.currentRunId){let U=f.get(Q.currentRunId);if(U)MO(U),await U.completion}return G.json({success:!0})}),O.get("/:sessionId/status",async(G)=>{let Z=G.req.param("sessionId"),J=await c(Z,G.req.query("projectPath")),Q=P.get(C(J));if(!Q?.currentRunId)return G.json({sessionId:Z,projectPath:J.projectPath,status:"idle"});let U=f.get(Q.currentRunId);return G.json({sessionId:Z,projectPath:J.projectPath,runId:Q.currentRunId,status:U?.status||"idle"})}),O};async function Z0(O,$,x,V,Y,j={}){let{abortController:N,sessionId:X,id:W}=O,A=j.preparedInputTurn?.messageId??GO(12),G=j.pendingInputOnly===!0||j.preparedInputTurn?.mode==="pending"||j.goalContinuationOnly===!0?void 0:GO(12),Z,J=v($),Q=(U,M)=>{y.publish(J,U,M)};try{if(!j.pendingInputOnly&&!j.goalContinuationOnly)Q("message.created",{messageId:A,role:"user",content:EO(x)});if(Q("session.status",{status:"running"}),G)Q("message.created",{messageId:G,role:"assistant",content:""});Z=await Y($);let U=Z,M=await Qx.createWithRuntime(U,{sessionId:X}),_=async(B)=>{let T=GO(12),d=300000;O.status="waiting_permission";let k=new Promise((SO)=>{let UO=setTimeout(()=>{F.warn(`[SessionRoutes] Permission ${T} timed out after 300000ms`),Q("permission.timeout",{requestId:T}),SO({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:T,resolve:(DO)=>{clearTimeout(UO),SO(DO)},details:B}}),NO=O.pendingPermission;if(!NO)throw Error("Permission request was not registered");let KO=Zx(NO);Q(KO.type,KO.properties),F.info(`[SessionRoutes] Permission request created: ${T}, runId: ${W}`);let u=await k;if(F.info(`[SessionRoutes] Permission response received: ${T}, approved: ${u.approved}`),!N.signal.aborted)O.status="running";if(O.pendingPermission===NO)O.pendingPermission=void 0;return u},K={messages:[...$.messages],userId:"web-user",sessionId:X,workspaceRoot:$.projectPath,signal:N.signal,permissionMode:V,confirmationHandler:{requestConfirmation:_}},z=()=>{if(!G)G=GO(12),Q("message.created",{messageId:G,role:"assistant",content:""});return G},w=async(B)=>{switch(B.kind){case"content_delta":Q("message.delta",{messageId:z(),delta:B.delta});break;case"thinking_delta":Q("thinking.delta",{delta:B.delta});break;case"tool_start":if("function"in B.toolCall)Q("tool.start",{messageId:z(),toolName:B.toolCall.function.name,toolCallId:B.toolCall.id,arguments:B.toolCall.function.arguments,toolKind:B.toolKind});break;case"tool_result":if("function"in B.toolCall)Q("tool.result",{messageId:z(),toolName:B.toolCall.function.name,toolCallId:B.toolCall.id,success:B.result.success,summary:B.result.metadata?.summary,output:mO(yO(B.toolCall.function.name,B.result)),metadata:jx(B.result.metadata)});break;case"token_usage":Q("token.usage",{...B.usage});break;case"turn_start":Q("turn.started",{turn:B.turn,maxTurns:B.maxTurns});break;case"steering_applied":Q("steering.applied",{runId:W,messageIds:B.messageIds,count:B.count,recovered:B.recovered,delivery:B.delivery,queued:U.getPendingSteeringCount()});break;case"follow_up_started":{if(G)Q("message.complete",{messageId:G}),G=void 0;for(let T of B.messages){if(!T.recovered||T.persisted)continue;Q("message.created",{messageId:T.id,role:"user",content:EO(T.content),recovered:!0})}Q("follow_up.started",{runId:W,queued:B.queued,recovered:B.recovered}),z();break}case"goal_updated":Q("goal.updated",{goal:B.goal});break;case"goal_continuation_started":Q("goal.continuation.started",{goal:B.goal,continuation:B.continuation}),z();break;case"compaction":Q(B.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":Q("model.fallback",{});break;case"task_update":Q("task.updated",{tasks:B.tasks});break;default:break}},H=await FO(M.chatStream(x,K,{stream:!0,pendingInputOnly:j.pendingInputOnly,preparedInputTurn:j.preparedInputTurn,goalContinuationOnly:j.goalContinuationOnly}),w);if(!H.success)throw Error(H.error?.message??"Agent run failed");for(let B=0;B<20;B++){let T=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,U.getPendingSteeringCount()===0){if(!T)break;continue}if(N.signal.aborted)break;if(H=await FO(M.chatStream("",K,{stream:!0,pendingInputOnly:!0}),w),!H.success)throw Error(H.error?.message??"Agent follow-up failed")}if($.messages=[...K.messages],$.updatedAt=new Date,N.signal.aborted||O.status==="cancelled"){Q("session.status",{status:"idle"});return}if(G)Q("message.complete",{messageId:G});Q("thinking.completed",{}),O.status="completed",Q("session.completed",{runId:W,outputTruncated:H.metadata?.outputTruncated??!1}),Q("session.status",{status:"idle"})}catch(U){if(Z&&j.preparedInputTurn)await Z.finishTurn(j.preparedInputTurn.handle).catch(()=>{return});if(N.signal.aborted||O.status==="cancelled"){MO(O,"runtime-abort"),Q("session.status",{status:"idle"});return}F.error("[SessionRoutes] Agent execution error:",U),O.status="failed",Q("session.error",{error:U instanceof Error?U.message:"Unknown error"}),Q("session.status",{status:"error"})}}function Xx(O,$,x){F.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),F.info(`[SessionRoutes] Active runs: ${f.size}`);for(let[V,Y]of f.entries())if(F.info(`[SessionRoutes] Checking run ${V}: sessionId=${Y.sessionId}, projectPath=${Y.projectPath}, pendingPermission=${Y.pendingPermission?.permissionId}`),Y.sessionId===O.sessionId&&Y.projectPath===O.projectPath&&Y.pendingPermission?.permissionId===$)return Y.pendingPermission.resolve(x),F.info(`[SessionRoutes] Permission ${$} responded, runId: ${Y.id}`),!0;return F.error(`[SessionRoutes] Permission not found: ${$}`),!1}var hO=L("Service"),U0=S.Object({approved:S.Boolean(),remember:S.Optional(S.Boolean()),scope:S.Optional(E(["once","session","project"])),targetMode:S.Optional(E(["default","autoEdit","plan","yolo"])),feedback:S.Optional(S.String()),answers:S.Optional(S.Record(S.String(),S.Union([S.String(),S.Array(S.String())])))}),_x=()=>{let O=new j0;return O.post("/:permissionId",async($)=>{let x=$.req.param("permissionId"),V=$.req.query("sessionId"),Y=$.req.query("projectPath");hO.info(`[PermissionRoutes] Received permission response: permissionId=${x}, sessionId=${V}`);try{let j=await $.req.json(),N=g(U0,j);if(!N.success)throw new b("Invalid permission response format");let{approved:X,remember:W,scope:A,targetMode:D,feedback:G,answers:Z}=N.data;if(!V)throw new b("sessionId query parameter is required");let J=await c(V,Y);if(!Xx(J,x,{approved:X,reason:G,scope:A,targetMode:D,feedback:G,answers:Z}))throw new m("Permission request",x);return hO.info(`[PermissionRoutes] Permission ${x} ${X?"approved":"denied"}`),$.json({success:!0,approved:X,remember:W})}catch(j){if(hO.error("[PermissionRoutes] Failed to respond to permission:",j),j instanceof b||j instanceof l||j instanceof m||j instanceof I)throw j;throw j}}),O};import{Hono as X0}from"hono";var Mx=L("Service"),Bx=()=>{let O=new X0;return O.get("/",async($)=>{try{let x=await Ax();return $.json(x)}catch(x){return Mx.error("[ProviderRoutes] Failed to list providers:",x),$.json([])}}),O.get("/:provider/models",async($)=>{let x=$.req.param("provider");try{let V=await Wx(x);return $.json(V)}catch(V){return Mx.error("[ProviderRoutes] Failed to list models:",V),$.json([])}}),O.put("/:provider/credential",async($)=>{let x=$.req.param("provider"),V=await $.req.json();if(!V.apiKey?.trim())throw new b("apiKey is required");return await r().setApiKey(x,V.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await r().clearCredential($.req.param("provider")),$.json({success:!0})}),O};import{Hono as _0}from"hono";import*as s from"node:fs/promises";import{homedir as M0}from"node:os";import*as WO from"node:path";var OO=L("Service"),fO=WO.join(M0(),".blade","skills-config.json");async function wx(){try{let O=await s.readFile(fO,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function A0(O){await s.mkdir(WO.dirname(fO),{recursive:!0}),await s.writeFile(fO,JSON.stringify(O,null,2))}async function W0(O,$){let x=await wx();if($)x.disabled=x.disabled.filter((V)=>V!==O);else if(!x.disabled.includes(O))x.disabled.push(O);await A0(x)}var YO=null,B0=300000;async function H0(){if(YO&&Date.now()-YO.timestamp<B0)return YO.data;try{let O=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!O.ok)return OO.warn(`GitHub API returned ${O.status}`),YO?.data||[];let $=await O.json(),x=[];for(let V of $){if(V.type!=="dir")continue;let Y=`Official ${V.name} skill`;try{let j=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${V.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{}x.push({name:V.name,description:Y,tag:"Official",author:"Anthropic"})}return YO={data:x,timestamp:Date.now()},x}catch(O){return OO.warn("Failed to fetch skills catalog from GitHub:",O),YO?.data||[]}}var Kx=()=>{let O=new _0;return O.get("/",async($)=>{try{let x=AO();await x.initialize();let V=x.getAll(),Y=await wx(),j=V.map((N)=>({id:N.name,name:N.name,enabled:!Y.disabled.includes(N.name),description:N.description||"",version:N.version||"1.0.0",provider:"Local",location:N.source==="builtin"?"Built-in":N.basePath,capabilities:["prompts"],allowedTools:N.allowedTools||[]}));return $.json(j)}catch(x){return OO.error("[SkillsRoutes] Failed to get skills:",x),$.json([])}}),O.post("/:name/toggle",async($)=>{try{let x=$.req.param("name"),V=await $.req.json();return await W0(x,V.enabled),$.json({success:!0,enabled:V.enabled})}catch(x){return OO.error("[SkillsRoutes] Failed to toggle skill:",x),$.json({success:!1,error:x.message},500)}}),O.delete("/:name",async($)=>{try{let x=$.req.param("name"),V=`${process.env.HOME}/.blade/skills/${x}`;return await s.rm(V,{recursive:!0,force:!0}),await AO().refresh(),$.json({success:!0})}catch(x){return OO.error("[SkillsRoutes] Failed to uninstall skill:",x),$.json({success:!1,error:x.message},500)}}),O.post("/install",async($)=>{try{let x=await $.req.json(),V=Hx(),Y=AO(),j=!1;if(x.source==="catalog"&&x.name){if(j=await V.installOfficialSkill(x.name),!j)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(x.source==="repo"&&x.url){if(j=await V.installFromRepo(x.url,x.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(x.source==="local"&&x.path){if(j=await V.installFromLocal(x.path,x.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(x){return OO.error("[SkillsRoutes] Failed to install skill:",x),$.json({success:!1,error:x.message},500)}}),O.get("/catalog",async($)=>{try{let x=await H0();return $.json(x)}catch(x){return OO.error("[SkillsRoutes] Failed to get catalog:",x),$.json([])}}),O};import w0 from"fast-glob";import{Hono as K0}from"hono";import{execSync as D0}from"node:child_process";import{readdir as z0}from"node:fs/promises";import BO from"node:path";var jO=L("Service"),T0=(O)=>{try{return D0("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},b0=[...HO.map((O)=>`${O}/**`),...HO,...kO.map((O)=>`**/${O}`)],q0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),Tx=()=>{let O=new K0;return O.get("/commands",async($)=>{try{let x=$.req.query("q")||"",V=zx(x).filter((Y)=>!q0.has(Y.command));return $.json(V)}catch(x){return jO.error("[SuggestionsRoutes] Failed to get command suggestions:",x),$.json([])}}),O.get("/files",async($)=>{try{let x=$.req.query("q")||"",V=$.get("directory")||h(),Y=Math.min(Number($.req.query("limit"))||100,1000),N=(await w0("**/*",{cwd:V,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:b0})).map((A)=>A.replace(/\\/g,"/"));if(!x)return $.json(N.slice(0,Y));let X=x.toLowerCase(),W=N.filter((A)=>A.toLowerCase().includes(X)).slice(0,Y);return $.json(W)}catch(x){return jO.error("[SuggestionsRoutes] Failed to get file suggestions:",x),$.json([])}}),O.get("/files/tree",async($)=>{try{let x=$.get("directory")||h(),V=$.req.query("path")||"",Y=V?BO.join(x,V):x,N=(await z0(Y,{withFileTypes:!0})).map((A)=>({name:A.name,path:V?`${V}/${A.name}`:A.name,type:A.isDirectory()?"dir":"file"}));N.sort((A,D)=>{if(A.type!==D.type)return A.type==="dir"?-1:1;return A.name.localeCompare(D.name)});let X=new Set(HO),W=N.filter((A)=>{let D=A.name;if(D.startsWith("."))return!1;if(X.has(D))return!1;for(let G of kO)if(D.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(W)}catch(x){return jO.error("[SuggestionsRoutes] Failed to get file tree:",x),$.json([])}}),O.get("/files/content",async($)=>{try{let x=$.req.query("path");if(!x)return $.json({error:"Missing file path"},400);let V=$.get("directory")||h(),Y=BO.resolve(V,x),j=BO.relative(V,Y);if(j.startsWith("..")||BO.isAbsolute(j))return $.json({error:"Invalid file path"},400);let N=Dx(),X=await N.stat(Y);if(!X?.isFile)return $.json({error:"File not found"},404);let W=200000,A=await N.readTextFile(Y),D=A.length>W;return $.json({path:x,content:D?A.slice(0,W):A,truncated:D,size:X.size})}catch(x){return jO.error("[SuggestionsRoutes] Failed to get file content:",x),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{try{let x=$.get("directory")||h(),V=T0(x);return $.json({branch:V})}catch(x){return jO.error("[SuggestionsRoutes] Failed to get git info:",x),$.json({branch:null})}}),O};import{Hono as F0}from"hono";var e=L("Service"),JO=new Map,bx=2097152,qx=65536;function Fx(){return typeof globalThis.Bun<"u"}async function L0(O,$,x){if(Fx()){let{spawn:j}=await import("bun-pty"),N=j(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env});return{pid:N.pid,write:(X)=>N.write(X),resize:(X,W)=>N.resize(X,W),kill:()=>N.kill(),onData:(X)=>N.onData(X),onExit:(X)=>N.onExit(X)}}let Y=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:x.cwd,env:x.env,cols:80,rows:24});return{pid:Y.pid,write:(j)=>Y.write(j),resize:(j,N)=>Y.resize(j,N),kill:()=>Y.kill(),onData:(j)=>{Y.onData(j)},onExit:(j)=>{Y.onExit(j)}}}var RO=void 0,pO;if(Fx())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();pO=$.upgradeWebSocket,RO=$.websocket}catch(O){e.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function Lx(O,$){let x=`term-${Date.now()}`;e.info(`[Terminal] New connection: ${x}, cwd: ${O}`);let V=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=V.endsWith("sh")?["-l"]:[],j=await L0(V,Y,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),N={id:x,process:j,cwd:O,buffer:"",subscribers:new Set};if(JO.set(x,N),N.subscribers.add($),j.onData((X)=>{let W=!1;for(let A of N.subscribers)try{A.send(X),W=!0}catch{N.subscribers.delete(A)}if(W)return;if(N.buffer+=X,N.buffer.length>bx)N.buffer=N.buffer.slice(-bx)}),j.onExit(({exitCode:X})=>{e.info(`[Terminal] Process exited: ${x}, code: ${X}`);for(let W of N.subscribers)try{W.close()}catch{}JO.delete(x)}),N.buffer){let X=N.buffer;N.buffer="";for(let W=0;W<X.length;W+=qx)$.send(X.slice(W,W+qx))}return{session:N,cleanup:()=>{if(e.info(`[Terminal] Connection closed: ${x}`),N.subscribers.delete($),N.subscribers.size===0){try{N.process.kill()}catch{}JO.delete(x)}}}}function Cx(O,$){O.on("connection",async(x,V)=>{let Y=new URL(V.url||"/",`http://${V.headers.host}`);if(!Y.pathname.endsWith("/terminal/ws")){x.close();return}let j=Y.searchParams.get("cwd")||$()||h();try{let{session:N,cleanup:X}=await Lx(j,{send:(W)=>x.send(W),close:()=>x.close()});x.on("message",(W)=>{try{N.process.write(String(W))}catch(A){e.error("[Terminal] Failed to write to PTY:",A)}}),x.on("close",X),x.on("error",X)}catch(N){e.error("[Terminal] Failed to spawn PTY:",N),x.close()}})}var Ex=()=>{let O=new F0;if(O.get("/status",($)=>{let x=Array.from(JO.values()).map((V)=>({id:V.id,cwd:V.cwd}));return $.json({active:x.length,terminals:x})}),O.post("/kill/:terminalId",($)=>{let x=$.req.param("terminalId"),V=JO.get(x);if(V){try{V.process.kill()}catch{}for(let Y of V.subscribers)Y.close();return JO.delete(x),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),pO)O.get("/ws",pO(($)=>{let x=$.req.query("cwd")||$.get("directory")||h(),V;return{async onOpen(Y,j){try{V=await Lx(x,{send:(N)=>j.send(N),close:()=>j.close()})}catch(N){e.error("[Terminal] Failed to spawn PTY:",N),j.close()}},onMessage(Y){if(!V)return;try{V.session.process.write(String(Y.data))}catch(j){e.error("[Terminal] Failed to write to PTY:",j)}},onClose(){V?.cleanup()}}}));else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};var R=L("Service"),IO=[];function p0(){let O=h0(k0(import.meta.url)),$=[xO(O,"web"),xO(h(),"dist/web"),xO(h(),"packages/cli/dist/web")];for(let x of $){let V=xO(x,"index.html");if(hx(V)){if(wO(V,"utf-8").includes("/assets/"))return R.debug(`[Server] Found web dist at: ${x}`),x}}return null}function R0(){let O=new C0;O.onError((x,V)=>{if(R.error("[Server] Request error:",x),x instanceof I)return V.json(x.toObject(),x.statusCode);let Y=x instanceof Error?x.message:String(x);return V.json({error:{code:"INTERNAL_ERROR",message:Y}},500)}),O.use(async(x,V)=>{let Y=process.env.BLADE_SERVER_PASSWORD;if(!Y)return V();let j=x.req.path;if(j==="/"||j.startsWith("/assets/")||j.endsWith(".html")||j.endsWith(".js")||j.endsWith(".css"))return V();let N=x.req.header("Authorization");if(!N?.startsWith("Basic "))return x.header("WWW-Authenticate",'Basic realm="Blade Server"'),x.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let X=Buffer.from(N.slice(6),"base64").toString(),[W,A]=X.split(":"),D=process.env.BLADE_SERVER_USERNAME??"blade";if(W!==D||A!==Y)return x.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return V()}),O.use(async(x,V)=>{let Y=x.req.path==="/health"||x.req.path==="/global/health"||x.req.path.startsWith("/assets/");if(!Y)R.debug(`[Server] ${x.req.method} ${x.req.path}`);let j=Date.now();if(await V(),!Y){let N=Date.now()-j;R.debug(`[Server] ${x.req.method} ${x.req.path} - ${x.res.status} (${N}ms)`)}}),O.use(E0({origin(x){if(!x)return;if(x.startsWith("http://localhost:"))return x;if(x.startsWith("http://127.0.0.1:"))return x;if(x==="tauri://localhost"||x==="http://tauri.localhost")return x;if(IO.includes(x))return x;return}})),O.use(async(x,V)=>{let Y=x.req.query("directory")||x.req.header("x-blade-directory")||h();try{Y=decodeURIComponent(Y)}catch{}return x.set("directory",Y),V()}),O.route("/global",vO()),O.route("/sessions",Ux()),O.route("/configs",gO()),O.route("/permissions",_x()),O.route("/providers",Bx()),O.route("/models",tO()),O.route("/suggestions",Tx()),O.route("/terminal",Ex()),O.route("/mcp",uO()),O.route("/skills",Kx()),O.get("/health",(x)=>{return x.json({healthy:!0,version:VO()})});let $=p0();if($)R.info(`[Server] Serving static files from ${$}`),O.get("/assets/*",(x)=>{let V=xO($,x.req.path);if(!hx(V))return x.json({error:{code:"NOT_FOUND",message:`File not found: ${x.req.path}`}},404);let Y=wO(V),j=f0(V).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"}})}),O.get("/",(x)=>{let V=xO($,"index.html"),Y=wO(V,"utf-8");return x.html(Y)}),O.get("*",(x)=>{let V=x.req.path;if(V.includes("."))return x.json({error:{code:"NOT_FOUND",message:`File not found: ${V}`}},404);let Y=xO($,"index.html"),j=wO(Y,"utf-8");return x.html(j)});else R.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(x)=>{return x.json({message:"Blade API Server",version:VO(),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"}})}),O.all("*",(x)=>{return x.json({error:{code:"NOT_FOUND",message:`Route not found: ${x.req.path}`}},404)});return O}function I0(){let O=m0(),$=[];for(let x of Object.keys(O)){let V=O[x];if(!V)continue;for(let Y of V){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;$.push(Y.address)}}return $}function yx(){return typeof globalThis.Bun<"u"}function mx(O,$){let x=globalThis.Bun,V=(j)=>{try{return x.serve({hostname:$.hostname,port:j,fetch:O.fetch,idleTimeout:0,websocket:RO})}catch(N){R.error("Failed to start Bun server:",N);return}},Y=$.port===0?V(4096)??V(0):V($.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 g0(O,$){return new Promise((x,V)=>{let Y=y0(async(A,D)=>{let G=new URL(A.url||"/",`http://${A.headers.host}`),Z=new Headers;for(let[U,M]of Object.entries(A.headers))if(M)if(Array.isArray(M))for(let _ of M)Z.append(U,_);else Z.set(U,M);let J;if(A.method!=="GET"&&A.method!=="HEAD")J=(await new Promise((M)=>{let _=[];A.on("data",(K)=>_.push(K)),A.on("end",()=>M(Buffer.concat(_)))})).toString();let Q=new Request(G.toString(),{method:A.method,headers:Z,body:J});try{let U=await O.fetch(Q);if(D.statusCode=U.status,U.headers.forEach((M,_)=>{D.setHeader(_,M)}),U.body){let M=U.body.getReader(),_=async()=>{let{done:K,value:z}=await M.read();if(K){D.end();return}return D.write(z),_()};await _()}else{let M=await U.text();D.end(M)}}catch(U){R.error("[Server] Node request error:",U),D.statusCode=500,D.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),j=new P0({noServer:!0}),N=h();Cx(j,()=>N),Y.on("upgrade",(A,D,G)=>{if(new URL(A.url||"/",`http://${A.headers.host}`).pathname==="/terminal/ws")j.handleUpgrade(A,D,G,(J)=>{j.emit("connection",J,A)});else D.destroy()});let X=(A)=>{return new Promise((D,G)=>{Y.once("error",(Z)=>{if(Z.code==="EADDRINUSE")G(Z);else G(Z)}),Y.listen(A,$.hostname,()=>{let Z=Y.address();if(Z&&typeof Z==="object")D(Z.port);else D(A)})})};(async()=>{let A;if($.port===0)try{A=await X(4096)}catch{A=await X(0)}else A=await X($.port);let D=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${A}`);x({url:D,port:A,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{j.close(()=>{Y.close(()=>G())})})}})})().catch(V)})}var fx;((Y1)=>{let O,$;function x(){if(!$)$=R0();return $}Y1.getApp=x;function V(N){IO=N.cors??[];let X=x();if(yx())O=mx(X,N),R.info(`[Server] Blade server listening on ${O.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=O;return{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if(O)await O.stop(),O=void 0,$=void 0,R.info("[Server] Blade server stopped")}}}Y1.listen=V;async function Y(N){IO=N.cors??[];let X=x();if(yx())O=mx(X,N),R.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await g0(X,N),R.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);let W=O;return{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if(O)await O.stop(),O=void 0,$=void 0,R.info("[Server] Blade server stopped")}}}Y1.listenAsync=Y;function j(){return O!==void 0}Y1.isRunning=j})(fx||={});export{v0 as a,u0 as b,I0 as c,fx as d};
@@ -0,0 +1,41 @@
1
+ import{Bb as d,wb as h,yb as X}from"./chunk-ctqf59q1.js";import{Ib as n}from"./chunk-gsfkrr25.js";import{Tb as s}from"./chunk-34pdtz4q.js";import{ec as B}from"./chunk-dr06x0cw.js";import{nanoid as V}from"nanoid";var g;((G)=>{G.PreToolUse="PreToolUse";G.PostToolUse="PostToolUse";G.PostToolUseFailure="PostToolUseFailure";G.PermissionRequest="PermissionRequest";G.UserPromptSubmit="UserPromptSubmit";G.SessionStart="SessionStart";G.SessionEnd="SessionEnd";G.Stop="Stop";G.SubagentStop="SubagentStop";G.Notification="Notification";G.Compaction="Compaction"})(g||={});var T;((Q)=>{Q.Approve="approve";Q.Block="block";Q.Async="async"})(T||={});var N;((Q)=>{Q.Allow="allow";Q.Deny="deny";Q.Ask="ask"})(N||={});var y={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function M(O,S){return{...O,...S,PreToolUse:S.PreToolUse??O.PreToolUse,PostToolUse:S.PostToolUse??O.PostToolUse,PostToolUseFailure:S.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:S.PermissionRequest??O.PermissionRequest,UserPromptSubmit:S.UserPromptSubmit??O.UserPromptSubmit,SessionStart:S.SessionStart??O.SessionStart,SessionEnd:S.SessionEnd??O.SessionEnd,Stop:S.Stop??O.Stop,SubagentStop:S.SubagentStop??O.SubagentStop,Notification:S.Notification??O.Notification,Compaction:S.Compaction??O.Compaction}}function k(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let S=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(S)&&S>0)O.defaultTimeout=S}return O}class C{executedHooks=new Map;canExecute(O,S){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(S))return console.warn(`[HookGuard] Hook ${S} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,S){let q=this.executedHooks.get(O);if(q)q.add(S)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}var r=X.Object({hookEventName:X.Literal("PreToolUse"),permissionDecision:X.Optional(X.Enum(N)),permissionDecisionReason:X.Optional(X.String()),updatedInput:X.Optional(X.Record(X.String(),X.Unknown()))}),o=X.Object({hookEventName:X.Literal("PostToolUse"),additionalContext:X.Optional(X.String()),updatedOutput:X.Optional(X.Unknown())}),e=X.Object({hookEventName:X.Literal("Stop"),continue:X.Optional(X.Boolean()),continueReason:X.Optional(X.String())}),t=X.Object({hookEventName:X.Literal("SubagentStop"),continue:X.Optional(X.Boolean()),continueReason:X.Optional(X.String()),additionalContext:X.Optional(X.String())}),OO=X.Object({hookEventName:X.Literal("PermissionRequest"),permissionDecision:X.Optional(d(["approve","deny","ask"])),permissionDecisionReason:X.Optional(X.String())}),SO=X.Object({hookEventName:X.Literal("UserPromptSubmit"),updatedPrompt:X.Optional(X.String()),contextInjection:X.Optional(X.String())}),qO=X.Object({hookEventName:X.Literal("SessionStart"),env:X.Optional(X.Record(X.String(),X.String()))}),QO=X.Object({hookEventName:X.Literal("Compaction"),blockCompaction:X.Optional(X.Boolean()),blockReason:X.Optional(X.String())}),YO=X.Object({decision:X.Optional(X.Object({behavior:X.Enum(T)})),systemMessage:X.Optional(X.String()),hookSpecificOutput:X.Optional(X.Union([r,o,e,t,OO,SO,qO,QO])),suppressOutput:X.Optional(X.Boolean())});function p(O){return h(YO,O)}class w{parse(O,S,q){if(O.timedOut){let Y=q?.timeoutBehavior||"ignore",Z="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S}}let Q=this.tryParseJSON(O.stdout);if(Q){let Y=p(Q);if(!Y.success){let W="error"in Y?Y.error.message:"Unknown validation error",$=q?.failureBehavior||"ignore",R=`Invalid hook output JSON: ${W}`;if($==="deny")return{success:!1,blocking:!0,error:R,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};else if($==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${R}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};else return{success:!1,blocking:!1,warning:R,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S}}let Z=Y.data;if(Z.decision?.behavior==="block")return{success:!1,blocking:!0,error:Z.systemMessage||"Hook blocked execution",output:Z,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};if(Z.decision?.behavior==="async")return{success:!0,output:Z,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S};return{success:!0,output:Z,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:S}}return this.parseByExitCode(O,S,q)}parseByExitCode(O,S,q){let Q=O.exitCode;switch(Q){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};case 124:{let Y=q?.timeoutBehavior||"ignore",Z="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S}}default:{let Y=q?.failureBehavior||"ignore",Z=O.stderr||O.stdout||`Hook failed with exit code ${Q}`;if(Y==="deny")return{success:!1,blocking:!0,error:Z,stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${Z}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S};else return{success:!1,blocking:!1,warning:Z,stdout:O.stdout,stderr:O.stderr,exitCode:Q,hook:S}}}}tryParseJSON(O){try{let S=O.trim();if(!S)return null;let q=S.match(/^\s*(\{[\s\S]*\})\s*$/);if(!q)return null;return JSON.parse(q[1])}catch{return null}}}import{spawn as u}from"node:child_process";var ZO=500;function WO(O){return new Promise((S)=>setTimeout(S,O))}function x(O){return O&&typeof O==="object"&&"code"in O?String(O.code):void 0}function $O(O,S){return new Promise((q)=>{let Q=["/PID",String(O),"/T"];if(S)Q.push("/F");let Y=u("taskkill",Q,{stdio:"ignore",windowsHide:!0}),Z=!1,W=($)=>{if(Z)return;Z=!0,q($)};Y.once("error",()=>W(!1)),Y.once("close",($)=>W($===0))})}class a{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(O,S={}){this.child=O;this.platform=S.platform??process.platform,this.gracePeriodMs=S.gracePeriodMs??ZO,this.killProcess=S.killProcess??process.kill.bind(process),this.taskkill=S.taskkill??$O,this.wait=S.wait??WO;let q=()=>{if(this.state==="owned")this.state="released"};O.once("close",q),O.once("error",q)}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((O)=>{return this.state="released",this.terminationResult=O,O}),this.terminationPromise}async terminateOwnedTree(){let O=this.child.pid;if(!O)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let Q=await this.taskkill(O,!1);await this.wait(this.gracePeriodMs);let Y=await this.taskkill(O,!0);if(!Q&&!Y)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let S=this.signalPosixTree(O,"SIGTERM");await this.wait(this.gracePeriodMs);let q=this.signalPosixTree(O,"SIGKILL");return{success:S||q,alreadyExited:!1,forced:q}}signalPosixTree(O,S){if(O<=1||O===process.pid)return this.signalDirectChild(S);try{return this.killProcess(-O,S)}catch(q){if(x(q)==="ESRCH")return!0;return this.signalDirectChild(S)}}signalDirectChild(O){try{return this.child.kill(O)}catch(S){return x(S)==="ESRCH"}}}function l(O,S,q={}){let Q=u(O,S,{...q,detached:process.platform==="win32"?q.detached:!0,windowsHide:q.windowsHide??!0});return{child:Q,processTree:new a(Q)}}class E{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let S=this.maxSize-this.content.length;this.content+=O.substring(0,S)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class I{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,S,q,Q){let Y=JSON.stringify(S);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let Z=this.createSafeEnv(S),{child:W,processTree:$}=l(O,[],{shell:!0,env:Z,cwd:q.projectDir}),R=new E(this.MAX_STDOUT_SIZE),J=new E(this.MAX_STDERR_SIZE);W.stdout?.setEncoding("utf8"),W.stderr?.setEncoding("utf8"),W.stdout?.on("data",(F)=>{R.append(F)}),W.stderr?.on("data",(F)=>{J.append(F)});try{W.stdin?.write(Y),W.stdin?.end()}catch(F){throw await $.terminate(),Error(`Failed to write hook input: ${F}`)}return new Promise((F,G)=>{let K=!1,z=!1,D,L=()=>{return D??=$.terminate(),D},j=null,A=()=>{if(j&&q.abortSignal)q.abortSignal.removeEventListener("abort",j),j=null},U=setTimeout(()=>{K=!0,L()},Q);if(W.on("close",async(b)=>{if(z)return;if(z=!0,clearTimeout(U),A(),K)await L();F({stdout:R.getContent(),stderr:J.getContent(),exitCode:K?124:b??1,timedOut:K})}),W.on("error",(b)=>{if(z)return;z=!0,clearTimeout(U),A(),G(b)}),q.abortSignal){if(j=()=>{if(z)return;z=!0,clearTimeout(U),A(),L().then(()=>{F({stdout:R.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},q.abortSignal.addEventListener("abort",j),q.abortSignal.aborted)j()}})}createSafeEnv(O){return{BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:"",PATH:process.env.PATH||"",HOME:process.env.HOME||"",USER:process.env.USER||"",SHELL:process.env.SHELL||"/bin/sh"}}}class _ extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function i(O,S={}){let q;try{q=new URL(O)}catch{throw new _(`Invalid URL: ${O}`)}if(q.protocol!=="https:"&&q.protocol!=="http:")throw new _(`Only http/https supported, got: ${q.protocol}`);let Q=q.hostname.toLowerCase();if(RO(Q,S.allowedHosts))return;if(q.protocol==="http:"&&!S.allowHttp)throw new _(`HTTP (non-TLS) blocked for ${Q}; use https:// or add to allowedHosts`);if(XO(Q)&&!S.allowLoopback)throw new _(`Loopback address blocked: ${Q}; enable policy.allowLoopback or add to allowedHosts`);if(JO(Q)&&!S.allowPrivateRanges)throw new _(`Private/link-local address blocked: ${Q}; enable policy.allowPrivateRanges or add to allowedHosts`)}function RO(O,S){if(!S||S.length===0)return!1;return S.some((q)=>{let Q=q.toLowerCase();if(Q===O)return!0;if(Q.startsWith("*.")){let Y=Q.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function XO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function JO(O){let S=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!S)return!1;let[q,Q]=S.slice(1).map(Number);if(q===10)return!0;if(q===172&&Q>=16&&Q<=31)return!0;if(q===192&&Q===168)return!0;if(q===169&&Q===254)return!0;return!1}function c(O){if(!O)return{};let S={};for(let[q,Q]of Object.entries(O))S[q]=Q.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,Z)=>{return process.env[Z]??`\${${Z}}`});return S}var zO=s("Execution"),FO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class f{processExecutor=new I;outputParser=new w;chatServiceCache=new Map;async executePreToolHooks(O,S,q){if(O.length===0)return{decision:"allow"};let Q="tool_input"in S?S.tool_input:{},Y=[];for(let Z of O)try{let W={...S,...Q&&{tool_input:Q}},$=await this.executeHook(Z,W,q);if(!$.success){if($.blocking)return{decision:"deny",reason:$.error};if($.needsConfirmation)return{decision:"ask",reason:$.warning||$.error};if($.warning)Y.push($.warning);continue}let R=$.output?.hookSpecificOutput;if(R&&"permissionDecision"in R){switch(R.permissionDecision){case"deny":return{decision:"deny",reason:R.permissionDecisionReason};case"ask":return{decision:"ask",reason:R.permissionDecisionReason};case"allow":break}if("updatedInput"in R&&R.updatedInput)Q={...Q,...R.updatedInput}}}catch(W){let $=W instanceof Error?W.message:String(W);if(Y.push(`Hook failed: ${$}`),q.config.failureBehavior==="deny")return{decision:"deny",reason:$};else if(q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${$}. Continue?`}}return{decision:"allow",modifiedInput:Q,warning:Y.length>0?Y.join(`
2
+ `):void 0}}async executePostToolHooks(O,S,q){if(O.length===0)return{};let Q=q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,S,q,Q),Z=[],W=void 0,$=[];for(let R of Y){if(!R.success&&R.warning){$.push(R.warning);continue}let J=R.output?.hookSpecificOutput;if(J&&"additionalContext"in J){if(J.additionalContext)Z.push(J.additionalContext);if("updatedOutput"in J&&J.updatedOutput!==void 0)W=J.updatedOutput}}return{additionalContext:Z.length>0?Z.join(`
3
+
4
+ `):void 0,modifiedOutput:W,warning:$.length>0?$.join(`
5
+ `):void 0}}async executeStopHooks(O,S,q){if(O.length===0)return{shouldStop:!0};let Q=[];for(let Y of O)try{let Z=await this.executeHook(Y,S,q);if(!Z.success){if(Z.warning)Q.push(Z.warning);continue}let W=Z.output?.hookSpecificOutput;if(W&&"continue"in W&&W.continue===!1)return{shouldStop:!1,continueReason:W.continueReason,warning:Q.length>0?Q.join(`
6
+ `):void 0}}catch(Z){let W=Z instanceof Error?Z.message:String(Z);Q.push(`Hook failed: ${W}`)}return{shouldStop:!0,warning:Q.length>0?Q.join(`
7
+ `):void 0}}async executeSubagentStopHooks(O,S,q){if(O.length===0)return{shouldStop:!0};let Q=[],Y=[];for(let Z of O)try{let W=await this.executeHook(Z,S,q);if(!W.success){if(W.warning)Q.push(W.warning);continue}let $=W.output?.hookSpecificOutput;if($&&"continue"in $){if($.continue===!1)return{shouldStop:!1,continueReason:$.continueReason,warning:Q.length>0?Q.join(`
8
+ `):void 0};if("additionalContext"in $&&$.additionalContext)Y.push($.additionalContext)}}catch(W){let $=W instanceof Error?W.message:String(W);Q.push(`Hook failed: ${$}`)}return{shouldStop:!0,additionalContext:Y.length>0?Y.join(`
9
+
10
+ `):void 0,warning:Q.length>0?Q.join(`
11
+ `):void 0}}async executePermissionRequestHooks(O,S,q){if(O.length===0)return{decision:"ask"};let Q=[];for(let Y of O)try{let Z=await this.executeHook(Y,S,q);if(!Z.success){if(Z.warning)Q.push(Z.warning);continue}let W=Z.output?.hookSpecificOutput;if(W&&"permissionDecision"in W){let $=W.permissionDecision;if($==="approve"||$==="deny")return{decision:$,reason:W.permissionDecisionReason,warning:Q.length>0?Q.join(`
12
+ `):void 0}}}catch(Z){let W=Z instanceof Error?Z.message:String(Z);Q.push(`Hook failed: ${W}`)}return{decision:"ask",warning:Q.length>0?Q.join(`
13
+ `):void 0}}async executeUserPromptSubmitHooks(O,S,q){if(O.length===0)return{proceed:!0};let Q=[],Y=[],Z;for(let W of O)try{let $=await this.executeHook(W,S,q);if(!$.success){if($.blocking)return{proceed:!1,warning:$.error};if($.warning)Q.push($.warning);continue}if($.stdout&&$.stdout.trim())Y.push($.stdout.trim());let R=$.output?.hookSpecificOutput;if(R&&"updatedPrompt"in R){if(R.updatedPrompt)Z=R.updatedPrompt;if(R.contextInjection)Y.push(R.contextInjection)}}catch($){let R=$ instanceof Error?$.message:String($);Q.push(`Hook failed: ${R}`)}return{proceed:!0,updatedPrompt:Z,contextInjection:Y.length>0?Y.join(`
14
+
15
+ `):void 0,warning:Q.length>0?Q.join(`
16
+ `):void 0}}async executeSessionStartHooks(O,S,q){if(O.length===0)return{proceed:!0};let Q=[],Y={};for(let Z of O)try{let W=await this.executeHook(Z,S,q);if(!W.success){if(W.blocking)return{proceed:!1,warning:W.error};if(W.warning)Q.push(W.warning);continue}let $=W.output?.hookSpecificOutput;if($&&"env"in $&&$.env)Object.assign(Y,$.env)}catch(W){let $=W instanceof Error?W.message:String(W);Q.push(`Hook failed: ${$}`)}return{proceed:!0,env:Object.keys(Y).length>0?Y:void 0,warning:Q.length>0?Q.join(`
17
+ `):void 0}}async executeSessionEndHooks(O,S,q){if(O.length===0)return{};let Q=[],Y=q.config.maxConcurrentHooks||5,Z=await this.executeHooksConcurrently(O,S,q,Y);for(let W of Z)if(!W.success&&W.warning)Q.push(W.warning);return{warning:Q.length>0?Q.join(`
18
+ `):void 0}}async executePostToolUseFailureHooks(O,S,q){if(O.length===0)return{};let Q=[],Y=[],Z=q.config.maxConcurrentHooks||5,W=await this.executeHooksConcurrently(O,S,q,Z);for(let $ of W){if(!$.success&&$.warning){Q.push($.warning);continue}if($.stdout&&$.stdout.trim())Y.push($.stdout.trim())}return{additionalContext:Y.length>0?Y.join(`
19
+
20
+ `):void 0,warning:Q.length>0?Q.join(`
21
+ `):void 0}}async executeNotificationHooks(O,S,q){let Q="message"in S?S.message:"";if(O.length===0)return{suppress:!1,message:Q};let Y=[],Z=!1,W=Q;for(let $ of O)try{let R=await this.executeHook($,S,q);if(!R.success){if(R.warning)Y.push(R.warning);continue}if(R.output?.suppressOutput){Z=!0;break}if(R.stdout&&R.stdout.trim())W=R.stdout.trim()}catch(R){let J=R instanceof Error?R.message:String(R);Y.push(`Hook failed: ${J}`)}return{suppress:Z,message:W,warning:Y.length>0?Y.join(`
22
+ `):void 0}}async executeCompactionHooks(O,S,q){if(O.length===0)return{blockCompaction:!1};let Q=[];for(let Y of O)try{let Z=await this.executeHook(Y,S,q);if(!Z.success){if(Z.warning)Q.push(Z.warning);continue}let W=Z.output?.hookSpecificOutput;if(W&&"blockCompaction"in W&&W.blockCompaction)return{blockCompaction:!0,blockReason:W.blockReason,warning:Q.length>0?Q.join(`
23
+ `):void 0}}catch(Z){let W=Z instanceof Error?Z.message:String(Z);Q.push(`Hook failed: ${W}`)}return{blockCompaction:!1,warning:Q.length>0?Q.join(`
24
+ `):void 0}}async executeHook(O,S,q){if(O.type==="command")return this.executeCommandHook(O,S,q);if(O.type==="prompt")return this.executePromptHook(O,S,q);if(O.type==="function")return this.executeFunctionHook(O,S,q);if(O.type==="http")return this.executeHttpHook(O,S,q);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,S,q){let Q=(O.timeout??q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,S,q,Q);return this.outputParser.parse(Y,O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,S,q){let Q=(O.timeout??q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model),Z="hook_event_name"in S?String(S.hook_event_name):"Unknown",W=this.buildPromptHookSystemMessage(O,Z),$=JSON.stringify(S,null,2),R=new AbortController,J=setTimeout(()=>R.abort(),Q),F;try{F=(await Y.chat([{role:"system",content:W},{role:"user",content:$}],void 0,R.signal)).content}catch(K){if(R.signal.aborted||K instanceof Error&&K.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior});throw K}finally{clearTimeout(J)}let G=this.extractJsonFromLLMResponse(F);return this.outputParser.parse({stdout:G,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior})}catch(Y){return zO.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,S,q){let Q=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,S,q,Q);if(Y===void 0||Y===null)return{success:!0,hook:O};let Z={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(Z,O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let Z={stdout:"",stderr:`Function hook timeout after ${Q}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse(Z,O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,S,q,Q){return new Promise((Y,Z)=>{let W=!1,$=setTimeout(()=>{if(W)return;W=!0;let J=Object.assign(Error(`Function hook timed out after ${Q}ms`),{isTimeout:!0});Z(J)},Q),R=()=>{if(W)return;W=!0,clearTimeout($),Z(Error("Function hook aborted"))};q.abortSignal?.addEventListener("abort",R,{once:!0}),Promise.resolve().then(()=>O(S,q)).then((J)=>{if(W)return;W=!0,clearTimeout($),q.abortSignal?.removeEventListener("abort",R),Y(J)},(J)=>{if(W)return;W=!0,clearTimeout($),q.abortSignal?.removeEventListener("abort",R),Z(J)})})}async executeHttpHook(O,S,q){let Q=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,Z=Math.max(1,(O.retries??0)+1);try{i(O.url,q.config.httpPolicy)}catch(J){return{success:!1,blocking:!0,error:J instanceof Error?J.message:String(J),hook:O}}let W={"Content-Type":"application/json",...c(O.headers)},$=JSON.stringify(S),R;for(let J=0;J<Z;J++){if(J>0){let z=Math.min(2**J*200,5000);await new Promise((D)=>setTimeout(D,z))}let F=new AbortController,G=setTimeout(()=>F.abort(),Q),K=()=>F.abort();q.abortSignal?.addEventListener("abort",K,{once:!0});try{let z=await fetch(O.url,{method:"POST",headers:W,body:$,redirect:"manual",signal:F.signal});if(z.status>=300&&z.status<400){R=Error(`HTTP hook received redirect (${z.status}); redirects are disabled`);continue}if(!z.ok){if(R=Error(`HTTP hook returned ${z.status} ${z.statusText}`),z.status>=400&&z.status<500)break;continue}let L={stdout:await GO(z,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(L,O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior})}catch(z){let D=z.name==="AbortError"||z.code==="ABORT_ERR";if(D&&q.abortSignal?.aborted){R=Error("HTTP hook aborted by caller");break}if(D){let L={stdout:"",stderr:`HTTP hook timeout after ${Q}ms`,exitCode:124,timedOut:!0};if(J===Z-1)return this.outputParser.parse(L,O,{timeoutBehavior:q.config.timeoutBehavior,failureBehavior:q.config.failureBehavior});R=Error(`HTTP hook timeout attempt ${J+1}`);continue}R=z}finally{clearTimeout(G),q.abortSignal?.removeEventListener("abort",K)}}return{success:!1,blocking:!1,error:R?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O){let S=O||"__default__",q=this.chatServiceCache.get(S);if(q)return q;let{ensureStoreInitialized:Q,getCurrentModel:Y,getModelById:Z}=await import("./chunk-j39q2kx7.js"),{createChatServiceAsync:W}=await import("./chunk-v5rn5r1h.js"),{resolveModelConfig:$}=await import("./chunk-a12tmmfr.js");await Q();let R=O?Z(O)||Y():Y();if(!R)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let J=(await import("./chunk-j39q2kx7.js")).getConfig();if(!J)throw Error("PromptHook: 配置未初始化");let F=await W($(R,J,!1).chat);return this.chatServiceCache.set(S,F),F}buildPromptHookSystemMessage(O,S){let q=FO[S]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${S} 事件中被触发。
25
+
26
+ `+`## 评估指令
27
+ ${O.prompt}
28
+
29
+ `+`## 输出格式
30
+ `+`必须返回一个 JSON 对象(不要包含任何其他文本):
31
+ `+`{
32
+ "decision": { "behavior": "approve" | "block" },
33
+ `+` "systemMessage": "可选的说明信息",
34
+ `+` "hookSpecificOutput": ${q}
35
+ }
36
+
37
+ `+`重要规则:
38
+ `+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
39
+ `+`- 如果没有发现问题,使用 "approve"
40
+ `+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(O){let S=O.trim(),q=S.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(q)return q[1].trim();return S}async executeHooksConcurrently(O,S,q,Q){let Y=[],Z=new Set;for(let W of O){if(Z.size>=Q)await Promise.race(Z);let $=this.executeHook(W,S,q).catch((J)=>({success:!1,blocking:!1,error:J instanceof Error?J.message:String(J),hook:W})),R=$.then(()=>{Z.delete(R)}).catch(()=>{Z.delete(R)});Z.add(R),Y.push($)}return Promise.all(Y)}}async function GO(O,S){let q=O.body?.getReader();if(!q)return"";let Q=new TextDecoder,Y=0,Z="";while(!0){let{value:W,done:$}=await q.read();if($)break;if(Y+=W.byteLength,Y>S){try{q.cancel()}catch{}Z+=Q.decode(W.slice(0,S-(Y-W.byteLength)));break}Z+=Q.decode(W,{stream:!0})}return Z+=Q.decode(),Z}import H from"picomatch";var KO=/^([A-Za-z0-9_|]+)\((.+)\)$/;class v{matches(O,S){if(!O)return!0;if(O.tools&&S.toolName){if(!this.matchTools(O.tools,S))return!1}if(O.paths&&S.filePath){if(!this.matchPaths(O.paths,S.filePath))return!1}if(O.commands&&S.command){if(!this.matchCommands(O.commands,S.command))return!1}return!0}matchTools(O,S){if(Array.isArray(O))return O.some((q)=>this.matchToolWithParams(q,S));return this.matchToolWithParams(O,S)}matchPaths(O,S){if(Array.isArray(O))return O.some((Q)=>{return H(Q)(S)});return H(O)(S)}matchCommands(O,S){if(Array.isArray(O))return O.some((q)=>this.matchPattern(S,q));return this.matchPattern(S,O)}matchToolWithParams(O,S){let{toolName:q,command:Q,filePath:Y}=S,Z=KO.exec(O);if(!Z)return this.matchPattern(q,O);let[,W,$]=Z;if(!this.matchPattern(q,W))return!1;let R=this.getArgValue(q,Q,Y);if(!R)return!1;return this.matchGlobOrPattern(R,$)}getArgValue(O,S,q){if(O==="Bash"||O==="BashTool")return S;if(["Read","Edit","Write","Glob","Grep"].includes(O))return q;return S||q}matchGlobOrPattern(O,S){if(/[*?[\]{}!]/.test(S))try{return H(S,{bash:!0,dot:!0})(O)}catch{}if(S.endsWith("*")){let q=S.slice(0,-1);return O.startsWith(q)}return O===S}matchPattern(O,S){if(S==="*")return!0;if(!S.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(S))return O===S;if(S.includes("|"))return S.split("|").map((Q)=>Q.trim()).includes(O);try{return new RegExp(S).test(O)}catch{return O===S}}}class P{static instance=null;config=y;executor=new f;guard=new C;matcher=new v;sessionDisabled=!1;constructor(){}static getInstance(){if(!P.instance)P.instance=new P;return P.instance}loadConfig(O){let S=M(y,O),q=k();S=M(S,q),this.config=S}isEnabled(){if(!this.config.enabled)return!1;if(this.sessionDisabled)return!1;return!0}disable(){this.sessionDisabled=!0,console.log("[HookManager] Hooks disabled for this session")}enable(){this.sessionDisabled=!1,console.log("[HookManager] Hooks enabled for this session")}getConfig(){return this.config}registerFunction(O,S,q,Q){let Y={type:"function",handler:q,timeout:Q?.timeout},Z={name:Q?.name??`inline-${O}-${Date.now()}`,matcher:S,hooks:[Y]},W=this.config[O]??[];return this.config[O]=[...W,Z],()=>{let $=this.config[O];if(!$)return;this.config[O]=$.filter((R)=>R!==Z)}}async reloadConfig(){let O=await import("node:fs/promises"),S=await import("node:path");try{let q=S.join(n(),".blade","settings.local.json"),Q=await O.readFile(q,"utf-8"),Y=JSON.parse(Q);if(Y.hooks)this.loadConfig(Y.hooks)}catch{}}async executePreToolHooks(O,S,q,Q){if(!this.isEnabled())return{decision:"allow"};if(Q.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(S,"PreToolUse"))return{decision:"allow"};let Y={hook_event_name:"PreToolUse",hook_execution_id:V(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:S,tool_input:q,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},Z=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePath(q),command:this.extractCommand(O,q)});if(Z.length===0)return{decision:"allow"};let W={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{let $=await this.executor.executePreToolHooks(Z,Y,W);if(this.guard.markExecuted(S,"PreToolUse"),Q.permissionMode==="yolo"){if($.decision==="deny")return $;return{decision:"allow",modifiedInput:$.modifiedInput,warning:$.warning,reason:$.reason}}return $}catch($){return console.error("[HookManager] Error executing PreToolUse hooks:",$),{decision:"allow",warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executePostToolHooks(O,S,q,Q,Y){if(!this.isEnabled())return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(S,"PostToolUse"))return{};let Z={hook_event_name:"PostToolUse",hook_execution_id:V(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:S,tool_input:q,tool_response:Q,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePath(q),command:this.extractCommand(O,q)});if(W.length===0)return{};let $={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{let R=await this.executor.executePostToolHooks(W,Z,$);return this.guard.markExecuted(S,"PostToolUse"),R}catch(R){return console.error("[HookManager] Error executing PostToolUse hooks:",R),{warning:`Hook execution failed: ${R instanceof Error?R.message:String(R)}`}}finally{this.guard.cleanup(S)}}async executeStopHooks(O){if(!this.isEnabled())return{shouldStop:!0};let S={hook_event_name:"Stop",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},q=this.getMatchingHooks("Stop",{});if(q.length===0)return{shouldStop:!0};let Q={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:this.config,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(q,S,Q)}catch(Y){return console.error("[HookManager] Error executing Stop hooks:",Y),{shouldStop:!0,warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executeSubagentStopHooks(O,S){if(!this.isEnabled())return{shouldStop:!0};let q={hook_event_name:"SubagentStop",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:S.projectDir,session_id:S.sessionId,permission_mode:S.permissionMode,agent_type:O,task_description:S.taskDescription,success:S.success,result_summary:S.resultSummary,error:S.error},Q=this.getMatchingHooks("SubagentStop",{});if(Q.length===0)return{shouldStop:!0};let Y={projectDir:S.projectDir,sessionId:S.sessionId,permissionMode:S.permissionMode,config:this.config,abortSignal:S.abortSignal};try{return await this.executor.executeSubagentStopHooks(Q,q,Y)}catch(Z){return console.error("[HookManager] Error executing SubagentStop hooks:",Z),{shouldStop:!0,warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async executePermissionRequestHooks(O,S,q,Q){if(!this.isEnabled())return{decision:"ask"};let Y={hook_event_name:"PermissionRequest",hook_execution_id:V(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:S,tool_input:q,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},Z=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePath(q),command:this.extractCommand(O,q)});if(Z.length===0)return{decision:"ask"};let W={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{return await this.executor.executePermissionRequestHooks(Z,Y,W)}catch($){return console.error("[HookManager] Error executing PermissionRequest hooks:",$),{decision:"ask",warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeUserPromptSubmitHooks(O,S){if(!this.isEnabled())return{proceed:!0};let q={hook_event_name:"UserPromptSubmit",hook_execution_id:V(),timestamp:new Date().toISOString(),user_prompt:O,has_images:S.hasImages,image_count:S.imageCount,project_dir:S.projectDir,session_id:S.sessionId,permission_mode:S.permissionMode},Q=this.getMatchingHooks("UserPromptSubmit",{});if(Q.length===0)return{proceed:!0};let Y={projectDir:S.projectDir,sessionId:S.sessionId,permissionMode:S.permissionMode,config:this.config,abortSignal:S.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Q,q,Y)}catch(Z){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",Z),{proceed:!0,warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async executeSessionStartHooks(O){if(!this.isEnabled())return{proceed:!0};let S={hook_event_name:"SessionStart",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},q=this.getMatchingHooks("SessionStart",{});if(q.length===0)return{proceed:!0};let Q={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:this.config,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(q,S,Q)}catch(Y){return console.error("[HookManager] Error executing SessionStart hooks:",Y),{proceed:!0,warning:`Hook execution failed: ${Y instanceof Error?Y.message:String(Y)}`}}}async executeSessionEndHooks(O,S){if(!this.isEnabled())return{};let q={hook_event_name:"SessionEnd",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:S.projectDir,session_id:S.sessionId,permission_mode:S.permissionMode,reason:O},Q=this.getMatchingHooks("SessionEnd",{});if(Q.length===0)return{};let Y={projectDir:S.projectDir,sessionId:S.sessionId,permissionMode:S.permissionMode,config:this.config,abortSignal:S.abortSignal};try{return await this.executor.executeSessionEndHooks(Q,q,Y),{}}catch(Z){return console.error("[HookManager] Error executing SessionEnd hooks:",Z),{warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async executePostToolUseFailureHooks(O,S,q,Q,Y){if(!this.isEnabled())return{};let Z={hook_event_name:"PostToolUseFailure",hook_execution_id:V(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:S,tool_input:q,error:Q,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePath(q),command:this.extractCommand(O,q)});if(W.length===0)return{};let $={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:this.config,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(W,Z,$)}catch(R){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",R),{warning:`Hook execution failed: ${R instanceof Error?R.message:String(R)}`}}}async executeNotificationHooks(O,S,q){if(!this.isEnabled())return{suppress:!1,message:S};let Q={hook_event_name:"Notification",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,notification_type:O,title:q.title,message:S},Y=this.getMatchingHooks("Notification",{});if(Y.length===0)return{suppress:!1,message:S};let Z={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:this.config,abortSignal:q.abortSignal};try{return await this.executor.executeNotificationHooks(Y,Q,Z)}catch(W){return console.error("[HookManager] Error executing Notification hooks:",W),{suppress:!1,message:S,warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeCompactionHooks(O,S){if(!this.isEnabled())return{blockCompaction:!1};let q={hook_event_name:"Compaction",hook_execution_id:V(),timestamp:new Date().toISOString(),project_dir:S.projectDir,session_id:S.sessionId,permission_mode:S.permissionMode,trigger:O,messages_before:S.messagesBefore,tokens_before:S.tokensBefore},Q=this.getMatchingHooks("Compaction",{});if(Q.length===0)return{blockCompaction:!1};let Y={projectDir:S.projectDir,sessionId:S.sessionId,permissionMode:S.permissionMode,config:this.config,abortSignal:S.abortSignal};try{return await this.executor.executeCompactionHooks(Q,q,Y)}catch(Z){return console.error("[HookManager] Error executing Compaction hooks:",Z),{blockCompaction:!1,warning:`Hook execution failed: ${Z instanceof Error?Z.message:String(Z)}`}}}getMatchingHooks(O,S){let q=this.config[O]||[],Q=[];for(let Y of q)if(this.matcher.matches(Y.matcher,S))Q.push(...Y.hooks);return Q}extractFilePath(O){let S=["file_path","path","filePath","source","target"];for(let q of S){let Q=O[q];if(typeof Q==="string")return Q}return}extractCommand(O,S){if(O==="Bash"||O==="BashTool"){let q=S.command;if(typeof q==="string")return q}return}cleanup(){this.guard.cleanupAll()}}
41
+ export{g as tb,l as ub,P as vb};
@@ -0,0 +1,2 @@
1
+ var e={name:"blade-code",version:"0.8.0",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",typebox:"1.3.7",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
2
+ export{r as Ja,n as Ka,o as La,c as Ma,d as Na,a as Oa};
@@ -1 +1 @@
1
- function f(x){return x!==void 0&&typeof x.pattern==="string"&&typeof x.search_path==="string"}function b(x){return x!==void 0&&x.kind==="edit"&&typeof x.matches_found==="number"}function h(x){return x==="readonly"}var v="__aborted__";export{f as nb,b as ob,h as pb,v as qb};
1
+ function f(x){return x!==void 0&&typeof x.pattern==="string"&&typeof x.search_path==="string"}function b(x){return x!==void 0&&x.kind==="edit"&&typeof x.matches_found==="number"}function h(x){return x==="readonly"}var v="__aborted__";export{f as pb,b as qb,h as rb,v as sb};
@@ -0,0 +1 @@
1
+ import{Ha as a,Ia as b}from"./chunk-d4ex0qvs.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";export{a as resolveModelConfig,b as getModelDisplayName};
@@ -0,0 +1 @@
1
+ import{Ja as a,Ka as b,La as c,Ma as d,Na as e,Oa as f}from"./chunk-6es6av6j.js";import"./chunk-dr06x0cw.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1,4 +1,4 @@
1
- import{Ab as _,vb as L}from"./chunk-v61bja34.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
1
+ import{Db as L,Ib as _}from"./chunk-gsfkrr25.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
2
2
  You have been invoked in the following environment:
3
3
  - Primary working directory: ${B.workingDirectory}
4
4
  - Is a git repository: ${$?"true":"false"}
@@ -0,0 +1,9 @@
1
+ import{B,I as j,K as T,P as h,Q as q,S as N,X as A,Z as b,_ as x}from"./chunk-jakzknh3.js";import"./chunk-9ad7tt9s.js";import{ca as u}from"./chunk-e4a240t7.js";import"./chunk-bm8vwfez.js";import{va as I}from"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import{Ia as C}from"./chunk-d4ex0qvs.js";import"./chunk-6es6av6j.js";import{ab as K}from"./chunk-1pt090dg.js";import{sb as E}from"./chunk-9xkjb87h.js";import"./chunk-49g067ek.js";import"./chunk-ctqf59q1.js";import{Cb as S}from"./chunk-jt62ctz7.js";import{Ib as M}from"./chunk-gsfkrr25.js";import"./chunk-0dj326ms.js";import{Tb as L}from"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";import{Readable as p,Writable as m}from"node:stream";import*as P from"@agentclientprotocol/sdk";import k from"node:path";import{PROTOCOL_VERSION as d}from"@agentclientprotocol/sdk";import{nanoid as O}from"nanoid";var V=L("Agent");function f(z){return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function c(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:f(z.env)};return{type:z.type,url:z.url,headers:f(z.headers)}}function g(z){return Object.fromEntries(z.map((H)=>[H.name,c(H)]))}function y(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let J=H.image_url.url,Q=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Q)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Q[1]??"image/png",data:Q[2]??""}]})}class _{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingResumeRequested=!1;availableCommandsTimer=null;destroyed=!1;messages;mode="default";constructor(z,H,J,Q,X={}){this.id=z;this.cwd=H;this.connection=J;this.clientCapabilities=Q;this.options=X;this.messages=[...X.initialMessages??[]]}async initialize(){V.debug(`[AcpSession ${this.id}] Initializing...`),B.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),V.debug(`[AcpSession ${this.id}] ACP service context initialized`);let z=this.options.mcpServers?g(this.options.mcpServers):void 0;this.runtime=await T.create({sessionId:this.id,workspaceRoot:this.cwd,...z?{mcpServers:z}:{}}),this.agent=await N.createWithRuntime(this.runtime,{sessionId:this.id}),V.debug(`[AcpSession ${this.id}] Agent created successfully`);let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let z of this.messages){if(!this.canSendUpdates())return;let H=z.role==="user"?"user_message_chunk":z.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let J of y(z.content)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:J}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);V.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,H){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let $=await this.runtime.rewindSession(Z);return this.messages=[...$.messages],await this.agent?.destroy(),this.agent=await N.createWithRuntime(this.runtime,{sessionId:this.id}),$}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let U=!1,W,G=(F)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.id,status:F.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:F.result?.message||F.result?.error||`Subagent ${F.status}`}}]})},w=this.runtime.resumeSubagent({agentId:Z,prompt:$,onCompleted:(F)=>{if(U)G(F);else W=F}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.session.id,status:"in_progress",title:`Resuming ${w.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${w.source.id} at depth ${w.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),U=!0,W)G(W);return w}},signal:H,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,$,U)=>{let W=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,G=this.mapToolKind(U);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify($,null,2)}}],kind:G})},sendToolResult:(Z,$)=>{if($.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.summary}})}}},Q=await b(z,J),X=Q.data?.action;if(X==="start_goal"||X==="resume_goal")this.schedulePendingResume();if(X==="rewind_session"&&Array.isArray(Q.data?.messages))this.messages=[...Q.data.messages];if((Q.message==="compact_completed"||Q.message==="compact_fallback")&&Q.data?.compactedMessages)this.messages=[...Q.data.compactedMessages];let Y=Q.content||Q.message;if(Y)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(J){return V.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=x(),H=["model","permissions","theme","config","exit","ide"],Q=z.filter((X)=>!H.includes(X.name)).map((X)=>{let Y;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Y=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;Y=Y?`${Y} | ${Z}`:Z}return{name:X.name,description:X.description,input:Y?{hint:Y}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),V.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(B.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt);if(this.pendingPrompt){if(/^\/goal(?:\s|$)/i.test(J.trim()))return this.handleSlashCommand(J,this.pendingPrompt.signal);let X=await this.runtime.enqueueSteering(J,{allowBeforeTurn:!0});if(!X.accepted)throw Error(X.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(V.debug(`[AcpSession ${this.id}] Queued steering for active turn (${X.queued})`),X.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let Q=new AbortController;this.pendingPrompt=Q;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${J.slice(0,100)}...`),A(J))return await this.handleSlashCommand(J,Q.signal);let X={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:Q.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(Y)=>{return this.requestPermission(Y)}}};if(await K(this.agent.chatStream(J,X,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly}),async(Y)=>{switch(Y.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Y.delta}});break;case"tool_start":{let Z=Y.toolCall,$="function"in Z?Z.function.name:Z.type,U=this.mapToolKind(Y.toolKind),W=`Executing ${$}`;if($==="Task"&&"function"in Z)try{let G=JSON.parse(Z.function.arguments),w=G.resume_from??G.resume;if(typeof w==="string")W=`Resuming ${String(G.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.id,status:"in_progress",title:W,content:[],kind:U});break}case"tool_result":{let{toolCall:Z,result:$}=Y,U=[],W=$.metadata;if(W?.kind==="edit"&&typeof W.file_path==="string"&&typeof W.oldContent==="string"&&(typeof W.newContent==="string"||W.newContent===void 0))U.push({type:"diff",path:W.file_path,oldText:W.oldContent,newText:W.newContent??null});else{let w="function"in Z?Z.function.name:Z.type,F=q(h(w,$));U.push({type:"content",content:{type:"text",text:F}})}let G=$.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.id,status:G,content:U});break}case"task_update":this.sendPlanUpdate(Y.tasks);break;case"steering_applied":break;case"follow_up_started":for(let Z of Y.messages){if(!Z.recovered||Z.persisted)continue;for(let $ of y(Z.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:$})}if(Y.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${Y.recovered} queued instruction${Y.recovered===1?"":"s"} recovered after restart]
2
+ `}});break;case"goal_updated":if(Y.goal&&Y.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Y.goal.status}: ${Y.goal.objective}]
3
+ `}});break;case"goal_continuation_started":break;default:break}}),this.messages=[...X.messages],Q.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(X){if(Q.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw V.error(`[AcpSession ${this.id}] Prompt error:`,X),X}finally{if(this.pendingPrompt===Q){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||!this.runtime||!this.agent)return;let z=this.runtime.getPendingSteeringCount()>0,J=(z?null:await this.runtime.getGoal())?.status==="active";if(!z&&!J){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:J}).catch((Q)=>{V.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Q)})}cancel(){if(V.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1,this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,V.info(`[AcpSession ${this.id}] Cancelled successfully`);else V.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"];this.mode=H.includes(z)?z:"default",V.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(V.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");await this.agent.switchModel(z)}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;let z=this.agent,H=this.runtime;this.agent=null,this.runtime=null;let J,Q=async(X)=>{try{await X()}catch(Y){J??=Y}};if(await Q(()=>this.cancel()),z)await Q(()=>z.destroy());if(H)await Q(()=>H.dispose());if(await Q(()=>B.destroySession(this.id)),V.debug(`[AcpSession ${this.id}] Destroyed`),J!==void 0)throw J}resolvePrompt(z){let H=[];for(let J of z)if(J.type==="text")H.push(J.text);else if(J.type==="image")H.push(`[Image: ${J.mimeType}]`);else if(J.type==="resource"){let Q=J.resource;if("text"in Q)H.push(`<file path="${Q.uri}">
4
+ ${Q.text}
5
+ </file>`)}else if(J.type==="resource_link")H.push(`[Resource: ${J.uri}]`);return H.join(`
6
+ `)}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:z}),this.canSendUpdates()}sendUpdate(z){if(!this.canSendUpdates())return;let H={sessionId:this.id,update:z};this.connection.sessionUpdate(H).catch((J)=>{V.warn(`[AcpSession ${this.id}] Failed to send update:`,J)})}sendPlanUpdate(z){let H=z.map((J)=>({content:J.subject,priority:J.priority,status:J.status}));V.debug(`[AcpSession ${this.id}] Sending plan update with ${H.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:H})}async requestPermission(z){let H=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,H);let J=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(J))return V.debug(`[AcpSession ${this.id}] Auto-approving ${J} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(J==="write"||J==="execute"))return V.debug(`[AcpSession ${this.id}] Rejecting ${J} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Q=O(),X=[];if(z.message)X.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)X.push({type:"content",content:{type:"text",text:`Risks:
7
+ - ${z.risks.join(`
8
+ - `)}`}});let Y=this.mapToolKind(J),Z={sessionId:this.id,options:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Q,status:"pending",title:z.title||"Permission Required",content:X,kind:Y}},$=await this.waitForClientInteraction(this.connection.requestPermission(Z),H);if(!$)return{approved:!1,reason:E};let U=$.outcome;if(U.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let W=U.optionId;if(W==="allow_always")return{approved:!0,scope:"project"};if(W==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let G=W==="allow_once";return{approved:G,scope:"once",reason:G?void 0:"User denied the operation"}}catch(Q){return V.warn(`[AcpSession ${this.id}] Permission request failed:`,Q),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,H){let J=z.questions??[];if(J.length===0)return{approved:!1,reason:"No structured questions were provided"};if(J.some((X)=>X.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Q={};try{for(let[X,Y]of J.entries()){let Z=Y.options.map((G,w)=>`answer:${X}:${w}`),$=`answer:${X}:cancel`,U=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Y.options.map((G,w)=>({optionId:Z[w],name:G.label,kind:"allow_once"})),{optionId:$,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:O(),status:"pending",title:Y.header,kind:"think",content:[{type:"content",content:{type:"text",text:[Y.question,...Y.options.map((G)=>`${G.label}: ${G.description}`)].join(`
9
+ `)}}]}}),H);if(!U)return{approved:!1,reason:E};if(U.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let W=Z.indexOf(U.outcome.optionId);if(W<0)return{approved:!1,reason:"User cancelled the question prompt"};Q[Y.header]=Y.options[W].label}return{approved:!0,answers:Q}}catch(X){return V.warn(`[AcpSession ${this.id}] Question request failed:`,X),{approved:!1,reason:"Question request failed"}}}async waitForClientInteraction(z,H){if(!H)return z;if(H.aborted)return;return new Promise((J,Q)=>{let X=!1,Y=($)=>{if(X)return;X=!0,H.removeEventListener("abort",Z),$()},Z=()=>Y(()=>J(void 0));if(H.addEventListener("abort",Z,{once:!0}),H.aborted)Z();z.then(($)=>Y(()=>J($)),($)=>Y(()=>Q($)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var D=L("Agent");class R{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(z){this.connection=z}async initialize(z){return D.info("[BladeAgent] Initializing ACP connection"),D.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,{protocolVersion:d,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let H=S("acp");D.info(`[BladeAgent] Creating new session: ${H}`),D.debug(`[BladeAgent] Session cwd: ${z.cwd||M()}`);let J=new _(H,z.cwd||M(),this.connection,this.clientCapabilities,{mcpServers:z.mcpServers});try{await J.initialize(),this.assertNotDestroyed()}catch(Q){throw await J.destroy().catch(()=>{return}),Q}return this.sessions.set(H,J),D.info(`[BladeAgent] Session ${H} created, scheduling available commands update`),J.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H)}async unstable_listSessions(z){if(z.cwd!=null&&!k.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let H=await j.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:H.sessions.map((J)=>({sessionId:J.sessionId,cwd:J.projectPath,title:J.title??null,updatedAt:J.lastMessageTime})),nextCursor:H.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!k.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let H=await j.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd});this.assertNotDestroyed();let J=new _(H.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:H.messages,mcpServers:z.mcpServers});try{await J.initialize(),this.assertNotDestroyed()}catch(Q){throw await J.destroy().catch(()=>{return}),Q}return this.sessions.set(H.sessionId,J),J.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H.sessionId)}async loadSession(z){this.assertNotDestroyed(),D.info(`[BladeAgent] Loading session: ${z.sessionId}`);let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Q=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Q);try{return await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Q)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed();let H=this.sessions.get(z.sessionId);if(H)try{await H.destroy()}finally{if(this.sessions.get(z.sessionId)===H)this.sessions.delete(z.sessionId)}let J=await j.loadSession(z.sessionId,z.cwd),Q=new _(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:J,mcpServers:z.mcpServers});try{await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed()}catch(X){throw await Q.destroy().catch(()=>{return}),X}return this.sessions.set(z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup()}buildChildSessionResponse(z){return{sessionId:z,...this.buildSessionSetup()}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(){let z=I(),H=z?.models||[],J=z?.currentModelId||H[0]?.id,Q=H.map((Y)=>({modelId:Y.id,name:C(Y),description:`${Y.provider}/${Y.model}`}));return{modes:{availableModes:[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],currentModeId:"default"},models:Q.length>0?{availableModels:Q,currentModelId:J}:void 0}}async prompt(z){let H=this.sessions.get(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);return H.prompt(z)}async cancel(z){D.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let H=this.sessions.get(z.sessionId);if(H)D.info("[BladeAgent] Found session, calling session.cancel()"),H.cancel();else D.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){D.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let H=this.sessions.get(z.sessionId);if(H)await H.setMode(z.modeId);return{}}async unstable_setSessionModel(z){D.info(`[BladeAgent] Setting session model: ${z.modelId}`);let H=this.sessions.get(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);return await H.setModel(z.modelId),{}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let H of this.sessions.values())try{await H.destroy()}catch(J){z??=J}this.sessions.clear();try{await u.getInstance().disconnectAll()}catch(H){z??=H}if(z!==void 0)throw z}}async function Bz(){let z=m.toWeb(process.stdout),H=p.toWeb(process.stdin),J=P.ndJsonStream(z,H);await new P.AgentSideConnection((X)=>new R(X),J).closed}export{Bz as runAcpIntegration};
@@ -0,0 +1,2 @@
1
+ import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
2
+ export{a as wb,f as xb,l as yb,x as zb,b as Ab,V as Bb};
@@ -0,0 +1 @@
1
+ import{a as y,b as A,c as C,d as D}from"./chunk-3gw66r7a.js";import"./chunk-xhnyy54e.js";import"./chunk-jakzknh3.js";import"./chunk-9ad7tt9s.js";import"./chunk-e4a240t7.js";import"./chunk-bm8vwfez.js";import{wa as q}from"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import"./chunk-d4ex0qvs.js";import"./chunk-6es6av6j.js";import"./chunk-1pt090dg.js";import"./chunk-9xkjb87h.js";import"./chunk-49g067ek.js";import"./chunk-ctqf59q1.js";import"./chunk-jt62ctz7.js";import"./chunk-gsfkrr25.js";import"./chunk-0dj326ms.js";import"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.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};
@@ -0,0 +1,2 @@
1
+ import{dc as r}from"./chunk-hjx5n3dw.js";function s(e,a,i){let t=r().resolveConfig(e),o=e.overrides;return{config:e,model:t,displayName:e.displayName??t.name,chat:{provider:e.provider,model:e.model,apiKey:process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??o?.baseUrl,temperature:o?.temperature??a.temperature,maxContextTokens:t.contextWindow,maxOutputTokens:o?.maxOutputTokens,timeout:o?.timeout??a.timeout,reasoningEnabled:t.reasoning&&i,fallbackModels:e.fallbackModels,enablePromptCaching:o?.enablePromptCaching,customHeaders:o?.customHeaders,apiVersion:o?.apiVersion,maxRetries:o?.maxRetries}}}function n(e){try{return e.displayName??r().getModel(e.provider,e.model).name}catch{return e.displayName??e.model}}
2
+ export{s as Ha,n as Ia};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as a}from"node:module";var c=a(import.meta.url);
2
- export{c as _b};
2
+ export{c as ec};
@@ -0,0 +1,34 @@
1
+ import{Ka as I,La as C}from"./chunk-6es6av6j.js";import{rb as R}from"./chunk-9xkjb87h.js";import{wb as E,yb as U}from"./chunk-ctqf59q1.js";import{ec as f}from"./chunk-dr06x0cw.js";import{EventEmitter as t}from"events";function p($){if($===void 0)return"undefined";if(typeof $==="string")return $;try{let L=JSON.stringify($);return L===void 0?String($):L}catch{return String($)}}function g($){let L=$;switch($.code){case"type":return`类型错误:${$.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${$.message}`;case"maxLength":return`字符串过长:${$.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${$.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${$.message}`;case"minItems":return`数组元素过少:${$.message}`;case"maxItems":return`数组元素过多:${$.message}`;case"format":return`格式错误:${$.message}`;case"enum":return`必须是枚举允许的值之一:${$.message}`;case"const":return`必须是指定的字面量值:${$.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${$.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return $.message||"自定义验证失败";default:return $.message||`验证失败:${p(L)}`}}class D extends Error{issues;type;constructor($,L,G="validation_error"){super($);this.issues=L;this.type=G;this.name="ToolValidationError"}}function N($,L){let G=E($,L);if(G.success)return G.data;let Q=G.error.issues.map((X)=>({field:X.path.length>0?X.path.join("."):"root",message:g(X),value:X.value})),W=Q.length===1?`参数验证失败 [${Q[0].field}]: ${Q[0].message}`:`参数验证失败 (${Q.length} 个错误):
2
+ ${Q.map((X)=>` - ${X.field}: ${X.message}`).join(`
3
+ `)}`;throw new D(W,Q)}function K($){if(!$||typeof $!=="object")return;let L=$;if(L.type==="object"&&L.properties)L.required??=[],L.additionalProperties??=!1;for(let G of Object.values(L))if(Array.isArray(G))for(let Q of G)K(Q);else K(G)}function x($){let L=JSON.parse(JSON.stringify($,(G,Q)=>G.startsWith("~")?void 0:Q));return K(L),L}class O{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor($,L,G,Q,W){this.toolName=$;this.params=L;this.executeFn=G;this.descriptionFn=Q;this.affectedPathsFn=W}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute($,L,G){let Q={signal:$,updateOutput:L,...G};return this.executeFn(this.params,Q)}}function h($){return{name:$.name,displayName:$.displayName,kind:$.kind,isReadOnly:$.isReadOnly??R($.kind),isConcurrencySafe:$.isConcurrencySafe??!1,strict:$.strict??!1,description:$.description,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],getFunctionDeclaration(){let L=x($.schema),G=$.description.short;if($.description.long)G+=`
4
+
5
+ ${$.description.long}`;if($.description.usageNotes&&$.description.usageNotes.length>0)G+=`
6
+
7
+ Usage Notes:
8
+ ${$.description.usageNotes.map((Q)=>`- ${Q}`).join(`
9
+ `)}`;if($.description.important&&$.description.important.length>0)G+=`
10
+
11
+ Important:
12
+ ${$.description.important.map((Q)=>`[WARN] ${Q}`).join(`
13
+ `)}`;return{name:$.name,description:G,parameters:L}},getMetadata(){return{name:$.name,displayName:$.displayName,kind:$.kind,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],description:$.description,schema:x($.schema)}},build(L){let G=N($.schema,L);return new O($.name,G,$.execute)},async execute(L,G,Q){return this.build(L).execute(G||new AbortController().signal,void 0,Q)},extractSignatureContent:$.extractSignatureContent?(L)=>$.extractSignatureContent(L):void 0,abstractPermissionRule:$.abstractPermissionRule?(L)=>$.abstractPermissionRule(L):void 0}}function z($,L,G,Q){let W=G.inputSchema&&typeof G.inputSchema==="object"?U.Unsafe(G.inputSchema):U.Any(),X=Q||G.name;return h({name:X,displayName:`${L}: ${G.name}`,kind:"execute",schema:W,description:{short:G.description||`MCP Tool: ${G.name}`,important:[`From MCP server: ${L}`,"Executes external tools; user confirmation required"]},category:"MCP tool",tags:["mcp","external",L],async execute(Y,q){try{let Z=await $.callTool(G.name,Y),A="";if(Z.content&&Array.isArray(Z.content)){for(let B of Z.content)if(B.type==="text"&&B.text)A+=B.text;else if(B.type==="image")A+=`[image: ${B.mimeType||"unknown"}]
14
+ `;else if(B.type==="resource")A+=`[resource: ${B.mimeType||"unknown"}]
15
+ `}if(Z.isError)return{success:!1,llmContent:A||"MCP tool execution failed",error:{type:"execution_error",message:A||"MCP tool execution failed"},metadata:{summary:`MCP ${G.name} 执行失败`,serverName:L,toolName:G.name}};return{success:!0,llmContent:A||"Execution succeeded",metadata:{summary:`MCP ${G.name} 执行成功`,serverName:L,toolName:G.name,mcpResult:Z}}}catch(Z){return{success:!1,llmContent:`MCP tool execution failed: ${Z.message}`,error:{type:"execution_error",message:Z.message},metadata:{summary:`MCP ${G.name} 执行失败`,serverName:L,toolName:G.name}}}}})}import{Client as i}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as a}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as c}from"@modelcontextprotocol/sdk/client/stdio.js";import{EventEmitter as s}from"events";import{spawn as m}from"child_process";import*as b from"crypto";import*as S from"http";import{URL as k}from"url";import{promises as w}from"fs";import v from"os";import _ from"path";class H{tokenFilePath;constructor(){let $=v.homedir(),L=_.join($,".blade");this.tokenFilePath=_.join(L,"mcp-oauth-tokens.json")}async ensureConfigDir(){let $=_.dirname(this.tokenFilePath);try{await w.mkdir($,{recursive:!0,mode:493})}catch{}}async loadAllCredentials(){let $=new Map;try{let L=await w.readFile(this.tokenFilePath,"utf-8"),G=JSON.parse(L);for(let Q of G)$.set(Q.serverName,Q)}catch(L){if(L.code!=="ENOENT")console.warn("[OAuthTokenStorage] 加载令牌失败:",L)}return $}async saveAllCredentials($){await this.ensureConfigDir();let L=Array.from($.values());await w.writeFile(this.tokenFilePath,JSON.stringify(L,null,2),{mode:384})}async saveToken($,L,G,Q){let W=await this.loadAllCredentials(),X={serverName:$,token:L,clientId:G,tokenUrl:Q,updatedAt:Date.now()};W.set($,X),await this.saveAllCredentials(W)}async getCredentials($){return(await this.loadAllCredentials()).get($)||null}async deleteCredentials($){let L=await this.loadAllCredentials();L.delete($),await this.saveAllCredentials(L)}async listServers(){let $=await this.loadAllCredentials();return Array.from($.keys())}isTokenExpired($){if(!$.expiresAt)return!1;let L=300000;return Date.now()>=$.expiresAt-L}}var V=7777,j="/oauth/callback",M=200;class F{tokenStorage;constructor($=new H){this.tokenStorage=$}generatePKCEParams(){let $=b.randomBytes(32).toString("base64url"),L=b.createHash("sha256").update($).digest("base64url"),G=b.randomBytes(16).toString("base64url");return{codeVerifier:$,codeChallenge:L,state:G}}buildAuthorizationUrl($,L){let G=$.redirectUri||`http://localhost:${V}${j}`,Q=new URLSearchParams({client_id:$.clientId,response_type:"code",redirect_uri:G,state:L.state,code_challenge:L.codeChallenge,code_challenge_method:"S256"});if($.scopes&&$.scopes.length>0)Q.append("scope",$.scopes.join(" "));let W=new k($.authorizationUrl);return Q.forEach((X,Y)=>{W.searchParams.append(Y,X)}),W.toString()}async startCallbackServer($){return new Promise((L,G)=>{let Q=S.createServer((W,X)=>{try{let Y=new k(W.url,`http://localhost:${V}`);if(Y.pathname!==j){X.writeHead(404),X.end("Not found");return}let q=Y.searchParams.get("code"),Z=Y.searchParams.get("state"),A=Y.searchParams.get("error");if(A){X.writeHead(M,{"Content-Type":"text/html"}),X.end(`
16
+ <html>
17
+ <body>
18
+ <h1>Authentication Failed</h1>
19
+ <p>Error: ${A}</p>
20
+ <p>You can close this window.</p>
21
+ </body>
22
+ </html>
23
+ `),Q.close(),G(Error(`OAuth error: ${A}`));return}if(!q||!Z){X.writeHead(400),X.end("Missing code or state parameter");return}if(Z!==$){X.writeHead(400),X.end("Invalid state parameter"),Q.close(),G(Error("State mismatch - possible CSRF attack"));return}X.writeHead(M,{"Content-Type":"text/html"}),X.end(`
24
+ <html>
25
+ <body>
26
+ <h1>Authentication Successful!</h1>
27
+ <p>You can close this window and return to Blade.</p>
28
+ <script>window.close();</script>
29
+ </body>
30
+ </html>
31
+ `),Q.close(),L(q)}catch(Y){Q.close(),G(Y)}});Q.on("error",G),Q.listen(V,()=>{console.log(`[OAuth] Callback server listening on port ${V}`)}),setTimeout(()=>{Q.close(),G(Error("OAuth callback timeout"))},300000)})}async exchangeCodeForToken($,L,G){let Q=$.redirectUri||`http://localhost:${V}${j}`,W=new URLSearchParams({grant_type:"authorization_code",code:L,redirect_uri:Q,code_verifier:G,client_id:$.clientId});if($.clientSecret)W.append("client_secret",$.clientSecret);let X=await fetch($.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:W.toString()});if(!X.ok){let Y=await X.text();throw Error(`Token exchange failed: ${X.status} - ${Y}`)}return await X.json()}async refreshAccessToken($,L){let G=new URLSearchParams({grant_type:"refresh_token",refresh_token:L,client_id:$.clientId});if($.clientSecret)G.append("client_secret",$.clientSecret);if($.scopes&&$.scopes.length>0)G.append("scope",$.scopes.join(" "));let Q=await fetch($.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:G.toString()});if(!Q.ok){let W=await Q.text();throw Error(`Token refresh failed: ${Q.status} - ${W}`)}return await Q.json()}async authenticate($,L){if(!L.clientId||!L.authorizationUrl||!L.tokenUrl)throw Error("Missing required OAuth configuration");let G=this.generatePKCEParams(),Q=this.buildAuthorizationUrl(L,G);console.log(`
32
+ [OAuth] Opening browser for authentication...`),console.log(`
33
+ If the browser does not open automatically, copy and paste this URL:`),console.log(Q),console.log("");let W=this.startCallbackServer(G.state);try{await this.openAuthorizationUrl(Q)}catch(Z){console.warn("[OAuth] Failed to open browser automatically:",Z)}let X=await W;console.log("[OAuth] Authorization code received, exchanging for tokens...");let Y=await this.exchangeCodeForToken(L,X,G.codeVerifier),q={accessToken:Y.access_token,tokenType:Y.token_type||"Bearer",refreshToken:Y.refresh_token,scope:Y.scope};if(Y.expires_in)q.expiresAt=Date.now()+Y.expires_in*1000;return await this.tokenStorage.saveToken($,q,L.clientId,L.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),q}async openAuthorizationUrl($){let{command:L,args:G}=this.getBrowserCommand($);await new Promise((Q,W)=>{let X=m(L,G,{stdio:"ignore"});X.once("error",W),X.once("close",(Y)=>{if(Y===0||Y===null)Q();else W(Error(`Failed to open browser (exit code ${Y})`))})})}getBrowserCommand($){if(process.platform==="darwin")return{command:"open",args:[$]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",$]};return{command:"xdg-open",args:[$]}}async getValidToken($,L){let G=await this.tokenStorage.getCredentials($);if(!G)return null;let{token:Q}=G;if(!this.tokenStorage.isTokenExpired(Q))return Q.accessToken;if(Q.refreshToken&&L.clientId&&G.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${$}`);let W=await this.refreshAccessToken(L,Q.refreshToken),X={accessToken:W.access_token,tokenType:W.token_type,refreshToken:W.refresh_token||Q.refreshToken,scope:W.scope||Q.scope};if(W.expires_in)X.expiresAt=Date.now()+W.expires_in*1000;return await this.tokenStorage.saveToken($,X,L.clientId,G.tokenUrl),X.accessToken}catch(W){console.error("[OAuth] Failed to refresh token:",W),await this.tokenStorage.deleteCredentials($)}return null}}import{EventEmitter as l}from"events";class P extends l{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor($,L={}){super();this.client=$,this.config={interval:L.interval??30000,timeout:L.timeout??1e4,enabled:L.enabled??!1,failureThreshold:L.failureThreshold??3}}start(){if(this.checkTimer){console.warn("[HealthMonitor] 健康监控已在运行");return}if(!this.config.enabled){console.log("[HealthMonitor] 健康监控未启用");return}console.log(`[HealthMonitor] 启动健康监控(间隔: ${this.config.interval}ms)`),this.scheduleNextCheck()}stop(){if(this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null,console.log("[HealthMonitor] 停止健康监控")}scheduleNextCheck(){this.checkTimer=setTimeout(async()=>{await this.performHealthCheck(),this.scheduleNextCheck()},this.config.interval)}async performHealthCheck(){if(this.isChecking)return console.warn("[HealthMonitor] 上一次检查仍在进行中"),this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let $=this.client.connectionStatus;if($==="connected"){await this.pingServer(),this.consecutiveFailures=0,this.setStatus("healthy");let L={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",L),L}else throw Error(`连接状态异常: ${$}`)}catch($){this.consecutiveFailures++;let L=$;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,L.message);let G;if(this.consecutiveFailures>=this.config.failureThreshold)G="unhealthy",this.emit("unhealthy",this.consecutiveFailures,L),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((W)=>{console.error("[HealthMonitor] 重连失败:",W)});else G="degraded";this.setStatus(G);let Q={status:G,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:L};return this.emit("healthCheck",Q),Q}finally{this.isChecking=!1}}async pingServer(){let $=new Promise((G,Q)=>{setTimeout(()=>Q(Error("Health check timeout")),this.config.timeout)}),L=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([L,$])}async triggerReconnection(){try{await this.client.disconnect(),await new Promise(($)=>setTimeout($,1000)),await this.client.connect(),console.log("[HealthMonitor] 重连成功"),this.consecutiveFailures=0,this.setStatus("healthy"),this.emit("reconnected")}catch($){throw console.error("[HealthMonitor] 重连失败:",$),$}}setStatus($){if(this.currentStatus!==$){let L=this.currentStatus;this.currentStatus=$,this.emit("statusChanged",$,L)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}function T($){if(!($ instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String($))};let L=$.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((W)=>L.includes(W)))return{type:"config_error",isRetryable:!1,originalError:$};if(L.includes("unauthorized")||L.includes("401")||L.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:$};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((W)=>L.includes(W)))return{type:"network_temporary",isRetryable:!0,originalError:$};return{type:"unknown",isRetryable:!0,originalError:$}}class y extends s{config;status="disconnected";sdkClient=null;tools=new Map;serverInfo=null;reconnectAttempts=0;MAX_RECONNECT_ATTEMPTS=5;reconnectTimer=null;isManualDisconnect=!1;oauthProvider=null;serverName;healthMonitor=null;constructor($,L,G){super();this.config=$;if(this.serverName=L||"default",$.oauth?.enabled)this.oauthProvider=new F;if(G?.enabled)this.healthMonitor=new P(this,G),this.healthMonitor.on("unhealthy",(Q,W)=>{this.emit("unhealthy",Q,W)}),this.healthMonitor.on("reconnected",()=>{this.emit("healthMonitorReconnected")})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get server(){return this.serverInfo}get healthCheck(){return this.healthMonitor}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry($=3,L=1000){if(this.status!=="disconnected"&&this.status!=="error")throw Error("客户端已连接或正在连接中");if(this.status==="error"){if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected")}let G=null;for(let Q=1;Q<=$;Q++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(W){G=W;let X=T(W);if(!X.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",X.type),W;if(Q<$){let Y=L*Math.pow(2,Q-1);console.warn(`[McpClient] 连接失败(${Q}/${$}),${Y}ms 后重试...`),await new Promise((q)=>setTimeout(q,Y))}}throw G||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new i({name:C(),version:I()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let $=await this.createTransport();await this.sdkClient.connect($);let L=this.sdkClient.getServerVersion();if(this.serverInfo={name:L?.name||"Unknown",version:L?.version||"0.0.0"},await this.loadTools(),this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor)this.healthMonitor.start()}catch($){throw this.setStatus("error"),this.emit("error",$),$}}handleUnexpectedClose(){if(this.isManualDisconnect)return;if(this.status==="connected")console.warn("[McpClient] 检测到意外断连,准备重连..."),this.setStatus("error"),this.emit("error",Error("MCP服务器连接意外关闭")),this.scheduleReconnect()}scheduleReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.reconnectAttempts>=this.MAX_RECONNECT_ATTEMPTS){console.error("[McpClient] 达到最大重连次数,放弃重连"),this.emit("reconnectFailed");return}let $=Math.min(1000*Math.pow(2,this.reconnectAttempts),30000);this.reconnectAttempts++,console.log(`[McpClient] 将在 ${$}ms 后进行第 ${this.reconnectAttempts} 次重连...`),this.reconnectTimer=setTimeout(async()=>{try{if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected"),await this.doConnect(),console.log("[McpClient] 重连成功"),this.reconnectAttempts=0,this.emit("reconnected")}catch(L){if(console.error("[McpClient] 重连失败:",L),T(L).isRetryable)this.scheduleReconnect();else console.error("[McpClient] 检测到永久性错误,停止重连"),this.emit("reconnectFailed")}},$)}async disconnect(){if(this.isManualDisconnect=!0,this.healthMonitor)this.healthMonitor.stop();if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.sdkClient){try{await this.sdkClient.close()}catch($){console.warn("[McpClient] 断开连接时出错:",$)}this.sdkClient=null}this.tools.clear(),this.serverInfo=null,this.reconnectAttempts=0,this.setStatus("disconnected"),this.emit("disconnected"),this.isManualDisconnect=!1}async callTool($,L={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has($))throw Error(`工具 "${$}" 不存在`);try{return await this.sdkClient.callTool({name:$,arguments:L})}catch(G){throw console.error(`[McpClient] 调用工具 "${$}" 失败:`,G),G}}async createTransport(){let{type:$,command:L,args:G,env:Q,url:W,headers:X,oauth:Y}=this.config,q={...X};if(Y?.enabled&&this.oauthProvider&&($==="sse"||$==="http"))try{let Z=await this.oauthProvider.getValidToken(this.serverName,Y);if(!Z){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let A=await this.oauthProvider.authenticate(this.serverName,Y);q.Authorization=`Bearer ${A.accessToken}`}else q.Authorization=`Bearer ${Z}`}catch(Z){throw console.error("[McpClient] OAuth 认证失败:",Z),Error(`OAuth 认证失败: ${Z instanceof Error?Z.message:String(Z)}`)}if($==="stdio"){if(!L)throw Error("stdio 传输需要 command 参数");let Z={};for(let[A,B]of Object.entries(process.env))if(B!==void 0)Z[A]=B;return new c({command:L,args:G||[],env:{...Z,...Q},stderr:"ignore"})}else if($==="sse"){if(!W)throw Error("sse 传输需要 url 参数");return new a(new URL(W),{requestInit:{headers:q}})}else if($==="http"){if(!W)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:Z}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new Z(new URL(W),{requestInit:{headers:q}})}throw Error(`不支持的传输类型: ${$}`)}async loadTools(){if(!this.sdkClient)return;try{let $=await this.sdkClient.listTools();if(this.tools.clear(),$.tools)for(let L of $.tools)this.tools.set(L.name,L);this.emit("toolsUpdated",this.availableTools)}catch($){throw console.error("[McpClient] 加载工具失败:",$),$}}setStatus($){let L=this.status;this.status=$,this.emit("statusChanged",$,L)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer($){return this.connect()}async disconnectFromServer($){return this.disconnect()}async listResources($){if(!this.sdkClient)return[];try{return(await this.sdkClient.listResources()).resources||[]}catch{return[]}}async listTools($){return this.availableTools}async readResource($,L){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:$})).contents?.[0]||{uri:$,text:""}}}class J extends t{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!J.instance)J.instance=new J;return J.instance}static createIsolated(){return new J}async registerServer($,L){if(this.servers.has($))throw Error(`MCP服务器 "${$}" 已经注册`);let G=new y(L,$,L.healthCheck),Q={config:L,client:G,status:"disconnected",tools:[]};this.setupClientEventHandlers(G,Q,$),this.servers.set($,Q),this.emit("serverRegistered",$,Q);try{await this.connectServer($)}catch(W){console.warn(`MCP服务器 "${$}" 连接失败:`,W)}}async unregisterServer($){let L=this.servers.get($);if(!L)return;try{await L.client.disconnect()}catch(G){console.warn(`断开MCP服务器 "${$}" 时出错:`,G)}this.servers.delete($),this.emit("serverUnregistered",$)}async connectServer($){let L=this.servers.get($);if(!L)throw Error(`MCP服务器 "${$}" 未注册`);if(L.status==="connected")return;try{L.status="connecting",await L.client.connect(),L.connectedAt=new Date,L.lastError=void 0,L.tools=L.client.availableTools}catch(G){throw L.lastError=G,L.status="error",G}}async disconnectServer($){let L=this.servers.get($);if(!L)return;await L.client.disconnect(),L.connectedAt=void 0}async reconnectServer($){let L=this.servers.get($);if(!L)throw Error(`MCP服务器 "${$}" 未注册`);if(L.status==="connected")await L.client.disconnect();try{L.status="connecting",await L.client.connect(),L.connectedAt=new Date,L.lastError=void 0,L.tools=L.client.availableTools}catch(G){throw L.lastError=G,L.status="error",G}}async getAvailableTools(){let $=[],L=new Map;for(let[G,Q]of this.servers)if(Q.status==="connected")for(let W of Q.tools){let X=L.get(W.name)||0;L.set(W.name,X+1)}for(let[G,Q]of this.servers)if(Q.status==="connected")for(let W of Q.tools){let Y=(L.get(W.name)||0)>1?`${G}__${W.name}`:W.name,q=z(Q.client,G,W,Y);$.push(q)}return $}async findTool($){for(let[L,G]of this.servers)if(G.status==="connected"){let Q=G.tools.find((W)=>W.name===$);if(Q)return z(G.client,L,Q)}return null}getToolsByServer($){let L=this.servers.get($);if(!L||L.status!=="connected")return[];return L.tools.map((G)=>z(L.client,$,G))}getServerStatus($){return this.servers.get($)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let $=[];for(let[L,G]of this.servers)if(G.status==="connected")$.push(this.refreshServerTools(L));await Promise.allSettled($)}async refreshServerTools($){let L=this.servers.get($);if(!L||L.status!=="connected")return;try{let G=L.client.availableTools,Q=L.tools.length;L.tools=G,this.emit("toolsUpdated",$,G,Q)}catch(G){console.warn(`刷新服务器 "${$}" 工具列表失败:`,G)}}setupClientEventHandlers($,L,G){$.on("connected",(Q)=>{L.status="connected",L.connectedAt=new Date,L.tools=$.availableTools,this.emit("serverConnected",G,Q)}),$.on("disconnected",()=>{L.status="disconnected",L.connectedAt=void 0,L.tools=[],this.emit("serverDisconnected",G)}),$.on("error",(Q)=>{L.status="error",L.lastError=Q,this.emit("serverError",G,Q)}),$.on("toolsUpdated",(Q)=>{let W=L.tools.length;L.tools=Q,this.emit("toolsUpdated",G,Q,W)}),$.on("statusChanged",(Q,W)=>{L.status=Q,this.emit("serverStatusChanged",G,Q,W)})}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers($){let L=Object.entries($).map(([G,Q])=>this.registerServer(G,Q).catch((W)=>{return console.warn(`注册MCP服务器 "${G}" 失败:`,W),W}));await Promise.allSettled(L)}getStatistics(){let $=0,L=0,G=0;for(let Q of this.servers.values())if(Q.status==="connected")$++,L+=Q.tools.length;else if(Q.status==="error")G++;return{totalServers:this.servers.size,connectedServers:$,errorServers:G,totalTools:L,isDiscovering:this.isDiscovering}}async disconnectAll(){let $=[];for(let[L,G]of this.servers)if(G.status==="connected")$.push(G.client.disconnect().catch((Q)=>{console.warn(`断开 MCP 服务器 "${L}" 时出错:`,Q)}));await Promise.allSettled($),this.servers.clear()}}
34
+ export{h as ba,J as ca};
@@ -1,2 +1,2 @@
1
1
  import{realpathSync as G}from"fs";import{cwd as b}from"process";var _=null;function T(){let N="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof G==="function"){let R=b();try{N=G(R).normalize("NFC")}catch{N=R.normalize("NFC")}}return{cwd:N,originalCwd:N,projectRoot:N}}function u(){if(!_)_=T();return _}function U(){return u().cwd}function D(N){u().cwd=N.normalize("NFC")}function X(){return u().originalCwd}function E(){return u().projectRoot}function F(N){u().projectRoot=N.normalize("NFC")}var f;((x)=>{x.DEFAULT="default";x.AUTO_EDIT="autoEdit";x.YOLO="yolo";x.PLAN="plan"})(f||={});import{AsyncLocalStorage as A}from"async_hooks";var V=new A;function $(){return V.getStore()??U()}function M(){try{return $()}catch{return X()}}var Y=100;function Z(N){return Number.isInteger(N)&&N>=-1&&N<=100}function z(){return"-1, 0, or an integer from 1 to 100"}
2
- export{D as vb,X as wb,E as xb,F as yb,f as zb,M as Ab,Y as Bb,Z as Cb,z as Db};
2
+ export{D as Db,X as Eb,E as Fb,F as Gb,f as Hb,M as Ib,Y as Jb,Z as Kb,z as Lb};
@@ -0,0 +1,6 @@
1
+ import{p as A,q as E,r as N,s as f}from"./chunk-yqxw7zz4.js";import{t as D}from"./chunk-nned222j.js";import{v as L,w as _,x}from"./chunk-syj3anec.js";import{y as B}from"./chunk-twem6p0g.js";import{K as $,S as b}from"./chunk-jakzknh3.js";import"./chunk-9ad7tt9s.js";import"./chunk-e4a240t7.js";import"./chunk-bm8vwfez.js";import"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import"./chunk-d4ex0qvs.js";import"./chunk-6es6av6j.js";import{ab as Z}from"./chunk-1pt090dg.js";import"./chunk-9xkjb87h.js";import"./chunk-49g067ek.js";import"./chunk-ctqf59q1.js";import"./chunk-jt62ctz7.js";import{Hb as Y,Ib as T}from"./chunk-gsfkrr25.js";import"./chunk-0dj326ms.js";import"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";import h from"yargs";import{hideBin as R}from"yargs/helpers";var w=new Set(Object.values(Y));function X(k){if(k&&w.has(k))return k;return}function M(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.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("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(F)=>{if(!F.p)return;let q=await O(F);process.exit(q)})}async function O(k,F=process){let q;try{await A();let J=await E({message:k.message,_:k._,defaultMessage:"Hello"}),G=await N(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
2
+ `);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:U}=await f({sessionId:k.sessionId,continue:k.continue,resume:k.resume,forkSession:k.forkSession,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,workspaceRoot:T(),modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig,agents:k.agents?B(k.agents):void 0});let V=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:X(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(V.chatStream(Q,{messages:[...U],userId:"cli-user",sessionId:K,workspaceRoot:T(),permissionMode:X(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
3
+ `);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
4
+ `);else F.stdout.write(`${H}
5
+ `);return 0}catch(J){return F.stderr.write(`Error: ${J instanceof Error?J.message:"未知错误"}
6
+ `),1}finally{await q?.dispose()}}async function d(){if(process.argv.slice(2).findIndex((q)=>q==="--print"||q==="-p")===-1)return!1;try{let{print:q,"output-format":J,"include-partial-messages":G,"input-format":Q,"system-prompt":K,"append-system-prompt":U,"max-turns":V,...W}=D,H=h(R(process.argv)).scriptName("blade").strict(!1).options(W).middleware([_,L,x]);return M(H),await H.parse(),!0}catch(q){console.error(`Print mode error: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}export{O as runPrint,d as handlePrintMode};
@@ -0,0 +1,3 @@
1
+ import{ec as $}from"./chunk-dr06x0cw.js";import{createModels as w}from"@earendil-works/pi-ai";import{builtinProviders as K}from"@earendil-works/pi-ai/providers/all";import{promises as L}from"node:fs";import X from"node:path";import{Mutex as U}from"async-mutex";import _ from"write-file-atomic";import{execSync as k}from"node:child_process";import*as W from"node:os";import*as G from"node:path";function A(q){return G.resolve(q).replace(/[/\\]/g,"-").replace(/:/g,"_")}function B(q){let z=q.replace(/_/g,":");if(z.startsWith("-"))z="/"+z.slice(1);return z.replace(/-/g,"/")}function O(q){let z=A(q);return G.join(J(),"projects",z)}function D(q){return typeof q==="string"&&q!=="."&&q!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(q)}function Q(q){if(!D(q))throw Error(`Invalid session ID: ${q}`)}function F(q,z){return Q(z),G.join(O(q),`${z}.jsonl`)}function R(q,z){return Q(z),G.join(O(q),`${z}.inbox.json`)}function C(q,z){return Q(z),G.join(O(q),`${z}.goal.json`)}function M(q){try{return k("git rev-parse --abbrev-ref HEAD",{cwd:q,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function J(){return process.env.BLADE_STORAGE_ROOT||G.join(W.homedir(),".blade")}async function V(){let{readdir:q}=await import("node:fs/promises");try{let z=G.join(J(),"projects");return(await q(z,{withFileTypes:!0})).filter((H)=>H.isDirectory()).map((H)=>H.name)}catch{return[]}}class T{filePath;mutex=new U;constructor(q=X.join(J(),"auth.json")){this.filePath=q}async read(q){return(await this.readAll())[q]}async list(){let q=await this.readAll();return Object.entries(q).map(([z,E])=>({providerId:z,type:E.type}))}async modify(q,z){return this.mutex.runExclusive(async()=>{let E=await this.readAll(),H=E[q],N=await z(H);if(N===void 0)return H;return E[q]=N,await this.writeAll(E),N})}async delete(q){await this.mutex.runExclusive(async()=>{let z=await this.readAll();if(!(q in z))return;delete z[q],await this.writeAll(z)})}async readAll(){try{let q=await L.readFile(this.filePath,"utf8"),z=JSON.parse(q);return z&&typeof z==="object"&&!Array.isArray(z)?z:{}}catch(q){if(q.code==="ENOENT")return{};throw q}}async writeAll(q){let z=X.dirname(this.filePath);await L.mkdir(z,{recursive:!0,mode:448}),await L.chmod(z,448),await _(this.filePath,`${JSON.stringify(q,null,2)}
2
+ `,{mode:384}),await L.chmod(this.filePath,384)}}class Z{credentials;models;constructor(q=new T){this.credentials=q,this.models=w({credentials:q});for(let z of K())this.models.setProvider(z)}async listProviders(){return Promise.all(this.models.getProviders().map(async(q)=>{let z=q.getModels();return{id:q.id,name:q.name,modelCount:z.length,defaultBaseUrl:q.baseUrl??z[0]?.baseUrl,supportsApiKey:Boolean(q.auth.apiKey),supportsOAuth:Boolean(q.auth.oauth),configured:Boolean(await this.models.checkAuth(q.id))}}))}listModels(q){return this.models.getModels(q).map((z)=>this.toCatalogEntry(z))}getModel(q,z){let E=this.models.getModel(q,z);if(!E)throw Error(`Unknown pi-ai model: ${q}/${z}`);return E}resolveConfig(q){let z=this.getModel(q.provider,q.model),E=q.overrides;return{...z,...E?.baseUrl?{baseUrl:E.baseUrl}:{},...E?.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}async setApiKey(q,z){this.requireProvider(q),await this.credentials.modify(q,async()=>({type:"api_key",key:z}))}async clearCredential(q){this.requireProvider(q),await this.credentials.delete(q)}async isConfigured(q){return this.requireProvider(q),Boolean(await this.models.checkAuth(q))}requireProvider(q){if(!this.models.getProvider(q))throw Error(`Unknown pi-ai provider: ${q}`)}toCatalogEntry(q){return{id:q.id,name:q.name,provider:q.provider,api:q.api,baseUrl:q.baseUrl,reasoning:q.reasoning,input:[...q.input],contextWindow:q.contextWindow,maxTokens:q.maxTokens,cost:{...q.cost}}}}var Y;function c(){return Y??=new Z,Y}
3
+ export{B as Vb,O as Wb,D as Xb,Q as Yb,F as Zb,R as _b,C as $b,M as ac,J as bc,V as cc,c as dc};