blade-code 0.10.118 → 0.10.120

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 (93) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-c5wrmq2e.js → chunk-0fyy97rq.js} +1 -1
  3. package/dist/{chunk-cqqmkwvn.js → chunk-0zzh482s.js} +1 -1
  4. package/dist/{chunk-gbjk078c.js → chunk-150w9kq4.js} +3 -3
  5. package/dist/{chunk-kr8rv2b9.js → chunk-1qbq7x98.js} +2 -2
  6. package/dist/{chunk-sr10jsjs.js → chunk-207s8tns.js} +1 -1
  7. package/dist/{chunk-eyb9psbc.js → chunk-2t6b962t.js} +1 -1
  8. package/dist/{chunk-z9g2x0vm.js → chunk-2v8fyvmh.js} +2 -2
  9. package/dist/{chunk-mnkdxt1v.js → chunk-2w10er3y.js} +1 -1
  10. package/dist/chunk-36k5c6wy.js +1 -0
  11. package/dist/{chunk-jp4j9tnn.js → chunk-3jdt8kqf.js} +1 -1
  12. package/dist/{chunk-bksfg23m.js → chunk-3jqd18d8.js} +2 -2
  13. package/dist/{chunk-cxbrqnqs.js → chunk-40pzrpjc.js} +1 -1
  14. package/dist/{chunk-z8xgk0m6.js → chunk-49javhkx.js} +1 -1
  15. package/dist/{chunk-2aysvx6k.js → chunk-4de6e3am.js} +2 -2
  16. package/dist/chunk-4jaqzjtw.js +1 -0
  17. package/dist/{chunk-9n9506vy.js → chunk-56fb0ece.js} +1 -1
  18. package/dist/{chunk-53aapkv1.js → chunk-5hmeb6yk.js} +2 -2
  19. package/dist/{chunk-gjw8100g.js → chunk-6h0kgpgv.js} +2 -2
  20. package/dist/chunk-6k7s3c7y.js +1 -0
  21. package/dist/{chunk-qdv0n8yt.js → chunk-7dykmcjj.js} +2 -2
  22. package/dist/{chunk-y21nw7g1.js → chunk-7k72dxwe.js} +2 -2
  23. package/dist/{chunk-935v0gpc.js → chunk-85bamng3.js} +1 -1
  24. package/dist/{chunk-kbkdhvk7.js → chunk-8mqbaptr.js} +1 -1
  25. package/dist/{chunk-hv6hrsnk.js → chunk-8qp8v96d.js} +1 -1
  26. package/dist/{chunk-6k5k40p8.js → chunk-9fgkg1vr.js} +1 -1
  27. package/dist/{chunk-x05zyqzf.js → chunk-9jtjq50j.js} +1 -1
  28. package/dist/{chunk-z52s82k7.js → chunk-a4dmw23t.js} +1 -1
  29. package/dist/chunk-a6nz99qf.js +1 -0
  30. package/dist/{chunk-9g64g1np.js → chunk-adkpwx6c.js} +1 -1
  31. package/dist/{chunk-3pwq56je.js → chunk-anjpwev3.js} +1 -1
  32. package/dist/{chunk-76f8ms39.js → chunk-apssk1cy.js} +1 -1
  33. package/dist/{chunk-tj2efrs1.js → chunk-b41den40.js} +2 -2
  34. package/dist/chunk-c5291k2x.js +1 -0
  35. package/dist/chunk-cmcgqa1d.js +1 -0
  36. package/dist/{chunk-ypbnczjp.js → chunk-dabq8kdx.js} +2 -2
  37. package/dist/{chunk-c3jb4xg7.js → chunk-dcy8s8rz.js} +1 -1
  38. package/dist/{chunk-vnbsq6ps.js → chunk-dfcc8q87.js} +2 -2
  39. package/dist/chunk-dspjxf4c.js +1 -0
  40. package/dist/{chunk-nyhqdpb6.js → chunk-exv1nb2x.js} +1 -1
  41. package/dist/{chunk-23v8c9b8.js → chunk-fpjhg6ce.js} +2 -2
  42. package/dist/chunk-gjw3g2jd.js +1 -0
  43. package/dist/{chunk-mqekerck.js → chunk-hgrdsef7.js} +1 -1
  44. package/dist/{chunk-90q4206c.js → chunk-j2pgrrkb.js} +2 -2
  45. package/dist/chunk-j8hzgacj.js +1 -0
  46. package/dist/{chunk-y1msyved.js → chunk-jn25d5qv.js} +1 -1
  47. package/dist/{chunk-q2exry0f.js → chunk-kpqdfn9z.js} +2 -2
  48. package/dist/{chunk-qw4hh3sv.js → chunk-kvf61fb1.js} +1 -1
  49. package/dist/{chunk-4w4wjm49.js → chunk-kz15jy62.js} +1 -1
  50. package/dist/{chunk-ecd727xh.js → chunk-kzzty3v5.js} +1 -1
  51. package/dist/{chunk-1w74gwns.js → chunk-kzzw1kwk.js} +2 -2
  52. package/dist/{chunk-tf7ezqew.js → chunk-m7b779kd.js} +1 -1
  53. package/dist/{chunk-yqygarpr.js → chunk-m9vhf4dg.js} +1 -1
  54. package/dist/{chunk-vbwvsgs1.js → chunk-ncqagb27.js} +2 -2
  55. package/dist/chunk-ne40tv38.js +10 -0
  56. package/dist/{chunk-xv3a1se1.js → chunk-nq0w1j1a.js} +1 -1
  57. package/dist/chunk-p7k7hqtb.js +1 -0
  58. package/dist/chunk-pykxe413.js +2 -0
  59. package/dist/{chunk-53h87fmt.js → chunk-q265drks.js} +1 -1
  60. package/dist/chunk-qp8qcmx0.js +1 -0
  61. package/dist/{chunk-dgf2xzzd.js → chunk-r6svhe3w.js} +2 -2
  62. package/dist/{chunk-cnhw5mqv.js → chunk-sca5q3tt.js} +1 -1
  63. package/dist/chunk-scgq3g37.js +8 -0
  64. package/dist/{chunk-bxjc7pg7.js → chunk-sefdw1mm.js} +2 -2
  65. package/dist/{chunk-rkdxqx8m.js → chunk-spxb931p.js} +2 -2
  66. package/dist/{chunk-swtap0bs.js → chunk-t169d8dc.js} +3 -3
  67. package/dist/{chunk-ng96f4xd.js → chunk-twdfyk78.js} +2 -2
  68. package/dist/chunk-v1cmz2bw.js +1 -0
  69. package/dist/chunk-v6sfs4qf.js +1 -0
  70. package/dist/{chunk-kk6rg27n.js → chunk-v95hk3fw.js} +1 -1
  71. package/dist/{chunk-dvv28pkc.js → chunk-w4xqaw4h.js} +2 -2
  72. package/dist/{chunk-fys5xx87.js → chunk-x4t1v4rb.js} +4 -4
  73. package/dist/{chunk-k3tqna1w.js → chunk-y1n8nf5w.js} +2 -2
  74. package/dist/{chunk-pshyn3yy.js → chunk-ye4wyq1k.js} +1 -1
  75. package/dist/chunk-zp8d0ma8.js +1 -0
  76. package/package.json +1 -1
  77. package/dist/chunk-25ps9fxw.js +0 -1
  78. package/dist/chunk-5j419kbp.js +0 -1
  79. package/dist/chunk-74m1zc1r.js +0 -1
  80. package/dist/chunk-9aqs02va.js +0 -8
  81. package/dist/chunk-bdgq4k40.js +0 -1
  82. package/dist/chunk-bpz7a5yn.js +0 -1
  83. package/dist/chunk-fqnqeca5.js +0 -1
  84. package/dist/chunk-j3cmytrt.js +0 -1
  85. package/dist/chunk-jdm0jffr.js +0 -1
  86. package/dist/chunk-jhsdden6.js +0 -10
  87. package/dist/chunk-m56bj6c6.js +0 -1
  88. package/dist/chunk-mdczqnc0.js +0 -1
  89. package/dist/chunk-nbhgg5p2.js +0 -1
  90. package/dist/chunk-nha6m2tx.js +0 -1
  91. package/dist/chunk-p3m1jyg5.js +0 -2
  92. package/dist/chunk-scc9kbd1.js +0 -1
  93. package/dist/chunk-wyw17nfy.js +0 -1
@@ -1,4 +1,4 @@
1
- import{$b as En,_b as Xt,ac as yn,bc as bn}from"./chunk-cnhw5mqv.js";import{tg as Bt}from"./chunk-swtap0bs.js";import{Ag as sn,Bg as zt,Cg as U,Dg as en,Eg as gt,Fg as mt,Hg as rn,Ig as Tn,Jg as B,Kg as dn,Lg as on,Mg as pn,Ng as lt,Og as un,Pg as cn,Qg as Mn,Sg as S,Vg as wn,Wg as Gt,Xg as Ut,Yg as h,Zg as Ht,yg as xt,zg as vi}from"./chunk-y21nw7g1.js";import{Eh as X,Gh as x}from"./chunk-6k5k40p8.js";import{Sh as It}from"./chunk-ecd727xh.js";import{Gi as tn,Hi as nn}from"./chunk-53aapkv1.js";import{_i as ns}from"./chunk-tf7ezqew.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{$b as Xt,ac as En,bc as yn,cc as bn}from"./chunk-sca5q3tt.js";import{ug as Bt}from"./chunk-t169d8dc.js";import{Ag as vi,Bg as sn,Cg as zt,Dg as U,Eg as en,Fg as gt,Gg as mt,Ig as rn,Jg as Tn,Kg as B,Lg as dn,Mg as on,Ng as pn,Og as lt,Pg as un,Qg as cn,Rg as Mn,Tg as S,Wg as wn,Xg as Gt,Yg as Ut,Zg as h,_g as Ht,zg as xt}from"./chunk-7k72dxwe.js";import{Fh as X,Hh as x}from"./chunk-9fgkg1vr.js";import{Th as It}from"./chunk-kzzty3v5.js";import{Hi as tn,Ii as nn}from"./chunk-5hmeb6yk.js";import{$i as ns}from"./chunk-m7b779kd.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -22,4 +22,4 @@ ${c}
22
22
 
23
23
  Preview (tail):
24
24
  ${M}`,u=!0}return{isError:t.isError===!0,llmContent:o,metadata:{contentCount:t.content.length,textBytes:n.textBytes,structuredBytes:r?.bytes??0,artifactCount:e.length,truncated:u,binaryOmitted:n.binaryBytes>0,artifacts:e}}}function yt(t){let i=t instanceof Error?t.message:String(t),n=gn(i.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")).trim();return wt(n||"MCP tool execution failed",Cn)}function Tt(t,i,n,s,e){let r=n.inputSchema&&typeof n.inputSchema==="object"?x.Unsafe(n.inputSchema):x.Any(),o=s||n.name;return jt({name:o,displayName:`${i}: ${n.name}`,kind:"execute",schema:r,description:{short:n.description||`MCP Tool: ${n.name}`,important:[`From MCP server: ${i}`,"Executes external tools; user confirmation required",...n.taskSupport==="required"?["This tool requires MCP task execution and returns an opaque task ID.","Use TaskOutput to retrieve the eventual result."]:[]]},category:"MCP tool",tags:["mcp","external",i],async execute(u,d){try{let p={...d.confirmationHandler?{confirmationHandler:d.confirmationHandler}:{},...d.mcpSamplingHandler?{samplingHandler:d.mcpSamplingHandler}:{},...d.onProgressUpdate?{progressHandler:d.onProgressUpdate}:{},...d.sessionId?{sessionId:d.sessionId}:{},...d.workspaceRoot?{workspaceRoot:d.workspaceRoot}:{},...d.permissionMode?{permissionMode:d.permissionMode}:{}};if(n.taskSupport==="required"){if(!d.sessionId)throw Error("MCP tasks require an active Session");let y=await T.getInstance().start({client:t,serverName:i,toolName:n.name,arguments:u,owner:{sessionId:d.sessionId,projectPath:Un.resolve(d.workspaceRoot||It())},interactionContext:p,signal:d.signal});return{success:!0,llmContent:{task_id:y.taskId,type:"mcp",status:y.status,message:`MCP task started. Use TaskOutput(task_id: "${y.taskId}") to retrieve its result.`},metadata:{summary:`Started MCP task ${y.taskId}`,serverName:i,toolName:n.name,task_id:y.taskId,taskType:"mcp",taskStatus:y.status,background:!0}}}let c=await t.callTool(n.name,u,{...d.signal?{signal:d.signal}:{},...p}),M=await j(c,e),w={summary:`MCP ${n.name} 执行${M.isError?"失败":"成功"}`,serverName:i,toolName:n.name,mcpResult:{isError:M.isError,...M.metadata}};if(M.isError){let y=yt(M.llmContent);return{success:!1,llmContent:y,error:{type:"execution_error",message:y},metadata:w}}return{success:!0,llmContent:M.llmContent,metadata:w}}catch(p){let c=yt(p);return{success:!1,llmContent:`MCP tool execution failed: ${c}`,error:{type:"execution_error",message:c},metadata:{summary:`MCP ${n.name} 执行失败`,serverName:i,toolName:n.name}}}}})}import{realpathSync as ss}from"node:fs";import Ni from"node:path";import{pathToFileURL as es}from"node:url";import{Client as rs}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as ds}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as os}from"@modelcontextprotocol/sdk/client/stdio.js";import{CallToolResultSchema as St,CreateMessageRequestSchema as ps,ElicitationCompleteNotificationSchema as us,ElicitRequestSchema as cs,ErrorCode as R,ListRootsRequestSchema as Ms,LoggingMessageNotificationSchema as ws,McpError as P,ResourceUpdatedNotificationSchema as ys,TaskStatusNotificationSchema as Ts}from"@modelcontextprotocol/sdk/types.js";import{EventEmitter as Es}from"events";import bs from"open";import{EventEmitter as Bn}from"events";function Et(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t)||!Number.isInteger(t)||t<s||t>e)throw Error(`${n} must be an integer between ${s} and ${e}`);return t}class bt extends Bn{client;config;checkTimer=null;isChecking=!1;running=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor(t,i={}){super();if(this.client=t,i.enabled!==void 0&&typeof i.enabled!=="boolean")throw Error("MCP health check enabled must be a boolean");this.config={interval:Et(i.interval,30000,"MCP health check interval",10,300000),timeout:Et(i.timeout,1e4,"MCP health check timeout",10,60000),enabled:i.enabled??!1,failureThreshold:Et(i.failureThreshold,3,"MCP health check failureThreshold",1,10)}}start(){if(this.running||!this.config.enabled)return;this.running=!0,this.scheduleNextCheck()}stop(){if(this.running=!1,this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null}scheduleNextCheck(){if(!this.running)return;this.checkTimer=setTimeout(async()=>{this.checkTimer=null,await this.performHealthCheck().catch(()=>{return}),this.scheduleNextCheck()},this.config.interval),this.checkTimer.unref()}async performHealthCheck(){if(this.isChecking)return this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let t=this.client.connectionStatus;if(t==="connected"){await this.client.ping(this.config.timeout),this.consecutiveFailures=0,this.setStatus("healthy");let i={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",i),i}else throw Error(`连接状态异常: ${t}`)}catch(t){this.consecutiveFailures++;let i=t,n;if(this.consecutiveFailures>=this.config.failureThreshold)n="unhealthy",this.emit("unhealthy",this.consecutiveFailures,i),this.client.requestRecovery(i,"health_check");else n="degraded";this.setStatus(n);let s={status:n,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:i};return this.emit("healthCheck",s),s}finally{this.isChecking=!1}}setStatus(t){if(this.currentStatus!==t){let i=this.currentStatus;this.currentStatus=t,this.emit("statusChanged",t,i)}}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")}}import{createHash as Xn}from"node:crypto";import{UriTemplate as zn}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";var ti=100,Yn=4096,Dn=65536,ft=1048576,ii=32,ni=65536,oi=4,ht=15000,si=256,ei=16384,Fn=256,Jn=8192,Vn=/[\p{Cf}\p{Co}\p{Cn}]/u;function jn(t){return[...new Set(new zn(t).variableNames)]}function pi(t,i){let n=G(t.argument.name,"completion argument name",si),s=ri(t.argument.value,"completion argument value",ei),e,r;if(t.reference.type==="prompt"){let p=G(t.reference.name,"completion prompt name",Fn),c=i.prompts.find((M)=>M.name===p);if(!c)throw Error(`MCP prompt "${p}" is not present in the current catalog`);e=new Set(c.arguments.map((M)=>M.name)),r={type:"ref/prompt",name:p}}else{let p=G(t.reference.uri,"completion resource template URI",Jn);if(!i.resourceTemplates.find((w)=>w.uriTemplate===p))throw Error(`MCP resource template "${p}" is not present in the current catalog`);let M;try{M=jn(p)}catch{throw Error(`MCP resource template "${p}" is invalid`)}e=new Set(M),r={type:"ref/resource",uri:p}}if(!e.has(n))throw Error(`MCP ${t.reference.type} completion argument "${n}" is not declared`);let o=Object.entries(t.context??{});if(o.length>ii)throw Error(`MCP completion context exceeds ${ii} arguments`);let u=Object.create(null),d=0;for(let[p,c]of o){let M=G(p,"completion context argument name",si);if(wi(M))throw Error(`Unsafe MCP completion context argument "${M}"`);if(!e.has(M))throw Error(`Unknown MCP completion context argument "${M}"`);let w=ri(c,`completion context argument "${M}"`,ei);if(d+=Buffer.byteLength(M)+Buffer.byteLength(w),d>ni)throw Error(`MCP completion context exceeds ${ni} bytes`);u[M]=w}return{ref:r,argument:{name:n,value:s},...o.length>0?{context:{arguments:u}}:{}}}function ui(t){let i=t.completion,n=JSON.stringify(i),s=Buffer.byteLength(n),e=Xn("sha256").update(n).digest("hex"),r=i.values.length,o=[],u=new Set,d=0,p=0,c=r>ti||s>ft;for(let w of i.values.slice(0,ti)){let y=Buffer.byteLength(w),E=Math.max(0,ft-p);if(E===0){c=!0;break}let a=di(w,Math.min(ft,E));if(p+=Buffer.byteLength(a),y>Buffer.byteLength(a))c=!0;let Dt=ci(a),L=di(Dt,Yn);if(Buffer.byteLength(L)<Buffer.byteLength(Dt))c=!0;if(u.has(L))continue;let Ft=Buffer.byteLength(L);if(d+Ft>Dn){c=!0;break}u.add(L),o.push(L),d+=Ft}if(o.length<r)c=!0;let M=i.total!==void 0&&Number.isSafeInteger(i.total)&&i.total>=0?i.total:void 0;return{values:o,...M!==void 0?{total:M}:{},hasMore:i.hasMore===!0||c||M!==void 0&&M>o.length,sourceValueCount:r,sourceBytes:s,projectedBytes:d,sha256:e,truncated:c}}function ci(t){return[...t.normalize("NFKC")].filter((i)=>{let n=i.codePointAt(0)??0;if(n<32||n===127)return!1;return!Vn.test(i)}).join("")}function G(t,i,n){if(typeof t!=="string"||!t||Buffer.byteLength(t)>n)throw Error(`MCP ${i} is invalid`);if(ci(t)!==t||Mi(t))throw Error(`MCP ${i} contains unsafe characters`);if(wi(t))throw Error(`MCP ${i} is unsafe`);return t}function ri(t,i,n){if(typeof t!=="string"||Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);if(Mi(t))throw Error(`MCP ${i} contains control characters`);return t}function Mi(t){return[...t].some((i)=>{let n=i.codePointAt(0)??0;return n<32||n===127})}function wi(t){return["__proto__","constructor","prototype"].includes(t)}function di(t,i){let n=Buffer.from(t);if(n.length<=i)return t;let s=n.subarray(0,Math.max(0,i)).toString("utf8");while(Buffer.byteLength(s)>i)s=s.slice(0,-1);return s}var At=20,_t=300000;function yi(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t))throw Error(`${n} must be a finite number`);if(t<s||t>e)throw Error(`${n} must be between ${s} and ${e}`);return t}function H(t,i,n,s,e){let r=yi(t,i,n,s,e);if(!Number.isInteger(r))throw Error(`${n} must be an integer`);return r}function Ti(t){let i=t.recovery;if(i!==void 0&&(i===null||typeof i!=="object"||Array.isArray(i)))throw Error("MCP recovery configuration must be an object");let n=i?.enabled??!0;if(typeof n!=="boolean")throw Error("MCP recovery enabled must be a boolean");let s=H(i?.maxAttempts,5,"MCP recovery maxAttempts",0,20),e=H(i?.initialDelayMs,1000,"MCP recovery initialDelayMs",10,300000),r=H(i?.maxDelayMs,30000,"MCP recovery maxDelayMs",e,300000),o=yi(i?.jitterRatio,0.2,"MCP recovery jitterRatio",0,1),u=H(i?.terminalErrorThreshold,3,"MCP recovery terminalErrorThreshold",1,10);return{enabled:n,maxAttempts:s,initialDelayMs:e,maxDelayMs:r,jitterRatio:o,terminalErrorThreshold:u}}function Ei(t,i,n=Math.random){let s=Math.max(0,i-1),e=Math.min(t.initialDelayMs*2**s,t.maxDelayMs);if(t.jitterRatio===0)return e;let r=Math.min(1,Math.max(0,n())),o=1-t.jitterRatio+2*t.jitterRatio*r;return Math.max(0,Math.round(e*o))}function k(t){let n=(t instanceof Error?t.message:String(t)).replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/[\r\n\t]+/g," ").trim();if(Buffer.byteLength(n)<=512)return n;let s=Buffer.from(n).subarray(0,512).toString("utf8");while(Buffer.byteLength(s)>512)s=s.slice(0,-1);return s}function bi(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return(n.includes("404")||n.includes("-32001"))&&(n.includes("session")||n.includes("not found"))}function fi(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return["econnreset","etimedout","epipe","ehostunreach","econnrefused","body timeout error","socket hang up","connection closed","connection terminated","sse stream disconnected","failed to reconnect sse stream","maximum reconnection attempts"].some((s)=>n.includes(s))}function C(t){return new DOMException(String(t||"MCP connection recovery cancelled"),"AbortError")}async function Rt(t,i,n=!0){if(i.aborted)throw C(i.reason);await new Promise((s,e)=>{let o=setTimeout(()=>{i.removeEventListener("abort",u),s()},t);if(n)o.unref();let u=()=>{clearTimeout(o),i.removeEventListener("abort",u),e(C(i.reason))};i.addEventListener("abort",u,{once:!0})})}import{createHash as ai}from"node:crypto";var Pt=100,q=1000,K=1000,W=1000,at=100,hi=64,Z=1048576,_=4194304,A=256,N=8192,g=256,m=16384,Ai=64,Gn=4096,_i=4194304,Ri=128;function $i(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Hn(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n===0||n>=1&&n<=8||n===11||n===12||n>=14&&n<=31||n===127})}function b(t,i,n){if(t===void 0)return;if(i==="description"?Hn(t):$i(t))throw Error(`MCP ${i} contains control characters`);if(Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);return t}function f(t,i,n){let s=t.trim();if(!s||s.length>n||$i(s))throw Error(`MCP ${i} is invalid`);return s}function $t(t){return Buffer.byteLength(JSON.stringify(t))}function Ct(t,i){if($t(t)>_i)throw Error(`MCP ${i} catalog exceeds ${_i} bytes`)}function Q(t,i){let n=new Set;for(let s of t){if(n.has(s))throw Error(`MCP ${i} catalog contains duplicate "${s}"`);n.add(s)}}function Ci(t){if(t.length>q)throw Error(`MCP resource catalog exceeds ${q} entries`);let i=t.map((n)=>({uri:f(n.uri,"resource URI",N),name:f(n.name,"resource name",A),...b(n.title,"resource title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource MIME type",g)?{mimeType:n.mimeType}:{},...n.size!==void 0&&Number.isSafeInteger(n.size)&&n.size>=0?{size:n.size}:{}}));return Q(i.map((n)=>n.uri),"resource"),Ct(i,"resource"),i}function ki(t){if(t.length>K)throw Error(`MCP resource template catalog exceeds ${K} entries`);let i=t.map((n)=>({uriTemplate:f(n.uriTemplate,"resource template URI",N),name:f(n.name,"resource template name",A),...b(n.title,"resource template title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource template MIME type",g)?{mimeType:n.mimeType}:{}}));return Q(i.map((n)=>n.uriTemplate),"resource template"),Ct(i,"resource template"),i}function Oi(t){if(t.length>W)throw Error(`MCP prompt catalog exceeds ${W} entries`);let i=t.map((n)=>{if((n.arguments?.length??0)>Ai)throw Error(`MCP prompt "${n.name}" exceeds ${Ai} arguments`);let s=(n.arguments??[]).map((e)=>{let r=f(e.name,"prompt argument name",A);if(["__proto__","constructor","prototype"].includes(r))throw Error(`MCP prompt argument name "${r}" is unsafe`);return{name:r,...b(e.description,"description",Gn)?{description:e.description}:{},required:e.required===!0}});return Q(s.map((e)=>e.name),`prompt "${n.name}" argument`),{name:f(n.name,"prompt name",A),...b(n.title,"prompt title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},arguments:s}});return Q(i.map((n)=>n.name),"prompt"),Ct(i,"prompt"),i}function Pi(t){return ai("sha256").update(JSON.stringify(t)).digest("hex")}function I(t,i,n){let s=new Map(t.map((r)=>[n(r),Pi(r)])),e=new Map(i.map((r)=>[n(r),Pi(r)]));return{added:[...e.keys()].filter((r)=>!s.has(r)).sort(),removed:[...s.keys()].filter((r)=>!e.has(r)).sort(),updated:[...e.keys()].filter((r)=>s.has(r)&&s.get(r)!==e.get(r)).sort()}}function Li(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function kt(t,i,n){if(t.bytes+=i,t.bytes>_)throw Error(`MCP ${n} exceeds ${_} total bytes`)}function Si(t,i,n){if(t.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw Error(`MCP ${i} contains invalid base64`);let s=Buffer.from(t,"base64");if(s.length>_)throw Error(`MCP ${i} exceeds ${_} decoded bytes`);return kt(n,s.length,i),{size:s.length,sha256:ai("sha256").update(s).digest("hex"),omitted:!0}}function xi(t,i){let n=f(typeof t.uri==="string"?t.uri:"","resource content URI",N),s=typeof t.mimeType==="string"?b(t.mimeType,"resource MIME type",g):void 0;if(typeof t.text==="string"){let e=Buffer.byteLength(t.text);if(e>Z)throw Error(`MCP resource text exceeds ${Z} bytes`);return kt(i,e,"resource result"),{uri:n,...s?{mimeType:s}:{},text:t.text}}if(typeof t.blob==="string")return{uri:n,...s?{mimeType:s}:{},binary:Si(t.blob,"resource blob",i)};throw Error("MCP resource content has neither text nor blob data")}function gi(t){let i=t&&typeof t==="object"&&Array.isArray(t.contents)?t.contents:[];if(i.length>hi)throw Error(`MCP resource result exceeds ${hi} contents`);let n={bytes:0},s=i.map((e)=>{if(!e||typeof e!=="object"||Array.isArray(e))throw Error("MCP resource content is malformed");return xi(e,n)});if($t(s)>_)throw Error(`MCP resource result exceeds ${_} bytes`);return{contents:s}}function mi(t){if(!t||typeof t!=="object"||Array.isArray(t))throw Error("MCP prompt result is malformed");let i=t,n=Array.isArray(i.messages)?i.messages:[];if(n.length>Ri)throw Error(`MCP prompt exceeds ${Ri} messages`);let s={bytes:0},e=n.map((r)=>{if(!r||typeof r!=="object"||Array.isArray(r))throw Error("MCP prompt message is malformed");let o=r,u=o.role;if(u!=="user"&&u!=="assistant")throw Error("MCP prompt message has an invalid role");let d=o.content;if(!d||typeof d!=="object"||Array.isArray(d))throw Error("MCP prompt message content is malformed");let p=d;if(p.type==="text"&&typeof p.text==="string"){let c=Buffer.byteLength(p.text);if(c>Z)throw Error(`MCP prompt text exceeds ${Z} bytes`);return kt(s,c,"prompt result"),{role:u,content:{type:"text",text:p.text}}}if((p.type==="image"||p.type==="audio")&&typeof p.data==="string"&&typeof p.mimeType==="string")return{role:u,content:{type:p.type,mimeType:f(p.mimeType,"prompt content MIME type",g),binary:Si(p.data,`prompt ${p.type}`,s)}};if(p.type==="resource"&&p.resource&&typeof p.resource==="object"&&!Array.isArray(p.resource))return{role:u,content:{type:"resource",resource:xi(p.resource,s)}};if(p.type==="resource_link"&&typeof p.uri==="string"&&typeof p.name==="string")return{role:u,content:{type:"resource_link",uri:f(p.uri,"prompt resource link URI",N),name:f(p.name,"prompt resource link name",A),...typeof p.mimeType==="string"?{mimeType:f(p.mimeType,"prompt resource link MIME type",g)}:{},...typeof p.description==="string"?{description:b(p.description,"description",m)}:{}}};throw Error(`Unsupported MCP prompt content type: ${String(p.type)}`)});if($t(e)>_)throw Error(`MCP prompt result exceeds ${_} bytes`);return{...typeof i.description==="string"?{description:b(i.description,"description",m)}:{},messages:e}}var li=4000,Ui=4096,Bi=32,qn=128,Xi=1000,zi=100,Yi=65536,Kn=new Set(["__proto__","constructor","prototype"]);function Di(t,i){if(!t.trim())throw Error("MCP elicitation server name is empty");if(!i.message.trim())throw Error("MCP elicitation message is empty");if(i.message.length>li)throw Error(`MCP elicitation message exceeds ${li} characters`);if(i.mode==="url"){let e=Nn(i.url);if(!i.elicitationId.trim())throw Error("MCP URL elicitation ID is empty");return{serverName:t,mode:"url",message:i.message,url:e.toString(),domain:e.hostname,elicitationId:i.elicitationId}}let n=Object.entries(i.requestedSchema.properties);if(n.length>Bi)throw Error(`MCP elicitation exceeds the ${Bi} field limit`);let s=new Set(i.requestedSchema.required??[]);for(let e of s)if(!Object.hasOwn(i.requestedSchema.properties,e))throw Error(`MCP elicitation requires an unknown field: ${e}`);return{serverName:t,mode:"form",message:i.message,fields:n.map(([e,r])=>Wn(e,r,s.has(e))),requestedSchema:structuredClone(i.requestedSchema)}}function vs(t){let i=Object.create(null);for(let n of t.fields??[])if(n.defaultValue!==void 0)i[n.name]=Array.isArray(n.defaultValue)?[...n.defaultValue]:n.defaultValue;return i}function te(t,i){let n=i.trim();if(!n){if(t.defaultValue!==void 0)return t.defaultValue;if(!t.required)return;throw Error(`${t.title} is required`)}if(t.type==="number"||t.type==="integer"){let s=Number(n);if(!Number.isFinite(s))throw Error(`${t.title} must be a finite number`);if(t.type==="integer"&&!Number.isSafeInteger(s))throw Error(`${t.title} must be a safe integer`);return s}if(t.type==="boolean"){if(["true","yes","y","1"].includes(n.toLowerCase()))return!0;if(["false","no","n","0"].includes(n.toLowerCase()))return!1;throw Error(`${t.title} must be true or false`)}return n}function Fi(t,i){if(i.action!=="accept")return{action:i.action};if(t.mode==="url")return{action:"accept"};if(!t.requestedSchema)throw Error("MCP form elicitation schema is unavailable");let n=i.content??{};if(Buffer.byteLength(JSON.stringify(n),"utf8")>Yi)throw Error(`MCP elicitation response exceeds ${Yi} bytes`);for(let r of Object.keys(n))Ji(r);for(let r of Object.values(n))if(typeof r==="number"&&(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r)))throw Error("MCP elicitation response contains an unsafe number");let s=x.Unsafe({...t.requestedSchema,additionalProperties:!1}),e=X(s,n);if(!e.success)throw Error(`Invalid MCP elicitation response: ${e.error.message}`);return{action:"accept",content:e.data}}function Wn(t,i,n){Ji(t);let s=tt(i.title?.trim()||t,"field title"),e=i.description?tt(i.description,"field description"):void 0,r={name:t,title:s,description:e,required:n};if(i.type==="boolean")return{...r,type:"boolean",...typeof i.default==="boolean"?{defaultValue:i.default}:{}};if(i.type==="number"||i.type==="integer")return{...r,type:i.type,...typeof i.default==="number"?{defaultValue:i.default}:{},...i.minimum!==void 0?{minimum:i.minimum}:{},...i.maximum!==void 0?{maximum:i.maximum}:{}};if(i.type==="array"){let u=Qn(i);return{...r,type:"multi-select",options:u,...Array.isArray(i.default)&&i.default.every((d)=>typeof d==="string")?{defaultValue:[...i.default]}:{},...i.minItems!==void 0?{minItems:i.minItems}:{},...i.maxItems!==void 0?{maxItems:i.maxItems}:{}}}let o=Zn(i);if(o)return{...r,type:"select",options:o,...typeof i.default==="string"?{defaultValue:i.default}:{}};return{...r,type:"string",...typeof i.default==="string"?{defaultValue:i.default}:{},...i.format?{format:i.format}:{},...i.minLength!==void 0?{minLength:i.minLength}:{},...i.maxLength!==void 0?{maxLength:i.maxLength}:{}}}function Zn(t){if(t.oneOf)return v(t.oneOf.map((i)=>({value:i.const,label:i.title})));if(!t.enum)return;return v(t.enum.map((i,n)=>({value:i,label:t.enumNames?.[n]??i})))}function Qn(t){if(t.items?.anyOf)return v(t.items.anyOf.map((i)=>({value:i.const,label:i.title})));if(t.items?.enum)return v(t.items.enum.map((i)=>({value:i,label:i})));throw Error("MCP multi-select elicitation is missing enum options")}function v(t){if(t.length===0||t.length>zi)throw Error(`MCP elicitation options must contain 1-${zi} items`);let i=new Set;return t.map((n)=>{if(i.has(n.value))throw Error(`MCP elicitation contains duplicate option: ${n.value}`);return i.add(n.value),{value:tt(n.value,"option value"),label:tt(n.label,"option label")}})}function Ji(t){if(!t||t.length>qn||Kn.has(t))throw Error(`Unsafe MCP elicitation field name: ${t||"(empty)"}`)}function tt(t,i){if(t.length>Xi)throw Error(`MCP elicitation ${i} exceeds ${Xi} characters`);return t}function Nn(t){if(t.length>Ui)throw Error(`MCP elicitation URL exceeds ${Ui} characters`);let i;try{i=new URL(t)}catch{throw Error("MCP elicitation URL is invalid")}if(!["http:","https:"].includes(i.protocol))throw Error(`MCP elicitation URL protocol is not allowed: ${i.protocol}`);if(i.username||i.password)throw Error("MCP elicitation URL must not contain credentials");return i}import{createHash as Ki}from"node:crypto";var l=1000,it=100,In=256,Vi=16384,ji=262144,Gi=4194304,Hi=24;function vn(t,i=10){return Ki("sha256").update(t).digest("hex").slice(0,i)}function Ot(t){if(Array.isArray(t))return t.map(Ot);if(!t||typeof t!=="object")return t;let i=t;return Object.fromEntries(Object.keys(i).sort().map((n)=>[n,Ot(i[n])]))}function Wi(t){let i=t.normalize("NFKC"),n=i.replace(/[^A-Za-z0-9_-]/g,"_");if(n&&n===i&&n.length<=Hi)return n;return`${(n||"unnamed").slice(0,Hi-11)}_${vn(i)}`}function Lt(t,i){return`${ts(t)}${Wi(i)}`}function ts(t){return`mcp__${Wi(t)}__`}function qi(t){return Ki("sha256").update(JSON.stringify(Ot({name:t.name,description:t.description,inputSchema:t.inputSchema,taskSupport:t.taskSupport}))).digest("hex")}function is(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Zi(t){if(t.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);let i=new Set,n=[],s=0;for(let e of t){let r=e.name.trim();if(!r||r.length>In||is(r))throw Error("MCP tool catalog contains an invalid tool name");if(i.has(r))throw Error(`MCP tool catalog contains duplicate tool "${r}"`);i.add(r);let o=e.description??"";if(Buffer.byteLength(o)>Vi)throw Error(`MCP tool "${r}" description exceeds ${Vi} bytes`);let u=JSON.stringify(e.inputSchema),d=Buffer.byteLength(u);if(d>ji)throw Error(`MCP tool "${r}" schema exceeds ${ji} bytes`);if(s+=Buffer.byteLength(r)+Buffer.byteLength(o)+d,s>Gi)throw Error(`MCP tool catalog exceeds ${Gi} bytes`);n.push({name:r,description:o,inputSchema:JSON.parse(u),...e.execution?.taskSupport?{taskSupport:e.execution.taskSupport}:{}})}return n}function Qi(t,i){let n=new Map(t.map((e)=>[e.name,qi(e)])),s=new Map(i.map((e)=>[e.name,qi(e)]));return{added:[...s.keys()].filter((e)=>!n.has(e)).sort(),removed:[...n.keys()].filter((e)=>!s.has(e)).sort(),updated:[...s.keys()].filter((e)=>n.has(e)&&n.get(e)!==s.get(e)).sort()}}function nt(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function Ii(t){if(t instanceof zt||t instanceof U)return{type:"auth_error",isRetryable:!1,originalError:t};if(!(t instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String(t))};let i=t.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((e)=>i.includes(e)))return{type:"config_error",isRetryable:!1,originalError:t};if(i.includes("unauthorized")||i.includes("401")||i.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:t};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((e)=>i.includes(e)))return{type:"network_temporary",isRetryable:!0,originalError:t};return{type:"unknown",isRetryable:!0,originalError:t}}class Yt extends Es{config;runtimeOptions;status="disconnected";sdkClient=null;tools=new Map;toolCatalogRevision=0;toolRefreshPromise;toolRefreshRequested=!1;resources=[];resourceTemplates=[];prompts=[];contentCatalogRevision=0;contentRefreshPromise;requestedContentCatalogs=new Set;contentRefreshReason="manual";catalogGeneration=0;desiredResourceSubscriptions=new Set;activeResourceSubscriptions=new Set;serverInfo=null;serverInstructions;completionCallsInFlight=0;loggingPolicy;logWindowStartedAt=0;logEventsInWindow=0;logRateWarningEmitted=!1;recoveryPolicy;desiredConnected=!1;connectionGeneration=0;connectPromise;connectAbortController;recoveryPromise;recoveryAbortController;recoveryState;consecutiveTerminalErrors=0;oauthProvider=null;serverName;healthMonitor=null;activeInteraction;taskInteractions=new Map;taskPolicy;roots;constructor(t,i,n,s={}){super();this.config=t;this.runtimeOptions=s;this.serverName=i||"default",this.recoveryPolicy=Ti(t),this.loggingPolicy=dn(t),this.taskPolicy=wn(t.tasks),this.roots=(s.roots??[]).map((r)=>{let o=ss.native(Ni.resolve(r));return{uri:es(o).href,name:Ni.basename(o)||o}});let e=vi(t);if(this.config={...t,...e?{oauth:e}:{}},e?.enabled&&t.url&&s.oauthCredentialAccess!==!1)this.oauthProvider=new en(this.serverName,t.url,e,s.oauthStorageRoot?{tokenStorage:new sn(s.oauthStorageRoot)}:{});if(n?.enabled)this.healthMonitor=new bt(this,n),this.healthMonitor.on("unhealthy",(r,o)=>{this.emit("unhealthy",r,o)})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get contentCatalog(){return{resources:structuredClone(this.resources),resourceTemplates:structuredClone(this.resourceTemplates),prompts:structuredClone(this.prompts)}}get completionSupported(){return Boolean(this.sdkClient?.getServerCapabilities()?.completions)}get tasks(){return{...this.taskPolicy}}get server(){return this.serverInfo}get instructions(){return this.serverInstructions?structuredClone(this.serverInstructions):void 0}get healthCheck(){return this.healthMonitor}get recovery(){return this.recoveryState?structuredClone(this.recoveryState):void 0}get logging(){return{...this.loggingPolicy}}get oauthEnabled(){return this.config.oauth?.enabled===!0}async getOAuthStatus(){if(!this.oauthEnabled)return"disabled";if(this.runtimeOptions.oauthCredentialAccess===!1)return"unavailable";return this.oauthProvider?.getStatus()??"error"}async beginOAuthLogin(t={}){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);return t.openBrowser?this.oauthProvider.openAuthorization():this.oauthProvider.beginAuthorization()}async logoutOAuth(){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(this.status!=="disconnected")await this.disconnect();await this.oauthProvider.logout()}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry(t=3,i=1000){if(!Number.isInteger(t)||t<1||t>At)throw Error(`MCP connection maxRetries must be an integer between 1 and ${At}`);if(!Number.isFinite(i)||i<0||i>_t)throw Error(`MCP connection initialDelay must be between 0 and ${_t}`);if(this.status==="connected")return;if(this.recoveryPromise)return this.recoveryPromise;if(this.connectPromise)return this.connectPromise;this.desiredConnected=!0;let n=++this.connectionGeneration,s=new AbortController;this.connectAbortController=s;let e=this.runInitialConnection(Math.max(1,t),Math.max(0,i),n,s.signal).finally(()=>{if(this.connectPromise===e)this.connectPromise=void 0;if(this.connectAbortController===s)this.connectAbortController=void 0});return this.connectPromise=e,e}async runInitialConnection(t,i,n,s){let e;for(let o=1;o<=t;o++){this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!1);return}catch(u){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=u instanceof Error?u:Error(String(u)),!Ii(e).isRetryable||o===t)break;await Rt(i*2**Math.max(0,o-1),s,!1)}}let r=e??Error("MCP connection failed");if(this.isConnectionGenerationCurrent(n))this.invalidateLiveConnection(!1),this.setStatus("error"),this.emitClientError(r);throw r}async doConnect(t,i){let n;try{this.assertConnectionGeneration(t),this.setStatus(i?"reconnecting":"connecting");let s=cn(this.config.sampling),e={...s,enabled:s.enabled&&this.runtimeOptions.samplingAvailable===!0};n=new rs({name:nn(),version:tn()},{capabilities:{roots:{listChanged:!1},elicitation:{form:{applyDefaults:!1},url:{}},...e.enabled?{sampling:{}}:{}},listChanged:{tools:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshTools("notification")}},resources:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["resources"])}},prompts:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["prompts"])}}}});let r=n;if(this.sdkClient=r,this.resetCatalogRefreshState(),this.registerElicitationHandlers(r),this.registerRootHandler(r),e.enabled)this.registerSamplingHandler(r,e);if(this.registerResourceNotificationHandler(r),this.registerLoggingHandler(r),this.taskPolicy.enabled)this.registerTaskStatusHandler(r);r.onclose=()=>{this.handleUnexpectedClose(r,t)},r.onerror=(d)=>{this.handleTransportError(r,t,d)};let o=await this.createTransport();this.assertConnectionGeneration(t),await r.connect(o),this.assertConnectionGeneration(t);let u=r.getServerVersion();this.serverInfo={name:u?.name||"Unknown",version:u?.version||"0.0.0"},this.serverInstructions=yn(r.getInstructions(),{exposeDetails:this.runtimeOptions.exposeInstructions}),await this.configureLogging(r),await this.refreshTools("initial"),await this.refreshContentCatalogs("initial").catch(()=>{return}),await this.reconcileResourceSubscriptions(r),this.assertConnectionGeneration(t),this.consecutiveTerminalErrors=0,this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor?.resetFailureCount(),this.healthMonitor?.start()}catch(s){if(n&&this.sdkClient===n)this.sdkClient=null;if(n)n.onclose=void 0,n.onerror=void 0,await n.close().catch(()=>{return});throw s}}handleUnexpectedClose(t,i){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;this.startRecovery(Error(`MCP server "${this.serverName}" connection closed`),"transport_closed",!1)}handleTransportError(t,i,n){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;if(this.emit("transportError",{serverName:this.serverName,error:k(n)}),bi(n)){this.startRecovery(n,"session_expired",!0);return}if(!fi(n)){this.consecutiveTerminalErrors=0;return}if(this.consecutiveTerminalErrors++,n.message.toLowerCase().includes("maximum reconnection attempts")||this.consecutiveTerminalErrors>=this.recoveryPolicy.terminalErrorThreshold)this.startRecovery(n,"transport_error",!0)}requestRecovery(t,i){if(!this.desiredConnected||this.status!=="connected"||this.recoveryPromise)return;this.startRecovery(t,i,!0)}startRecovery(t,i,n){if(!this.desiredConnected||this.recoveryPromise)return;let s=this.sdkClient;if(this.sdkClient=null,s)s.onclose=void 0,s.onerror=void 0;this.healthMonitor?.stop(),this.invalidateLiveConnection(!0);let e=++this.connectionGeneration,r=new AbortController;if(this.recoveryAbortController=r,this.setStatus("reconnecting"),n&&s)s.close().catch(()=>{return});let o=Promise.resolve().then(()=>this.runRecoveryLoop(t,i,e,r.signal)).finally(()=>{if(this.recoveryPromise===o)this.recoveryPromise=void 0;if(this.recoveryAbortController===r)this.recoveryAbortController=void 0});this.recoveryPromise=o,o.catch(()=>{return})}async runRecoveryLoop(t,i,n,s){let e=t;if(!this.recoveryPolicy.enabled||this.recoveryPolicy.maxAttempts===0){this.failRecovery(e,i,0,n);return}for(let r=1;r<=this.recoveryPolicy.maxAttempts;r++){this.assertConnectionGeneration(n,s);let o=Ei(this.recoveryPolicy,r,this.runtimeOptions.recoveryRandom),u=Date.now()+o;this.publishConnectionLifecycle({phase:"reconnecting",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts,nextRetryAt:u,error:k(e)}),await Rt(o,s),this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!0),this.healthMonitor?.resetFailureCount(),this.publishConnectionLifecycle({phase:"recovered",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts}),this.emit("reconnected");return}catch(d){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=d instanceof Error?d:Error(String(d)),!Ii(e).isRetryable){this.failRecovery(e,i,r,n);return}}}this.failRecovery(e,i,this.recoveryPolicy.maxAttempts,n)}failRecovery(t,i,n,s){if(!this.isConnectionGenerationCurrent(s))return;this.setStatus("error"),this.publishConnectionLifecycle({phase:"failed",reason:i,attempt:n,maxAttempts:this.recoveryPolicy.maxAttempts,error:k(t)}),this.emit("reconnectFailed",t)}publishConnectionLifecycle(t){this.recoveryState=structuredClone(t),this.emit("connectionLifecycleChanged",structuredClone(t))}isConnectionGenerationCurrent(t){return this.desiredConnected&&this.connectionGeneration===t}assertConnectionGeneration(t,i){if(i?.aborted||!this.desiredConnected||this.connectionGeneration!==t)throw C(i?.reason)}invalidateLiveConnection(t){if(this.resetCatalogRefreshState(),this.tools.clear(),this.resources=[],this.resourceTemplates=[],this.prompts=[],this.activeResourceSubscriptions.clear(),!t)this.desiredResourceSubscriptions.clear();if(!t)this.taskInteractions.clear();this.serverInfo=null,this.serverInstructions=void 0,this.consecutiveTerminalErrors=0}resetCatalogRefreshState(){this.catalogGeneration++,this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,this.contentRefreshPromise=void 0,this.requestedContentCatalogs.clear(),this.contentRefreshReason="manual"}emitClientError(t){if(this.listenerCount("error")>0)this.emit("error",t)}async ping(t=1e4){let i=this.sdkClient;if(!i||this.status!=="connected")throw Error(`MCP server "${this.serverName}" is not connected`);let n=new AbortController,s=setTimeout(()=>n.abort("MCP health check timeout"),t);s.unref();try{await i.ping({signal:n.signal,timeout:t,maxTotalTimeout:t})}catch(e){if(n.signal.aborted)throw Error(`MCP server "${this.serverName}" health check timed out after ${t}ms`);throw e}finally{clearTimeout(s)}}async disconnect(){this.desiredConnected=!1,this.connectionGeneration++,this.connectAbortController?.abort("MCP client disconnected"),this.recoveryAbortController?.abort("MCP client disconnected"),this.healthMonitor?.stop();let t=this.sdkClient;if(this.sdkClient=null,t)t.onclose=void 0,t.onerror=void 0,await t.close().catch(()=>{return});await Promise.allSettled([this.connectPromise,this.recoveryPromise].filter((i)=>i!==void 0)),this.invalidateLiveConnection(!1),this.recoveryState=void 0,await this.oauthProvider?.dispose(),this.setStatus("disconnected"),this.emit("disconnected")}async callTool(t,i={},n={}){let s=this.sdkClient;if(!s||this.status!=="connected")throw Error("客户端未连接到服务器");if(!this.tools.has(t))throw Error(`工具 "${t}" 不存在`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive tool calls`);let e=gt(this.config),r=Symbol(t);this.activeInteraction={token:r,context:n,samplingRequests:0,samplingInFlight:!1};let o=new AbortController,u=setTimeout(()=>o.abort("mcp-tool-timeout"),e.totalTimeoutMs);u.unref();let d=n.signal?AbortSignal.any([n.signal,o.signal]):o.signal,p={count:0};try{return await s.callTool({name:t,arguments:i},St,{signal:d,timeout:e.idleTimeoutMs,resetTimeoutOnProgress:!0,maxTotalTimeout:e.totalTimeoutMs,onprogress:(M)=>{let w=mt(M,p,e);if(w&&!d.aborted&&this.activeInteraction?.token===r)n.progressHandler?.(w),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...w})}})}catch(c){if(n.signal?.aborted)throw new DOMException(String(n.signal.reason||"MCP tool call cancelled"),"AbortError");if(o.signal.aborted&&!n.signal?.aborted)throw new P(R.RequestTimeout,`MCP server "${this.serverName}" tool "${t}" timed out after ${e.totalTimeoutMs}ms`);throw console.error(`[McpClient] 调用工具 "${t}" 失败:`,c),c}finally{if(clearTimeout(u),this.activeInteraction?.token===r)this.activeInteraction=void 0}}getToolTaskSupport(t){return this.tools.get(t)?.taskSupport}async createToolTask(t,i,n,s,e){let r=this.sdkClient;if(!r||this.status!=="connected")throw Error("MCP client is not connected");if(!this.taskPolicy.enabled)throw Error(`MCP tasks are disabled for server "${this.serverName}"`);if(!r.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);let o=this.getToolTaskSupport(t);if(o!=="required"&&o!=="optional")throw Error(`MCP tool "${t}" does not support task execution`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive task creation`);let u=gt(this.config),d=Symbol(t),p={token:d,context:{...n,signal:s},samplingRequests:0,samplingInFlight:!1};this.activeInteraction=p;let c={count:0},M=r.experimental.tasks.callToolStream({name:t,arguments:i},St,{signal:s,task:{ttl:e??this.taskPolicy.defaultTtlMs,pollInterval:this.taskPolicy.pollIntervalMs},timeout:u.idleTimeoutMs,maxTotalTimeout:u.totalTimeoutMs,resetTimeoutOnProgress:!0,onprogress:(y)=>{let E=mt(y,c,u);if(E&&!s.aborted&&this.hasInteractionToken(d))n.progressHandler?.(E),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...E})}}),w=!1;try{let y=await M.next();if(await M.return(void 0),y.done||y.value.type!=="taskCreated"){if(!y.done&&y.value.type==="error")throw y.value.error;throw Error(`MCP tool "${t}" did not create a task`)}if(this.sdkClient!==r)throw Error("MCP client changed while creating a task");let E=Ut(y.value.task,this.taskPolicy);return this.taskInteractions.set(E.taskId,p),w=!0,this.emit("taskCreated",{serverName:this.serverName,toolName:t,task:E}),E}finally{if(this.activeInteraction?.token===d)this.activeInteraction=void 0;if(!w){for(let[y,E]of this.taskInteractions)if(E.token===d)this.taskInteractions.delete(y)}}}async getToolTask(t,i,n){let s=this.requireTaskClient(),e=await s.experimental.tasks.getTask(t,{signal:n,timeout:this.taskPolicy.pollIntervalMs+1e4,maxTotalTimeout:this.taskPolicy.pollIntervalMs+1e4});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task");return Ut(e,this.taskPolicy,{taskId:t,createdAt:i})}async getToolTaskResult(t,i,n=this.taskPolicy.maxLifetimeMs){let s=this.requireTaskClient(),e=Math.max(1,Math.min(n,this.taskPolicy.maxLifetimeMs)),r=await s.experimental.tasks.getTaskResult(t,St,{signal:i,timeout:e,maxTotalTimeout:e});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task result");return r}async cancelToolTask(t,i){let n=this.requireTaskClient();if(!n.getServerCapabilities()?.tasks?.cancel)throw Error(`MCP server "${this.serverName}" does not support task cancellation`);if(await n.experimental.tasks.cancelTask(t,{signal:i,timeout:15000,maxTotalTimeout:15000}),this.sdkClient!==n)throw Error("MCP client changed while cancelling a task")}async normalizeToolTaskResult(t){return j(t,this.runtimeOptions.artifactWriter)}releaseTaskInteraction(t){this.taskInteractions.delete(t)}async waitUntilConnected(t,i){if(this.status==="connected"&&this.sdkClient)return;if(!this.desiredConnected)throw Error(`MCP server "${this.serverName}" is disconnected`);await new Promise((n,s)=>{let e=setTimeout(()=>{d(),s(Error(`MCP server "${this.serverName}" recovery timed out`))},i);e.unref();let r=()=>{d(),n()},o=()=>{if(this.desiredConnected)return;d(),s(Error(`MCP server "${this.serverName}" was disconnected`))},u=()=>{d(),s(new DOMException(String(t.reason||"MCP task recovery cancelled"),"AbortError"))},d=()=>{clearTimeout(e),this.off("connected",r),this.off("disconnected",o),t.removeEventListener("abort",u)};if(this.on("connected",r),this.on("disconnected",o),t.addEventListener("abort",u,{once:!0}),t.aborted)u()})}requireTaskClient(){let t=this.sdkClient;if(!t||this.status!=="connected"||!this.taskPolicy.enabled)throw Error(`MCP server "${this.serverName}" task client is unavailable`);if(!t.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);return t}hasInteractionToken(t){if(this.activeInteraction?.token===t)return!0;return[...this.taskInteractions.values()].some((i)=>i.token===t)}registerRootHandler(t){t.setRequestHandler(Ms,async()=>({roots:this.roots.map((i)=>({...i}))}))}resolveInteraction(t){let i=t._meta?.["io.modelcontextprotocol/related-task"]?.taskId;return i?this.taskInteractions.get(i):this.activeInteraction}registerTaskStatusHandler(t){t.setNotificationHandler(Ts,(i)=>{this.emit("taskStatus",i.params)})}registerSamplingHandler(t,i){t.setRequestHandler(ps,async(n,s)=>{let e=this.resolveInteraction(n.params);if(!e?.context.confirmationHandler||!e.context.samplingHandler)throw new P(R.InvalidRequest,"MCP sampling requires an active interactive Session");if(e.samplingInFlight)throw new P(R.InvalidRequest,"MCP server does not allow overlapping sampling requests");e.samplingInFlight=!0;try{if(e.samplingRequests++,e.samplingRequests>i.maxRequestsPerToolCall)throw new P(R.InvalidRequest,`MCP sampling exceeded ${i.maxRequestsPerToolCall} requests for one tool call`);let r=e.context.signal?AbortSignal.any([e.context.signal,s.signal]):s.signal;if(r.aborted)throw new P(R.InvalidRequest,"MCP sampling was cancelled");let o;try{o=Mn(n.params,i)}catch(p){throw new P(R.InvalidRequest,p instanceof Error?p.message:String(p))}let u=await e.context.confirmationHandler.requestConfirmation({type:"mcpSampling",kind:"execute",toolName:`MCP sampling: ${this.serverName}`,title:"MCP model sampling request",message:`MCP server "${this.serverName}" wants to call the current Session model with up to ${o.maxTokens} output tokens.`,details:o.preview,risks:[`May consume up to ${o.maxTokens} output tokens`,"The model response will be returned to the MCP server"]},r);if(r.aborted||u.reason===Xt||u.reason==="timeout")throw new P(R.InvalidRequest,"MCP sampling was cancelled");if(!u.approved)throw new P(R.InvalidRequest,"MCP sampling was denied");let d=await e.context.samplingHandler(o,r);return this.emit("samplingCompleted",{serverName:this.serverName,model:d.model,maxTokens:o.maxTokens}),d}finally{e.samplingInFlight=!1}})}registerElicitationHandlers(t){t.setRequestHandler(cs,async(i,n)=>{let s=this.resolveInteraction(i.params)?.context;if(!s?.confirmationHandler)return this.emit("elicitationCancelled",{serverName:this.serverName,reason:"no-interaction-handler"}),{action:"cancel"};let e=s.signal?AbortSignal.any([s.signal,n.signal]):n.signal;if(e.aborted)return{action:"cancel"};let r;try{r=Di(this.serverName,i.params)}catch(o){return this.emit("elicitationRejected",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"decline"}}try{let o=s.sessionId&&s.workspaceRoot&&s.permissionMode?{projectDir:s.workspaceRoot,sessionId:s.sessionId,permissionMode:s.permissionMode,abortSignal:e}:void 0,u=o?await Bt.getInstance().executeElicitationHooks(r,o):{},d;if(u.blockedReason)d={action:"decline"};else if(u.response)d=u.response;else{let M=await s.confirmationHandler.requestConfirmation({type:"mcpElicitation",message:r.message,title:`MCP input requested by ${this.serverName}`,mcpElicitation:r},e),w=this.resolveElicitationAction(M,e);if(d=M.elicitation??{action:w},w==="accept"&&r.mode==="url"&&M.openExternalUrl&&r.url)await bs(r.url,{wait:!1})}let p=o?await Bt.getInstance().executeElicitationResultHooks(r,d,o):{};if(p.blockedReason)d={action:"cancel"};else if(p.response)d=p.response;let c=Fi(r,d);return this.emit("elicitationResolved",{serverName:this.serverName,mode:r.mode,action:c.action,elicitationId:r.elicitationId}),c}catch(o){return this.emit("elicitationCancelled",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"cancel"}}}),t.setNotificationHandler(us,(i)=>{this.emit("elicitationCompleted",{serverName:this.serverName,elicitationId:i.params.elicitationId})})}resolveElicitationAction(t,i){if(i.aborted||t.reason===Xt||t.reason==="timeout")return"cancel";if(t.elicitation)return t.elicitation.action;return t.approved?"accept":"decline"}async createTransport(){let{type:t,command:i,args:n,env:s,cwd:e,url:r,headers:o,oauth:u}=this.config,d;if(u?.enabled){if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(!await this.oauthProvider.hasUsableCredentials())throw new zt(this.serverName);d=this.oauthProvider}if(t==="stdio"){if(!i)throw Error("stdio 传输需要 command 参数");let p={};for(let[c,M]of Object.entries(process.env))if(M!==void 0)p[c]=M;return new os({command:i,args:n||[],env:{...p,...s},cwd:e,stderr:"ignore"})}else if(t==="sse"){if(!r)throw Error("sse 传输需要 url 参数");return new ds(new URL(r),{requestInit:{headers:o},...u?.enabled?{fetch:xt}:{},...d?{authProvider:d}:{}})}else if(t==="http"){if(!r)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:p}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new p(new URL(r),{requestInit:{headers:o},...u?.enabled?{fetch:xt}:{},...d?{authProvider:d}:{}})}throw Error(`不支持的传输类型: ${t}`)}async refreshTools(t="manual"){if(this.toolRefreshRequested=!0,this.toolRefreshPromise)return this.toolRefreshPromise;let i=this.catalogGeneration,n=(t==="notification"?new Promise((s)=>{setTimeout(s,25).unref()}):Promise.resolve()).then(()=>this.runToolRefresh(t)).finally(()=>{if(i!==this.catalogGeneration||this.toolRefreshPromise!==n)return;let s=this.toolRefreshRequested;if(this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,s&&this.sdkClient)this.refreshTools("notification")});return this.toolRefreshPromise=n,n}async waitForToolRefresh(){while(this.toolRefreshPromise)await this.toolRefreshPromise}async runToolRefresh(t){let i=t;for(let n=0;n<3&&this.toolRefreshRequested;n++){this.toolRefreshRequested=!1;try{await this.fetchAndPublishTools(i)}catch(s){if(this.emit("toolsRefreshFailed",{serverName:this.serverName,reason:i,error:s instanceof Error?s:Error(String(s))}),i!=="notification")throw s;return}i="notification"}}async fetchAndPublishTools(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=[],s=new Set,e;for(let p=0;p<it;p++){let c=await i.listTools(e?{cursor:e}:void 0);if(n.push(...c.tools),n.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);if(e=c.nextCursor,!e)break;if(s.has(e))throw Error("MCP tool catalog returned a repeated cursor");if(s.add(e),p===it-1)throw Error(`MCP tool catalog exceeds ${it} pages`)}let r=Zi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing tools");let o=this.availableTools,u=Qi(o,r);if(this.tools=new Map(r.map((p)=>[p.name,p])),!nt(u))return;this.toolCatalogRevision++;let d={revision:this.toolCatalogRevision,reason:t,...u};this.emit("toolsUpdated",this.availableTools,d)}async refreshContentCatalogs(t="manual",i=["resources","prompts"]){let n=this.sdkClient?.getServerCapabilities();for(let r of i){if(r==="resources"&&n?.resources)this.requestedContentCatalogs.add(r);if(r==="prompts"&&n?.prompts)this.requestedContentCatalogs.add(r)}if(this.requestedContentCatalogs.size===0)return;if(this.contentRefreshPromise){if(t!=="notification")this.contentRefreshReason=t;return this.contentRefreshPromise}this.contentRefreshReason=t;let s=this.catalogGeneration,e=(t==="notification"?new Promise((r)=>{setTimeout(r,25).unref()}):Promise.resolve()).then(()=>this.runContentCatalogRefresh()).finally(()=>{if(s!==this.catalogGeneration||this.contentRefreshPromise!==e)return;let r=this.requestedContentCatalogs.size>0;if(this.contentRefreshPromise=void 0,this.contentRefreshReason="manual",r&&this.sdkClient)this.refreshContentCatalogs("notification")});return this.contentRefreshPromise=e,e}async waitForCatalogRefresh(){while(this.toolRefreshPromise||this.contentRefreshPromise)await Promise.all([this.toolRefreshPromise??Promise.resolve(),this.contentRefreshPromise??Promise.resolve()])}async runContentCatalogRefresh(){for(let t=0;t<3&&this.requestedContentCatalogs.size>0;t++){let i=[...this.requestedContentCatalogs];this.requestedContentCatalogs.clear();let n=this.contentRefreshReason;this.contentRefreshReason="notification";let s=[];for(let e of i)try{if(e==="resources")await this.fetchAndPublishResourceCatalog(n);else await this.fetchAndPublishPromptCatalog(n)}catch(r){let o=r instanceof Error?r:Error(String(r));s.push(o),this.emit("contentCatalogRefreshFailed",{serverName:this.serverName,catalog:e,reason:n,error:o})}if(s.length>0&&n!=="notification")throw AggregateError(s,`Failed to refresh MCP content catalogs for "${this.serverName}"`)}}async fetchAndPublishResourceCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("resource",q,(d)=>i.listResources(d?{cursor:d}:void 0),(d)=>d.resources),s=await this.fetchContentPages("resource template",K,(d)=>i.listResourceTemplates(d?{cursor:d}:void 0),(d)=>d.resourceTemplates),e=Ci(n),r=ki(s);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing resource catalogs");let o=I(this.resources,e,(d)=>d.uri),u=I(this.resourceTemplates,r,(d)=>d.uriTemplate);this.resources=e,this.resourceTemplates=r,await this.reconcileResourceSubscriptions(i),this.publishContentCatalogDelta("resources",t,o),this.publishContentCatalogDelta("resourceTemplates",t,u)}async fetchAndPublishPromptCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("prompt",W,(r)=>i.listPrompts(r?{cursor:r}:void 0),(r)=>r.prompts),s=Oi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing prompts");let e=I(this.prompts,s,(r)=>r.name);this.prompts=s,this.publishContentCatalogDelta("prompts",t,e)}async fetchContentPages(t,i,n,s){let e=[],r=new Set,o;for(let u=0;u<Pt;u++){let d=await n(o);if(e.push(...s(d)),e.length>i)throw Error(`MCP ${t} catalog exceeds ${i} entries`);if(o=d.nextCursor,!o)return e;if(r.has(o))throw Error(`MCP ${t} catalog returned a repeated cursor`);r.add(o)}throw Error(`MCP ${t} catalog exceeds ${Pt} pages`)}publishContentCatalogDelta(t,i,n){if(!Li(n))return;this.contentCatalogRevision++;let s={revision:this.contentCatalogRevision,kind:t,reason:i,...n};this.emit("contentCatalogUpdated",this.contentCatalog,s)}registerResourceNotificationHandler(t){t.setNotificationHandler(ys,(i)=>{let n=i.params.uri;if(this.sdkClient!==t||!this.activeResourceSubscriptions.has(n))return;this.contentCatalogRevision++,this.emit("resourceUpdated",{revision:this.contentCatalogRevision,serverName:this.serverName,uri:n})})}registerLoggingHandler(t){t.setNotificationHandler(ws,(i)=>{if(this.sdkClient!==t||!this.loggingPolicy.enabled||!pn(i.params.level,this.loggingPolicy.level))return;let n=Date.now();if(n-this.logWindowStartedAt>=1000)this.logWindowStartedAt=n,this.logEventsInWindow=0,this.logRateWarningEmitted=!1;if(this.logEventsInWindow>=rn){if(!this.logRateWarningEmitted)this.logRateWarningEmitted=!0,this.emit("log",un(1,{now:n}));return}this.logEventsInWindow++;let s=lt({level:i.params.level,logger:i.params.logger,data:i.params.data},{exposeDetails:this.runtimeOptions.exposeLogDetails,now:n});this.emit("log",s)})}async configureLogging(t){if(this.logWindowStartedAt=Date.now(),this.logEventsInWindow=0,this.logRateWarningEmitted=!1,!this.loggingPolicy.enabled||!t.getServerCapabilities()?.logging)return;try{await t.setLoggingLevel(this.loggingPolicy.level)}catch(i){if(this.sdkClient!==t)return;let n={serverName:this.serverName,level:this.loggingPolicy.level,error:k(i)};this.emit("loggingSetupFailed",n),this.emit("log",{...lt({level:"warning",logger:"blade.mcp.logging",data:`Failed to set MCP logging level: ${n.error}`},{exposeDetails:this.runtimeOptions.exposeLogDetails}),synthetic:!0})}}async setLoggingLevel(t){if(!on(t))throw Error("Invalid MCP logging level");let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!i.getServerCapabilities()?.logging)throw Error(`MCP server "${this.serverName}" does not support logging`);if(await i.setLoggingLevel(t),this.sdkClient!==i)throw Error("MCP client changed while setting logging level");this.loggingPolicy={enabled:!0,level:t},this.emit("loggingLevelChanged",{serverName:this.serverName,level:t})}async complete(t,i){let n=this.sdkClient;if(!n||this.status!=="connected")throw Error("MCP client is not connected");if(!n.getServerCapabilities()?.completions)throw Error(`MCP server "${this.serverName}" does not support completions`);if(this.completionCallsInFlight>=oi)throw Error(`MCP server "${this.serverName}" has too many completion requests`);let s=pi(t,this.contentCatalog);this.completionCallsInFlight++;try{let e=await n.complete(s,{signal:i,timeout:ht,maxTotalTimeout:ht});if(this.sdkClient!==n)throw Error("MCP client changed while completing an argument");return ui(e)}catch(e){if(i?.aborted)throw new DOMException(String(i.reason||"MCP completion cancelled"),"AbortError");throw e}finally{this.completionCallsInFlight--}}async readResource(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!this.resources.some((n)=>n.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);return gi(await i.readResource({uri:t}))}async getPrompt(t,i={}){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");let s=this.prompts.find((r)=>r.name===t);if(!s)throw Error(`MCP prompt "${t}" is not present in server "${this.serverName}" catalog`);let e=new Set(s.arguments.map((r)=>r.name));for(let[r,o]of Object.entries(i)){if(["__proto__","constructor","prototype"].includes(r))throw Error(`Unsafe argument "${r}" for MCP prompt "${t}"`);if(!e.has(r))throw Error(`Unknown argument "${r}" for MCP prompt "${t}"`);if(Buffer.byteLength(o)>16384)throw Error(`Argument "${r}" for MCP prompt "${t}" is too large`)}for(let r of s.arguments)if(r.required&&i[r.name]===void 0)throw Error(`Required argument "${r.name}" is missing for MCP prompt "${t}"`);return mi(await n.getPrompt({name:t,arguments:i}))}async setResourceSubscription(t,i){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");if(i){if(!this.resources.some((s)=>s.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);if(this.desiredResourceSubscriptions.has(t)&&this.activeResourceSubscriptions.has(t))return;if(!this.desiredResourceSubscriptions.has(t)&&this.desiredResourceSubscriptions.size>=at)throw Error(`MCP resource subscriptions exceed ${at}`);if(!n.getServerCapabilities()?.resources?.subscribe)throw Error(`MCP server "${this.serverName}" does not support resource subscriptions`);if(await n.subscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while subscribing to resource");this.desiredResourceSubscriptions.add(t),this.activeResourceSubscriptions.add(t);return}if(!this.desiredResourceSubscriptions.has(t))return;if(this.activeResourceSubscriptions.has(t)){if(await n.unsubscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while unsubscribing from resource")}this.activeResourceSubscriptions.delete(t),this.desiredResourceSubscriptions.delete(t)}async reconcileResourceSubscriptions(t){if(this.sdkClient!==t)return;let i=new Set(this.resources.map((n)=>n.uri));for(let n of this.activeResourceSubscriptions)if(!i.has(n))this.activeResourceSubscriptions.delete(n);if(!t.getServerCapabilities()?.resources?.subscribe){this.activeResourceSubscriptions.clear();return}for(let n of this.desiredResourceSubscriptions){if(!i.has(n)||this.activeResourceSubscriptions.has(n))continue;try{if(await t.subscribeResource({uri:n}),this.sdkClient!==t)return;this.activeResourceSubscriptions.add(n)}catch(s){this.emit("resourceSubscriptionRestoreFailed",{serverName:this.serverName,uri:n,error:k(s)})}}}setStatus(t){let i=this.status;if(i===t)return;this.status=t,this.emit("statusChanged",t,i)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer(t){return this.connect()}async disconnectFromServer(t){return this.disconnect()}async listResources(t){return structuredClone(this.resources)}async listResourceTemplates(){return structuredClone(this.resourceTemplates)}async listPrompts(){return structuredClone(this.prompts)}async listTools(t){return this.availableTools}}class O extends fs{runtimeOptions;static instance=null;servers=new Map;isDiscovering=!1;catalogRevision=0;contentCatalogRevision=0;connectionRevision=0;logRevision=0;instructionsRevision=0;logEntries=[];projectedTools=new Map;constructor(t={}){super();this.runtimeOptions=t}static getInstance(){if(!O.instance)O.instance=new O;return O.instance}static createIsolated(t={}){return new O(t)}async registerServer(t,i,n={}){if(this.servers.has(t))throw Error(`MCP服务器 "${t}" 已经注册`);let s=new Yt(i,t,i.healthCheck,this.runtimeOptions),e={config:i,client:s,status:"disconnected",tools:[],contentCatalog:{resources:[],resourceTemplates:[],prompts:[]},logging:s.logging};if(this.setupClientEventHandlers(s,e,t),this.servers.set(t,e),this.emit("serverRegistered",t,e),n.connect===!1)return;try{await this.connectServer(t)}catch(r){console.warn(`MCP服务器 "${t}" 连接失败:`,r)}}async unregisterServer(t){let i=this.servers.get(t);if(!i)return;try{await T.getInstance().cancelClient(i.client),await i.client.disconnect()}catch(n){console.warn(`断开MCP服务器 "${t}" 时出错:`,n)}this.servers.delete(t),this.logEntries=this.logEntries.filter((n)=>n.serverName!==t),this.emit("serverUnregistered",t)}async connectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status==="connected")return;try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async disconnectServer(t){let i=this.servers.get(t);if(!i)return;await T.getInstance().cancelClient(i.client),await i.client.disconnect(),i.connectedAt=void 0}async reconnectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await T.getInstance().cancelClient(i.client),await i.client.disconnect();try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async getAvailableTools(){return[...this.projectedTools.values()]}getCatalogSnapshot(){return{revision:this.catalogRevision,tools:[...this.projectedTools.values()]}}async waitForCatalogIdle(){await Promise.all([...this.servers.values()].map((t)=>t.client.waitForCatalogRefresh()))}getContentCatalogSnapshot(){let t=[],i=[],n=[];for(let[s,e]of this.servers){if(e.status!=="connected")continue;t.push(...e.contentCatalog.resources.map((r)=>({server:s,...structuredClone(r)}))),i.push(...e.contentCatalog.resourceTemplates.map((r)=>({server:s,...structuredClone(r)}))),n.push(...e.contentCatalog.prompts.map((r)=>({server:s,...structuredClone(r)})))}return{revision:this.contentCatalogRevision,resources:t,resourceTemplates:i,prompts:n}}getLogSnapshot(t,i={}){let n=Number.isSafeInteger(i.afterRevision)&&(i.afterRevision??0)>=0?i.afterRevision??0:0,s=Number.isSafeInteger(i.limit)&&(i.limit??0)>=1&&(i.limit??0)<=B?i.limit??B:B,e=this.logEntries.filter((r)=>r.revision>n&&(!t||r.serverName===t)).slice(-s).map((r)=>structuredClone(r));return{revision:this.logRevision,entries:e}}getInstructionsSnapshot(){let t=[];for(let[i,n]of this.servers){if(n.status!=="connected"||!n.instructions)continue;t.push({serverName:i,...structuredClone(n.instructions)})}return t.sort((i,n)=>i.serverName.localeCompare(n.serverName)),{revision:this.instructionsRevision,instructions:t}}async refreshContentCatalogs(t){if(t){await this.requireConnectedServer(t).client.refreshContentCatalogs("manual");return}await Promise.all([...this.servers.values()].filter((i)=>i.status==="connected").map((i)=>i.client.refreshContentCatalogs("manual")))}async readResource(t,i){return this.requireConnectedServer(t).client.readResource(i)}async getPrompt(t,i,n={}){return this.requireConnectedServer(t).client.getPrompt(i,n)}async complete(t,i,n){return this.requireConnectedServer(t).client.complete(i,n)}async startTask(t,i,n,s,e,r,o){let u=this.requireConnectedServer(t);if(!u.tools.some((d)=>d.name===i))throw Error(`MCP tool "${i}" is not present in server "${t}" catalog`);return T.getInstance().start({client:u.client,serverName:t,toolName:i,arguments:n,owner:s,interactionContext:e,signal:r,ttlMs:o})}listTasks(t,i){return T.getInstance().list(t,i)}getTask(t,i){return T.getInstance().get(t,i)}waitForTask(t,i,n,s){return T.getInstance().wait(t,i,n,s)}cancelTask(t,i,n){return T.getInstance().cancel(t,i,n)}async setResourceSubscription(t,i,n){await this.requireConnectedServer(t).client.setResourceSubscription(i,n)}async setServerLoggingLevel(t,i){let n=this.requireConnectedServer(t);await n.client.setLoggingLevel(i),n.logging=n.client.logging}async findTool(t){return this.projectedTools.get(t)??null}getToolsByServer(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return[];return i.tools.map((n)=>Tt(i.client,t,n,Lt(t,n.name),this.runtimeOptions.artifactWriter))}getServerStatus(t){return this.servers.get(t)||null}getAllServers(){return new Map(this.servers)}async getServerOAuthStatus(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);return i.client.getOAuthStatus()}async beginOAuthLogin(t,i={}){let n=this.servers.get(t);if(!n)throw Error(`MCP服务器 "${t}" 未注册`);let s=await n.client.beginOAuthLogin(i);this.emit("serverOAuthStatusChanged",t,"authorizing");let e=s.completion.then(async()=>{this.emit("serverOAuthCompleted",t),this.emit("serverOAuthStatusChanged",t,"authenticated");try{await this.reconnectServer(t)}catch(r){n.lastError=r instanceof Error?r:Error(String(r)),n.status="error",this.emit("serverError",t,n.lastError)}},(r)=>{throw n.lastError=r instanceof Error?r:Error(String(r)),this.emit("serverOAuthError",t,n.lastError),this.emit("serverOAuthStatusChanged",t,"error"),n.lastError});return e.catch(()=>{return}),{...s,completion:e}}async logoutOAuth(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await i.client.logoutOAuth(),i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.tools=[],this.emit("serverOAuthStatusChanged",t,"unauthenticated")}async refreshAllTools(){let t=[];for(let[i,n]of this.servers)if(n.status==="connected")t.push(this.refreshServerTools(i));await Promise.allSettled(t)}async refreshServerTools(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return;try{await i.client.refreshTools("manual")}catch(n){throw console.warn(`刷新服务器 "${t}" 工具列表失败:`,n),n}}setupClientEventHandlers(t,i,n){t.on("connected",(s)=>{if(i.status="connected",i.connectedAt=new Date,i.lastError=void 0,i.tools=t.availableTools,i.contentCatalog=t.contentCatalog,i.logging=t.logging,i.instructions=this.fitInstructionBudget(n,t.instructions),this.publishCatalog(n,"connection"),this.publishInitialContentCatalog(n,i.contentCatalog),i.instructions)this.publishInstructions(n,"added","connection",i.instructions);this.emit("serverConnected",n,s)}),t.on("disconnected",()=>{i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.recovery=void 0,this.invalidateServerProjection(n,i),this.emit("serverDisconnected",n)}),t.on("error",(s)=>{i.status="error",i.lastError=s,this.invalidateServerProjection(n,i),this.emit("serverError",n,s)}),t.on("connectionLifecycleChanged",(s)=>{if(i.recovery=structuredClone(s),s.phase==="reconnecting")i.status="reconnecting",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError,this.invalidateServerProjection(n,i);else if(s.phase==="recovered")i.status="connected",i.lastError=void 0;else i.status="error",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError;this.publishConnectionLifecycle(n,s)}),t.on("toolsUpdated",(s,e)=>{let r=i.tools.length;if(i.tools=s,i.status==="connected"&&e)this.publishCatalog(n,e.reason);this.emit("toolsUpdated",n,s,r)}),t.on("toolsRefreshFailed",(s)=>{this.emit("catalogRefreshFailed",{serverName:n,...s})}),t.on("contentCatalogUpdated",(s,e)=>{if(i.contentCatalog=s,i.status!=="connected")return;this.publishContentCatalogChange(n,e.kind,e.reason,{added:e.added,removed:e.removed,updated:e.updated})}),t.on("contentCatalogRefreshFailed",(s)=>{this.emit("contentCatalogRefreshFailed",{serverName:n,...s})}),t.on("resourceUpdated",(s)=>{if(i.status!=="connected")return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:n,uri:s.uri};this.emit("resourceUpdated",e)}),t.on("statusChanged",(s,e)=>{if(i.status=s,s==="reconnecting"&&e==="connected")i.connectedAt=void 0,this.invalidateServerProjection(n,i);this.emit("serverStatusChanged",n,s,e)}),t.on("loggingLevelChanged",()=>{i.logging=t.logging,this.emit("serverLoggingLevelChanged",n,i.logging.level)}),t.on("log",(s)=>{this.publishLog(n,s)})}publishLog(t,i){this.logRevision++;let n={revision:this.logRevision,serverName:t,...structuredClone(i)};this.logEntries.push(n);let s=0;for(let e=this.logEntries.length-1;e>=0;e--){if(this.logEntries[e]?.serverName!==t)continue;if(s++,s>Tn)this.logEntries.splice(e,1)}while(this.logEntries.length>B)this.logEntries.shift();this.emit("log",structuredClone(n))}invalidateServerProjection(t,i){let n=i.contentCatalog,s=i.instructions!==void 0;if(i.tools=[],i.contentCatalog={resources:[],resourceTemplates:[],prompts:[]},i.instructions=void 0,this.publishCatalog(t,"disconnection"),this.publishRemovedContentCatalog(t,n),s)this.publishInstructions(t,"removed","disconnection")}fitInstructionBudget(t,i){if(!i)return;let n=0;for(let[s,e]of this.servers){if(s===t)continue;n+=e.instructions?.projectedBytes??0}return bn(i,Math.max(0,En-n))}publishInstructions(t,i,n,s){this.instructionsRevision++;let e={revision:this.instructionsRevision,serverName:t,action:i,reason:n,...s?{instruction:structuredClone(s)}:{}};this.emit("instructionsChanged",e)}publishConnectionLifecycle(t,i){this.connectionRevision++;let n={revision:this.connectionRevision,serverName:t,...structuredClone(i)};this.emit("connectionLifecycleChanged",n)}publishCatalog(t,i){let n=new Map;for(let[u,d]of this.servers){if(d.status!=="connected")continue;for(let p of d.tools){let c=Lt(u,p.name);if(n.has(c))throw Error(`Duplicate projected MCP tool "${c}"`);n.set(c,Tt(d.client,u,p,c,this.runtimeOptions.artifactWriter))}}let s=new Map([...this.projectedTools].map(([u,d])=>[u,JSON.stringify(d.getFunctionDeclaration())])),e=new Map([...n].map(([u,d])=>[u,JSON.stringify(d.getFunctionDeclaration())])),r={added:[...n.keys()].filter((u)=>!this.projectedTools.has(u)).sort(),removed:[...this.projectedTools.keys()].filter((u)=>!n.has(u)).sort(),updated:[...n.keys()].filter((u)=>this.projectedTools.has(u)&&s.get(u)!==e.get(u)).sort()};if(this.projectedTools=n,!nt(r))return;this.catalogRevision++;let o={revision:this.catalogRevision,serverName:t,reason:i,tools:[...n.values()],...r};this.emit("catalogChanged",o)}publishInitialContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","connection",{added:i.resources.map((n)=>n.uri).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","connection",{added:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"prompts","connection",{added:i.prompts.map((n)=>n.name).sort(),removed:[],updated:[]})}publishRemovedContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","disconnection",{added:[],removed:i.resources.map((n)=>n.uri).sort(),updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","disconnection",{added:[],removed:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),updated:[]}),this.publishContentCatalogChange(t,"prompts","disconnection",{added:[],removed:i.prompts.map((n)=>n.name).sort(),updated:[]})}publishContentCatalogChange(t,i,n,s){if(s.added.length===0&&s.removed.length===0&&s.updated.length===0)return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:t,kind:i,reason:n,...s};this.emit("contentCatalogChanged",e)}requireConnectedServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status!=="connected")throw Error(`MCP服务器 "${t}" 未连接`);return i}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(t){let i=Object.entries(t).map(([n,s])=>this.registerServer(n,s).catch((e)=>{return console.warn(`注册MCP服务器 "${n}" 失败:`,e),e}));await Promise.allSettled(i)}getStatistics(){let t=0,i=0,n=0;for(let s of this.servers.values())if(s.status==="connected")t++,i+=s.tools.length;else if(s.status==="error")n++;return{totalServers:this.servers.size,connectedServers:t,errorServers:n,totalTools:i,isDiscovering:this.isDiscovering}}async disconnectAll(){let t=[];for(let[i,n]of this.servers)t.push(T.getInstance().cancelClient(n.client).then(()=>n.client.disconnect()).catch((s)=>{console.warn(`断开 MCP 服务器 "${i}" 时出错:`,s)}));await Promise.allSettled(t),this.servers.clear(),this.projectedTools.clear(),this.logEntries=[]}}
25
- export{jt as Ca,T as Da,jn as Ea,vs as Fa,te as Ga,Fi as Ha,Lt as Ia,ts as Ja,O as Ka};
25
+ export{jt as Da,T as Ea,jn as Fa,vs as Ga,te as Ha,Fi as Ia,Lt as Ja,ts as Ka,O as La};
@@ -1,4 +1,4 @@
1
- import{Z as P}from"./chunk-fys5xx87.js";import{wb as K}from"./chunk-gbjk078c.js";import{Td as B,ad as G,bd as N,cd as S,dd as O,ed as s}from"./chunk-bxjc7pg7.js";import{ce as j}from"./chunk-qdv0n8yt.js";import{df as q}from"./chunk-pshyn3yy.js";import{Bf as v}from"./chunk-90q4206c.js";import{Ui as z}from"./chunk-rkdxqx8m.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{_ as P}from"./chunk-x4t1v4rb.js";import{xb as K}from"./chunk-150w9kq4.js";import{Ud as B,bd as G,cd as N,dd as S,ed as O,fd as s}from"./chunk-sefdw1mm.js";import{de as j}from"./chunk-7dykmcjj.js";import{ef as q}from"./chunk-ye4wyq1k.js";import{Cf as v}from"./chunk-j2pgrrkb.js";import{Vi as z}from"./chunk-spxb931p.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -0,0 +1 @@
1
+ import{$e as m,Pe as a,Qe as b,Re as c,Se as d,Te as e,Ue as f,Ve as g,We as h,Xe as i,Ye as j,Ze as k,_e as l,af as n,bf as o,cf as p,df as q}from"./chunk-1qbq7x98.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-7k72dxwe.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,3 +1,3 @@
1
- import{g as i}from"./chunk-xv3a1se1.js";import{Sh as s}from"./chunk-ecd727xh.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{g as i}from"./chunk-nq0w1j1a.js";import{Th as s}from"./chunk-kzzty3v5.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -1,2 +1,2 @@
1
- import{qg as Q}from"./chunk-935v0gpc.js";import{Eh as F,Gh as k,Jh as G}from"./chunk-6k5k40p8.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
- export{Z as we};
1
+ import{rg as Q}from"./chunk-85bamng3.js";import{Fh as F,Hh as k,Kh as G}from"./chunk-9fgkg1vr.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
+ export{Z as xe};
@@ -1,2 +1,2 @@
1
- import{S as I}from"./chunk-fys5xx87.js";import{Td as M}from"./chunk-bxjc7pg7.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
1
+ import{S as I}from"./chunk-x4t1v4rb.js";import{Ud as M}from"./chunk-sefdw1mm.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
2
2
  export{C as y,$ as z,V as A,x as B,i as C,K as D};
@@ -1,4 +1,4 @@
1
- import{e as q3,f as z3}from"./chunk-3pwq56je.js";import{i as OX,j as _X,k as NX}from"./chunk-kk6rg27n.js";import{x as M8}from"./chunk-mnkdxt1v.js";import{$ as y9,F as NY,J as RX,L as h4,M as f4,N as ZY,T as l9,U as r9,Y as E$,_ as M9,ba as a9,da as v2,ea as T3,fa as C3,ia as I3,ja as S3,na as dJ,oa as DY,qa as kY,ra as fY,sa as TX,ta as V9,va as j9,xa as FY}from"./chunk-fys5xx87.js";import"./chunk-ypbnczjp.js";import{Fa as l6,Ga as r6,Ha as a6,Ka as yX}from"./chunk-z9g2x0vm.js";import{Ma as d9}from"./chunk-23v8c9b8.js";import{Gb as c9,Pb as T4,tb as x9,ub as u9}from"./chunk-gbjk078c.js";import{_b as E2}from"./chunk-cnhw5mqv.js";import{Ed as C9,Fd as R4,Gd as I9,Id as L8,Qd as f2,Td as f0,dd as E9,sd as b9,xd as P9}from"./chunk-bxjc7pg7.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{we as qX}from"./chunk-bksfg23m.js";import{Ae as n$,xe as h2,ye as y8}from"./chunk-k3tqna1w.js";import"./chunk-ng96f4xd.js";import{Ee as t1,Fe as K$,Ge as R1,He as GJ,Ie as H8,Je as B9,Ke as O6,Le as CJ,Me as J3,Ne as _6,Oe as J2,Pe as Y$,Qe as PX,Re as U$,Se as GX,Te as Z4,Ue as V2,Xe as v9,cf as a0}from"./chunk-kr8rv2b9.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import{sf as IJ}from"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-gjw8100g.js";import{Ef as C8,Hf as x3,Mf as R3,Vf as MX}from"./chunk-90q4206c.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import{rg as OJ,tg as y$}from"./chunk-swtap0bs.js";import"./chunk-eyb9psbc.js";import{Ah as y3,Bh as bX,vh as AX}from"./chunk-y21nw7g1.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import{Kh as K2,Lh as w8,Nh as _J}from"./chunk-p3m1jyg5.js";import{Sh as X$}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import{pi as BX,si as y1}from"./chunk-dvv28pkc.js";import{ui as K3,vi as U3,yi as Q1}from"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import{Ki as n6}from"./chunk-53aapkv1.js";import{Ni as cJ}from"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import{Yi as y4}from"./chunk-rkdxqx8m.js";import{_i as zJ}from"./chunk-tf7ezqew.js";import{useMemoizedFn as H4}from"ahooks";import{useEffect as IK,useState as W4}from"react";import{useMemoizedFn as t0}from"ahooks";import UX from"ansi-escapes";import{Box as W1,useStdout as bK}from"ink";import{useEffect as L1,useMemo as PK,useRef as t2,useState as MK}from"react";import{useShallow as IX}from"zustand/react/shallow";import{useStore as CX}from"zustand";function X0($){return CX(J2,$)}var SX=[],Y2=()=>X0(($)=>$.session.sessionId),o$=()=>X0(($)=>$.session.workspaceRoot),J8=()=>X0(($)=>$.session.messages),lJ=()=>X0(($)=>$.session.clearCount),rJ=()=>X0(($)=>$.session.isCompacting),aJ=()=>X0(($)=>$.session.tokenUsage.estimatedCostUsd),iJ=()=>X0(($)=>{let{totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}=$.session.tokenUsage;return dJ({totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}).hitRate}),oJ=()=>X0(($)=>$.session.providerCircuit),nJ=()=>X0(($)=>$.session.providerAdmission),tJ=()=>X0(($)=>$.session.providerRetry),sJ=()=>X0(($)=>$.session.providerStall),eJ=()=>X0(($)=>$.session.actionStationarity),P1=()=>X0(($)=>$.session.actions),$9=()=>X0(($)=>{let{totalTokens:J,maxContextTokens:X}=$.session.tokenUsage;if(X<=0)return 100;let Y=Math.max(0,100-J/X*100);return Math.round(Y)}),J9=()=>X0(($)=>$.app.initializationStatus),Y9=()=>X0(($)=>$.app.initializationError),Y8=()=>X0(($)=>$.app.activeModal),X9=()=>X0(($)=>$.app.tasks),Z9=()=>X0(($)=>$.app.modelEditorTarget),Q9=()=>X0(($)=>$.app.sessionSelectorData),K9=()=>X0(($)=>$.app.awaitingSecondCtrlC),M1=()=>X0(($)=>$.app.actions),X8=()=>X0(($)=>$.app.sideConversation),U9=()=>X0(($)=>$.app.teams),Z8=()=>X0(($)=>$.app.initializationStatus==="ready"),G9=()=>X0(($)=>$.app.tasks.length>0),X2=()=>X0(($)=>$.config.config?.permissionMode||"default"),q9=()=>X0(($)=>$.config.config?.models??SX),Q8=()=>X0(($)=>{let J=$.config.config;if(!J)return;let X=J.currentModelId;return J.models.find((Z)=>Z.id===X)??J.models[0]}),K8=()=>X0(($)=>$.config.config?.currentModelId),z9=()=>X0(($)=>$.config.config?.agentTeamsEnabled===!0),P0=()=>X0(($)=>{return K$.getTheme()}),O9=()=>X0(($)=>$.config.config?.codeTheme??"default"),r0=()=>X0(($)=>$.focus.currentFocus),_9=()=>X0(($)=>$.focus.actions),Z2=()=>X0(($)=>$.command.isProcessing),N9=()=>X0(($)=>$.command.actions),Q2=()=>X0(($)=>$.command.pendingCommands),F9=()=>X0(($)=>$.command.recoveredSteeringCount),U8=()=>X0(($)=>$.app.reasoningEffort!=="off"),G8=()=>X0(($)=>$.app.reasoningEffort),q8=()=>X0(($)=>$.app.serviceTier),z8=()=>X0(($)=>$.app.responseVerbosity),O8=()=>X0(($)=>$.app.communicationStyle),_8=()=>X0(($)=>$.session.currentThinkingContent),H9=()=>X0(($)=>$.session.thinkingExpanded),N8=()=>X0(($)=>$.session.currentStreamingMessageId),F8=()=>X0(IX(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),W9=()=>X0(($)=>$.session.finalizingStreamingMessageId),L9=()=>X0(($)=>$.session.historyExpanded),w9=()=>X0(($)=>$.session.expandedMessageCount);import{useMemoizedFn as Z1}from"ahooks";import{useEffect as g1,useMemo as tX,useRef as T8}from"react";class L4{options;requested=!1;scheduled=!1;inFlight=!1;disposed=!1;generation=0;activeRunController=null;scheduleCallback;constructor($){this.options=$;this.scheduleCallback=$.schedule??queueMicrotask}request(){if(this.disposed)return;this.requested=!0,this.scheduleIfRunnable()}notifyIdle(){this.scheduleIfRunnable()}dispose(){this.disposed=!0,this.requested=!1,this.scheduled=!1,this.generation++,this.activeRunController?.abort("pending-resume-coordinator-disposed"),this.activeRunController=null}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduled||this.inFlight||!this.options.canRun())return;this.scheduled=!0;let $=this.generation;this.scheduleCallback(()=>{if(this.disposed||$!==this.generation)return;this.scheduled=!1,this.flush()})}async flush(){if(this.disposed||this.inFlight||!this.requested||!this.options.canRun())return;this.requested=!1,this.inFlight=!0;let $=new AbortController;this.activeRunController=$;let J="completed";try{J=await this.options.run($.signal)}finally{if(this.activeRunController===$)this.activeRunController=null;if(this.inFlight=!1,J==="deferred")this.requested=!0;this.scheduleIfRunnable()}}}class S2{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)H8(J,$.extraContent);B9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function kX($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let K=JSON.parse(Y.responseBody)?.error?.message;if(K){let U=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function fX($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function vX($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function W8($){let J=fX($),X=vX($),Y;if(X)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=kX($);return{displayMessage:Y,isAbort:J,isVisionNotSupported:X}}import{appendFileSync as DX,mkdirSync as VX,writeFileSync as jX}from"node:fs";import EX from"node:os";import w4 from"node:path";var A9=null;function hX(){let $=process.env.BLADE_STORAGE_ROOT||w4.join(EX.homedir(),".blade");return w4.join($,"logs","stream-debug.log")}function gX($){if(A9===$)return;let J=w4.dirname($);VX(J,{recursive:!0,mode:493}),jX($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{e as q3,f as z3}from"./chunk-anjpwev3.js";import{i as OX,j as _X,k as NX}from"./chunk-v95hk3fw.js";import{x as M8}from"./chunk-2w10er3y.js";import{$ as M9,F as NY,J as RX,L as h4,M as f4,N as ZY,T as l9,U as r9,Z as E$,aa as y9,ca as a9,ea as v2,fa as T3,ga as C3,ja as I3,ka as S3,oa as dJ,pa as DY,ra as kY,sa as fY,ta as TX,ua as V9,wa as j9,ya as FY}from"./chunk-x4t1v4rb.js";import"./chunk-dabq8kdx.js";import{Ga as l6,Ha as r6,Ia as a6,La as yX}from"./chunk-2v8fyvmh.js";import{Na as d9}from"./chunk-fpjhg6ce.js";import{Hb as c9,Qb as T4,ub as x9,vb as u9}from"./chunk-150w9kq4.js";import{$b as E2}from"./chunk-sca5q3tt.js";import{Fd as C9,Gd as R4,Hd as I9,Jd as L8,Rd as f2,Ud as f0,ed as E9,td as b9,yd as P9}from"./chunk-sefdw1mm.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{xe as qX}from"./chunk-3jqd18d8.js";import{Be as n$,ye as h2,ze as y8}from"./chunk-y1n8nf5w.js";import"./chunk-twdfyk78.js";import{Fe as t1,Ge as K$,He as R1,Ie as GJ,Je as H8,Ke as B9,Le as O6,Me as CJ,Ne as J3,Oe as _6,Pe as J2,Qe as Y$,Re as PX,Se as U$,Te as GX,Ue as Z4,Ve as V2,Ye as v9,df as a0}from"./chunk-1qbq7x98.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import{tf as IJ}from"./chunk-b41den40.js";import"./chunk-8qp8v96d.js";import"./chunk-6h0kgpgv.js";import{Ff as C8,If as x3,Nf as R3,Wf as MX}from"./chunk-j2pgrrkb.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import{sg as OJ,ug as y$}from"./chunk-t169d8dc.js";import"./chunk-2t6b962t.js";import{Bh as y3,Ch as bX,wh as AX}from"./chunk-7k72dxwe.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import{Lh as K2,Mh as w8,Oh as _J}from"./chunk-pykxe413.js";import{Th as X$}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import{qi as BX,ti as y1}from"./chunk-w4xqaw4h.js";import{vi as K3,wi as U3,zi as Q1}from"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import{Li as n6}from"./chunk-5hmeb6yk.js";import{Oi as cJ}from"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import{Zi as y4}from"./chunk-spxb931p.js";import{$i as zJ}from"./chunk-m7b779kd.js";import{useMemoizedFn as H4}from"ahooks";import{useEffect as IK,useState as W4}from"react";import{useMemoizedFn as t0}from"ahooks";import UX from"ansi-escapes";import{Box as W1,useStdout as bK}from"ink";import{useEffect as L1,useMemo as PK,useRef as t2,useState as MK}from"react";import{useShallow as IX}from"zustand/react/shallow";import{useStore as CX}from"zustand";function X0($){return CX(J2,$)}var SX=[],Y2=()=>X0(($)=>$.session.sessionId),o$=()=>X0(($)=>$.session.workspaceRoot),J8=()=>X0(($)=>$.session.messages),lJ=()=>X0(($)=>$.session.clearCount),rJ=()=>X0(($)=>$.session.isCompacting),aJ=()=>X0(($)=>$.session.tokenUsage.estimatedCostUsd),iJ=()=>X0(($)=>{let{totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}=$.session.tokenUsage;return dJ({totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}).hitRate}),oJ=()=>X0(($)=>$.session.providerCircuit),nJ=()=>X0(($)=>$.session.providerAdmission),tJ=()=>X0(($)=>$.session.providerRetry),sJ=()=>X0(($)=>$.session.providerStall),eJ=()=>X0(($)=>$.session.actionStationarity),P1=()=>X0(($)=>$.session.actions),$9=()=>X0(($)=>{let{totalTokens:J,maxContextTokens:X}=$.session.tokenUsage;if(X<=0)return 100;let Y=Math.max(0,100-J/X*100);return Math.round(Y)}),J9=()=>X0(($)=>$.app.initializationStatus),Y9=()=>X0(($)=>$.app.initializationError),Y8=()=>X0(($)=>$.app.activeModal),X9=()=>X0(($)=>$.app.tasks),Z9=()=>X0(($)=>$.app.modelEditorTarget),Q9=()=>X0(($)=>$.app.sessionSelectorData),K9=()=>X0(($)=>$.app.awaitingSecondCtrlC),M1=()=>X0(($)=>$.app.actions),X8=()=>X0(($)=>$.app.sideConversation),U9=()=>X0(($)=>$.app.teams),Z8=()=>X0(($)=>$.app.initializationStatus==="ready"),G9=()=>X0(($)=>$.app.tasks.length>0),X2=()=>X0(($)=>$.config.config?.permissionMode||"default"),q9=()=>X0(($)=>$.config.config?.models??SX),Q8=()=>X0(($)=>{let J=$.config.config;if(!J)return;let X=J.currentModelId;return J.models.find((Z)=>Z.id===X)??J.models[0]}),K8=()=>X0(($)=>$.config.config?.currentModelId),z9=()=>X0(($)=>$.config.config?.agentTeamsEnabled===!0),P0=()=>X0(($)=>{return K$.getTheme()}),O9=()=>X0(($)=>$.config.config?.codeTheme??"default"),r0=()=>X0(($)=>$.focus.currentFocus),_9=()=>X0(($)=>$.focus.actions),Z2=()=>X0(($)=>$.command.isProcessing),N9=()=>X0(($)=>$.command.actions),Q2=()=>X0(($)=>$.command.pendingCommands),F9=()=>X0(($)=>$.command.recoveredSteeringCount),U8=()=>X0(($)=>$.app.reasoningEffort!=="off"),G8=()=>X0(($)=>$.app.reasoningEffort),q8=()=>X0(($)=>$.app.serviceTier),z8=()=>X0(($)=>$.app.responseVerbosity),O8=()=>X0(($)=>$.app.communicationStyle),_8=()=>X0(($)=>$.session.currentThinkingContent),H9=()=>X0(($)=>$.session.thinkingExpanded),N8=()=>X0(($)=>$.session.currentStreamingMessageId),F8=()=>X0(IX(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),W9=()=>X0(($)=>$.session.finalizingStreamingMessageId),L9=()=>X0(($)=>$.session.historyExpanded),w9=()=>X0(($)=>$.session.expandedMessageCount);import{useMemoizedFn as Z1}from"ahooks";import{useEffect as g1,useMemo as tX,useRef as T8}from"react";class L4{options;requested=!1;scheduled=!1;inFlight=!1;disposed=!1;generation=0;activeRunController=null;scheduleCallback;constructor($){this.options=$;this.scheduleCallback=$.schedule??queueMicrotask}request(){if(this.disposed)return;this.requested=!0,this.scheduleIfRunnable()}notifyIdle(){this.scheduleIfRunnable()}dispose(){this.disposed=!0,this.requested=!1,this.scheduled=!1,this.generation++,this.activeRunController?.abort("pending-resume-coordinator-disposed"),this.activeRunController=null}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduled||this.inFlight||!this.options.canRun())return;this.scheduled=!0;let $=this.generation;this.scheduleCallback(()=>{if(this.disposed||$!==this.generation)return;this.scheduled=!1,this.flush()})}async flush(){if(this.disposed||this.inFlight||!this.requested||!this.options.canRun())return;this.requested=!1,this.inFlight=!0;let $=new AbortController;this.activeRunController=$;let J="completed";try{J=await this.options.run($.signal)}finally{if(this.activeRunController===$)this.activeRunController=null;if(this.inFlight=!1,J==="deferred")this.requested=!0;this.scheduleIfRunnable()}}}class S2{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)H8(J,$.extraContent);B9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function kX($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let K=JSON.parse(Y.responseBody)?.error?.message;if(K){let U=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function fX($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function vX($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function W8($){let J=fX($),X=vX($),Y;if(X)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=kX($);return{displayMessage:Y,isAbort:J,isVisionNotSupported:X}}import{appendFileSync as DX,mkdirSync as VX,writeFileSync as jX}from"node:fs";import EX from"node:os";import w4 from"node:path";var A9=null;function hX(){let $=process.env.BLADE_STORAGE_ROOT||w4.join(EX.homedir(),".blade");return w4.join($,"logs","stream-debug.log")}function gX($){if(A9===$)return;let J=w4.dirname($);VX(J,{recursive:!0,mode:493}),jX($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),A9=$}function B4($,J,X){try{let Y=hX();gX(Y);let Z=new Date().toISOString(),Q=X?` | ${JSON.stringify(X)}`:"",K=`[${Z}] [${$}] ${J}${Q}
3
3
  `;DX(Y,K)}catch{}}var k2=y1("UI");function b4($,J){if(J.state==="requires_attention"){let X=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:X?"An interrupted tool may have partially completed":"A completed tool may already have changed external state",detail:`${J.turnId} · inspect workspace, processes, and external state before retrying`});return}$.addToolMessage(J.state==="completed"?"Recovered completed turn":"Resuming interrupted turn",{toolName:"Runtime Recovery",phase:"complete",summary:J.state==="completed"?"The durable final response was recovered":"No tool execution was recorded before interruption",detail:J.turnId})}function R9($,J){let X=$.streamSession??new S2({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)});return(Y)=>{switch(Y.kind){case"content_delta":if(!X.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=Y.delta.length,B4("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:Y.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(Y.delta);break;case"thinking_delta":if(!X.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(Y.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),k2.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:X.isFinalized,signalAborted:$.signal.aborted}),B4("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:X.isFinalized,signalAborted:$.signal.aborted}),X.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),X.discard();break;case"provider_admission":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderAdmission(Y.phase==="queued"?Q:null);break}case"provider_circuit":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderCircuit(Y.phase==="closed"?null:Q);break}case"provider_retry":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderRetry(Y.phase==="recovered"?null:Q);break}case"provider_stall":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderStall(Y.phase==="detected"?Q:null);break}case"action_stationarity":{let{kind:Z,...Q}=Y;$.sessionActions.setActionStationarity(Y.phase==="recovered"?null:Q);break}case"turn_recovery":{b4($.sessionActions,Y.assessment);break}case"tool_start":{let Z=Y.toolCall;if(!("function"in Z))break;if(Z.function.name===L8)break;if(k2.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:Y.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let Q=JSON.parse(Z.function.arguments),K=M9(Z.function.name,Q);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:Q})}catch(Q){k2.error("[loopEventHandler] onToolStart error:",Q)}break}case"tool_progress":{let Z=Y.toolCall;if(!("function"in Z))break;if(Z.function.name===L8)break;let Q=Y.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((Y.update.progress??0)/Y.update.total*100)))}%`:"",K=`${Z.function.name}${Q}: ${Y.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...Y.update.admission?{admission:Y.update.admission}:{}});break}case"tool_result":{let Z=Y.toolCall;if(!("function"in Z))break;if(Z.function.name===L8)break;k2.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:Y.result.success});let Q=P9(y9(Z.function.name,Y.result),b9);$.sessionActions.addToolMessage(Q.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:Q.summary,detail:Q.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(Y.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(Y.usage);break;case"compaction":if($.sessionActions.setCompacting(Y.phase==="start"),Y.phase==="end"){if($.sessionActions.resetContextUsage(),Y.outcome!=="failed")J.compactionCount=(J.compactionCount??0)+1}break;case"turn_start":k2.debug("[loopEventHandler] turn_start",{turn:Y.turn,maxTurns:Y.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:Y.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),X.startTurn();break;case"task_update":$.appActions.setTasks(Y.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(Y.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${Y.revision}: +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[Y.added.length>0?`Added: ${Y.added.join(", ")}`:"",Y.removed.length>0?`Removed: ${Y.removed.join(", ")}`:"",Y.updated.length>0?`Updated: ${Y.updated.join(", ")}`:""].filter(Boolean).join(`
4
4
  `)});break}case"mcp_content_changed":{let Z=`MCP ${Y.contentKind} r${Y.revision}: +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[Y.added.length>0?`Added: ${Y.added.join(", ")}`:"",Y.removed.length>0?`Removed: ${Y.removed.join(", ")}`:"",Y.updated.length>0?`Updated: ${Y.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -1,6 +1,6 @@
1
- import{we as s}from"./chunk-bksfg23m.js";import{Pe as o}from"./chunk-kr8rv2b9.js";import{$g as y,Ah as l,Bh as n,ah as D,ch as N,eh as j,fh as F,hh as R,lh as E,mh as _,nh as f,oh as C,qh as S,rh as m,vh as c}from"./chunk-y21nw7g1.js";import{Ch as Y}from"./chunk-4w4wjm49.js";import{Eh as x,Gh as k,Jh as Z}from"./chunk-6k5k40p8.js";import{Qh as X}from"./chunk-ecd727xh.js";import{$h as P,Uh as h,Vh as A,ai as T,ci as $,di as U,ei as G,gi as L,hi as M,ji as O,ki as I}from"./chunk-x05zyqzf.js";import{si as d}from"./chunk-dvv28pkc.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{xe as s}from"./chunk-3jqd18d8.js";import{Qe as o}from"./chunk-1qbq7x98.js";import{Bh as l,Ch as n,ah as y,bh as D,dh as N,fh as j,gh as F,ih as R,mh as E,nh as _,oh as f,ph as C,rh as S,sh as m,wh as c}from"./chunk-7k72dxwe.js";import{Dh as Y}from"./chunk-kz15jy62.js";import{Fh as x,Hh as k,Kh as Z}from"./chunk-9fgkg1vr.js";import{Rh as X}from"./chunk-kzzty3v5.js";import{Vh as h,Wh as A,ai as P,bi as T,di as $,ei as U,fi as G,hi as L,ii as M,ki as O,li as I}from"./chunk-9jtjq50j.js";import{ti as d}from"./chunk-w4xqaw4h.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
5
  `),process.exit(1)}};function r(q){if(q.continue&&q.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(q.forkSession&&!q.continue&&!q.resume)throw Error("--fork-session requires --resume or --continue");if(q.sessionId&&(q.continue||q.resume)&&!q.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var Ak=(q)=>{if(q.jsonSchema&&q.outputSchema)throw Error("--json-schema cannot be combined with --output-schema");if((q.jsonSchema||q.outputSchema)&&!q.print&&!q.headless)throw Error("--json-schema and --output-schema can only be used with --print or --headless");if(q.outputFormat&&q.outputFormat!=="text"&&!q.print&&!q.headless)throw Error("--output-format can only be used with --print or --headless");if(q.headless&&q.outputFormat&&!["text","jsonl"].includes(q.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${q.outputFormat}". Use --print for json|stream-json support.`);if(q.print&&q.outputFormat&&!["text","json","stream-json"].includes(q.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${q.outputFormat}". Use --headless for jsonl support.`);if(q.inputFormat==="stream-json"&&q.print)Q.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
- export{Dk as te,hk as ue,Ak as ve};
6
+ export{Dk as ue,hk as ve,Ak as we};
@@ -0,0 +1 @@
1
+ import{Rf as a,Sf as b,Tf as c,Uf as d,Vf as e,Wf as f,Xf as g,Yf as h,Zf as i,_f as j}from"./chunk-j2pgrrkb.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-t169d8dc.js";import"./chunk-2t6b962t.js";import"./chunk-7k72dxwe.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1,2 +1,2 @@
1
- import{pd as C}from"./chunk-bxjc7pg7.js";import{jh as F,kh as L}from"./chunk-y21nw7g1.js";import{Mutex as G}from"async-mutex";class $ extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(j){super("Session runtime capacity is full");this.limit=j;this.name="SessionRuntimeCapacityError"}}class X extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class W extends Error{constructor(j){super(`Session runtime residency already owns key: ${j}`);this.name="SessionRuntimeResidencyConflictError"}}class U{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new G;nextGeneration=1;closed=!1;constructor(j){if(!F(j.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!L(j.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=j.maxResident,this.idleMs=j.idleMs,this.now=j.now??Date.now}acquire(j){let q=this.residents.get(j);if(!q||q.poisoned)return;return q.pins++,q.lastUsedAt=this.now(),this.createLease(q)}owns(j,q){let z=this.residents.get(j);return Boolean(z&&(q===void 0||z.value===q))}async reserve(j,q){if(!j.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new X;if(this.residents.has(j)||this.reservations.has(j))throw new W(j);while(this.retainedCount()>=this.maxResident){if(!q.allowEviction)throw new $(this.maxResident);let H=this.oldestEvictableWebResident();if(!H)throw new $(this.maxResident);await this.disposeResident(H,!0)}let z={generation:this.allocateGeneration(),surface:q.surface};return this.reservations.set(j,z),this.createReservation(j,z)})}async remove(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q)return!1;if(z.pins>0)return!1;return await this.disposeResident(z,!0),!0})}async forget(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q||z.pins>0)return!1;return this.residents.delete(j),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let j=0;while(!0){let q=this.oldestIdleWebResident();if(!q)return j;await this.disposeResident(q,!0),j++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let j;for(let q of[...this.residents.values()])try{await this.disposeResident(q,!1)}catch(z){j??=z}if(this.residents.clear(),j!==void 0)throw j})}getStats(){let j=0;for(let q of this.residents.values())if(q.pins>0)j++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:j,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let j=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,j}createReservation(j,q){let z=!1;return{commit:(H)=>{if(z)throw new W(j);if(H.key!==j||H.surface!==q.surface||this.reservations.get(j)!==q||this.closed)throw this.reservations.delete(j),z=!0,this.closed?new X:new W(j);this.reservations.delete(j);let J={...H,generation:q.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(j,J),z=!0,this.createLease(J)},cancel:()=>{if(z)return;if(this.reservations.get(j)===q)this.reservations.delete(j);z=!0}}}createLease(j){let q=!1;return{value:j.value,release:()=>{if(q)return;q=!0;let z=this.residents.get(j.key);if(z!==j||z.generation!==j.generation)return;z.pins=Math.max(0,z.pins-1),z.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((j)=>this.canEvict(j))}oldestIdleWebResident(){let j=this.now();return this.sortedWebResidents().find((q)=>j-q.lastUsedAt>=this.idleMs&&this.canEvict(q))}sortedWebResidents(){return[...this.residents.values()].filter((j)=>j.surface==="web").sort((j,q)=>j.lastUsedAt-q.lastUsedAt||j.generation-q.generation)}canEvict(j){if(j.pins>0||j.poisoned)return!1;try{return j.canEvict()}catch{return!1}}async disposeResident(j,q){if(this.residents.get(j.key)!==j)return;this.residents.delete(j.key);try{await j.dispose()}catch(z){if(q&&!this.closed&&!this.residents.has(j.key))j.lastUsedAt=this.now(),j.poisoned=!0,this.residents.set(j.key,j);throw z}}}import{createHash as B}from"node:crypto";var P=4,b=1000,Y=4000,D=120000,O=0.2;function w(j){try{return C(j)&&j.retryable}catch{return!1}}function N(j,q){let z=Number.isSafeInteger(q)&&q>0?q:1,H=z-1,J=Math.min(b*2**H,Y),K=B("sha256").update(`${j}\x00${z}`).digest().readUInt32BE(0)/4294967295,Q=1-O+2*O*K;return Math.min(Y,Math.max(0,Math.round(J*Q)))}function _(j){let q=N(j.sessionIdentity,j.failedAttempt),z=j.evidence,H=j.workStillPending===!0&&z!==void 0&&w(z.taskFailure)&&z.outputStarted===!1&&z.toolExecutionStarted===!1&&Number.isInteger(z.toolCallsCount)&&z.toolCallsCount===0,J=Number.isSafeInteger(j.failedAttempt)&&j.failedAttempt>0&&j.failedAttempt<P,Z=j.now??Date.now(),K=Z-j.recoveryStartedAt,Q=Number.isFinite(Z)&&Number.isFinite(j.recoveryStartedAt)&&Number.isFinite(K)&&K>=0&&K+q<=D;return{phase:H?J&&Q?"retry_scheduled":"exhausted":"failed",delayMs:q,retryable:H,withinAttemptBudget:J,withinTimeBudget:Q}}
1
+ import{qd as C}from"./chunk-sefdw1mm.js";import{kh as F,lh as L}from"./chunk-7k72dxwe.js";import{Mutex as G}from"async-mutex";class $ extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(j){super("Session runtime capacity is full");this.limit=j;this.name="SessionRuntimeCapacityError"}}class X extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class W extends Error{constructor(j){super(`Session runtime residency already owns key: ${j}`);this.name="SessionRuntimeResidencyConflictError"}}class U{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new G;nextGeneration=1;closed=!1;constructor(j){if(!F(j.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!L(j.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=j.maxResident,this.idleMs=j.idleMs,this.now=j.now??Date.now}acquire(j){let q=this.residents.get(j);if(!q||q.poisoned)return;return q.pins++,q.lastUsedAt=this.now(),this.createLease(q)}owns(j,q){let z=this.residents.get(j);return Boolean(z&&(q===void 0||z.value===q))}async reserve(j,q){if(!j.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new X;if(this.residents.has(j)||this.reservations.has(j))throw new W(j);while(this.retainedCount()>=this.maxResident){if(!q.allowEviction)throw new $(this.maxResident);let H=this.oldestEvictableWebResident();if(!H)throw new $(this.maxResident);await this.disposeResident(H,!0)}let z={generation:this.allocateGeneration(),surface:q.surface};return this.reservations.set(j,z),this.createReservation(j,z)})}async remove(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q)return!1;if(z.pins>0)return!1;return await this.disposeResident(z,!0),!0})}async forget(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q||z.pins>0)return!1;return this.residents.delete(j),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let j=0;while(!0){let q=this.oldestIdleWebResident();if(!q)return j;await this.disposeResident(q,!0),j++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let j;for(let q of[...this.residents.values()])try{await this.disposeResident(q,!1)}catch(z){j??=z}if(this.residents.clear(),j!==void 0)throw j})}getStats(){let j=0;for(let q of this.residents.values())if(q.pins>0)j++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:j,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let j=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,j}createReservation(j,q){let z=!1;return{commit:(H)=>{if(z)throw new W(j);if(H.key!==j||H.surface!==q.surface||this.reservations.get(j)!==q||this.closed)throw this.reservations.delete(j),z=!0,this.closed?new X:new W(j);this.reservations.delete(j);let J={...H,generation:q.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(j,J),z=!0,this.createLease(J)},cancel:()=>{if(z)return;if(this.reservations.get(j)===q)this.reservations.delete(j);z=!0}}}createLease(j){let q=!1;return{value:j.value,release:()=>{if(q)return;q=!0;let z=this.residents.get(j.key);if(z!==j||z.generation!==j.generation)return;z.pins=Math.max(0,z.pins-1),z.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((j)=>this.canEvict(j))}oldestIdleWebResident(){let j=this.now();return this.sortedWebResidents().find((q)=>j-q.lastUsedAt>=this.idleMs&&this.canEvict(q))}sortedWebResidents(){return[...this.residents.values()].filter((j)=>j.surface==="web").sort((j,q)=>j.lastUsedAt-q.lastUsedAt||j.generation-q.generation)}canEvict(j){if(j.pins>0||j.poisoned)return!1;try{return j.canEvict()}catch{return!1}}async disposeResident(j,q){if(this.residents.get(j.key)!==j)return;this.residents.delete(j.key);try{await j.dispose()}catch(z){if(q&&!this.closed&&!this.residents.has(j.key))j.lastUsedAt=this.now(),j.poisoned=!0,this.residents.set(j.key,j);throw z}}}import{createHash as B}from"node:crypto";var P=4,b=1000,Y=4000,D=120000,O=0.2;function w(j){try{return C(j)&&j.retryable}catch{return!1}}function N(j,q){let z=Number.isSafeInteger(q)&&q>0?q:1,H=z-1,J=Math.min(b*2**H,Y),K=B("sha256").update(`${j}\x00${z}`).digest().readUInt32BE(0)/4294967295,Q=1-O+2*O*K;return Math.min(Y,Math.max(0,Math.round(J*Q)))}function _(j){let q=N(j.sessionIdentity,j.failedAttempt),z=j.evidence,H=j.workStillPending===!0&&z!==void 0&&w(z.taskFailure)&&z.outputStarted===!1&&z.toolExecutionStarted===!1&&Number.isInteger(z.toolCallsCount)&&z.toolCallsCount===0,J=Number.isSafeInteger(j.failedAttempt)&&j.failedAttempt>0&&j.failedAttempt<P,Z=j.now??Date.now(),K=Z-j.recoveryStartedAt,Q=Number.isFinite(Z)&&Number.isFinite(j.recoveryStartedAt)&&Number.isFinite(K)&&K>=0&&K+q<=D;return{phase:H?J&&Q?"retry_scheduled":"exhausted":"failed",delayMs:q,retryable:H,withinAttemptBudget:J,withinTimeBudget:Q}}
2
2
  export{$ as s,U as t,P as u,D as v,_ as w};
@@ -1,2 +1,2 @@
1
- import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.118",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 --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","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","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","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",prepack:"node scripts/run-bun.js run build",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",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",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.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
2
- export{y as Fi,p as Gi,v as Hi,g as Ii,f as Ji,w as Ki};
1
+ import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.120",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 --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","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","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","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",prepack:"node scripts/run-bun.js run build",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",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",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.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
2
+ export{y as Gi,p as Hi,v as Ii,g as Ji,f as Ki,w as Li};
@@ -1,2 +1,2 @@
1
- import{Ah as F}from"./chunk-y21nw7g1.js";import{xi as D,yi as E}from"./chunk-dgf2xzzd.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
- export{H as vf,Q as wf,T as xf};
1
+ import{Bh as F}from"./chunk-7k72dxwe.js";import{yi as D,zi as E}from"./chunk-r6svhe3w.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
+ export{H as wf,Q as xf,T as yf};
@@ -0,0 +1 @@
1
+ import{wf as a,xf as b,yf as c}from"./chunk-6h0kgpgv.js";import"./chunk-7k72dxwe.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1,4 +1,4 @@
1
- import{si as r}from"./chunk-dvv28pkc.js";import{Qi as d,Si as x,Ui as j,Yi as u,Zi as i}from"./chunk-rkdxqx8m.js";import{_i as I}from"./chunk-tf7ezqew.js";import{stat as a}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var e=50,__=100,E_=new Set(["queued","running","completed","failed","cancelled","interrupted"]),R_=new Set(["high","medium","low"]),W_=/^[A-Za-z0-9_-]+$/,$_=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function H_(_){return typeof _==="string"&&$_.test(_)&&Number.isFinite(Date.parse(_))}function v(_){return typeof _==="string"&&U.isAbsolute(_)}function M_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function Q_(_){try{if(!W_.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||v(R.cwd))||!H_(R.lastMessageTime)||!v(R.projectPath)||!x(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function J(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function V_(_){if(!_.cursor)return;let E=Q_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function O_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:M=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let H=W===void 0?e:W;if(!Number.isInteger(H)||H<1||H>__)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:H,includeSubagents:$,archived:M}}function N_(_={}){let E=c(_.taskStatus,E_,"task status"),R=c(_.taskPriority,R_,"task priority"),W=S(_.taskDueAfter,"taskDueAfter"),$=S(_.taskDueBefore,"taskDueBefore");return X_(W,$),{...E?{taskStatuses:E}:{},...R?{taskPriorities:R}:{},...W?{taskDueAfter:W}:{},...$?{taskDueBefore:$}:{}}}function c(_,E,R){if(_===void 0)return;let W=Array.isArray(_)?_:[_];if(W.length===0)return;let $=new Set;for(let M of W){if(typeof M!=="string"||!E.has(M))throw Error(`Invalid session ${R} filter`);$.add(M)}return[...$].sort()}function S(_,E){if(_===void 0)return;if(typeof _!=="string"||!Number.isFinite(Date.parse(_)))throw Error(`Invalid session ${E} filter`);return new Date(_).toISOString()}function X_(_,E){if(_!==void 0&&E!==void 0&&_>E)throw Error("Session task due range is inverted")}function Y_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=V_(E);if(W)R=R.filter((H)=>Y_(H,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let M=$[$.length-1];return{sessions:$,nextCursor:M_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:M.lastMessageTime,projectPath:M.projectPath,sessionId:M.sessionId})}}function G_(_){return _.type==="message_created"||_.type==="token_budget_handoff_recorded"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="turn_recovery_acknowledged"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function O(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function N(_,E){let R=_.find((W)=>O(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:m(_,E),createdAt:R.data.createdAt}}function m(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function h(_,E){N(_,E);let R=_.findIndex((H)=>H.type==="message_created"&&H.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,M=new Set(_.flatMap((H)=>H.type==="turn_started"&&$&&H.data.inputMessageIds?.includes($)?[H.data.turnId]:[]));return _.filter((H,Q)=>{if((H.type==="turn_started"||H.type==="turn_completed"||H.type==="turn_aborted"||H.type==="turn_recovery_acknowledged")&&M.has(H.data.turnId))return!1;return Q<R||!G_(H)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(N(E,R.data.targetMessageId),R.data.mode!=="code")E=h(E,R.data.targetMessageId)}return E}function j_(_){let E=w(_);return E.filter(O).map((R)=>({messageId:R.data.messageId,preview:m(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function u_(_,E){let R=w(_),W=N(R,E),$=R.findIndex((H)=>H.type==="message_created"&&H.data.messageId===E),M=R.slice($);return{checkpoint:W,projectedEntries:h(R,E),removedTurns:M.filter(O).length,snapshotMessageIds:M.flatMap((H)=>H.type==="part_created"&&H.data.partType==="tool_call"?[H.data.partId]:[])}}import*as z from"node:fs";import{createReadStream as g_}from"node:fs";import*as X from"node:fs/promises";import*as f from"node:path";import{createInterface as T_}from"node:readline";var b=65536;function D(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function Z_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function y(_,E="session transcript"){let R=_.split(`
1
+ import{ti as r}from"./chunk-w4xqaw4h.js";import{Ri as d,Ti as x,Vi as j,Zi as u,_i as i}from"./chunk-spxb931p.js";import{$i as I}from"./chunk-m7b779kd.js";import{stat as a}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var e=50,__=100,E_=new Set(["queued","running","completed","failed","cancelled","interrupted"]),R_=new Set(["high","medium","low"]),W_=/^[A-Za-z0-9_-]+$/,$_=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function H_(_){return typeof _==="string"&&$_.test(_)&&Number.isFinite(Date.parse(_))}function v(_){return typeof _==="string"&&U.isAbsolute(_)}function M_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function Q_(_){try{if(!W_.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||v(R.cwd))||!H_(R.lastMessageTime)||!v(R.projectPath)||!x(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function J(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function V_(_){if(!_.cursor)return;let E=Q_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function O_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:M=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let H=W===void 0?e:W;if(!Number.isInteger(H)||H<1||H>__)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:H,includeSubagents:$,archived:M}}function N_(_={}){let E=c(_.taskStatus,E_,"task status"),R=c(_.taskPriority,R_,"task priority"),W=S(_.taskDueAfter,"taskDueAfter"),$=S(_.taskDueBefore,"taskDueBefore");return X_(W,$),{...E?{taskStatuses:E}:{},...R?{taskPriorities:R}:{},...W?{taskDueAfter:W}:{},...$?{taskDueBefore:$}:{}}}function c(_,E,R){if(_===void 0)return;let W=Array.isArray(_)?_:[_];if(W.length===0)return;let $=new Set;for(let M of W){if(typeof M!=="string"||!E.has(M))throw Error(`Invalid session ${R} filter`);$.add(M)}return[...$].sort()}function S(_,E){if(_===void 0)return;if(typeof _!=="string"||!Number.isFinite(Date.parse(_)))throw Error(`Invalid session ${E} filter`);return new Date(_).toISOString()}function X_(_,E){if(_!==void 0&&E!==void 0&&_>E)throw Error("Session task due range is inverted")}function Y_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=V_(E);if(W)R=R.filter((H)=>Y_(H,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let M=$[$.length-1];return{sessions:$,nextCursor:M_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:M.lastMessageTime,projectPath:M.projectPath,sessionId:M.sessionId})}}function G_(_){return _.type==="message_created"||_.type==="token_budget_handoff_recorded"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="turn_recovery_acknowledged"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function O(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function N(_,E){let R=_.find((W)=>O(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:m(_,E),createdAt:R.data.createdAt}}function m(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function h(_,E){N(_,E);let R=_.findIndex((H)=>H.type==="message_created"&&H.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,M=new Set(_.flatMap((H)=>H.type==="turn_started"&&$&&H.data.inputMessageIds?.includes($)?[H.data.turnId]:[]));return _.filter((H,Q)=>{if((H.type==="turn_started"||H.type==="turn_completed"||H.type==="turn_aborted"||H.type==="turn_recovery_acknowledged")&&M.has(H.data.turnId))return!1;return Q<R||!G_(H)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(N(E,R.data.targetMessageId),R.data.mode!=="code")E=h(E,R.data.targetMessageId)}return E}function j_(_){let E=w(_);return E.filter(O).map((R)=>({messageId:R.data.messageId,preview:m(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function u_(_,E){let R=w(_),W=N(R,E),$=R.findIndex((H)=>H.type==="message_created"&&H.data.messageId===E),M=R.slice($);return{checkpoint:W,projectedEntries:h(R,E),removedTurns:M.filter(O).length,snapshotMessageIds:M.flatMap((H)=>H.type==="part_created"&&H.data.partType==="tool_call"?[H.data.partId]:[])}}import*as z from"node:fs";import{createReadStream as g_}from"node:fs";import*as X from"node:fs/promises";import*as f from"node:path";import{createInterface as T_}from"node:readline";var b=65536;function D(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function Z_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function y(_,E="session transcript"){let R=_.split(`
2
2
  `),W=!_.endsWith(`
3
3
  `),$=[];for(let[M,H]of R.entries())try{let Q=Z_(H,M+1,E);if(Q){if(typeof Q.seq!=="number")Q.seq=$.length+1;$.push(Q)}}catch(Q){if(W&&M===R.length-1)break;throw Q}return $}class G{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return G.stampSeqFrom(_,G.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await X.mkdir(f.dirname(this.filePath),{recursive:!0,mode:493});let E=await X.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=G.stampSeqFrom(_,W),M=`${$.map(D).join(`
4
4
  `)}
@@ -137,4 +137,4 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
137
137
  ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
138
138
  WHERE parts_fts MATCH ?
139
139
  ORDER BY timestamp DESC LIMIT ?`,Q=_.prepare(H);return R?Q.all(M,R,W):Q.all(M,W)}
140
- export{w as _d,j_ as $d,u_ as ae,y as be,G as ce,J as de,V_ as ee,O_ as fe,N_ as ge,Y_ as he,f_ as ie,s as je,B_ as ke,A_ as le,y_ as me,z_ as ne,t_ as oe,e_ as pe,_E as qe};
140
+ export{w as $d,j_ as ae,u_ as be,y as ce,G as de,J as ee,V_ as fe,O_ as ge,N_ as he,Y_ as ie,f_ as je,s as ke,B_ as le,A_ as me,y_ as ne,z_ as oe,t_ as pe,e_ as qe,_E as re};