blade-code 0.11.8 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-74vmjngm.js → chunk-0vet7np5.js} +1 -1
  3. package/dist/{chunk-j5e589we.js → chunk-113t7z1d.js} +1 -1
  4. package/dist/{chunk-926rkw87.js → chunk-123x4vv0.js} +1 -1
  5. package/dist/{chunk-2fj047zf.js → chunk-1j3y40wn.js} +1 -1
  6. package/dist/{chunk-hdy7b6zw.js → chunk-3ce55d11.js} +1 -1
  7. package/dist/{chunk-34y4z9ns.js → chunk-54mb3ar4.js} +1 -1
  8. package/dist/{chunk-0e9nrf53.js → chunk-58t96cyv.js} +1 -1
  9. package/dist/{chunk-1gr9vqy1.js → chunk-5tf0hs46.js} +1 -1
  10. package/dist/{chunk-7876fd4b.js → chunk-75an4n90.js} +1 -1
  11. package/dist/{chunk-ayqqhefz.js → chunk-7bvtz3mm.js} +1 -1
  12. package/dist/{chunk-de3wa8nq.js → chunk-7me3rm8n.js} +1 -1
  13. package/dist/{chunk-np5t59fa.js → chunk-8cr35jh6.js} +1 -1
  14. package/dist/{chunk-53twn9t2.js → chunk-8fasjabf.js} +1 -1
  15. package/dist/{chunk-vjvw3v6b.js → chunk-8hke5rc9.js} +1 -1
  16. package/dist/{chunk-m8sttgjc.js → chunk-8httqk7j.js} +1 -1
  17. package/dist/{chunk-3t655nhk.js → chunk-8tjh8nzm.js} +1 -1
  18. package/dist/{chunk-e613h191.js → chunk-8wk4q3bz.js} +363 -363
  19. package/dist/{chunk-8r8fp09p.js → chunk-am63xh9m.js} +1 -1
  20. package/dist/{chunk-1crgzzz7.js → chunk-bckm03fv.js} +53 -53
  21. package/dist/{chunk-erget6wk.js → chunk-d40j41s5.js} +1 -1
  22. package/dist/{chunk-14jd0cj6.js → chunk-geakn1sr.js} +1 -1
  23. package/dist/{chunk-s7jd42xp.js → chunk-j5nz7kb4.js} +1 -1
  24. package/dist/chunk-j63n860q.js +1 -0
  25. package/dist/{chunk-rwtsvy5y.js → chunk-jgmaytrk.js} +1 -1
  26. package/dist/{chunk-rcfef8qj.js → chunk-k5595spk.js} +1 -1
  27. package/dist/{chunk-dgypy6yt.js → chunk-k6knawfb.js} +9 -9
  28. package/dist/{chunk-b0smnpzh.js → chunk-katmqxmn.js} +1 -1
  29. package/dist/{chunk-rh1q6srx.js → chunk-kn7jya27.js} +1 -1
  30. package/dist/chunk-mnm8epn5.js +2 -0
  31. package/dist/{chunk-547g7bq5.js → chunk-mvyrhqrm.js} +2 -2
  32. package/dist/{chunk-22py5y1p.js → chunk-pt4reckf.js} +1 -1
  33. package/dist/chunk-se9tcqqv.js +1 -0
  34. package/dist/{chunk-re6hbrmb.js → chunk-t5hhrj1g.js} +1 -1
  35. package/dist/{chunk-5q2gp1bb.js → chunk-vh5za5en.js} +1 -1
  36. package/dist/{chunk-mmwqe49e.js → chunk-vhc0z5k0.js} +1 -1
  37. package/dist/{chunk-3m8949fr.js → chunk-vkabej0v.js} +1 -1
  38. package/dist/{chunk-29t2wbwt.js → chunk-yzw0e9a5.js} +1 -1
  39. package/dist/{chunk-nr5s7qtp.js → chunk-z7f2a75f.js} +1 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-c1331rdc.js +0 -2
  42. package/dist/chunk-jbp9wt3f.js +0 -1
  43. package/dist/chunk-kz842bqy.js +0 -1
@@ -1 +1 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-7876fd4b.js";import"./chunk-j5e589we.js";import"./chunk-870szc6v.js";import"./chunk-mmwqe49e.js";import"./chunk-vjvw3v6b.js";import"./chunk-22py5y1p.js";import"./chunk-e613h191.js";import"./chunk-nad5spvc.js";import"./chunk-74vmjngm.js";import"./chunk-whxkwaz1.js";import"./chunk-3t655nhk.js";import"./chunk-9qxch6sy.js";import"./chunk-ayqqhefz.js";import"./chunk-skktstg8.js";import"./chunk-s14zayxp.js";import"./chunk-b5cz00mt.js";import{Ef as n}from"./chunk-8r8fp09p.js";import"./chunk-crv3sghv.js";import{_f as s}from"./chunk-dgypy6yt.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-1g7c3f82.js";import"./chunk-3v9epq9s.js";import"./chunk-eexs73bz.js";import"./chunk-pm163dfm.js";import"./chunk-np5t59fa.js";import"./chunk-34y4z9ns.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-3m8949fr.js";import"./chunk-ys8gysg8.js";import"./chunk-nr5s7qtp.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-c1331rdc.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.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
+ import{a,b as i,c as l,d as m}from"./chunk-75an4n90.js";import"./chunk-113t7z1d.js";import"./chunk-870szc6v.js";import"./chunk-vhc0z5k0.js";import"./chunk-8hke5rc9.js";import"./chunk-pt4reckf.js";import"./chunk-8wk4q3bz.js";import"./chunk-nad5spvc.js";import"./chunk-0vet7np5.js";import"./chunk-whxkwaz1.js";import"./chunk-8tjh8nzm.js";import"./chunk-9qxch6sy.js";import"./chunk-7bvtz3mm.js";import"./chunk-skktstg8.js";import"./chunk-s14zayxp.js";import"./chunk-b5cz00mt.js";import{Ef as n}from"./chunk-am63xh9m.js";import"./chunk-crv3sghv.js";import{_f as s}from"./chunk-k6knawfb.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-1g7c3f82.js";import"./chunk-3v9epq9s.js";import"./chunk-eexs73bz.js";import"./chunk-pm163dfm.js";import"./chunk-8cr35jh6.js";import"./chunk-54mb3ar4.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-vkabej0v.js";import"./chunk-ys8gysg8.js";import"./chunk-z7f2a75f.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-mnm8epn5.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.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,2 +1,2 @@
1
- import{Ui as I}from"./chunk-nr5s7qtp.js";import{Pj as G,Qj as H}from"./chunk-xhwdac1j.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
1
+ import{Ui as I}from"./chunk-z7f2a75f.js";import{Pj as G,Qj as H}from"./chunk-xhwdac1j.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
2
2
  export{D as zg,Q as Ag,T as Bg,U as Cg};
@@ -1 +1 @@
1
- import{Xj as a,Yj as b,Zj as c,_j as d}from"./chunk-c1331rdc.js";import"./chunk-gmpsfkgg.js";export{a as getVersion,b as getPackageName,c as getDescription,d as getCopyright};
1
+ import{Xj as a,Yj as b,Zj as c,_j as d}from"./chunk-mnm8epn5.js";import"./chunk-gmpsfkgg.js";export{a as getVersion,b as getPackageName,c as getDescription,d as getCopyright};
@@ -1,4 +1,4 @@
1
- import{ia as p}from"./chunk-e613h191.js";import{Tb as _}from"./chunk-3t655nhk.js";import{Ed as N,Fd as U,Gd as I,Hd as A,Id as z,Td as q,ne as O}from"./chunk-ayqqhefz.js";import{ze as o}from"./chunk-s14zayxp.js";import{fg as P}from"./chunk-x6k5ye1z.js";import{Gg as e}from"./chunk-34y4z9ns.js";import{Ak as j}from"./chunk-ed2hdrwe.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
1
+ import{ia as p}from"./chunk-8wk4q3bz.js";import{Tb as _}from"./chunk-8tjh8nzm.js";import{Ed as N,Fd as U,Gd as I,Hd as A,Id as z,Td as q,ne as O}from"./chunk-7bvtz3mm.js";import{ze as o}from"./chunk-s14zayxp.js";import{fg as P}from"./chunk-x6k5ye1z.js";import{Gg as e}from"./chunk-54mb3ar4.js";import{Ak as j}from"./chunk-ed2hdrwe.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${c} must contain 1-${u} characters`);return f}function Q(a){return a.split("\x00").filter(Boolean)}async function X(a,c){return(await C(a,["rev-parse","--verify",`${c}^{commit}`])).trim()}async function Ff(a,c,f,w,h){let g=h,$=await i(a);for(let k of c){let l=n.resolve($,k),x=n.relative($,l);if(!x||x.startsWith("..")||n.isAbsolute(x))throw Error(`Untracked review path escapes the workspace: ${k}`);let b=await bf(l);if(!b.isFile()||b.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${k}`);if(g+=b.size,g>T)throw Error(`Review target exceeds ${T} bytes`);f.update("\x00untracked\x00"),f.update(x.replaceAll(n.sep,"/")),f.update("\x00");let F=await mf(l);f.update(F);let m=Math.max(1,F.toString("utf8").split(`
3
3
  `).length);w.set(x.replaceAll(n.sep,"/"),[{start:1,end:m}])}}function Y(a,c){let f=new Map,w,h,g,$,k=!1,l=(x,b)=>{let F=f.get(x)??[],m=F.at(-1);if(m&&b<=m.end+1)m.end=Math.max(m.end,b);else F.push({start:b,end:b});f.set(x,F)};for(let x of a.split(`
4
4
  `)){if(x.startsWith("--- ")){let b=x.slice(4).split("\t")[0]?.trim();w=b&&b!=="/dev/null"?b.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(x.startsWith("+++ ")){let b=x.slice(4).split("\t")[0]?.trim();k=b==="/dev/null",h=k?w:b?b.replace(/^b\//,"").replaceAll("\\","/"):void 0,g=void 0,$=void 0;continue}if(x.startsWith("@@ ")){let b=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(x);g=b?Math.max(1,Number(b[1])):void 0,$=b?Math.max(1,Number(b[2])):void 0;continue}if(!h||g===void 0||$===void 0)continue;if(x.startsWith("+")&&!x.startsWith("+++"))l(h,$),$++;else if(x.startsWith("-")&&!x.startsWith("---"))l(h,k?g:$),g++;else if(!x.startsWith("\\"))g++,$++}for(let x of c)if(!f.has(x))f.set(x,[{start:1,end:1}]);return f}function D(a){if(a.length>s)throw Error(`Review target exceeds the ${s} file limit`)}class K{static async resolve(a,c){let f=await i(a);await C(f,["rev-parse","--is-inside-work-tree"]);let w=await X(f,"HEAD"),h=xf("sha256");h.update(`kind\x00${c.kind}\x00head\x00${w}\x00`);let g="",$=[],k,l,x,b,F=new Map;switch(c.kind){case"uncommitted":{g=await C(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=Q(await C(f,["diff","--name-only","-z","--relative","HEAD","--","."])),L=Q(await C(f,["ls-files","--others","--exclude-standard","-z","--","."]));if($=[...new Set([...m,...L])].sort(),D($),$.length===0)throw Error("No uncommitted changes to review");h.update(g),F=Y(g,m),await Ff(f,L,h,F,Buffer.byteLength(g)),x="uncommitted changes",b=["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=d(c.ref,"Base ref");k=await X(f,m);let L=(await C(f,["merge-base",k,w])).trim();if(g=await C(f,["diff","--binary","--no-ext-diff","--relative",`${L}..${w}`,"--","."]),$=Q(await C(f,["diff","--name-only","-z","--relative",`${L}..${w}`,"--","."])),D($),$.length===0)throw Error(`No changes between ${m} and HEAD`);h.update(g),h.update(`\x00merge-base\x00${L}`),F=Y(g,$),x=`changes against ${m}`,b=`Review changes introduced by ${L}..${w}.`;break}case"commit":{let m=d(c.ref,"Commit ref");if(l=await X(f,m),g=await C(f,["show","--format=","--binary","--no-ext-diff","--relative",l,"--","."]),$=Q(await C(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",l,"--","."])),D($),$.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);h.update(g),h.update(`\x00commit\x00${l}`),F=Y(g,$),x=`commit ${m}`,b=`Review only the changes introduced by commit ${l}.`;break}}if(Buffer.byteLength(g)>T)throw Error(`Review diff exceeds ${T} bytes`);return{info:{kind:c.kind,label:x,headSha:w,...k?{baseSha:k}:{},...l?{commitSha:l}:{},digest:h.digest("hex"),fileCount:$.length},instruction:b,changedLines:F}}}var Wf=131072,t=50,Z=new Set;function v(a,c){return`${R.resolve(a)}\x00${c}`}function S(a){return`/review ${a.kind}${a.kind==="uncommitted"?"":` ${a.ref?.trim()??""}`}`}function V(a,c,f,w=!1){if(typeof a!=="string")throw Error(`${c} must be a string`);let h=a.trim();if(!w&&!h||h.length>f)throw Error(`${c} exceeds its allowed length`);return h}function Hf(a,c,f){if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Review finding must be an object");let w=a,h=typeof w.line==="number"&&Number.isInteger(w.line)?w.line:void 0,g=w.code_location??(typeof w.file==="string"&&h!==void 0?{path:w.file,line_start:h,line_end:h}:void 0);if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Review finding has no code_location");let $=g,k=V($.path,"Finding path",1000),l=R.posix.normalize(k.replaceAll("\\","/"));if(R.posix.isAbsolute(l)||l===".."||l.startsWith("../"))throw Error("Review finding path must be workspace-relative");let x=R.resolve(c,l),b=R.relative(R.resolve(c),x);if(b.startsWith("..")||R.isAbsolute(b))throw Error("Review finding path escapes the workspace");let F=typeof w.severity==="string"?w.severity.toLowerCase():"",m=F==="critical"?0:F==="high"?1:F==="medium"?2:F==="low"?3:void 0,L=w.priority??m;if(L!==0&&L!==1&&L!==2&&L!==3)throw Error("Review finding priority must be 0-3");let W=w.confidence_score??w.confidence??0.8;if(typeof W!=="number"||!Number.isFinite(W)||W<0||W>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:H,line_end:r}=$;if(!Number.isInteger(H)||!Number.isInteger(r)||H<1||r<H||r-H>=10)throw Error("Review finding line range is invalid");let G=f.changedLines.get(l);if(!G)throw Error("Review finding path is outside the review target");if(!G.some((y)=>H<=y.end&&r>=y.start))throw Error("Review finding line range does not overlap the changed lines");let B=V(w.title??`[P${L}] ${String(w.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(y)=>y.toUpperCase())}`,"Finding title",120);if(!B.startsWith(`[P${L}] `))throw Error("Review finding title priority does not match priority");return{title:B,body:V(w.body??w.description,"Finding body",4000),priority:L,confidenceScore:W,codeLocation:{path:l,lineStart:H,lineEnd:r}}}function Rf(a,c,f){if(Buffer.byteLength(a)>Wf)throw Error("Review output exceeds the 128 KiB limit");let w=a.indexOf("{"),h=a.lastIndexOf("}");if(w<0||h<=w)throw Error("Reviewer did not return a JSON object");let g;try{g=JSON.parse(a.slice(w,h+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Reviewer output must be an object");let $=g;if(!Array.isArray($.findings))throw Error("Reviewer output must contain findings");if($.findings.length>t)throw Error(`Reviewer returned more than ${t} findings`);return{overallExplanation:V($.overall_explanation??$.summary,"Review explanation",1e4,!0),findings:$.findings.map((k)=>Hf(k,c,f))}}async function J(a,c){return new o(j(a,c)).readAll()}class rf{static async start(a){let{sessionId:c,projectPath:f,runtime:w,request:h,onEvent:g}=a;if(w.sessionId!==c||R.resolve(w.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(w.hasTurnOwner())throw Error("Cannot start a review during an active turn");await O.assertSessionWritable(c,f);let $=v(f,c);if(Z.has($))throw Error("Session already has an active review");let k=await J(f,c);if(U(k))throw Error("Session has an interrupted review that must be recovered");let l=h.instructions?.trim();if(l&&l.length>4000)throw Error("Review instructions exceed 4,000 characters");let x=await K.resolve(f,h),b=Lf(16),F=P("review"),m=new Date().toISOString(),L={reviewId:b,reviewerSessionId:F,target:x.info,startedAt:m},W=new _(f);await W.saveReviewStart(c,L),await W.saveMessage(c,"user",S(h),null,{codeReview:{reviewId:b,phase:"started",targetKind:x.info.kind,targetDigest:x.info.digest}}),await O.updateSessionMetadata(c,f,{taskStatus:"running",taskStatusReason:`Reviewing ${x.info.label}`,taskPromptSummary:S(h),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),Z.add($);let H=this.execute({...a,target:x,reviewId:b,reviewerSessionId:F,instructions:l,store:W,onEvent:g}).finally(()=>{Z.delete($)});return{reviewId:b,completion:H}}static async execute(a){let{sessionId:c,projectPath:f,runtime:w,request:h,signal:g,onEvent:$,target:k,reviewId:l,reviewerSessionId:x,instructions:b,store:F}=a,m;try{let W=[k.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${k.info.digest}`,`Changed file count: ${k.info.fileCount}`,b?`Additional review instructions:
@@ -1 +1 @@
1
- import{Af as b,Bf as c,zf as a}from"./chunk-1gr9vqy1.js";import"./chunk-yjdyzb5z.js";import"./chunk-dgypy6yt.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-7ajvrtb3.js";import"./chunk-nr5s7qtp.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-c1331rdc.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
1
+ import{Af as b,Bf as c,zf as a}from"./chunk-5tf0hs46.js";import"./chunk-yjdyzb5z.js";import"./chunk-k6knawfb.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-7ajvrtb3.js";import"./chunk-z7f2a75f.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-mnm8epn5.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,4 +1,4 @@
1
- import{Bc as f4}from"./chunk-9qxch6sy.js";import{Ad as x2,Bd as I2,Cc as D$,Cd as L6,Dd as q6,Ec as j$,Fc as M2,Gc as r1,Ic as H$,Jd as h2,Kd as k4,Ld as M4,Md as j6,Nd as e1,Od as R4,Pd as x4,Qd as d1,Ud as Z2,ae as o2,ce as A0,ee as x6,fe as o1,ge as I6,ne as W1,yd as R2}from"./chunk-ayqqhefz.js";import{se as T4}from"./chunk-skktstg8.js";import{Ke as F0,Le as n2,ve as P0,ye as F2,ze as s1}from"./chunk-s14zayxp.js";import{fg as t2}from"./chunk-x6k5ye1z.js";import{gg as A4,hg as h0,ig as O4,jg as sJ,lg as u1,mg as R6,ng as tJ,og as eJ,rg as $2}from"./chunk-1g7c3f82.js";import{ch as Z$,dh as c0,fh as E4,gh as S4}from"./chunk-kehgewqh.js";import{lh as H4,ph as j2}from"./chunk-kkzznz4w.js";import{Ah as T$}from"./chunk-3m8949fr.js";import{Ih as M$}from"./chunk-nr5s7qtp.js";import{Zi as H0}from"./chunk-b22ab7yw.js";import{Ej as L0}from"./chunk-saz6mwpq.js";import{Xj as k2}from"./chunk-c1331rdc.js";import{Ak as S2,Ck as T2,Hk as f2,dk as E2,sk as N2,tk as _2,wk as xJ,zk as AJ}from"./chunk-ed2hdrwe.js";import{Jk as lZ}from"./chunk-gmpsfkgg.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function b$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class x1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(b$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!b$(W))}get historyLength(){return this._history.length}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getHistory(){return this._history}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!b$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...F0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.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((Z)=>!A$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!A$(Z)&&!b$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}}function QJ($){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 XJ($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function HJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import X$ from"node:path";var i4=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"]),l4=/^(LD_.+|DYLD_.+|PATH)$/,VJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function e$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(VJ);if(!K)break;let Q=K[1];if(!i4.has(Q))break;Z=Y}return Z}function qW($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(VJ);if(!K)break;let Q=K[1];if(l4.test(Q))break;Z=Y}return Z}var r4=[/^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 IZ($){let Z=$,J=!0;while(J){J=!1;for(let W of r4){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function $1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let Q=0;Q<$.length;Q++){let X=$[Q];if(K){J+=X,K=!1;continue}if(X==="\\"&&!W){J+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,J+=X;continue}if(X==='"'&&!W){Y=!Y,J+=X;continue}if(W||Y){J+=X;continue}if(X==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(J.trim())Z.push(J.trim());J="",Q++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(J.trim())Z.push(J.trim());J="",Q++;continue}if(X==="&")return null;if(X===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=X}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function zJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function Q$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let Q=0;Q<$.length;Q++){let X=$[Q];if(K){J+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let H=$[Q+1];if(H&&'$`"\\'.includes(H))continue;J+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(J)Z.push(J),J="";continue}J+=X}if(J)Z.push(J);return Z}var n4=new Set(["npm","pnpm","yarn","bun"]),BJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),o4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),a4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function s4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function jJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function t4($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Q$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let Q=X$.isAbsolute(K)?X$.resolve(K):X$.resolve(J,K);if(!H$.isWithinWorkspace(Q,J))return;return W[2]?.trim()||void 0}function e4($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(Y){Y=!1;continue}if(Q==="\\"&&!J){Y=!0;continue}if(Q==="'"&&!W){J=!J;continue}if(Q==='"'&&!J){W=!W;continue}if(Q!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function $5($){let Z=Q$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function Z5($){let Z=jJ($.replace(a4,"").trim()),J=e4(Z);if(!J)return;if(J.length===0)return DJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=jJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!$5(K))return;return DJ(Y)}function DJ($){let J=$1($)?.at(-1);if(!J)return $;let W=Q$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((X)=>X==="--configLoader"||X.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function E$($,Z){let J=Z5($);if(!J)return!1;let W=e$(J),Y=$1(W);if(!Y||zJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:t4(W,Y,Z);if(!K)return!1;let Q=Q$(K);if(Q.length===0||Q.some((V)=>[...o4].some((j)=>V===j||V.startsWith(`${j}=`))))return!1;let[X,H,z]=Q;if(n4.has(X??""))return s4(H==="run"?z:H)||H==="--test";if((X==="npx"||X==="bunx")&&BJ.has(H??""))return!0;if(BJ.has(X??""))return!0;if(X==="node"&&H==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(H??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(H??"")}function _W($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!X$.isAbsolute($);let J=X$.isAbsolute($)?X$.resolve($):X$.resolve(Z,$);return H$.isWithinWorkspace(J,Z)}var hZ=L0("Agent"),J5=3;function vZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=J5)return{action:"truncated"};if(QJ(J)==="stop")return hZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var W5=[/:\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],Y5=/```[\s\S]{50,}```/,wJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",K5=2;function CZ($,Z,J=!0){if(!$||Z>=K5)return{action:"none"};if(!J&&Y5.test($))return{action:"retry",prompt:wJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(W5.some((Q)=>Q.test(W)))return{action:"retry",prompt:wJ};return{action:"none"}}var I1=2,Q5="The model returned tool-call JSON as text instead of completing the requested tool workflow.",X5="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function pZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let Q=new Set;for(let X of K.tool_calls){if(!X||typeof X!=="object"||Array.isArray(X))return{action:"none"};let H="function"in X;if(Object.keys(X).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in X&&X.type!=="function")return{action:"none"};let z=H?X.function:X;if(!z||typeof z!=="object"||Array.isArray(z)||!("name"in z)||typeof z.name!=="string"||!("arguments"in z))return{action:"none"};if(H&&Object.keys(z).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(z.name))return{action:"none"};let V=z.arguments;if(typeof V!=="string"&&(!V||typeof V!=="object"||Array.isArray(V)))return{action:"none"};let j=z.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${j}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${j}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${j}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${j}(?![\\w:-])`,"i");if(!B.test(Y)||w.test(Y))return{action:"none"};Q.add(z.name)}return W<I1?{action:"retry",prompt:X5,...Q.size===1?{toolName:[...Q][0]}:{}}:{action:"fail",message:Q5}}var H5=[/\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}(?:测试|单测|集成测试|检查|构建)/],UJ={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},V5={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},z5="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.",B5="Required verification did not run successfully before the retry limit.",j5=3;function LJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&E$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&E$(K,W))$.add(K)}function gZ($,Z,J){if(!$||!H5.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(UJ).filter((H)=>UJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((z)=>V5[H].test(z)));if(W.length>0?K.length===0:Y.some((H)=>E$(H)))return{action:"none"};if(J>=j5)return{action:"fail",message:B5};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${z5}${X}`}}var D5=[/\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|子代理|子智能体)/],qJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function FJ($){return typeof $==="string"&&qJ.some((Z)=>Z.test($))}var w5=[/\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|子代理)/],U5=[/\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 G5($){if(typeof $!=="string")return;if(U5.some((Z)=>Z.test($)))return"multiple-allowed";return w5.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=G5(Z);if(J!==void 0)return J==="required"}return!1}var L5="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.",q5="Required delegation did not complete before the retry limit.",F5=3;function OJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let Q of W){if(qJ.some((X)=>X.test(Q)))break;if(D5.some((X)=>X.test(Q))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=F5)return{action:"fail",message:q5};return{action:"retry",prompt:L5}}var O5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],P5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],N5=[/\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 PJ($){return N5.reduce((Z,J)=>Z.replace(J," "),$)}function h1($){if(typeof $!=="string")return!1;let Z=PJ($);return O5.some((J)=>J.test(Z))}var _5="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.",y5="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.",b5="Required worktree lifecycle did not complete before the retry limit.",A5=3;function NJ($,Z,J){if(!$)return{action:"none"};let W=PJ($);if(!h1(W))return{action:"none"};let Y=P5.some((Q)=>Q.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=A5)return{action:"fail",message:b5};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?_5:y5}}var GJ=30000;async function mZ($){try{let J=T$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),GJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return hZ.warn(`[Loop] Stop hook 超时 (${GJ}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=K;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return hZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function E5($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var S5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function T5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function f5($){let Z=$;for(let H of S5)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),Q=K.lastIndexOf(" ");return`${(Q>36?K.slice(0,Q):K).trimEnd()}…`}function _J($){return f5(T5($))}import{EventEmitter as k5}from"events";import yJ from"node:path";function uZ($){if(AJ($.sessionId),!yJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:yJ.resolve($.projectPath)}}function bJ($){let Z=uZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function hW($,Z){return bJ($)===bJ(Z)}class f$ extends k5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!f$.instance)f$.instance=new f$;return f$.instance}publish($,Z,J,W){let Y=uZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var J1=f$.getInstance();var a0=L0("Agent"),v1=new Set;async function M5($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(v1.has(J))return;if(v1.size>=5000)v1.clear();v1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=_J(Z);if(!K)return;await W1.updateSessionMetadata(J,Y.projectPath,{title:K}),J1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){a0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var dZ=`<turn_aborted>
1
+ import{Bc as f4}from"./chunk-9qxch6sy.js";import{Ad as x2,Bd as I2,Cc as D$,Cd as L6,Dd as q6,Ec as j$,Fc as M2,Gc as r1,Ic as H$,Jd as h2,Kd as k4,Ld as M4,Md as j6,Nd as e1,Od as R4,Pd as x4,Qd as d1,Ud as Z2,ae as o2,ce as A0,ee as x6,fe as o1,ge as I6,ne as W1,yd as R2}from"./chunk-7bvtz3mm.js";import{se as T4}from"./chunk-skktstg8.js";import{Ke as F0,Le as n2,ve as P0,ye as F2,ze as s1}from"./chunk-s14zayxp.js";import{fg as t2}from"./chunk-x6k5ye1z.js";import{gg as A4,hg as h0,ig as O4,jg as sJ,lg as u1,mg as R6,ng as tJ,og as eJ,rg as $2}from"./chunk-1g7c3f82.js";import{ch as Z$,dh as c0,fh as E4,gh as S4}from"./chunk-kehgewqh.js";import{lh as H4,ph as j2}from"./chunk-kkzznz4w.js";import{Ah as T$}from"./chunk-vkabej0v.js";import{Ih as M$}from"./chunk-z7f2a75f.js";import{Zi as H0}from"./chunk-b22ab7yw.js";import{Ej as L0}from"./chunk-saz6mwpq.js";import{Xj as k2}from"./chunk-mnm8epn5.js";import{Ak as S2,Ck as T2,Hk as f2,dk as E2,sk as N2,tk as _2,wk as xJ,zk as AJ}from"./chunk-ed2hdrwe.js";import{Jk as lZ}from"./chunk-gmpsfkgg.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function b$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class x1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(b$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!b$(W))}get historyLength(){return this._history.length}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getHistory(){return this._history}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!b$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...F0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.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((Z)=>!A$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!A$(Z)&&!b$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}}function QJ($){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 XJ($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function HJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import X$ from"node:path";var i4=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"]),l4=/^(LD_.+|DYLD_.+|PATH)$/,VJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function e$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(VJ);if(!K)break;let Q=K[1];if(!i4.has(Q))break;Z=Y}return Z}function qW($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(VJ);if(!K)break;let Q=K[1];if(l4.test(Q))break;Z=Y}return Z}var r4=[/^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 IZ($){let Z=$,J=!0;while(J){J=!1;for(let W of r4){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function $1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let Q=0;Q<$.length;Q++){let X=$[Q];if(K){J+=X,K=!1;continue}if(X==="\\"&&!W){J+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,J+=X;continue}if(X==='"'&&!W){Y=!Y,J+=X;continue}if(W||Y){J+=X;continue}if(X==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(J.trim())Z.push(J.trim());J="",Q++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(J.trim())Z.push(J.trim());J="",Q++;continue}if(X==="&")return null;if(X===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=X}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function zJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function Q$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let Q=0;Q<$.length;Q++){let X=$[Q];if(K){J+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let H=$[Q+1];if(H&&'$`"\\'.includes(H))continue;J+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(J)Z.push(J),J="";continue}J+=X}if(J)Z.push(J);return Z}var n4=new Set(["npm","pnpm","yarn","bun"]),BJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),o4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),a4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function s4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function jJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function t4($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Q$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let Q=X$.isAbsolute(K)?X$.resolve(K):X$.resolve(J,K);if(!H$.isWithinWorkspace(Q,J))return;return W[2]?.trim()||void 0}function e4($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(Y){Y=!1;continue}if(Q==="\\"&&!J){Y=!0;continue}if(Q==="'"&&!W){J=!J;continue}if(Q==='"'&&!J){W=!W;continue}if(Q!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function $5($){let Z=Q$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function Z5($){let Z=jJ($.replace(a4,"").trim()),J=e4(Z);if(!J)return;if(J.length===0)return DJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=jJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!$5(K))return;return DJ(Y)}function DJ($){let J=$1($)?.at(-1);if(!J)return $;let W=Q$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((X)=>X==="--configLoader"||X.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function E$($,Z){let J=Z5($);if(!J)return!1;let W=e$(J),Y=$1(W);if(!Y||zJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:t4(W,Y,Z);if(!K)return!1;let Q=Q$(K);if(Q.length===0||Q.some((V)=>[...o4].some((j)=>V===j||V.startsWith(`${j}=`))))return!1;let[X,H,z]=Q;if(n4.has(X??""))return s4(H==="run"?z:H)||H==="--test";if((X==="npx"||X==="bunx")&&BJ.has(H??""))return!0;if(BJ.has(X??""))return!0;if(X==="node"&&H==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(H??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(H??"")}function _W($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!X$.isAbsolute($);let J=X$.isAbsolute($)?X$.resolve($):X$.resolve(Z,$);return H$.isWithinWorkspace(J,Z)}var hZ=L0("Agent"),J5=3;function vZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=J5)return{action:"truncated"};if(QJ(J)==="stop")return hZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var W5=[/:\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],Y5=/```[\s\S]{50,}```/,wJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",K5=2;function CZ($,Z,J=!0){if(!$||Z>=K5)return{action:"none"};if(!J&&Y5.test($))return{action:"retry",prompt:wJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(W5.some((Q)=>Q.test(W)))return{action:"retry",prompt:wJ};return{action:"none"}}var I1=2,Q5="The model returned tool-call JSON as text instead of completing the requested tool workflow.",X5="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function pZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let Q=new Set;for(let X of K.tool_calls){if(!X||typeof X!=="object"||Array.isArray(X))return{action:"none"};let H="function"in X;if(Object.keys(X).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in X&&X.type!=="function")return{action:"none"};let z=H?X.function:X;if(!z||typeof z!=="object"||Array.isArray(z)||!("name"in z)||typeof z.name!=="string"||!("arguments"in z))return{action:"none"};if(H&&Object.keys(z).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(z.name))return{action:"none"};let V=z.arguments;if(typeof V!=="string"&&(!V||typeof V!=="object"||Array.isArray(V)))return{action:"none"};let j=z.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${j}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${j}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${j}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${j}(?![\\w:-])`,"i");if(!B.test(Y)||w.test(Y))return{action:"none"};Q.add(z.name)}return W<I1?{action:"retry",prompt:X5,...Q.size===1?{toolName:[...Q][0]}:{}}:{action:"fail",message:Q5}}var H5=[/\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}(?:测试|单测|集成测试|检查|构建)/],UJ={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},V5={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},z5="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.",B5="Required verification did not run successfully before the retry limit.",j5=3;function LJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&E$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&E$(K,W))$.add(K)}function gZ($,Z,J){if(!$||!H5.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(UJ).filter((H)=>UJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((z)=>V5[H].test(z)));if(W.length>0?K.length===0:Y.some((H)=>E$(H)))return{action:"none"};if(J>=j5)return{action:"fail",message:B5};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${z5}${X}`}}var D5=[/\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|子代理|子智能体)/],qJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function FJ($){return typeof $==="string"&&qJ.some((Z)=>Z.test($))}var w5=[/\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|子代理)/],U5=[/\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 G5($){if(typeof $!=="string")return;if(U5.some((Z)=>Z.test($)))return"multiple-allowed";return w5.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=G5(Z);if(J!==void 0)return J==="required"}return!1}var L5="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.",q5="Required delegation did not complete before the retry limit.",F5=3;function OJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let Q of W){if(qJ.some((X)=>X.test(Q)))break;if(D5.some((X)=>X.test(Q))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=F5)return{action:"fail",message:q5};return{action:"retry",prompt:L5}}var O5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],P5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],N5=[/\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 PJ($){return N5.reduce((Z,J)=>Z.replace(J," "),$)}function h1($){if(typeof $!=="string")return!1;let Z=PJ($);return O5.some((J)=>J.test(Z))}var _5="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.",y5="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.",b5="Required worktree lifecycle did not complete before the retry limit.",A5=3;function NJ($,Z,J){if(!$)return{action:"none"};let W=PJ($);if(!h1(W))return{action:"none"};let Y=P5.some((Q)=>Q.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=A5)return{action:"fail",message:b5};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?_5:y5}}var GJ=30000;async function mZ($){try{let J=T$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),GJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return hZ.warn(`[Loop] Stop hook 超时 (${GJ}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=K;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return hZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function E5($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var S5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function T5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function f5($){let Z=$;for(let H of S5)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),Q=K.lastIndexOf(" ");return`${(Q>36?K.slice(0,Q):K).trimEnd()}…`}function _J($){return f5(T5($))}import{EventEmitter as k5}from"events";import yJ from"node:path";function uZ($){if(AJ($.sessionId),!yJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:yJ.resolve($.projectPath)}}function bJ($){let Z=uZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function hW($,Z){return bJ($)===bJ(Z)}class f$ extends k5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!f$.instance)f$.instance=new f$;return f$.instance}publish($,Z,J,W){let Y=uZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var J1=f$.getInstance();var a0=L0("Agent"),v1=new Set;async function M5($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(v1.has(J))return;if(v1.size>=5000)v1.clear();v1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=_J(Z);if(!K)return;await W1.updateSessionMetadata(J,Y.projectPath,{title:K}),J1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){a0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var dZ=`<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>`,V$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",EJ="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 k$ extends Error{phase;constructor($,Z){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.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function z$($){return $.executionEngine?.getContextManager()}async function d0($,Z,J,W=null,Y,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=typeof J==="string"?J.trim()!=="":J.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(X&&Z.sessionId&&H){let z=await X.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(Q&&!z)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)M5(Z,J);return z}if(Q&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(X){if(a0.warn("[Loop] 保存用户消息失败:",X),Q)throw new k$("user_message",{cause:X})}return null}async function O0($,Z,J,W,Y,K,Q={}){let X=Q.required??$.executionEngine!==void 0;try{let H=z$($),z=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&z){let V=await H.saveMessage(Z.sessionId,"assistant",J,W,K,Z.subagentInfo,Y);if(X&&!V)throw Error("Durable assistant-message commit returned no identity");return V}if(X&&Z.sessionId&&z)throw Error("Durable assistant-message storage is unavailable")}catch(H){if(a0.warn("[Loop] 保存助手消息失败:",H),X)throw new k$("assistant_message",{cause:H})}return null}async function SJ($,Z,J){try{let W=z$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",dZ,J,void 0,Z.subagentInfo)}catch(W){a0.warn("[Loop] 保存中断边界失败:",W)}return null}async function TJ($,Z,J,W,Y){try{let K=z$($);if(!K||!Z.sessionId||J.length===0)return null;return await K.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((Q)=>({...Q})))),triggerPaths:[...W]},Z.subagentInfo)}catch(K){a0.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function cZ($,Z,J,W,Y,K={}){try{let Q=z$($);if(Q&&Z.sessionId){let X=await Q.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,K.providerToolCallId);if(K.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(K.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(Q){if(a0.warn("[Loop] 保存工具调用失败:",Q),K.required)throw Q}return null}async function C1($,Z,J,W,Y,K,Q,X,H,z={}){try{let V=z$($);if(V&&Z.sessionId){let j=await V.saveToolResult(Z.sessionId,J,W,Y,K,Q,Z.subagentInfo,X,H);if(z.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(z.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(V){if(a0.warn("[Loop] 保存工具结果失败:",V),z.required)throw V}return null}async function Y1($,Z,J,W,Y={}){try{let K=z$($);if(K&&Z.sessionId){let Q=await K.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!Q)throw Error("Compaction checkpoint commit returned no identity");return Q||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if(a0.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function X0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:Q,controlPrompt:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let H=Q,z=await O0(Z,J,Y,H,K);if(z)H=z;if(X!==void 0){let V={role:"user",content:X,metadata:F0};W.appendControl("user",V);let j=await d0(Z,J,X,H,F0);if(j)H=j}return H}import{createHash as h6}from"node:crypto";import{promises as X8}from"node:fs";import H8 from"node:path";import{nanoid as t0}from"nanoid";import*as s from"node:fs/promises";import*as s0 from"node:path";import kJ from"write-file-atomic";var fJ={enabled:!0,maxIndexLines:200};var R5="memory",iZ="MEMORY.md",rZ="<!-- blade:auto-memory-topics:start -->",p1="<!-- blade:auto-memory-topics:end -->",x5={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},I5=new M$,MJ;function IJ($){return $.trim().replace(/\s+/g," ")}function h5($){return IJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function v5($){return[rZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),p1].join(`
4
4
  `)}function C5($,Z){let J=v5(Z),W=$.indexOf(rZ),Y=$.indexOf(p1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+p1.length);if(!$)return`${J}