blade-code 0.10.38 → 0.10.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-m0a2zdm8.js → chunk-03bzxkdg.js} +1 -1
- package/dist/chunk-0442z8f4.js +1 -0
- package/dist/{chunk-6aw2ts3m.js → chunk-0s11h8yd.js} +1 -1
- package/dist/{chunk-vxpj2jgx.js → chunk-1hea2ad2.js} +1 -1
- package/dist/chunk-2b4h0nb5.js +1 -0
- package/dist/{chunk-6t2bkj8s.js → chunk-2fgmsnh6.js} +1 -1
- package/dist/{chunk-gh0vdddb.js → chunk-34cexc50.js} +1 -1
- package/dist/{chunk-atdb1pks.js → chunk-3azdwanx.js} +1 -1
- package/dist/chunk-3nj2f0q9.js +2 -0
- package/dist/chunk-3w64mkc3.js +22 -0
- package/dist/{chunk-g7v01gjg.js → chunk-4dq8rbq2.js} +187 -187
- package/dist/{chunk-r863t0fx.js → chunk-4p8sp6p3.js} +1 -1
- package/dist/{chunk-9zfr1ydk.js → chunk-4wk9cc2b.js} +1 -1
- package/dist/{chunk-kzr5n83y.js → chunk-74jd1hcs.js} +57 -57
- package/dist/{chunk-gvx3707k.js → chunk-7qj2tbew.js} +1 -1
- package/dist/{chunk-jtjcg93t.js → chunk-8jexqfqg.js} +1 -1
- package/dist/{chunk-asqah231.js → chunk-8kqnezvc.js} +1 -1
- package/dist/{chunk-m3yb3rek.js → chunk-9dxkfqxg.js} +1 -1
- package/dist/{chunk-9yd3av82.js → chunk-9wxj0gxa.js} +1 -1
- package/dist/chunk-bqpqh6re.js +2 -0
- package/dist/{chunk-5xfef98g.js → chunk-dhcm8958.js} +1 -1
- package/dist/{chunk-0tdc8pg9.js → chunk-dhsdn91x.js} +1 -1
- package/dist/{chunk-tczrjn95.js → chunk-ew5dmar1.js} +2 -2
- package/dist/chunk-fa1gxd12.js +1 -0
- package/dist/{chunk-0dw58ycv.js → chunk-fk8jf873.js} +2 -2
- package/dist/{chunk-e6ttz45s.js → chunk-h188kz0p.js} +1 -1
- package/dist/{chunk-b9zfq3et.js → chunk-h7bat4ws.js} +1 -1
- package/dist/chunk-h9620q2d.js +1 -0
- package/dist/{chunk-rj1z55m8.js → chunk-hpqhk0jf.js} +1 -1
- package/dist/{chunk-y3sb4wda.js → chunk-k2hzhw9f.js} +1 -1
- package/dist/{chunk-a9r3w0t9.js → chunk-keart8yy.js} +2 -2
- package/dist/chunk-kpr5nqh2.js +5 -0
- package/dist/{chunk-aw4r1zhr.js → chunk-mc42kjv9.js} +2 -2
- package/dist/{chunk-ak37gg0n.js → chunk-np8f17zg.js} +1 -1
- package/dist/{chunk-kw543czm.js → chunk-nxc705wc.js} +1 -1
- package/dist/chunk-nzyc8z6k.js +6 -0
- package/dist/{chunk-cm4t4cz6.js → chunk-p504jme7.js} +2 -2
- package/dist/chunk-px491bge.js +1 -0
- package/dist/{chunk-921c6fm5.js → chunk-r01spp7a.js} +1 -1
- package/dist/{chunk-ydy9bvcp.js → chunk-rb1fv7en.js} +1 -1
- package/dist/{chunk-htvt9e1j.js → chunk-rs43m9d9.js} +4 -4
- package/dist/chunk-s3nz9qx8.js +1 -0
- package/dist/{chunk-qc5qwgpt.js → chunk-ts3pgkmz.js} +2 -2
- package/dist/chunk-v53vv0e9.js +6 -0
- package/dist/chunk-v85q852a.js +44 -0
- package/dist/{chunk-a1shhh83.js → chunk-vs7tcyse.js} +1 -1
- package/dist/{chunk-rfec0k27.js → chunk-vtb0m80j.js} +7 -7
- package/dist/chunk-vtdg5cb1.js +1 -0
- package/dist/chunk-vv0vk8bp.js +1 -0
- package/dist/chunk-w69qkark.js +1 -0
- package/dist/{chunk-199as76m.js → chunk-x6c6yqpx.js} +2 -2
- package/dist/chunk-xpmr9bf7.js +1 -0
- package/dist/{chunk-fj6frvhd.js → chunk-xtfy56qh.js} +1 -1
- package/dist/chunk-y10jqqyg.js +1 -0
- package/dist/{chunk-7t97xngf.js → chunk-ydz6bvs1.js} +48 -48
- package/dist/{chunk-e8wpd0s4.js → chunk-zfn7w33a.js} +1 -1
- package/dist/{chunk-jpzrwcm7.js → chunk-zv9jxwdp.js} +1 -1
- package/dist/web/assets/{ChatView-BB4nYdEf.js → ChatView-BP89vdT_.js} +14 -14
- package/dist/web/assets/{CodeBlockHighlighter-CAFugWXU.js → CodeBlockHighlighter-UnjC3KVk.js} +1 -1
- package/dist/web/assets/{FilePreview-O5aDfFS4.js → FilePreview-D0BiZowf.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-C_qekwq_.js → MarkdownRenderer-CPu_rkPT.js} +3 -3
- package/dist/web/assets/{SettingsModal-FADlD0Da.js → SettingsModal-CM9pcJas.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-D3k3tRpI.js → TaskSwitcher-BOCm7kPO.js} +1 -1
- package/dist/web/assets/{TerminalPanel-DBmKVVbI.js → TerminalPanel-CUZ4slSS.js} +1 -1
- package/dist/web/assets/{index-CMIW4J1Q.js → index-CthLsVgC.js} +7 -7
- package/dist/web/assets/{session-events-Dk20sSDo.js → session-events-109FkhOM.js} +6 -6
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-0b3fnxry.js +0 -22
- package/dist/chunk-13bzyvs2.js +0 -1
- package/dist/chunk-169rpaqn.js +0 -1
- package/dist/chunk-2mkdj63h.js +0 -1
- package/dist/chunk-4mpx8rad.js +0 -1
- package/dist/chunk-572gdsjd.js +0 -1
- package/dist/chunk-8xp6djrk.js +0 -1
- package/dist/chunk-ahkpjvaq.js +0 -2
- package/dist/chunk-fjpqxdct.js +0 -1
- package/dist/chunk-gc7bk6v0.js +0 -1
- package/dist/chunk-h4k801hr.js +0 -6
- package/dist/chunk-hcrfkqc1.js +0 -1
- package/dist/chunk-hkrbsqsw.js +0 -6
- package/dist/chunk-jd764yqg.js +0 -5
- package/dist/chunk-jtv91ez8.js +0 -2
- package/dist/chunk-n5nj8d8f.js +0 -1
- package/dist/chunk-ts8h7mx5.js +0 -44
- package/dist/chunk-vxxhd72z.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Cc as u,Dc as Hf,Ec as C$,Fc as Yf,Gc as I,Hc as N$,Ic as Wf,Jc as G$,Kc as _$,Lc as x$,Nc as g0,Qc as J$,Rc as Uf}from"./chunk-
|
|
1
|
+
import{Cc as u,Dc as Hf,Ec as C$,Fc as Yf,Gc as I,Hc as N$,Ic as Wf,Jc as G$,Kc as _$,Lc as x$,Nc as g0,Qc as J$,Rc as Uf}from"./chunk-3azdwanx.js";import{Rd as V0}from"./chunk-3rjmkaey.js";import{we as Z0}from"./chunk-zwt7f9ab.js";import{Ie as i$}from"./chunk-v11r4ahz.js";import{Hf as Qf,If as Xf}from"./chunk-thstqcg3.js";import{Nf as A$}from"./chunk-6360fg4j.js";import{ig as U0}from"./chunk-fk8jf873.js";import{pg as x0,sg as J0}from"./chunk-8kqnezvc.js";import{wg as p}from"./chunk-mc42kjv9.js";import{Dg as Ff,Eg as q0,Fg as Kf,Gg as A,Hg as m,Jg as G0,Kg as c,Lg as C0}from"./chunk-ts3pgkmz.js";import{readdir as L$,readFile as a,rm as $0,stat as E0}from"node:fs/promises";import*as V from"node:path";import{nanoid as j}from"nanoid";import{createHash as yf,randomUUID as Sf}from"node:crypto";import*as v from"node:fs/promises";import*as H0 from"node:path";import{execFileSync as Mf}from"node:child_process";import{createHash as gf}from"node:crypto";import{readFileSync as Ef}from"node:fs";var bf=/^[a-f0-9]{64}$/;function Y$($){if(!$||typeof $!=="object")return!1;let f=$;return(f.platform==="linux"||f.platform==="darwin"||f.platform==="win32")&&typeof f.fingerprint==="string"&&bf.test(f.fingerprint)}var W$={readFile:($)=>Ef($,"utf8"),execFile:($,f)=>Mf($,f,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},wf=($)=>{try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f&&f.code==="EPERM"}};function u0($,f){return{platform:$,fingerprint:gf("sha256").update(`${$}\x00${f}`).digest("hex")}}function kf($,f){let T=f.readFile(`/proc/${$}/stat`).trim(),q=T.lastIndexOf(")");if(q<0)throw Error("Invalid /proc process stat");let L=T.slice(q+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function Q0($,f=process.platform,T=W$){if(!Number.isInteger($)||$<=1)return;try{if(f==="linux")return u0(f,kf($,T));if(f==="darwin"){let q=T.execFile("ps",["-o","lstart=","-p",String($)]).trim();return q?u0(f,q):void 0}if(f==="win32"){let q=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,B=T.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",q]).trim();return B?u0(f,B):void 0}}catch{return}return}function U$($,f){return Q0($,f.platform)?.fingerprint===f.fingerprint}function o1($,f,T=W$,q=wf){if(!Number.isInteger($)||$<=1)return!1;let B=Q0($,f.platform,T);if(B)return B.fingerprint===f.fingerprint;return!q($)}var z$=1;function jf($,f){let T=yf("sha256").update(f).digest("hex");return H0.join(q0($),".locks",`${T}.lock`)}function X0($,f){return $ instanceof Error&&"code"in $&&$.code===f}async function P0($){try{let f=JSON.parse(await v.readFile($,"utf8"));if(f.version!==z$||typeof f.sessionId!=="string"||typeof f.ownerId!=="string"||!Number.isInteger(f.pid)||(f.pid??0)<=0||f.processIdentity!==void 0&&!Y$(f.processIdentity)||typeof f.acquiredAt!=="string")return;return f}catch{return}}async function D$($){let f=await P0($);if(f)return f;return await new Promise((T)=>setTimeout(T,10)),P0($)}function mf($){try{return process.kill($,0),!0}catch(f){return X0(f,"EPERM")}}async function R$($,f){let T;try{return T=await v.open($,"wx",384),await T.writeFile(`${JSON.stringify(f)}
|
|
2
2
|
`,"utf8"),!0}catch(q){if(X0(q,"EEXIST"))return!1;if(T)await v.unlink($).catch(()=>{return});throw q}finally{await T?.close().catch(()=>{return})}}class h extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class n{filePath;record;released=!1;constructor($,f){this.filePath=$;this.record=f}static async acquire($,f=A$()){let T=jf(f,$),q={version:z$,sessionId:$,ownerId:Sf(),pid:process.pid,processIdentity:Q0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(H0.dirname(T),{recursive:!0,mode:448}),await R$(T,q))return new n(T,q);let B=await D$(T);if(B&&mf(B.pid)&&(!B.processIdentity||U$(B.pid,B.processIdentity)))throw new h(B.pid);if(await v.unlink(T).catch((L)=>{if(!X0(L,"ENOENT"))throw L}),await R$(T,q))return new n(T,q);throw new h((await D$(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await P0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch((f)=>{if(!X0(f,"ENOENT"))throw f})}}var TT=1;function h0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function If($){if(!h0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&h0($.image_url)&&typeof $.image_url.url==="string"}function vf($){if(!h0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(If)}function M$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let f=JSON.stringify($);if(Buffer.byteLength(f)>16777216)return;let T=JSON.parse(f);if(!Array.isArray(T)||!T.every(vf))return;return T}function qT($){let f=M$($);if(!f)throw Error("Compaction replacement context is invalid or exceeds limits");return f}function g$($){return M$($)}function uf($,f){for(let T of $){if(T.type!=="part_created"||T.data.partType!=="tool_result")continue;let q=T.data.payload;if(!q||typeof q!=="object"||Array.isArray(q))continue;let B=q;if(B.toolCallId===f||T.data.partId===f||T.data.messageId===f)return B}return}function E$($){let f=u($),T=new Map;for(let q of f){if(q.type==="interaction_requested"){T.set(q.data.requestId,{request:q.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(q.type==="interaction_responded"){let B=T.get(q.data.requestId);if(B)B.response=q.data;continue}if(q.type==="interaction_recovered"){let B=T.get(q.data.requestId);if(B)B.recovery=q.data}}for(let q of T.values()){let B=uf(f,q.request.toolCallId);q.hasToolResult=B!==void 0;let L=B?.metadata&&typeof B.metadata==="object"?B.metadata:void 0;q.hasRecoveryToolResult=L?.interactionRecovery===!0&&L.requestId===q.request.requestId}return[...T.values()]}function b$($){return E$($).reverse().find((f)=>!f.response&&!f.recovery)}function OT($){let f=new Map;for(let T of E$($))f.set(T.request.toolCallId,T);return[...f.values()].filter((T)=>T.response&&!T.recovery&&(!T.hasToolResult||T.hasRecoveryToolResult))}function w$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function Y0($){let f=new Map,T=[];for(let q of $){if(q.type==="review_started"){if(!f.has(q.data.reviewId))T.push(q.data.reviewId),f.set(q.data.reviewId,{start:q.data});continue}if(q.type!=="review_completed")continue;let B=f.get(q.data.reviewId);if(B&&B.completion===void 0)B.completion=q.data}return T.map((q)=>f.get(q)).filter((q)=>q!==void 0)}function NT($){return Y0($).reverse().find((f)=>f.completion===void 0)}function n0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function k$($,f){let T=["## Code Review","",`Target: ${$.target.label}`,`Status: ${n0(f.status)}`,"",f.overallExplanation||"No overall explanation was provided."];if(f.findings.length===0)T.push("","No actionable findings.");else{T.push("","### Findings");for(let[q,B]of f.findings.entries()){let L=B.codeLocation.lineStart===B.codeLocation.lineEnd?`${B.codeLocation.lineStart}`:`${B.codeLocation.lineStart}-${B.codeLocation.lineEnd}`;T.push("",`${q+1}. ${B.title}`,` ${B.codeLocation.path}:L${L} · confidence ${B.confidenceScore.toFixed(2)}`,` ${B.body}`)}}if(f.error)T.push("",`Error: ${f.error}`);return T.join(`
|
|
3
3
|
`)}function y$($,f){return{reviewId:$.reviewId,phase:"completed",status:f.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:f.overallExplanation,findings:f.findings.map((T)=>({title:T.title,body:T.body,priority:T.priority,confidenceScore:T.confidenceScore,codeLocation:{...T.codeLocation}})),...f.error?{error:f.error}:{}}}var l0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function Pf($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function hf($){let f=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(f))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(f))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(f))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(f))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(f))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(f))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(f))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(f))return"unsupported_input";return"runtime"}function nf($){return{code:$,...l0[$]}}function c0($){return nf(hf(Pf($)))}function p0($){if(!$||typeof $!=="object")return!1;let f=$;if(typeof f.code!=="string"||!(f.code in l0))return!1;let T=l0[f.code];return f.message===T.message&&f.retryable===T.retryable}import{promises as L0,realpathSync as cf}from"node:fs";import W0 from"node:path";import*as r from"fs/promises";import*as H from"path";var S$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,f){super($);this.code=f;this.name="PathSecurityError"}}class i0{static normalize($,f){let T=H.isAbsolute($)?$:H.resolve(f,$),q=H.normalize(T),B=H.normalize(f);if(!this.isWithinWorkspace(q,B))throw new d(`Path outside workspace: ${$} (resolved to ${q}, workspace: ${B})`,"PATH_OUTSIDE_WORKSPACE");return q}static checkRestricted($){let f=$.split(H.sep);for(let T of S$)if(f.includes(T))throw new d(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,f){this.checkTraversal($);let T=this.normalize($,f);this.checkRestricted(T);try{await r.access(T)}catch(q){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink($,f){try{let T=await r.realpath($),q=await r.realpath(f);if(!this.isWithinWorkspace(T,q))throw new d(`Symlink points outside workspace: ${$} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof d)throw T;return $}}static getRelativePath($,f){return H.relative(f,$)}static isWithinWorkspace($,f){let T=H.resolve($),q=H.resolve(f),B=H.relative(q,T);return B===""||B!==".."&&!B.startsWith(`..${H.sep}`)&&!H.isAbsolute(B)}static async isWithinWorkspaceResolved($,f){let T=H.resolve(f),q=H.isAbsolute($)?H.resolve($):H.resolve(T,$);if(!this.isWithinWorkspace(q,T))return!1;let B;try{B=await r.realpath(T)}catch{return!1}let L=q;while(!0){try{let C=await r.realpath(L);return this.isWithinWorkspace(C,B)}catch(C){let _=C.code;if(_!=="ENOENT"&&_!=="ENOTDIR")return!1}let O=H.dirname(L);if(O===L)return!1;L=O}}static isRestricted($){let f=$.split(H.sep);return S$.some((T)=>f.includes(T))}}var B0=U0("Tool");class l{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}async recordFileRead($,f){try{let T=await L0.stat($),q={filePath:W0.resolve($),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:f,lastOperation:"read"};this.setRecord(q),await this.recordAliases($,q.filePath),B0.debug(`记录文件读取: ${$}`)}catch(T){B0.warn(`记录文件读取失败: ${$}`,T)}}async recordFileEdit($,f,T="edit"){try{let q=await L0.stat($),B={filePath:W0.resolve($),accessTime:Date.now(),mtime:q.mtimeMs,sessionId:f,lastOperation:T};this.setRecord(B),await this.recordAliases($,B.filePath),B0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${$}`)}catch(q){B0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${$}`,q)}}hasFileBeenRead($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return!1;return f?T.has(f):T.size>0}async checkFileModification($,f){let T=this.getFileRecord($,f);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(Math.abs(q.mtimeMs-T.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(T.accessTime).toISOString()}, 当前修改时间: ${q.mtime.toISOString()})`};return{modified:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${B.message}`}}}async checkExternalModification($,f){let T=this.getFileRecord($,f);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(q.mtimeMs-T.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(T.accessTime).toISOString()} (${T.lastOperation}) 之后被外部程序修改(当前修改时间: ${q.mtime.toISOString()})`};return{isExternal:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${$}`,q),{isExternal:!1,message:`无法检查文件状态: ${B.message}`}}}getFileRecord($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return;if(f)return T.get(f);return[...T.values()].sort((q,B)=>B.accessTime-q.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,f){let T=this.resolveTrackedPath($);if(!f){this.accessedFiles.delete(T),this.removeAliases(T);return}let q=this.accessedFiles.get(T);if(q?.delete(f),q?.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,f){for(let[T,q]of this.accessedFiles.entries()){if(f&&!i0.isWithinWorkspace(T,f))continue;if(q.delete($),q.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){l.instance=null}setRecord($){let f=this.accessedFiles.get($.filePath);if(!f)f=new Map,this.accessedFiles.set($.filePath,f);f.set($.sessionId,$)}async recordAliases($,f){this.pathAliases.set(W0.resolve($),f);let T=await L0.realpath($).catch(()=>{return});if(T)this.pathAliases.set(T,f)}resolveTrackedPath($){let f=W0.resolve($);if(this.accessedFiles.has(f))return f;let T=this.pathAliases.get(f);if(T)return T;try{let q=cf.native(f);return this.pathAliases.get(q)??q}catch{return f}}removeAliases($){for(let[f,T]of this.pathAliases)if(T===$)this.pathAliases.delete(f)}}import*as O0 from"node:crypto";import{promises as F}from"node:fs";import*as Q from"node:path";import d0 from"write-file-atomic";var j$="missing";class D0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(A($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!Q.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?Q.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let f=C0();this.snapshotDir=Q.join(f,"file-history",this.sessionId),this.manifestPath=Q.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await F.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=C0(),f=await F.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=O0.createHash("sha256").update(f).digest("hex").slice(0,24),q=Q.join($,"file-history",this.sessionId),B=Q.join($,"file-history","workspaces",T,this.sessionId),L=Q.join(B,"manifest.json");try{await F.access(L)}catch{await this.migrateLegacySnapshotDir(q,B,f)}this.snapshotDir=B,this.manifestPath=L}async migrateLegacySnapshotDir($,f,T){let q;try{q=JSON.parse(await F.readFile(Q.join($,"manifest.json"),"utf8"))}catch{return}if(q.schemaVersion!==1||!Array.isArray(q.snapshots)||!q.snapshots.every((B)=>this.isWithinWorkspace(B.filePath,T)))return;await F.mkdir(Q.dirname(f),{recursive:!0,mode:493});try{await F.rename($,f)}catch(B){let L=B.code;if(L!=="ENOENT"&&L!=="EEXIST"&&L!=="ENOTEMPTY")throw B}}isWithinWorkspace($,f){if(!Q.isAbsolute($))return!1;let T=Q.relative(f,Q.resolve($));return T===""||T!==".."&&!T.startsWith(`..${Q.sep}`)&&!Q.isAbsolute(T)}async createSnapshot($,f){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity($),q=!0;try{await F.access(T)}catch{q=!1}let B=this.trackedFileBackups.get(T),L=B?B.version+1:1,O=this.generateFileHash(T,L),C=this.getSnapshotPath(O,L),_=new Date;if(q){let G=await F.readFile(T);await F.writeFile(C,G)}let N={backupFileName:O,version:L,backupTime:_};return this.trackedFileBackups.set(T,N),this.snapshots.push({messageId:f,backupFileName:O,timestamp:_,filePath:T,version:L,existedBefore:q}),await this.cleanupOldSnapshots(T),await this.persistManifest(),N}async recordPostEditState($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)throw Error(`未找到待完成的快照: ${T}`);q.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)return;this.removeSnapshot(q),await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let f=await this.resolveFileIdentity($),T=this.snapshots.slice().reverse().find((L)=>L.filePath===f&&L.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${f}`);if(await this.hashFile(f)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${f}`);let B=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(f),{recursive:!0}),await F.writeFile(f,L)}else await F.rm(f,{force:!0});return this.removeSnapshot(T),await F.rm(B,{force:!0}),await this.persistManifest(),T}async restoreSnapshot($,f){let T=await this.resolveFileIdentity($),q=this.snapshots.slice().reverse().find((L)=>L.messageId===f&&L.filePath===T);if(!q)throw Error(`未找到快照: messageId=${f}, filePath=${T}`);let B=this.getSnapshotPath(q.backupFileName,q.version);if(q.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(T),{recursive:!0}),await F.writeFile(T,L)}else await F.rm(T,{force:!0})}async listSnapshots($){let f=await this.resolveFileIdentity($);return this.snapshots.filter((T)=>T.filePath===f)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let f=this.buildRewindPlan($);return{files:f.map((T)=>T.filePath),snapshotCount:f.reduce((T,q)=>T+q.selected.length,0)}}async rewindSnapshots($){let f=this.buildRewindPlan($);if(f.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let B of f){let L,O=!0;try{L=await F.readFile(B.filePath)}catch(_){if(_.code!=="ENOENT")throw _;O=!1}if((L?O0.createHash("sha256").update(L).digest("hex"):j$)!==B.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${B.filePath}`);if(T.set(B.filePath,{existed:O,content:L}),B.target.existedBefore)await F.access(this.getSnapshotPath(B.target.backupFileName,B.target.version))}let q=[...this.snapshots];try{for(let L of f)if(L.target.existedBefore){let O=await F.readFile(this.getSnapshotPath(L.target.backupFileName,L.target.version));await F.mkdir(Q.dirname(L.filePath),{recursive:!0}),await d0(L.filePath,O)}else await F.rm(L.filePath,{force:!0});let B=new Set(f.flatMap((L)=>L.selected));this.snapshots=this.snapshots.filter((L)=>!B.has(L)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...B].map((L)=>F.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}).catch(()=>{return})))}catch(B){this.snapshots=q,this.rebuildTrackedFileBackups();let L=[];for(let[O,C]of T)try{if(C.existed&&C.content)await d0(O,C.content);else await F.rm(O,{force:!0})}catch(_){L.push(_)}if(L.length>0)throw AggregateError([B,...L],"快照回退失败且无法完整恢复回退前状态");throw B}return{files:f.map((B)=>B.filePath),snapshotCount:f.reduce((B,L)=>B+L.selected.length,0)}}async commitSnapshots($){let f=this.buildRewindPlan($),T=new Set(f.flatMap((B)=>B.selected));if(T.size===0)return{files:[],snapshotCount:0};let q=[...this.snapshots];this.snapshots=this.snapshots.filter((B)=>!T.has(B)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(B){throw this.snapshots=q,this.rebuildTrackedFileBackups(),B}return await Promise.all([...T].map((B)=>F.rm(this.getSnapshotPath(B.backupFileName,B.version),{force:!0}).catch(()=>{return}))),{files:f.map((B)=>B.filePath),snapshotCount:T.size}}buildRewindPlan($){let f=new Set($),T=this.snapshots.filter((L)=>L.postEditHash!==void 0),q=T.filter((L)=>f.has(L.messageId));return[...new Set(q.map((L)=>L.filePath))].sort().map((L)=>{let O=T.filter((G)=>G.filePath===L),C=O.filter((G)=>f.has(G.messageId)),_=O.indexOf(C[0]),N=O.slice(_);if(N.length!==C.length||N.some((G)=>!f.has(G.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${L}`);return{filePath:L,selected:C,target:C[0],latest:C.at(-1)}})}async loadManifest(){try{let $=await F.readFile(this.manifestPath,"utf-8"),f=JSON.parse($);if(f.schemaVersion!==1||!Array.isArray(f.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(f.snapshots.map(async(T)=>({...T,filePath:await this.resolveFileIdentity(T.filePath),timestamp:new Date(T.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await F.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((f)=>({...f,timestamp:f.timestamp.toISOString()}))};await d0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let T=this.snapshots.filter((q)=>q.filePath===$).slice(0,-this.maxSnapshots);for(let q of T)await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),this.removeSnapshot(q)}async cleanup($=0){let f=this.snapshots.slice().sort((q,B)=>B.timestamp.getTime()-q.timestamp.getTime()),T=new Set(f.slice(0,$));for(let q of this.snapshots)if(!T.has(q))await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0});this.snapshots=f.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,f){return Q.join(this.snapshotDir,`${$}@v${f}`)}async resolveFileIdentity($){let f=Q.resolve($),T=[],q=f;while(!0){try{let L=await F.realpath(q);return Q.join(L,...T.reverse())}catch(L){let O=L.code;if(O!=="ENOENT"&&O!=="ENOTDIR")throw L}let B=Q.dirname(q);if(B===q)return f;T.push(Q.basename(q)),q=B}}async hashFile($){try{let f=await F.readFile($);return O0.createHash("sha256").update(f).digest("hex")}catch(f){if(f.code==="ENOENT")return j$;throw f}}removeSnapshot($){let f=this.snapshots.indexOf($);if(f>=0)this.snapshots.splice(f,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let f=this.trackedFileBackups.get($.filePath);if(!f||f.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,f){let T=O0.createHash("md5");return T.update(`${$}:${f}`),T.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var DT=1200,RT=2000,AT=2000,zT=2000;function I$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function pf($){if(typeof $==="string"&&$.length>0)return $;if(I$($)&&typeof $.message==="string")return $.message;return}function df($,f){if($===null||$===void 0)return f??"";if(typeof $==="string")return $;if(typeof $==="object")return $;return String($)}function v$($){let f=$.error!==null&&$.error!==void 0,T=f?pf($.error)??"Tool execution failed":void 0,q=I$($.metadata)?$.metadata:void 0;return{success:!f,llmContent:df($.output,T),...T?{error:{type:"execution_error",message:T}}:{},...q?{metadata:q}:{}}}function o0($,f){if($.length<=f)return $;let T=Math.max(0,f);if(T>0&&T<$.length&&/[\uD800-\uDBFF]/.test($.charAt(T-1)))T-=1;return $.slice(0,T)}function m$($,f){if($.length<=f)return $;let T=Math.max(0,$.length-f);if(T<$.length&&/[\uDC00-\uDFFF]/.test($.charAt(T)))T+=1;return $.slice(T)}function r0($,f){if($.length<=f)return $;if(f<=0)return"";let T=`
|
|
4
4
|
... (display clipped) ...
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as a}from"node:module";var c=a(import.meta.url);
|
|
2
|
-
export{c as
|
|
2
|
+
export{c as Ng};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as pg,p as qg,u as rg,S as sg,c as tg,l as ug};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as T,g as W,h as X,i as Y}from"./chunk-
|
|
1
|
+
import{f as T,g as W,h as X,i as Y}from"./chunk-rs43m9d9.js";import"./chunk-np8f17zg.js";import"./chunk-h188kz0p.js";import"./chunk-2fgmsnh6.js";import"./chunk-dhcm8958.js";import"./chunk-4dq8rbq2.js";import"./chunk-9wxj0gxa.js";import"./chunk-34cexc50.js";import"./chunk-74jd1hcs.js";import"./chunk-5cgyevqj.js";import"./chunk-7qj2tbew.js";import"./chunk-qgez5vw6.js";import"./chunk-3azdwanx.js";import{$c as R}from"./chunk-4p8sp6p3.js";import"./chunk-0evyrnx0.js";import{vd as Q}from"./chunk-vtb0m80j.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-kpr5nqh2.js";import"./chunk-3nj2f0q9.js";import"./chunk-3rjmkaey.js";import"./chunk-0s11h8yd.js";import"./chunk-vs7tcyse.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-ckfc7j7m.js";import"./chunk-keart8yy.js";import"./chunk-v11r4ahz.js";import"./chunk-v85q852a.js";import"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import"./chunk-6360fg4j.js";import"./chunk-bqpqh6re.js";import"./chunk-fk8jf873.js";import"./chunk-p504jme7.js";import"./chunk-8kqnezvc.js";import{wg as M}from"./chunk-mc42kjv9.js";import"./chunk-ew5dmar1.js";import"./chunk-03bzxkdg.js";import"./chunk-ts3pgkmz.js";import"./chunk-8jexqfqg.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ab as Xt,Bb as bn,Cb as Tn,Db as fn}from"./chunk-5cgyevqj.js";import{Bc as jt}from"./chunk-qgez5vw6.js";import{Ee as Bt}from"./chunk-
|
|
1
|
+
import{Ab as Xt,Bb as bn,Cb as Tn,Db as fn}from"./chunk-5cgyevqj.js";import{Bc as jt}from"./chunk-qgez5vw6.js";import{Ee as Bt}from"./chunk-keart8yy.js";import{$e as wn,Je as xt,Ke as tn,Le as en,Me as zt,Ne as U,Oe as rn,Pe as gt,Qe as mt,Se as dn,Te as En,Ue as B,Ve as on,We as pn,Xe as un,Ye as lt,Ze as cn,_e as Mn,bf as S,ef as yn,ff as Ht,gf as Ut,hf as R,if as qt}from"./chunk-v85q852a.js";import{Bf as X,Df as x}from"./chunk-93jx06kq.js";import{Nf as vt}from"./chunk-6360fg4j.js";import{wg as nn,xg as sn}from"./chunk-mc42kjv9.js";import{Ng as ss}from"./chunk-8jexqfqg.js";import{EventEmitter as hs}from"events";import Bn from"node:path";function An(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 _n(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||`验证失败:${An(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:_n(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;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}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 Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!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
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var I=600000,n=30000,R=3600000,t=12,r=15000,C=60000;function E(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=30000&&_<=3600000}var P=1e4,o=1000,M=300000;function N(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=300000}var D=4,T=1,U=16,S=180000,i=1000,x=600000;function V(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=16}function m(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=600000}
|
|
2
|
+
export{I as Of,n as Pf,R as Qf,t as Rf,r as Sf,C as Tf,E as Uf,P as Vf,o as Wf,M as Xf,N as Yf,D as Zf,T as _f,U as $f,S as ag,i as bg,x as cg,V as dg,m as eg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{I}from"./chunk-
|
|
1
|
+
import{I}from"./chunk-4dq8rbq2.js";import{xc as D}from"./chunk-7qj2tbew.js";import w from"node:path";function C(a){let t=a.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}function P(a){let t=a.replace(/\s+/g," ").trim();return t.length<=500?t:`${t.slice(0,497)}...`}function S(a){return`task/${a.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class z{static async createSessionTask(a){if(!a.prompt.trim())throw Error("Task prompt must not be blank");if(!w.isAbsolute(a.sourceProjectPath))throw Error("Task source project path must be absolute");let t=w.resolve(a.sourceProjectPath),s;try{return s=a.isolation==="worktree"?await I.enter({sessionId:a.sessionId,workspaceRoot:t,name:S(a.sessionId)}):void 0,{metadata:await D.createSessionMetadata(a.sessionId,s?.workspaceRoot??t,{title:a.title?.trim()||C(a.prompt),taskPromptSummary:P(a.prompt),taskDispatch:a.dispatch,taskModelId:a.dispatch?.modelId,selectedModelId:a.dispatch?.modelId,permissionMode:a.dispatch?.permissionMode,reasoningEffort:a.dispatch?.reasoningEffort,serviceTier:a.dispatch?.serviceTier,responseVerbosity:a.dispatch?.responseVerbosity,communicationStyle:a.dispatch?.communicationStyle,communicationStyleDigest:a.dispatch?.communicationStyleDigest,projectInstructionsDigest:a.dispatch?.projectInstructionsDigest,taskRetriedFrom:a.retriedFrom,taskIsolation:a.isolation,taskSourceProjectPath:t,taskWorktree:s}),taskWorktree:s}}catch(k){if(s)await I.exit({sessionId:a.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var N=256,Z=8388608,_=30000;class c extends Error{kind;pendingItems;pendingBytes;constructor(a,t,s){super(t,s);this.kind=a;this.name="BoundedSerialEgressError",this.pendingItems=s?.pendingItems,this.pendingBytes=s?.pendingBytes}}function m(a){a.catch(()=>{return})}class F{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(a){this.options=a;if(this.assertPositiveInteger(a.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(a.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(a.writeTimeoutMs,"writeTimeoutMs"),a.signal?.addEventListener("abort",this.handleAbort,{once:!0}),a.signal?.aborted)this.handleAbort()}offer(a){if(this.closed)return{accepted:!1,error:this.failure??new c("closed","Egress is already closed")};let t;try{t=this.options.sizeOf(a)}catch(i){return this.rejectAdmission(new c("invalid_size","Egress size calculation failed",{cause:i}))}if(!Number.isSafeInteger(t)||t<0)return this.rejectAdmission(new c("invalid_size","Egress size must be a non-negative safe integer"));if(t>this.options.maxPendingBytes)return this.rejectAdmission(new c("oversized",`Egress value requires ${t} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+t>this.options.maxPendingBytes)return this.rejectAdmission(new c("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let s,k,h=new Promise((i,f)=>{s=i,k=f});return m(h),this.nextSequence+=1,this.pending.push({value:a,bytes:t,sequence:this.nextSequence,resolve:s,reject:k,completion:h}),this.pendingBytes+=t,this.startDrain(),{accepted:!0,completion:h}}flush(){if(this.failure){let h=Promise.reject(this.failure);return m(h),h}let a=this.nextSequence;if(a<=this.completedSequence)return Promise.resolve();let t,s,k=new Promise((h,i)=>{t=h,s=i});return m(k),this.flushWaiters.push({targetSequence:a,resolve:t,reject:s}),k}close(a){let t=a instanceof c?a:new c("closed","Egress was closed",{cause:a});this.fail(t)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new c("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(a){return this.fail(a),{accepted:!1,error:a}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let a=this.drain();m(a)}async drain(){try{while(!this.closed){let a=this.pending[0];if(!a)return;try{await this.writeOne(a.value)}catch(t){this.fail(this.normalizeWriteError(t));return}if(this.closed||this.pending[0]!==a)return;this.pending.shift(),this.pendingBytes-=a.bytes,this.completedSequence=a.sequence,a.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(a){let t=new AbortController;this.activeWriteAbort=t;let s,k,h=new Promise((W,T)=>{k=T});m(h),this.activeWriteStop=k;let i=Promise.resolve().then(()=>this.options.write(a,t.signal));m(i);let f=new Promise((W,T)=>{s=setTimeout(()=>{let M=new c("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);t.abort(M),T(M)},this.options.writeTimeoutMs),this.activeWriteTimeout=s});m(f);try{await Promise.race([i,f,h])}finally{if(s!==void 0)clearTimeout(s);if(this.activeWriteTimeout===s)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===t)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(a){if(a instanceof c)return a;return new c("write_failed","Egress write failed",{cause:a})}fail(a){if(this.closed)return;if(a.pendingItems??=this.pending.length,a.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=a,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(a),this.activeWriteStop?.(a),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let t=this.pending.splice(0);this.pendingBytes=0;for(let s of t)s.reject(a);for(let s of this.flushWaiters.splice(0))s.reject(a);try{this.options.onFailure?.(a)}catch{}}settleFlushWaiters(){for(let a=0;a<this.flushWaiters.length;){let t=this.flushWaiters[a];if(t.targetSequence>this.completedSequence){a+=1;continue}this.flushWaiters.splice(a,1),t.resolve()}}assertPositiveInteger(a,t){if(!Number.isSafeInteger(a)||a<=0)throw RangeError(`${t} must be a positive safe integer`)}}
|
|
2
2
|
export{z as t,N as u,Z as v,_ as w,c as x,F as y};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{wg as d,yg as h}from"./chunk-mc42kjv9.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as Uc,w as Vc};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Cg as y}from"./chunk-03bzxkdg.js";import{Lg as b}from"./chunk-ts3pgkmz.js";import{createHash as N}from"node:crypto";import{constants as v,promises as d}from"node:fs";import W from"node:os";import a from"node:path";import{Mutex as A}from"async-mutex";import O from"write-file-atomic";var w=1,x=65536,T=1048576,m=100;function p(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function k(e,t=2048){return e.length<=t?e:`${e.slice(0,t-1)}…`}function S(e){if(typeof e!=="string"||!e.trim())return;try{let t=new URL(e);return k(`${t.origin}${t.pathname}`)}catch{return k(e)}}function D(e){return Array.isArray(e)?e.filter((t)=>typeof t==="string"):[]}function R(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.type==="string"?r.type:"unknown",n=typeof r.command==="string"?r.command:void 0,o=D(r.args),c=i==="stdio"?k([n,...o].filter(Boolean).join(" ")):S(r.url);return{kind:"mcp",name:`${t} (${i})`,...c?{target:c}:{}}})}function F(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.command==="string"?k(r.command):void 0,n=p(r.extensionToLanguage)?Object.keys(r.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${t} (${n})`,...i?{target:i}:{}}})}function j(e){if(!Array.isArray(e))return[];return e.slice(0,m).flatMap((t)=>{if(!p(t))return[];let s=typeof t.id==="string"?t.id:"unnamed",r=typeof t.provider==="string"?t.provider:"unknown",i=typeof t.model==="string"?t.model:"unknown",n=p(t.overrides)?t.overrides:{},o=S(n.baseUrl);return[{kind:"model",name:`${s}: ${r}/${i}`,...o?{target:o}:{}}]})}function $(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.wireApi==="string"?r.wireApi:"unknown",n=S(r.baseUrl);return{kind:"model",name:`${t} (${i})`,...n?{target:n}:{}}})}function P(e){if(!p(e))return[];let t=[];for(let s of["allow","ask","deny"])for(let r of D(e[s]).slice(0,m))t.push({kind:"permission",name:`${s}: ${k(r,512)}`});return t}function C(e){let t=[...R(e.mcpServers),...F(e.lspServers),...j(e.models),...$(e.modelProviders),...P(e.permissions)];if(p(e.env))for(let s of Object.keys(e.env).slice(0,m))t.push({kind:"environment",name:s});if(typeof e.permissionMode==="string")t.push({kind:"permission",name:`permissionMode: ${e.permissionMode}`});return t}function I(e){return e!=="hooks"&&e!=="disableAllHooks"}function M(e){return N("sha256").update(e).digest("hex")}function L(e,t){let s=a.relative(e,t);return s===""||!s.startsWith(`..${a.sep}`)&&s!==".."&&!a.isAbsolute(s)}class h{storeDir;static instance=null;mutex=new A;statusCache=new Map;constructor(e=a.join(b(),"workspace-trust")){this.storeDir=e}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}static resetInstance(){h.instance=null}async getStatus(e){let t=await y(e),s;try{s=await this.discoverSensitiveSources(t.projectPath)}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:0,sources:[],decision:"undecided",error:u instanceof Error?u.message:"Workspace trust review failed"};return this.cacheStatus(e,g),g}if(s.length===0){let u={...t,state:"not_required",trusted:!0,sensitiveSources:0,sources:s,decision:"undecided"};return this.cacheStatus(e,u),u}let r;try{r=await this.readDecisions()}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:s.length,sources:s,decision:"undecided",error:u instanceof Error?u.message:"Workspace trust store is unavailable"};return this.cacheStatus(e,g),g}let i=r.filter((u)=>L(u.path,t.trustRoot)),n=Math.max(-1,...i.map((u)=>u.path.split(a.sep).length)),o=i.filter((u)=>u.path.split(a.sep).length===n),c=o.length>0&&o.every((u)=>u.trusted),f=o[0],l=f?.path===t.trustRoot,E={...t,state:c?"trusted":"untrusted",trusted:c,sensitiveSources:s.length,sources:s,decision:f?l?f.trusted?"trusted":"untrusted":"inherited":"undecided",...f?.decidedAt?{decidedAt:f.decidedAt}:{},...!l&&f?.path?{inheritedFrom:f.path}:{}};return this.cacheStatus(e,E),E}cacheStatus(e,t){this.statusCache.set(a.resolve(e),t),this.statusCache.set(t.projectPath,t)}getCachedStatus(e){return this.statusCache.get(a.resolve(e))}isTrustedCached(e){return this.getCachedStatus(e)?.state==="trusted"}async trust(e){return this.recordDecision(e,!0)}async revoke(e){return this.recordDecision(e,!1)}async recordDecision(e,t){return this.mutex.runExclusive(async()=>{let s=await y(e);await this.assertSafeTrustRoot(s);let r={version:w,path:s.trustRoot,trusted:t,decidedAt:new Date().toISOString()};return await this.writeDecision(r),this.statusCache.clear(),this.getStatus(e)})}async assertSafeTrustRoot(e){let t=a.parse(e.trustRoot).root,s=await d.realpath(W.homedir()).catch(()=>a.resolve(W.homedir()));if(!a.isAbsolute(e.trustRoot)||e.trustRoot===t||e.trustRoot===s)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(e){let t=[],s=await this.reviewPackageScripts(e);if(s)t.push(s);for(let[r,i]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let n=await this.reviewConfigFile(e,r,i);if(n)t.push(n)}for(let r of[".blade/plugins",".claude/plugins"]){let i=await this.reviewResourceDirectory(e,r,"plugins","plugin");if(i)t.push(i)}for(let r of[".blade/commands",".claude/commands"]){let i=await this.reviewResourceDirectory(e,r,"commands","command");if(i)t.push(i)}for(let[r,i,n]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let o=await this.reviewResourceDirectory(e,r,i,n);if(o)t.push(o)}for(let r of["CLAUDE.md","AGENTS.md","BLADE.md"]){let i=await this.reviewInstructionFile(e,r);if(i)t.push(i)}return t}async reviewPackageScripts(e){let t=a.join(e,"package.json"),s;try{s=await d.stat(t)}catch(o){if(o.code==="ENOENT")return;throw o}if(!s.isFile())return;if(s.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let r;try{r=JSON.parse(await d.readFile(t,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!p(r)||!p(r.scripts))return;let i=r.scripts,n=Object.keys(i).filter((o)=>typeof i[o]==="string").sort().slice(0,m);if(n.length===0)return;return{path:"package.json",kind:"package",keys:n,effects:n.map((o)=>({kind:"command",name:`package script: ${o}`}))}}async reviewInstructionFile(e,t){try{if(!(await d.stat(a.join(e,t))).isFile())return}catch(s){if(s.code==="ENOENT")return;throw s}return{path:t,kind:"instructions",keys:[t],effects:[{kind:"instruction",name:t}]}}async reviewConfigFile(e,t,s){let r=a.join(e,t),i;try{i=await d.stat(r)}catch(l){if(l.code==="ENOENT")return;throw l}if(!i.isFile())return;if(i.size>T)throw Error(`${t} exceeds the 1 MiB workspace review limit`);let n;try{n=JSON.parse(await d.readFile(r,"utf8"))}catch{return{path:t,kind:s,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!p(n))return{path:t,kind:s,keys:[],effects:[],warning:"Configuration root is not an object"};let o=Object.keys(n).filter(I).sort();if(o.length===0)return;let c=C(n),f=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let l of o)if(!f.has(l))c.push({kind:"configuration",name:l});return{path:t,kind:s,keys:o,effects:c}}async reviewResourceDirectory(e,t,s,r){let i=a.join(e,t),n;try{n=await d.readdir(i,{withFileTypes:!0})}catch(c){if(c.code==="ENOENT")return;throw c}let o=n.filter((c)=>s==="plugins"||s==="skills"?c.isDirectory()||c.isSymbolicLink():c.isFile()||c.isDirectory()||c.isSymbolicLink()).slice(0,m);if(o.length===0)return;return{path:t,kind:s,keys:o.map((c)=>c.name),effects:o.map((c)=>({kind:r,name:c.name}))}}async readDecisions(){let e;try{e=await d.lstat(this.storeDir)}catch(r){if(r.code==="ENOENT")return[];throw r}if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let t=await d.readdir(this.storeDir,{withFileTypes:!0}),s=[];for(let r of t){if(!r.name.endsWith(".json"))continue;if(!r.isFile())throw Error("Workspace trust store entries must be regular files");s.push(await this.readDecision(a.join(this.storeDir,r.name)))}return s}async readDecision(e){let t;try{t=await d.open(e,v.O_RDONLY|v.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let s=await t.stat();if(!s.isFile()||s.size>x)throw Error("Workspace trust decision is invalid");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let r=JSON.parse(await t.readFile("utf8"));if(!p(r)||r.version!==w||typeof r.path!=="string"||!a.isAbsolute(r.path)||typeof r.trusted!=="boolean"||typeof r.decidedAt!=="string"||!Number.isFinite(Date.parse(r.decidedAt))||Object.keys(r).some((i)=>i!=="version"&&i!=="path"&&i!=="trusted"&&i!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:w,path:r.path,trusted:r.trusted,decidedAt:r.decidedAt}}finally{await t.close()}}async writeDecision(e){await this.ensureStoreDirectoryForWrite();let t=a.join(this.storeDir,`${M(e.path)}.json`);try{let s=await d.lstat(t);if(!s.isFile()||s.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(s){if(s.code!=="ENOENT")throw s}await O(t,`${JSON.stringify(e,null,2)}
|
|
2
2
|
`,{mode:384}),await d.chmod(t,384)}async ensureStoreDirectoryForWrite(){try{let e=await d.lstat(this.storeDir);if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(e){if(e.code!=="ENOENT")throw e;await d.mkdir(this.storeDir,{recursive:!0,mode:448}),await d.chmod(this.storeDir,448)}}}
|
|
3
|
-
export{h as
|
|
3
|
+
export{h as Bg};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Nd as a}from"./chunk-kpr5nqh2.js";import"./chunk-bqpqh6re.js";import"./chunk-fk8jf873.js";import"./chunk-p504jme7.js";import"./chunk-8kqnezvc.js";import"./chunk-ts3pgkmz.js";import"./chunk-8jexqfqg.js";export{a as createChatServiceAsync};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Lg as j}from"./chunk-ts3pgkmz.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
|
|
2
2
|
`)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
|
|
3
|
-
export{m as
|
|
3
|
+
export{m as fg,I as gg,M as hg,V as ig,h as jg};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Kg as $,Lg as F}from"./chunk-ts3pgkmz.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
|
|
2
2
|
`,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
|
|
3
3
|
export{_ as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{rc as a,sc as b,tc as c,uc as d,vc as e,wc as f,xc as g}from"./chunk-
|
|
1
|
+
import{rc as a,sc as b,tc as c,uc as d,vc as e,wc as f,xc as g}from"./chunk-7qj2tbew.js";import"./chunk-qgez5vw6.js";import"./chunk-3azdwanx.js";import"./chunk-3rjmkaey.js";import"./chunk-zwt7f9ab.js";import"./chunk-v11r4ahz.js";import"./chunk-thstqcg3.js";import"./chunk-6360fg4j.js";import"./chunk-fk8jf873.js";import"./chunk-8kqnezvc.js";import"./chunk-mc42kjv9.js";import"./chunk-ts3pgkmz.js";import"./chunk-8jexqfqg.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$a as a,ab as b,cb as c,gb as d,hb as e,ib as f,jb as g,kb as h,lb as i,mb as j,nb as k,sb as l,tb as m,ub as n,vb as o,xb as p,yb as q,zb as r}from"./chunk-74jd1hcs.js";import"./chunk-5cgyevqj.js";import"./chunk-7qj2tbew.js";import"./chunk-qgez5vw6.js";import"./chunk-3azdwanx.js";import"./chunk-atsw605q.js";import"./chunk-kpr5nqh2.js";import"./chunk-3rjmkaey.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-keart8yy.js";import"./chunk-v11r4ahz.js";import"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import"./chunk-6360fg4j.js";import"./chunk-bqpqh6re.js";import"./chunk-fk8jf873.js";import"./chunk-p504jme7.js";import"./chunk-8kqnezvc.js";import"./chunk-mc42kjv9.js";import"./chunk-03bzxkdg.js";import"./chunk-ts3pgkmz.js";import"./chunk-8jexqfqg.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Mc as a,Nc as b,Oc as c,Pc as d,Qc as e,Rc as f,Sc as g,Tc as h}from"./chunk-
|
|
1
|
+
import{Mc as a,Nc as b,Oc as c,Pc as d,Qc as e,Rc as f,Sc as g,Tc as h}from"./chunk-3azdwanx.js";import"./chunk-fk8jf873.js";import"./chunk-ts3pgkmz.js";import"./chunk-8jexqfqg.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{wg as S}from"./chunk-mc42kjv9.js";import{Ng as f}from"./chunk-8jexqfqg.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
|
|
2
2
|
export{_ as a,u as b,g as c,C as d,V as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ie as YO}from"./chunk-v11r4ahz.js";import{Bf as qO,Df as S,Gf as y}from"./chunk-93jx06kq.js";import{Nf as K}from"./chunk-6360fg4j.js";import{
|
|
1
|
+
import{Ie as YO}from"./chunk-v11r4ahz.js";import{Bf as qO,Df as S,Gf as y}from"./chunk-93jx06kq.js";import{Nf as K}from"./chunk-6360fg4j.js";import{ig as XO}from"./chunk-fk8jf873.js";import{Cg as n}from"./chunk-03bzxkdg.js";import{Lg as r}from"./chunk-ts3pgkmz.js";import{Ng as w}from"./chunk-8jexqfqg.js";var N;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(N||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import _ from"node:path";import{nanoid as z}from"nanoid";var C={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import jO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import h from"node:path";import{Mutex as WO}from"async-mutex";import SO from"write-file-atomic";var k=1,GO=1048576,VO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function LO(O){let q={};for(let Q of Object.values(N)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(N))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(LO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new WO;filePath;constructor(O=h.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let J;try{J=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let W=J.projects[Z];if(!W)return{...X,state:"untrusted"};return{...X,state:W.digest===$?"trusted":"modified",trustedDigest:W.digest,trustedAt:W.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:k,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>GO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==k)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!h.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!VO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:k,projects:Z}}async writeStore(O){let q=h.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await SO(this.filePath,`${JSON.stringify(O,null,2)}
|
|
2
2
|
`,{mode:384}),await j.chmod(this.filePath,384)}}class T extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function e(O,q={}){let Q;try{Q=new URL(O)}catch{throw new T(`Invalid URL: ${O}`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw new T(`Only http/https supported, got: ${Q.protocol}`);let Z=Q.hostname.toLowerCase();if(zO(Z,q.allowedHosts))return;if(Q.protocol==="http:"&&!q.allowHttp)throw new T(`HTTP (non-TLS) blocked for ${Z}; use https:// or add to allowedHosts`);if(BO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(AO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function zO(O,q){if(!q||q.length===0)return!1;return q.some((Q)=>{let Z=Q.toLowerCase();if(Z===O)return!0;if(Z.startsWith("*.")){let Y=Z.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function BO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function AO(O){let q=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!q)return!1;let[Q,Z]=q.slice(1).map(Number);if(Q===10)return!0;if(Q===172&&Z>=16&&Z<=31)return!0;if(Q===192&&Z===168)return!0;if(Q===169&&Z===254)return!0;return!1}function OO(O){if(!O)return{};let q={};for(let[Q,Z]of Object.entries(O))q[Q]=Z.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,$)=>{return process.env[$]??`\${${$}}`});return q}var KO=S.Object({hookEventName:S.Literal("PreToolUse"),permissionDecision:S.Optional(S.Enum(m)),permissionDecisionReason:S.Optional(S.String()),updatedInput:S.Optional(S.Record(S.String(),S.Unknown()))}),PO=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),_O=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),UO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),bO=S.Object({hookEventName:S.Literal("PermissionRequest"),permissionDecision:S.Optional(y(["approve","deny","ask"])),permissionDecisionReason:S.Optional(S.String())}),QO=S.Record(S.String(),S.Union([S.String(),S.Number(),S.Boolean(),S.Array(S.String(),{maxItems:100})]),{maxProperties:32}),NO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),MO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),wO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),CO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),EO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([KO,PO,_O,UO,bO,NO,MO,TO,wO,CO])),suppressOutput:S.Optional(S.Boolean())});function ZO(O){return qO(EO,O)}class p{parse(O,q,Q){if(O.timedOut){let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let Z=this.tryParseJSON(O.stdout);if(Z){let Y=ZO(Z);if(!Y.success){let X="error"in Y?Y.error.message:"Unknown validation error",J=Q?.failureBehavior||"ignore",W=`Invalid hook output JSON: ${X}`;if(J==="deny")return{success:!1,blocking:!0,error:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(J==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${W}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let $=Y.data;if($.decision?.behavior==="block")return{success:!1,blocking:!0,error:$.systemMessage||"Hook blocked execution",output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};if($.decision?.behavior==="async")return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}return this.parseByExitCode(O,q,Q)}parseByExitCode(O,q,Q){let Z=O.exitCode;switch(Z){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 124:{let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}default:{let Y=Q?.failureBehavior||"ignore",$=O.stderr||O.stdout||`Hook failed with exit code ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${$}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}}}tryParseJSON(O){try{let q=O.trim();if(!q)return null;let Q=q.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Q)return null;return JSON.parse(Q[1])}catch{return null}}}class l{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let q=this.maxSize-this.content.length;this.content+=O.substring(0,q)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class u{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,q,Q,Z){let Y=JSON.stringify(q);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let $=this.createSafeEnv(q,Q.environment),{child:X,processTree:J}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),W=new l(this.MAX_STDOUT_SIZE),G=new l(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{W.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await J.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,R)=>{let F=!1,V=!1,B,P=()=>{return B??=J.terminate(),B},b=null,H=()=>{if(b&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",b),b=null},I=setTimeout(()=>{F=!0,P()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(I),H(),F)await P();L({stdout:W.getContent(),stderr:G.getContent(),exitCode:F?124:f??1,timedOut:F})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(I),H(),R(f)}),Q.abortSignal){if(b=()=>{if(V)return;V=!0,clearTimeout(I),H(),P().then(()=>{L({stdout:W.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",b),Q.abortSignal.aborted)b()}})}createSafeEnv(O,q={}){return{...q,PATH:q.PATH??process.env.PATH??"",HOME:q.HOME??process.env.HOME??"",USER:q.USER??process.env.USER??"",SHELL:q.SHELL??process.env.SHELL??"/bin/sh",BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:""}}}var $O=XO("Execution"),DO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',Elicitation:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',ElicitationResult:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class x{processExecutor=new u;outputParser=new p;chatServiceCache=new Map;sessionModelResources=new Map;sessionEnvironments=new Map;trustWarnings=new Set;bindSessionModelResources(O,q,Q){for(let Z of q)this.sessionModelResources.set(this.sessionResourceKey(O,Z),Q),this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q.config.env)}bindSessionEnvironment(O,q,Q){for(let Z of q)this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q)}async unbindSessionModelResources(O,q){for(let Q of q){let Z=this.sessionResourceKey(O,Q);this.sessionModelResources.delete(Z),this.sessionEnvironments.delete(Z);let Y=`${Z}\x00`;for(let[$,X]of this.chatServiceCache){if(!$.startsWith(Y))continue;this.chatServiceCache.delete($),await X.dispose?.()}}}async executePreToolHooks(O,q,Q){if(O.length===0)return{decision:"allow"};let Z="tool_input"in q?q.tool_input:{},Y=[];for(let $ of O)try{let X={...q,...Z&&{tool_input:Z}},J=await this.executeHook($,X,Q);if(!J.success){if(J.blocking)return{decision:"deny",reason:J.error};if(J.needsConfirmation)return{decision:"ask",reason:J.warning||J.error};if(J.warning)Y.push(J.warning);continue}let W=J.output?.hookSpecificOutput;if(W&&"permissionDecision"in W){switch(W.permissionDecision){case"deny":return{decision:"deny",reason:W.permissionDecisionReason};case"ask":return{decision:"ask",reason:W.permissionDecisionReason};case"allow":break}if("updatedInput"in W&&W.updatedInput)Z={...Z,...W.updatedInput}}}catch(X){let J=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${J}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:J};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${J}. Continue?`}}return{decision:"allow",modifiedInput:Z,warning:Y.length>0?Y.join(`
|
|
3
3
|
`):void 0}}async executePostToolHooks(O,q,Q){if(O.length===0)return{};let Z=Q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,q,Q,Z),$=[],X=void 0,J=[];for(let W of Y){if(!W.success&&W.warning){J.push(W.warning);continue}let G=W.output?.hookSpecificOutput;if(G&&"additionalContext"in G){if(G.additionalContext)$.push(G.additionalContext);if("updatedOutput"in G&&G.updatedOutput!==void 0)X=G.updatedOutput}}return{additionalContext:$.length>0?$.join(`
|
|
4
4
|
|
|
@@ -25,7 +25,7 @@ import{Ie as YO}from"./chunk-v11r4ahz.js";import{Bf as qO,Df as S,Gf as y}from".
|
|
|
25
25
|
`):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let J of O)try{let W=await this.executeHook(J,q,Q);if(!W.success){if(W.warning)Y.push(W.warning);continue}if(W.output?.suppressOutput){$=!0;break}if(W.stdout&&W.stdout.trim())X=W.stdout.trim()}catch(W){let G=W instanceof Error?W.message:String(W);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
|
|
26
26
|
`):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
|
|
27
27
|
`):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
|
|
28
|
-
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal)).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-
|
|
28
|
+
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-r01spp7a.js"),{createChatServiceAsync:J}=await import("./chunk-fa1gxd12.js"),{resolveModelConfig:W}=await import("./chunk-s3nz9qx8.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-vtdg5cb1.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
|
|
29
29
|
|
|
30
30
|
`+`## 评估指令
|
|
31
31
|
${O.prompt}
|