blade-code 0.10.66 → 0.10.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-te21eb71.js → chunk-0aja46wq.js} +1 -1
  3. package/dist/{chunk-a2594p5r.js → chunk-2a9rndk2.js} +1 -1
  4. package/dist/{chunk-4sztphe9.js → chunk-2wz3mf50.js} +1 -1
  5. package/dist/{chunk-ax9ftraa.js → chunk-37g8mh93.js} +1 -1
  6. package/dist/{chunk-30kmydfj.js → chunk-38x7njj5.js} +1 -1
  7. package/dist/{chunk-dc64v4sa.js → chunk-3j8q6yrf.js} +1 -1
  8. package/dist/{chunk-ybv6stfh.js → chunk-53xbkvk1.js} +1 -1
  9. package/dist/{chunk-a3xnd8cg.js → chunk-5kz804w9.js} +1 -1
  10. package/dist/{chunk-1c69c4rd.js → chunk-696t7mzc.js} +1 -1
  11. package/dist/{chunk-pzb5sqwd.js → chunk-6am7zz57.js} +1 -1
  12. package/dist/{chunk-zk42hrdh.js → chunk-7agkmjm7.js} +1 -1
  13. package/dist/{chunk-gezg1mpa.js → chunk-7pxpwkeg.js} +1 -1
  14. package/dist/{chunk-rf01e14b.js → chunk-8mr5vydg.js} +1 -1
  15. package/dist/{chunk-jmjn6zcc.js → chunk-8t2xknh6.js} +1 -1
  16. package/dist/{chunk-j38jh128.js → chunk-amaxww4b.js} +1 -1
  17. package/dist/chunk-cn9jekw9.js +1 -0
  18. package/dist/{chunk-ha50z8dp.js → chunk-eqqxr26g.js} +1 -1
  19. package/dist/{chunk-89090tyx.js → chunk-fs6ashcf.js} +1 -1
  20. package/dist/{chunk-t89q7d03.js → chunk-gak96awp.js} +1 -1
  21. package/dist/{chunk-qdah5kkc.js → chunk-gayy8vky.js} +3 -3
  22. package/dist/chunk-gn3fxtkj.js +1 -0
  23. package/dist/{chunk-0scxrkcf.js → chunk-gvxpdb2v.js} +1 -1
  24. package/dist/{chunk-2xk6m4fc.js → chunk-k5a3n7q5.js} +1 -1
  25. package/dist/{chunk-p0b4mv7e.js → chunk-kccs7c9r.js} +1 -1
  26. package/dist/{chunk-abef6dq1.js → chunk-nacssmem.js} +1 -1
  27. package/dist/{chunk-0qtrv97b.js → chunk-nrh7qjat.js} +1 -1
  28. package/dist/{chunk-k99r5c4v.js → chunk-p0gyfy9p.js} +1 -1
  29. package/dist/{chunk-q3mfescm.js → chunk-pf6ftbra.js} +2 -2
  30. package/dist/{chunk-nt55nz8d.js → chunk-pv576mrv.js} +1 -1
  31. package/dist/{chunk-kv0bkxhd.js → chunk-rbdd49vr.js} +1 -1
  32. package/dist/{chunk-b66veqye.js → chunk-tb363yj8.js} +1 -1
  33. package/dist/{chunk-xny9q252.js → chunk-te88v4a8.js} +1 -1
  34. package/dist/{chunk-w6p2hcfw.js → chunk-vavy5dw8.js} +1 -1
  35. package/dist/{chunk-8nmwft1y.js → chunk-w5jdnsyz.js} +1 -1
  36. package/dist/{chunk-c8zcyvss.js → chunk-wr60s2qh.js} +1 -1
  37. package/dist/{chunk-69j98a7j.js → chunk-yq2891kc.js} +55 -55
  38. package/dist/{chunk-rhs1dv6w.js → chunk-zd05g5qs.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-2eq5dyga.js +0 -1
  41. package/dist/chunk-8c677xtx.js +0 -1
@@ -1,4 +1,4 @@
1
- import{$c as F$,Sc as u,Tc as I1,Uc as O$,Vc as v1,Wc as I,Xc as N$,Yc as u1,Zc as U$,_c as P1,ad as R$,cd as g0,fd as x$,gd as h1}from"./chunk-zdxxqchm.js";import{ie as H0}from"./chunk-yn51162x.js";import{Te as K0}from"./chunk-cdy9efgm.js";import{df as V1}from"./chunk-m57w4p91.js";import{qg as j1,rg as m1}from"./chunk-xz6y0w4n.js";import{wg as v$}from"./chunk-k0pa8874.js";import{Xg as D0}from"./chunk-98n2rxmq.js";import{ch as Y0,fh as W0}from"./chunk-t8xmh4w2.js";import{jh as i}from"./chunk-j38jh128.js";import{rh as k1,sh as B0,th as S1,uh as b,vh as m,xh as V0,yh as p,zh as G0}from"./chunk-ppsvzgs5.js";import{readdir as H$,readFile as s,rm as q0,stat as y0}from"node:fs/promises";import*as H from"node:path";import{nanoid as j}from"nanoid";import{createHash as e1,randomUUID as $q}from"node:crypto";import*as v from"node:fs/promises";import*as F0 from"node:path";import{execFileSync as d1}from"node:child_process";import{createHash as r1}from"node:crypto";import{readFileSync as o1}from"node:fs";var t1=/^[a-f0-9]{64}$/;function k$($){if(!$||typeof $!=="object")return!1;let q=$;return(q.platform==="linux"||q.platform==="darwin"||q.platform==="win32")&&typeof q.fingerprint==="string"&&t1.test(q.fingerprint)}var S$={readFile:($)=>o1($,"utf8"),execFile:($,q)=>d1($,q,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},a1=($)=>{try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}};function l0($,q){return{platform:$,fingerprint:r1("sha256").update(`${$}\x00${q}`).digest("hex")}}function s1($,q){let L=q.readFile(`/proc/${$}/stat`).trim(),f=L.lastIndexOf(")");if(f<0)throw Error("Invalid /proc process stat");let B=L.slice(f+2).split(/\s+/)[19];if(!B||!/^\d+$/.test(B))throw Error("Missing process start ticks");return B}function N0($,q=process.platform,L=S$){if(!Number.isInteger($)||$<=1)return;try{if(q==="linux")return l0(q,s1($,L));if(q==="darwin"){let f=L.execFile("ps",["-o","lstart=","-p",String($)]).trim();return f?l0(q,f):void 0}if(q==="win32"){let f=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,J=L.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",f]).trim();return J?l0(q,J):void 0}}catch{return}return}function j$($,q){return N0($,q.platform)?.fingerprint===q.fingerprint}function wL($,q,L=S$,f=a1){if(!Number.isInteger($)||$<=1)return!1;let J=N0($,q.platform,L);if(J)return J.fingerprint===q.fingerprint;return!f($)}var u$=1;function qq($,q){let L=e1("sha256").update(q).digest("hex");return F0.join(B0($),".locks",`${L}.lock`)}function U0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function p0($){try{let q=JSON.parse(await v.readFile($,"utf8"));if(q.version!==u$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||q.processIdentity!==void 0&&!k$(q.processIdentity)||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function m$($){let q=await p0($);if(q)return q;return await new Promise((L)=>setTimeout(L,10)),p0($)}function Lq($){try{return process.kill($,0),!0}catch(q){return U0(q,"EPERM")}}async function I$($,q){let L;try{return L=await v.open($,"wx",384),await L.writeFile(`${JSON.stringify(q)}
1
+ import{$c as F$,Sc as u,Tc as I1,Uc as O$,Vc as v1,Wc as I,Xc as N$,Yc as u1,Zc as U$,_c as P1,ad as R$,cd as g0,fd as x$,gd as h1}from"./chunk-zdxxqchm.js";import{ie as H0}from"./chunk-yn51162x.js";import{Te as K0}from"./chunk-cdy9efgm.js";import{df as V1}from"./chunk-m57w4p91.js";import{qg as j1,rg as m1}from"./chunk-xz6y0w4n.js";import{wg as v$}from"./chunk-k0pa8874.js";import{Xg as D0}from"./chunk-98n2rxmq.js";import{ch as Y0,fh as W0}from"./chunk-t8xmh4w2.js";import{jh as i}from"./chunk-amaxww4b.js";import{rh as k1,sh as B0,th as S1,uh as b,vh as m,xh as V0,yh as p,zh as G0}from"./chunk-ppsvzgs5.js";import{readdir as H$,readFile as s,rm as q0,stat as y0}from"node:fs/promises";import*as H from"node:path";import{nanoid as j}from"nanoid";import{createHash as e1,randomUUID as $q}from"node:crypto";import*as v from"node:fs/promises";import*as F0 from"node:path";import{execFileSync as d1}from"node:child_process";import{createHash as r1}from"node:crypto";import{readFileSync as o1}from"node:fs";var t1=/^[a-f0-9]{64}$/;function k$($){if(!$||typeof $!=="object")return!1;let q=$;return(q.platform==="linux"||q.platform==="darwin"||q.platform==="win32")&&typeof q.fingerprint==="string"&&t1.test(q.fingerprint)}var S$={readFile:($)=>o1($,"utf8"),execFile:($,q)=>d1($,q,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},a1=($)=>{try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}};function l0($,q){return{platform:$,fingerprint:r1("sha256").update(`${$}\x00${q}`).digest("hex")}}function s1($,q){let L=q.readFile(`/proc/${$}/stat`).trim(),f=L.lastIndexOf(")");if(f<0)throw Error("Invalid /proc process stat");let B=L.slice(f+2).split(/\s+/)[19];if(!B||!/^\d+$/.test(B))throw Error("Missing process start ticks");return B}function N0($,q=process.platform,L=S$){if(!Number.isInteger($)||$<=1)return;try{if(q==="linux")return l0(q,s1($,L));if(q==="darwin"){let f=L.execFile("ps",["-o","lstart=","-p",String($)]).trim();return f?l0(q,f):void 0}if(q==="win32"){let f=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,J=L.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",f]).trim();return J?l0(q,J):void 0}}catch{return}return}function j$($,q){return N0($,q.platform)?.fingerprint===q.fingerprint}function wL($,q,L=S$,f=a1){if(!Number.isInteger($)||$<=1)return!1;let J=N0($,q.platform,L);if(J)return J.fingerprint===q.fingerprint;return!f($)}var u$=1;function qq($,q){let L=e1("sha256").update(q).digest("hex");return F0.join(B0($),".locks",`${L}.lock`)}function U0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function p0($){try{let q=JSON.parse(await v.readFile($,"utf8"));if(q.version!==u$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||q.processIdentity!==void 0&&!k$(q.processIdentity)||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function m$($){let q=await p0($);if(q)return q;return await new Promise((L)=>setTimeout(L,10)),p0($)}function Lq($){try{return process.kill($,0),!0}catch(q){return U0(q,"EPERM")}}async function I$($,q){let L;try{return L=await v.open($,"wx",384),await L.writeFile(`${JSON.stringify(q)}
2
2
  `,"utf8"),!0}catch(f){if(U0(f,"EEXIST"))return!1;if(L)await v.unlink($).catch(()=>{return});throw f}finally{await L?.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 c{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=v$()){let L=qq(q,$),f={version:u$,sessionId:$,ownerId:$q(),pid:process.pid,processIdentity:N0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(F0.dirname(L),{recursive:!0,mode:448}),await I$(L,f))return new c(L,f);let J=await m$(L);if(J&&Lq(J.pid)&&(!J.processIdentity||j$(J.pid,J.processIdentity)))throw new h(J.pid);if(await v.unlink(L).catch((B)=>{if(!U0(B,"ENOENT"))throw B}),await I$(L,f))return new c(L,f);throw new h((await m$(L))?.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((q)=>{if(!U0(q,"ENOENT"))throw q})}}var mL=1;function i0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function fq($){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 Bq($){if(!i0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(fq)}function P$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let q=JSON.stringify($);if(Buffer.byteLength(q)>16777216)return;let L=JSON.parse(q);if(!Array.isArray(L)||!L.every(Bq))return;return L}function IL($){let q=P$($);if(!q)throw Error("Compaction replacement context is invalid or exceeds limits");return q}function R0($){return P$($)}function Jq($,q){for(let L of $){if(L.type!=="part_created"||L.data.partType!=="tool_result")continue;let f=L.data.payload;if(!f||typeof f!=="object"||Array.isArray(f))continue;let J=f;if(J.toolCallId===q||L.data.partId===q||L.data.messageId===q)return J}return}function h$($){let q=u($),L=new Map;for(let f of q){if(f.type==="interaction_requested"){L.set(f.data.requestId,{request:f.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(f.type==="interaction_responded"){let J=L.get(f.data.requestId);if(J)J.response=f.data;continue}if(f.type==="interaction_recovered"){let J=L.get(f.data.requestId);if(J)J.recovery=f.data}}for(let f of L.values()){let J=Jq(q,f.request.toolCallId);f.hasToolResult=J!==void 0;let B=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;f.hasRecoveryToolResult=B?.interactionRecovery===!0&&B.requestId===f.request.requestId}return[...L.values()]}function c$($){return h$($).reverse().find((q)=>!q.response&&!q.recovery)}function PL($){let q=new Map;for(let L of h$($))q.set(L.request.toolCallId,L);return[...q.values()].filter((L)=>L.response&&!L.recovery&&(!L.hasToolResult||L.hasRecoveryToolResult))}function n$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function x0($){let q=new Map,L=[];for(let f of $){if(f.type==="review_started"){if(!q.has(f.data.reviewId))L.push(f.data.reviewId),q.set(f.data.reviewId,{start:f.data});continue}if(f.type!=="review_completed")continue;let J=q.get(f.data.reviewId);if(J&&J.completion===void 0)J.completion=f.data}return L.map((f)=>q.get(f)).filter((f)=>f!==void 0)}function cL($){return x0($).reverse().find((q)=>q.completion===void 0)}function d0($){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 l$($,q){let L=["## Code Review","",`Target: ${$.target.label}`,`Status: ${d0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)L.push("","No actionable findings.");else{L.push("","### Findings");for(let[f,J]of q.findings.entries()){let B=J.codeLocation.lineStart===J.codeLocation.lineEnd?`${J.codeLocation.lineStart}`:`${J.codeLocation.lineStart}-${J.codeLocation.lineEnd}`;L.push("",`${f+1}. ${J.title}`,` ${J.codeLocation.path}:L${B} · confidence ${J.confidenceScore.toFixed(2)}`,` ${J.body}`)}}if(q.error)L.push("",`Error: ${q.error}`);return L.join(`
3
3
  `)}function p$($,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((L)=>({title:L.title,body:L.body,priority:L.priority,confidenceScore:L.confidenceScore,codeLocation:{...L.codeLocation}})),...q.error?{error:q.error}:{}}}var a0=1;var r0=2000,Zq='<token-budget-handoff version="1">',pL="handoff-message-",Cq=128,Gq=["version","messageId","observedPromptTokens","availableForInput","handoffThreshold","compactionThreshold","createdAt"],Qq=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,Vq=/(?:^|\n)Remaining prompt-token headroom before compaction: (\d+)\.$/;function n($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function s0($){return n($)&&$>0}function Xq($){for(let q=0;q<$.length;q+=1){let L=$.charCodeAt(q);if(L<=31||L===127)return!0}return!1}function i$($){return typeof $==="string"&&$.length>=1&&$.length<=Cq&&!Xq($)}function o0($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let q=Object.getPrototypeOf($);return q===Object.prototype||q===null}function T0($,q){let L=Math.floor($/10),f=$%10;return L*q+Math.floor(f*q/10)}function Yq($){if(typeof $!=="string"||!Qq.test($))return!1;try{let q=new Date($);return Number.isFinite(q.getTime())&&q.toISOString()===$}catch{return!1}}function d$($){if(!n($))throw Error("Token budget handoff headroom must be a safe nonnegative integer");return[Zq,"Context rollover is approaching. Continue the user task from this state only.","Make objective, decisions, mutations, verification, background work, blockers, and the exact next action explicit.","For pending work, preserve exact commands, tool arguments, and required final-response constraints when they are known.","Do not claim success or completion unless it is already proven in the transcript.","Do not create bookkeeping files the user did not request.",`Remaining prompt-token headroom before compaction: ${$}.`].join(`
4
4
  `)}function Wq($){let q=d$($);if(new TextEncoder().encode(q).length>r0)throw Error(`Token budget handoff reminder exceeds ${r0} bytes`);return q}function t0($,q){let L=Object.keys($).sort(),f=[...q].sort();return L.length===f.length&&L.every((J,B)=>J===f[B])}function iL($){let{maxContextTokens:q,maxOutputTokens:L,configuredMaxOutputTokens:f}=$,J=L??f??void 0;if(J!==void 0)return J;if(!s0(q))return;return Math.min(Math.max(Math.floor(q*0.1),8192),32768)}function dL($){let{actualPromptTokens:q,maxContextTokens:L,maxOutputTokens:f}=$;if(!s0(L)||!n(f)||f>=L)return{phase:"unknown"};let J=L-f;if(J<=0)return{phase:"unknown"};let B=T0(J,7),Z=T0(J,8);if(!n(q))return{phase:"unknown",maxContextTokens:L,maxOutputTokens:f,availableForInput:J,handoffThreshold:B,compactionThreshold:Z};if(q<B)return{phase:"below_handoff",actualPromptTokens:q,maxContextTokens:L,maxOutputTokens:f,availableForInput:J,handoffThreshold:B,compactionThreshold:Z};if(q<Z)return{phase:"handoff_band",actualPromptTokens:q,maxContextTokens:L,maxOutputTokens:f,availableForInput:J,handoffThreshold:B,compactionThreshold:Z};return{phase:"compaction_due",actualPromptTokens:q,maxContextTokens:L,maxOutputTokens:f,availableForInput:J,handoffThreshold:B,compactionThreshold:Z}}function r$($){if($.type!=="token_budget_handoff_recorded"||!o0($.data))return;let q=$.data;if(!t0(q,Gq)||q.version!==a0||!i$(q.messageId)||!n(q.observedPromptTokens)||!s0(q.availableForInput)||!n(q.handoffThreshold)||!n(q.compactionThreshold)||!Yq(q.createdAt))return;let L=T0(q.availableForInput,7),f=T0(q.availableForInput,8);if(q.handoffThreshold!==L||q.compactionThreshold!==f||q.observedPromptTokens<q.handoffThreshold||q.observedPromptTokens>=q.compactionThreshold)return;return $}function Hq($){return $.type==="token_budget_handoff_recorded"}function o$($){let q=$.findLastIndex((B)=>{if(B.type!=="part_created"||B.data.partType!=="summary")return!1;let Z=B.data.payload;return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)&&R0(Z.replacementMessages)!==void 0}),L=$.slice(q+1).filter(Hq);if(L.length===0)return{kind:"none"};let f=L.at(-1);if(!f)return{kind:"none"};if(L.length!==1)return{kind:"suppressed",recordId:f.id};let J=r$(f);return J?{kind:"valid",event:J}:{kind:"suppressed",recordId:f.id}}function t$($){let q=r$($);if(!q)return;let L={clientVisible:!1,tokenBudgetHandoff:{version:a0,messageId:q.data.messageId}};return{id:q.data.messageId,role:"user",content:Wq(Math.max(0,q.data.compactionThreshold-q.data.observedPromptTokens)),metadata:L}}function Kq($){if(typeof $.id!=="string"||$.role!=="user"||typeof $.content!=="string"||!o0($.metadata)||$.metadata.clientVisible!==!1)return!1;let q=$.metadata;if(!t0(q,["clientVisible","tokenBudgetHandoff"]))return!1;let L=q.tokenBudgetHandoff;if(!o0(L))return!1;if(!t0(L,["messageId","version"]))return!1;if(L.version!==a0||!i$(L.messageId)||L.messageId!==$.id)return!1;if(new TextEncoder().encode($.content).length>r0)return!1;let J=Vq.exec($.content);if(!J)return!1;let B=Number(J[1]);return n(B)&&$.content===d$(B)}function rL($){return $.filter((q)=>!Kq(q))}var e0={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},capacity:{message:"Task admission capacity is full. Retry after running tasks complete.",retryable:!0},runtime:{message:"Agent execution failed.",retryable:!0}};function _q($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function Oq($){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";if(/\btask admission\b.*\b(capacity|queue)\b/.test(q))return"capacity";return"runtime"}function Nq($){try{if(!$||typeof $!=="object"||!("name"in $)||$.name!=="TaskAdmissionQueueFullError"&&$.name!=="SessionRuntimeCapacityError"||!("resource"in $))return;return $.resource==="pending_count"||$.resource==="pending_bytes"||$.resource==="resident_runtimes"?$.resource:void 0}catch{return}}function a$($){return{code:$,...e0[$]}}function $$($){let q=Nq($);if(q)return{...a$("capacity"),resource:q};return a$(Oq(_q($)))}function q$($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in e0))return!1;let L=e0[q.code],f=q.resource===void 0||q.resource==="pending_count"||q.resource==="pending_bytes"||q.resource==="resident_runtimes";return q.message===L.message&&q.retryable===L.retryable&&f&&(q.code==="capacity"||q.resource===void 0)}import{promises as J0,realpathSync as Fq}from"node:fs";import z0 from"node:path";import*as o from"fs/promises";import*as x from"path";var s$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class r extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class L${static normalize($,q){let L=x.isAbsolute($)?$:x.resolve(q,$),f=x.normalize(L),J=x.normalize(q);if(!this.isWithinWorkspace(f,J))throw new r(`Path outside workspace: ${$} (resolved to ${f}, workspace: ${J})`,"PATH_OUTSIDE_WORKSPACE");return f}static checkRestricted($){let q=$.split(x.sep);for(let L of s$)if(q.includes(L))throw new r(`Access denied: "${L}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new r(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let L=this.normalize($,q);this.checkRestricted(L);try{await o.access(L)}catch(f){throw new r(`Path not found: ${$}`,"PATH_NOT_FOUND")}return L}static async resolveSymlink($,q){try{let L=await o.realpath($),f=await o.realpath(q);if(!this.isWithinWorkspace(L,f))throw new r(`Symlink points outside workspace: ${$} -> ${L}`,"SYMLINK_OUTSIDE_WORKSPACE");return L}catch(L){if(L instanceof r)throw L;return $}}static getRelativePath($,q){return x.relative(q,$)}static isWithinWorkspace($,q){let L=x.resolve($),f=x.resolve(q),J=x.relative(f,L);return J===""||J!==".."&&!J.startsWith(`..${x.sep}`)&&!x.isAbsolute(J)}static async isWithinWorkspaceResolved($,q){let L=x.resolve(q),f=x.isAbsolute($)?x.resolve($):x.resolve(L,$);if(!this.isWithinWorkspace(f,L))return!1;let J;try{J=await o.realpath(L)}catch{return!1}let B=f;while(!0){try{let C=await o.realpath(B);return this.isWithinWorkspace(C,J)}catch(C){let Q=C.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")return!1}let Z=x.dirname(B);if(Z===B)return!1;B=Z}}static isRestricted($){let q=$.split(x.sep);return s$.some((L)=>q.includes(L))}}var Z0=D0("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($,q){try{let L=await J0.stat($),f={filePath:z0.resolve($),accessTime:Date.now(),mtime:L.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(f),await this.recordAliases($,f.filePath),Z0.debug(`记录文件读取: ${$}`)}catch(L){Z0.warn(`记录文件读取失败: ${$}`,L)}}async recordFileEdit($,q,L="edit"){try{let f=await J0.stat($),J={filePath:z0.resolve($),accessTime:Date.now(),mtime:f.mtimeMs,sessionId:q,lastOperation:L};this.setRecord(J),await this.recordAliases($,J.filePath),Z0.debug(`记录文件${L==="edit"?"编辑":"写入"}: ${$}`)}catch(f){Z0.warn(`记录文件${L==="edit"?"编辑":"写入"}失败: ${$}`,f)}}hasFileBeenRead($,q){let L=this.accessedFiles.get(this.resolveTrackedPath($));if(!L)return!1;return q?L.has(q):L.size>0}async checkFileModification($,q){let L=this.getFileRecord($,q);if(!L)return{modified:!1,message:"文件未被跟踪"};try{let f=await J0.stat($);if(Math.abs(f.mtimeMs-L.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(L.accessTime).toISOString()}, 当前修改时间: ${f.mtime.toISOString()})`};return{modified:!1}}catch(f){let J=f;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification($,q){let L=this.getFileRecord($,q);if(!L)return{isExternal:!1,message:"文件未被跟踪"};try{let f=await J0.stat($);if(f.mtimeMs-L.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(L.accessTime).toISOString()} (${L.lastOperation}) 之后被外部程序修改(当前修改时间: ${f.mtime.toISOString()})`};return{isExternal:!1}}catch(f){let J=f;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return Z0.warn(`检查文件外部修改失败: ${$}`,f),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord($,q){let L=this.accessedFiles.get(this.resolveTrackedPath($));if(!L)return;if(q)return L.get(q);return[...L.values()].sort((f,J)=>J.accessTime-f.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let L=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(L),this.removeAliases(L);return}let f=this.accessedFiles.get(L);if(f?.delete(q),f?.size===0)this.accessedFiles.delete(L),this.removeAliases(L)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[L,f]of this.accessedFiles.entries()){if(q&&!L$.isWithinWorkspace(L,q))continue;if(f.delete($),f.size===0)this.accessedFiles.delete(L),this.removeAliases(L)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){l.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(z0.resolve($),q);let L=await J0.realpath($).catch(()=>{return});if(L)this.pathAliases.set(L,q)}resolveTrackedPath($){let q=z0.resolve($);if(this.accessedFiles.has(q))return q;let L=this.pathAliases.get(q);if(L)return L;try{let f=Fq.native(q);return this.pathAliases.get(f)??f}catch{return q}}removeAliases($){for(let[q,L]of this.pathAliases)if(L===$)this.pathAliases.delete(q)}}import*as C0 from"node:crypto";import{promises as _}from"node:fs";import*as N from"node:path";import f$ from"write-file-atomic";var e$="missing";class A0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(b($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!N.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?N.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=G0();this.snapshotDir=N.join(q,"file-history",this.sessionId),this.manifestPath=N.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await _.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=G0(),q=await _.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),L=C0.createHash("sha256").update(q).digest("hex").slice(0,24),f=N.join($,"file-history",this.sessionId),J=N.join($,"file-history","workspaces",L,this.sessionId),B=N.join(J,"manifest.json");try{await _.access(B)}catch{await this.migrateLegacySnapshotDir(f,J,q)}this.snapshotDir=J,this.manifestPath=B}async migrateLegacySnapshotDir($,q,L){let f;try{f=JSON.parse(await _.readFile(N.join($,"manifest.json"),"utf8"))}catch{return}if(f.schemaVersion!==1||!Array.isArray(f.snapshots)||!f.snapshots.every((J)=>this.isWithinWorkspace(J.filePath,L)))return;await _.mkdir(N.dirname(q),{recursive:!0,mode:493});try{await _.rename($,q)}catch(J){let B=J.code;if(B!=="ENOENT"&&B!=="EEXIST"&&B!=="ENOTEMPTY")throw J}}isWithinWorkspace($,q){if(!N.isAbsolute($))return!1;let L=N.relative(q,N.resolve($));return L===""||L!==".."&&!L.startsWith(`..${N.sep}`)&&!N.isAbsolute(L)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let L=await this.resolveFileIdentity($),f=!0;try{await _.access(L)}catch{f=!1}let J=this.trackedFileBackups.get(L),B=J?J.version+1:1,Z=this.generateFileHash(L,B),C=this.getSnapshotPath(Z,B),Q=new Date;if(f){let Y=await _.readFile(L);await _.writeFile(C,Y)}let X={backupFileName:Z,version:B,backupTime:Q};return this.trackedFileBackups.set(L,X),this.snapshots.push({messageId:q,backupFileName:Z,timestamp:Q,filePath:L,version:B,existedBefore:f}),await this.cleanupOldSnapshots(L),await this.persistManifest(),X}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let L=await this.resolveFileIdentity($),f=this.snapshots.find((J)=>J.filePath===L&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!f)throw Error(`未找到待完成的快照: ${L}`);f.postEditHash=await this.hashFile(L),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let L=await this.resolveFileIdentity($),f=this.snapshots.find((J)=>J.filePath===L&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!f)return;this.removeSnapshot(f),await _.rm(this.getSnapshotPath(f.backupFileName,f.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),L=this.snapshots.slice().reverse().find((B)=>B.filePath===q&&B.postEditHash!==void 0);if(!L?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==L.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let J=this.getSnapshotPath(L.backupFileName,L.version);if(L.existedBefore){let B=await _.readFile(J);await _.mkdir(N.dirname(q),{recursive:!0}),await _.writeFile(q,B)}else await _.rm(q,{force:!0});return this.removeSnapshot(L),await _.rm(J,{force:!0}),await this.persistManifest(),L}async restoreSnapshot($,q){let L=await this.resolveFileIdentity($),f=this.snapshots.slice().reverse().find((B)=>B.messageId===q&&B.filePath===L);if(!f)throw Error(`未找到快照: messageId=${q}, filePath=${L}`);let J=this.getSnapshotPath(f.backupFileName,f.version);if(f.existedBefore){let B=await _.readFile(J);await _.mkdir(N.dirname(L),{recursive:!0}),await _.writeFile(L,B)}else await _.rm(L,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((L)=>L.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((L)=>L.filePath),snapshotCount:q.reduce((L,f)=>L+f.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let L=new Map;for(let J of q){let B,Z=!0;try{B=await _.readFile(J.filePath)}catch(Q){if(Q.code!=="ENOENT")throw Q;Z=!1}if((B?C0.createHash("sha256").update(B).digest("hex"):e$)!==J.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${J.filePath}`);if(L.set(J.filePath,{existed:Z,content:B}),J.target.existedBefore)await _.access(this.getSnapshotPath(J.target.backupFileName,J.target.version))}let f=[...this.snapshots];try{for(let B of q)if(B.target.existedBefore){let Z=await _.readFile(this.getSnapshotPath(B.target.backupFileName,B.target.version));await _.mkdir(N.dirname(B.filePath),{recursive:!0}),await f$(B.filePath,Z)}else await _.rm(B.filePath,{force:!0});let J=new Set(q.flatMap((B)=>B.selected));this.snapshots=this.snapshots.filter((B)=>!J.has(B)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...J].map((B)=>_.rm(this.getSnapshotPath(B.backupFileName,B.version),{force:!0}).catch(()=>{return})))}catch(J){this.snapshots=f,this.rebuildTrackedFileBackups();let B=[];for(let[Z,C]of L)try{if(C.existed&&C.content)await f$(Z,C.content);else await _.rm(Z,{force:!0})}catch(Q){B.push(Q)}if(B.length>0)throw AggregateError([J,...B],"快照回退失败且无法完整恢复回退前状态");throw J}return{files:q.map((J)=>J.filePath),snapshotCount:q.reduce((J,B)=>J+B.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),L=new Set(q.flatMap((J)=>J.selected));if(L.size===0)return{files:[],snapshotCount:0};let f=[...this.snapshots];this.snapshots=this.snapshots.filter((J)=>!L.has(J)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(J){throw this.snapshots=f,this.rebuildTrackedFileBackups(),J}return await Promise.all([...L].map((J)=>_.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return}))),{files:q.map((J)=>J.filePath),snapshotCount:L.size}}buildRewindPlan($){let q=new Set($),L=this.snapshots.filter((B)=>B.postEditHash!==void 0),f=L.filter((B)=>q.has(B.messageId));return[...new Set(f.map((B)=>B.filePath))].sort().map((B)=>{let Z=L.filter((Y)=>Y.filePath===B),C=Z.filter((Y)=>q.has(Y.messageId)),Q=Z.indexOf(C[0]),X=Z.slice(Q);if(X.length!==C.length||X.some((Y)=>!q.has(Y.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${B}`);return{filePath:B,selected:C,target:C[0],latest:C.at(-1)}})}async loadManifest(){try{let $=await _.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(L)=>({...L,filePath:await this.resolveFileIdentity(L.filePath),timestamp:new Date(L.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await _.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await f$(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let L=this.snapshots.filter((f)=>f.filePath===$).slice(0,-this.maxSnapshots);for(let f of L)await _.rm(this.getSnapshotPath(f.backupFileName,f.version),{force:!0}),this.removeSnapshot(f)}async cleanup($=0){let q=this.snapshots.slice().sort((f,J)=>J.timestamp.getTime()-f.timestamp.getTime()),L=new Set(q.slice(0,$));for(let f of this.snapshots)if(!L.has(f))await _.rm(this.getSnapshotPath(f.backupFileName,f.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return N.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=N.resolve($),L=[],f=q;while(!0){try{let B=await _.realpath(f);return N.join(B,...L.reverse())}catch(B){let Z=B.code;if(Z!=="ENOENT"&&Z!=="ENOTDIR")throw B}let J=N.dirname(f);if(J===f)return q;L.push(N.basename(f)),f=J}}async hashFile($){try{let q=await _.readFile($);return C0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return e$;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 L=C0.createHash("md5");return L.update(`${$}:${q}`),L.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var Q2=1200,V2=2000,X2=2000,Y2=2000;function q1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Rq($){if(typeof $==="string"&&$.length>0)return $;if(q1($)&&typeof $.message==="string")return $.message;return}function xq($,q){if($===null||$===void 0)return q??"";if(typeof $==="string")return $;if(typeof $==="object")return $;return String($)}function L1($){let q=$.error!==null&&$.error!==void 0,L=q?Rq($.error)??"Tool execution failed":void 0,f=q1($.metadata)?$.metadata:void 0;return{success:!q,llmContent:xq($.output,L),...L?{error:{type:"execution_error",message:L}}:{},...f?{metadata:f}:{}}}function J$($,q){if($.length<=q)return $;let L=Math.max(0,q);if(L>0&&L<$.length&&/[\uD800-\uDBFF]/.test($.charAt(L-1)))L-=1;return $.slice(0,L)}function $1($,q){if($.length<=q)return $;let L=Math.max(0,$.length-q);if(L<$.length&&/[\uDC00-\uDFFF]/.test($.charAt(L)))L+=1;return $.slice(L)}function B$($,q){if($.length<=q)return $;if(q<=0)return"";let L=`
@@ -1 +1 @@
1
- import{ld as a,md as b,nd as c}from"./chunk-ybv6stfh.js";import"./chunk-s7jsadnc.js";import"./chunk-a3xnd8cg.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zvz2cnt4.js";import"./chunk-abef6dq1.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-j38jh128.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
1
+ import{ld as a,md as b,nd as c}from"./chunk-53xbkvk1.js";import"./chunk-s7jsadnc.js";import"./chunk-5kz804w9.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zvz2cnt4.js";import"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-amaxww4b.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};