blade-code 0.10.67 → 0.10.68

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 (48) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-0f8nn2h1.js +5 -0
  3. package/dist/{chunk-8t2xknh6.js → chunk-1r3zgzsk.js} +1 -1
  4. package/dist/{chunk-amaxww4b.js → chunk-1rg4p2v1.js} +1 -1
  5. package/dist/{chunk-8mr5vydg.js → chunk-2xz8kw3r.js} +1 -1
  6. package/dist/{chunk-wr60s2qh.js → chunk-3b0z45ej.js} +1 -1
  7. package/dist/{chunk-6am7zz57.js → chunk-3hmvp733.js} +1 -1
  8. package/dist/{chunk-gayy8vky.js → chunk-3mm2n48d.js} +3 -3
  9. package/dist/{chunk-7agkmjm7.js → chunk-4khwmc1s.js} +1 -1
  10. package/dist/{chunk-eq99gcj8.js → chunk-8gzm51m8.js} +1 -1
  11. package/dist/{chunk-gak96awp.js → chunk-8y7wvqx4.js} +1 -1
  12. package/dist/{chunk-gvxpdb2v.js → chunk-9jpksycv.js} +1 -1
  13. package/dist/{chunk-nacssmem.js → chunk-a6bg3tyj.js} +1 -1
  14. package/dist/{chunk-pv576mrv.js → chunk-ab7awwm7.js} +1 -1
  15. package/dist/{chunk-nrh7qjat.js → chunk-b760m6w5.js} +1 -1
  16. package/dist/{chunk-7pxpwkeg.js → chunk-c8nx34eq.js} +1 -1
  17. package/dist/{chunk-k5a3n7q5.js → chunk-cw72ydsc.js} +1 -1
  18. package/dist/{chunk-5kz804w9.js → chunk-e1dqxg53.js} +1 -1
  19. package/dist/{chunk-vavy5dw8.js → chunk-e5a9jxnw.js} +1 -1
  20. package/dist/chunk-edgd965j.js +1 -0
  21. package/dist/chunk-efemjy9y.js +2 -0
  22. package/dist/{chunk-p0gyfy9p.js → chunk-ektjpv2v.js} +1 -1
  23. package/dist/{chunk-w5jdnsyz.js → chunk-f1qvcn1z.js} +1 -1
  24. package/dist/{chunk-2wz3mf50.js → chunk-f2xng5g1.js} +1 -1
  25. package/dist/{chunk-eqqxr26g.js → chunk-fknvpxg5.js} +1 -1
  26. package/dist/{chunk-0aja46wq.js → chunk-gkf4j7hd.js} +1 -1
  27. package/dist/{chunk-fs6ashcf.js → chunk-j7tweh9y.js} +1 -1
  28. package/dist/{chunk-37g8mh93.js → chunk-kg9kvbg4.js} +1 -1
  29. package/dist/{chunk-696t7mzc.js → chunk-kwykw1mk.js} +1 -1
  30. package/dist/{chunk-3j8q6yrf.js → chunk-mmfrypfb.js} +1 -1
  31. package/dist/{chunk-pf6ftbra.js → chunk-msh36mac.js} +2 -2
  32. package/dist/{chunk-zd05g5qs.js → chunk-n728g0r7.js} +1 -1
  33. package/dist/{chunk-te88v4a8.js → chunk-q48ksbhx.js} +1 -1
  34. package/dist/{chunk-yq2891kc.js → chunk-q4adr6y2.js} +1 -1
  35. package/dist/{chunk-kccs7c9r.js → chunk-shhnxq90.js} +1 -1
  36. package/dist/{chunk-tb363yj8.js → chunk-tqfp6grc.js} +1 -1
  37. package/dist/{chunk-2a9rndk2.js → chunk-tqr5w9br.js} +1 -1
  38. package/dist/chunk-tqvxyrab.js +6 -0
  39. package/dist/{chunk-38x7njj5.js → chunk-vmd7skd7.js} +1 -1
  40. package/dist/{chunk-yy6h97k0.js → chunk-w67k19a1.js} +1 -1
  41. package/dist/{chunk-rbdd49vr.js → chunk-y1cv193c.js} +1 -1
  42. package/dist/chunk-z1784103.js +1 -0
  43. package/package.json +1 -1
  44. package/dist/chunk-2kkpn41a.js +0 -5
  45. package/dist/chunk-53xbkvk1.js +0 -6
  46. package/dist/chunk-cn9jekw9.js +0 -1
  47. package/dist/chunk-f99n8812.js +0 -2
  48. package/dist/chunk-gn3fxtkj.js +0 -1
@@ -1 +1 @@
1
- import{Ee as a,Fe as b,Ge as c,He as d,Ie as e,Je as f,Ke as g,Le as h,Me as i,Ne as j}from"./chunk-k5a3n7q5.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-p0gyfy9p.js";import"./chunk-m57w4p91.js";import"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-amaxww4b.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
1
+ import{Ee as a,Fe as b,Ge as c,He as d,Ie as e,Je as f,Ke as g,Le as h,Me as i,Ne as j}from"./chunk-cw72ydsc.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-ektjpv2v.js";import"./chunk-m57w4p91.js";import"./chunk-a6bg3tyj.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-1rg4p2v1.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1,4 +1,4 @@
1
- import{O as P}from"./chunk-gayy8vky.js";import{fb as K}from"./chunk-yq2891kc.js";import{$b as s,Nc as B,Xb as G,Yb as N,Zb as S,_b as O}from"./chunk-w5jdnsyz.js";import{Wc as j}from"./chunk-zdxxqchm.js";import{Xd as q}from"./chunk-0j22w4wh.js";import{pe as v}from"./chunk-k5a3n7q5.js";import{vh as z}from"./chunk-ppsvzgs5.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(`
1
+ import{O as P}from"./chunk-3mm2n48d.js";import{fb as K}from"./chunk-q4adr6y2.js";import{$b as s,Nc as B,Xb as G,Yb as N,Zb as S,_b as O}from"./chunk-f1qvcn1z.js";import{Wc as j}from"./chunk-zdxxqchm.js";import{Xd as q}from"./chunk-0j22w4wh.js";import{pe as v}from"./chunk-cw72ydsc.js";import{vh as z}from"./chunk-ppsvzgs5.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 +1 @@
1
- import{f as a,g as i,h as l,i as m}from"./chunk-rbdd49vr.js";import"./chunk-dktrankr.js";import"./chunk-yvg961q3.js";import"./chunk-2a9rndk2.js";import"./chunk-696t7mzc.js";import"./chunk-nrh7qjat.js";import"./chunk-gayy8vky.js";import"./chunk-6am7zz57.js";import"./chunk-5147jh26.js";import"./chunk-yq2891kc.js";import"./chunk-th4jjfgm.js";import"./chunk-w5jdnsyz.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as n}from"./chunk-te88v4a8.js";import"./chunk-bjqjdw34.js";import{Md as s}from"./chunk-5kz804w9.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-2kkpn41a.js";import"./chunk-f99n8812.js";import"./chunk-yn51162x.js";import"./chunk-tb363yj8.js";import"./chunk-k5a3n7q5.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-p0gyfy9p.js";import"./chunk-m57w4p91.js";import"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-amaxww4b.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";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{f as a,g as i,h as l,i as m}from"./chunk-y1cv193c.js";import"./chunk-dktrankr.js";import"./chunk-yvg961q3.js";import"./chunk-tqr5w9br.js";import"./chunk-kwykw1mk.js";import"./chunk-b760m6w5.js";import"./chunk-3mm2n48d.js";import"./chunk-3hmvp733.js";import"./chunk-5147jh26.js";import"./chunk-q4adr6y2.js";import"./chunk-th4jjfgm.js";import"./chunk-f1qvcn1z.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as n}from"./chunk-q48ksbhx.js";import"./chunk-bjqjdw34.js";import{Md as s}from"./chunk-e1dqxg53.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-0f8nn2h1.js";import"./chunk-efemjy9y.js";import"./chunk-yn51162x.js";import"./chunk-tqfp6grc.js";import"./chunk-cw72ydsc.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-ektjpv2v.js";import"./chunk-m57w4p91.js";import"./chunk-a6bg3tyj.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-1rg4p2v1.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.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"./chunk-v508x7cg.js";import{gg as Q}from"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as L}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-amaxww4b.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import{Bh as F}from"./chunk-hcv17986.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-kmarzy98.js"),{SessionService:B}=await import("./chunk-gvxpdb2v.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...
1
+ import"./chunk-v508x7cg.js";import{gg as Q}from"./chunk-a6bg3tyj.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as L}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-1rg4p2v1.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import{Bh as F}from"./chunk-hcv17986.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-kmarzy98.js"),{SessionService:B}=await import("./chunk-9jpksycv.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 +1 @@
1
- import{ih as a,jh as b,kh as c,lh as d,mh as e,nh as f}from"./chunk-amaxww4b.js";import"./chunk-hcv17986.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{ih as a,jh as b,kh as c,lh as d,mh as e,nh as f}from"./chunk-1rg4p2v1.js";import"./chunk-hcv17986.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{Hd as N}from"./chunk-5kz804w9.js";import{$e as $}from"./chunk-p0gyfy9p.js";import{wg as _}from"./chunk-k0pa8874.js";import{Vg as Y,Xg as Z}from"./chunk-98n2rxmq.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{Hd as N}from"./chunk-e1dqxg53.js";import{$e as $}from"./chunk-ektjpv2v.js";import{wg as _}from"./chunk-k0pa8874.js";import{Vg as Y,Xg as Z}from"./chunk-98n2rxmq.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
4
4
  export{O as pd,y as qd,j as rd,C as sd};
@@ -1,4 +1,4 @@
1
- import{Lb as d2}from"./chunk-th4jjfgm.js";import{Cc as S0,Ec as R6,Fc as F1,Gc as C6,Mb as J$,Nc as I$,Tb as tJ,Ub as eJ,Vb as G6,Wb as F6,ac as $2,bc as c2,cc as i2,dc as j6,ec as N1,fc as l2,gc as r2,hc as L1,kc as MJ,sc as U$}from"./chunk-w5jdnsyz.js";import{Sc as l,Vc as cJ,Wc as A0}from"./chunk-zdxxqchm.js";import{Xd as w2}from"./chunk-0j22w4wh.js";import{Yd as g2,Zd as i0,_d as h2,be as m2,ce as h6,ee as kJ}from"./chunk-2kkpn41a.js";import{Oe as r0,Pe as C0,Se as u2}from"./chunk-hat9v5c5.js";import{$e as V$}from"./chunk-p0gyfy9p.js";import{jg as z2}from"./chunk-h0ft81a3.js";import{wg as K0}from"./chunk-k0pa8874.js";import{Xg as b0}from"./chunk-98n2rxmq.js";import{jh as sJ}from"./chunk-amaxww4b.js";import{Ah as aJ,sh as w$,uh as yJ,vh as L0,wh as G1,yh as oJ}from"./chunk-ppsvzgs5.js";import{Bh as PZ}from"./chunk-hcv17986.js";function z$($){return $.role==="system"&&Array.isArray($.content)}function Q$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class X1{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(z$);if(this._contextualSystemMessages=$.messages.filter(Q$),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)=>!z$(W)&&!Q$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}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(!Q$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(z$);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)=>!z$(J)&&!Q$(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(Q$),this._history=$.filter((J)=>!z$(J)&&!Q$(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function WJ($){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 YJ($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function KJ($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import $$ from"node:path";var Z8=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"]),W8=/^(LD_.+|DYLD_.+|PATH)$/,HJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function h$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(HJ);if(!K)break;let H=K[1];if(!Z8.has(H))break;J=Y}return J}function m4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(HJ);if(!K)break;let H=K[1];if(W8.test(H))break;J=Y}return J}var Y8=[/^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 a1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Y8){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 R$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function XJ($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function e0($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let Q=$[H+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var K8=new Set(["npm","pnpm","yarn","bun"]),QJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),H8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),X8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function Q8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function zJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function z8($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=e0(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=$$.isAbsolute(K)?$$.resolve(K):$$.resolve(Z,K);if(!J$.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function B8($){let J=[],Z=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let H=$[K];if(Y){Y=!1;continue}if(H==="\\"&&!Z){Y=!0;continue}if(H==="'"&&!W){Z=!Z;continue}if(H==='"'&&!Z){W=!W;continue}if(H!=="|"||Z||W)continue;if($[K+1]==="|")return;J.push(K)}return J}function V8($){let J=e0($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let K=(H)=>H!==void 0&&/^[1-9]\d{0,4}$/.test(H);if(J.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function D8($){let J=zJ($.replace(X8,"").trim()),Z=B8(J);if(!Z)return;if(Z.length===0)return BJ(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=zJ(J.slice(0,W).trim()),K=J.slice(W+1).trim();if(!Y||!V8(K))return;return BJ(Y)}function BJ($){let Z=R$($)?.at(-1);if(!Z)return $;let W=e0(Z),[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 B$($,J){let Z=D8($);if(!Z)return!1;let W=h$(Z),Y=R$(W);if(!Y||XJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:z8(W,Y,J);if(!K)return!1;let H=e0(K);if(H.length===0||H.some((w)=>[...H8].some((D)=>w===D||w.startsWith(`${D}=`))))return!1;let[X,Q,z]=H;if(K8.has(X??""))return Q8(Q==="run"?z:Q)||Q==="--test";if((X==="npx"||X==="bunx")&&QJ.has(Q??""))return!0;if(QJ.has(X??""))return!0;if(X==="node"&&Q==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(Q??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(Q??"")}function l4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!$$.isAbsolute($);let Z=$$.isAbsolute($)?$$.resolve($):$$.resolve(J,$);return J$.isWithinWorkspace(Z,J)}var s1=b0("Agent"),j8=3;function t1($,J,Z){if($!=="length")return{action:"none"};if(J>=j8)return{action:"truncated"};if(WJ(Z)==="stop")return s1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var w8=[/:\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],L8=/```[\s\S]{50,}```/,VJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",q8=2;function e1($,J,Z=!0){if(!$||J>=q8)return{action:"none"};if(!Z&&L8.test($))return{action:"retry",prompt:VJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(w8.some((H)=>H.test(W)))return{action:"retry",prompt:VJ};return{action:"none"}}var O8=[/\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}(?:测试|单测|集成测试|检查|构建)/],DJ={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},G8={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},F8="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.",U8="Required verification did not run successfully before the retry limit.",N8=3;function wJ($,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&&B$(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 K of Y)if(typeof K==="string"&&B$(K,W))$.add(K)}function $6($,J,Z){if(!$||!O8.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(DJ).filter((Q)=>DJ[Q].test($)),Y=[...J],K=W.filter((Q)=>!Y.some((z)=>G8[Q].test(z)));if(W.length>0?K.length===0:Y.some((Q)=>B$(Q)))return{action:"none"};if(Z>=N8)return{action:"fail",message:U8};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${F8}${X}`}}var P8=[/\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|子代理|子智能体)/],LJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function qJ($){return typeof $==="string"&&LJ.some((J)=>J.test($))}var y8=[/\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|子代理)/],_8=[/\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 b8($){if(typeof $!=="string")return;if(_8.some((J)=>J.test($)))return"multiple-allowed";return y8.some((J)=>J.test($))?"required":void 0}function z1($){for(let J of $){let Z=b8(J);if(Z!==void 0)return Z==="required"}return!1}var A8="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.",T8="Required delegation did not complete before the retry limit.",E8=3;function OJ($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=z1(W),K=!1;if(!Y)for(let H of W){if(LJ.some((X)=>X.test(H)))break;if(P8.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=E8)return{action:"fail",message:T8};return{action:"retry",prompt:A8}}var S8=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],f8=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],x8=[/\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 GJ($){return x8.reduce((J,Z)=>J.replace(Z," "),$)}function B1($){if(typeof $!=="string")return!1;let J=GJ($);return S8.some((Z)=>Z.test(J))}var k8="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.",M8="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.",h8="Required worktree lifecycle did not complete before the retry limit.",R8=3;function FJ($,J,Z){if(!$)return{action:"none"};let W=GJ($);if(!B1(W))return{action:"none"};let Y=f8.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=R8)return{action:"fail",message:h8};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?k8:M8}}var jJ=30000;async function J6($){try{let Z=V$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??K0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),jJ)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return s1.warn(`[Loop] Stop hook 超时 (${jJ}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return s1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function C8($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var I8=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function v8($){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 p8($){let J=$;for(let Q of I8)J=J.replace(Q," ");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 K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function UJ($){return p8(v8($))}import{EventEmitter as g8}from"events";import NJ from"node:path";function Z6($){if(yJ($.sessionId),!NJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:NJ.resolve($.projectPath)}}function PJ($){let J=Z6($);return JSON.stringify([J.projectPath,J.sessionId])}function Y5($,J){return PJ($)===PJ(J)}class D$ extends g8{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!D$.instance)D$.instance=new D$;return D$.instance}publish($,J,Z,W){let Y=Z6($);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 C$=D$.getInstance();var u0=b0("Agent"),V1=new Set;async function m8($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(V1.has(Z))return;if(V1.size>=5000)V1.clear();V1.add(Z);try{let W=$.workspaceRoot,Y=await I$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=UJ(J);if(!K)return;await I$.updateSessionMetadata(Z,Y.projectPath,{title:K}),C$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){u0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var W6=`<turn_aborted>
1
+ import{Lb as d2}from"./chunk-th4jjfgm.js";import{Cc as S0,Ec as R6,Fc as F1,Gc as C6,Mb as J$,Nc as I$,Tb as tJ,Ub as eJ,Vb as G6,Wb as F6,ac as $2,bc as c2,cc as i2,dc as j6,ec as N1,fc as l2,gc as r2,hc as L1,kc as MJ,sc as U$}from"./chunk-f1qvcn1z.js";import{Sc as l,Vc as cJ,Wc as A0}from"./chunk-zdxxqchm.js";import{Xd as w2}from"./chunk-0j22w4wh.js";import{Yd as g2,Zd as i0,_d as h2,be as m2,ce as h6,ee as kJ}from"./chunk-0f8nn2h1.js";import{Oe as r0,Pe as C0,Se as u2}from"./chunk-hat9v5c5.js";import{$e as V$}from"./chunk-ektjpv2v.js";import{jg as z2}from"./chunk-h0ft81a3.js";import{wg as K0}from"./chunk-k0pa8874.js";import{Xg as b0}from"./chunk-98n2rxmq.js";import{jh as sJ}from"./chunk-1rg4p2v1.js";import{Ah as aJ,sh as w$,uh as yJ,vh as L0,wh as G1,yh as oJ}from"./chunk-ppsvzgs5.js";import{Bh as PZ}from"./chunk-hcv17986.js";function z$($){return $.role==="system"&&Array.isArray($.content)}function Q$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class X1{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(z$);if(this._contextualSystemMessages=$.messages.filter(Q$),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)=>!z$(W)&&!Q$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}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(!Q$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(z$);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)=>!z$(J)&&!Q$(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(Q$),this._history=$.filter((J)=>!z$(J)&&!Q$(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function WJ($){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 YJ($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function KJ($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import $$ from"node:path";var Z8=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"]),W8=/^(LD_.+|DYLD_.+|PATH)$/,HJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function h$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(HJ);if(!K)break;let H=K[1];if(!Z8.has(H))break;J=Y}return J}function m4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(HJ);if(!K)break;let H=K[1];if(W8.test(H))break;J=Y}return J}var Y8=[/^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 a1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Y8){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 R$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function XJ($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function e0($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let Q=$[H+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var K8=new Set(["npm","pnpm","yarn","bun"]),QJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),H8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),X8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function Q8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function zJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function z8($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=e0(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=$$.isAbsolute(K)?$$.resolve(K):$$.resolve(Z,K);if(!J$.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function B8($){let J=[],Z=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let H=$[K];if(Y){Y=!1;continue}if(H==="\\"&&!Z){Y=!0;continue}if(H==="'"&&!W){Z=!Z;continue}if(H==='"'&&!Z){W=!W;continue}if(H!=="|"||Z||W)continue;if($[K+1]==="|")return;J.push(K)}return J}function V8($){let J=e0($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let K=(H)=>H!==void 0&&/^[1-9]\d{0,4}$/.test(H);if(J.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function D8($){let J=zJ($.replace(X8,"").trim()),Z=B8(J);if(!Z)return;if(Z.length===0)return BJ(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=zJ(J.slice(0,W).trim()),K=J.slice(W+1).trim();if(!Y||!V8(K))return;return BJ(Y)}function BJ($){let Z=R$($)?.at(-1);if(!Z)return $;let W=e0(Z),[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 B$($,J){let Z=D8($);if(!Z)return!1;let W=h$(Z),Y=R$(W);if(!Y||XJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:z8(W,Y,J);if(!K)return!1;let H=e0(K);if(H.length===0||H.some((w)=>[...H8].some((D)=>w===D||w.startsWith(`${D}=`))))return!1;let[X,Q,z]=H;if(K8.has(X??""))return Q8(Q==="run"?z:Q)||Q==="--test";if((X==="npx"||X==="bunx")&&QJ.has(Q??""))return!0;if(QJ.has(X??""))return!0;if(X==="node"&&Q==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(Q??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(Q??"")}function l4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!$$.isAbsolute($);let Z=$$.isAbsolute($)?$$.resolve($):$$.resolve(J,$);return J$.isWithinWorkspace(Z,J)}var s1=b0("Agent"),j8=3;function t1($,J,Z){if($!=="length")return{action:"none"};if(J>=j8)return{action:"truncated"};if(WJ(Z)==="stop")return s1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var w8=[/:\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],L8=/```[\s\S]{50,}```/,VJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",q8=2;function e1($,J,Z=!0){if(!$||J>=q8)return{action:"none"};if(!Z&&L8.test($))return{action:"retry",prompt:VJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(w8.some((H)=>H.test(W)))return{action:"retry",prompt:VJ};return{action:"none"}}var O8=[/\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}(?:测试|单测|集成测试|检查|构建)/],DJ={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},G8={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},F8="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.",U8="Required verification did not run successfully before the retry limit.",N8=3;function wJ($,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&&B$(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 K of Y)if(typeof K==="string"&&B$(K,W))$.add(K)}function $6($,J,Z){if(!$||!O8.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(DJ).filter((Q)=>DJ[Q].test($)),Y=[...J],K=W.filter((Q)=>!Y.some((z)=>G8[Q].test(z)));if(W.length>0?K.length===0:Y.some((Q)=>B$(Q)))return{action:"none"};if(Z>=N8)return{action:"fail",message:U8};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${F8}${X}`}}var P8=[/\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|子代理|子智能体)/],LJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function qJ($){return typeof $==="string"&&LJ.some((J)=>J.test($))}var y8=[/\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|子代理)/],_8=[/\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 b8($){if(typeof $!=="string")return;if(_8.some((J)=>J.test($)))return"multiple-allowed";return y8.some((J)=>J.test($))?"required":void 0}function z1($){for(let J of $){let Z=b8(J);if(Z!==void 0)return Z==="required"}return!1}var A8="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.",T8="Required delegation did not complete before the retry limit.",E8=3;function OJ($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=z1(W),K=!1;if(!Y)for(let H of W){if(LJ.some((X)=>X.test(H)))break;if(P8.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=E8)return{action:"fail",message:T8};return{action:"retry",prompt:A8}}var S8=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],f8=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],x8=[/\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 GJ($){return x8.reduce((J,Z)=>J.replace(Z," "),$)}function B1($){if(typeof $!=="string")return!1;let J=GJ($);return S8.some((Z)=>Z.test(J))}var k8="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.",M8="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.",h8="Required worktree lifecycle did not complete before the retry limit.",R8=3;function FJ($,J,Z){if(!$)return{action:"none"};let W=GJ($);if(!B1(W))return{action:"none"};let Y=f8.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=R8)return{action:"fail",message:h8};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?k8:M8}}var jJ=30000;async function J6($){try{let Z=V$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??K0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),jJ)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return s1.warn(`[Loop] Stop hook 超时 (${jJ}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return s1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function C8($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var I8=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function v8($){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 p8($){let J=$;for(let Q of I8)J=J.replace(Q," ");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 K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function UJ($){return p8(v8($))}import{EventEmitter as g8}from"events";import NJ from"node:path";function Z6($){if(yJ($.sessionId),!NJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:NJ.resolve($.projectPath)}}function PJ($){let J=Z6($);return JSON.stringify([J.projectPath,J.sessionId])}function Y5($,J){return PJ($)===PJ(J)}class D$ extends g8{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!D$.instance)D$.instance=new D$;return D$.instance}publish($,J,Z,W){let Y=Z6($);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 C$=D$.getInstance();var u0=b0("Agent"),V1=new Set;async function m8($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(V1.has(Z))return;if(V1.size>=5000)V1.clear();V1.add(Z);try{let W=$.workspaceRoot,Y=await I$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=UJ(J);if(!K)return;await I$.updateSessionMetadata(Z,Y.projectPath,{title:K}),C$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){u0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var W6=`<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>`,Z$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",_J="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 j$ 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 W$($){return $.executionEngine?.getContextManager()}async function B0($,J,Z,W=null,Y,K={}){let H=K.required??$.executionEngine!==void 0;try{let X=W$($),Q=typeof Z==="string"?Z.trim()!=="":Z.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(X&&J.sessionId&&Q){let z=await X.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(H&&!z)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)m8(J,Z);return z}if(H&&J.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(X){if(u0.warn("[Loop] 保存用户消息失败:",X),H)throw new j$("user_message",{cause:X})}return null}async function i($,J,Z,W,Y,K,H={}){let X=H.required??$.executionEngine!==void 0;try{let Q=W$($),z=Boolean(Z.trim()||Y?.trim());if(Q&&J.sessionId&&z){let w=await Q.saveMessage(J.sessionId,"assistant",Z,W,K,J.subagentInfo,Y);if(X&&!w)throw Error("Durable assistant-message commit returned no identity");return w}if(X&&J.sessionId&&z)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(u0.warn("[Loop] 保存助手消息失败:",Q),X)throw new j$("assistant_message",{cause:Q})}return null}async function bJ($,J,Z){try{let W=W$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",W6,Z,void 0,J.subagentInfo)}catch(W){u0.warn("[Loop] 保存中断边界失败:",W)}return null}async function AJ($,J,Z,W,Y){try{let K=W$($);if(!K||!J.sessionId||Z.length===0)return null;return await K.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((H)=>({...H})))),triggerPaths:[...W]},J.subagentInfo)}catch(K){u0.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function Y6($,J,Z,W,Y,K={}){try{let H=W$($);if(H&&J.sessionId){let X=await H.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,K.providerToolCallId);if(K.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(K.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(H){if(u0.warn("[Loop] 保存工具调用失败:",H),K.required)throw H}return null}async function D1($,J,Z,W,Y,K,H,X,Q,z={}){try{let w=W$($);if(w&&J.sessionId){let D=await w.saveToolResult(J.sessionId,Z,W,Y,K,H,J.subagentInfo,X,Q);if(z.required&&!D)throw Error("Durable tool-result commit returned no identity");return D}if(z.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(w){if(u0.warn("[Loop] 保存工具结果失败:",w),z.required)throw w}return null}async function v$($,J,Z,W,Y={}){try{let K=W$($);if(K&&J.sessionId){let H=await K.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!H)throw Error("Compaction checkpoint commit returned no identity");return H||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if(u0.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}import{createHash as n2}from"node:crypto";import{promises as s8}from"node:fs";import t8 from"node:path";import{nanoid as c0}from"nanoid";import*as s from"node:fs/promises";import*as Y$ from"node:path";var TJ={enabled:!0,maxIndexLines:200};var u8="memory",EJ="MEMORY.md";class K6{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=w$($);this.memoryDir=Y$.join(W,u8)}this.config={...TJ,...J}}async initialize(){if(this.initialized)return;await s.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=Y$.join(this.memoryDir,EJ);try{let J=await s.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
4
4
  `),Y=Z.slice(0,this.config.maxIndexLines).join(`
@@ -1,4 +1,4 @@
1
- import{f as T,g as W,h as X,i as Y}from"./chunk-rbdd49vr.js";import"./chunk-dktrankr.js";import"./chunk-yvg961q3.js";import"./chunk-2a9rndk2.js";import"./chunk-696t7mzc.js";import"./chunk-nrh7qjat.js";import"./chunk-gayy8vky.js";import"./chunk-6am7zz57.js";import"./chunk-5147jh26.js";import"./chunk-yq2891kc.js";import"./chunk-th4jjfgm.js";import"./chunk-w5jdnsyz.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as R}from"./chunk-te88v4a8.js";import"./chunk-bjqjdw34.js";import{Md as Q}from"./chunk-5kz804w9.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-2kkpn41a.js";import"./chunk-f99n8812.js";import"./chunk-yn51162x.js";import"./chunk-tb363yj8.js";import"./chunk-k5a3n7q5.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-p0gyfy9p.js";import"./chunk-m57w4p91.js";import"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import{jh as M}from"./chunk-amaxww4b.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import m from"chalk";import K from"open";var A=`
1
+ import{f as T,g as W,h as X,i as Y}from"./chunk-y1cv193c.js";import"./chunk-dktrankr.js";import"./chunk-yvg961q3.js";import"./chunk-tqr5w9br.js";import"./chunk-kwykw1mk.js";import"./chunk-b760m6w5.js";import"./chunk-3mm2n48d.js";import"./chunk-3hmvp733.js";import"./chunk-5147jh26.js";import"./chunk-q4adr6y2.js";import"./chunk-th4jjfgm.js";import"./chunk-f1qvcn1z.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as R}from"./chunk-q48ksbhx.js";import"./chunk-bjqjdw34.js";import{Md as Q}from"./chunk-e1dqxg53.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-0f8nn2h1.js";import"./chunk-efemjy9y.js";import"./chunk-yn51162x.js";import"./chunk-tqfp6grc.js";import"./chunk-cw72ydsc.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-ektjpv2v.js";import"./chunk-m57w4p91.js";import"./chunk-a6bg3tyj.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import{jh as M}from"./chunk-1rg4p2v1.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import m from"chalk";import K from"open";var A=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1,2 +1,2 @@
1
- import{gg as F}from"./chunk-nacssmem.js";import{ah as D,bh as E}from"./chunk-ypqp368c.js";import G 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 H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
1
+ import{gg as F}from"./chunk-a6bg3tyj.js";import{ah as D,bh as E}from"./chunk-ypqp368c.js";import G 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 H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
2
  export{H as ke,Q as le,T as me};
@@ -1,2 +1,2 @@
1
- import{Rf as H,Sf as I}from"./chunk-nacssmem.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}}}
1
+ import{Rf as H,Sf as I}from"./chunk-a6bg3tyj.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};
@@ -0,0 +1,6 @@
1
+ import{od as o}from"./chunk-s7jsadnc.js";import{Hd as n}from"./chunk-e1dqxg53.js";import{Hf as Y,If as x,Kf as I,Mf as N,Nf as j,Pf as F,Tf as R,Uf as E,Vf as _,Wf as f,Yf as C,Zf as S,bg as m,gg as d,hg as l}from"./chunk-a6bg3tyj.js";import{ig as V}from"./chunk-h0ft81a3.js";import{kg as X,mg as k,pg as Z}from"./chunk-v0rsz1rt.js";import{ug as Q}from"./chunk-k0pa8874.js";import{Fg as h,Gg as A,Jg as P,Kg as T,Mg as U,Ng as L,Pg as M,Qg as O,yg as y,zg as D}from"./chunk-6pyktfa4.js";import{Xg as u}from"./chunk-98n2rxmq.js";import{promises as s}from"node:fs";import i from"node:path";var t=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],e=new Set([...Object.keys(m),...t]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),$=k.Array(k.String()),v=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:Y,maximum:x})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:P,maximum:T})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:M,maximum:O})),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(V)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:R,maximum:E})),maxQueuedTasks:k.Optional(k.Integer({minimum:_,maximum:f})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:C,maximum:S})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:I,maximum:N})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:j,maximum:F})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional($),ask:k.Optional($),deny:k.Optional($)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),a=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function G(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!e.has(H))throw Error(`Unknown --settings field: ${H}`);let J=X(v,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function c(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return G(B,"inline JSON");let w=i.resolve(Q(),B),J;try{J=await s.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return G(J,w)}function p(q,B){if(!B)return;let w=B;for(let[J,H]of a){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var b=u("General"),yk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Dk=async(q)=>{let B=await c(typeof q.settings==="string"?q.settings:void 0);if(p(q,B),typeof q.agents==="string")o(q.agents);g(q);try{let J=await d.getInstance().initialize(B),H=l(J,q);if(n().config.actions.setConfig(H),q.debug)b.info("[CLI] 配置已加载到 Store")}catch(w){b.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
+ [FAIL] 配置初始化失败
3
+ `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
+ 请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
+ `),process.exit(1)}};function g(q){if(q.continue&&q.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(q.forkSession&&!q.continue&&!q.resume)throw Error("--fork-session requires --resume or --continue");if(q.sessionId&&(q.continue||q.resume)&&!q.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var hk=(q)=>{if(q.jsonSchema&&q.outputSchema)throw Error("--json-schema cannot be combined with --output-schema");if((q.jsonSchema||q.outputSchema)&&!q.print&&!q.headless)throw Error("--json-schema and --output-schema can only be used with --print or --headless");if(q.outputFormat&&q.outputFormat!=="text"&&!q.print&&!q.headless)throw Error("--output-format can only be used with --print or --headless");if(q.headless&&q.outputFormat&&!["text","jsonl"].includes(q.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${q.outputFormat}". Use --print for json|stream-json support.`);if(q.print&&q.outputFormat&&!["text","json","stream-json"].includes(q.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${q.outputFormat}". Use --headless for jsonl support.`);if(q.inputFormat==="stream-json"&&q.print)b.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
+ export{yk as ld,Dk as md,hk as nd};
@@ -1,2 +1,2 @@
1
- import{jh as d,lh as h}from"./chunk-amaxww4b.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{jh as d,lh as h}from"./chunk-1rg4p2v1.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as jd,w as kd};
@@ -1 +1 @@
1
- import{fe as a,ge as b,he as c}from"./chunk-f99n8812.js";import"./chunk-yn51162x.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
1
+ import{fe as a,ge as b,he as c}from"./chunk-efemjy9y.js";import"./chunk-yn51162x.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
@@ -1,4 +1,4 @@
1
- import{j as X4,k as V4}from"./chunk-dktrankr.js";import{l as tO}from"./chunk-yvg961q3.js";import{s as QO,t as g1}from"./chunk-2a9rndk2.js";import{u as a0}from"./chunk-696t7mzc.js";import{A as a$,v as S1,w as l$,x as c$,y as i$,z as $O}from"./chunk-nrh7qjat.js";import{$ as e1,C as w4,F as R1,G as VO,H as A$,I as iO,J as W$,K as E0,L as F$,M as f0,N as TO,Q as IO,R as SO,T as q1,U as k1,V as I1,W as o1,X as n1,Y as t1,Z as s1,_ as r1,aa as O4,ba as $4,ca as x4,fa as G4,ia as y4,na as M4}from"./chunk-gayy8vky.js";import{qa as Q1,wa as U0}from"./chunk-6am7zz57.js";import{Ba as j4,Ca as j$,Da as P1,Ea as f1,Fa as T4,Ga as C4,Ha as T$,Ia as b4,Ja as t0,Ka as K4,La as W4,Ma as F4,Na as y1,Oa as m1,Pa as h1,Qa as u$,Ra as q$,ya as x$}from"./chunk-5147jh26.js";import{ab as m0,bb as g,db as R,eb as E1,pb as K$,yb as o0}from"./chunk-yq2891kc.js";import{Hb as M1}from"./chunk-th4jjfgm.js";import{Ac as C1,Cc as YO,Fc as X$,Kc as b1,Lc as V$,Mc as N$,Nc as E,_b as A1,jc as aO,pc as qO,qc as D$,rc as kO,tc as j1,zc as T1}from"./chunk-w5jdnsyz.js";import{Ld as J0,Pd as G1,Wd as L0}from"./chunk-5kz804w9.js";import{Xd as G$}from"./chunk-0j22w4wh.js";import{je as L1}from"./chunk-yn51162x.js";import{le as cO}from"./chunk-tb363yj8.js";import{Be as MO,Ce as AO,Ge as d4,Je as T0,Ke as jO,Ne as l4,ue as D4,xe as a1}from"./chunk-k5a3n7q5.js";import{Ve as X1,We as w1}from"./chunk-cdy9efgm.js";import{$e as JO,_e as O1}from"./chunk-p0gyfy9p.js";import{Lf as D1,Of as H1,Qf as B1,bg as $1,gg as wO,rf as J1}from"./chunk-nacssmem.js";import{jg as z$}from"./chunk-h0ft81a3.js";import{kg as P,mg as U,pg as F0}from"./chunk-v0rsz1rt.js";import{rg as oO}from"./chunk-xz6y0w4n.js";import{wg as c}from"./chunk-k0pa8874.js";import{Xg as a}from"./chunk-98n2rxmq.js";import{bh as c0}from"./chunk-ypqp368c.js";import{dh as Y1,eh as U1,gh as z1,hh as _1}from"./chunk-t8xmh4w2.js";import{jh as xO}from"./chunk-amaxww4b.js";import{ph as E$}from"./chunk-t2gq918a.js";import{uh as pO,yh as n$}from"./chunk-ppsvzgs5.js";import{Bh as C$}from"./chunk-hcv17986.js";var a5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function o5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as k$,readFileSync as yO}from"node:fs";import{createServer as j5}from"node:http";import{networkInterfaces as T5}from"node:os";import{dirname as C5,extname as b5,join as u0}from"node:path";import{fileURLToPath as R5}from"node:url";import{brotliCompressSync as E5,gzipSync as q5,constants as k5}from"node:zlib";import{Hono as I5}from"hono";import{cors as S5}from"hono/cors";import{WebSocketServer as P5}from"ws";var OO=a("Service"),a4=30000,o4=new Set(["completed","failed","cancelled","interrupted"]);class J${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??u$.getInstance(),this.tickMs=O.tickMs??a4}start(){if(this.timer)return;OO.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!o4.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,OO.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){OO.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),OO.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??n4(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),OO.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let z=Q instanceof Error?Q.message:String(Q);OO.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let Y=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:z,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Q=(await this.store.list()).find((z)=>z.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function n4(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Z0 extends Error{code;statusCode;details;constructor(O,$,x=500,J){super($);this.code=O;this.statusCode=x;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class S extends Z0{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class H extends Z0{constructor(O){super("BAD_REQUEST",O,400)}}class q extends Z0{constructor(O){super("CONFLICT",O,409)}}class k0 extends Z0{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class l0 extends Z0{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class B0 extends Z0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class r extends Z0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var x3=U.Object({error:U.Object({code:U.String(),message:U.String(),details:U.Optional(U.Record(U.String(),U.Unknown()))})});import{Hono as t4}from"hono";var Q$=a("Service"),s4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(F0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function r4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var p$=()=>{let O=new t4;return O.get("/",async($)=>{try{let x=J0();return $.json(x?r4(x):{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),J=P(s4,x);if(!J.success)throw new H("Invalid config update format");let{updates:Q,options:z}=J.data;return await L0().updateConfig(Q,z),$.json({success:!0,updates:Q})}catch(x){throw Q$.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=J0();return $.json(x?.permissions||{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as e4}from"hono";import{streamSSE as O2}from"hono/streaming";function d$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
1
+ import{j as X4,k as V4}from"./chunk-dktrankr.js";import{l as tO}from"./chunk-yvg961q3.js";import{s as QO,t as g1}from"./chunk-tqr5w9br.js";import{u as a0}from"./chunk-kwykw1mk.js";import{A as a$,v as S1,w as l$,x as c$,y as i$,z as $O}from"./chunk-b760m6w5.js";import{$ as e1,C as w4,F as R1,G as VO,H as A$,I as iO,J as W$,K as E0,L as F$,M as f0,N as TO,Q as IO,R as SO,T as q1,U as k1,V as I1,W as o1,X as n1,Y as t1,Z as s1,_ as r1,aa as O4,ba as $4,ca as x4,fa as G4,ia as y4,na as M4}from"./chunk-3mm2n48d.js";import{qa as Q1,wa as U0}from"./chunk-3hmvp733.js";import{Ba as j4,Ca as j$,Da as P1,Ea as f1,Fa as T4,Ga as C4,Ha as T$,Ia as b4,Ja as t0,Ka as K4,La as W4,Ma as F4,Na as y1,Oa as m1,Pa as h1,Qa as u$,Ra as q$,ya as x$}from"./chunk-5147jh26.js";import{ab as m0,bb as g,db as R,eb as E1,pb as K$,yb as o0}from"./chunk-q4adr6y2.js";import{Hb as M1}from"./chunk-th4jjfgm.js";import{Ac as C1,Cc as YO,Fc as X$,Kc as b1,Lc as V$,Mc as N$,Nc as E,_b as A1,jc as aO,pc as qO,qc as D$,rc as kO,tc as j1,zc as T1}from"./chunk-f1qvcn1z.js";import{Ld as J0,Pd as G1,Wd as L0}from"./chunk-e1dqxg53.js";import{Xd as G$}from"./chunk-0j22w4wh.js";import{je as L1}from"./chunk-yn51162x.js";import{le as cO}from"./chunk-tqfp6grc.js";import{Be as MO,Ce as AO,Ge as d4,Je as T0,Ke as jO,Ne as l4,ue as D4,xe as a1}from"./chunk-cw72ydsc.js";import{Ve as X1,We as w1}from"./chunk-cdy9efgm.js";import{$e as JO,_e as O1}from"./chunk-ektjpv2v.js";import{Lf as D1,Of as H1,Qf as B1,bg as $1,gg as wO,rf as J1}from"./chunk-a6bg3tyj.js";import{jg as z$}from"./chunk-h0ft81a3.js";import{kg as P,mg as U,pg as F0}from"./chunk-v0rsz1rt.js";import{rg as oO}from"./chunk-xz6y0w4n.js";import{wg as c}from"./chunk-k0pa8874.js";import{Xg as a}from"./chunk-98n2rxmq.js";import{bh as c0}from"./chunk-ypqp368c.js";import{dh as Y1,eh as U1,gh as z1,hh as _1}from"./chunk-t8xmh4w2.js";import{jh as xO}from"./chunk-1rg4p2v1.js";import{ph as E$}from"./chunk-t2gq918a.js";import{uh as pO,yh as n$}from"./chunk-ppsvzgs5.js";import{Bh as C$}from"./chunk-hcv17986.js";var a5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function o5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as k$,readFileSync as yO}from"node:fs";import{createServer as j5}from"node:http";import{networkInterfaces as T5}from"node:os";import{dirname as C5,extname as b5,join as u0}from"node:path";import{fileURLToPath as R5}from"node:url";import{brotliCompressSync as E5,gzipSync as q5,constants as k5}from"node:zlib";import{Hono as I5}from"hono";import{cors as S5}from"hono/cors";import{WebSocketServer as P5}from"ws";var OO=a("Service"),a4=30000,o4=new Set(["completed","failed","cancelled","interrupted"]);class J${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??u$.getInstance(),this.tickMs=O.tickMs??a4}start(){if(this.timer)return;OO.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!o4.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,OO.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){OO.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),OO.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??n4(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),OO.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let z=Q instanceof Error?Q.message:String(Q);OO.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let Y=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:z,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Q=(await this.store.list()).find((z)=>z.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function n4(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Z0 extends Error{code;statusCode;details;constructor(O,$,x=500,J){super($);this.code=O;this.statusCode=x;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class S extends Z0{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class H extends Z0{constructor(O){super("BAD_REQUEST",O,400)}}class q extends Z0{constructor(O){super("CONFLICT",O,409)}}class k0 extends Z0{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class l0 extends Z0{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class B0 extends Z0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class r extends Z0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var x3=U.Object({error:U.Object({code:U.String(),message:U.String(),details:U.Optional(U.Record(U.String(),U.Unknown()))})});import{Hono as t4}from"hono";var Q$=a("Service"),s4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(F0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function r4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var p$=()=>{let O=new t4;return O.get("/",async($)=>{try{let x=J0();return $.json(x?r4(x):{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),J=P(s4,x);if(!J.success)throw new H("Invalid config update format");let{updates:Q,options:z}=J.data;return await L0().updateConfig(Q,z),$.json({success:!0,updates:Q})}catch(x){throw Q$.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=J0();return $.json(x?.permissions||{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as e4}from"hono";import{streamSSE as O2}from"hono/streaming";function d$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)$+=`event: ${O.event}
3
3
  `;for(let x of O.data.split(/\r\n|\r|\n/))$+=`data: ${x}
4
4
  `;if(O.retry!==void 0)$+=`retry: ${O.retry}
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-f2xng5g1.js";import"./chunk-1rg4p2v1.js";import"./chunk-hcv17986.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.67",
3
+ "version": "0.10.68",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1,5 +0,0 @@
1
- import{Ag as e_,Bg as vf,Cg as Ff,Dg as n_,Eg as jf,Gg as Bf,Ig as Jf,Jg as Af,Kg as Sf,Lg as Wf,Ng as Cf,Og as $f,Qg as K}from"./chunk-6pyktfa4.js";import{Xg as a}from"./chunk-98n2rxmq.js";import{$g as T_,bh as sf}from"./chunk-ypqp368c.js";import{eh as m_}from"./chunk-t8xmh4w2.js";var SE={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},ef=(f)=>SE[f]||{};var CE=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Nf(f){return typeof f==="string"&&CE.has(f)}function Ut(f){if(!f.aborted)return;if(Nf(f.reason))return f.reason;return"user-cancel"}function Ot(f){if(Nf(f))return!0;if(!(f instanceof Error))return!1;if(f.name==="AbortError")return!0;if(f instanceof DOMException&&f.name==="AbortError")return!0;if(f.message.includes("aborted"))return!0;return!1}function nf(...f){let _=f.filter(Boolean);if(_.length===0)return new AbortController().signal;if(_.length===1)return _[0];let E=AbortSignal;if(typeof E.any==="function")return E.any(_);for(let h of _)if(h.aborted)return h;let t=new AbortController,T=new Map;for(let h of _){let S=()=>{t.abort(h.reason);for(let[A,x]of T)A.removeEventListener("abort",x)};T.set(h,S)}for(let[h,S]of T)h.addEventListener("abort",S,{once:!0});return t.signal}function d(f,_,E){let t=E?.throwOnAbort??!1;if(_?.aborted){if(t)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((T,h)=>{let S,A=setTimeout(()=>{if(_&&S)_.removeEventListener("abort",S);T()},f);if(_)S=()=>{if(clearTimeout(A),t)h(new DOMException("Aborted","AbortError"));else T()},_.addEventListener("abort",S,{once:!0})})}var PE=a("Chat"),uE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Of(f){if(typeof f==="string")return f;return f.filter((_)=>_.type==="text").map((_)=>_.text).join(`
2
- `)}function DE(f){if(!f)return{};try{let _=JSON.parse(f);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return PE.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function bE(f){let _=f.match(/^data:([^;,]+);base64,(.+)$/s);return _?{mimeType:_[1],data:_[2]}:void 0}async function HE(f,_){let E=bE(f);if(E)return{type:"image",...E};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let t=await fetch(f,{signal:_});if(!t.ok)throw Error(`Failed to load image ${f}: HTTP ${t.status}`);return{type:"image",mimeType:t.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await t.arrayBuffer()).toString("base64")}}async function __(f,_,E,t,T){let h=f.filter((x)=>x.role==="system").map((x)=>Of(x.content)).filter(Boolean).join(`
3
-
4
- `),S=[];for(let x of f){if(x.role==="system")continue;if(x.role==="user"){let C=_.input.includes("image"),c=typeof x.content==="string"?x.content:await Promise.all(x.content.map((R)=>R.type==="text"?Promise.resolve({type:"text",text:R.text}):C?HE(R.image_url.url,t):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));S.push({role:"user",content:c,timestamp:Date.now()});continue}if(x.role==="assistant"){let C=[];if(x.reasoningContent?.trim())C.push({type:"thinking",thinking:x.reasoningContent});let c=Of(x.content);if(c)C.push({type:"text",text:c});for(let R of x.tool_calls??[]){if(!("function"in R))continue;C.push({type:"toolCall",id:R.id,name:R.function.name,arguments:DE(R.function.arguments)})}S.push({role:"assistant",content:C,api:_.api,provider:_.provider,model:_.id,usage:uE,stopReason:x.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}S.push({role:"toolResult",toolCallId:x.tool_call_id??"",toolName:x.name??"unknown",content:[{type:"text",text:Of(x.content)}],isError:!1,timestamp:Date.now()})}let A=E?.filter((x)=>!T||x.name===T).map((x)=>({name:x.name,description:x.description,parameters:x.parameters,constrainedSampling:x.constrainedSampling})).sort((x,C)=>x.name<C.name?-1:x.name>C.name?1:0);return{...h?{systemPrompt:h}:{},messages:S,...A?.length?{tools:A}:{}}}function E_(f){let _=[];for(let E=0;E<f.length;E++){let t=f[E];if(t.role==="tool")continue;let T=t.role==="assistant"&&t.tool_calls?.length?t.tool_calls:void 0;if(!T){_.push(t);continue}let h=[],S=E+1;while(S<f.length&&f[S].role==="tool")h.push(f[S++]);let A=new Set(T.map((c)=>c.id)),x=h.filter((c)=>c.tool_call_id&&A.has(c.tool_call_id)),C=new Set(x.map((c)=>c.tool_call_id));if(A.size===T.length&&x.length===A.size&&C.size===A.size)_.push(t,...x);E=S-1}return _}function t_(f){return f.some((_)=>_.role==="assistant"&&Boolean(_.tool_calls?.length)&&!_.reasoningContent?.trim())}function h_(f,_){return{...f,..._.baseUrl?{baseUrl:T_(f.api,_.baseUrl)}:{},..._.maxOutputTokens?{maxTokens:_.maxOutputTokens}:{}}}function kf(f){let _=f.modelCatalog??sf();return{models:_.models,model:h_(_.getModel(f.provider,f.model),f)}}function x_(f,_){let E=f.modelCatalog??sf();return h_(E.getModel(_.provider,_.model),f)}import{createHash as UE}from"node:crypto";var YE=32,NE=1000,OE=512,sE=2000,kE=0.1,VE=0.05,jE=0.9,BE=300000,XE=3600000;class Vf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let _=f.now??Date.now(),E=zE(f,_),t=this.sessions.get(f.sessionId);if(E.callCount=(t?.callCount??0)+1,this.touch(f.sessionId,E),t&&E.contextEpoch!==t.contextEpoch)return;if(!t||t.cacheReadTokens<NE)return;let T=t.cacheReadTokens-E.cacheReadTokens,h=Math.min(sE,Math.max(OE,t.cacheReadTokens*kE));if(T<h||E.cacheReadTokens>=t.cacheReadTokens*(1-VE))return;let S=E.modelIdentity!==t.modelIdentity,A=E.systemHash!==t.systemHash,x=E.toolsHash!==t.toolsHash,C=E.policyHash!==t.policyHash;if(!(S||A||x||C)&&E.promptTokens<t.promptTokens*jE)return;let R=Math.max(0,_-t.recordedAt),u=t.retention==="long"?XE:BE,H=S?"model_changed":A?"system_prompt_changed":x?"tools_changed":C?"request_policy_changed":R>=u?"ttl_expired":"server_side",X=IE(t,E);return{reason:H,previousCacheReadTokens:t.cacheReadTokens,cacheReadTokens:E.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:T,elapsedMs:R,callNumber:E.callCount,systemPromptChanged:A,systemCharDelta:E.systemChars-t.systemChars,toolsChanged:x,addedToolCount:X.added,removedToolCount:X.removed,changedToolCount:X.changed,modelChanged:S,requestPolicyChanged:C}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,_){this.sessions.delete(f),this.sessions.set(f,_);while(this.sessions.size>YE){let E=this.sessions.keys().next().value;if(E===void 0)break;this.sessions.delete(E)}}}function zE(f,_){let E=[...f.tools??f.context.tools??[]].map((t)=>({identityHash:e(t.name),contractHash:e(n(t))})).sort((t,T)=>t.identityHash<T.identityHash?-1:t.identityHash>T.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:e(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:e(n(E)),toolFingerprints:E,policyHash:e(n(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:_,callCount:1}}function IE(f,_){let E=new Map(f.toolFingerprints.map((T)=>[T.identityHash,T.contractHash])),t=new Map(_.toolFingerprints.map((T)=>[T.identityHash,T.contractHash]));return{added:[...t.keys()].filter((T)=>!E.has(T)).length,removed:[...E.keys()].filter((T)=>!t.has(T)).length,changed:[...t].filter(([T,h])=>E.has(T)&&E.get(T)!==h).length}}function n(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(n).join(",")}]`;let _=f;return`{${Object.keys(_).sort().map((E)=>`${JSON.stringify(E)}:${n(_[E])}`).join(",")}}`}function e(f){return UE("sha256").update(f).digest("hex")}import{randomBytes as LE}from"node:crypto";import{createHmac as JE}from"node:crypto";function WE(f){try{let _=new URL(f);if(_.hash="",_.hostname=_.hostname.toLowerCase(),_.searchParams.sort(),_.pathname!=="/")_.pathname=_.pathname.replace(/\/+$/,"");return _.toString()}catch{return f.trim().replace(/\/+$/,"")}}function $E(f){if(!f)return[];return Object.entries(f).map(([_,E])=>[_.trim().toLowerCase(),E.trim()]).sort(([_],[E])=>_.localeCompare(E))}function cf(f,_,E){let t=JSON.stringify([f.provider.trim(),String(f.api).trim(),WE(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",$E(f.customHeaders),E]);return JE("sha256",Buffer.from(_)).update(t).digest("hex")}var GE=60000,ZE=4,KE=0.8;var Mf=300000,Xf=600000;var c_=128,R_=256,QE=1800000,Rf=50;class ff extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function zf(f){return f instanceof ff||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function m(f,_){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:_}function oE(f,_){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:_}function vE(f,_){return cf(f,_,{providerCircuitOpenDurationMs:f.openDurationMs})}function i(f){let _=0;for(let E of f)if(E.failure)_++;return _}function M_(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function A_(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Bf)}class C_{#h=new Map;#R=new WeakMap;#f;#_;#t;#E;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):LE(32),this.#_=f.now??(()=>performance.now()),this.#t=f.wallNow??f.now??Date.now,this.#E={maxEntries:Math.min(m(f.maxEntries,c_),c_),maxWindowEntries:Math.min(m(f.maxWindowEntries,R_),R_),windowMs:m(f.windowMs,GE),minSamples:m(f.minSamples,ZE),errorRateThreshold:oE(f.errorRateThreshold,KE),idleTtlMs:m(f.idleTtlMs,QE)}}get size(){return this.#h.size}get(f){if(f.openDurationMs===0)return this.#x();let _=this.#_();this.#U(_);let E=vE(f,this.#f),t=this.#h.get(E);if(t)return t.lastTouchedAt=_,this.#T(t,f.probeLeaseMs);if(this.#h.size>=this.#E.maxEntries)this.#O();if(this.#h.size>=this.#E.maxEntries)return this.#x();let T={key:E,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:_,detached:!1};return this.#h.set(E,T),this.#T(T,f.probeLeaseMs)}#T(f,_){let E=this,t=Math.max(Mf,Math.min(m(_,Mf),Xf));return{preflight:()=>E.#C(f),check:()=>E.#P(f,t),recordSuccess:(T)=>E.#b(T,"success"),recordFailure:(T,h)=>E.#b(T,"failure",h),recordNeutral:(T)=>E.#b(T,"neutral"),abandon:(T)=>E.#N(T),snapshot:()=>E.#Y(f)}}#x(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let _=Object.freeze({kind:"noop"});return f.#R.set(_,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:_}},recordSuccess:(_)=>f.#c(_),recordFailure:(_)=>f.#c(_),recordNeutral:(_)=>f.#c(_),abandon:(_)=>f.#N(_),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#c(f){let _=this.#R.get(f);if(_?.kind==="noop")_.settled=!0;return}#C(f){let _=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=_,this.#H(f,_),f.state==="closed")return{eligible:!0};if(f.state==="open"){let t=f.nextProbeAt??_;return _<t?this.#M(f,t-_):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return{eligible:!0};let E=Math.max(1,(f.probeLeaseExpiresAt??_+Rf)-_);return this.#M(f,Math.min(Rf,E))}#M(f,_){let{allowed:E,...t}=this.#D(f,_);return{eligible:!1,...t}}#P(f,_){let E=this.#_();if(f.detached)return this.#x().check();if(f.lastTouchedAt=E,this.#H(f,E),f.state==="closed")return this.#A(f,"regular");if(f.state==="open"){let T=f.nextProbeAt??E;if(E<T)return this.#D(f,T-E);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return this.#u(f,E,_);let t=Math.max(1,(f.probeLeaseExpiresAt??E+Rf)-E);return this.#D(f,Math.min(Rf,t))}#A(f,_,E){let t=Object.freeze({kind:_});return this.#R.set(t,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:_,...E!==void 0?{probeLeaseId:E}:{},settled:!1}),{allowed:!0,probe:_==="probe",token:t}}#u(f,_,E){let t=f.nextProbeLeaseId++;f.probeLeaseId=t,f.probeLeaseExpiresAt=_+E,f.lastTouchedAt=_;let T=this.#A(f,"probe",t),h=f.lastFailure??{reason:"server_error"};return{...T,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:i(f.samples)}}#D(f,_){let E=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(_)),nextProbeAt:this.#t()+Math.max(0,Math.ceil(_)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:i(f.samples)}}#b(f,_,E){let t=this.#R.get(f);if(!t||t.settled)return;if(t.settled=!0,t.kind==="noop"||!t.entry)return;let T=t.entry;if(T.detached||t.generation!==T.generation||t.kind==="regular"&&T.state!=="closed"||t.kind==="probe"&&(T.state!=="half_open"||t.probeLeaseId!==T.probeLeaseId))return;let h=this.#_();if(T.lastTouchedAt=h,t.kind==="probe"){if(_==="failure"&&E)return this.#S(T,E,h,"reopened");return this.#k(T)}if(_==="neutral")return;if(this.#V(T,_==="failure",h),_!=="failure"||!E)return;let S=i(T.samples),A=T.samples.length===0?0:S/T.samples.length;if(T.samples.length>=this.#E.minSamples&&A>=this.#E.errorRateThreshold)return this.#S(T,E,h,"opened");return}#S(f,_,E,t){let T={reason:_.reason,...M_(_.statusCode)!==void 0?{statusCode:M_(_.statusCode)}:{},...A_(_.retryAfterMs)!==void 0?{retryAfterMs:A_(_.retryAfterMs)}:{}},h=T.retryAfterMs??0,S=Math.max(f.configuredOpenDurationMs,h);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=S,f.nextProbeAt=E+S,f.lastFailure=T,{phase:t,reason:T.reason,...T.statusCode!==void 0?{statusCode:T.statusCode}:{},retryAfterMs:S,nextProbeAt:this.#t()+S,openDurationMs:S,sampleCount:f.samples.length,failureCount:i(f.samples)}}#k(f){let _=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#N(f){let _=this.#R.get(f);if(!_||_.settled)return!1;if(_.settled=!0,_.kind==="noop")return!0;let E=_.entry;if(!E||E.detached||_.kind!=="probe"||_.generation!==E.generation||_.probeLeaseId!==E.probeLeaseId)return!1;return E.probeLeaseId=void 0,E.probeLeaseExpiresAt=void 0,E.lastTouchedAt=this.#_(),!0}#V(f,_,E){if(this.#H(f,E),f.samples.length>=this.#E.maxWindowEntries)f.samples.shift();f.samples.push({at:E,failure:_})}#H(f,_){let E=_-this.#E.windowMs,t=0;while(t<f.samples.length&&f.samples[t].at<E)t++;if(t>0)f.samples.splice(0,t)}#Y(f){if(!f.detached)this.#H(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:i(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#U(f){for(let[_,E]of this.#h)if(E.state==="closed"&&f-E.lastTouchedAt>this.#E.idleTtlMs)this.#s(_,E)}#O(){let f;for(let _ of this.#h.values())if(_.state==="closed"&&(!f||_.lastTouchedAt<f.lastTouchedAt))f=_;if(f)this.#s(f.key,f)}#s(f,_){_.detached=!0,this.#h.delete(f)}}var S_;function P_(){return S_??=new C_,S_}import{randomBytes as FE}from"node:crypto";var u_=16,D_=128,b_=32,H_=3,U_=16,Y_=96,N_=24,O_=12,s_=16,k_=4,V_=4,j_=67108864,B_=33554432,X_=12,z_=2,I_=2,J_=1,G_=15000,W_=30000;class _f extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,_,E,t,T,h,S,A){super(f==="queue_full"?`Provider request admission ${_} ${t} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${_} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=_;this.requestClass=E;this.resource=t;this.inFlight=T;this.limit=h;this.queued=S;this.maxWaitMs=A;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function Ef(f){return f instanceof _f||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function j(f,_,E){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return _;return Math.min(f,E)}function pE(f){let _=j(f.globalMaxInFlight,u_,u_),E=j(f.globalMaxPending,D_,D_),t=j(f.domainMaxPending,b_,b_),T=Math.min(j(f.ownerMaxInFlight,H_,H_),_),h=Math.min(j(f.ownerMaxPending,U_,U_),E),S=Math.min(j(f.nonForegroundGlobalMaxPending,Math.min(Y_,Math.max(1,Math.floor(E*3/4))),Y_),E),A=Math.min(j(f.nonForegroundDomainMaxPending,Math.min(N_,Math.max(1,Math.floor(t*3/4))),N_),t),x=Math.min(j(f.nonForegroundOwnerMaxPending,Math.min(O_,Math.max(1,Math.floor(h*3/4))),O_),h),C=Math.min(j(f.internalGlobalMaxPending,Math.min(s_,Math.max(1,Math.floor(E/8))),s_),S),c=Math.min(j(f.internalDomainMaxPending,Math.min(k_,Math.max(1,Math.floor(t/8))),k_),A),R=Math.min(j(f.internalOwnerMaxPending,Math.min(V_,Math.max(1,Math.floor(h/4))),V_),x),u=j(f.globalMaxPendingBytes,K,K),H=Math.min(j(f.domainMaxPendingBytes,j_,j_),u),X=Math.min(j(f.ownerMaxPendingBytes,B_,B_),u),W=Math.min(j(f.nonForegroundGlobalMaxInFlight,Math.min(X_,_),X_),_),$=Math.min(j(f.nonForegroundOwnerMaxInFlight,Math.min(z_,T),z_),T),Z=Math.min(j(f.internalGlobalMaxInFlight,Math.min(I_,_),I_),_),uf=j(f.internalDomainMaxInFlight,J_,J_),tf=j(f.agingMs,W_,W_);return{globalMaxInFlight:_,globalMaxPending:E,domainMaxPending:t,ownerMaxInFlight:T,ownerMaxPending:h,nonForegroundGlobalMaxPending:S,nonForegroundDomainMaxPending:A,nonForegroundOwnerMaxPending:x,internalGlobalMaxPending:C,internalDomainMaxPending:c,internalOwnerMaxPending:R,globalMaxPendingBytes:u,domainMaxPendingBytes:H,ownerMaxPendingBytes:X,nonForegroundGlobalMaxInFlight:W,nonForegroundOwnerMaxInFlight:$,internalGlobalMaxInFlight:Z,internalDomainMaxInFlight:uf,agingMs:tf}}function $_(f,_){if(!f.trim())throw Error(`${_} must not be blank`)}function aE(f){if($_(f.sessionId,"sessionId"),$_(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<Af||f.scope.maxConcurrent>Sf)throw Error(`maxConcurrent must be between ${Af} and ${Sf}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>K)throw Error(`maxPendingBytes must be between 1 and ${K}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>K+1)throw Error(`pendingBytes must be between 1 and ${K+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Cf)throw Error(`maxWaitMs must be 0-${Cf}`)}function If(f,_){if(_!==void 0)return _;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function mE(f,_){return cf(f,_,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class Z_{#h;#R;#f;#_=[];#t=new Map;#E=new Map;#T=0;#x=0;#c=0;#C=0;#M=0;#P=0;#A=0;#u=0;#D=1;#b=0;#S=!1;constructor(f={}){this.#h=f.processSecret?new Uint8Array(f.processSecret):FE(32),this.#R=f.now??(()=>performance.now()),this.#f=pE(f)}admit(f){if(aE(f),this.#S)throw this.#X("closed",f,{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw If(f.signal);let _=mE(f.scope,this.#h),E=this.#t.get(_),t=this.#E.get(f.ownerId),T=E??this.#V(f.scope.maxConcurrent),h=t??this.#H();if(this.#_.length===0&&this.#Y(T,h,f.requestClass)){if(!E)this.#t.set(_,T);if(!t)this.#E.set(f.ownerId,h),this.#D++;let u=this.#O(_,f.ownerId,f.requestClass),H=this.#Q(f,0);return{ready:Promise.resolve(u),getSnapshot:()=>({...H}),cancel:()=>{H={...H}}}}let S=this.#k(f,T,h);if(S)throw this.#X("queue_full",f,S,this.#_.length);let A=this.#U(T,h,f.requestClass);if(f.maxWaitMs===0)throw this.#X("wait_timeout",f,A,this.#_.length);if(!E)this.#t.set(_,T);if(!t)this.#E.set(f.ownerId,h),this.#D++;let x,C,c=new Promise((u,H)=>{x=u,C=H});c.catch(()=>{return});let R={domainKey:_,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#R(),signal:f.signal,resolve:x,reject:C,settled:!1,admitted:!1};if(f.signal)R.abortListener=()=>this.#z(R,If(f.signal)),f.signal.addEventListener("abort",R.abortListener,{once:!0});return R.timer=setTimeout(()=>this.#L(R),f.maxWaitMs),R.timer.unref?.(),this.#_.push(R),this.#N(T,h,R),this.#j(),{ready:c,getSnapshot:()=>this.#K(R),cancel:(u)=>this.#z(R,If(f.signal,u))}}close(){if(this.#S)return;this.#S=!0;for(let f of[...this.#_]){let _=this.#t.get(f.domainKey),E=this.#E.get(f.ownerId),t=_&&E?this.#U(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};this.#B(f,new _f("closed",t.scope,f.requestClass,t.resource,t.inFlight,t.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:this.#T,queued:this.#_.length,pendingBytes:this.#P,nonForegroundInFlight:this.#x,internalInFlight:this.#c,nonForegroundQueued:this.#C,internalQueued:this.#M,nonForegroundPendingBytes:this.#A,internalPendingBytes:this.#u,domainCount:this.#t.size,ownerCount:this.#E.size,closed:this.#S}}#k(f,_,E){let t=(c,R,u)=>R>=u?{scope:c,resource:"pending_count",inFlight:R,limit:u}:void 0;if(f.requestClass==="internal"){let c=t("class",this.#M,this.#f.internalGlobalMaxPending)??t("class",E.internalQueued,this.#f.internalOwnerMaxPending)??t("class",_.internalQueued,this.#f.internalDomainMaxPending);if(c)return c}if(f.requestClass!=="foreground"){let c=t("class",this.#C,this.#f.nonForegroundGlobalMaxPending)??t("class",E.nonForegroundQueued,this.#f.nonForegroundOwnerMaxPending)??t("class",_.nonForegroundQueued,this.#f.nonForegroundDomainMaxPending);if(c)return c}let T=t("global",this.#_.length,this.#f.globalMaxPending)??t("owner",E.queued,this.#f.ownerMaxPending)??t("domain",_.queued,this.#f.domainMaxPending);if(T)return T;let h=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),S=Math.min(h,this.#f.domainMaxPendingBytes),A=Math.min(h,this.#f.ownerMaxPendingBytes),x=(c,R)=>f.pendingBytes>R-c,C=(c)=>{if(c==="owner")return{scope:c,resource:"pending_bytes",inFlight:E.inFlight,limit:this.#f.ownerMaxInFlight};if(c==="domain")return{scope:c,resource:"pending_bytes",inFlight:_.inFlight,limit:_.maxConcurrent};return{scope:c,resource:"pending_bytes",inFlight:this.#T,limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let c=Math.max(1,Math.floor(h/8)),R=Math.max(1,Math.floor(S/4)),u=Math.max(1,Math.floor(A/4));if(x(this.#u,c)||x(E.internalPendingBytes,u)||x(_.internalPendingBytes,R))return C("class")}if(f.requestClass!=="foreground"){let c=Math.max(1,Math.floor(h*3/4)),R=Math.max(1,Math.floor(S*3/4)),u=Math.max(1,Math.floor(A/2));if(x(this.#A,c)||x(E.nonForegroundPendingBytes,u)||x(_.nonForegroundPendingBytes,R))return C("class")}if(x(this.#P,h))return C("global");if(x(E.pendingBytes,A))return C("owner");if(x(_.pendingBytes,S))return C("domain");return}#N(f,_,E){if(f.queued++,_.queued++,this.#P+=E.pendingBytes,f.pendingBytes+=E.pendingBytes,_.pendingBytes+=E.pendingBytes,E.requestClass!=="foreground")this.#C++,f.nonForegroundQueued++,_.nonForegroundQueued++,this.#A+=E.pendingBytes,f.nonForegroundPendingBytes+=E.pendingBytes,_.nonForegroundPendingBytes+=E.pendingBytes;if(E.requestClass==="internal")this.#M++,f.internalQueued++,_.internalQueued++,this.#u+=E.pendingBytes,f.internalPendingBytes+=E.pendingBytes,_.internalPendingBytes+=E.pendingBytes}#V(f){return{maxConcurrent:f,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#H(){return{order:this.#D,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#Y(f,_,E){if(this.#T>=this.#f.globalMaxInFlight)return!1;if(f.inFlight>=f.maxConcurrent)return!1;if(_.inFlight>=this.#f.ownerMaxInFlight)return!1;if(E==="foreground")return!0;if(this.#x>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(_.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let t=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=t)return!1;if(E!=="internal")return!0;return this.#c<this.#f.internalGlobalMaxInFlight&&f.internalInFlight<this.#f.internalDomainMaxInFlight}#U(f,_,E){if(_.inFlight>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:_.inFlight,limit:this.#f.ownerMaxInFlight};if(E!=="foreground"&&_.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:_.nonForegroundInFlight,limit:this.#f.nonForegroundOwnerMaxInFlight};if(f.inFlight>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent};if(E!=="foreground"){let t=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=t)return{scope:"class",resource:"stream",inFlight:f.nonForegroundInFlight,limit:t}}if(E==="internal"&&f.internalInFlight>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.internalInFlight,limit:this.#f.internalDomainMaxInFlight};if(this.#T>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};if(E!=="foreground"&&this.#x>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#x,limit:this.#f.nonForegroundGlobalMaxInFlight};if(E==="internal"&&this.#c>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#c,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent}}#O(f,_,E){let t=this.#t.get(f),T=this.#E.get(_);if(!t||!T)throw Error("Provider admission accounting state is unavailable");if(this.#T++,t.inFlight++,T.inFlight++,E!=="foreground")this.#x++,t.nonForegroundInFlight++,T.nonForegroundInFlight++;if(E==="internal")this.#c++,t.internalInFlight++,T.internalInFlight++;let h=!1;return{release:()=>{if(h)return;h=!0,this.#s(f,_,E)}}}#s(f,_,E){let t=this.#t.get(f),T=this.#E.get(_);if(this.#T=Math.max(0,this.#T-1),t)t.inFlight=Math.max(0,t.inFlight-1);if(T)T.inFlight=Math.max(0,T.inFlight-1);if(E!=="foreground"){if(this.#x=Math.max(0,this.#x-1),t)t.nonForegroundInFlight=Math.max(0,t.nonForegroundInFlight-1);if(T)T.nonForegroundInFlight=Math.max(0,T.nonForegroundInFlight-1)}if(E==="internal"){if(this.#c=Math.max(0,this.#c-1),t)t.internalInFlight=Math.max(0,t.internalInFlight-1);if(T)T.internalInFlight=Math.max(0,T.internalInFlight-1)}this.#J(f,_),this.#j()}#j(){if(this.#S)return;while(this.#_.length>0){let f=this.#R(),_=new Map;for(let[A,x]of this.#_.entries()){let C=this.#t.get(x.domainKey),c=this.#E.get(x.ownerId);if(C===void 0||c===void 0||!this.#Y(C,c,x.requestClass))continue;let R=this.#W(x,f),u=_.get(x.ownerId);if(!u||R<u.rank||R===u.rank&&A<u.index)_.set(x.ownerId,{pending:x,rank:R,index:A})}let E=[..._.values()].filter(({pending:A})=>{let x=this.#t.get(A.domainKey),C=this.#E.get(A.ownerId);return x!==void 0&&C!==void 0&&this.#Y(x,C,A.requestClass)}).map(({pending:A,rank:x})=>({pending:A,rank:x,order:this.#E.get(A.ownerId).order}));if(E.length===0)return;let t=Math.min(...E.map((A)=>A.rank)),T=E.filter((A)=>A.rank===t),S=T.filter((A)=>A.order>this.#b).sort((A,x)=>A.order-x.order)[0]??T.sort((A,x)=>A.order-x.order)[0];this.#$(S.pending,S.order)}}#W(f,_){let E=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,t=Math.floor(Math.max(0,_-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,E-t)}#$(f,_){if(!this.#I(f,!1))return;f.settled=!0,f.admitted=!0,this.#b=_;let E=this.#O(f.domainKey,f.ownerId,f.requestClass);f.permit=E,f.resolve(E)}#L(f){let _=this.#t.get(f.domainKey),E=this.#E.get(f.ownerId),t=_&&E?this.#U(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};this.#B(f,new _f("wait_timeout",t.scope,f.requestClass,t.resource,t.inFlight,t.limit,this.#_.length,f.maxWaitMs))}#z(f,_){this.#B(f,_)}#B(f,_){if(!this.#I(f))return;f.settled=!0,f.reject(_),this.#j()}#I(f,_=!0){if(f.settled||f.admitted)return!1;let E=this.#_.indexOf(f);if(E<0)return!1;this.#_.splice(E,1);let t=this.#t.get(f.domainKey),T=this.#E.get(f.ownerId);if(t&&T)this.#G(t,T,f);if(this.#Z(f),_)this.#J(f.domainKey,f.ownerId);return!0}#G(f,_,E){if(f.queued=Math.max(0,f.queued-1),_.queued=Math.max(0,_.queued-1),this.#P=Math.max(0,this.#P-E.pendingBytes),f.pendingBytes=Math.max(0,f.pendingBytes-E.pendingBytes),_.pendingBytes=Math.max(0,_.pendingBytes-E.pendingBytes),E.requestClass!=="foreground")this.#C=Math.max(0,this.#C-1),f.nonForegroundQueued=Math.max(0,f.nonForegroundQueued-1),_.nonForegroundQueued=Math.max(0,_.nonForegroundQueued-1),this.#A=Math.max(0,this.#A-E.pendingBytes),f.nonForegroundPendingBytes=Math.max(0,f.nonForegroundPendingBytes-E.pendingBytes),_.nonForegroundPendingBytes=Math.max(0,_.nonForegroundPendingBytes-E.pendingBytes);if(E.requestClass==="internal")this.#M=Math.max(0,this.#M-1),f.internalQueued=Math.max(0,f.internalQueued-1),_.internalQueued=Math.max(0,_.internalQueued-1),this.#u=Math.max(0,this.#u-E.pendingBytes),f.internalPendingBytes=Math.max(0,f.internalPendingBytes-E.pendingBytes),_.internalPendingBytes=Math.max(0,_.internalPendingBytes-E.pendingBytes)}#Z(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#J(f,_){let E=this.#t.get(f);if(E&&E.inFlight===0&&E.queued===0)this.#t.delete(f);let t=this.#E.get(_);if(t&&t.inFlight===0&&t.queued===0)this.#E.delete(_)}#K(f){let _=Math.max(0,Math.floor(this.#R()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#T,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs};let E=this.#t.get(f.domainKey),t=this.#E.get(f.ownerId),T=E&&t?this.#U(E,t,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:T.resource,scope:T.scope,reason:"capacity",queuePosition:this.#o(f,T.scope),queueDepth:this.#_.length,inFlight:T.inFlight,limit:T.limit,waitMs:_,maxWaitMs:f.maxWaitMs}}#Q(f,_){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#T,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs}}#o(f,_){let E=this.#_.filter((t)=>{switch(_){case"owner":return t.ownerId===f.ownerId;case"domain":return t.domainKey===f.domainKey;case"class":return t.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,E.indexOf(f)+1)}#X(f,_,E,t){return new _f(f,E.scope,_.requestClass,E.resource,E.inFlight,E.limit,t,_.maxWaitMs)}}var L_;function K_(){return L_??=new Z_,L_}function Q_(f,_={}){let E=_.maxBytes??134217728,t=_.maxNodes??1e5;if(!Number.isSafeInteger(E)||E<=0||E>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(t)||t<=0)throw Error("maxNodes must be a positive safe integer");let T=new WeakSet,h=0,S=0,A=!1,x=(c)=>{if(A||c<=0)return;if(!Number.isSafeInteger(c)||c>E-h){h=E+1,A=!0;return}h+=c},C=(c)=>{if(A)return;if(S+=1,S>t){x(E+1);return}if(c===null){x(4);return}switch(typeof c){case"string":x(Buffer.byteLength(c,"utf8"));return;case"number":case"bigint":x(8);return;case"boolean":x(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(T.has(c))return;if(T.add(c),ArrayBuffer.isView(c)){x(32+c.byteLength);return}if(c instanceof ArrayBuffer){x(32+c.byteLength);return}if(c instanceof Date){x(40);return}if(c instanceof RegExp){x(32+Buffer.byteLength(c.source,"utf8"));return}if(c instanceof Map){x(32);for(let[R,u]of c)if(C(R),C(u),A)return;return}if(c instanceof Set){x(32);for(let R of c)if(C(R),A)return;return}if(c instanceof WeakMap||c instanceof WeakSet){x(32);return}if(Array.isArray(c)){x(16);for(let R of c)if(C(R),A)return;return}x(32);for(let R of Reflect.ownKeys(c)){if(typeof R!=="string")continue;let u=Object.getOwnPropertyDescriptor(c,R);if(!u?.enumerable||!("value"in u))continue;if(x(8+Buffer.byteLength(R,"utf8")),C(u.value),A)return}};return C(f),h}function o_(f){return Q_([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:K})}var v_=new WeakSet;class w extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,_){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=_;this.name="ProviderRecoveryBudgetExceededError"}}class Lf extends Error{timeoutMs;code="PROVIDER_REQUEST_DEADLINE_EXCEEDED";constructor(f){super(`Provider request deadline exceeded after ${f}ms`);this.timeoutMs=f;this.name="ProviderRequestDeadlineExceededError"}}var wE=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],qE=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],lE=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function F_(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function yE(f){let _=F_(f);return qE.some((E)=>_.includes(E))}function Gf(f){if(f!==null&&typeof f==="object")v_.add(f)}function _T(f){return f!==null&&typeof f==="object"&&v_.has(f)}function gE(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function rE(f){if(f===null||typeof f!=="object")return;let _=f;for(let E of["status","statusCode"]){let t=_[E];if(typeof t==="number"&&Number.isInteger(t))return t}return}function dE(f){let _=f.match(/^(?:error:\s*)?(\d{3})\b/),E=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),t=Number(_?.[1]??E?.[1]);return Number.isInteger(t)?t:void 0}function q(f,_){let E=F_(f),t=gE(f);if(t==="STREAM_IDLE_TIMEOUT"||t==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||E.includes("request aborted")||E==="aborted")return{retryable:!1};if(wE.some((h)=>E.includes(h))||yE(f))return{retryable:!1};if(_?.shouldRetry==="false")return{retryable:!1,statusCode:_.statusCode};if(t==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let T=_?.statusCode??rE(f)??dE(E);if(_?.shouldRetry==="true")return{retryable:!0,reason:T===429?"rate_limit":T===408||T===409?"timeout":"server_error",statusCode:T};if(T===429)return{retryable:!0,reason:"rate_limit",statusCode:T};if(T===408||T===409)return{retryable:!0,reason:"timeout",statusCode:T};if(T!==void 0&&T>=500&&T<=599)return{retryable:!0,reason:"server_error",statusCode:T};if(t==="PROVIDER_STREAM_CLOSED"||E.includes("stream closed before completion")||E.includes("ended without")||E.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:T};if(lE.some((h)=>E.includes(h)))return{retryable:!0,reason:"transport",statusCode:T};if(E.includes("timeout")||E.includes("timed out")||E.includes("temporarily unavailable")||E.includes("upstream_error")||E.includes("overloaded")||E.includes("rate limit")||E.includes("too many requests")||E.includes("service unavailable")||E.includes("server error")||E.includes("internal error")||E.includes("please retry")||E.includes("try your request again"))return{retryable:!0,reason:E.includes("rate")||E.includes("too many")?"rate_limit":E.includes("timeout")||E.includes("timed out")?"timeout":"server_error",statusCode:T};return{retryable:!1,statusCode:T}}function Zf(f,_){if(!f)return;if(f.retryAfterMs!==void 0){let T=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(T))return Math.max(0,T)}if(f.retryAfter===void 0)return;let E=Number.parseFloat(f.retryAfter);if(Number.isFinite(E))return Math.max(0,E*1000);let t=Date.parse(f.retryAfter);return Number.isFinite(t)?Math.max(0,t-_):void 0}function p_(f,_,E={}){let t=E.now??Date.now(),T=E.maxDelayMs??60000,h=Zf(_,t);if(h!==void 0)return Math.min(Math.ceil(h),T);let S=Math.max(0,f-1),A=E.maxExponentialDelayMs??8000,x=Math.min(500*2**S,A),C=Math.max(0,Math.min(1,E.random??Math.random())),c=x*(0.75+C*0.25);return Math.min(Math.round(c),T)}function w_(f,_){let E=f.onPayload;f.onPayload=async(t,T)=>{let h=E?await E(t,T):t;return _(h===void 0?t:h,T)}}function eE(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function Kf(f,_,E){if(!f.enablePromptCaching)return"none";if(E&&_.api==="openai-completions"&&!_.baseUrl.includes("api.openai.com"))return"long";return"short"}function nE(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function iE(f,_,E,t){let T=t?void 0:eE(E);if(!T){if(_.api==="anthropic-messages")f.thinkingEnabled=!1;if(_.api==="google-generative-ai"||_.api==="google-vertex")f.thinking={enabled:!1};return}switch(_.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=T;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:nE(T)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=T;break;default:f.reasoningEffort=T}}function ft(f,_,E){if(!E)return;switch(_){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:E};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:E}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:E};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function _t(f,_,E){let t=E.serviceTier;if(!t)return;if(_.api==="openai-responses"||_.api==="openai-codex-responses"||_.api==="azure-openai-responses"){f.serviceTier=t;return}if(_.api!=="openai-completions"&&!(_.api==="anthropic-messages"&&t==="fast"))return;w_(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;return _.api==="anthropic-messages"?{...T,speed:"fast"}:{...T,service_tier:t}})}function Et(f,_,E){let t=E.responseVerbosity;if(!t)return;if(m_(_,t),_.api==="openai-codex-responses"){f.textVerbosity=t;return}w_(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;if(_.api==="openai-completions")return{...T,verbosity:t};let h="text"in T&&T.text&&typeof T.text==="object"&&!Array.isArray(T.text)?T.text:{};return{...T,text:{...h,verbosity:t}}})}function q_(f,_,E,t,T=!1){let h={apiKey:f.apiKey,headers:f.customHeaders,signal:E,temperature:t?.temperature??f.temperature??0,maxTokens:t?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:Kf(f,_,t?.providerSessionId),sessionId:t?.providerSessionId};if(iE(h,_,f,T),ft(h,_.api,t?.toolChoice?.toolName),_t(h,_,f),Et(h,_,f),_.api==="azure-openai-responses")h.azureBaseUrl=f.baseUrl,h.azureApiVersion=f.apiVersion,h.azureDeploymentName=_.id;return h}function a_(f,_){let E=_.get("x-should-retry");return{statusCode:f,..._.get("retry-after")!==null?{retryAfter:_.get("retry-after")??void 0}:{},..._.get("retry-after-ms")!==null?{retryAfterMs:_.get("retry-after-ms")??void 0}:{},...E==="true"||E==="false"?{shouldRetry:E}:{}}}var tt=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function l_(f,_,E){let t=f.onResponse;if(f.onResponse=async(h,S)=>{let A=new Headers(h.headers);E(a_(h.status,A)),await t?.(h,S)},!tt.has(_.api)||typeof globalThis.fetch!=="function")return;let T=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(h,S)=>{let A=await T(h,S);return E(a_(A.status,A.headers)),A}}function y_(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Pf=300000,Tt=30000;class g_ extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(f){super(`Provider stream idle timeout after ${f}ms without an event`);this.timeoutMs=f;this.name="StreamIdleTimeoutError"}}class r_ extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function Qf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function ht(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Pf}function xt(f,_){if(_===0)return;let E=_!==void 0&&_>0?_:Tt;return Math.max(1,Math.min(E,Math.floor(f/2)))}function ct(f,_,E){if(E?.aborted)return Promise.reject(Qf(E));return new Promise((t,T)=>{let h=!1,S=()=>{clearTimeout(c),E?.removeEventListener("abort",C)},A=(R)=>{if(h)return;h=!0,S(),t(R)},x=(R)=>{if(h)return;h=!0,S(),T(R instanceof Error?R:Error(String(R)))},C=()=>{if(E)x(Qf(E))},c=setTimeout(()=>A({kind:"timer"}),Math.max(0,_));if(E?.addEventListener("abort",C,{once:!0}),E?.aborted){C();return}f.then((R)=>A({kind:"next",result:R}),x)})}async function*Rt(f,_,E){let t=ht(_),T=xt(t,_.stallWarningMs);if(_.signal?.aborted)throw Qf(_.signal);let h=Date.now(),S=Promise.resolve().then(()=>f.next()),A;for(;;){let C=await ct(S,(A?t:T??t)-(Date.now()-h),_.signal);if(C.kind==="next"){if(A)yield{...A,phase:"recovered",durationMs:Math.max(A.durationMs,Date.now()-h)};return C.result}if(!A&&T!==void 0){E.stallCount++,A={phase:"detected",stallCount:E.stallCount,durationMs:T,warningAfterMs:T,timeoutMs:t,outputStarted:E.outputStarted},yield A;continue}let c=new g_(t);throw _.abort?.(c),c}}async function*d_(f,_,E,t,T={}){let S=f.stream(_,E,t)[Symbol.asyncIterator](),A=0,x=!1,C={stallCount:0,outputStarted:!1};try{while(!0){let c=Rt(S,T,C),R=await c.next();while(!R.done)yield{providerStall:R.value},R=await c.next();let u=R.value;if(u.done)throw new r_;let H=u.value;switch(H.type){case"text_delta":C.outputStarted=!0,yield{content:H.delta};break;case"thinking_delta":C.outputStarted=!0,yield{reasoningContent:H.delta};break;case"toolcall_end":C.outputStarted=!0,yield{toolCalls:[{index:A++,id:H.toolCall.id,type:"function",function:{name:H.toolCall.name,arguments:JSON.stringify(H.toolCall.arguments)}}]};break;case"done":x=!0,yield{finishReason:H.reason,usage:y_(H.message.usage)};return;case"error":throw Error(H.error.errorMessage??`Request ${H.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!x)Promise.resolve(S.return?.()).catch(()=>{return})}}var of=a("Chat"),Mt=1;function At(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((_)=>_.type==="image_url"))}function St(f){let E=f.findLast((t)=>{let T=t.metadata;return T!==null&&typeof T==="object"&&!Array.isArray(T)&&T.isCompactSummary===!0})?.metadata;return E!==null&&typeof E==="object"&&!Array.isArray(E)&&typeof E.parentId==="string"?E.parentId:""}function Ct(f,_){let E=q(f,_);if(!E.retryable||!E.reason)return;let t=E.statusCode;switch(E.reason){case"rate_limit":if(t!==429)return;break;case"server_error":if(t===void 0||t<500||t>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let T=Zf(_,Date.now());return{reason:E.reason,...t!==void 0?{statusCode:t}:{},...T!==void 0?{retryAfterMs:T}:{}}}function Pt(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class pf{config;models;model;promptCacheBreakMonitor=new Vf;admissionFallbackOwnerId=`pi-service-${process.pid}-${Mt++}`;constructor(f){let _=kf(f);this.config={...f,maxContextTokens:_.model.contextWindow,maxOutputTokens:f.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,of.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,_,E,t){let T="",h="",S=[],A,x;for await(let C of this.streamChat(f,_,E,t)){T+=C.content??"",h+=C.reasoningContent??"";for(let c of C.toolCalls??[])if(c.id&&c.type==="function"&&c.function?.name)S.push(c);A=C.usage??A,x=C.finishReason??x}return{content:T,...h?{reasoningContent:h}:{},...S.length>0?{toolCalls:S}:{},usage:A,finishReason:x}}async*streamChat(f,_,E,t){let T=t?.toolChoice?.toolName;if(T&&!_?.some((M)=>M.name===T))throw Error(`Required tool is unavailable: ${T}`);let h=E_(f);if(h.some((M)=>At(M))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let S=Boolean(T)||t_(h),A=await __(h,this.model,_,E,T),x=(M,P)=>{let k=t?.providerSessionId;if(!k||!M.usage)return M;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(k),M;let D=Kf(this.config,P,k),N=this.promptCacheBreakMonitor.observe({sessionId:k,modelIdentity:`${P.provider}\x00${P.api}\x00${P.id}`,context:A,retention:D,contextEpoch:St(h),policy:{baseUrl:P.baseUrl??this.config.baseUrl??"",retention:D,requiredTool:T??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:t?.temperature??this.config.temperature??0,maxOutputTokens:t?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:M.usage});if(!N)return M;return of.warn("[PiAIChatService] Prompt cache break detected",{reason:N.reason,previousCacheReadTokens:N.previousCacheReadTokens,cacheReadTokens:N.cacheReadTokens,tokenDrop:N.tokenDrop,callNumber:N.callNumber}),{...M,usage:{...M.usage,promptCacheBreak:N}}},C=o_({messages:h,context:A,tools:_,requestOptions:t}),c=t?.providerRecovery;if(c&&!n_(c.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let R=c?.mode==="bounded_foreground"&&c.budgetMs>0?{budgetMs:c.budgetMs,startedAt:void 0}:void 0,u=R?"bounded_foreground":"standard",H=this.config.maxRetries??2,X=this.config.maxRetries??(R?e_:2),W=R!==void 0&&this.config.maxRetries===void 0,$=0,Z,uf=this.config.providerCircuitRegistry??P_(),tf=this.config.providerCircuitBreakerOpenMs??jf,i_=Math.max(Mf,Math.min(this.config.streamIdleTimeout??Pf,Xf)),fE=this.config.providerRequestAdmissionScheduler??K_(),_E=this.config.providerRequestConcurrency??Jf,af=this.config.providerRequestAdmissionMs??Wf,EE=this.config.providerRequestPendingBytes??$f,Df=t?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},tE=(M)=>uf.get({provider:M.provider,api:M.api,baseUrl:M.baseUrl??this.config.baseUrl??"",model:M.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,openDurationMs:tf,probeLeaseMs:i_}),TE=(M)=>({provider:M.provider,api:M.api,baseUrl:M.baseUrl??this.config.baseUrl??"",model:M.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,maxConcurrent:_E,maxPendingBytes:EE}),s=(M=Date.now())=>{if(!R)return;let P=R.startedAt===void 0?0:Math.min(R.budgetMs,Math.max(0,M-R.startedAt));return{recoveryBudgetMs:R.budgetMs,recoveryElapsedMs:P,recoveryRemainingMs:Math.max(0,R.budgetMs-P)}},Q=()=>({mode:u,...s()??{}}),mf=()=>{if(R&&R.startedAt===void 0)R.startedAt=Date.now()},o=()=>{let M=s();return new w(R?.budgetMs??0,M?.recoveryElapsedMs??0)},l=()=>!W||$<X+1,bf=(M,P)=>{let{state:k,...D}=P;return{phase:M,...D,...s()?{recoveryRemainingMs:s()?.recoveryRemainingMs}:{}}},wf=(M)=>({phase:"rejected",requestClass:M.requestClass,resource:M.resource,scope:M.scope,reason:M.reason,queuePosition:0,queueDepth:Math.max(0,M.queued),inFlight:Math.max(0,M.inFlight),limit:Math.max(0,M.limit),waitMs:M.reason==="wait_timeout"?M.maxWaitMs:0,maxWaitMs:M.maxWaitMs,...s()?{recoveryRemainingMs:s()?.recoveryRemainingMs}:{}}),hE=async function*(M){let P=s()?.recoveryRemainingMs,k=P!==void 0&&R?.startedAt!==void 0?Math.min(af,P):af,D;try{D=fE.admit({scope:TE(M),sessionId:Df.sessionId,ownerId:Df.ownerId,requestClass:Df.requestClass,maxWaitMs:k,pendingBytes:C,signal:E})}catch(U){if(Ef(U)){if(U.reason==="wait_timeout"&&R?.startedAt!==void 0&&(s()?.recoveryRemainingMs??0)<=0)throw o();yield{providerAdmission:wf(U)}}throw U}let N=D.getSnapshot();if(N.state==="admitted")return await D.ready;yield{providerAdmission:bf("queued",N)};let G=D.ready.then((U)=>({kind:"ready",permit:U}),(U)=>({kind:"error",error:U}));while(!0){let U=D.getSnapshot(),Y=Math.max(1,Math.min(G_,Math.max(1,k-U.waitMs))),B,V=new Promise((v)=>{B=setTimeout(()=>v({kind:"heartbeat"}),Y),B.unref?.()}),I=await Promise.race([G,V]);if(B)clearTimeout(B);if(I.kind==="heartbeat"){yield{providerAdmission:bf("queued",D.getSnapshot())};continue}if(I.kind==="error"){if(Ef(I.error)){if(I.error.reason==="wait_timeout"&&R?.startedAt!==void 0&&(s()?.recoveryRemainingMs??0)<=0)throw o();yield{providerAdmission:wf(I.error)}}throw I.error}return yield{providerAdmission:bf("admitted",D.getSnapshot())},I.permit}},xE=(M)=>{if(!l())throw o();if(W)$++;Z=void 0;let P=new AbortController,k=E?nf(E,P.signal):P.signal,D=typeof this.config.timeout==="number"&&Number.isFinite(this.config.timeout)&&this.config.timeout>0?Math.max(1,Math.floor(this.config.timeout)):void 0,N;if(R?.startedAt!==void 0){let Y=s()?.recoveryRemainingMs??0;if(Y<=0)throw o();N={remainingMs:Y,error:new w(R.budgetMs,R.budgetMs)}}let G=q_(this.config,M,k,t,S);l_(G,M,(Y)=>{Z=Y});let U=d_(this.models,M,A,G,{idleTimeoutMs:this.config.streamIdleTimeout??Pf,signal:k,abort:(Y)=>P.abort(Y)});return async function*(){let Y,B;try{if(D!==void 0&&(N===void 0||D<N.remainingMs)){let V=new Lf(D);Y=setTimeout(()=>P.abort(V),D),Y.unref?.()}if(N){let V=N;B=setTimeout(()=>P.abort(V.error),V.remainingMs),B.unref?.()}yield*U}finally{if(Y)clearTimeout(Y);if(B)clearTimeout(B)}}()},qf=this,p=(M)=>({phase:M.phase,reason:M.reason,...M.statusCode!==void 0?{statusCode:M.statusCode}:{},...M.retryAfterMs!==void 0?{retryAfterMs:M.retryAfterMs}:{},...M.nextProbeAt!==void 0?{nextProbeAt:M.nextProbeAt}:{},openDurationMs:M.openDurationMs,sampleCount:M.sampleCount,failureCount:M.failureCount,...s()?{recoveryRemainingMs:s()?.recoveryRemainingMs}:{}}),lf=(M,P)=>({phase:M,reason:P.reason,...P.statusCode!==void 0?{statusCode:P.statusCode}:{},retryAfterMs:P.retryAfterMs,...P.nextProbeAt!==void 0?{nextProbeAt:P.nextProbeAt}:{},openDurationMs:P.openDurationMs,sampleCount:P.sampleCount,failureCount:P.failureCount,...s()?{recoveryRemainingMs:s()?.recoveryRemainingMs}:{}}),cE=(M)=>({phase:"probe",reason:M.reason??"server_error",...M.statusCode!==void 0?{statusCode:M.statusCode}:{},openDurationMs:M.openDurationMs??tf,...M.sampleCount!==void 0?{sampleCount:M.sampleCount}:{},...M.failureCount!==void 0?{failureCount:M.failureCount}:{},...s()?{recoveryRemainingMs:s()?.recoveryRemainingMs}:{}}),Hf=(M,P,k)=>({providerRetry:{phase:"exhausted",attempt:M,maxRetries:X,reason:P,...k!==void 0?{statusCode:k}:{},...Q(),exhaustedBy:"recovery_budget"}}),yf=async function*(M,P,k,D){let N,G=!1,U,Y,B=tE(M);for(let V=0;V<=k;V++){if(!l())break;let I,v;while(!I){let b=B.preflight();while(!b.eligible){if(U=b.reason,Y=b.statusCode,!R||!D){let L=lf("rejected",b);throw yield{providerCircuit:L},new ff(L)}mf();let O=s()?.recoveryRemainingMs??0;if(O<=0){let L=o();throw yield Hf(W?Math.max(0,$-1):V,b.reason,b.statusCode),L}yield{providerCircuit:lf("waiting",b)};let F=Math.min(Math.max(1,b.retryAfterMs),vf,O);if(await d(F,E,{throwOnAbort:!0}),(s()?.recoveryRemainingMs??0)<=0){let L=o();throw yield Hf(W?Math.max(0,$-1):V,b.reason,b.statusCode),L}b=B.preflight()}try{v=yield*hE(M)}catch(J){if(J instanceof w)yield Hf(W?Math.max(0,$-1):V,U??"timeout",Y);throw J}let z=B.check();if(z.allowed)I=z;else v.release(),v=void 0}let y=I.token;if(I.probe)yield{providerCircuit:cE(I)};try{let b=!1,z=!1;for await(let J of xE(M)){if(J.providerStall){yield J;continue}let O=W?$-1:V;if(O>0&&U&&!b)b=!0,yield{providerRetry:{phase:"recovered",attempt:O,maxRetries:X,reason:U,...Y!==void 0?{statusCode:Y}:{},...Q()}};if(!z){z=!0;let F=B.recordSuccess(y);if(F)yield{providerCircuit:p(F)}}G=!0,P(),yield x(J,M)}if(!z){let J=B.recordSuccess(y);if(J)yield{providerCircuit:p(J)}}return}catch(b){if(v?.release(),N=b,qf.logIdleTimeout(b,G,M),await qf.handleAbort(E),b instanceof w){if(G)throw Gf(b),b;throw yield{providerRetry:{phase:"exhausted",attempt:W?Math.max(0,$-1):V,maxRetries:X,reason:U??"timeout",...Y!==void 0?{statusCode:Y}:{},...Q(),exhaustedBy:"recovery_budget"}},b}let z=q(b,Z);if(G)throw Gf(b),b;let J=Ct(b,Z),O=J?B.recordFailure(y,J):Z&&!Pt(b)?B.recordNeutral(y):void 0;if(O)yield{providerCircuit:p(O)};if(!z.retryable||!z.reason){if(V>0&&U)yield{providerRetry:{phase:"exhausted",attempt:W?Math.max(0,$-1):V,maxRetries:X,reason:U,...Y!==void 0?{statusCode:Y}:{},...Q()}};throw b}U=z.reason,Y=z.statusCode;let F=V<k&&l();if(O&&O.phase!=="closed"&&F&&(!R||!D)){let L={...p(O),phase:"rejected"};throw yield{providerCircuit:L},new ff(L)}if(F){mf();let L=W?$:V+1,ME=p_(L,Z,R?{maxDelayMs:Ff,maxExponentialDelayMs:Ff}:void 0),rf=O&&O.phase!=="closed"?O.retryAfterMs??0:0;if(R&&rf>0&&O)yield{providerCircuit:{...p(O),phase:"waiting"}};let AE=s(),Yf=Math.max(ME,rf),g=R?Math.min(Yf,AE?.recoveryRemainingMs??Yf):Yf,hf={attempt:L,maxRetries:X,reason:z.reason,...z.statusCode!==void 0?{statusCode:z.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...hf,delayMs:g,nextRetryAt:Date.now()+g,...Q()}},R){let r=g;while(r>0){let df=Math.min(r,vf);if(await d(df,E,{throwOnAbort:!0}),r-=df,(s()?.recoveryRemainingMs??0)<=0){let xf=o();throw yield{providerRetry:{phase:"exhausted",...hf,...Q(),exhaustedBy:"recovery_budget"}},xf}if(r>0){if(O&&O.phase!=="closed"&&O.nextProbeAt!==void 0){let xf=Math.max(0,O.nextProbeAt-Date.now());if(xf>0)yield{providerCircuit:{...p(O),phase:"waiting",retryAfterMs:xf}}}yield{providerRetry:{phase:"waiting",...hf,delayMs:g,nextRetryAt:Date.now()+r,...Q()}}}}}else await d(g,E,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...hf,...Q()}}}else yield{providerRetry:{phase:"exhausted",attempt:W?Math.max(0,$-1):V,maxRetries:X,reason:z.reason,...z.statusCode!==void 0?{statusCode:z.statusCode}:{},...Q(),...R&&(D||!l())?{exhaustedBy:"attempt_limit"}:{}}}}finally{B.abandon(y),v?.release()}}throw N},Uf,gf=!1,Tf=this.config.fallbackModels??[],RE=R&&Tf.length>0?Math.min(H,X):X;try{for await(let M of yf(this.model,()=>{gf=!0},RE,Tf.length===0))yield M;return}catch(M){if(Uf=M,gf||!Ef(M)&&!zf(M)&&!q(M,Z).retryable)throw M}for(let[M,P]of Tf.entries()){if(!l())break;yield{modelFallback:!0};let k=!1;try{let D=x_(this.config,P),N=M===Tf.length-1,G=R&&!N?Math.min(H,X):X;for await(let U of yf(D,()=>{k=!0},G,N))yield U;return}catch(D){if(Uf=D,k||!Ef(D)&&!zf(D)&&!q(D,Z).retryable)throw D}}throw Uf}async handleAbort(f){if(f?.aborted)await d(0,f,{throwOnAbort:!0})}logIdleTimeout(f,_,E){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;of.warn("[PiAIChatService] Provider stream idle timeout",{provider:E.provider,model:E.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:_})}getConfig(){return{...this.config}}updateConfig(f){let _={...this.config,...f},E=kf(_);this.config={..._,maxContextTokens:E.model.contextWindow,maxOutputTokens:_.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model}}var ut=a("Service");async function jT(f){let _=f;if(_.provider){let E=ef(_.provider);if(Object.keys(E).length>0)_={..._,customHeaders:{...E,..._.customHeaders}},ut.debug(`Injected ${_.provider} specific headers:`,Object.keys(E))}return Dt(_)}function Dt(f){return new pf(f)}
5
- export{Ut as Yd,Ot as Zd,nf as _d,Ef as $d,Q_ as ae,yE as be,_T as ce,pf as de,jT as ee};