blade-code 0.10.17 → 0.10.19
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-cd087ckq.js → chunk-07mstszb.js} +2 -2
- package/dist/{chunk-kjet3e74.js → chunk-1wz10w2m.js} +1 -1
- package/dist/{chunk-z9mpf0t7.js → chunk-1ydqqzp1.js} +1 -1
- package/dist/{chunk-bpnyda6p.js → chunk-29axr7g4.js} +1 -1
- package/dist/chunk-2gj76ba1.js +1 -0
- package/dist/{chunk-ab3a9gdc.js → chunk-30e3v8cw.js} +1 -1
- package/dist/{chunk-bjzykvs1.js → chunk-36626eyr.js} +1 -1
- package/dist/{chunk-gjw014rv.js → chunk-3gra6n0k.js} +1 -1
- package/dist/{chunk-2675vkx5.js → chunk-5a8tqdrk.js} +1 -1
- package/dist/{chunk-wvh6entt.js → chunk-5ra89kse.js} +1 -1
- package/dist/{chunk-rn04c7hs.js → chunk-6r0nj7ay.js} +1 -1
- package/dist/{chunk-bqgd4db7.js → chunk-8mafna0v.js} +1 -1
- package/dist/{chunk-fm8vpym2.js → chunk-8zywzb9j.js} +1 -1
- package/dist/{chunk-a0hk9xrj.js → chunk-aem57a6n.js} +1 -1
- package/dist/{chunk-fneamw65.js → chunk-amzz0mk6.js} +1 -1
- package/dist/{chunk-hm3yme2m.js → chunk-c6rff43d.js} +1 -1
- package/dist/{chunk-6yjn2wj7.js → chunk-ctkxf0y7.js} +50 -50
- package/dist/{chunk-677ywzhs.js → chunk-cyda7gnb.js} +1 -1
- package/dist/{chunk-w320ev24.js → chunk-ddqwtw3z.js} +1 -1
- package/dist/{chunk-rgy886ad.js → chunk-et9k9pac.js} +1 -1
- package/dist/{chunk-nqj9c68w.js → chunk-hmvyreyx.js} +3 -3
- package/dist/{chunk-hxcd65h1.js → chunk-kgypdjdw.js} +1 -1
- package/dist/{chunk-6aw8vpf8.js → chunk-ks6by04t.js} +1 -1
- package/dist/{chunk-2x0marf0.js → chunk-mg421b17.js} +1 -1
- package/dist/{chunk-wzvy13p2.js → chunk-qwxqfb9z.js} +1 -1
- package/dist/{chunk-3d4cgnpw.js → chunk-t8g4288j.js} +1 -1
- package/dist/{chunk-amdw5728.js → chunk-tcnnh890.js} +1 -1
- package/dist/{chunk-c18qckn4.js → chunk-y5fk4fx5.js} +1 -1
- package/dist/{chunk-ncj12cv0.js → chunk-ycwrykxe.js} +1 -1
- package/dist/{chunk-8vd6q2wt.js → chunk-yp02wzek.js} +1 -1
- package/dist/{chunk-774jxdm3.js → chunk-yxmy7g38.js} +1 -1
- package/dist/{chunk-69ma931b.js → chunk-zek2ec3c.js} +1 -1
- package/dist/{chunk-w9zgpqjd.js → chunk-zgt1jpgg.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-wygpe92c.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{cc as v,dc as Lq,ec as $$,fc as Zq,gc as u,hc as q$,ic as Qq,jc as G$,kc as J$,lc as L$,nc as M0,qc as Z$,rc as xq}from"./chunk-8rzwyknk.js";import{sd as K0}from"./chunk-5chec8rs.js";import{Xd as V0}from"./chunk-6sb7cg95.js";import{ee as k$}from"./chunk-q3c07kb4.js";import{ie as W0}from"./chunk-6207mbmr.js";import{gf as Gq,hf as Jq}from"./chunk-3qhqbj09.js";import{mf as X$}from"./chunk-prgh321y.js";import{sf as x0,vf as N0}from"./chunk-yqfqj7mh.js";import{zf as l}from"./chunk-
|
|
1
|
+
import{cc as v,dc as Lq,ec as $$,fc as Zq,gc as u,hc as q$,ic as Qq,jc as G$,kc as J$,lc as L$,nc as M0,qc as Z$,rc as xq}from"./chunk-8rzwyknk.js";import{sd as K0}from"./chunk-5chec8rs.js";import{Xd as V0}from"./chunk-6sb7cg95.js";import{ee as k$}from"./chunk-q3c07kb4.js";import{ie as W0}from"./chunk-6207mbmr.js";import{gf as Gq,hf as Jq}from"./chunk-3qhqbj09.js";import{mf as X$}from"./chunk-prgh321y.js";import{sf as x0,vf as N0}from"./chunk-yqfqj7mh.js";import{zf as l}from"./chunk-cyda7gnb.js";import{Gf as qq,Hf as H0,Jf as R,Kf as m,Mf as e0,Nf as c,Of as Z0}from"./chunk-yvf4nmds.js";import{readdir as i$,readFile as t,rm as D0,stat as eq}from"node:fs/promises";import*as C from"node:path";import{nanoid as j}from"nanoid";import{createHash as Yq,randomUUID as Cq}from"node:crypto";import*as I from"node:fs/promises";import*as X0 from"node:path";var T$=1;function Hq($,q){let G=Yq("sha256").update(q).digest("hex");return X0.join(H0($),".locks",`${G}.lock`)}function C0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function m0($){try{let q=JSON.parse(await I.readFile($,"utf8"));if(q.version!==T$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function C$($){let q=await m0($);if(q)return q;return await new Promise((G)=>setTimeout(G,10)),m0($)}function Xq($){try{return process.kill($,0),!0}catch(q){return C0(q,"EPERM")}}async function H$($,q){let G;try{return G=await I.open($,"wx",384),await G.writeFile(`${JSON.stringify(q)}
|
|
2
2
|
`,"utf8"),!0}catch(J){if(C0(J,"EEXIST"))return!1;if(G)await I.unlink($).catch(()=>{return});throw J}finally{await G?.close().catch(()=>{return})}}class n extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class i{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=X$()){let G=Hq(q,$),J={version:T$,sessionId:$,ownerId:Cq(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await I.mkdir(X0.dirname(G),{recursive:!0,mode:448}),await H$(G,J))return new i(G,J);let Z=await C$(G);if(Z&&Xq(Z.pid))throw new n(Z.pid);if(await I.unlink(G).catch((L)=>{if(!C0(L,"ENOENT"))throw L}),await H$(G,J))return new i(G,J);throw new n((await C$(G))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await m0(this.filePath))?.ownerId!==this.record.ownerId)return;await I.unlink(this.filePath).catch((q)=>{if(!C0(q,"ENOENT"))throw q})}}var R1=1;function I0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Tq($){if(!I0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&I0($.image_url)&&typeof $.image_url.url==="string"}function Fq($){if(!I0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(Tq)}function F$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let q=JSON.stringify($);if(Buffer.byteLength(q)>16777216)return;let G=JSON.parse(q);if(!Array.isArray(G)||!G.every(Fq))return;return G}function M1($){let q=F$($);if(!q)throw Error("Compaction replacement context is invalid or exceeds limits");return q}function W$($){return F$($)}function Wq($,q){for(let G of $){if(G.type!=="part_created"||G.data.partType!=="tool_result")continue;let J=G.data.payload;if(!J||typeof J!=="object"||Array.isArray(J))continue;let Z=J;if(Z.toolCallId===q||G.data.partId===q||G.data.messageId===q)return Z}return}function O$($){let q=v($),G=new Map;for(let J of q){if(J.type==="interaction_requested"){G.set(J.data.requestId,{request:J.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(J.type==="interaction_responded"){let Z=G.get(J.data.requestId);if(Z)Z.response=J.data;continue}if(J.type==="interaction_recovered"){let Z=G.get(J.data.requestId);if(Z)Z.recovery=J.data}}for(let J of G.values()){let Z=Wq(q,J.request.toolCallId);J.hasToolResult=Z!==void 0;let L=Z?.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0;J.hasRecoveryToolResult=L?.interactionRecovery===!0&&L.requestId===J.request.requestId}return[...G.values()]}function _$($){return O$($).reverse().find((q)=>!q.response&&!q.recovery)}function w1($){let q=new Map;for(let G of O$($))q.set(G.request.toolCallId,G);return[...q.values()].filter((G)=>G.response&&!G.recovery&&(!G.hasToolResult||G.hasRecoveryToolResult))}function U$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function T0($){let q=new Map,G=[];for(let J of $){if(J.type==="review_started"){if(!q.has(J.data.reviewId))G.push(J.data.reviewId),q.set(J.data.reviewId,{start:J.data});continue}if(J.type!=="review_completed")continue;let Z=q.get(J.data.reviewId);if(Z&&Z.completion===void 0)Z.completion=J.data}return G.map((J)=>q.get(J)).filter((J)=>J!==void 0)}function k1($){return T0($).reverse().find((q)=>q.completion===void 0)}function v0($){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 z$($,q){let G=["## Code Review","",`Target: ${$.target.label}`,`Status: ${v0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)G.push("","No actionable findings.");else{G.push("","### Findings");for(let[J,Z]of q.findings.entries()){let L=Z.codeLocation.lineStart===Z.codeLocation.lineEnd?`${Z.codeLocation.lineStart}`:`${Z.codeLocation.lineStart}-${Z.codeLocation.lineEnd}`;G.push("",`${J+1}. ${Z.title}`,` ${Z.codeLocation.path}:L${L} · confidence ${Z.confidenceScore.toFixed(2)}`,` ${Z.body}`)}}if(q.error)G.push("",`Error: ${q.error}`);return G.join(`
|
|
3
3
|
`)}function f$($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((G)=>({title:G.title,body:G.body,priority:G.priority,confidenceScore:G.confidenceScore,codeLocation:{...G.codeLocation}})),...q.error?{error:q.error}:{}}}var u0={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 Oq($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function _q($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";return"runtime"}function Uq($){return{code:$,...u0[$]}}function P0($){return Uq(_q(Oq($)))}function h0($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in u0))return!1;let G=u0[q.code];return q.message===G.message&&q.retryable===G.retryable}import{promises as G0,realpathSync as fq}from"node:fs";import F0 from"node:path";import*as o from"fs/promises";import*as O from"path";var D$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class c0{static normalize($,q){let G=O.isAbsolute($)?$:O.resolve(q,$),J=O.normalize(G),Z=O.normalize(q);if(!this.isWithinWorkspace(J,Z))throw new d(`Path outside workspace: ${$} (resolved to ${J}, workspace: ${Z})`,"PATH_OUTSIDE_WORKSPACE");return J}static checkRestricted($){let q=$.split(O.sep);for(let G of D$)if(q.includes(G))throw new d(`Access denied: "${G}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let G=this.normalize($,q);this.checkRestricted(G);try{await o.access(G)}catch(J){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return G}static async resolveSymlink($,q){try{let G=await o.realpath($),J=await o.realpath(q);if(!this.isWithinWorkspace(G,J))throw new d(`Symlink points outside workspace: ${$} -> ${G}`,"SYMLINK_OUTSIDE_WORKSPACE");return G}catch(G){if(G instanceof d)throw G;return $}}static getRelativePath($,q){return O.relative(q,$)}static isWithinWorkspace($,q){let G=O.resolve($),J=O.resolve(q),Z=O.relative(J,G);return Z===""||Z!==".."&&!Z.startsWith(`..${O.sep}`)&&!O.isAbsolute(Z)}static async isWithinWorkspaceResolved($,q){let G=O.resolve(q),J=O.isAbsolute($)?O.resolve($):O.resolve(G,$);if(!this.isWithinWorkspace(J,G))return!1;let Z;try{Z=await o.realpath(G)}catch{return!1}let L=J;while(!0){try{let x=await o.realpath(L);return this.isWithinWorkspace(x,Z)}catch(x){let V=x.code;if(V!=="ENOENT"&&V!=="ENOTDIR")return!1}let Q=O.dirname(L);if(Q===L)return!1;L=Q}}static isRestricted($){let q=$.split(O.sep);return D$.some((G)=>q.includes(G))}}var J0=W0("Tool");class h{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}async recordFileRead($,q){try{let G=await G0.stat($),J={filePath:F0.resolve($),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(J),await this.recordAliases($,J.filePath),J0.debug(`记录文件读取: ${$}`)}catch(G){J0.warn(`记录文件读取失败: ${$}`,G)}}async recordFileEdit($,q,G="edit"){try{let J=await G0.stat($),Z={filePath:F0.resolve($),accessTime:Date.now(),mtime:J.mtimeMs,sessionId:q,lastOperation:G};this.setRecord(Z),await this.recordAliases($,Z.filePath),J0.debug(`记录文件${G==="edit"?"编辑":"写入"}: ${$}`)}catch(J){J0.warn(`记录文件${G==="edit"?"编辑":"写入"}失败: ${$}`,J)}}hasFileBeenRead($,q){let G=this.accessedFiles.get(this.resolveTrackedPath($));if(!G)return!1;return q?G.has(q):G.size>0}async checkFileModification($,q){let G=this.getFileRecord($,q);if(!G)return{modified:!1,message:"文件未被跟踪"};try{let J=await G0.stat($);if(Math.abs(J.mtimeMs-G.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(G.accessTime).toISOString()}, 当前修改时间: ${J.mtime.toISOString()})`};return{modified:!1}}catch(J){let Z=J;if(Z.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${Z.message}`}}}async checkExternalModification($,q){let G=this.getFileRecord($,q);if(!G)return{isExternal:!1,message:"文件未被跟踪"};try{let J=await G0.stat($);if(J.mtimeMs-G.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(G.accessTime).toISOString()} (${G.lastOperation}) 之后被外部程序修改(当前修改时间: ${J.mtime.toISOString()})`};return{isExternal:!1}}catch(J){let Z=J;if(Z.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return J0.warn(`检查文件外部修改失败: ${$}`,J),{isExternal:!1,message:`无法检查文件状态: ${Z.message}`}}}getFileRecord($,q){let G=this.accessedFiles.get(this.resolveTrackedPath($));if(!G)return;if(q)return G.get(q);return[...G.values()].sort((J,Z)=>Z.accessTime-J.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let G=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(G),this.removeAliases(G);return}let J=this.accessedFiles.get(G);if(J?.delete(q),J?.size===0)this.accessedFiles.delete(G),this.removeAliases(G)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[G,J]of this.accessedFiles.entries()){if(q&&!c0.isWithinWorkspace(G,q))continue;if(J.delete($),J.size===0)this.accessedFiles.delete(G),this.removeAliases(G)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){h.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(F0.resolve($),q);let G=await G0.realpath($).catch(()=>{return});if(G)this.pathAliases.set(G,q)}resolveTrackedPath($){let q=F0.resolve($);if(this.accessedFiles.has(q))return q;let G=this.pathAliases.get(q);if(G)return G;try{let J=fq.native(q);return this.pathAliases.get(J)??J}catch{return q}}removeAliases($){for(let[q,G]of this.pathAliases)if(G===$)this.pathAliases.delete(q)}}import*as L0 from"node:crypto";import{promises as X}from"node:fs";import*as F from"node:path";import l0 from"write-file-atomic";var R$="missing";class O0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(R($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!F.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?F.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=Z0();this.snapshotDir=F.join(q,"file-history",this.sessionId),this.manifestPath=F.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await X.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=Z0(),q=await X.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),G=L0.createHash("sha256").update(q).digest("hex").slice(0,24),J=F.join($,"file-history",this.sessionId),Z=F.join($,"file-history","workspaces",G,this.sessionId),L=F.join(Z,"manifest.json");try{await X.access(L)}catch{await this.migrateLegacySnapshotDir(J,Z,q)}this.snapshotDir=Z,this.manifestPath=L}async migrateLegacySnapshotDir($,q,G){let J;try{J=JSON.parse(await X.readFile(F.join($,"manifest.json"),"utf8"))}catch{return}if(J.schemaVersion!==1||!Array.isArray(J.snapshots)||!J.snapshots.every((Z)=>this.isWithinWorkspace(Z.filePath,G)))return;await X.mkdir(F.dirname(q),{recursive:!0,mode:493});try{await X.rename($,q)}catch(Z){let L=Z.code;if(L!=="ENOENT"&&L!=="EEXIST"&&L!=="ENOTEMPTY")throw Z}}isWithinWorkspace($,q){if(!F.isAbsolute($))return!1;let G=F.relative(q,F.resolve($));return G===""||G!==".."&&!G.startsWith(`..${F.sep}`)&&!F.isAbsolute(G)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let G=await this.resolveFileIdentity($),J=!0;try{await X.access(G)}catch{J=!1}let Z=this.trackedFileBackups.get(G),L=Z?Z.version+1:1,Q=this.generateFileHash(G,L),x=this.getSnapshotPath(Q,L),V=new Date;if(J){let K=await X.readFile(G);await X.writeFile(x,K)}let N={backupFileName:Q,version:L,backupTime:V};return this.trackedFileBackups.set(G,N),this.snapshots.push({messageId:q,backupFileName:Q,timestamp:V,filePath:G,version:L,existedBefore:J}),await this.cleanupOldSnapshots(G),await this.persistManifest(),N}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let G=await this.resolveFileIdentity($),J=this.snapshots.find((Z)=>Z.filePath===G&&Z.backupFileName===q.backupFileName&&Z.version===q.version);if(!J)throw Error(`未找到待完成的快照: ${G}`);J.postEditHash=await this.hashFile(G),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let G=await this.resolveFileIdentity($),J=this.snapshots.find((Z)=>Z.filePath===G&&Z.backupFileName===q.backupFileName&&Z.version===q.version);if(!J)return;this.removeSnapshot(J),await X.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),G=this.snapshots.slice().reverse().find((L)=>L.filePath===q&&L.postEditHash!==void 0);if(!G?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==G.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let Z=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let L=await X.readFile(Z);await X.mkdir(F.dirname(q),{recursive:!0}),await X.writeFile(q,L)}else await X.rm(q,{force:!0});return this.removeSnapshot(G),await X.rm(Z,{force:!0}),await this.persistManifest(),G}async restoreSnapshot($,q){let G=await this.resolveFileIdentity($),J=this.snapshots.slice().reverse().find((L)=>L.messageId===q&&L.filePath===G);if(!J)throw Error(`未找到快照: messageId=${q}, filePath=${G}`);let Z=this.getSnapshotPath(J.backupFileName,J.version);if(J.existedBefore){let L=await X.readFile(Z);await X.mkdir(F.dirname(G),{recursive:!0}),await X.writeFile(G,L)}else await X.rm(G,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((G)=>G.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((G)=>G.filePath),snapshotCount:q.reduce((G,J)=>G+J.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let G=new Map;for(let Z of q){let L,Q=!0;try{L=await X.readFile(Z.filePath)}catch(V){if(V.code!=="ENOENT")throw V;Q=!1}if((L?L0.createHash("sha256").update(L).digest("hex"):R$)!==Z.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${Z.filePath}`);if(G.set(Z.filePath,{existed:Q,content:L}),Z.target.existedBefore)await X.access(this.getSnapshotPath(Z.target.backupFileName,Z.target.version))}let J=[...this.snapshots];try{for(let L of q)if(L.target.existedBefore){let Q=await X.readFile(this.getSnapshotPath(L.target.backupFileName,L.target.version));await X.mkdir(F.dirname(L.filePath),{recursive:!0}),await l0(L.filePath,Q)}else await X.rm(L.filePath,{force:!0});let Z=new Set(q.flatMap((L)=>L.selected));this.snapshots=this.snapshots.filter((L)=>!Z.has(L)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...Z].map((L)=>X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}).catch(()=>{return})))}catch(Z){this.snapshots=J,this.rebuildTrackedFileBackups();let L=[];for(let[Q,x]of G)try{if(x.existed&&x.content)await l0(Q,x.content);else await X.rm(Q,{force:!0})}catch(V){L.push(V)}if(L.length>0)throw AggregateError([Z,...L],"快照回退失败且无法完整恢复回退前状态");throw Z}return{files:q.map((Z)=>Z.filePath),snapshotCount:q.reduce((Z,L)=>Z+L.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),G=new Set(q.flatMap((Z)=>Z.selected));if(G.size===0)return{files:[],snapshotCount:0};let J=[...this.snapshots];this.snapshots=this.snapshots.filter((Z)=>!G.has(Z)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(Z){throw this.snapshots=J,this.rebuildTrackedFileBackups(),Z}return await Promise.all([...G].map((Z)=>X.rm(this.getSnapshotPath(Z.backupFileName,Z.version),{force:!0}).catch(()=>{return}))),{files:q.map((Z)=>Z.filePath),snapshotCount:G.size}}buildRewindPlan($){let q=new Set($),G=this.snapshots.filter((L)=>L.postEditHash!==void 0),J=G.filter((L)=>q.has(L.messageId));return[...new Set(J.map((L)=>L.filePath))].sort().map((L)=>{let Q=G.filter((K)=>K.filePath===L),x=Q.filter((K)=>q.has(K.messageId)),V=Q.indexOf(x[0]),N=Q.slice(V);if(N.length!==x.length||N.some((K)=>!q.has(K.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${L}`);return{filePath:L,selected:x,target:x[0],latest:x.at(-1)}})}async loadManifest(){try{let $=await X.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(G)=>({...G,filePath:await this.resolveFileIdentity(G.filePath),timestamp:new Date(G.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await X.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await l0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let G=this.snapshots.filter((J)=>J.filePath===$).slice(0,-this.maxSnapshots);for(let J of G)await X.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}),this.removeSnapshot(J)}async cleanup($=0){let q=this.snapshots.slice().sort((J,Z)=>Z.timestamp.getTime()-J.timestamp.getTime()),G=new Set(q.slice(0,$));for(let J of this.snapshots)if(!G.has(J))await X.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return F.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=F.resolve($),G=[],J=q;while(!0){try{let L=await X.realpath(J);return F.join(L,...G.reverse())}catch(L){let Q=L.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")throw L}let Z=F.dirname(J);if(Z===J)return q;G.push(F.basename(J)),J=Z}}async hashFile($){try{let q=await X.readFile($);return L0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return R$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let G=L0.createHash("md5");return G.update(`${$}:${q}`),G.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}import{createHash as mq}from"node:crypto";import S$ from"node:path";import{StringDecoder as Aq}from"node:string_decoder";function Dq($,q){let G=q;while(G<$.length&&($[G]&192)===128)G+=1;return G}class p0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?Buffer.from($):Buffer.from($);if(q.length===0)return;this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),omittedBytes:this.omittedBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}trimToLimit(){while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let q=this.retainedBytes-this.maxBytes;if($.length<=q){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length;continue}let G=Dq($,q);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G}}}var _0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},r={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},M$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},Rq={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},Mq=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:_0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:_0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:r,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:M$},{pattern:/^git\s+(status|branch|remote)/i,config:r},{pattern:/^git\s+(log|diff|show)/i,config:M$},{pattern:/^(ls|dir|tree)\s+/i,config:r,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:r,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:r,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:_0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:_0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:r,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:r,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class n0{static getConfigForCommand($){for(let{pattern:q,config:G,summaryTemplate:J}of Mq)if(q.test($))return{config:G,summaryTemplate:J};return{config:Rq}}static truncate($,q){let{config:G,summaryTemplate:J}=this.getConfigForCommand(q);return this.truncateWithConfig($,G,J)}static truncateWithConfig($,q,G){let J=$.length,Z=$.split(`
|
|
4
4
|
`),L=Z.length;if(L<=q.maxLines&&J<=q.maxChars)return{content:$,truncated:!1,originalLines:L,originalChars:J};let Q=Z.slice(0,q.keepHead),x=Z.slice(-q.keepTail),V=L-q.keepHead-q.keepTail,N=Q.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{zc as I}from"./chunk-wt7gy9bm.js";import{Sc as A}from"./chunk-
|
|
1
|
+
import{zc as I}from"./chunk-wt7gy9bm.js";import{Sc as A}from"./chunk-8mafna0v.js";import{ie as h}from"./chunk-6207mbmr.js";import{Me as f,Qe as T,Re as w,Se as M,Te as P,We as k,Xe as E}from"./chunk-et9k9pac.js";import{Ye as c,Ze as y}from"./chunk-y2g5a5bp.js";import{af as S,cf as n,ff as p}from"./chunk-96h588rd.js";import{kf as O}from"./chunk-prgh321y.js";import{promises as R}from"node:fs";import C from"node:path";var U=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],x=new Set([...Object.keys(f),...U]),m=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:p(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),timeout:n.Optional(m),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(m),theme:n.Optional(n.String()),uiTheme:n.Optional(p(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(m),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1,maximum:y})),maxConcurrentTasks:n.Optional(n.Integer({minimum:T,maximum:w})),maxQueuedTasks:n.Optional(n.Integer({minimum:M,maximum:P})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(p(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(p(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(r),ask:n.Optional(r),deny:n.Optional(r)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),_=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!x.has(s))throw Error(`Unknown --settings field: ${s}`);let l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.data}async function N(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=C.resolve(O(),i),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of _){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}var u=h("General"),Z=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},g=async(o)=>{let i=await N(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let l=await k.getInstance().initialize(i),s=E(l,o);if(A().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
|
|
2
2
|
[FAIL] 配置初始化失败
|
|
3
3
|
`),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
|
|
4
4
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
package/package.json
CHANGED
package/dist/chunk-wygpe92c.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{uc as a,vc as b}from"./chunk-bpnyda6p.js";import"./chunk-677ywzhs.js";import"./chunk-6g5k5de1.js";export{a as globalOptions,b as cliConfig};
|