blade-code 0.10.93 → 0.10.94
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-fyms8zy1.js → chunk-0538yd6h.js} +1 -1
- package/dist/{chunk-96pnk11m.js → chunk-076txzms.js} +1 -1
- package/dist/{chunk-05fctawm.js → chunk-088bnp26.js} +1 -1
- package/dist/{chunk-xh4pgtj2.js → chunk-0ytp28pf.js} +1 -1
- package/dist/{chunk-wgd4ject.js → chunk-0z3c8p6d.js} +1 -1
- package/dist/{chunk-82n941y8.js → chunk-11fmyrjt.js} +1 -1
- package/dist/{chunk-93rvs2hb.js → chunk-216xzne9.js} +1 -1
- package/dist/{chunk-qr3w31ys.js → chunk-4rw9kt3s.js} +1 -1
- package/dist/{chunk-qern9m2c.js → chunk-5hh577nr.js} +1 -1
- package/dist/{chunk-b9bbyzk4.js → chunk-5qanqw0d.js} +1 -1
- package/dist/{chunk-9h756tk9.js → chunk-73hasjfg.js} +2 -2
- package/dist/{chunk-v7rnx21e.js → chunk-7cx577bv.js} +1 -1
- package/dist/{chunk-scfwdpph.js → chunk-8488pkzv.js} +1 -1
- package/dist/{chunk-n23chvhe.js → chunk-939sa81a.js} +1 -1
- package/dist/{chunk-mmd1hx8c.js → chunk-b5bwg47r.js} +1 -1
- package/dist/{chunk-nht2hy5h.js → chunk-bbvw06fr.js} +1 -1
- package/dist/{chunk-hn1xztva.js → chunk-cd2xwddv.js} +1 -1
- package/dist/chunk-fc7dbcad.js +1 -0
- package/dist/{chunk-3p7c1dsk.js → chunk-fts2cp88.js} +1 -1
- package/dist/{chunk-5rtjx9xk.js → chunk-gzv143jr.js} +1 -1
- package/dist/chunk-h9ww5k16.js +1 -0
- package/dist/{chunk-fs8ra760.js → chunk-k3crvmvt.js} +1 -1
- package/dist/{chunk-sbrj2czw.js → chunk-k40dje0b.js} +1 -1
- package/dist/{chunk-9kfk68qj.js → chunk-k8c48qxn.js} +1 -1
- package/dist/{chunk-m4tpqesg.js → chunk-kfmpnq2r.js} +3 -3
- package/dist/{chunk-7b718dgf.js → chunk-kp6cjt82.js} +1 -1
- package/dist/{chunk-0pnj92hk.js → chunk-nahy2t67.js} +1 -1
- package/dist/{chunk-7wf2acxx.js → chunk-pkcvxa1z.js} +1 -1
- package/dist/{chunk-61efg3yh.js → chunk-reb25993.js} +1 -1
- package/dist/{chunk-37csc3d2.js → chunk-rvpveaf3.js} +1 -1
- package/dist/{chunk-fkhtff66.js → chunk-v5c34zya.js} +1 -1
- package/dist/{chunk-t7nj9vg8.js → chunk-vnnxvpnn.js} +1 -1
- package/dist/{chunk-7jgj63tj.js → chunk-wxm2zjs9.js} +1 -1
- package/dist/{chunk-xby5w74x.js → chunk-xdvjwtfc.js} +1 -1
- package/dist/{chunk-tt3n8gnq.js → chunk-zd410m70.js} +1 -1
- package/dist/{chunk-gynpj5sv.js → chunk-zgd524h0.js} +1 -1
- package/dist/{chunk-ns5vb2p4.js → chunk-zkxszt12.js} +1 -1
- package/dist/web/assets/{ChatView-D-UBHYgT.js → ChatView-DacNycYI.js} +4 -4
- package/dist/web/assets/{CodeBlockHighlighter-CjP3le5E.js → CodeBlockHighlighter-CevKBV7g.js} +1 -1
- package/dist/web/assets/{FilePreview-DRJTAYmL.js → FilePreview-DiS4nCrp.js} +1 -1
- package/dist/web/assets/{KanbanBoard-CRu-0zva.js → KanbanBoard-C9620zMQ.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-fbB4bMCw.js → MarkdownRenderer-DR0tbtqc.js} +3 -3
- package/dist/web/assets/{SettingsModal-RAG8JMXx.js → SettingsModal-C_TpGMs0.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-DC-7RPBv.js → TaskSwitcher-CGWELaxg.js} +1 -1
- package/dist/web/assets/{TerminalPanel-CCB3heKF.js → TerminalPanel-DPxm68h1.js} +1 -1
- package/dist/web/assets/{arrow-left-Dwndq437.js → arrow-left-n3ENbaSb.js} +1 -1
- package/dist/web/assets/{calendar-clock-CNd8rd6n.js → calendar-clock-C2E8mlWS.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-DGxAunkR.js → chevrons-up-down-DgOF3xz6.js} +1 -1
- package/dist/web/assets/{clock-3-BEqhPeh5.js → clock-3-D9h1svFg.js} +1 -1
- package/dist/web/assets/{external-link-ClLpF7at.js → external-link-kvylbcSF.js} +1 -1
- package/dist/web/assets/{folder-B5LF32bS.js → folder-C_KPQmg6.js} +1 -1
- package/dist/web/assets/{index-BgdiwWDg.js → index-D11FYWsc.js} +4 -4
- package/dist/web/assets/{pause-B39o8olb.js → pause-hCE9Bvm9.js} +1 -1
- package/dist/web/assets/{play-Bmh7JaqQ.js → play-BpCmIsMH.js} +1 -1
- package/dist/web/assets/{session-events-Bgir_Gl_.js → session-events-qDVUI3Ca.js} +1 -1
- package/dist/web/assets/{teamService-4Cn4uKC9.js → teamService-7LNlaq8e.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-jaegtaq3.js +0 -1
- package/dist/chunk-z2asrfm1.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{re as W}from"./chunk-
|
|
2
|
+
import{re as W}from"./chunk-nahy2t67.js";import{ue as F,ve as M}from"./chunk-ztp2ff01.js";import"./chunk-reb25993.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-gzv143jr.js";import"./chunk-74yge4ka.js";import"./chunk-pkcvxa1z.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Hh as N,Ih as B}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import{hi as T}from"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import{Qi as J}from"./chunk-nh45xp7r.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-5qanqw0d.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-k8c48qxn.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-d45gd36e.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-4rw9kt3s.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-5hh577nr.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-wxm2zjs9.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-fc7dbcad.js"),import("./chunk-bbvw06fr.js"),import("./chunk-dwttn5xg.js"),import("./chunk-73hasjfg.js"),import("./chunk-va1exak5.js"),import("./chunk-0ytp28pf.js"),import("./chunk-epmxrw4f.js"),import("./chunk-am66822r.js"),import("./chunk-11fmyrjt.js"),import("./chunk-b5bwg47r.js"),import("./chunk-216xzne9.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-h9ww5k16.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-rvpveaf3.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{U as P}from"./chunk-
|
|
1
|
+
import{U as P}from"./chunk-kfmpnq2r.js";import{sb as K}from"./chunk-7cx577bv.js";import{$c as s,Nd as B,Xc as G,Yc as N,Zc as S,_c as O}from"./chunk-vnnxvpnn.js";import{Wd as j}from"./chunk-4jbpvete.js";import{Xe as q}from"./chunk-zj4kfyer.js";import{tf as v}from"./chunk-zd410m70.js";import{Ki as z}from"./chunk-na1cney5.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
|
|
2
2
|
`)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
|
|
3
3
|
`).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
|
|
4
4
|
`)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$g as H,ah as I}from"./chunk-
|
|
1
|
+
import{$g as H,ah as I}from"./chunk-pkcvxa1z.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as s,K as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Hd as a,Id as b,Jd as c,Kd as d,Ld as e,Md as f,Nd as g}from"./chunk-
|
|
1
|
+
import{Hd as a,Id as b,Jd as c,Kd as d,Ld as e,Md as f,Nd as g}from"./chunk-vnnxvpnn.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import"./chunk-z6xfknxe.js";import"./chunk-rsh4rw9k.js";import"./chunk-74yge4ka.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-h4j0nve8.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ga as H}from"./chunk-
|
|
1
|
+
import{Ga as H}from"./chunk-fts2cp88.js";import"./chunk-ya5p7mx7.js";import"./chunk-gbsxnvgg.js";import{Qe as $,We as T}from"./chunk-reb25993.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-gzv143jr.js";import"./chunk-74yge4ka.js";import"./chunk-pkcvxa1z.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Ih as k}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pa as F,ra as L}from"./chunk-
|
|
1
|
+
import{pa as F,ra as L}from"./chunk-kfmpnq2r.js";import{Dd as $,Fd as B,Nd as Q}from"./chunk-vnnxvpnn.js";import{Nf as y}from"./chunk-zd410m70.js";import{Ih as V}from"./chunk-qa4efys0.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
|
|
2
2
|
|
|
3
3
|
${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{j as m,I as n,M as o,R as p,_ as q,C as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b as i,c as l,d as m}from"./chunk-
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-k3crvmvt.js";import"./chunk-7k5v52ct.js";import"./chunk-9318pj5k.js";import"./chunk-076txzms.js";import"./chunk-0538yd6h.js";import"./chunk-k40dje0b.js";import"./chunk-kfmpnq2r.js";import"./chunk-z5rtzcm4.js";import"./chunk-fts2cp88.js";import"./chunk-8eh0vp98.js";import"./chunk-7cx577bv.js";import"./chunk-ya5p7mx7.js";import"./chunk-vnnxvpnn.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{qe as n}from"./chunk-nahy2t67.js";import"./chunk-ztp2ff01.js";import{Me as s}from"./chunk-reb25993.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-zkxszt12.js";import"./chunk-zd410m70.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-gzv143jr.js";import"./chunk-74yge4ka.js";import"./chunk-pkcvxa1z.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-k3crvmvt.js";import"./chunk-7k5v52ct.js";import"./chunk-9318pj5k.js";import"./chunk-076txzms.js";import"./chunk-0538yd6h.js";import"./chunk-k40dje0b.js";import"./chunk-kfmpnq2r.js";import"./chunk-z5rtzcm4.js";import"./chunk-fts2cp88.js";import"./chunk-8eh0vp98.js";import"./chunk-7cx577bv.js";import"./chunk-ya5p7mx7.js";import"./chunk-vnnxvpnn.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{qe as R}from"./chunk-nahy2t67.js";import"./chunk-ztp2ff01.js";import{Me as Q}from"./chunk-reb25993.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-zkxszt12.js";import"./chunk-zd410m70.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-gzv143jr.js";import"./chunk-74yge4ka.js";import"./chunk-pkcvxa1z.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import{wi as M}from"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as SH,n as TH,o as bH,p as IH,q as RH,r as gH}from"./chunk-wgd4ject.js";import{A as VH,v as yH,w as HH,x as JH,y as KH,z as d}from"./chunk-sbrj2czw.js";import{$ as FH,T as _H,V as GH,W as PH,Y as qH}from"./chunk-m4tpqesg.js";import"./chunk-z5rtzcm4.js";import"./chunk-3p7c1dsk.js";import"./chunk-8eh0vp98.js";import{Cb as xH,Lb as UH,qb as o}from"./chunk-v7rnx21e.js";import"./chunk-ya5p7mx7.js";import{Cd as O,Nd as i,nd as WH,rd as jH}from"./chunk-t7nj9vg8.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as AH}from"./chunk-fkhtff66.js";import{le as MH,me as fH,ne as zH}from"./chunk-xby5w74x.js";import{oe as EH}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Oe as LH}from"./chunk-61efg3yh.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-ns5vb2p4.js";import"./chunk-tt3n8gnq.js";import{$f as $H}from"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-5rtjx9xk.js";import"./chunk-74yge4ka.js";import"./chunk-7wf2acxx.js";import{sh as QH}from"./chunk-t48zm299.js";import{uh as DH,wh as H,xh as ZH,zh as N}from"./chunk-7dqh8bqm.js";import{Dh as a,Eh as s}from"./chunk-d83bfr0b.js";import{Ih as g}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-hn1xztva.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import SJ from"yargs";import{hideBin as TJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function uH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),P=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let y=K.once?.bind(K)??K.on?.bind(K);y?.("drain",x),y?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function dH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await uH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new VH({maxPendingItems:V.maxPendingItems??HH,maxPendingBytes:V.maxPendingBytes??JH,writeTimeoutMs:V.writeTimeoutMs??KH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>dH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var XH=1;function D(K){return H.Object({event_version:H.Literal(XH),...K})}var pH=D({type:H.Literal("content_delta"),delta:H.String()}),vH=D({type:H.Literal("thinking_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking"),content:H.String()}),aH=D({type:H.Literal("stream_end")}),sH=D({type:H.Literal("content"),content:H.String()}),iH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),oH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),rH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),nH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(oH)}),tH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),eH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(tH)}),HJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),JJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),VJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),ZJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),$J=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),XJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),YJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),BJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),NJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),QJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),DJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),LJ=D({type:H.Literal("task_update"),tasks:H.Array(qH)}),WJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N($H)),premature_stop_count:H.Optional(H.Integer({minimum:1}))}),jJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),xJ=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),UJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),_J=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),GJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),PJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),FJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),EJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),MJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),fJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),yJ=D({type:H.Literal("error"),message:H.String()}),rJ=ZH(H.Union([pH,vH,lH,aH,sH,iH,rH,nH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,GJ,PJ,_J,FJ,EJ,AJ,MJ,fJ,zJ,yJ]));function YH(K,V){return{event_version:XH,type:K,...V}}function bJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function IJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var RJ=N(["text","jsonl"]),gJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(QH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(RJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function CJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function kJ(K){let V=DH(gJ,K);if(!V.success)throw Error(`Invalid headless options: ${CJ(V.error)}`);return V.data}function hJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await dJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
1
|
+
import{m as SH,n as TH,o as bH,p as IH,q as RH,r as gH}from"./chunk-0z3c8p6d.js";import{A as VH,v as yH,w as HH,x as JH,y as KH,z as d}from"./chunk-k40dje0b.js";import{$ as FH,T as _H,V as GH,W as PH,Y as qH}from"./chunk-kfmpnq2r.js";import"./chunk-z5rtzcm4.js";import"./chunk-fts2cp88.js";import"./chunk-8eh0vp98.js";import{Cb as xH,Lb as UH,qb as o}from"./chunk-7cx577bv.js";import"./chunk-ya5p7mx7.js";import{Cd as O,Nd as i,nd as WH,rd as jH}from"./chunk-vnnxvpnn.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as AH}from"./chunk-v5c34zya.js";import{le as MH,me as fH,ne as zH}from"./chunk-xdvjwtfc.js";import{oe as EH}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Oe as LH}from"./chunk-reb25993.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-zkxszt12.js";import"./chunk-zd410m70.js";import{$f as $H}from"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-gzv143jr.js";import"./chunk-74yge4ka.js";import"./chunk-pkcvxa1z.js";import{sh as QH}from"./chunk-t48zm299.js";import{uh as DH,wh as H,xh as ZH,zh as N}from"./chunk-7dqh8bqm.js";import{Dh as a,Eh as s}from"./chunk-d83bfr0b.js";import{Ih as g}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import SJ from"yargs";import{hideBin as TJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function uH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),P=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let y=K.once?.bind(K)??K.on?.bind(K);y?.("drain",x),y?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function dH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await uH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new VH({maxPendingItems:V.maxPendingItems??HH,maxPendingBytes:V.maxPendingBytes??JH,writeTimeoutMs:V.writeTimeoutMs??KH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>dH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var XH=1;function D(K){return H.Object({event_version:H.Literal(XH),...K})}var pH=D({type:H.Literal("content_delta"),delta:H.String()}),vH=D({type:H.Literal("thinking_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking"),content:H.String()}),aH=D({type:H.Literal("stream_end")}),sH=D({type:H.Literal("content"),content:H.String()}),iH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),oH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),rH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),nH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(oH)}),tH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),eH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(tH)}),HJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),JJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),VJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),ZJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),$J=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),XJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),YJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),BJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),NJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),QJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),DJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),LJ=D({type:H.Literal("task_update"),tasks:H.Array(qH)}),WJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N($H)),premature_stop_count:H.Optional(H.Integer({minimum:1}))}),jJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),xJ=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),UJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),_J=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),GJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),PJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),FJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),EJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),MJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),fJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),yJ=D({type:H.Literal("error"),message:H.String()}),rJ=ZH(H.Union([pH,vH,lH,aH,sH,iH,rH,nH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,GJ,PJ,_J,FJ,EJ,AJ,MJ,fJ,zJ,yJ]));function YH(K,V){return{event_version:XH,type:K,...V}}function bJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function IJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var RJ=N(["text","jsonl"]),gJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(QH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(RJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function CJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function kJ(K){let V=DH(gJ,K);if(!V.success)throw Error(`Invalid headless options: ${CJ(V.error)}`);return V.data}function hJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await dJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
2
2
|
`)}function OJ(K){return`[task] [${K.status}] ${K.subject}`}function wJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function mJ(K){if(!(K instanceof Error))return"Unknown error";let q=K.lastError??K;if(q.responseBody)try{let W=JSON.parse(q.responseBody)?.error?.message;if(W)return q.statusCode?`${W} (HTTP ${q.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function cJ(K){return K==="jsonl"?"jsonl":"text"}function BH(K,V){let Q=(...q)=>{for(let J of q){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function uJ(K,V,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function NH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify(YH(J,Z))}
|
|
3
3
|
`)};return{contentDelta(J){if(V==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return q("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){q("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){q("stream_end",{});return}if(Z)K.stderr.write(`
|
|
4
4
|
`);if(J)K.stdout.write(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-
|
|
1
|
+
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-0z3c8p6d.js";import{$ as y,T as M}from"./chunk-kfmpnq2r.js";import"./chunk-z5rtzcm4.js";import"./chunk-fts2cp88.js";import"./chunk-8eh0vp98.js";import{Cb as h,Lb as A}from"./chunk-7cx577bv.js";import"./chunk-ya5p7mx7.js";import{Nd as U,zd as w}from"./chunk-vnnxvpnn.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as C}from"./chunk-v5c34zya.js";import{le as I,me as S,ne as v}from"./chunk-xdvjwtfc.js";import{oe as O}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Le as P}from"./chunk-reb25993.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-zkxszt12.js";import"./chunk-zd410m70.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-gzv143jr.js";import"./chunk-74yge4ka.js";import"./chunk-pkcvxa1z.js";import{sh as F}from"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Ih as z}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
2
|
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
3
|
`);else j.io.stdout.write(`${j.response}
|
|
4
4
|
`)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ai as f,vi as a,wi as b,xi as c,yi as d,zi as e}from"./chunk-
|
|
1
|
+
import{Ai as f,vi as a,wi as b,xi as c,yi as d,zi as e}from"./chunk-cd2xwddv.js";import"./chunk-nh45xp7r.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-v508x7cg.js";import{qh as Q}from"./chunk-
|
|
2
|
-
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-vy4dz3yz.js"),{SessionService:B}=await import("./chunk-
|
|
1
|
+
import"./chunk-v508x7cg.js";import{qh as Q}from"./chunk-pkcvxa1z.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Ih as L}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import{Qi as F}from"./chunk-nh45xp7r.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
|
|
2
|
+
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-vy4dz3yz.js"),{SessionService:B}=await import("./chunk-088bnp26.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
|
|
3
3
|
`);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
|
|
4
4
|
Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{_b as E4}from"./chunk-ya5p7mx7.js";import{Cd as I0,Ed as V6,Fd as R1,Gd as K6,Nd as n$,Rc as kJ,Tc as CJ,Uc as vJ,Vc as d2,Wc as m2,ac as X$,ad as IJ,bd as S4,cd as T4,dd as v2,ed as x1,fd as M4,gd as R4,hd as E1,kd as UJ,sd as V1}from"./chunk-t7nj9vg8.js";import{Sd as F0,Vd as _J,Wd as k0}from"./chunk-4jbpvete.js";import{Xe as tJ}from"./chunk-zj4kfyer.js";import{$e as HJ,Ye as _4,Ze as i0,_e as O4,cf as b1,df as Y6,ef as zJ,ff as BJ,hf as jJ}from"./chunk-0eqk29xr.js";import{Sf as J$,Tf as r0,Wf as b4,_f as X4}from"./chunk-yjh47zv6.js";import{jg as A$}from"./chunk-5rtjx9xk.js";import{th as rJ}from"./chunk-t48zm299.js";import{Ih as H0}from"./chunk-qa4efys0.js";import{ii as h0}from"./chunk-h4j0nve8.js";import{wi as xJ}from"./chunk-hn1xztva.js";import{Hi as _$,Ji as i6,Ki as y0,Li as M1,Ni as MJ,Oi as RJ,Pi as hJ}from"./chunk-na1cney5.js";import{Qi as G8}from"./chunk-nh45xp7r.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class f1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function _6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function b6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function E6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var d4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),m4=/^(LD_.+|DYLD_.+|PATH)$/,S6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function c$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(!d4.has(K))break;J=Y}return J}function vZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(m4.test(K))break;J=Y}return J}var c4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function U2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of c4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var l4=new Set(["npm","pnpm","yarn","bun"]),M6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),i4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),r4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function n4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function R6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function o4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function a4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function s4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function t4($){let J=R6($.replace(r4,"").trim()),Z=a4(J);if(!Z)return;if(Z.length===0)return h6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=R6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!s4(V))return;return h6(Y)}function h6($){let Z=l$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=t4($);if(!Z)return!1;let W=c$(Z),Y=l$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:o4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...i4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(l4.has(Q??""))return n4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&M6.has(X??""))return!0;if(M6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function dZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var D2=h0("Agent"),e4=3;function w2($,J,Z){if($!=="length")return{action:"none"};if(J>=e4)return{action:"truncated"};if(_6(Z)==="stop")return D2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var $5=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],J5=/```[\s\S]{50,}```/,x6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Z5=2;function q2($,J,Z=!0){if(!$||J>=Z5)return{action:"none"};if(!Z&&J5.test($))return{action:"retry",prompt:x6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if($5.some((K)=>K.test(W)))return{action:"retry",prompt:x6};return{action:"none"}}var W5=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],k6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},Y5={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},V5="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",K5="Required verification did not run successfully before the retry limit.",Q5=3;function v6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function G2($,J,Z){if(!$||!W5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(k6).filter((X)=>k6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Y5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=Q5)return{action:"fail",message:K5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${V5}${Q}`}}var X5=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],I6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function u6($){return typeof $==="string"&&I6.some((J)=>J.test($))}var H5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],z5=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function B5($){if(typeof $!=="string")return;if(z5.some((J)=>J.test($)))return"multiple-allowed";return H5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=B5(J);if(Z!==void 0)return Z==="required"}return!1}var j5="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",U5="Required delegation did not complete before the retry limit.",D5=3;function g6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(I6.some((Q)=>Q.test(K)))break;if(X5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=D5)return{action:"fail",message:U5};return{action:"retry",prompt:j5}}var w5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],G5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function p6($){return G5.reduce((J,Z)=>J.replace(Z," "),$)}function A1($){if(typeof $!=="string")return!1;let J=p6($);return w5.some((Z)=>Z.test(J))}var F5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",L5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",O5="Required worktree lifecycle did not complete before the retry limit.",f5=3;function d6($,J,Z){if(!$)return{action:"none"};let W=p6($);if(!A1(W))return{action:"none"};let Y=q5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=f5)return{action:"fail",message:O5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?F5:L5}}var C6=30000;async function F2($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),C6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return D2.warn(`[Loop] Stop hook 超时 (${C6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return D2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function y5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var A5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function P5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function N5($){let J=$;for(let X of A5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function m6($){return N5(P5($))}import{EventEmitter as _5}from"events";import c6 from"node:path";function L2($){if(i6($.sessionId),!c6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:c6.resolve($.projectPath)}}function l6($){let J=L2($);return JSON.stringify([J.projectPath,J.sessionId])}function $3($,J){return l6($)===l6(J)}class P$ extends _5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=L2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var t0=h0("Agent"),P1=new Set;async function b5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=m6(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var O2=`<turn_aborted>
|
|
1
|
+
import{_b as E4}from"./chunk-ya5p7mx7.js";import{Cd as I0,Ed as V6,Fd as R1,Gd as K6,Nd as n$,Rc as kJ,Tc as CJ,Uc as vJ,Vc as d2,Wc as m2,ac as X$,ad as IJ,bd as S4,cd as T4,dd as v2,ed as x1,fd as M4,gd as R4,hd as E1,kd as UJ,sd as V1}from"./chunk-vnnxvpnn.js";import{Sd as F0,Vd as _J,Wd as k0}from"./chunk-4jbpvete.js";import{Xe as tJ}from"./chunk-zj4kfyer.js";import{$e as HJ,Ye as _4,Ze as i0,_e as O4,cf as b1,df as Y6,ef as zJ,ff as BJ,hf as jJ}from"./chunk-0eqk29xr.js";import{Sf as J$,Tf as r0,Wf as b4,_f as X4}from"./chunk-yjh47zv6.js";import{jg as A$}from"./chunk-gzv143jr.js";import{th as rJ}from"./chunk-t48zm299.js";import{Ih as H0}from"./chunk-qa4efys0.js";import{ii as h0}from"./chunk-h4j0nve8.js";import{wi as xJ}from"./chunk-cd2xwddv.js";import{Hi as _$,Ji as i6,Ki as y0,Li as M1,Ni as MJ,Oi as RJ,Pi as hJ}from"./chunk-na1cney5.js";import{Qi as G8}from"./chunk-nh45xp7r.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class f1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function _6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function b6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function E6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var d4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),m4=/^(LD_.+|DYLD_.+|PATH)$/,S6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function c$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(!d4.has(K))break;J=Y}return J}function vZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(m4.test(K))break;J=Y}return J}var c4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function U2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of c4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var l4=new Set(["npm","pnpm","yarn","bun"]),M6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),i4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),r4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function n4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function R6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function o4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function a4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function s4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function t4($){let J=R6($.replace(r4,"").trim()),Z=a4(J);if(!Z)return;if(Z.length===0)return h6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=R6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!s4(V))return;return h6(Y)}function h6($){let Z=l$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=t4($);if(!Z)return!1;let W=c$(Z),Y=l$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:o4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...i4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(l4.has(Q??""))return n4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&M6.has(X??""))return!0;if(M6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function dZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var D2=h0("Agent"),e4=3;function w2($,J,Z){if($!=="length")return{action:"none"};if(J>=e4)return{action:"truncated"};if(_6(Z)==="stop")return D2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var $5=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],J5=/```[\s\S]{50,}```/,x6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Z5=2;function q2($,J,Z=!0){if(!$||J>=Z5)return{action:"none"};if(!Z&&J5.test($))return{action:"retry",prompt:x6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if($5.some((K)=>K.test(W)))return{action:"retry",prompt:x6};return{action:"none"}}var W5=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],k6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},Y5={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},V5="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",K5="Required verification did not run successfully before the retry limit.",Q5=3;function v6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function G2($,J,Z){if(!$||!W5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(k6).filter((X)=>k6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Y5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=Q5)return{action:"fail",message:K5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${V5}${Q}`}}var X5=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],I6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function u6($){return typeof $==="string"&&I6.some((J)=>J.test($))}var H5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],z5=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function B5($){if(typeof $!=="string")return;if(z5.some((J)=>J.test($)))return"multiple-allowed";return H5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=B5(J);if(Z!==void 0)return Z==="required"}return!1}var j5="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",U5="Required delegation did not complete before the retry limit.",D5=3;function g6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(I6.some((Q)=>Q.test(K)))break;if(X5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=D5)return{action:"fail",message:U5};return{action:"retry",prompt:j5}}var w5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],G5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function p6($){return G5.reduce((J,Z)=>J.replace(Z," "),$)}function A1($){if(typeof $!=="string")return!1;let J=p6($);return w5.some((Z)=>Z.test(J))}var F5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",L5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",O5="Required worktree lifecycle did not complete before the retry limit.",f5=3;function d6($,J,Z){if(!$)return{action:"none"};let W=p6($);if(!A1(W))return{action:"none"};let Y=q5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=f5)return{action:"fail",message:O5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?F5:L5}}var C6=30000;async function F2($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),C6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return D2.warn(`[Loop] Stop hook 超时 (${C6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return D2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function y5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var A5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function P5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function N5($){let J=$;for(let X of A5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function m6($){return N5(P5($))}import{EventEmitter as _5}from"events";import c6 from"node:path";function L2($){if(i6($.sessionId),!c6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:c6.resolve($.projectPath)}}function l6($){let J=L2($);return JSON.stringify([J.projectPath,J.sessionId])}function $3($,J){return l6($)===l6(J)}class P$ extends _5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=L2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var t0=h0("Agent"),P1=new Set;async function b5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=m6(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var O2=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",r6="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class N$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function z$($){return $.executionEngine?.getContextManager()}async function l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)b5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new N$("user_message",{cause:Q})}return null}async function x0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let B=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!B)throw Error("Durable assistant-message commit returned no identity");return B}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new N$("assistant_message",{cause:X})}return null}async function n6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",O2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function o6($,J,Z,W,Y){try{let V=z$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function f2($,J,Z,W,Y,V={}){try{let K=z$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function N1($,J,Z,W,Y,V,K,Q,X,H={}){try{let B=z$($);if(B&&J.sessionId){let j=await B.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(B){if(t0.warn("[Loop] 保存工具结果失败:",B),H.required)throw B}return null}async function o$($,J,Z,W,Y={}){try{let V=z$($);if(V&&J.sessionId){let K=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(t0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function U0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,B=await x0(J,Z,Y,H,V);if(B)H=B;if(Q!==void 0){let j={role:"user",content:Q};if(X)j.metadata=X;W.appendControl("user",j);let z=await l0(J,Z,j.content,H,X);if(z)H=z}return H}import{createHash as Q6}from"node:crypto";import{promises as m5}from"node:fs";import c5 from"node:path";import{nanoid as e0}from"nanoid";import*as J0 from"node:fs/promises";import*as B$ from"node:path";var a6={enabled:!0,maxIndexLines:200};var E5="memory",s6="MEMORY.md";class y2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=_$($);this.memoryDir=B$.join(W,E5)}this.config={...a6,...J}}async initialize(){if(this.initialized)return;await J0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=B$.join(this.memoryDir,s6);try{let J=await J0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{wi as S}from"./chunk-
|
|
1
|
+
import{wi as S}from"./chunk-cd2xwddv.js";import{Qi as f}from"./chunk-nh45xp7r.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 h,u as i,g as j,C as k,V as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ab as d,Bb as e,Cb as f,Db as g,Eb as h,Fb as i,Gb as j,Hb as k,Ob as l,Pb as m,Qb as n,Rb as o,Tb as p,Ub as q,Vb as r,tb as a,ub as b,wb as c}from"./chunk-
|
|
1
|
+
import{Ab as d,Bb as e,Cb as f,Db as g,Eb as h,Fb as i,Gb as j,Hb as k,Ob as l,Pb as m,Qb as n,Rb as o,Tb as p,Ub as q,Vb as r,tb as a,ub as b,wb as c}from"./chunk-7cx577bv.js";import"./chunk-ya5p7mx7.js";import"./chunk-vnnxvpnn.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-z6xfknxe.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-gzv143jr.js";import"./chunk-74yge4ka.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.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{h as o}from"./chunk-
|
|
1
|
+
import{h as o}from"./chunk-8488pkzv.js";import"./chunk-cd2xwddv.js";import"./chunk-nh45xp7r.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{le as a,me as b,ne as c}from"./chunk-
|
|
1
|
+
import{le as a,me as b,ne as c}from"./chunk-xdvjwtfc.js";import"./chunk-wbfa6xce.js";import"./chunk-reb25993.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-4cvmfne8.js";import"./chunk-pkcvxa1z.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.
|
|
1
|
+
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.94",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
|
|
2
2
|
export{y as vi,p as wi,v as xi,g as yi,f as zi,w as Ai};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{je as a,ke as b}from"./chunk-v5c34zya.js";import"./chunk-cd2xwddv.js";import"./chunk-nh45xp7r.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Wb as Xt,Xb as fn,Yb as yn,Zb as En}from"./chunk-ya5p7mx7.js";import{jg as Bt}from"./chunk-
|
|
1
|
+
import{Wb as Xt,Xb as fn,Yb as yn,Zb as En}from"./chunk-ya5p7mx7.js";import{jg as Bt}from"./chunk-gzv143jr.js";import{Ag as dn,Bg as on,Cg as pn,Dg as lt,Eg as cn,Fg as un,Gg as Mn,Ig as S,Lg as wn,Mg as Gt,Ng as Ut,Og as h,Pg as Ht,og as gt,pg as vi,qg as sn,rg as zt,sg as U,tg as en,ug as xt,vg as mt,xg as rn,yg as Tn,zg as B}from"./chunk-pkcvxa1z.js";import{uh as X,wh as g}from"./chunk-7dqh8bqm.js";import{Ih as It}from"./chunk-qa4efys0.js";import{wi as tn,xi as nn}from"./chunk-cd2xwddv.js";import{Qi as ns}from"./chunk-nh45xp7r.js";import{EventEmitter as bs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;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 jt(t){return{name:t.name,displayName:t.displayName,kind: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
|
|