blade-code 0.10.139 → 0.10.141
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-jb4hmk56.js → chunk-0b67y4j1.js} +2 -2
- package/dist/{chunk-5w8pmsqe.js → chunk-0chvj0qt.js} +2 -2
- package/dist/chunk-0s0er9wr.js +1 -0
- package/dist/{chunk-1bqatrxs.js → chunk-28tzj187.js} +1 -1
- package/dist/chunk-2b3j2egw.js +1 -0
- package/dist/{chunk-bgzj85za.js → chunk-34fmx68h.js} +1 -1
- package/dist/{chunk-05cv54r8.js → chunk-3da7sqx6.js} +1 -1
- package/dist/chunk-3kszepm6.js +2 -0
- package/dist/chunk-44edbaa1.js +1 -0
- package/dist/{chunk-mh3ne2sf.js → chunk-4dtshx9v.js} +2 -2
- package/dist/{chunk-dw0mewc2.js → chunk-4pexd8a7.js} +2 -2
- package/dist/{chunk-5qwpdx3n.js → chunk-4w8v677q.js} +1 -1
- package/dist/chunk-514va7ce.js +2 -0
- package/dist/{chunk-ft1bdqbs.js → chunk-5q4z0sfr.js} +2 -2
- package/dist/{chunk-gc4kj295.js → chunk-5v3eng7c.js} +1 -1
- package/dist/chunk-5vxhttdq.js +10 -0
- package/dist/{chunk-f4cn6v8t.js → chunk-6w8p6c0g.js} +2 -2
- package/dist/{chunk-25r1v5rn.js → chunk-7azws27d.js} +43 -43
- package/dist/chunk-7g76xzzg.js +2 -0
- package/dist/{chunk-d64b7wta.js → chunk-7wcxjbyg.js} +1 -1
- package/dist/{chunk-5j68055h.js → chunk-7xhw74hk.js} +1 -1
- package/dist/{chunk-t88sfhjj.js → chunk-7xtxvrh8.js} +1 -1
- package/dist/{chunk-esff371k.js → chunk-83je3g6c.js} +3 -3
- package/dist/chunk-8tvf39jm.js +1 -0
- package/dist/{chunk-65c3vjwm.js → chunk-9kj19a8t.js} +1 -1
- package/dist/{chunk-6ezffjq1.js → chunk-9tk6wq70.js} +1 -1
- package/dist/{chunk-zx78c1an.js → chunk-9xbwtjac.js} +1 -1
- package/dist/{chunk-40pd090k.js → chunk-ae0fws1f.js} +2 -2
- package/dist/chunk-be1fyzb3.js +181 -0
- package/dist/{chunk-3ekz3zms.js → chunk-cbgsjzdw.js} +2 -2
- package/dist/chunk-enf0egke.js +1 -0
- package/dist/{chunk-az08pq83.js → chunk-erhaedch.js} +1 -1
- package/dist/{chunk-mtfjwsn2.js → chunk-f2jm4x5q.js} +2 -2
- package/dist/{chunk-bq6d0v5b.js → chunk-f2y0gxyq.js} +2 -2
- package/dist/chunk-f5t7a64t.js +1 -0
- package/dist/{chunk-8py443a5.js → chunk-frvdjy8y.js} +1 -1
- package/dist/{chunk-1h3736q2.js → chunk-fx4xr1g6.js} +365 -361
- package/dist/{chunk-awheqy52.js → chunk-fx9vm1n5.js} +2 -2
- package/dist/{chunk-jy7k2dwm.js → chunk-gm2yfq3r.js} +2 -2
- package/dist/chunk-h273dnvq.js +1 -0
- package/dist/{chunk-2jq9ed09.js → chunk-h5xad96g.js} +1 -1
- package/dist/{chunk-rhwkvx96.js → chunk-hv8nt7wj.js} +1 -1
- package/dist/{chunk-7pg5y3pg.js → chunk-j1pptwsq.js} +1 -1
- package/dist/chunk-j7784bxm.js +1 -0
- package/dist/{chunk-8rccn1y2.js → chunk-jbpasjg9.js} +1 -1
- package/dist/chunk-jr402gf8.js +1 -0
- package/dist/{chunk-dv2m2xe5.js → chunk-jsv3e4k6.js} +1 -1
- package/dist/{chunk-grx6fv9w.js → chunk-k1tfry97.js} +2 -2
- package/dist/{chunk-hrcz179j.js → chunk-k3ne93k8.js} +2 -2
- package/dist/{chunk-mec8yedz.js → chunk-kf9j9z9k.js} +1 -1
- package/dist/{chunk-fbrdcveb.js → chunk-n34qsnks.js} +1 -1
- package/dist/{chunk-earhezc8.js → chunk-n9819k4p.js} +1 -1
- package/dist/{chunk-6j5v5emj.js → chunk-ppp4gpy4.js} +6 -6
- package/dist/{chunk-9m7d3ajv.js → chunk-pv6cgfv1.js} +1 -1
- package/dist/{chunk-zz5n2qxk.js → chunk-pzxg2sdv.js} +1 -1
- package/dist/{chunk-x3c718v5.js → chunk-r5dmdsjb.js} +2 -2
- package/dist/{chunk-a5hkv8er.js → chunk-rv80nkve.js} +2 -2
- package/dist/{chunk-cefmcwyv.js → chunk-ryyzbd76.js} +2 -2
- package/dist/chunk-s56t6kzj.js +2 -0
- package/dist/{chunk-npc7jt96.js → chunk-sd9bze9x.js} +1 -1
- package/dist/{chunk-516adpx6.js → chunk-sdapqhj0.js} +1 -1
- package/dist/chunk-se0q0p3v.js +1 -0
- package/dist/chunk-sz5g7eh5.js +1 -0
- package/dist/{chunk-sdhdn0yx.js → chunk-tp4yy3a6.js} +3 -3
- package/dist/{chunk-04t21rey.js → chunk-tqg9y2p6.js} +1 -1
- package/dist/{chunk-7j4s1nrc.js → chunk-tya95jej.js} +1 -1
- package/dist/{chunk-6qhbdcse.js → chunk-v1mamd1x.js} +2 -2
- package/dist/{chunk-v2fewxvw.js → chunk-v67st2xb.js} +2 -2
- package/dist/chunk-wemdt9n6.js +6 -0
- package/dist/{chunk-3eskgvpy.js → chunk-wm896gnx.js} +1 -1
- package/dist/chunk-yjbpfd3b.js +1 -0
- package/dist/{chunk-qrv72yy6.js → chunk-ze1ra6f9.js} +2 -2
- package/dist/{chunk-sj4gz23a.js → chunk-zj32chp7.js} +1 -1
- package/dist/chunk-znrafpad.js +1 -0
- package/dist/chunk-zqjm9yd8.js +1 -0
- package/dist/{chunk-16648v5c.js → chunk-zrgfvc4k.js} +1 -1
- package/dist/web/assets/ChatView-BBYsaZIk.js +63 -0
- package/dist/web/assets/{CodeBlockHighlighter-CYhxXWvb.js → CodeBlockHighlighter-BC17_i4m.js} +1 -1
- package/dist/web/assets/{FilePreview-ByTaE1GR.js → FilePreview-DuvfuHLi.js} +1 -1
- package/dist/web/assets/{KanbanBoard-KMmGvNPc.js → KanbanBoard-B-Z7lSaC.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-C6lKOJaG.js → MarkdownRenderer-DF-nYnJu.js} +3 -3
- package/dist/web/assets/{ScrollArea-Bo6cZ3PH.js → ScrollArea-dipnxnqf.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-Cymc4xw0.js → SessionHistorySurface-CnMBkiZW.js} +1 -1
- package/dist/web/assets/{SettingsModal-D36xhHwa.js → SettingsModal-DLA1WQ6g.js} +1 -1
- package/dist/web/assets/{Sidebar-DEGQINYb.js → Sidebar-tu4OcImk.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BEISb7-8.js → TaskSwitcher-D2TIUyr3.js} +1 -1
- package/dist/web/assets/{TerminalPanel-B7PXaRGh.js → TerminalPanel-CcJVvSnz.js} +1 -1
- package/dist/web/assets/{archive-Dyn5Oz68.js → archive-EoUobrxu.js} +1 -1
- package/dist/web/assets/{arrow-left-mWU3P1zb.js → arrow-left-Y8E5lnQ1.js} +1 -1
- package/dist/web/assets/{calendar-clock-B6b0Cb3d.js → calendar-clock-Cl0Spu99.js} +1 -1
- package/dist/web/assets/{chevron-right-Cl6g5_0e.js → chevron-right-DmM1dl1s.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-FKryGzO4.js → chevrons-up-down-DFQNAYac.js} +1 -1
- package/dist/web/assets/{clock-3-CfVjvMmA.js → clock-3-D3dzsSrc.js} +1 -1
- package/dist/web/assets/{copy-CIYuf7du.js → copy-BwNmbccC.js} +1 -1
- package/dist/web/assets/{download-DecDFX8n.js → download-DHzGZhJT.js} +1 -1
- package/dist/web/assets/{external-link-DaSwvjf7.js → external-link-Dr_8T3Ah.js} +1 -1
- package/dist/web/assets/{folder-DZtlKvFm.js → folder-DcgRdL_P.js} +1 -1
- package/dist/web/assets/index-BZZUIkal.js +203 -0
- package/dist/web/assets/{pause-Bd-STGLc.js → pause-DXzNhd_w.js} +1 -1
- package/dist/web/assets/{pencil-BoTIqqxX.js → pencil-CYRCKPnu.js} +1 -1
- package/dist/web/assets/{play-C4ctis0t.js → play-CfNxuNSd.js} +1 -1
- package/dist/web/assets/{plus-D08TlGJu.js → plus-DBUPwsji.js} +1 -1
- package/dist/web/assets/session-events-DTVYDdaH.js +29 -0
- package/dist/web/assets/{settings-BGRhMFaU.js → settings-K2UJIIf_.js} +1 -1
- package/dist/web/assets/{team-CPme0l2K.js → team-BoulGGnJ.js} +1 -1
- package/dist/web/assets/{teamService-CVCtTVfY.js → teamService-Cfm0Cd6e.js} +1 -1
- package/dist/web/assets/{terminal-D7GsyYki.js → terminal-C9ZyLrcq.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-2agbk8ef.js +0 -1
- package/dist/chunk-2bty4510.js +0 -6
- package/dist/chunk-2f7nr9hh.js +0 -1
- package/dist/chunk-2t9vtt75.js +0 -1
- package/dist/chunk-3aaehgva.js +0 -1
- package/dist/chunk-3t5r41yh.js +0 -1
- package/dist/chunk-5xgyx25z.js +0 -2
- package/dist/chunk-gjc1hhhv.js +0 -1
- package/dist/chunk-gx4seq5c.js +0 -10
- package/dist/chunk-h2gp7smy.js +0 -1
- package/dist/chunk-mc2mr1kn.js +0 -2
- package/dist/chunk-mkckss82.js +0 -1
- package/dist/chunk-ntpwqfy3.js +0 -1
- package/dist/chunk-q82ntq7t.js +0 -1
- package/dist/chunk-recafw5r.js +0 -171
- package/dist/chunk-smjfqtws.js +0 -1
- package/dist/chunk-wazhd8bm.js +0 -1
- package/dist/chunk-wf4s1hp2.js +0 -1
- package/dist/chunk-yvmexv2c.js +0 -2
- package/dist/chunk-z9qv0d6k.js +0 -1
- package/dist/web/assets/ChatView-CQnuGDqk.js +0 -63
- package/dist/web/assets/index-DQaqO-lw.js +0 -203
- package/dist/web/assets/session-events-DKjIMNKI.js +0 -29
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{A as
|
|
1
|
+
import{Gj as b,Hj as k,Jj as w}from"./chunk-5q4z0sfr.js";function g(j){return b.Object(j,{additionalProperties:!1})}var W=b.String({pattern:"^acp-remote-workspace:[A-Za-z0-9_-]{43}$"}),I=b.Optional(b.Integer({minimum:1,maximum:100})),x=b.String({minLength:1,maxLength:200,pattern:"^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$"}),A=k(b.Union([g({version:b.Literal(2),sessionId:x,workspace:g({kind:b.Literal("local"),projectPath:b.String({minLength:1})})}),g({version:b.Literal(2),sessionId:x,workspace:g({kind:b.Literal("acp-remote"),workspaceRef:W})})])),C=k(w(["history-only","owner-offline","owner-mismatch","archived","surface-not-supported","capability-not-advertised"])),X=k(g({connection:w(["local","online","offline"]),history:g({read:b.Boolean(),fork:b.Boolean()}),turn:g({start:b.Boolean(),reason:b.Optional(C)}),files:g({readText:b.Boolean(),writeText:b.Boolean(),browse:w(["none","known-files","tree"]),reason:b.Optional(C)}),terminal:g({mode:w(["none","command","interactive"]),owner:w(["none","local","acp-remote"]),reason:b.Optional(C)})})),Y=k(g({id:b.String({pattern:"^surface-message:[0-9]+:.+$"}),role:w(["user","assistant"]),content:b.String(),timestamp:b.String({minLength:1}),truncated:b.Optional(b.Boolean())})),Z=w(["queued","running","completed","failed","cancelled","interrupted"]),_=w(["posix","win32"]),$=w(["subagent","fork"]),D=b.String({minLength:1}),J=b.String({minLength:1}),z=40,H=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-](\d{2}):(\d{2}))$/,M="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}Z$";function T(j){return j%4===0&&(j%100!==0||j%400===0)}function R(j,q){if(q===2)return T(j)?29:28;return[4,6,9,11].includes(q)?30:31}function d(j){if(j===void 0||j.length<20||j.length>z)return;let q=H.exec(j);if(!q)return;let L=Number(q[1]),B=Number(q[2]),E=Number(q[3]),N=Number(q[4]),O=Number(q[5]),P=Number(q[6]),Q=q[8],U=Number(q[9]),V=Number(q[10]);if(B<1||B>12||E<1||E>R(L,B)||N>23||O>59||P>59||Q!=="Z"&&(U>23||V>59))return;let F=Date.parse(j);if(!Number.isFinite(F))return;let G=new Date(F).toISOString();return G.length===24?G:void 0}var S=b.Refine(b.String({minLength:24,maxLength:24,pattern:M}),(j)=>d(j)===j,()=>"must be a canonical ISO instant"),K=k(g({locator:A,displayCwd:b.String({minLength:1}),pathStyle:b.Optional(_),title:b.Optional(b.String()),rootId:x,parentId:b.Optional(x),relationType:b.Optional($),taskStatus:Z,taskCompletedAt:b.Optional(S),messageCount:b.Integer({minimum:0}),firstMessageTime:b.String({minLength:1}),lastMessageTime:b.String({minLength:1}),hasErrors:b.Boolean(),archivedAt:b.Optional(b.String({minLength:1})),selectedModelId:b.Optional(b.String({minLength:1})),capabilities:X})),p=k(w(["invalid_session_surface_request","invalid_session_locator","session_surface_not_found","workspace_binding_mismatch","session_surface_cursor_invalid","session_surface_snapshot_changed","session_surface_read_only","session_surface_capability_unavailable","session_surface_capacity","session_surface_unavailable","session_surface_state_invalid"])),i=k(g({error:g({code:p,message:b.String({minLength:1}),retryable:b.Boolean()})})),s=k(g({sessions:b.Array(K),nextCursor:b.Optional(D)})),f=k(g({messages:b.Array(Y),olderCursor:b.Optional(D),snapshot:J,truncated:b.Boolean()})),v=k(g({locator:A,limit:I})),l=k(g({session:K,history:f})),r=k(g({locator:A,cursor:D,expectedSnapshot:J,limit:I})),n=k(g({locator:A}));
|
|
2
|
+
export{A as ff,Y as gf,d as hf,K as if,i as jf,s as kf,f as lf,v as mf,l as nf,r as of,n as pf};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Xj as C,Yj as I}from"./chunk-earhezc8.js";import{Zj as _}from"./chunk-t88sfhjj.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
|
|
1
|
+
import{ck as C,dk as I}from"./chunk-n9819k4p.js";import{ek as _}from"./chunk-7xtxvrh8.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
|
|
2
2
|
`,{mode:384}),await B.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await B.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await B.mkdir(this.storeDir,{recursive:!0,mode:448}),await B.chmod(this.storeDir,448)}}}
|
|
3
|
-
export{R as
|
|
3
|
+
export{R as $j,t as ak,x as bk};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{k as a,l as b,m as c,n as d,o as e}from"./chunk-tqg9y2p6.js";import"./chunk-f2jm4x5q.js";import"./chunk-sdapqhj0.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{rc as Xt,sc as En,tc as yn,uc as bn}from"./chunk-wm896gnx.js";import{yh as Bt}from"./chunk-tp4yy3a6.js";import{$h as Gt,Dh as xt,Eh as vi,Fh as sn,Gh as zt,Hh as U,Ih as en,Jh as gt,Kh as mt,Mh as rn,Nh as Tn,Oh as B,Ph as dn,Qh as on,Rh as pn,Sh as lt,Th as un,Uh as cn,Vh as Mn,Xh as S,_h as wn,ai as Ut,bi as h,ci as Ht}from"./chunk-ae0fws1f.js";import{aj as It}from"./chunk-jsv3e4k6.js";import{Ej as X,Gj as x}from"./chunk-5q4z0sfr.js";import{Wj as tn,Xj as nn}from"./chunk-f2jm4x5q.js";import{Lk as ns}from"./chunk-sdapqhj0.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Qa as H}from"./chunk-
|
|
1
|
+
import{Qa as H}from"./chunk-h5xad96g.js";import"./chunk-wm896gnx.js";import"./chunk-9xbwtjac.js";import{Xf as $,bg as T}from"./chunk-r5dmdsjb.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-tp4yy3a6.js";import"./chunk-28tzj187.js";import"./chunk-ae0fws1f.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import{aj as k}from"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-f2jm4x5q.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{og as a}from"./chunk-k1tfry97.js";import"./chunk-f2y0gxyq.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{a as createChatServiceAsync};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-sdapqhj0.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ae as a,be as b,ce as c,de as d,ee as e,fe as f,ge as g}from"./chunk-ryyzbd76.js";import"./chunk-9xbwtjac.js";import"./chunk-rv80nkve.js";import"./chunk-fx9vm1n5.js";import"./chunk-7wcxjbyg.js";import"./chunk-hv8nt7wj.js";import"./chunk-28tzj187.js";import"./chunk-514va7ce.js";import"./chunk-jsv3e4k6.js";import"./chunk-5q4z0sfr.js";import"./chunk-9kj19a8t.js";import"./chunk-f2jm4x5q.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as Zi,D as _i,P as $i,V as aj};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{qg as of}from"./chunk-f2y0gxyq.js";import{ej as t_,fj as yf,gj as af,hj as R_,ij as Lf,kj as Gf,mj as Hf,oj as g,pj as Cf,rj as Uf,sj as Ff,uj as s}from"./chunk-n34qsnks.js";import{Cj as a}from"./chunk-5q4z0sfr.js";import{Mj as IE,Oj as Jf}from"./chunk-0b67y4j1.js";import{Rj as eE}from"./chunk-9kj19a8t.js";var B_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},RE=(f)=>B_[f]||{};var b_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function cf(f){return typeof f==="string"&&b_.has(f)}function LT(f){if(!f.aborted)return;if(cf(f.reason))return f.reason;return"user-cancel"}function ZT(f){if(cf(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 PE(...f){let E=f.filter(Boolean);if(E.length===0)return new AbortController().signal;if(E.length===1)return E[0];let _=AbortSignal;if(typeof _.any==="function")return _.any(E);for(let x of E)if(x.aborted)return x;let T=new AbortController,h=new Map;for(let x of E){let N=()=>{T.abort(x.reason);for(let[P,M]of h)P.removeEventListener("abort",M)};h.set(x,N)}for(let[x,N]of h)x.addEventListener("abort",N,{once:!0});return T.signal}function _f(f,E,_){let T=_?.throwOnAbort??!1;if(E?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((h,x)=>{let N,P=setTimeout(()=>{if(E&&N)E.removeEventListener("abort",N);h()},f);if(E)N=()=>{if(clearTimeout(P),T)x(new DOMException("Aborted","AbortError"));else h()},E.addEventListener("abort",N,{once:!0})})}var O_=a("Chat"),V_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function AE(f){if(typeof f==="string")return f;return f.filter((E)=>E.type==="text").map((E)=>E.text).join(`
|
|
2
2
|
`)}function j_(f){if(!f)return{};try{let E=JSON.parse(f);return E&&typeof E==="object"&&!Array.isArray(E)?E:{}}catch{return O_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function X_(f){let E=f.match(/^data:([^;,]+);base64,(.+)$/s);return E?{mimeType:E[1],data:E[2]}:void 0}async function c_(f,E){let _=X_(f);if(_)return{type:"image",..._};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:E});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 SE(f,E,_){return Promise.all(f.map((T)=>T.type==="text"?Promise.resolve({type:"text",text:T.text}):E?c_(T.image_url.url,_):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})))}async function NE(f,E,_,T,h){let x=f.filter((S)=>S.role==="system").map((S)=>AE(S.content)).filter(Boolean).join(`
|
|
3
3
|
|
|
4
4
|
`),N=[],P=E.input.includes("image");for(let S of f){if(S.role==="system")continue;if(S.role==="user"){let t=typeof S.content==="string"?S.content:await SE(S.content,P,T);N.push({role:"user",content:t,timestamp:Date.now()});continue}if(S.role==="assistant"){let t=[];if(S.reasoningContent?.trim())t.push({type:"thinking",thinking:S.reasoningContent});let A=AE(S.content);if(A)t.push({type:"text",text:A});for(let D of S.tool_calls??[]){if(!("function"in D))continue;t.push({type:"toolCall",id:D.id,name:D.function.name,arguments:j_(D.function.arguments)})}N.push({role:"assistant",content:t,api:E.api,provider:E.provider,model:E.id,usage:V_,stopReason:S.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}N.push({role:"toolResult",toolCallId:S.tool_call_id??"",toolName:S.name??"unknown",content:typeof S.content==="string"?[{type:"text",text:S.content}]:await SE(S.content,P,T),isError:!1,timestamp:Date.now()})}let M=_?.filter((S)=>!h||S.name===h).map((S)=>({name:S.name,description:S.description,parameters:S.parameters,constrainedSampling:S.constrainedSampling})).sort((S,t)=>S.name<t.name?-1:S.name>t.name?1:0);return{...x?{systemPrompt:x}:{},messages:N,...M?.length?{tools:M}:{}}}function uE(f){let E=[];for(let _=0;_<f.length;_++){let T=f[_];if(T.role==="tool")continue;let h=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!h){E.push(T);continue}let x=[],N=_+1;while(N<f.length&&f[N].role==="tool")x.push(f[N++]);let P=new Set(h.map((t)=>t.id)),M=x.filter((t)=>t.tool_call_id&&P.has(t.tool_call_id)),S=new Set(M.map((t)=>t.tool_call_id));if(P.size===h.length&&M.length===P.size&&S.size===P.size)E.push(T,...M);_=N-1}return E}function DE(f){return f.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function HE(f,E){return{...f,...E.baseUrl?{baseUrl:IE(f.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function Wf(f){let E=f.modelCatalog??Jf();return{models:E.models,model:HE(E.getModel(f.provider,f.model),f)}}function UE(f,E){let _=f.modelCatalog??Jf();return HE(_.getModel(E.provider,E.model),f)}import{createHash as J_}from"node:crypto";var W_=32,$_=1000,z_=512,L_=2000,G_=0.1,k_=0.05,Z_=0.9,Q_=300000,K_=3600000;class $f{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let E=f.now??Date.now(),_=C_(f,E),T=this.sessions.get(f.sessionId);if(_.callCount=(T?.callCount??0)+1,this.touch(f.sessionId,_),T&&_.contextEpoch!==T.contextEpoch)return;if(!T||T.cacheReadTokens<$_)return;let h=T.cacheReadTokens-_.cacheReadTokens,x=Math.min(L_,Math.max(z_,T.cacheReadTokens*G_));if(h<x||_.cacheReadTokens>=T.cacheReadTokens*(1-k_))return;let N=_.modelIdentity!==T.modelIdentity,P=_.systemHash!==T.systemHash,M=_.toolsHash!==T.toolsHash,S=_.policyHash!==T.policyHash;if(!(N||P||M||S)&&_.promptTokens<T.promptTokens*Z_)return;let A=Math.max(0,E-T.recordedAt),D=T.retention==="long"?K_:Q_,Y=N?"model_changed":P?"system_prompt_changed":M?"tools_changed":S?"request_policy_changed":A>=D?"ttl_expired":"server_side",z=F_(T,_);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:_.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:h,elapsedMs:A,callNumber:_.callCount,systemPromptChanged:P,systemCharDelta:_.systemChars-T.systemChars,toolsChanged:M,addedToolCount:z.added,removedToolCount:z.removed,changedToolCount:z.changed,modelChanged:N,requestPolicyChanged:S}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,E){this.sessions.delete(f),this.sessions.set(f,E);while(this.sessions.size>W_){let _=this.sessions.keys().next().value;if(_===void 0)break;this.sessions.delete(_)}}}function C_(f,E){let _=[...f.tools??f.context.tools??[]].map((T)=>({identityHash:Tf(T.name),contractHash:Tf(hf(T))})).sort((T,h)=>T.identityHash<h.identityHash?-1:T.identityHash>h.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:Tf(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:Tf(hf(_)),toolFingerprints:_,policyHash:Tf(hf(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:E,callCount:1}}function F_(f,E){let _=new Map(f.toolFingerprints.map((h)=>[h.identityHash,h.contractHash])),T=new Map(E.toolFingerprints.map((h)=>[h.identityHash,h.contractHash]));return{added:[...T.keys()].filter((h)=>!_.has(h)).length,removed:[..._.keys()].filter((h)=>!T.has(h)).length,changed:[...T].filter(([h,x])=>_.has(h)&&_.get(h)!==x).length}}function hf(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(hf).join(",")}]`;let E=f;return`{${Object.keys(E).sort().map((_)=>`${JSON.stringify(_)}:${hf(E[_])}`).join(",")}}`}function Tf(f){return J_("sha256").update(f).digest("hex")}import{randomBytes as o_}from"node:crypto";import{createHmac as v_}from"node:crypto";function s_(f){try{let E=new URL(f);if(E.hash="",E.hostname=E.hostname.toLowerCase(),E.searchParams.sort(),E.pathname!=="/")E.pathname=E.pathname.replace(/\/+$/,"");return E.toString()}catch{return f.trim().replace(/\/+$/,"")}}function w_(f){if(!f)return[];return Object.entries(f).map(([E,_])=>[E.trim().toLowerCase(),_.trim()]).sort(([E],[_])=>E.localeCompare(_))}function uf(f,E,_){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),s_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",w_(f.customHeaders),_]);return v_("sha256",Buffer.from(E)).update(T).digest("hex")}var p_=60000,m_=4,q_=0.8;var If=300000,kf=600000;var YE=128,BE=256,g_=1800000,Df=50;class tf 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 Rf(f){return f instanceof tf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function d(f,E){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:E}function l_(f,E){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:E}function y_(f,E){return uf(f,E,{providerCircuitOpenDurationMs:f.openDurationMs})}function xf(f){let E=0;for(let _ of f)if(_.failure)E++;return E}function bE(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function zf(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Gf)}class VE{#x=new Map;#t=new WeakMap;#f;#_;#h;#T;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):o_(32),this.#_=f.now??(()=>performance.now()),this.#h=f.wallNow??f.now??Date.now,this.#T={maxEntries:Math.min(d(f.maxEntries,YE),YE),maxWindowEntries:Math.min(d(f.maxWindowEntries,BE),BE),windowMs:d(f.windowMs,p_),minSamples:d(f.minSamples,m_),errorRateThreshold:l_(f.errorRateThreshold,q_),idleTtlMs:d(f.idleTtlMs,g_)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#P();let E=this.#_();this.#B(E);let _=y_(f,this.#f),T=this.#x.get(_);if(T)return T.lastTouchedAt=E,this.#E(T,f.probeLeaseMs);if(this.#x.size>=this.#T.maxEntries)this.#I();if(this.#x.size>=this.#T.maxEntries)return this.#P();let h={key:_,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:E,detached:!1};return this.#x.set(_,h),this.#E(h,f.probeLeaseMs)}#E(f,E){let _=this,T=Math.max(If,Math.min(d(E,If),kf));return{preflight:()=>_.#A(f),check:()=>_.#b(f,T),recordSuccess:(h)=>_.#R(h,"success"),recordFailure:(h,x)=>_.#R(h,"failure",x),recordNeutral:(h)=>_.#R(h,"neutral"),abandon:(h)=>_.#u(h),snapshot:()=>_.#X(f)}}#P(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let E=Object.freeze({kind:"noop"});return f.#t.set(E,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:E}},recordSuccess:(E)=>f.#M(E),recordFailure:(E)=>f.#M(E),recordNeutral:(E)=>f.#M(E),abandon:(E)=>f.#u(E),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#M(f){let E=this.#t.get(f);if(E?.kind==="noop")E.settled=!0;return}#A(f){let E=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=E,this.#D(f,E),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??E;return E<T?this.#U(f,T-E):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return{eligible:!0};let _=Math.max(1,(f.probeLeaseExpiresAt??E+Df)-E);return this.#U(f,Math.min(Df,_))}#U(f,E){let{allowed:_,...T}=this.#S(f,E);return{eligible:!1,...T}}#b(f,E){let _=this.#_();if(f.detached)return this.#P().check();if(f.lastTouchedAt=_,this.#D(f,_),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let h=f.nextProbeAt??_;if(_<h)return this.#S(f,h-_);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return this.#O(f,_,E);let T=Math.max(1,(f.probeLeaseExpiresAt??_+Df)-_);return this.#S(f,Math.min(Df,T))}#Y(f,E,_){let T=Object.freeze({kind:E});return this.#t.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:E,..._!==void 0?{probeLeaseId:_}:{},settled:!1}),{allowed:!0,probe:E==="probe",token:T}}#O(f,E,_){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=E+_,f.lastTouchedAt=E;let h=this.#Y(f,"probe",T),x=f.lastFailure??{reason:"server_error"};return{...h,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:xf(f.samples)}}#S(f,E){let _=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(E)),nextProbeAt:this.#h()+Math.max(0,Math.ceil(E)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:xf(f.samples)}}#R(f,E,_){let T=this.#t.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let h=T.entry;if(h.detached||T.generation!==h.generation||T.kind==="regular"&&h.state!=="closed"||T.kind==="probe"&&(h.state!=="half_open"||T.probeLeaseId!==h.probeLeaseId))return;let x=this.#_();if(h.lastTouchedAt=x,T.kind==="probe"){if(E==="failure"&&_)return this.#N(h,_,x,"reopened");return this.#V(h)}if(E==="neutral")return;if(this.#j(h,E==="failure",x),E!=="failure"||!_)return;let N=zf(_.retryAfterMs);if(_.reason==="rate_limit"&&_.statusCode===429&&N!==void 0&&N>0)return this.#N(h,{..._,retryAfterMs:N},x,"opened");let P=xf(h.samples),M=h.samples.length===0?0:P/h.samples.length;if(h.samples.length>=this.#T.minSamples&&M>=this.#T.errorRateThreshold)return this.#N(h,_,x,"opened");return}#N(f,E,_,T){let h={reason:E.reason,...bE(E.statusCode)!==void 0?{statusCode:bE(E.statusCode)}:{},...zf(E.retryAfterMs)!==void 0?{retryAfterMs:zf(E.retryAfterMs)}:{}},x=h.retryAfterMs??0,N=Math.max(f.configuredOpenDurationMs,x);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=N,f.nextProbeAt=_+N,f.lastFailure=h,{phase:T,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},retryAfterMs:N,nextProbeAt:this.#h()+N,openDurationMs:N,sampleCount:f.samples.length,failureCount:xf(f.samples)}}#V(f){let E=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:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#u(f){let E=this.#t.get(f);if(!E||E.settled)return!1;if(E.settled=!0,E.kind==="noop")return!0;let _=E.entry;if(!_||_.detached||E.kind!=="probe"||E.generation!==_.generation||E.probeLeaseId!==_.probeLeaseId)return!1;return _.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.lastTouchedAt=this.#_(),!0}#j(f,E,_){if(this.#D(f,_),f.samples.length>=this.#T.maxWindowEntries)f.samples.shift();f.samples.push({at:_,failure:E})}#D(f,E){let _=E-this.#T.windowMs,T=0;while(T<f.samples.length&&f.samples[T].at<_)T++;if(T>0)f.samples.splice(0,T)}#X(f){if(!f.detached)this.#D(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:xf(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#B(f){for(let[E,_]of this.#x)if(_.state==="closed"&&f-_.lastTouchedAt>this.#T.idleTtlMs)this.#H(E,_)}#I(){let f;for(let E of this.#x.values())if(E.state==="closed"&&(!f||E.lastTouchedAt<f.lastTouchedAt))f=E;if(f)this.#H(f.key,f)}#H(f,E){E.detached=!0,this.#x.delete(f)}}var OE;function jE(){return OE??=new VE,OE}import{randomBytes as a_}from"node:crypto";var d_=16,XE=128,cE=32,n_=3,JE=16,WE=96,$E=24,zE=12,LE=16,GE=4,kE=4,ZE=67108864,QE=33554432,e_=12,r_=2,KE=2,CE=1,oE=15000,FE=30000;function Zf(){return{foreground:0,background:0,internal:0}}function Qf(){return{inFlight:Zf(),queued:Zf(),pendingBytes:Zf()}}function U(f){return f.foreground+f.background+f.internal}function $(f){return f.background+f.internal}function vE(f){return f.inFlight.foreground===0&&f.inFlight.background===0&&f.inFlight.internal===0&&f.queued.foreground===0&&f.queued.background===0&&f.queued.internal===0&&f.pendingBytes.foreground===0&&f.pendingBytes.background===0&&f.pendingBytes.internal===0}class Pf extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,E,_,T,h,x,N,P){super(f==="queue_full"?`Provider request admission ${E} ${T} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${E} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=E;this.requestClass=_;this.resource=T;this.inFlight=h;this.limit=x;this.queued=N;this.maxWaitMs=P;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function l(f){return f instanceof Pf||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 E;return Math.min(f,_)}function i_(f){let E=J(f.globalMaxInFlight,d_,Number.MAX_SAFE_INTEGER),_=J(f.globalMaxPending,XE,XE),T=J(f.domainMaxPending,cE,cE),h=Math.min(J(f.ownerMaxInFlight,n_,Number.MAX_SAFE_INTEGER),E),x=Math.min(J(f.ownerMaxPending,JE,JE),_),N=Math.min(J(f.nonForegroundGlobalMaxPending,Math.min(WE,Math.max(1,Math.floor(_*3/4))),WE),_),P=Math.min(J(f.nonForegroundDomainMaxPending,Math.min($E,Math.max(1,Math.floor(T*3/4))),$E),T),M=Math.min(J(f.nonForegroundOwnerMaxPending,Math.min(zE,Math.max(1,Math.floor(x*3/4))),zE),x),S=Math.min(J(f.internalGlobalMaxPending,Math.min(LE,Math.max(1,Math.floor(_/8))),LE),N),t=Math.min(J(f.internalDomainMaxPending,Math.min(GE,Math.max(1,Math.floor(T/8))),GE),P),A=Math.min(J(f.internalOwnerMaxPending,Math.min(kE,Math.max(1,Math.floor(x/4))),kE),M),D=J(f.globalMaxPendingBytes,s,s),Y=Math.min(J(f.domainMaxPendingBytes,ZE,ZE),D),z=Math.min(J(f.ownerMaxPendingBytes,QE,QE),D),Q=Math.min(J(f.nonForegroundGlobalMaxInFlight,Math.min(e_,E),E),E),K=Math.min(J(f.nonForegroundOwnerMaxInFlight,Math.min(r_,h),h),h),F=Math.min(J(f.internalGlobalMaxInFlight,Math.min(KE,E),KE),E),Bf=J(f.internalDomainMaxInFlight,CE,CE),Af=J(f.agingMs,FE,FE);return{globalMaxInFlight:E,globalMaxPending:_,domainMaxPending:T,ownerMaxInFlight:h,ownerMaxPending:x,nonForegroundGlobalMaxPending:N,nonForegroundDomainMaxPending:P,nonForegroundOwnerMaxPending:M,internalGlobalMaxPending:S,internalDomainMaxPending:t,internalOwnerMaxPending:A,globalMaxPendingBytes:D,domainMaxPendingBytes:Y,ownerMaxPendingBytes:z,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:F,internalDomainMaxInFlight:Bf,agingMs:Af,classLimitsEnabled:f.classLimitsEnabled!==!1}}function sE(f,E){if(!f.trim())throw Error(`${E} must not be blank`)}function fT(f){if(sE(f.sessionId,"sessionId"),sE(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<Hf||f.scope.maxConcurrent>g)throw Error(`maxConcurrent must be between ${Hf} and ${g}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>s)throw Error(`maxPendingBytes must be between 1 and ${s}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>s+1)throw Error(`pendingBytes must be between 1 and ${s+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Uf)throw Error(`maxWaitMs must be 0-${Uf}`)}function Kf(f,E){if(E!==void 0)return E;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function ET(f,E){return uf(f,E,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class pE{#x;#t;#f;#_=[];#h=new Map;#T=new Map;#E=Qf();#P=1;#M=0;#A=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):a_(32),this.#t=f.now??(()=>performance.now()),this.#f=i_(f)}admit(f){if(fT(f),this.#A)throw this.#c("closed",f,{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw Kf(f.signal);let E=ET(f.scope,this.#x),_=this.#h.get(E),T=this.#T.get(f.ownerId),h=_??this.#Y(f.scope.maxConcurrent),x=T??this.#O();if(this.#_.length===0&&this.#S(h,x,f.requestClass)){if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let D=this.#N(E,f.ownerId,f.requestClass),Y=this.#L(f,0);return{ready:Promise.resolve(D),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let N=this.#U(f,h,x);if(N)throw this.#c("queue_full",f,N,this.#_.length);let P=this.#R(h,x,f.requestClass);if(f.maxWaitMs===0)throw this.#c("wait_timeout",f,P,this.#_.length);if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let M,S,t=new Promise((D,Y)=>{M=D,S=Y});t.catch(()=>{return});let A={domainKey:E,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:M,reject:S,settled:!1,admitted:!1};if(f.signal)A.abortListener=()=>this.#B(A,Kf(f.signal)),f.signal.addEventListener("abort",A.abortListener,{once:!0});return A.timer=setTimeout(()=>this.#X(A),f.maxWaitMs),A.timer.unref?.(),this.#_.push(A),this.#b(h,x,A),this.#u(),{ready:t,getSnapshot:()=>this.#z(A),cancel:(D)=>this.#B(A,Kf(f.signal,D))}}close(){if(this.#A)return;this.#A=!0;for(let f of[...this.#_]){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#I(f,new Pf("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:U(this.#E.inFlight),queued:this.#_.length,pendingBytes:U(this.#E.pendingBytes),nonForegroundInFlight:$(this.#E.inFlight),internalInFlight:this.#E.inFlight.internal,nonForegroundQueued:$(this.#E.queued),internalQueued:this.#E.queued.internal,nonForegroundPendingBytes:$(this.#E.pendingBytes),internalPendingBytes:this.#E.pendingBytes.internal,domainCount:this.#h.size,ownerCount:this.#T.size,closed:this.#A}}#U(f,E,_){let T=(t,A,D)=>A>=D?{scope:t,resource:"pending_count",inFlight:A,limit:D}:void 0;if(this.#f.classLimitsEnabled&&f.requestClass==="internal"){let t=T("class",this.#E.queued.internal,this.#f.internalGlobalMaxPending)??T("class",_.counters.queued.internal,this.#f.internalOwnerMaxPending)??T("class",E.counters.queued.internal,this.#f.internalDomainMaxPending);if(t)return t}if(this.#f.classLimitsEnabled&&f.requestClass!=="foreground"){let t=T("class",$(this.#E.queued),this.#f.nonForegroundGlobalMaxPending)??T("class",$(_.counters.queued),this.#f.nonForegroundOwnerMaxPending)??T("class",$(E.counters.queued),this.#f.nonForegroundDomainMaxPending);if(t)return t}let h=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",U(_.counters.queued),this.#f.ownerMaxPending)??T("domain",U(E.counters.queued),this.#f.domainMaxPending);if(h)return h;let x=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),N=Math.min(x,this.#f.domainMaxPendingBytes),P=Math.min(x,this.#f.ownerMaxPendingBytes),M=(t,A)=>f.pendingBytes>A-t,S=(t)=>{if(t==="owner")return{scope:t,resource:"pending_bytes",inFlight:U(_.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(t==="domain")return{scope:t,resource:"pending_bytes",inFlight:U(E.counters.inFlight),limit:E.maxConcurrent};return{scope:t,resource:"pending_bytes",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let t=Math.max(1,Math.floor(x/8)),A=Math.max(1,Math.floor(N/4)),D=Math.max(1,Math.floor(P/4));if(M(this.#E.pendingBytes.internal,t)||M(_.counters.pendingBytes.internal,D)||M(E.counters.pendingBytes.internal,A))return S("class")}if(f.requestClass!=="foreground"){let t=Math.max(1,Math.floor(x*3/4)),A=Math.max(1,Math.floor(N*3/4)),D=Math.max(1,Math.floor(P/2));if(M($(this.#E.pendingBytes),t)||M($(_.counters.pendingBytes),D)||M($(E.counters.pendingBytes),A))return S("class")}if(M(U(this.#E.pendingBytes),x))return S("global");if(M(U(_.counters.pendingBytes),P))return S("owner");if(M(U(E.counters.pendingBytes),N))return S("domain");return}#b(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]++,f.counters.queued[T]++,E.counters.queued[T]++,this.#E.pendingBytes[T]+=h,f.counters.pendingBytes[T]+=h,E.counters.pendingBytes[T]+=h}#Y(f){return{maxConcurrent:f,counters:Qf()}}#O(){return{order:this.#P,counters:Qf()}}#S(f,E,_){if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return!1;if(U(f.counters.inFlight)>=f.maxConcurrent)return!1;if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return!1;if(_==="foreground"||!this.#f.classLimitsEnabled)return!0;if($(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if($(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if($(f.counters.inFlight)>=T)return!1;if(_!=="internal")return!0;return this.#E.inFlight.internal<this.#f.internalGlobalMaxInFlight&&f.counters.inFlight.internal<this.#f.internalDomainMaxInFlight}#R(f,E,_){if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:U(E.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&$(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:$(E.counters.inFlight),limit:this.#f.nonForegroundOwnerMaxInFlight};if(U(f.counters.inFlight)>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent};if(this.#f.classLimitsEnabled&&_!=="foreground"){let T=Math.max(1,f.maxConcurrent-1);if($(f.counters.inFlight)>=T)return{scope:"class",resource:"stream",inFlight:$(f.counters.inFlight),limit:T}}if(this.#f.classLimitsEnabled&&_==="internal"&&f.counters.inFlight.internal>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.counters.inFlight.internal,limit:this.#f.internalDomainMaxInFlight};if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&$(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:$(this.#E.inFlight),limit:this.#f.nonForegroundGlobalMaxInFlight};if(this.#f.classLimitsEnabled&&_==="internal"&&this.#E.inFlight.internal>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#E.inFlight.internal,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent}}#N(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(!T||!h)throw Error("Provider admission accounting state is unavailable");this.#E.inFlight[_]++,T.counters.inFlight[_]++,h.counters.inFlight[_]++;let x=!1;return{release:()=>{if(x)return;x=!0,this.#V(f,E,_)}}}#V(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(this.#E.inFlight[_]--,T)T.counters.inFlight[_]--;if(h)h.counters.inFlight[_]--;this.#J(f,E),this.#u()}#u(){if(this.#A)return;while(this.#_.length>0){let f=this.#t(),E=new Map;for(let[P,M]of this.#_.entries()){let S=this.#h.get(M.domainKey),t=this.#T.get(M.ownerId);if(S===void 0||t===void 0||!this.#S(S,t,M.requestClass))continue;let A=this.#j(M,f),D=E.get(M.ownerId);if(!D||A<D.rank||A===D.rank&&P<D.index)E.set(M.ownerId,{pending:M,rank:A,index:P})}let _=[...E.values()].filter(({pending:P})=>{let M=this.#h.get(P.domainKey),S=this.#T.get(P.ownerId);return M!==void 0&&S!==void 0&&this.#S(M,S,P.requestClass)}).map(({pending:P,rank:M})=>({pending:P,rank:M,order:this.#T.get(P.ownerId).order}));if(_.length===0)return;let T=Math.min(..._.map((P)=>P.rank)),h=_.filter((P)=>P.rank===T),N=h.filter((P)=>P.order>this.#M).sort((P,M)=>P.order-M.order)[0]??h.sort((P,M)=>P.order-M.order)[0];this.#D(N.pending,N.order)}}#j(f,E){let _=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,E-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,_-T)}#D(f,E){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#M=E;let _=this.#N(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#X(f){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#I(f,new Pf("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#B(f,E){this.#I(f,E)}#I(f,E){if(!this.#H(f))return;f.settled=!0,f.reject(E),this.#u()}#H(f,E=!0){if(f.settled||f.admitted)return!1;let _=this.#_.indexOf(f);if(_<0)return!1;this.#_.splice(_,1);let T=this.#h.get(f.domainKey),h=this.#T.get(f.ownerId);if(T&&h)this.#W(T,h,f);if(this.#$(f),E)this.#J(f.domainKey,f.ownerId);return!0}#W(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]--,f.counters.queued[T]--,E.counters.queued[T]--,this.#E.pendingBytes[T]-=h,f.counters.pendingBytes[T]-=h,E.counters.pendingBytes[T]-=h}#$(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#J(f,E){let _=this.#h.get(f);if(_&&vE(_.counters))this.#h.delete(f);let T=this.#T.get(E);if(T&&vE(T.counters))this.#T.delete(E)}#z(f){let E=Math.max(0,Math.floor(this.#t()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs};let _=this.#h.get(f.domainKey),T=this.#T.get(f.ownerId),h=_&&T?this.#R(_,T,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:h.resource,scope:h.scope,reason:"capacity",queuePosition:this.#G(f,h.scope),queueDepth:this.#_.length,inFlight:h.inFlight,limit:h.limit,waitMs:E,maxWaitMs:f.maxWaitMs}}#L(f,E){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs}}#G(f,E){let _=this.#_.filter((T)=>{switch(E){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,_.indexOf(f)+1)}#c(f,E,_,T){return new Pf(f,_.scope,E.requestClass,_.resource,_.inFlight,_.limit,T,E.maxWaitMs)}}var wE;function mE(f={}){return wE??=new pE(f),wE}var qE=new WeakSet;class n extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,E){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=E;this.name="ProviderRecoveryBudgetExceededError"}}class vf extends Error{timeoutMs;code="PROVIDER_REQUEST_DEADLINE_EXCEEDED";constructor(f){super(`Provider request deadline exceeded after ${f}ms`);this.timeoutMs=f;this.name="ProviderRequestDeadlineExceededError"}}var _T=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],TT=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],hT=["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 gE(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function xT(f){let E=gE(f);return TT.some((_)=>E.includes(_))}function sf(f){if(f!==null&&typeof f==="object")qE.add(f)}function Rh(f){return f!==null&&typeof f==="object"&&qE.has(f)}function tT(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function RT(f){if(f===null||typeof f!=="object")return;let E=f;for(let _ of["status","statusCode"]){let T=E[_];if(typeof T==="number"&&Number.isInteger(T))return T}return}function PT(f){let E=f.match(/^(?:error:\s*)?(\d{3})\b/),_=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(E?.[1]??_?.[1]);return Number.isInteger(T)?T:void 0}function o(f,E){let _=gE(f),T=tT(f);if(T==="STREAM_IDLE_TIMEOUT"||T==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||_.includes("request aborted")||_==="aborted")return{retryable:!1};if(_T.some((x)=>_.includes(x))||xT(f))return{retryable:!1};if(E?.shouldRetry==="false")return{retryable:!1,statusCode:E.statusCode};if(T==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let h=E?.statusCode??RT(f)??PT(_);if(E?.shouldRetry==="true")return{retryable:!0,reason:h===429?"rate_limit":h===408||h===409?"timeout":"server_error",statusCode:h};if(h===429)return{retryable:!0,reason:"rate_limit",statusCode:h};if(h===408||h===409)return{retryable:!0,reason:"timeout",statusCode:h};if(h!==void 0&&h>=500&&h<=599)return{retryable:!0,reason:"server_error",statusCode:h};if(T==="PROVIDER_STREAM_CLOSED"||_.includes("stream closed before completion")||_.includes("ended without")||_.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:h};if(hT.some((x)=>_.includes(x)))return{retryable:!0,reason:"transport",statusCode:h};if(_.includes("timeout")||_.includes("timed out")||_.includes("temporarily unavailable")||_.includes("upstream_error")||_.includes("overloaded")||_.includes("rate limit")||_.includes("too many requests")||_.includes("service unavailable")||_.includes("server error")||_.includes("internal error")||_.includes("please retry")||_.includes("try your request again"))return{retryable:!0,reason:_.includes("rate")||_.includes("too many")?"rate_limit":_.includes("timeout")||_.includes("timed out")?"timeout":"server_error",statusCode:h};return{retryable:!1,statusCode:h}}function wf(f,E){if(!f)return;if(f.retryAfterMs!==void 0){let h=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(h))return Math.max(0,h)}if(f.retryAfter===void 0)return;let _=Number.parseFloat(f.retryAfter);if(Number.isFinite(_))return Math.max(0,_*1000);let T=Date.parse(f.retryAfter);return Number.isFinite(T)?Math.max(0,T-E):void 0}function lE(f,E,_={}){let T=_.now??Date.now(),h=_.maxDelayMs??60000,x=wf(E,T);if(x!==void 0)return Math.min(Math.ceil(x),h);let N=Math.max(0,f-1),P=_.maxExponentialDelayMs??8000,M=Math.min(500*2**N,P),S=Math.max(0,Math.min(1,_.random??Math.random())),t=M*(0.75+S*0.25);return Math.min(Math.round(t),h)}function pf(f,E){return{provider:of(f),model:of(E)}}function yE(f,E){if(l(f))return{source:"admission",reason:f.reason};if(Rf(f))return{source:"circuit",reason:f.circuit.reason,...f.circuit.statusCode!==void 0?{statusCode:f.circuit.statusCode}:{}};if(f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT")return{source:"stall",reason:"timeout"};let _=o(f,E);if(_.retryable&&_.reason)return{source:"retry",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{}};throw Error("Provider fallback trigger is not classified")}function aE(f,E={}){let _=E.maxBytes??134217728,T=E.maxNodes??1e5;if(!Number.isSafeInteger(_)||_<=0||_>=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 h=new WeakSet,x=0,N=0,P=!1,M=(t)=>{if(P||t<=0)return;if(!Number.isSafeInteger(t)||t>_-x){x=_+1,P=!0;return}x+=t},S=(t)=>{if(P)return;if(N+=1,N>T){M(_+1);return}if(t===null){M(4);return}switch(typeof t){case"string":M(Buffer.byteLength(t,"utf8"));return;case"number":case"bigint":M(8);return;case"boolean":M(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(h.has(t))return;if(h.add(t),ArrayBuffer.isView(t)){M(32+t.byteLength);return}if(t instanceof ArrayBuffer){M(32+t.byteLength);return}if(t instanceof Date){M(40);return}if(t instanceof RegExp){M(32+Buffer.byteLength(t.source,"utf8"));return}if(t instanceof Map){M(32);for(let[A,D]of t)if(S(A),S(D),P)return;return}if(t instanceof Set){M(32);for(let A of t)if(S(A),P)return;return}if(t instanceof WeakMap||t instanceof WeakSet){M(32);return}if(Array.isArray(t)){M(16);for(let A of t)if(S(A),P)return;return}M(32);for(let A of Reflect.ownKeys(t)){if(typeof A!=="string")continue;let D=Object.getOwnPropertyDescriptor(t,A);if(!D?.enumerable||!("value"in D))continue;if(M(8+Buffer.byteLength(A,"utf8")),S(D.value),P)return}};return S(f),x}function dE(f){return aE([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}function rE(f,E){let _=f.onPayload;f.onPayload=async(T,h)=>{let x=_?await _(T,h):T;return E(x===void 0?T:x,h)}}function AT(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function mf(f,E,_){if(!f.enablePromptCaching)return"none";if(_&&E.api==="openai-completions"&&!E.baseUrl.includes("api.openai.com"))return"long";return"short"}function ST(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function MT(f,E,_,T){let h=T?void 0:AT(_);if(!h){if(E.api==="anthropic-messages")f.thinkingEnabled=!1;if(E.api==="google-generative-ai"||E.api==="google-vertex")f.thinking={enabled:!1};return}switch(E.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=h;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:ST(h)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=h;break;default:f.reasoningEffort=h}}function NT(f,E,_){if(!_)return;switch(E){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:_};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:_}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:_};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function uT(f,E,_){let T=_.serviceTier;if(!T)return;if(E.api==="openai-responses"||E.api==="openai-codex-responses"||E.api==="azure-openai-responses"){f.serviceTier=T;return}if(E.api!=="openai-completions"&&!(E.api==="anthropic-messages"&&T==="fast"))return;rE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;return E.api==="anthropic-messages"?{...h,speed:"fast"}:{...h,service_tier:T}})}function DT(f,E,_){let T=_.responseVerbosity;if(!T)return;if(eE(E,T),E.api==="openai-codex-responses"){f.textVerbosity=T;return}rE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;if(E.api==="openai-completions")return{...h,verbosity:T};let x="text"in h&&h.text&&typeof h.text==="object"&&!Array.isArray(h.text)?h.text:{};return{...h,text:{...x,verbosity:T}}})}function iE(f,E,_,T,h=!1){let x={apiKey:f.apiKey,headers:f.customHeaders,signal:_,temperature:T?.temperature??f.temperature??0,maxTokens:T?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:mf(f,E,T?.providerSessionId),sessionId:T?.providerSessionId};if(MT(x,E,f,h),NT(x,E.api,T?.toolChoice?.toolName),uT(x,E,f),DT(x,E,f),E.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=E.id;return x}function nE(f,E){let _=E.get("x-should-retry");return{statusCode:f,...E.get("retry-after")!==null?{retryAfter:E.get("retry-after")??void 0}:{},...E.get("retry-after-ms")!==null?{retryAfterMs:E.get("retry-after-ms")??void 0}:{},..._==="true"||_==="false"?{shouldRetry:_}:{}}}var IT=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function f_(f,E,_){let T=f.onResponse;if(f.onResponse=async(x,N)=>{let P=new Headers(x.headers);_(nE(x.status,P)),await T?.(x,N)},!IT.has(E.api)||typeof globalThis.fetch!=="function")return;let h=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(x,N)=>{let P=await h(x,N);return _(nE(P.status,P.headers)),P}}function E_(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,HT=30000;class __ 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 T_ extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function qf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function UT(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Yf}function YT(f,E){if(E===0)return;let _=E!==void 0&&E>0?E:HT;return Math.max(1,Math.min(_,Math.floor(f/2)))}function BT(f,E,_){if(_?.aborted)return Promise.reject(qf(_));return new Promise((T,h)=>{let x=!1,N=()=>{clearTimeout(t),_?.removeEventListener("abort",S)},P=(A)=>{if(x)return;x=!0,N(),T(A)},M=(A)=>{if(x)return;x=!0,N(),h(A instanceof Error?A:Error(String(A)))},S=()=>{if(_)M(qf(_))},t=setTimeout(()=>P({kind:"timer"}),Math.max(0,E));if(_?.addEventListener("abort",S,{once:!0}),_?.aborted){S();return}f.then((A)=>P({kind:"next",result:A}),M)})}async function*bT(f,E,_){let T=UT(E),h=YT(T,E.stallWarningMs);if(E.signal?.aborted)throw qf(E.signal);let x=Date.now(),N=Promise.resolve().then(()=>f.next()),P;for(;;){let S=await BT(N,(P?T:h??T)-(Date.now()-x),E.signal);if(S.kind==="next"){if(P)yield{...P,phase:"recovered",durationMs:Math.max(P.durationMs,Date.now()-x)};return S.result}if(!P&&h!==void 0){_.stallCount++,P={phase:"detected",stallCount:_.stallCount,durationMs:h,warningAfterMs:h,timeoutMs:T,outputStarted:_.outputStarted},yield P;continue}let t=new __(T);throw E.abort?.(t),t}}async function*h_(f,E,_,T,h={}){let N=f.stream(E,_,T)[Symbol.asyncIterator](),P=0,M=!1,S={stallCount:0,outputStarted:!1};try{while(!0){let t=bT(N,h,S),A=await t.next();while(!A.done)yield{providerStall:A.value},A=await t.next();let D=A.value;if(D.done)throw new T_;let Y=D.value;switch(Y.type){case"text_delta":S.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":S.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":S.outputStarted=!0,yield{toolCalls:[{index:P++,id:Y.toolCall.id,type:"function",function:{name:Y.toolCall.name,arguments:JSON.stringify(Y.toolCall.arguments)}}]};break;case"done":M=!0,yield{finishReason:Y.reason,usage:E_(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!M)Promise.resolve(N.return?.()).catch(()=>{return})}}var gf=a("Chat"),OT=1;function VT(f,E){let _=E.provider===f.provider,T=_&&E.channel===void 0,h=E.channel;return{...f,provider:E.provider,model:E.model,apiKey:h?.apiKey??(T?f.apiKey:void 0),baseUrl:h?.baseUrl??(T?f.baseUrl:void 0),temperature:h?.temperature??f.temperature,maxOutputTokens:h?.maxOutputTokens??(T?f.maxOutputTokens:void 0),timeout:h?.timeout??f.timeout,streamIdleTimeout:h?.streamIdleTimeout??f.streamIdleTimeout,apiVersion:h?.apiVersion??(T?f.apiVersion:void 0),customHeaders:h?.customHeaders??(T?f.customHeaders:void 0),enablePromptCaching:h?.enablePromptCaching??(T?f.enablePromptCaching:void 0),serviceTier:_?f.serviceTier:void 0,responseVerbosity:_?f.responseVerbosity:void 0,fallbackModels:void 0}}function jT(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((E)=>E.type==="image_url"))}function XT(f){let _=f.findLast((T)=>{let h=T.metadata;return h!==null&&typeof h==="object"&&!Array.isArray(h)&&h.isCompactSummary===!0})?.metadata;return _!==null&&typeof _==="object"&&!Array.isArray(_)&&typeof _.parentId==="string"?_.parentId:""}function cT(f,E){let _=o(f,E);if(!_.retryable||!_.reason)return;let T=_.statusCode;switch(_.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 h=wf(E,Date.now());return{reason:_.reason,...T!==void 0?{statusCode:T}:{},...h!==void 0?{retryAfterMs:h}:{}}}function lf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class df{config;models;model;promptCacheBreakMonitor=new $f;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${OT++}`;constructor(f){let E=Wf(f);this.config={...f,maxContextTokens:E.model.contextWindow,maxOutputTokens:f.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model,this.providerAdmissionScheduler=x_(this.config),gf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,E,_,T){let h="",x="",N=[],P,M;for await(let S of this.streamChat(f,E,_,T)){h+=S.content??"",x+=S.reasoningContent??"";for(let t of S.toolCalls??[])if(t.id&&t.type==="function"&&t.function?.name)N.push(t);P=S.usage??P,M=S.finishReason??M}return{content:h,...x?{reasoningContent:x}:{},...N.length>0?{toolCalls:N}:{},usage:P,finishReason:M}}async*streamChat(f,E,_,T){let h=T?.toolChoice?.toolName;if(h&&!E?.some((R)=>R.name===h))throw Error(`Required tool is unavailable: ${h}`);let x=uE(f);if(x.some((R)=>jT(R))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let N=Boolean(h)||DE(x),P=await NE(x,this.model,E,_,h),M=(R,u)=>{let V=T?.providerSessionId;if(!V||!R.usage)return R;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(V),R;let B=mf(this.config,u,V),I=this.promptCacheBreakMonitor.observe({sessionId:V,modelIdentity:`${u.provider}\x00${u.api}\x00${u.id}`,context:P,retention:B,contextEpoch:XT(x),policy:{baseUrl:u.baseUrl??this.config.baseUrl??"",retention:B,requiredTool:h??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:T?.temperature??this.config.temperature??0,maxOutputTokens:T?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:R.usage});if(!I)return R;return gf.warn("[PiAIChatService] Prompt cache break detected",{reason:I.reason,previousCacheReadTokens:I.previousCacheReadTokens,cacheReadTokens:I.cacheReadTokens,tokenDrop:I.tokenDrop,callNumber:I.callNumber}),{...R,usage:{...R.usage,promptCacheBreak:I}}},S=dE({messages:x,context:P,tools:E,requestOptions:T}),t=T?.providerRecovery;if(t&&!R_(t.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let A=t?.mode==="bounded_foreground"&&t.budgetMs>0?{budgetMs:t.budgetMs,startedAt:void 0}:void 0,D=A?"bounded_foreground":"standard",Y=this.config.maxRetries??2,z=this.config.maxRetries??(A?t_:2),Q=A!==void 0&&this.config.maxRetries===void 0,K=0,F,Bf=this.config.providerCircuitRegistry??jE(),Af=this.config.providerCircuitBreakerOpenMs??Lf,P_=Math.max(If,Math.min(this.config.streamIdleTimeout??Yf,kf)),nf=this.providerAdmissionScheduler,A_=this.config.providerRequestConcurrency??g,ef=this.config.providerRequestAdmissionMs??Cf,S_=this.config.providerRequestPendingBytes??Ff,bf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},M_=(R,u)=>Bf.get({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,openDurationMs:Af,probeLeaseMs:P_}),N_=(R,u)=>({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,maxConcurrent:A_,maxPendingBytes:S_}),X=(R=Date.now())=>{if(!A)return;let u=A.startedAt===void 0?0:Math.min(A.budgetMs,Math.max(0,R-A.startedAt));return{recoveryBudgetMs:A.budgetMs,recoveryElapsedMs:u,recoveryRemainingMs:Math.max(0,A.budgetMs-u)}},w=()=>({mode:D,...X()??{}}),rf=()=>{if(A&&A.startedAt===void 0)A.startedAt=Date.now()},p=()=>{let R=X();return new n(A?.budgetMs??0,R?.recoveryElapsedMs??0)},e=()=>!Q||K<z+1,Of=(R,u)=>{let{state:V,...B}=u;return{phase:R,...B,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}},fE=(R)=>({phase:"rejected",requestClass:R.requestClass,resource:R.resource,scope:R.scope,reason:R.reason,queuePosition:0,queueDepth:Math.max(0,R.queued),inFlight:Math.max(0,R.inFlight),limit:Math.max(0,R.limit),waitMs:R.reason==="wait_timeout"?R.maxWaitMs:0,maxWaitMs:R.maxWaitMs,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),u_=async function*(R,u){if(!nf)return{release:()=>{return}};let V=X()?.recoveryRemainingMs,B=V!==void 0&&A?.startedAt!==void 0?Math.min(ef,V):ef,I;try{I=nf.admit({scope:N_(R,u),sessionId:bf.sessionId,ownerId:bf.ownerId,requestClass:bf.requestClass,maxWaitMs:B,pendingBytes:S,signal:_})}catch(b){if(l(b)){if(b.reason==="wait_timeout"&&A?.startedAt!==void 0&&(X()?.recoveryRemainingMs??0)<=0)throw p();yield{providerAdmission:fE(b)}}throw b}let G=I.getSnapshot();if(G.state==="admitted")return await I.ready;yield{providerAdmission:Of("queued",G)};let v=I.ready.then((b)=>({kind:"ready",permit:b}),(b)=>({kind:"error",error:b}));while(!0){let b=I.getSnapshot(),O=Math.max(1,Math.min(oE,Math.max(1,B-b.waitMs))),W,c=new Promise((m)=>{W=setTimeout(()=>m({kind:"heartbeat"}),O),W.unref?.()}),k=await Promise.race([v,c]);if(W)clearTimeout(W);if(k.kind==="heartbeat"){yield{providerAdmission:Of("queued",I.getSnapshot())};continue}if(k.kind==="error"){if(l(k.error)){if(k.error.reason==="wait_timeout"&&A?.startedAt!==void 0&&(X()?.recoveryRemainingMs??0)<=0)throw p();yield{providerAdmission:fE(k.error)}}throw k.error}return yield{providerAdmission:Of("admitted",I.getSnapshot())},k.permit}},D_=(R,u)=>{if(!e())throw p();if(Q)K++;F=void 0;let V=new AbortController,B=_?PE(_,V.signal):V.signal,I=typeof u.timeout==="number"&&Number.isFinite(u.timeout)&&u.timeout>0?Math.max(1,Math.floor(u.timeout)):void 0,G;if(A?.startedAt!==void 0){let O=X()?.recoveryRemainingMs??0;if(O<=0)throw p();G={remainingMs:O,error:new n(A.budgetMs,A.budgetMs)}}let v=iE(u,R,B,T,N);f_(v,R,(O)=>{F=O});let b=h_(this.models,R,P,v,{idleTimeoutMs:u.streamIdleTimeout??Yf,signal:B,abort:(O)=>V.abort(O)});return async function*(){let O,W;try{if(I!==void 0&&(G===void 0||I<G.remainingMs)){let c=new vf(I);O=setTimeout(()=>V.abort(c),I),O.unref?.()}if(G){let c=G;W=setTimeout(()=>V.abort(c.error),c.remainingMs),W.unref?.()}yield*b}finally{if(O)clearTimeout(O);if(W)clearTimeout(W)}}()},EE=this,y=(R)=>({phase:R.phase,reason:R.reason,...R.statusCode!==void 0?{statusCode:R.statusCode}:{},...R.retryAfterMs!==void 0?{retryAfterMs:R.retryAfterMs}:{},...R.nextProbeAt!==void 0?{nextProbeAt:R.nextProbeAt}:{},openDurationMs:R.openDurationMs,sampleCount:R.sampleCount,failureCount:R.failureCount,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),_E=(R,u)=>({phase:R,reason:u.reason,...u.statusCode!==void 0?{statusCode:u.statusCode}:{},retryAfterMs:u.retryAfterMs,...u.nextProbeAt!==void 0?{nextProbeAt:u.nextProbeAt}:{},openDurationMs:u.openDurationMs,sampleCount:u.sampleCount,failureCount:u.failureCount,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),I_=(R)=>({phase:"probe",reason:R.reason??"server_error",...R.statusCode!==void 0?{statusCode:R.statusCode}:{},openDurationMs:R.openDurationMs??Af,...R.sampleCount!==void 0?{sampleCount:R.sampleCount}:{},...R.failureCount!==void 0?{failureCount:R.failureCount}:{},...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),Vf=(R,u,V)=>({providerRetry:{phase:"exhausted",attempt:R,maxRetries:z,reason:u,...V!==void 0?{statusCode:V}:{},...w(),exhaustedBy:"recovery_budget"}}),TE=async function*(R,u,V,B,I){let G,v=!1,b,O,W=M_(R,u);for(let c=0;c<=B;c++){if(!e())break;let k,m;while(!k){let H=W.preflight();while(!H.eligible){if(b=H.reason,O=H.statusCode,!A||!I){let C=_E("rejected",H);throw yield{providerCircuit:C},new tf(C)}rf();let j=X()?.recoveryRemainingMs??0;if(j<=0){let C=p();throw yield Vf(Q?Math.max(0,K-1):c,H.reason,H.statusCode),C}yield{providerCircuit:_E("waiting",H)};let q=Math.min(Math.max(1,H.retryAfterMs),yf,j);if(await _f(q,_,{throwOnAbort:!0}),(X()?.recoveryRemainingMs??0)<=0){let C=p();throw yield Vf(Q?Math.max(0,K-1):c,H.reason,H.statusCode),C}H=W.preflight()}try{m=yield*u_(R,u)}catch(Z){if(Z instanceof n)yield Vf(Q?Math.max(0,K-1):c,b??"timeout",O);throw Z}let L=W.check();if(L.allowed)k=L;else m.release(),m=void 0}let i=k.token;if(k.probe)yield{providerCircuit:I_(k)};try{let H=!1,L=!1;for await(let Z of D_(R,u)){if(Z.providerStall){yield Z;continue}let j=Q?K-1:c;if(j>0&&b&&!H)H=!0,yield{providerRetry:{phase:"recovered",attempt:j,maxRetries:z,reason:b,...O!==void 0?{statusCode:O}:{},...w()}};if(!L){L=!0;let q=W.recordSuccess(i);if(q)yield{providerCircuit:y(q)}}v=!0,V(),yield M(Z,R)}if(!L){let Z=W.recordSuccess(i);if(Z)yield{providerCircuit:y(Z)}}return}catch(H){if(m?.release(),G=H,EE.logIdleTimeout(H,v,R),await EE.handleAbort(_),H instanceof n){if(v)throw sf(H),H;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:z,reason:b??"timeout",...O!==void 0?{statusCode:O}:{},...w(),exhaustedBy:"recovery_budget"}},H}let L=o(H,F);if(v)throw sf(H),H;let Z=cT(H,F),j=Z?W.recordFailure(i,Z):F&&!lf(H)?W.recordNeutral(i):void 0;if(j)yield{providerCircuit:y(j)};if(!L.retryable||!L.reason){if(c>0&&b)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:z,reason:b,...O!==void 0?{statusCode:O}:{},...w()}};throw H}b=L.reason,O=L.statusCode;let q=c<B&&e();if(j&&j.phase!=="closed"&&q&&(!A||!I)){let C={...y(j),phase:"rejected"};throw yield{providerCircuit:C},new tf(C)}if(q){rf();let C=Q?K:c+1,U_=lE(C,F,A?{maxDelayMs:af,maxExponentialDelayMs:af}:void 0),xE=j&&j.phase!=="closed"?j.retryAfterMs??0:0;if(A&&xE>0&&j)yield{providerCircuit:{...y(j),phase:"waiting"}};let Y_=X(),Xf=Math.max(U_,xE),ff=A?Math.min(Xf,Y_?.recoveryRemainingMs??Xf):Xf,Mf={attempt:C,maxRetries:z,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Mf,delayMs:ff,nextRetryAt:Date.now()+ff,...w()}},A){let Ef=ff;while(Ef>0){let tE=Math.min(Ef,yf);if(await _f(tE,_,{throwOnAbort:!0}),Ef-=tE,(X()?.recoveryRemainingMs??0)<=0){let Nf=p();throw yield{providerRetry:{phase:"exhausted",...Mf,...w(),exhaustedBy:"recovery_budget"}},Nf}if(Ef>0){if(j&&j.phase!=="closed"&&j.nextProbeAt!==void 0){let Nf=Math.max(0,j.nextProbeAt-Date.now());if(Nf>0)yield{providerCircuit:{...y(j),phase:"waiting",retryAfterMs:Nf}}}yield{providerRetry:{phase:"waiting",...Mf,delayMs:ff,nextRetryAt:Date.now()+Ef,...w()}}}}}else await _f(ff,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Mf,...w()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:z,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{},...w(),...A&&(I||!e())?{exhaustedBy:"attempt_limit"}:{}}}}finally{W.abandon(i),m?.release()}}throw G},Sf,hE=!1,jf=this.model,r=this.config.fallbackModels??[],H_=A&&r.length>0?Math.min(Y,z):z;try{for await(let R of TE(this.model,this.config,()=>{hE=!0},H_,r.length===0))yield R;return}catch(R){if(Sf=R,hE||!l(R)&&!Rf(R)&&!lf(R)&&!o(R,F).retryable)throw R}for(let[R,u]of r.entries()){if(!e())break;let V=!1;try{let B=VT(this.config,u),I=UE(B,u);yield{modelFallback:{from:pf(jf.provider,jf.id),to:pf(I.provider,I.id),candidate:R+1,candidateCount:r.length,trigger:yE(Sf,F)}},jf=I;let G=R===r.length-1,v=A&&!G?Math.min(Y,z):z;for await(let b of TE(I,B,()=>{V=!0},v,G))yield b;return}catch(B){if(Sf=B,V||!l(B)&&!Rf(B)&&!lf(B)&&!o(B,F).retryable)throw B}}throw Sf}async handleAbort(f){if(f?.aborted)await _f(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;gf.warn("[PiAIChatService] Provider stream idle timeout",{provider:_.provider,model:_.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:E})}getConfig(){return{...this.config}}updateConfig(f){let E={...this.config,...f},_=Wf(E);this.config={...E,maxContextTokens:_.model.contextWindow,maxOutputTokens:E.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,this.providerAdmissionScheduler=x_(this.config)}}function x_(f){if(f.providerRequestAdmissionScheduler)return f.providerRequestAdmissionScheduler;if(f.providerRequestConcurrency===void 0&&f.providerGlobalConcurrency===void 0&&f.providerOwnerConcurrency===void 0)return;let E=f.providerGlobalConcurrency??Number.MAX_SAFE_INTEGER,_=f.providerOwnerConcurrency??Number.MAX_SAFE_INTEGER;return mE({globalMaxInFlight:E,ownerMaxInFlight:_,nonForegroundGlobalMaxInFlight:E,nonForegroundOwnerMaxInFlight:_,internalGlobalMaxInFlight:E,internalDomainMaxInFlight:f.providerRequestConcurrency??g,classLimitsEnabled:!1})}var JT=a("Service");async function mh(f){let E=f;if(E.provider){let _=RE(E.provider);if(Object.keys(_).length>0)E={...E,customHeaders:{..._,...E.customHeaders}},JT.debug(`Injected ${E.provider} specific headers:`,Object.keys(_))}return WT(E)}function WT(f){return new df(f)}
|
|
5
|
-
export{LT as
|
|
5
|
+
export{LT as dg,ZT as eg,PE as fg,_f as gg,l as hg,xT as ig,Rh as jg,o as kg,lE as lg,aE as mg,df as ng,mh as og};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{D as
|
|
1
|
+
import{vg as B}from"./chunk-7wcxjbyg.js";import{Oj as Y}from"./chunk-0b67y4j1.js";import{Rj as Z,Uj as $}from"./chunk-9kj19a8t.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
|
|
2
|
+
export{D as rg,h as sg,j as tg};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{k as o}from"./chunk-
|
|
1
|
+
import{k as o}from"./chunk-tqg9y2p6.js";import"./chunk-f2jm4x5q.js";import"./chunk-sdapqhj0.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
|
var I=600000,r=30000,t=3600000,o=12,O=15000,P=60000;function R(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=30000&&_<=3600000}var C=1e4,M=1000,p=300000;function E(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=300000}var T=1,s=16,n=Number.MAX_SAFE_INTEGER,D=180000,m=1000,x=600000,S=134217728,U=65536,V=134217728;function A(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=16}function w(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=n}function z(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=600000}function F(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=65536&&_<=134217728}
|
|
2
|
-
export{I as
|
|
2
|
+
export{I as bj,r as cj,t as dj,o as ej,O as fj,P as gj,R as hj,C as ij,M as jj,p as kj,E as lj,T as mj,s as nj,n as oj,D as pj,m as qj,x as rj,S as sj,U as tj,V as uj,A as vj,w as wj,z as xj,F as yj};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{promises as B}from"node:fs";import q from"node:path";import{LRUCache as H}from"lru-cache";var K=512,Z=new H({max:K});async function L(x){let b=x;while(!0){try{return await B.lstat(q.join(b,".git")),b}catch(V){if(V.code!=="ENOENT")return}let F=q.dirname(b);if(F===b)return;b=F}}async function M(x){let b=q.join(x,".git"),F=await B.lstat(b);if(F.isDirectory())return x;if(!F.isFile())return;let V=await B.readFile(b,"utf8"),J=/^gitdir:\s*(.+)\s*$/im.exec(V);if(!J)return;let Q=await B.realpath(q.isAbsolute(J[1])?J[1]:q.resolve(x,J[1])),Y=Q;try{let z=(await B.readFile(q.join(Q,"commondir"),"utf8")).trim();if(z)Y=await B.realpath(q.resolve(Q,z))}catch(z){if(z.code!=="ENOENT")throw z}return q.basename(Y)===".git"?B.realpath(q.dirname(Y)):void 0}async function N(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x),F=Z.get(b);if(F)return F;let V=b;try{let Q=await L(b);if(Q){let Y=await M(Q),z=q.relative(Q,b);if(Y&&(z===""||!z.startsWith(`..${q.sep}`)&&z!==".."&&!q.isAbsolute(z))){let $=q.resolve(Y,z);V=await B.realpath($).catch(()=>$)}}}catch{}let J={projectPath:b,trustRoot:V};return Z.set(b,J),J}async function S(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x);Z.delete(b)}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as ck,S as dk};
|