blade-code 0.10.42 → 0.10.44

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 (105) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-dx7xefys.js → chunk-0qsssahq.js} +1 -1
  3. package/dist/{chunk-xkg84094.js → chunk-1vydfzvy.js} +2 -2
  4. package/dist/{chunk-ecw74d2s.js → chunk-26wse17p.js} +2 -2
  5. package/dist/{chunk-3xx2ebr7.js → chunk-2eddqgnh.js} +1 -1
  6. package/dist/{chunk-hypq4t4z.js → chunk-2yvte5a7.js} +1 -1
  7. package/dist/chunk-3nfse1ps.js +1 -0
  8. package/dist/chunk-3y784b9c.js +1 -0
  9. package/dist/{chunk-7gjb405q.js → chunk-50a5xx45.js} +1 -1
  10. package/dist/{chunk-1yjzj2d0.js → chunk-56qew7w0.js} +2 -2
  11. package/dist/{chunk-jz2gkqdt.js → chunk-583kv07t.js} +7 -7
  12. package/dist/chunk-619q1w65.js +1 -0
  13. package/dist/{chunk-qb49rm5q.js → chunk-63p5mj97.js} +1 -1
  14. package/dist/chunk-6cx4t8r6.js +1 -0
  15. package/dist/{chunk-mt7fn8cv.js → chunk-706zda55.js} +3 -3
  16. package/dist/{chunk-d2fce0vk.js → chunk-74hcqcn7.js} +2 -2
  17. package/dist/{chunk-kfv4mdcm.js → chunk-7fqsgdee.js} +2 -2
  18. package/dist/{chunk-5zr3w30g.js → chunk-7sna3js9.js} +1 -1
  19. package/dist/chunk-7z5t63ke.js +10 -0
  20. package/dist/chunk-86tba7p4.js +1 -0
  21. package/dist/{chunk-020hgyg7.js → chunk-8vtyatd6.js} +1 -1
  22. package/dist/chunk-99nka030.js +1 -0
  23. package/dist/{chunk-f90ybvrs.js → chunk-9rrced3b.js} +1 -1
  24. package/dist/chunk-a68fws4p.js +1 -0
  25. package/dist/chunk-agbyfdvw.js +1 -0
  26. package/dist/{chunk-sw3p1ygn.js → chunk-aw7w91f0.js} +68 -68
  27. package/dist/{chunk-0qf7h4n2.js → chunk-bvf9syb2.js} +2 -2
  28. package/dist/{chunk-dr4et3gj.js → chunk-c9s4n31b.js} +1 -1
  29. package/dist/{chunk-q6n6rqzs.js → chunk-cf2541w5.js} +2 -2
  30. package/dist/{chunk-4rmdfme3.js → chunk-ckqj0pxz.js} +1 -1
  31. package/dist/{chunk-f542fh7g.js → chunk-cxzx7j0p.js} +1 -1
  32. package/dist/chunk-d18mw6d1.js +2 -0
  33. package/dist/{chunk-1e9866ye.js → chunk-egczvfsv.js} +2 -2
  34. package/dist/{chunk-anwm8rp3.js → chunk-f4sp074f.js} +1 -1
  35. package/dist/chunk-fer18bbe.js +1 -0
  36. package/dist/{chunk-t2mc97k7.js → chunk-fhnkyqfb.js} +2 -2
  37. package/dist/chunk-fk0q25dp.js +8 -0
  38. package/dist/{chunk-3v2sgvzt.js → chunk-fk4wbmv6.js} +2 -2
  39. package/dist/{chunk-wm944thh.js → chunk-g96t2yrz.js} +22 -22
  40. package/dist/{chunk-pm9kt54d.js → chunk-hcm55r3d.js} +1 -1
  41. package/dist/{chunk-m8s208g3.js → chunk-hfrcwkc8.js} +1 -1
  42. package/dist/{chunk-yqxyy3w2.js → chunk-j0k3mbkd.js} +2 -2
  43. package/dist/chunk-j7edwwg1.js +2 -0
  44. package/dist/{chunk-jv9zg1fw.js → chunk-kfpzrmq7.js} +1 -1
  45. package/dist/{chunk-8csfb83y.js → chunk-m1b6v1zn.js} +2 -2
  46. package/dist/{chunk-18wnstzp.js → chunk-m8ss9rmx.js} +1 -1
  47. package/dist/{chunk-te95z52n.js → chunk-mrsc4a55.js} +1 -1
  48. package/dist/{chunk-fye8eghq.js → chunk-mzq3ps9j.js} +2 -2
  49. package/dist/chunk-n4ywszmn.js +6 -0
  50. package/dist/chunk-p4egmgt6.js +2 -0
  51. package/dist/chunk-pk9peyzp.js +1 -0
  52. package/dist/{chunk-mpymjr7j.js → chunk-q78s028m.js} +1 -1
  53. package/dist/{chunk-m3dvta6k.js → chunk-qb0sqh29.js} +2 -2
  54. package/dist/{chunk-0jsy9eav.js → chunk-qp2z1r7y.js} +1 -1
  55. package/dist/chunk-qzd9d0p8.js +22 -0
  56. package/dist/{chunk-mp637mb6.js → chunk-r085zhqr.js} +2 -2
  57. package/dist/{chunk-1whfdz08.js → chunk-s4denzh4.js} +1 -1
  58. package/dist/{chunk-6d0hphtd.js → chunk-sqd5ge5s.js} +1 -1
  59. package/dist/{chunk-brwdd5kp.js → chunk-svj24r6g.js} +2 -2
  60. package/dist/{chunk-jf6mkx0j.js → chunk-synjj8b3.js} +1 -1
  61. package/dist/chunk-t33njg4e.js +1 -0
  62. package/dist/{chunk-vc32qrmq.js → chunk-tpa75y39.js} +1 -1
  63. package/dist/chunk-tzp486wc.js +1 -0
  64. package/dist/{chunk-y75y911b.js → chunk-v9tzhe90.js} +2 -2
  65. package/dist/{chunk-ex21hxqf.js → chunk-vx5tjahq.js} +1 -1
  66. package/dist/chunk-wr2rkg9t.js +1 -0
  67. package/dist/{chunk-7pmpm5yq.js → chunk-wwvb6znp.js} +1 -1
  68. package/dist/chunk-wx5nj2s2.js +44 -0
  69. package/dist/{chunk-8b2bpfnt.js → chunk-x3cyg9pe.js} +3 -3
  70. package/dist/chunk-y6tkxqjx.js +2 -0
  71. package/dist/{chunk-4k37vmxh.js → chunk-yk9pxkc1.js} +1 -1
  72. package/dist/chunk-z1aqe7ms.js +1 -0
  73. package/dist/{chunk-z60w7p8a.js → chunk-z9absgab.js} +1 -1
  74. package/dist/web/assets/{ChatView-DBgMoUrW.js → ChatView-CyxiCTbL.js} +3 -3
  75. package/dist/web/assets/{CodeBlockHighlighter-DLFQUVD6.js → CodeBlockHighlighter-Bb3gIeQv.js} +1 -1
  76. package/dist/web/assets/{FilePreview--1qHdJP_.js → FilePreview-BXg9VaTv.js} +1 -1
  77. package/dist/web/assets/{MarkdownRenderer-DcVHyjtl.js → MarkdownRenderer-vxpqGt4L.js} +3 -3
  78. package/dist/web/assets/{SettingsModal-BM6SPUXW.js → SettingsModal-4L1nPkh0.js} +1 -1
  79. package/dist/web/assets/{TaskSwitcher-B5VYY_QG.js → TaskSwitcher-DKSqTLK1.js} +1 -1
  80. package/dist/web/assets/{TerminalPanel-XWA1jGs8.js → TerminalPanel-Bv9PDclr.js} +1 -1
  81. package/dist/web/assets/{index-B8y5_J0i.js → index-Bz4W1-8a.js} +3 -3
  82. package/dist/web/index.html +1 -1
  83. package/package.json +1 -1
  84. package/dist/chunk-5hbm5e24.js +0 -44
  85. package/dist/chunk-74sxsd1h.js +0 -1
  86. package/dist/chunk-78jy2kby.js +0 -1
  87. package/dist/chunk-7qd6xqjs.js +0 -1
  88. package/dist/chunk-8wg7g98v.js +0 -10
  89. package/dist/chunk-c53hc8ze.js +0 -1
  90. package/dist/chunk-dgs04r04.js +0 -2
  91. package/dist/chunk-h9fkttf1.js +0 -2
  92. package/dist/chunk-hkmgrdxc.js +0 -1
  93. package/dist/chunk-katrmbxc.js +0 -1
  94. package/dist/chunk-m4ya7qqd.js +0 -1
  95. package/dist/chunk-n6c6k87j.js +0 -1
  96. package/dist/chunk-ppxn94za.js +0 -1
  97. package/dist/chunk-rf7hdke7.js +0 -1
  98. package/dist/chunk-rjjjgcw4.js +0 -1
  99. package/dist/chunk-vsaqjbm2.js +0 -6
  100. package/dist/chunk-wcxsm922.js +0 -2
  101. package/dist/chunk-wn23bvs0.js +0 -1
  102. package/dist/chunk-wtczk025.js +0 -22
  103. package/dist/chunk-yatvtpft.js +0 -1
  104. package/dist/chunk-za6zyd82.js +0 -8
  105. package/dist/chunk-zhrc510s.js +0 -1
@@ -1,3 +1,3 @@
1
- import{Ng as y}from"./chunk-mpymjr7j.js";import{Wg as b}from"./chunk-m3dvta6k.js";import{createHash as N}from"node:crypto";import{constants as v,promises as d}from"node:fs";import W from"node:os";import a from"node:path";import{Mutex as A}from"async-mutex";import O from"write-file-atomic";var w=1,x=65536,T=1048576,m=100;function p(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function k(e,t=2048){return e.length<=t?e:`${e.slice(0,t-1)}…`}function S(e){if(typeof e!=="string"||!e.trim())return;try{let t=new URL(e);return k(`${t.origin}${t.pathname}`)}catch{return k(e)}}function D(e){return Array.isArray(e)?e.filter((t)=>typeof t==="string"):[]}function R(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.type==="string"?r.type:"unknown",n=typeof r.command==="string"?r.command:void 0,o=D(r.args),c=i==="stdio"?k([n,...o].filter(Boolean).join(" ")):S(r.url);return{kind:"mcp",name:`${t} (${i})`,...c?{target:c}:{}}})}function F(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.command==="string"?k(r.command):void 0,n=p(r.extensionToLanguage)?Object.keys(r.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${t} (${n})`,...i?{target:i}:{}}})}function j(e){if(!Array.isArray(e))return[];return e.slice(0,m).flatMap((t)=>{if(!p(t))return[];let s=typeof t.id==="string"?t.id:"unnamed",r=typeof t.provider==="string"?t.provider:"unknown",i=typeof t.model==="string"?t.model:"unknown",n=p(t.overrides)?t.overrides:{},o=S(n.baseUrl);return[{kind:"model",name:`${s}: ${r}/${i}`,...o?{target:o}:{}}]})}function $(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.wireApi==="string"?r.wireApi:"unknown",n=S(r.baseUrl);return{kind:"model",name:`${t} (${i})`,...n?{target:n}:{}}})}function P(e){if(!p(e))return[];let t=[];for(let s of["allow","ask","deny"])for(let r of D(e[s]).slice(0,m))t.push({kind:"permission",name:`${s}: ${k(r,512)}`});return t}function C(e){let t=[...R(e.mcpServers),...F(e.lspServers),...j(e.models),...$(e.modelProviders),...P(e.permissions)];if(p(e.env))for(let s of Object.keys(e.env).slice(0,m))t.push({kind:"environment",name:s});if(typeof e.permissionMode==="string")t.push({kind:"permission",name:`permissionMode: ${e.permissionMode}`});return t}function I(e){return e!=="hooks"&&e!=="disableAllHooks"}function M(e){return N("sha256").update(e).digest("hex")}function L(e,t){let s=a.relative(e,t);return s===""||!s.startsWith(`..${a.sep}`)&&s!==".."&&!a.isAbsolute(s)}class h{storeDir;static instance=null;mutex=new A;statusCache=new Map;constructor(e=a.join(b(),"workspace-trust")){this.storeDir=e}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}static resetInstance(){h.instance=null}async getStatus(e){let t=await y(e),s;try{s=await this.discoverSensitiveSources(t.projectPath)}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:0,sources:[],decision:"undecided",error:u instanceof Error?u.message:"Workspace trust review failed"};return this.cacheStatus(e,g),g}if(s.length===0){let u={...t,state:"not_required",trusted:!0,sensitiveSources:0,sources:s,decision:"undecided"};return this.cacheStatus(e,u),u}let r;try{r=await this.readDecisions()}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:s.length,sources:s,decision:"undecided",error:u instanceof Error?u.message:"Workspace trust store is unavailable"};return this.cacheStatus(e,g),g}let i=r.filter((u)=>L(u.path,t.trustRoot)),n=Math.max(-1,...i.map((u)=>u.path.split(a.sep).length)),o=i.filter((u)=>u.path.split(a.sep).length===n),c=o.length>0&&o.every((u)=>u.trusted),f=o[0],l=f?.path===t.trustRoot,E={...t,state:c?"trusted":"untrusted",trusted:c,sensitiveSources:s.length,sources:s,decision:f?l?f.trusted?"trusted":"untrusted":"inherited":"undecided",...f?.decidedAt?{decidedAt:f.decidedAt}:{},...!l&&f?.path?{inheritedFrom:f.path}:{}};return this.cacheStatus(e,E),E}cacheStatus(e,t){this.statusCache.set(a.resolve(e),t),this.statusCache.set(t.projectPath,t)}getCachedStatus(e){return this.statusCache.get(a.resolve(e))}isTrustedCached(e){return this.getCachedStatus(e)?.state==="trusted"}async trust(e){return this.recordDecision(e,!0)}async revoke(e){return this.recordDecision(e,!1)}async recordDecision(e,t){return this.mutex.runExclusive(async()=>{let s=await y(e);await this.assertSafeTrustRoot(s);let r={version:w,path:s.trustRoot,trusted:t,decidedAt:new Date().toISOString()};return await this.writeDecision(r),this.statusCache.clear(),this.getStatus(e)})}async assertSafeTrustRoot(e){let t=a.parse(e.trustRoot).root,s=await d.realpath(W.homedir()).catch(()=>a.resolve(W.homedir()));if(!a.isAbsolute(e.trustRoot)||e.trustRoot===t||e.trustRoot===s)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(e){let t=[],s=await this.reviewPackageScripts(e);if(s)t.push(s);for(let[r,i]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let n=await this.reviewConfigFile(e,r,i);if(n)t.push(n)}for(let r of[".blade/plugins",".claude/plugins"]){let i=await this.reviewResourceDirectory(e,r,"plugins","plugin");if(i)t.push(i)}for(let r of[".blade/commands",".claude/commands"]){let i=await this.reviewResourceDirectory(e,r,"commands","command");if(i)t.push(i)}for(let[r,i,n]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let o=await this.reviewResourceDirectory(e,r,i,n);if(o)t.push(o)}for(let r of["CLAUDE.md","AGENTS.md","BLADE.md"]){let i=await this.reviewInstructionFile(e,r);if(i)t.push(i)}return t}async reviewPackageScripts(e){let t=a.join(e,"package.json"),s;try{s=await d.stat(t)}catch(o){if(o.code==="ENOENT")return;throw o}if(!s.isFile())return;if(s.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let r;try{r=JSON.parse(await d.readFile(t,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!p(r)||!p(r.scripts))return;let i=r.scripts,n=Object.keys(i).filter((o)=>typeof i[o]==="string").sort().slice(0,m);if(n.length===0)return;return{path:"package.json",kind:"package",keys:n,effects:n.map((o)=>({kind:"command",name:`package script: ${o}`}))}}async reviewInstructionFile(e,t){try{if(!(await d.stat(a.join(e,t))).isFile())return}catch(s){if(s.code==="ENOENT")return;throw s}return{path:t,kind:"instructions",keys:[t],effects:[{kind:"instruction",name:t}]}}async reviewConfigFile(e,t,s){let r=a.join(e,t),i;try{i=await d.stat(r)}catch(l){if(l.code==="ENOENT")return;throw l}if(!i.isFile())return;if(i.size>T)throw Error(`${t} exceeds the 1 MiB workspace review limit`);let n;try{n=JSON.parse(await d.readFile(r,"utf8"))}catch{return{path:t,kind:s,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!p(n))return{path:t,kind:s,keys:[],effects:[],warning:"Configuration root is not an object"};let o=Object.keys(n).filter(I).sort();if(o.length===0)return;let c=C(n),f=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let l of o)if(!f.has(l))c.push({kind:"configuration",name:l});return{path:t,kind:s,keys:o,effects:c}}async reviewResourceDirectory(e,t,s,r){let i=a.join(e,t),n;try{n=await d.readdir(i,{withFileTypes:!0})}catch(c){if(c.code==="ENOENT")return;throw c}let o=n.filter((c)=>s==="plugins"||s==="skills"?c.isDirectory()||c.isSymbolicLink():c.isFile()||c.isDirectory()||c.isSymbolicLink()).slice(0,m);if(o.length===0)return;return{path:t,kind:s,keys:o.map((c)=>c.name),effects:o.map((c)=>({kind:r,name:c.name}))}}async readDecisions(){let e;try{e=await d.lstat(this.storeDir)}catch(r){if(r.code==="ENOENT")return[];throw r}if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let t=await d.readdir(this.storeDir,{withFileTypes:!0}),s=[];for(let r of t){if(!r.name.endsWith(".json"))continue;if(!r.isFile())throw Error("Workspace trust store entries must be regular files");s.push(await this.readDecision(a.join(this.storeDir,r.name)))}return s}async readDecision(e){let t;try{t=await d.open(e,v.O_RDONLY|v.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let s=await t.stat();if(!s.isFile()||s.size>x)throw Error("Workspace trust decision is invalid");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let r=JSON.parse(await t.readFile("utf8"));if(!p(r)||r.version!==w||typeof r.path!=="string"||!a.isAbsolute(r.path)||typeof r.trusted!=="boolean"||typeof r.decidedAt!=="string"||!Number.isFinite(Date.parse(r.decidedAt))||Object.keys(r).some((i)=>i!=="version"&&i!=="path"&&i!=="trusted"&&i!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:w,path:r.path,trusted:r.trusted,decidedAt:r.decidedAt}}finally{await t.close()}}async writeDecision(e){await this.ensureStoreDirectoryForWrite();let t=a.join(this.storeDir,`${M(e.path)}.json`);try{let s=await d.lstat(t);if(!s.isFile()||s.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(s){if(s.code!=="ENOENT")throw s}await O(t,`${JSON.stringify(e,null,2)}
1
+ import{Yg as y}from"./chunk-q78s028m.js";import{fh as b}from"./chunk-qb0sqh29.js";import{createHash as N}from"node:crypto";import{constants as v,promises as d}from"node:fs";import W from"node:os";import a from"node:path";import{Mutex as A}from"async-mutex";import O from"write-file-atomic";var w=1,x=65536,T=1048576,m=100;function p(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function k(e,t=2048){return e.length<=t?e:`${e.slice(0,t-1)}…`}function S(e){if(typeof e!=="string"||!e.trim())return;try{let t=new URL(e);return k(`${t.origin}${t.pathname}`)}catch{return k(e)}}function D(e){return Array.isArray(e)?e.filter((t)=>typeof t==="string"):[]}function R(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.type==="string"?r.type:"unknown",n=typeof r.command==="string"?r.command:void 0,o=D(r.args),c=i==="stdio"?k([n,...o].filter(Boolean).join(" ")):S(r.url);return{kind:"mcp",name:`${t} (${i})`,...c?{target:c}:{}}})}function F(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.command==="string"?k(r.command):void 0,n=p(r.extensionToLanguage)?Object.keys(r.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${t} (${n})`,...i?{target:i}:{}}})}function j(e){if(!Array.isArray(e))return[];return e.slice(0,m).flatMap((t)=>{if(!p(t))return[];let s=typeof t.id==="string"?t.id:"unnamed",r=typeof t.provider==="string"?t.provider:"unknown",i=typeof t.model==="string"?t.model:"unknown",n=p(t.overrides)?t.overrides:{},o=S(n.baseUrl);return[{kind:"model",name:`${s}: ${r}/${i}`,...o?{target:o}:{}}]})}function $(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.wireApi==="string"?r.wireApi:"unknown",n=S(r.baseUrl);return{kind:"model",name:`${t} (${i})`,...n?{target:n}:{}}})}function P(e){if(!p(e))return[];let t=[];for(let s of["allow","ask","deny"])for(let r of D(e[s]).slice(0,m))t.push({kind:"permission",name:`${s}: ${k(r,512)}`});return t}function C(e){let t=[...R(e.mcpServers),...F(e.lspServers),...j(e.models),...$(e.modelProviders),...P(e.permissions)];if(p(e.env))for(let s of Object.keys(e.env).slice(0,m))t.push({kind:"environment",name:s});if(typeof e.permissionMode==="string")t.push({kind:"permission",name:`permissionMode: ${e.permissionMode}`});return t}function I(e){return e!=="hooks"&&e!=="disableAllHooks"}function M(e){return N("sha256").update(e).digest("hex")}function L(e,t){let s=a.relative(e,t);return s===""||!s.startsWith(`..${a.sep}`)&&s!==".."&&!a.isAbsolute(s)}class h{storeDir;static instance=null;mutex=new A;statusCache=new Map;constructor(e=a.join(b(),"workspace-trust")){this.storeDir=e}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}static resetInstance(){h.instance=null}async getStatus(e){let t=await y(e),s;try{s=await this.discoverSensitiveSources(t.projectPath)}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:0,sources:[],decision:"undecided",error:u instanceof Error?u.message:"Workspace trust review failed"};return this.cacheStatus(e,g),g}if(s.length===0){let u={...t,state:"not_required",trusted:!0,sensitiveSources:0,sources:s,decision:"undecided"};return this.cacheStatus(e,u),u}let r;try{r=await this.readDecisions()}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:s.length,sources:s,decision:"undecided",error:u instanceof Error?u.message:"Workspace trust store is unavailable"};return this.cacheStatus(e,g),g}let i=r.filter((u)=>L(u.path,t.trustRoot)),n=Math.max(-1,...i.map((u)=>u.path.split(a.sep).length)),o=i.filter((u)=>u.path.split(a.sep).length===n),c=o.length>0&&o.every((u)=>u.trusted),f=o[0],l=f?.path===t.trustRoot,E={...t,state:c?"trusted":"untrusted",trusted:c,sensitiveSources:s.length,sources:s,decision:f?l?f.trusted?"trusted":"untrusted":"inherited":"undecided",...f?.decidedAt?{decidedAt:f.decidedAt}:{},...!l&&f?.path?{inheritedFrom:f.path}:{}};return this.cacheStatus(e,E),E}cacheStatus(e,t){this.statusCache.set(a.resolve(e),t),this.statusCache.set(t.projectPath,t)}getCachedStatus(e){return this.statusCache.get(a.resolve(e))}isTrustedCached(e){return this.getCachedStatus(e)?.state==="trusted"}async trust(e){return this.recordDecision(e,!0)}async revoke(e){return this.recordDecision(e,!1)}async recordDecision(e,t){return this.mutex.runExclusive(async()=>{let s=await y(e);await this.assertSafeTrustRoot(s);let r={version:w,path:s.trustRoot,trusted:t,decidedAt:new Date().toISOString()};return await this.writeDecision(r),this.statusCache.clear(),this.getStatus(e)})}async assertSafeTrustRoot(e){let t=a.parse(e.trustRoot).root,s=await d.realpath(W.homedir()).catch(()=>a.resolve(W.homedir()));if(!a.isAbsolute(e.trustRoot)||e.trustRoot===t||e.trustRoot===s)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(e){let t=[],s=await this.reviewPackageScripts(e);if(s)t.push(s);for(let[r,i]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let n=await this.reviewConfigFile(e,r,i);if(n)t.push(n)}for(let r of[".blade/plugins",".claude/plugins"]){let i=await this.reviewResourceDirectory(e,r,"plugins","plugin");if(i)t.push(i)}for(let r of[".blade/commands",".claude/commands"]){let i=await this.reviewResourceDirectory(e,r,"commands","command");if(i)t.push(i)}for(let[r,i,n]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let o=await this.reviewResourceDirectory(e,r,i,n);if(o)t.push(o)}for(let r of["CLAUDE.md","AGENTS.md","BLADE.md"]){let i=await this.reviewInstructionFile(e,r);if(i)t.push(i)}return t}async reviewPackageScripts(e){let t=a.join(e,"package.json"),s;try{s=await d.stat(t)}catch(o){if(o.code==="ENOENT")return;throw o}if(!s.isFile())return;if(s.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let r;try{r=JSON.parse(await d.readFile(t,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!p(r)||!p(r.scripts))return;let i=r.scripts,n=Object.keys(i).filter((o)=>typeof i[o]==="string").sort().slice(0,m);if(n.length===0)return;return{path:"package.json",kind:"package",keys:n,effects:n.map((o)=>({kind:"command",name:`package script: ${o}`}))}}async reviewInstructionFile(e,t){try{if(!(await d.stat(a.join(e,t))).isFile())return}catch(s){if(s.code==="ENOENT")return;throw s}return{path:t,kind:"instructions",keys:[t],effects:[{kind:"instruction",name:t}]}}async reviewConfigFile(e,t,s){let r=a.join(e,t),i;try{i=await d.stat(r)}catch(l){if(l.code==="ENOENT")return;throw l}if(!i.isFile())return;if(i.size>T)throw Error(`${t} exceeds the 1 MiB workspace review limit`);let n;try{n=JSON.parse(await d.readFile(r,"utf8"))}catch{return{path:t,kind:s,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!p(n))return{path:t,kind:s,keys:[],effects:[],warning:"Configuration root is not an object"};let o=Object.keys(n).filter(I).sort();if(o.length===0)return;let c=C(n),f=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let l of o)if(!f.has(l))c.push({kind:"configuration",name:l});return{path:t,kind:s,keys:o,effects:c}}async reviewResourceDirectory(e,t,s,r){let i=a.join(e,t),n;try{n=await d.readdir(i,{withFileTypes:!0})}catch(c){if(c.code==="ENOENT")return;throw c}let o=n.filter((c)=>s==="plugins"||s==="skills"?c.isDirectory()||c.isSymbolicLink():c.isFile()||c.isDirectory()||c.isSymbolicLink()).slice(0,m);if(o.length===0)return;return{path:t,kind:s,keys:o.map((c)=>c.name),effects:o.map((c)=>({kind:r,name:c.name}))}}async readDecisions(){let e;try{e=await d.lstat(this.storeDir)}catch(r){if(r.code==="ENOENT")return[];throw r}if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let t=await d.readdir(this.storeDir,{withFileTypes:!0}),s=[];for(let r of t){if(!r.name.endsWith(".json"))continue;if(!r.isFile())throw Error("Workspace trust store entries must be regular files");s.push(await this.readDecision(a.join(this.storeDir,r.name)))}return s}async readDecision(e){let t;try{t=await d.open(e,v.O_RDONLY|v.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let s=await t.stat();if(!s.isFile()||s.size>x)throw Error("Workspace trust decision is invalid");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let r=JSON.parse(await t.readFile("utf8"));if(!p(r)||r.version!==w||typeof r.path!=="string"||!a.isAbsolute(r.path)||typeof r.trusted!=="boolean"||typeof r.decidedAt!=="string"||!Number.isFinite(Date.parse(r.decidedAt))||Object.keys(r).some((i)=>i!=="version"&&i!=="path"&&i!=="trusted"&&i!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:w,path:r.path,trusted:r.trusted,decidedAt:r.decidedAt}}finally{await t.close()}}async writeDecision(e){await this.ensureStoreDirectoryForWrite();let t=a.join(this.storeDir,`${M(e.path)}.json`);try{let s=await d.lstat(t);if(!s.isFile()||s.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(s){if(s.code!=="ENOENT")throw s}await O(t,`${JSON.stringify(e,null,2)}
2
2
  `,{mode:384}),await d.chmod(t,384)}async ensureStoreDirectoryForWrite(){try{let e=await d.lstat(this.storeDir);if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(e){if(e.code!=="ENOENT")throw e;await d.mkdir(this.storeDir,{recursive:!0,mode:448}),await d.chmod(this.storeDir,448)}}}
3
- export{h as Mg};
3
+ export{h as Xg};
@@ -1 +1 @@
1
- import"./chunk-m8s208g3.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
1
+ import"./chunk-hfrcwkc8.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
@@ -1,4 +1,4 @@
1
- import{rd as N}from"./chunk-mp637mb6.js";import{He as $}from"./chunk-mt7fn8cv.js";import{Uf as _}from"./chunk-jv9zg1fw.js";import{rg as Y,tg as Z}from"./chunk-t2mc97k7.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{td as N}from"./chunk-r085zhqr.js";import{Je as $}from"./chunk-706zda55.js";import{dg as _}from"./chunk-kfpzrmq7.js";import{Cg as Y,Eg as Z}from"./chunk-fhnkyqfb.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
- export{O as $c,y as ad,j as bd,C as cd};
4
+ export{O as bd,y as cd,j as dd,C as ed};
@@ -1 +1 @@
1
- import{a as o}from"./chunk-z60w7p8a.js";import"./chunk-yqxyy3w2.js";import"./chunk-m8s208g3.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{a as o}from"./chunk-z9absgab.js";import"./chunk-j0k3mbkd.js";import"./chunk-hfrcwkc8.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1,2 +1,2 @@
1
1
  import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
2
- export{G as Ie,F as Je,R as Ke,v as Le};
2
+ export{G as Ke,F as Le,R as Me,v as Ne};
@@ -0,0 +1,2 @@
1
+ import{K as I}from"./chunk-aw7w91f0.js";import{Ac as D}from"./chunk-g96t2yrz.js";import w from"node:path";function C(a){let t=a.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}function P(a){let t=a.replace(/\s+/g," ").trim();return t.length<=500?t:`${t.slice(0,497)}...`}function S(a){return`task/${a.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class z{static async createSessionTask(a){if(!a.prompt.trim())throw Error("Task prompt must not be blank");if(!w.isAbsolute(a.sourceProjectPath))throw Error("Task source project path must be absolute");let t=w.resolve(a.sourceProjectPath),s;try{return s=a.isolation==="worktree"?await I.enter({sessionId:a.sessionId,workspaceRoot:t,name:S(a.sessionId)}):void 0,{metadata:await D.createSessionMetadata(a.sessionId,s?.workspaceRoot??t,{title:a.title?.trim()||C(a.prompt),taskPromptSummary:P(a.prompt),taskDispatch:a.dispatch,taskModelId:a.dispatch?.modelId,selectedModelId:a.dispatch?.modelId,permissionMode:a.dispatch?.permissionMode,reasoningEffort:a.dispatch?.reasoningEffort,serviceTier:a.dispatch?.serviceTier,responseVerbosity:a.dispatch?.responseVerbosity,communicationStyle:a.dispatch?.communicationStyle,communicationStyleDigest:a.dispatch?.communicationStyleDigest,projectInstructionsDigest:a.dispatch?.projectInstructionsDigest,taskRetriedFrom:a.retriedFrom,taskIsolation:a.isolation,taskSourceProjectPath:t,taskWorktree:s}),taskWorktree:s}}catch(k){if(s)await I.exit({sessionId:a.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var N=256,Z=8388608,_=30000;class c extends Error{kind;pendingItems;pendingBytes;constructor(a,t,s){super(t,s);this.kind=a;this.name="BoundedSerialEgressError",this.pendingItems=s?.pendingItems,this.pendingBytes=s?.pendingBytes}}function m(a){a.catch(()=>{return})}class F{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(a){this.options=a;if(this.assertPositiveInteger(a.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(a.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(a.writeTimeoutMs,"writeTimeoutMs"),a.signal?.addEventListener("abort",this.handleAbort,{once:!0}),a.signal?.aborted)this.handleAbort()}offer(a){if(this.closed)return{accepted:!1,error:this.failure??new c("closed","Egress is already closed")};let t;try{t=this.options.sizeOf(a)}catch(i){return this.rejectAdmission(new c("invalid_size","Egress size calculation failed",{cause:i}))}if(!Number.isSafeInteger(t)||t<0)return this.rejectAdmission(new c("invalid_size","Egress size must be a non-negative safe integer"));if(t>this.options.maxPendingBytes)return this.rejectAdmission(new c("oversized",`Egress value requires ${t} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+t>this.options.maxPendingBytes)return this.rejectAdmission(new c("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let s,k,h=new Promise((i,f)=>{s=i,k=f});return m(h),this.nextSequence+=1,this.pending.push({value:a,bytes:t,sequence:this.nextSequence,resolve:s,reject:k,completion:h}),this.pendingBytes+=t,this.startDrain(),{accepted:!0,completion:h}}flush(){if(this.failure){let h=Promise.reject(this.failure);return m(h),h}let a=this.nextSequence;if(a<=this.completedSequence)return Promise.resolve();let t,s,k=new Promise((h,i)=>{t=h,s=i});return m(k),this.flushWaiters.push({targetSequence:a,resolve:t,reject:s}),k}close(a){let t=a instanceof c?a:new c("closed","Egress was closed",{cause:a});this.fail(t)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new c("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(a){return this.fail(a),{accepted:!1,error:a}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let a=this.drain();m(a)}async drain(){try{while(!this.closed){let a=this.pending[0];if(!a)return;try{await this.writeOne(a.value)}catch(t){this.fail(this.normalizeWriteError(t));return}if(this.closed||this.pending[0]!==a)return;this.pending.shift(),this.pendingBytes-=a.bytes,this.completedSequence=a.sequence,a.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(a){let t=new AbortController;this.activeWriteAbort=t;let s,k,h=new Promise((W,T)=>{k=T});m(h),this.activeWriteStop=k;let i=Promise.resolve().then(()=>this.options.write(a,t.signal));m(i);let f=new Promise((W,T)=>{s=setTimeout(()=>{let M=new c("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);t.abort(M),T(M)},this.options.writeTimeoutMs),this.activeWriteTimeout=s});m(f);try{await Promise.race([i,f,h])}finally{if(s!==void 0)clearTimeout(s);if(this.activeWriteTimeout===s)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===t)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(a){if(a instanceof c)return a;return new c("write_failed","Egress write failed",{cause:a})}fail(a){if(this.closed)return;if(a.pendingItems??=this.pending.length,a.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=a,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(a),this.activeWriteStop?.(a),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let t=this.pending.splice(0);this.pendingBytes=0;for(let s of t)s.reject(a);for(let s of this.flushWaiters.splice(0))s.reject(a);try{this.options.onFailure?.(a)}catch{}}settleFlushWaiters(){for(let a=0;a<this.flushWaiters.length;){let t=this.flushWaiters[a];if(t.targetSequence>this.completedSequence){a+=1;continue}this.flushWaiters.splice(a,1),t.resolve()}}assertPositiveInteger(a,t){if(!Number.isSafeInteger(a)||a<=0)throw RangeError(`${t} must be a positive safe integer`)}}
2
+ export{z as v,N as w,Z as x,_ as y,c as z,F as A};
@@ -1,5 +1,5 @@
1
- import{$f as g_,Yf as y_,Zf as Qf,_f as Kf,ag as zf,cg as Wf,eg as Hf,fg as hf,gg as Rf,hg as $f,jg as Sf,kg as Gf,mg as I}from"./chunk-4k37vmxh.js";import{tg as q}from"./chunk-t2mc97k7.js";import{xg as ef,zg as Cf}from"./chunk-ecw74d2s.js";import{Cg as v_}from"./chunk-pm9kt54d.js";var ME={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},af=(f)=>ME[f]||{};var AE=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&AE.has(f)}function nE(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function ET(f){if(Vf(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 yf(...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 A of _)if(A.aborted)return A;let T=new AbortController,x=new Map;for(let A of _){let Y=()=>{T.abort(A.reason);for(let[R,h]of x)R.removeEventListener("abort",h)};x.set(A,Y)}for(let[A,Y]of x)A.addEventListener("abort",Y,{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((x,A)=>{let Y,R=setTimeout(()=>{if(_&&Y)_.removeEventListener("abort",Y);x()},f);if(_)Y=()=>{if(clearTimeout(R),T)A(new DOMException("Aborted","AbortError"));else x()},_.addEventListener("abort",Y,{once:!0})})}var hE=q("Chat"),RE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function bf(f){if(typeof f==="string")return f;return f.filter((_)=>_.type==="text").map((_)=>_.text).join(`
1
+ import{hg as y_,ig as Qf,jg as Kf,kg as g_,lg as zf,ng as Wf,pg as Hf,qg as hf,rg as Rf,sg as $f,ug as Sf,vg as Gf,xg as I}from"./chunk-yk9pxkc1.js";import{Eg as q}from"./chunk-fhnkyqfb.js";import{Ig as ef,Kg as Cf}from"./chunk-26wse17p.js";import{Ng as v_}from"./chunk-hcm55r3d.js";var ME={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},af=(f)=>ME[f]||{};var AE=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&AE.has(f)}function nE(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function ET(f){if(Vf(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 yf(...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 A of _)if(A.aborted)return A;let T=new AbortController,x=new Map;for(let A of _){let Y=()=>{T.abort(A.reason);for(let[R,h]of x)R.removeEventListener("abort",h)};x.set(A,Y)}for(let[A,Y]of x)A.addEventListener("abort",Y,{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((x,A)=>{let Y,R=setTimeout(()=>{if(_&&Y)_.removeEventListener("abort",Y);x()},f);if(_)Y=()=>{if(clearTimeout(R),T)A(new DOMException("Aborted","AbortError"));else x()},_.addEventListener("abort",Y,{once:!0})})}var hE=q("Chat"),RE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function bf(f){if(typeof f==="string")return f;return f.filter((_)=>_.type==="text").map((_)=>_.text).join(`
2
2
  `)}function SE(f){if(!f)return{};try{let _=JSON.parse(f);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return hE.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function YE(f){let _=f.match(/^data:([^;,]+);base64,(.+)$/s);return _?{mimeType:_[1],data:_[2]}:void 0}async function PE(f,_){let E=YE(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 of(f,_,E,T,x){let A=f.filter((h)=>h.role==="system").map((h)=>bf(h.content)).filter(Boolean).join(`
3
3
 
4
4
  `),Y=[];for(let h of f){if(h.role==="system")continue;if(h.role==="user"){let U=_.input.includes("image"),M=typeof h.content==="string"?h.content:await Promise.all(h.content.map((P)=>P.type==="text"?Promise.resolve({type:"text",text:P.text}):U?PE(P.image_url.url,T):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));Y.push({role:"user",content:M,timestamp:Date.now()});continue}if(h.role==="assistant"){let U=[];if(h.reasoningContent?.trim())U.push({type:"thinking",thinking:h.reasoningContent});let M=bf(h.content);if(M)U.push({type:"text",text:M});for(let P of h.tool_calls??[]){if(!("function"in P))continue;U.push({type:"toolCall",id:P.id,name:P.function.name,arguments:SE(P.function.arguments)})}Y.push({role:"assistant",content:U,api:_.api,provider:_.provider,model:_.id,usage:RE,stopReason:h.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}Y.push({role:"toolResult",toolCallId:h.tool_call_id??"",toolName:h.name??"unknown",content:[{type:"text",text:bf(h.content)}],isError:!1,timestamp:Date.now()})}let R=E?.filter((h)=>!x||h.name===x).map((h)=>({name:h.name,description:h.description,parameters:h.parameters,constrainedSampling:h.constrainedSampling}));return{...A?{systemPrompt:A}:{},messages:Y,...R?.length?{tools:R}:{}}}function df(f){let _=[];for(let E=0;E<f.length;E++){let T=f[E];if(T.role==="tool")continue;let x=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!x){_.push(T);continue}let A=[],Y=E+1;while(Y<f.length&&f[Y].role==="tool")A.push(f[Y++]);let R=new Set(x.map((M)=>M.id)),h=A.filter((M)=>M.tool_call_id&&R.has(M.tool_call_id)),U=new Set(h.map((M)=>M.tool_call_id));if(R.size===x.length&&h.length===R.size&&U.size===R.size)_.push(T,...h);E=Y-1}return _}function rf(f){return f.some((_)=>_.role==="assistant"&&Boolean(_.tool_calls?.length)&&!_.reasoningContent?.trim())}function nf(f,_){return{...f,..._.baseUrl?{baseUrl:ef(f.api,_.baseUrl)}:{},..._.maxOutputTokens?{maxTokens:_.maxOutputTokens}:{}}}function jf(f){let _=f.modelCatalog??Cf();return{models:_.models,model:nf(_.getModel(f.provider,f.model),f)}}function f_(f,_){let E=f.modelCatalog??Cf();return nf(E.getModel(_.provider,_.model),f)}import{randomBytes as OE}from"node:crypto";import{createHmac as UE}from"node:crypto";function uE(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 DE(f){if(!f)return[];return Object.entries(f).map(([_,E])=>[_.trim().toLowerCase(),E.trim()]).sort(([_],[E])=>_.localeCompare(E))}function xf(f,_,E){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),uE(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",DE(f.customHeaders),E]);return UE("sha256",Buffer.from(_)).update(T).digest("hex")}var NE=60000,BE=4,VE=0.8;var Af=300000,Xf=600000;var __=128,E_=256,bE=1800000,Mf=50;class e 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 Jf(f){return f instanceof e||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 CE(f,_){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:_}function jE(f,_){return xf(f,_,{providerCircuitOpenDurationMs:f.openDurationMs})}function r(f){let _=0;for(let E of f)if(E.failure)_++;return _}function T_(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function x_(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Wf)}class A_{#M=new Map;#R=new WeakMap;#f;#_;#T;#E;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):OE(32),this.#_=f.now??(()=>performance.now()),this.#T=f.wallNow??f.now??Date.now,this.#E={maxEntries:Math.min(m(f.maxEntries,__),__),maxWindowEntries:Math.min(m(f.maxWindowEntries,E_),E_),windowMs:m(f.windowMs,NE),minSamples:m(f.minSamples,BE),errorRateThreshold:CE(f.errorRateThreshold,VE),idleTtlMs:m(f.idleTtlMs,bE)}}get size(){return this.#M.size}get(f){if(f.openDurationMs===0)return this.#A();let _=this.#_();this.#V(_);let E=jE(f,this.#f),T=this.#M.get(E);if(T)return T.lastTouchedAt=_,this.#x(T,f.probeLeaseMs);if(this.#M.size>=this.#E.maxEntries)this.#j();if(this.#M.size>=this.#E.maxEntries)return this.#A();let x={key:E,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:_,detached:!1};return this.#M.set(E,x),this.#x(x,f.probeLeaseMs)}#x(f,_){let E=this,T=Math.max(Af,Math.min(m(_,Af),Xf));return{preflight:()=>E.#U(f),check:()=>E.#u(f,T),recordSuccess:(x)=>E.#N(x,"success"),recordFailure:(x,A)=>E.#N(x,"failure",A),recordNeutral:(x)=>E.#N(x,"neutral"),abandon:(x)=>E.#C(x),snapshot:()=>E.#b(f)}}#A(){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.#h(_),recordFailure:(_)=>f.#h(_),recordNeutral:(_)=>f.#h(_),abandon:(_)=>f.#C(_),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#h(f){let _=this.#R.get(f);if(_?.kind==="noop")_.settled=!0;return}#U(f){let _=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=_,this.#B(f,_),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??_;return _<T?this.#S(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??_+Mf)-_);return this.#S(f,Math.min(Mf,E))}#S(f,_){let{allowed:E,...T}=this.#O(f,_);return{eligible:!1,...T}}#u(f,_){let E=this.#_();if(f.detached)return this.#A().check();if(f.lastTouchedAt=E,this.#B(f,E),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let x=f.nextProbeAt??E;if(E<x)return this.#O(f,x-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.#D(f,E,_);let T=Math.max(1,(f.probeLeaseExpiresAt??E+Mf)-E);return this.#O(f,Math.min(Mf,T))}#Y(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}}#D(f,_,E){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=_+E,f.lastTouchedAt=_;let x=this.#Y(f,"probe",T),A=f.lastFailure??{reason:"server_error"};return{...x,reason:A.reason,...A.statusCode!==void 0?{statusCode:A.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:r(f.samples)}}#O(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:r(f.samples)}}#N(f,_,E){let T=this.#R.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let x=T.entry;if(x.detached||T.generation!==x.generation||T.kind==="regular"&&x.state!=="closed"||T.kind==="probe"&&(x.state!=="half_open"||T.probeLeaseId!==x.probeLeaseId))return;let A=this.#_();if(x.lastTouchedAt=A,T.kind==="probe"){if(_==="failure"&&E)return this.#P(x,E,A,"reopened");return this.#W(x)}if(_==="neutral")return;if(this.#X(x,_==="failure",A),_!=="failure"||!E)return;let Y=r(x.samples),R=x.samples.length===0?0:Y/x.samples.length;if(x.samples.length>=this.#E.minSamples&&R>=this.#E.errorRateThreshold)return this.#P(x,E,A,"opened");return}#P(f,_,E,T){let x={reason:_.reason,...T_(_.statusCode)!==void 0?{statusCode:T_(_.statusCode)}:{},...x_(_.retryAfterMs)!==void 0?{retryAfterMs:x_(_.retryAfterMs)}:{}},A=x.retryAfterMs??0,Y=Math.max(f.configuredOpenDurationMs,A);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=Y,f.nextProbeAt=E+Y,f.lastFailure=x,{phase:T,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},retryAfterMs:Y,nextProbeAt:this.#T()+Y,openDurationMs:Y,sampleCount:f.samples.length,failureCount:r(f.samples)}}#W(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}}#C(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}#X(f,_,E){if(this.#B(f,E),f.samples.length>=this.#E.maxWindowEntries)f.samples.shift();f.samples.push({at:E,failure:_})}#B(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)}#b(f){if(!f.detached)this.#B(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:r(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#V(f){for(let[_,E]of this.#M)if(E.state==="closed"&&f-E.lastTouchedAt>this.#E.idleTtlMs)this.#z(_,E)}#j(){let f;for(let _ of this.#M.values())if(_.state==="closed"&&(!f||_.lastTouchedAt<f.lastTouchedAt))f=_;if(f)this.#z(f.key,f)}#z(f,_){_.detached=!0,this.#M.delete(f)}}var M_;function h_(){return M_??=new A_,M_}import{randomBytes as zE}from"node:crypto";var R_=16,S_=128,Y_=32,P_=3,U_=16,u_=96,D_=24,O_=12,N_=16,B_=4,V_=4,b_=67108864,C_=33554432,j_=12,z_=2,W_=2,X_=1,$_=15000,J_=30000;class i extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,_,E,T,x,A,Y,R){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=x;this.limit=A;this.queued=Y;this.maxWaitMs=R;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function n(f){return f instanceof i||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 WE(f){let _=j(f.globalMaxInFlight,R_,R_),E=j(f.globalMaxPending,S_,S_),T=j(f.domainMaxPending,Y_,Y_),x=Math.min(j(f.ownerMaxInFlight,P_,P_),_),A=Math.min(j(f.ownerMaxPending,U_,U_),E),Y=Math.min(j(f.nonForegroundGlobalMaxPending,Math.min(u_,Math.max(1,Math.floor(E*3/4))),u_),E),R=Math.min(j(f.nonForegroundDomainMaxPending,Math.min(D_,Math.max(1,Math.floor(T*3/4))),D_),T),h=Math.min(j(f.nonForegroundOwnerMaxPending,Math.min(O_,Math.max(1,Math.floor(A*3/4))),O_),A),U=Math.min(j(f.internalGlobalMaxPending,Math.min(N_,Math.max(1,Math.floor(E/8))),N_),Y),M=Math.min(j(f.internalDomainMaxPending,Math.min(B_,Math.max(1,Math.floor(T/8))),B_),R),P=Math.min(j(f.internalOwnerMaxPending,Math.min(V_,Math.max(1,Math.floor(A/4))),V_),h),u=j(f.globalMaxPendingBytes,I,I),D=Math.min(j(f.domainMaxPendingBytes,b_,b_),u),G=Math.min(j(f.ownerMaxPendingBytes,C_,C_),u),L=Math.min(j(f.nonForegroundGlobalMaxInFlight,Math.min(j_,_),j_),_),Q=Math.min(j(f.nonForegroundOwnerMaxInFlight,Math.min(z_,x),z_),x),Pf=Math.min(j(f.internalGlobalMaxInFlight,Math.min(W_,_),W_),_),ff=j(f.internalDomainMaxInFlight,X_,X_),Uf=j(f.agingMs,J_,J_);return{globalMaxInFlight:_,globalMaxPending:E,domainMaxPending:T,ownerMaxInFlight:x,ownerMaxPending:A,nonForegroundGlobalMaxPending:Y,nonForegroundDomainMaxPending:R,nonForegroundOwnerMaxPending:h,internalGlobalMaxPending:U,internalDomainMaxPending:M,internalOwnerMaxPending:P,globalMaxPendingBytes:u,domainMaxPendingBytes:D,ownerMaxPendingBytes:G,nonForegroundGlobalMaxInFlight:L,nonForegroundOwnerMaxInFlight:Q,internalGlobalMaxInFlight:Pf,internalDomainMaxInFlight:ff,agingMs:Uf}}function k_(f,_){if(!f.trim())throw Error(`${_} must not be blank`)}function XE(f){if(k_(f.sessionId,"sessionId"),k_(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<hf||f.scope.maxConcurrent>Rf)throw Error(`maxConcurrent must be between ${hf} and ${Rf}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>I)throw Error(`maxPendingBytes must be between 1 and ${I}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>I+1)throw Error(`pendingBytes must be between 1 and ${I+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Sf)throw Error(`maxWaitMs must be 0-${Sf}`)}function kf(f,_){if(_!==void 0)return _;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function JE(f,_){return xf(f,_,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class G_{#M;#R;#f;#_=[];#T=new Map;#E=new Map;#x=0;#A=0;#h=0;#U=0;#S=0;#u=0;#Y=0;#D=0;#O=1;#N=0;#P=!1;constructor(f={}){this.#M=f.processSecret?new Uint8Array(f.processSecret):zE(32),this.#R=f.now??(()=>performance.now()),this.#f=WE(f)}admit(f){if(XE(f),this.#P)throw this.#H("closed",f,{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw kf(f.signal);let _=JE(f.scope,this.#M),E=this.#T.get(_),T=this.#E.get(f.ownerId),x=E??this.#X(f.scope.maxConcurrent),A=T??this.#B();if(this.#_.length===0&&this.#b(x,A,f.requestClass)){if(!E)this.#T.set(_,x);if(!T)this.#E.set(f.ownerId,A),this.#O++;let u=this.#j(_,f.ownerId,f.requestClass),D=this.#v(f,0);return{ready:Promise.resolve(u),getSnapshot:()=>({...D}),cancel:()=>{D={...D}}}}let Y=this.#W(f,x,A);if(Y)throw this.#H("queue_full",f,Y,this.#_.length);let R=this.#V(x,A,f.requestClass);if(f.maxWaitMs===0)throw this.#H("wait_timeout",f,R,this.#_.length);if(!E)this.#T.set(_,x);if(!T)this.#E.set(f.ownerId,A),this.#O++;let h,U,M=new Promise((u,D)=>{h=u,U=D});M.catch(()=>{return});let P={domainKey:_,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#R(),signal:f.signal,resolve:h,reject:U,settled:!1,admitted:!1};if(f.signal)P.abortListener=()=>this.#$(P,kf(f.signal)),f.signal.addEventListener("abort",P.abortListener,{once:!0});return P.timer=setTimeout(()=>this.#Q(P),f.maxWaitMs),P.timer.unref?.(),this.#_.push(P),this.#C(x,A,P),this.#J(),{ready:M,getSnapshot:()=>this.#F(P),cancel:(u)=>this.#$(P,kf(f.signal,u))}}close(){if(this.#P)return;this.#P=!0;for(let f of[...this.#_]){let _=this.#T.get(f.domainKey),E=this.#E.get(f.ownerId),T=_&&E?this.#V(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};this.#k(f,new i("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:this.#x,queued:this.#_.length,pendingBytes:this.#u,nonForegroundInFlight:this.#A,internalInFlight:this.#h,nonForegroundQueued:this.#U,internalQueued:this.#S,nonForegroundPendingBytes:this.#Y,internalPendingBytes:this.#D,domainCount:this.#T.size,ownerCount:this.#E.size,closed:this.#P}}#W(f,_,E){let T=(M,P,u)=>P>=u?{scope:M,resource:"pending_count",inFlight:P,limit:u}:void 0;if(f.requestClass==="internal"){let M=T("class",this.#S,this.#f.internalGlobalMaxPending)??T("class",E.internalQueued,this.#f.internalOwnerMaxPending)??T("class",_.internalQueued,this.#f.internalDomainMaxPending);if(M)return M}if(f.requestClass!=="foreground"){let M=T("class",this.#U,this.#f.nonForegroundGlobalMaxPending)??T("class",E.nonForegroundQueued,this.#f.nonForegroundOwnerMaxPending)??T("class",_.nonForegroundQueued,this.#f.nonForegroundDomainMaxPending);if(M)return M}let x=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",E.queued,this.#f.ownerMaxPending)??T("domain",_.queued,this.#f.domainMaxPending);if(x)return x;let A=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),Y=Math.min(A,this.#f.domainMaxPendingBytes),R=Math.min(A,this.#f.ownerMaxPendingBytes),h=(M,P)=>f.pendingBytes>P-M,U=(M)=>{if(M==="owner")return{scope:M,resource:"pending_bytes",inFlight:E.inFlight,limit:this.#f.ownerMaxInFlight};if(M==="domain")return{scope:M,resource:"pending_bytes",inFlight:_.inFlight,limit:_.maxConcurrent};return{scope:M,resource:"pending_bytes",inFlight:this.#x,limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let M=Math.max(1,Math.floor(A/8)),P=Math.max(1,Math.floor(Y/4)),u=Math.max(1,Math.floor(R/4));if(h(this.#D,M)||h(E.internalPendingBytes,u)||h(_.internalPendingBytes,P))return U("class")}if(f.requestClass!=="foreground"){let M=Math.max(1,Math.floor(A*3/4)),P=Math.max(1,Math.floor(Y*3/4)),u=Math.max(1,Math.floor(R/2));if(h(this.#Y,M)||h(E.nonForegroundPendingBytes,u)||h(_.nonForegroundPendingBytes,P))return U("class")}if(h(this.#u,A))return U("global");if(h(E.pendingBytes,R))return U("owner");if(h(_.pendingBytes,Y))return U("domain");return}#C(f,_,E){if(f.queued++,_.queued++,this.#u+=E.pendingBytes,f.pendingBytes+=E.pendingBytes,_.pendingBytes+=E.pendingBytes,E.requestClass!=="foreground")this.#U++,f.nonForegroundQueued++,_.nonForegroundQueued++,this.#Y+=E.pendingBytes,f.nonForegroundPendingBytes+=E.pendingBytes,_.nonForegroundPendingBytes+=E.pendingBytes;if(E.requestClass==="internal")this.#S++,f.internalQueued++,_.internalQueued++,this.#D+=E.pendingBytes,f.internalPendingBytes+=E.pendingBytes,_.internalPendingBytes+=E.pendingBytes}#X(f){return{maxConcurrent:f,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#B(){return{order:this.#O,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#b(f,_,E){if(this.#x>=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.#A>=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.#h<this.#f.internalGlobalMaxInFlight&&f.internalInFlight<this.#f.internalDomainMaxInFlight}#V(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.#x>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};if(E!=="foreground"&&this.#A>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#A,limit:this.#f.nonForegroundGlobalMaxInFlight};if(E==="internal"&&this.#h>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#h,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent}}#j(f,_,E){let T=this.#T.get(f),x=this.#E.get(_);if(!T||!x)throw Error("Provider admission accounting state is unavailable");if(this.#x++,T.inFlight++,x.inFlight++,E!=="foreground")this.#A++,T.nonForegroundInFlight++,x.nonForegroundInFlight++;if(E==="internal")this.#h++,T.internalInFlight++,x.internalInFlight++;let A=!1;return{release:()=>{if(A)return;A=!0,this.#z(f,_,E)}}}#z(f,_,E){let T=this.#T.get(f),x=this.#E.get(_);if(this.#x=Math.max(0,this.#x-1),T)T.inFlight=Math.max(0,T.inFlight-1);if(x)x.inFlight=Math.max(0,x.inFlight-1);if(E!=="foreground"){if(this.#A=Math.max(0,this.#A-1),T)T.nonForegroundInFlight=Math.max(0,T.nonForegroundInFlight-1);if(x)x.nonForegroundInFlight=Math.max(0,x.nonForegroundInFlight-1)}if(E==="internal"){if(this.#h=Math.max(0,this.#h-1),T)T.internalInFlight=Math.max(0,T.internalInFlight-1);if(x)x.internalInFlight=Math.max(0,x.internalInFlight-1)}this.#L(f,_),this.#J()}#J(){if(this.#P)return;while(this.#_.length>0){let f=this.#R(),_=new Map;for(let[R,h]of this.#_.entries()){let U=this.#T.get(h.domainKey),M=this.#E.get(h.ownerId);if(U===void 0||M===void 0||!this.#b(U,M,h.requestClass))continue;let P=this.#Z(h,f),u=_.get(h.ownerId);if(!u||P<u.rank||P===u.rank&&R<u.index)_.set(h.ownerId,{pending:h,rank:P,index:R})}let E=[..._.values()].filter(({pending:R})=>{let h=this.#T.get(R.domainKey),U=this.#E.get(R.ownerId);return h!==void 0&&U!==void 0&&this.#b(h,U,R.requestClass)}).map(({pending:R,rank:h})=>({pending:R,rank:h,order:this.#E.get(R.ownerId).order}));if(E.length===0)return;let T=Math.min(...E.map((R)=>R.rank)),x=E.filter((R)=>R.rank===T),Y=x.filter((R)=>R.order>this.#N).sort((R,h)=>R.order-h.order)[0]??x.sort((R,h)=>R.order-h.order)[0];this.#c(Y.pending,Y.order)}}#Z(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)}#c(f,_){if(!this.#G(f,!1))return;f.settled=!0,f.admitted=!0,this.#N=_;let E=this.#j(f.domainKey,f.ownerId,f.requestClass);f.permit=E,f.resolve(E)}#Q(f){let _=this.#T.get(f.domainKey),E=this.#E.get(f.ownerId),T=_&&E?this.#V(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};this.#k(f,new i("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#$(f,_){this.#k(f,_)}#k(f,_){if(!this.#G(f))return;f.settled=!0,f.reject(_),this.#J()}#G(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),x=this.#E.get(f.ownerId);if(T&&x)this.#K(T,x,f);if(this.#I(f),_)this.#L(f.domainKey,f.ownerId);return!0}#K(f,_,E){if(f.queued=Math.max(0,f.queued-1),_.queued=Math.max(0,_.queued-1),this.#u=Math.max(0,this.#u-E.pendingBytes),f.pendingBytes=Math.max(0,f.pendingBytes-E.pendingBytes),_.pendingBytes=Math.max(0,_.pendingBytes-E.pendingBytes),E.requestClass!=="foreground")this.#U=Math.max(0,this.#U-1),f.nonForegroundQueued=Math.max(0,f.nonForegroundQueued-1),_.nonForegroundQueued=Math.max(0,_.nonForegroundQueued-1),this.#Y=Math.max(0,this.#Y-E.pendingBytes),f.nonForegroundPendingBytes=Math.max(0,f.nonForegroundPendingBytes-E.pendingBytes),_.nonForegroundPendingBytes=Math.max(0,_.nonForegroundPendingBytes-E.pendingBytes);if(E.requestClass==="internal")this.#S=Math.max(0,this.#S-1),f.internalQueued=Math.max(0,f.internalQueued-1),_.internalQueued=Math.max(0,_.internalQueued-1),this.#D=Math.max(0,this.#D-E.pendingBytes),f.internalPendingBytes=Math.max(0,f.internalPendingBytes-E.pendingBytes),_.internalPendingBytes=Math.max(0,_.internalPendingBytes-E.pendingBytes)}#I(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}#L(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(_)}#F(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.#x,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs};let E=this.#T.get(f.domainKey),T=this.#E.get(f.ownerId),x=E&&T?this.#V(E,T,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:x.resource,scope:x.scope,reason:"capacity",queuePosition:this.#t(f,x.scope),queueDepth:this.#_.length,inFlight:x.inFlight,limit:x.limit,waitMs:_,maxWaitMs:f.maxWaitMs}}#v(f,_){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#x,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs}}#t(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)}#H(f,_,E,T){return new i(f,E.scope,_.requestClass,E.resource,E.inFlight,E.limit,T,_.maxWaitMs)}}var H_;function L_(){return H_??=new G_,H_}function Z_(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 x=new WeakSet,A=0,Y=0,R=!1,h=(M)=>{if(R||M<=0)return;if(!Number.isSafeInteger(M)||M>E-A){A=E+1,R=!0;return}A+=M},U=(M)=>{if(R)return;if(Y+=1,Y>T){h(E+1);return}if(M===null){h(4);return}switch(typeof M){case"string":h(Buffer.byteLength(M,"utf8"));return;case"number":case"bigint":h(8);return;case"boolean":h(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(x.has(M))return;if(x.add(M),ArrayBuffer.isView(M)){h(32+M.byteLength);return}if(M instanceof ArrayBuffer){h(32+M.byteLength);return}if(M instanceof Date){h(40);return}if(M instanceof RegExp){h(32+Buffer.byteLength(M.source,"utf8"));return}if(M instanceof Map){h(32);for(let[P,u]of M)if(U(P),U(u),R)return;return}if(M instanceof Set){h(32);for(let P of M)if(U(P),R)return;return}if(M instanceof WeakMap||M instanceof WeakSet){h(32);return}if(Array.isArray(M)){h(16);for(let P of M)if(U(P),R)return;return}h(32);for(let P of Reflect.ownKeys(M)){if(typeof P!=="string")continue;let u=Object.getOwnPropertyDescriptor(M,P);if(!u?.enumerable||!("value"in u))continue;if(h(8+Buffer.byteLength(P,"utf8")),U(u.value),R)return}};return U(f),A}function c_(f){return Z_([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:I})}var Q_=new WeakSet;class s 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"}}var kE=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],HE=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],$E=["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 K_(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function GE(f){let _=K_(f);return HE.some((E)=>_.includes(E))}function Lf(f){if(f!==null&&typeof f==="object")Q_.add(f)}function KT(f){return f!==null&&typeof f==="object"&&Q_.has(f)}function LE(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function ZE(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 cE(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 l(f,_){let E=K_(f),T=LE(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(kE.some((A)=>E.includes(A))||GE(f))return{retryable:!1};if(_?.shouldRetry==="false")return{retryable:!1,statusCode:_.statusCode};let x=_?.statusCode??ZE(f)??cE(E);if(_?.shouldRetry==="true")return{retryable:!0,reason:x===429?"rate_limit":x===408||x===409?"timeout":"server_error",statusCode:x};if(x===429)return{retryable:!0,reason:"rate_limit",statusCode:x};if(x===408||x===409)return{retryable:!0,reason:"timeout",statusCode:x};if(x!==void 0&&x>=500&&x<=599)return{retryable:!0,reason:"server_error",statusCode:x};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:x};if($E.some((A)=>E.includes(A)))return{retryable:!0,reason:"transport",statusCode:x};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:x};return{retryable:!1,statusCode:x}}function Zf(f,_){if(!f)return;if(f.retryAfterMs!==void 0){let x=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(x))return Math.max(0,x)}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 I_(f,_,E={}){let T=E.now??Date.now(),x=E.maxDelayMs??60000,A=Zf(_,T);if(A!==void 0)return Math.min(Math.ceil(A),x);let Y=Math.max(0,f-1),R=E.maxExponentialDelayMs??8000,h=Math.min(500*2**Y,R),U=Math.max(0,Math.min(1,E.random??Math.random())),M=h*(0.75+U*0.25);return Math.min(Math.round(M),x)}function t_(f,_){let E=f.onPayload;f.onPayload=async(T,x)=>{let A=E?await E(T,x):T;return _(A===void 0?T:A,x)}}function QE(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function KE(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function IE(f,_,E,T){let x=T?void 0:QE(E);if(!x){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=x;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:KE(x)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=x;break;default:f.reasoningEffort=x}}function FE(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 vE(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;t_(f,(x)=>{if(!x||typeof x!=="object"||Array.isArray(x))return x;return _.api==="anthropic-messages"?{...x,speed:"fast"}:{...x,service_tier:T}})}function tE(f,_,E){let T=E.responseVerbosity;if(!T)return;if(v_(_,T),_.api==="openai-codex-responses"){f.textVerbosity=T;return}t_(f,(x)=>{if(!x||typeof x!=="object"||Array.isArray(x))return x;if(_.api==="openai-completions")return{...x,verbosity:T};let A="text"in x&&x.text&&typeof x.text==="object"&&!Array.isArray(x.text)?x.text:{};return{...x,text:{...A,verbosity:T}}})}function w_(f,_,E,T,x=!1){let A={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:f.enablePromptCaching?"short":"none"};if(IE(A,_,f,x),FE(A,_.api,T?.toolChoice?.toolName),vE(A,_,f),tE(A,_,f),_.api==="azure-openai-responses")A.azureBaseUrl=f.baseUrl,A.azureApiVersion=f.apiVersion,A.azureDeploymentName=_.id;return A}function F_(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 wE=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function p_(f,_,E){let T=f.onResponse;if(f.onResponse=async(A,Y)=>{let R=new Headers(A.headers);E(F_(A.status,R)),await T?.(A,Y)},!wE.has(_.api)||typeof globalThis.fetch!=="function")return;let x=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(A,Y)=>{let R=await x(A,Y);return E(F_(R.status,R.headers)),R}}function q_(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 Yf=300000,pE=30000;class m_ 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 s_ extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function cf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function qE(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Yf}function mE(f,_){if(_===0)return;let E=_!==void 0&&_>0?_:pE;return Math.max(1,Math.min(E,Math.floor(f/2)))}function sE(f,_,E){if(E?.aborted)return Promise.reject(cf(E));return new Promise((T,x)=>{let A=!1,Y=()=>{clearTimeout(M),E?.removeEventListener("abort",U)},R=(P)=>{if(A)return;A=!0,Y(),T(P)},h=(P)=>{if(A)return;A=!0,Y(),x(P instanceof Error?P:Error(String(P)))},U=()=>{if(E)h(cf(E))},M=setTimeout(()=>R({kind:"timer"}),Math.max(0,_));if(E?.addEventListener("abort",U,{once:!0}),E?.aborted){U();return}f.then((P)=>R({kind:"next",result:P}),h)})}async function*lE(f,_,E){let T=qE(_),x=mE(T,_.stallWarningMs);if(_.signal?.aborted)throw cf(_.signal);let A=Date.now(),Y=Promise.resolve().then(()=>f.next()),R;for(;;){let U=await sE(Y,(R?T:x??T)-(Date.now()-A),_.signal);if(U.kind==="next"){if(R)yield{...R,phase:"recovered",durationMs:Math.max(R.durationMs,Date.now()-A)};return U.result}if(!R&&x!==void 0){E.stallCount++,R={phase:"detected",stallCount:E.stallCount,durationMs:x,warningAfterMs:x,timeoutMs:T,outputStarted:E.outputStarted},yield R;continue}let M=new m_(T);throw _.abort?.(M),M}}async function*l_(f,_,E,T,x={}){let Y=f.stream(_,E,T)[Symbol.asyncIterator](),R=0,h=!1,U={stallCount:0,outputStarted:!1};try{while(!0){let M=lE(Y,x,U),P=await M.next();while(!P.done)yield{providerStall:P.value},P=await M.next();let u=P.value;if(u.done)throw new s_;let D=u.value;switch(D.type){case"text_delta":U.outputStarted=!0,yield{content:D.delta};break;case"thinking_delta":U.outputStarted=!0,yield{reasoningContent:D.delta};break;case"toolcall_end":U.outputStarted=!0,yield{toolCalls:[{index:R++,id:D.toolCall.id,type:"function",function:{name:D.toolCall.name,arguments:JSON.stringify(D.toolCall.arguments)}}]};break;case"done":h=!0,yield{finishReason:D.reason,usage:q_(D.message.usage)};return;case"error":throw Error(D.error.errorMessage??`Request ${D.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!h)Promise.resolve(Y.return?.()).catch(()=>{return})}}var a_=q("Chat"),aE=1;function yE(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((_)=>_.type==="image_url"))}function gE(f,_){let E=l(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 x=Zf(_,Date.now());return{reason:E.reason,...T!==void 0?{statusCode:T}:{},...x!==void 0?{retryAfterMs:x}:{}}}function oE(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class If{config;models;model;admissionFallbackOwnerId=`pi-service-${process.pid}-${aE++}`;constructor(f){let _=jf(f);this.config={...f,maxContextTokens:_.model.contextWindow,maxOutputTokens:f.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,a_.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,_,E,T){let x="",A="",Y=[],R,h;for await(let U of this.streamChat(f,_,E,T)){x+=U.content??"",A+=U.reasoningContent??"";for(let M of U.toolCalls??[])if(M.id&&M.type==="function"&&M.function?.name)Y.push(M);R=U.usage??R,h=U.finishReason??h}return{content:x,...A?{reasoningContent:A}:{},...Y.length>0?{toolCalls:Y}:{},usage:R,finishReason:h}}async*streamChat(f,_,E,T){let x=T?.toolChoice?.toolName;if(x&&!_?.some((S)=>S.name===x))throw Error(`Required tool is unavailable: ${x}`);let A=df(f);if(A.some((S)=>yE(S))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let Y=Boolean(x)||rf(A),R=await of(A,this.model,_,E,x),h=c_({messages:A,context:R,tools:_,requestOptions:T}),U=T?.providerRecovery;if(U&&!g_(U.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let M=U?.mode==="bounded_foreground"&&U.budgetMs>0?{budgetMs:U.budgetMs,startedAt:void 0}:void 0,P=M?"bounded_foreground":"standard",u=this.config.maxRetries??2,D=this.config.maxRetries??(M?y_:2),G=M!==void 0&&this.config.maxRetries===void 0,L=0,Q,Pf=this.config.providerCircuitRegistry??h_(),ff=this.config.providerCircuitBreakerOpenMs??zf,Uf=Math.max(Af,Math.min(this.config.streamIdleTimeout??Yf,Xf)),o_=this.config.providerRequestAdmissionScheduler??L_(),d_=this.config.providerRequestConcurrency??Hf,Ff=this.config.providerRequestAdmissionMs??$f,r_=this.config.providerRequestPendingBytes??Gf,uf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},e_=(S)=>Pf.get({provider:S.provider,api:S.api,baseUrl:S.baseUrl??this.config.baseUrl??"",model:S.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,openDurationMs:ff,probeLeaseMs:Uf}),i_=(S)=>({provider:S.provider,api:S.api,baseUrl:S.baseUrl??this.config.baseUrl??"",model:S.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,maxConcurrent:d_,maxPendingBytes:r_}),C=(S=Date.now())=>{if(!M)return;let O=M.startedAt===void 0?0:Math.min(M.budgetMs,Math.max(0,S-M.startedAt));return{recoveryBudgetMs:M.budgetMs,recoveryElapsedMs:O,recoveryRemainingMs:Math.max(0,M.budgetMs-O)}},F=()=>({mode:P,...C()??{}}),vf=()=>{if(M&&M.startedAt===void 0)M.startedAt=Date.now()},v=()=>{let S=C();return new s(M?.budgetMs??0,S?.recoveryElapsedMs??0)},a=()=>!G||L<D+1,Df=(S,O)=>{let{state:W,...V}=O;return{phase:S,...V,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}},tf=(S)=>({phase:"rejected",requestClass:S.requestClass,resource:S.resource,scope:S.scope,reason:S.reason,queuePosition:0,queueDepth:Math.max(0,S.queued),inFlight:Math.max(0,S.inFlight),limit:Math.max(0,S.limit),waitMs:S.reason==="wait_timeout"?S.maxWaitMs:0,maxWaitMs:S.maxWaitMs,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),n_=async function*(S){let O=C()?.recoveryRemainingMs,W=O!==void 0&&M?.startedAt!==void 0?Math.min(Ff,O):Ff,V;try{V=o_.admit({scope:i_(S),sessionId:uf.sessionId,ownerId:uf.ownerId,requestClass:uf.requestClass,maxWaitMs:W,pendingBytes:h,signal:E})}catch(N){if(n(N)){if(N.reason==="wait_timeout"&&M?.startedAt!==void 0&&(C()?.recoveryRemainingMs??0)<=0)throw v();yield{providerAdmission:tf(N)}}throw N}let c=V.getSnapshot();if(c.state==="admitted")return await V.ready;yield{providerAdmission:Df("queued",c)};let K=V.ready.then((N)=>({kind:"ready",permit:N}),(N)=>({kind:"error",error:N}));while(!0){let N=V.getSnapshot(),J=Math.max(1,Math.min($_,Math.max(1,W-N.waitMs))),k,X=new Promise((t)=>{k=setTimeout(()=>t({kind:"heartbeat"}),J),k.unref?.()}),H=await Promise.race([K,X]);if(k)clearTimeout(k);if(H.kind==="heartbeat"){yield{providerAdmission:Df("queued",V.getSnapshot())};continue}if(H.kind==="error"){if(n(H.error)){if(H.error.reason==="wait_timeout"&&M?.startedAt!==void 0&&(C()?.recoveryRemainingMs??0)<=0)throw v();yield{providerAdmission:tf(H.error)}}throw H.error}return yield{providerAdmission:Df("admitted",V.getSnapshot())},H.permit}},fE=(S)=>{if(!a())throw v();if(G)L++;Q=void 0;let O=new AbortController,W=E?yf(E,O.signal):O.signal,V;if(M?.startedAt!==void 0){let N=C()?.recoveryRemainingMs??0;if(N<=0)throw v();let J=new s(M.budgetMs,M.budgetMs);V=setTimeout(()=>O.abort(J),N),V.unref?.()}let c=w_(this.config,S,W,T,Y);p_(c,S,(N)=>{Q=N});let K=l_(this.models,S,R,c,{idleTimeoutMs:this.config.streamIdleTimeout??Yf,signal:W,abort:(N)=>O.abort(N)});return async function*(){try{yield*K}finally{if(V)clearTimeout(V)}}()},wf=this,p=(S)=>({phase:S.phase,reason:S.reason,...S.statusCode!==void 0?{statusCode:S.statusCode}:{},...S.retryAfterMs!==void 0?{retryAfterMs:S.retryAfterMs}:{},...S.nextProbeAt!==void 0?{nextProbeAt:S.nextProbeAt}:{},openDurationMs:S.openDurationMs,sampleCount:S.sampleCount,failureCount:S.failureCount,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),pf=(S,O)=>({phase:S,reason:O.reason,...O.statusCode!==void 0?{statusCode:O.statusCode}:{},retryAfterMs:O.retryAfterMs,...O.nextProbeAt!==void 0?{nextProbeAt:O.nextProbeAt}:{},openDurationMs:O.openDurationMs,sampleCount:O.sampleCount,failureCount:O.failureCount,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),_E=(S)=>({phase:"probe",reason:S.reason??"server_error",...S.statusCode!==void 0?{statusCode:S.statusCode}:{},openDurationMs:S.openDurationMs??ff,...S.sampleCount!==void 0?{sampleCount:S.sampleCount}:{},...S.failureCount!==void 0?{failureCount:S.failureCount}:{},...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),Of=(S,O,W)=>({providerRetry:{phase:"exhausted",attempt:S,maxRetries:D,reason:O,...W!==void 0?{statusCode:W}:{},...F(),exhaustedBy:"recovery_budget"}}),qf=async function*(S,O,W,V){let c,K=!1,N,J,k=e_(S);for(let X=0;X<=W;X++){if(!a())break;let H,t;while(!H){let B=k.preflight();while(!B.eligible){if(N=B.reason,J=B.statusCode,!M||!V){let Z=pf("rejected",B);throw yield{providerCircuit:Z},new e(Z)}vf();let b=C()?.recoveryRemainingMs??0;if(b<=0){let Z=v();throw yield Of(G?Math.max(0,L-1):X,B.reason,B.statusCode),Z}yield{providerCircuit:pf("waiting",B)};let w=Math.min(Math.max(1,B.retryAfterMs),Qf,b);if(await d(w,E,{throwOnAbort:!0}),(C()?.recoveryRemainingMs??0)<=0){let Z=v();throw yield Of(G?Math.max(0,L-1):X,B.reason,B.statusCode),Z}B=k.preflight()}try{t=yield*n_(S)}catch($){if($ instanceof s)yield Of(G?Math.max(0,L-1):X,N??"timeout",J);throw $}let z=k.check();if(z.allowed)H=z;else t.release(),t=void 0}let y=H.token;if(H.probe)yield{providerCircuit:_E(H)};try{let B=!1,z=!1;for await(let $ of fE(S)){if($.providerStall){yield $;continue}let b=G?L-1:X;if(b>0&&N&&!B)B=!0,yield{providerRetry:{phase:"recovered",attempt:b,maxRetries:D,reason:N,...J!==void 0?{statusCode:J}:{},...F()}};if(!z){z=!0;let w=k.recordSuccess(y);if(w)yield{providerCircuit:p(w)}}K=!0,O(),yield $}if(!z){let $=k.recordSuccess(y);if($)yield{providerCircuit:p($)}}return}catch(B){if(t?.release(),c=B,wf.logIdleTimeout(B,K,S),await wf.handleAbort(E),B instanceof s){if(K)throw Lf(B),B;throw yield{providerRetry:{phase:"exhausted",attempt:G?Math.max(0,L-1):X,maxRetries:D,reason:N??"timeout",...J!==void 0?{statusCode:J}:{},...F(),exhaustedBy:"recovery_budget"}},B}let z=l(B,Q);if(K)throw Lf(B),B;let $=gE(B,Q),b=$?k.recordFailure(y,$):Q&&!oE(B)?k.recordNeutral(y):void 0;if(b)yield{providerCircuit:p(b)};if(!z.retryable||!z.reason){if(X>0&&N)yield{providerRetry:{phase:"exhausted",attempt:G?Math.max(0,L-1):X,maxRetries:D,reason:N,...J!==void 0?{statusCode:J}:{},...F()}};throw B}N=z.reason,J=z.statusCode;let w=X<W&&a();if(b&&b.phase!=="closed"&&w&&(!M||!V)){let Z={...p(b),phase:"rejected"};throw yield{providerCircuit:Z},new e(Z)}if(w){vf();let Z=G?L:X+1,TE=I_(Z,Q,M?{maxDelayMs:Kf,maxExponentialDelayMs:Kf}:void 0),sf=b&&b.phase!=="closed"?b.retryAfterMs??0:0;if(M&&sf>0&&b)yield{providerCircuit:{...p(b),phase:"waiting"}};let xE=C(),Bf=Math.max(TE,sf),g=M?Math.min(Bf,xE?.recoveryRemainingMs??Bf):Bf,Ef={attempt:Z,maxRetries:D,reason:z.reason,...z.statusCode!==void 0?{statusCode:z.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Ef,delayMs:g,nextRetryAt:Date.now()+g,...F()}},M){let o=g;while(o>0){let lf=Math.min(o,Qf);if(await d(lf,E,{throwOnAbort:!0}),o-=lf,(C()?.recoveryRemainingMs??0)<=0){let Tf=v();throw yield{providerRetry:{phase:"exhausted",...Ef,...F(),exhaustedBy:"recovery_budget"}},Tf}if(o>0){if(b&&b.phase!=="closed"&&b.nextProbeAt!==void 0){let Tf=Math.max(0,b.nextProbeAt-Date.now());if(Tf>0)yield{providerCircuit:{...p(b),phase:"waiting",retryAfterMs:Tf}}}yield{providerRetry:{phase:"waiting",...Ef,delayMs:g,nextRetryAt:Date.now()+o,...F()}}}}}else await d(g,E,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Ef,...F()}}}else yield{providerRetry:{phase:"exhausted",attempt:G?Math.max(0,L-1):X,maxRetries:D,reason:z.reason,...z.statusCode!==void 0?{statusCode:z.statusCode}:{},...F(),...M&&(V||!a())?{exhaustedBy:"attempt_limit"}:{}}}}finally{k.abandon(y),t?.release()}}throw c},Nf,mf=!1,_f=this.config.fallbackModels??[],EE=M&&_f.length>0?Math.min(u,D):D;try{for await(let S of qf(this.model,()=>{mf=!0},EE,_f.length===0))yield S;return}catch(S){if(Nf=S,mf||!n(S)&&!Jf(S)&&!l(S,Q).retryable)throw S}for(let[S,O]of _f.entries()){if(!a())break;yield{modelFallback:!0};let W=!1;try{let V=f_(this.config,O),c=S===_f.length-1,K=M&&!c?Math.min(u,D):D;for await(let N of qf(V,()=>{W=!0},K,c))yield N;return}catch(V){if(Nf=V,W||!n(V)&&!Jf(V)&&!l(V,Q).retryable)throw V}}throw Nf}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;a_.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=jf(_);this.config={..._,maxContextTokens:E.model.contextWindow,maxOutputTokens:_.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model}}var dE=q("Service");async function Tx(f){let _=f;if(_.provider){let E=af(_.provider);if(Object.keys(E).length>0)_={..._,customHeaders:{...E,..._.customHeaders}},dE.debug(`Injected ${_.provider} specific headers:`,Object.keys(E))}return rE(_)}function rE(f){return new If(f)}
5
- export{nE as Id,ET as Jd,yf as Kd,n as Ld,Z_ as Md,GE as Nd,KT as Od,If as Pd,Tx as Qd};
5
+ export{nE as Kd,ET as Ld,yf as Md,n as Nd,Z_ as Od,GE as Pd,KT as Qd,If as Rd,Tx as Sd};
@@ -1,3 +1,3 @@
1
- import{Vg as $,Wg as F}from"./chunk-m3dvta6k.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
1
+ import{eh as $,fh as F}from"./chunk-qb0sqh29.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
2
2
  `,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
3
3
  export{_ as l};
@@ -0,0 +1 @@
1
+ import{Td as a,Ud as b,Vd as c}from"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
@@ -1,3 +1,3 @@
1
- import{Wg as j}from"./chunk-m3dvta6k.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
1
+ import{fh as j}from"./chunk-qb0sqh29.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
2
2
  `)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
3
- export{m as qg,I as rg,M as sg,V as tg,h as ug};
3
+ export{m as Bg,I as Cg,M as Dg,V as Eg,h as Fg};