blade-code 0.10.69 → 0.10.70
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-g324ww9d.js → chunk-0kmrvxsz.js} +262 -263
- package/dist/{chunk-ypqp368c.js → chunk-0p0e70cy.js} +1 -1
- package/dist/{chunk-crkkpx3m.js → chunk-0p95nha3.js} +1 -1
- package/dist/{chunk-2da7j2sw.js → chunk-1bcp0qc4.js} +1 -1
- package/dist/{chunk-6pkyc8r6.js → chunk-1z9k5dmz.js} +1 -1
- package/dist/{chunk-bbcb9jzb.js → chunk-20vj0npz.js} +1 -1
- package/dist/chunk-2z75emht.js +1 -0
- package/dist/{chunk-2e7sedzn.js → chunk-31k6x4kn.js} +2 -2
- package/dist/chunk-3j413cgh.js +1 -0
- package/dist/chunk-4aam3qhk.js +8 -0
- package/dist/{chunk-efemjy9y.js → chunk-4md4sd4j.js} +1 -1
- package/dist/{chunk-kwv6vyst.js → chunk-5wnx38ze.js} +1 -1
- package/dist/{chunk-1z9wct9w.js → chunk-63121s4r.js} +1 -1
- package/dist/{chunk-n6rgqmf7.js → chunk-728anavt.js} +1 -1
- package/dist/{chunk-dfrgc84s.js → chunk-7b5s752s.js} +1 -1
- package/dist/{chunk-c8h3c8an.js → chunk-832va1mp.js} +1 -1
- package/dist/{chunk-b793bj62.js → chunk-83b4vfjs.js} +7 -7
- package/dist/chunk-8bsyhr4v.js +1 -0
- package/dist/{chunk-ppsvzgs5.js → chunk-8wea3qty.js} +2 -2
- package/dist/{chunk-yvg961q3.js → chunk-b2p4kd07.js} +1 -1
- package/dist/{chunk-kf070906.js → chunk-b39p4f5r.js} +1 -1
- package/dist/{chunk-7cm6tfnn.js → chunk-bkajr86v.js} +1 -1
- package/dist/{chunk-16n849z3.js → chunk-brdxkp0y.js} +1 -1
- package/dist/chunk-c0qm0wwk.js +1 -0
- package/dist/{chunk-xjse24zd.js → chunk-cmpj3a5a.js} +1 -1
- package/dist/chunk-cx5s0rf3.js +1 -0
- package/dist/{chunk-1xjzd1jn.js → chunk-d2vrbbvd.js} +1 -1
- package/dist/{chunk-98n2rxmq.js → chunk-d808m826.js} +1 -1
- package/dist/chunk-e3asq942.js +1 -0
- package/dist/{chunk-zdxxqchm.js → chunk-f7yfcw8s.js} +1 -1
- package/dist/{chunk-8gd0ksz7.js → chunk-ffym3kf3.js} +1 -1
- package/dist/{chunk-50jthhfq.js → chunk-g28pgqyn.js} +1 -1
- package/dist/{chunk-ftmbgtnk.js → chunk-h94vfh7s.js} +1 -1
- package/dist/{chunk-5d2cdvdy.js → chunk-jrr361h1.js} +1 -1
- package/dist/{chunk-hcv17986.js → chunk-k6shq7rk.js} +1 -1
- package/dist/chunk-nea4rcdf.js +1 -0
- package/dist/{chunk-qd9vk8t1.js → chunk-p9vaaayr.js} +6 -6
- package/dist/{chunk-68zek95f.js → chunk-pw87f92g.js} +1 -1
- package/dist/chunk-q919ypcz.js +5 -0
- package/dist/{chunk-asgyyv1s.js → chunk-qm5c9wew.js} +2 -2
- package/dist/{chunk-jj0b6n20.js → chunk-qstf0gpe.js} +1 -1
- package/dist/{chunk-nxek5ev2.js → chunk-r9n8y8m1.js} +1 -1
- package/dist/{chunk-qjg390mv.js → chunk-rpfa4a56.js} +1 -1
- package/dist/{chunk-v712dqde.js → chunk-sch01e04.js} +1 -1
- package/dist/{chunk-a0j0xwt1.js → chunk-sh17gjxv.js} +1 -1
- package/dist/{chunk-rpmmy3qs.js → chunk-smjkx71w.js} +1 -1
- package/dist/chunk-v3kkv21n.js +1 -0
- package/dist/{chunk-z9p0by31.js → chunk-w2gr97qt.js} +1 -1
- package/dist/{chunk-ptcb5fb7.js → chunk-wahhwjp9.js} +1 -1
- package/dist/{chunk-5147jh26.js → chunk-wepvrnmh.js} +1 -1
- package/dist/chunk-wj6t3tv2.js +3 -0
- package/dist/chunk-wkpacysr.js +166 -0
- package/dist/{chunk-4ge1jkf8.js → chunk-y9d9nqnn.js} +1 -1
- package/dist/{chunk-dktrankr.js → chunk-ypgjqg23.js} +1 -1
- package/dist/{chunk-kmarzy98.js → chunk-ysmqje92.js} +1 -1
- package/dist/{chunk-mgv3qr9b.js → chunk-z77c18j5.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-0f8nn2h1.js +0 -5
- package/dist/chunk-8gzm51m8.js +0 -1
- package/dist/chunk-bvyydst6.js +0 -166
- package/dist/chunk-e7pssnr9.js +0 -1
- package/dist/chunk-eym0bdee.js +0 -1
- package/dist/chunk-hsgcdk2a.js +0 -1
- package/dist/chunk-m65pse74.js +0 -1
- package/dist/chunk-q9y9hxnt.js +0 -1
- package/dist/chunk-qz0pe10c.js +0 -1
- package/dist/chunk-t2gq918a.js +0 -3
- package/dist/chunk-w3fy09rw.js +0 -8
- package/dist/chunk-w67k19a1.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.
|
|
1
|
+
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.70",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
|
|
2
2
|
export{y as ih,p as jh,v as kh,g as lh,f as mh,w as nh};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{bh as o}from"./chunk-
|
|
1
|
+
import{bh as o}from"./chunk-0p0e70cy.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
|
|
2
2
|
export{e as j,i as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{bd as a,cd as b,dd as c,ed as d,fd as e,gd as f,hd as g,id as h}from"./chunk-
|
|
1
|
+
import{bd as a,cd as b,dd as c,ed as d,fd as e,gd as f,hd as g,id as h}from"./chunk-f7yfcw8s.js";import"./chunk-d808m826.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ja as F,la as L}from"./chunk-
|
|
1
|
+
import{ja as F,la as L}from"./chunk-0kmrvxsz.js";import{Dc as $,Fc as B,Nc as Q}from"./chunk-1z9k5dmz.js";import{Je as y}from"./chunk-wahhwjp9.js";import{wg as V}from"./chunk-k0pa8874.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
|
|
2
2
|
|
|
3
3
|
${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{j as m,I as n,M as o,R as p,_ as q,C as r};
|
package/package.json
CHANGED
package/dist/chunk-0f8nn2h1.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{Ag as i_,Bg as wf,Cg as pf,Dg as fE,Eg as Xf,Gg as zf,Ig as $f,Jg as uf,Kg as cf,Lg as kf,Ng as Pf,Og as Lf,Qg as Q}from"./chunk-6pyktfa4.js";import{Xg as m}from"./chunk-98n2rxmq.js";import{$g as t_,bh as Cf}from"./chunk-ypqp368c.js";import{eh as l_}from"./chunk-t8xmh4w2.js";var PE={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},f_=(f)=>PE[f]||{};var DE=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function sf(f){return typeof f==="string"&&DE.has(f)}function bT(f){if(!f.aborted)return;if(sf(f.reason))return f.reason;return"user-cancel"}function CT(f){if(sf(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 __(...f){let _=f.filter(Boolean);if(_.length===0)return new AbortController().signal;if(_.length===1)return _[0];let E=AbortSignal;if(typeof E.any==="function")return E.any(_);for(let h of _)if(h.aborted)return h;let T=new AbortController,x=new Map;for(let h of _){let u=()=>{T.abort(h.reason);for(let[S,t]of x)S.removeEventListener("abort",t)};x.set(h,u)}for(let[h,u]of x)h.addEventListener("abort",u,{once:!0});return T.signal}function d(f,_,E){let T=E?.throwOnAbort??!1;if(_?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((x,h)=>{let u,S=setTimeout(()=>{if(_&&u)_.removeEventListener("abort",u);x()},f);if(_)u=()=>{if(clearTimeout(S),T)h(new DOMException("Aborted","AbortError"));else x()},_.addEventListener("abort",u,{once:!0})})}var HE=m("Chat"),UE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Vf(f){if(typeof f==="string")return f;return f.filter((_)=>_.type==="text").map((_)=>_.text).join(`
|
|
2
|
-
`)}function YE(f){if(!f)return{};try{let _=JSON.parse(f);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return HE.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function NE(f){let _=f.match(/^data:([^;,]+);base64,(.+)$/s);return _?{mimeType:_[1],data:_[2]}:void 0}async function OE(f,_){let E=NE(f);if(E)return{type:"image",...E};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:_});if(!T.ok)throw Error(`Failed to load image ${f}: HTTP ${T.status}`);return{type:"image",mimeType:T.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await T.arrayBuffer()).toString("base64")}}async function T_(f,_,E,T,x){let h=f.filter((t)=>t.role==="system").map((t)=>Vf(t.content)).filter(Boolean).join(`
|
|
3
|
-
|
|
4
|
-
`),u=[];for(let t of f){if(t.role==="system")continue;if(t.role==="user"){let c=_.input.includes("image"),M=typeof t.content==="string"?t.content:await Promise.all(t.content.map((R)=>R.type==="text"?Promise.resolve({type:"text",text:R.text}):c?OE(R.image_url.url,T):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));u.push({role:"user",content:M,timestamp:Date.now()});continue}if(t.role==="assistant"){let c=[];if(t.reasoningContent?.trim())c.push({type:"thinking",thinking:t.reasoningContent});let M=Vf(t.content);if(M)c.push({type:"text",text:M});for(let R of t.tool_calls??[]){if(!("function"in R))continue;c.push({type:"toolCall",id:R.id,name:R.function.name,arguments:YE(R.function.arguments)})}u.push({role:"assistant",content:c,api:_.api,provider:_.provider,model:_.id,usage:UE,stopReason:t.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}u.push({role:"toolResult",toolCallId:t.tool_call_id??"",toolName:t.name??"unknown",content:[{type:"text",text:Vf(t.content)}],isError:!1,timestamp:Date.now()})}let S=E?.filter((t)=>!x||t.name===x).map((t)=>({name:t.name,description:t.description,parameters:t.parameters,constrainedSampling:t.constrainedSampling})).sort((t,c)=>t.name<c.name?-1:t.name>c.name?1:0);return{...h?{systemPrompt:h}:{},messages:u,...S?.length?{tools:S}:{}}}function x_(f){let _=[];for(let E=0;E<f.length;E++){let T=f[E];if(T.role==="tool")continue;let x=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!x){_.push(T);continue}let h=[],u=E+1;while(u<f.length&&f[u].role==="tool")h.push(f[u++]);let S=new Set(x.map((M)=>M.id)),t=h.filter((M)=>M.tool_call_id&&S.has(M.tool_call_id)),c=new Set(t.map((M)=>M.tool_call_id));if(S.size===x.length&&t.length===S.size&&c.size===S.size)_.push(T,...t);E=u-1}return _}function h_(f){return f.some((_)=>_.role==="assistant"&&Boolean(_.tool_calls?.length)&&!_.reasoningContent?.trim())}function M_(f,_){return{...f,..._.baseUrl?{baseUrl:t_(f.api,_.baseUrl)}:{},..._.maxOutputTokens?{maxTokens:_.maxOutputTokens}:{}}}function jf(f){let _=f.modelCatalog??Cf();return{models:_.models,model:M_(_.getModel(f.provider,f.model),f)}}function R_(f,_){let E=f.modelCatalog??Cf();return M_(E.getModel(_.provider,_.model),f)}import{createHash as bE}from"node:crypto";var sE=32,VE=1000,CE=512,jE=2000,BE=0.1,XE=0.05,zE=0.9,IE=300000,JE=3600000;class Bf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let _=f.now??Date.now(),E=WE(f,_),T=this.sessions.get(f.sessionId);if(E.callCount=(T?.callCount??0)+1,this.touch(f.sessionId,E),T&&E.contextEpoch!==T.contextEpoch)return;if(!T||T.cacheReadTokens<VE)return;let x=T.cacheReadTokens-E.cacheReadTokens,h=Math.min(jE,Math.max(CE,T.cacheReadTokens*BE));if(x<h||E.cacheReadTokens>=T.cacheReadTokens*(1-XE))return;let u=E.modelIdentity!==T.modelIdentity,S=E.systemHash!==T.systemHash,t=E.toolsHash!==T.toolsHash,c=E.policyHash!==T.policyHash;if(!(u||S||t||c)&&E.promptTokens<T.promptTokens*zE)return;let R=Math.max(0,_-T.recordedAt),D=T.retention==="long"?JE:IE,Y=u?"model_changed":S?"system_prompt_changed":t?"tools_changed":c?"request_policy_changed":R>=D?"ttl_expired":"server_side",z=$E(T,E);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:E.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:x,elapsedMs:R,callNumber:E.callCount,systemPromptChanged:S,systemCharDelta:E.systemChars-T.systemChars,toolsChanged:t,addedToolCount:z.added,removedToolCount:z.removed,changedToolCount:z.changed,modelChanged:u,requestPolicyChanged:c}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,_){this.sessions.delete(f),this.sessions.set(f,_);while(this.sessions.size>sE){let E=this.sessions.keys().next().value;if(E===void 0)break;this.sessions.delete(E)}}}function WE(f,_){let E=[...f.tools??f.context.tools??[]].map((T)=>({identityHash:n(T.name),contractHash:n(i(T))})).sort((T,x)=>T.identityHash<x.identityHash?-1:T.identityHash>x.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:n(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:n(i(E)),toolFingerprints:E,policyHash:n(i(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:_,callCount:1}}function $E(f,_){let E=new Map(f.toolFingerprints.map((x)=>[x.identityHash,x.contractHash])),T=new Map(_.toolFingerprints.map((x)=>[x.identityHash,x.contractHash]));return{added:[...T.keys()].filter((x)=>!E.has(x)).length,removed:[...E.keys()].filter((x)=>!T.has(x)).length,changed:[...T].filter(([x,h])=>E.has(x)&&E.get(x)!==h).length}}function i(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(i).join(",")}]`;let _=f;return`{${Object.keys(_).sort().map((E)=>`${JSON.stringify(E)}:${i(_[E])}`).join(",")}}`}function n(f){return bE("sha256").update(f).digest("hex")}import{randomBytes as ZE}from"node:crypto";import{createHmac as kE}from"node:crypto";function LE(f){try{let _=new URL(f);if(_.hash="",_.hostname=_.hostname.toLowerCase(),_.searchParams.sort(),_.pathname!=="/")_.pathname=_.pathname.replace(/\/+$/,"");return _.toString()}catch{return f.trim().replace(/\/+$/,"")}}function GE(f){if(!f)return[];return Object.entries(f).map(([_,E])=>[_.trim().toLowerCase(),E.trim()]).sort(([_],[E])=>_.localeCompare(E))}function Rf(f,_,E){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),LE(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",GE(f.customHeaders),E]);return kE("sha256",Buffer.from(_)).update(T).digest("hex")}var KE=60000,QE=4,FE=0.8;var Sf=300000,If=600000;var A_=128,S_=256,vE=1800000,Af=50;class _f extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function Jf(f){return f instanceof _f||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function q(f,_){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:_}function oE(f,_){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:_}function wE(f,_){return Rf(f,_,{providerCircuitOpenDurationMs:f.openDurationMs})}function ff(f){let _=0;for(let E of f)if(E.failure)_++;return _}function u_(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function c_(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),zf)}class D_{#h=new Map;#R=new WeakMap;#f;#_;#T;#E;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):ZE(32),this.#_=f.now??(()=>performance.now()),this.#T=f.wallNow??f.now??Date.now,this.#E={maxEntries:Math.min(q(f.maxEntries,A_),A_),maxWindowEntries:Math.min(q(f.maxWindowEntries,S_),S_),windowMs:q(f.windowMs,KE),minSamples:q(f.minSamples,QE),errorRateThreshold:oE(f.errorRateThreshold,FE),idleTtlMs:q(f.idleTtlMs,vE)}}get size(){return this.#h.size}get(f){if(f.openDurationMs===0)return this.#t();let _=this.#_();this.#N(_);let E=wE(f,this.#f),T=this.#h.get(E);if(T)return T.lastTouchedAt=_,this.#x(T,f.probeLeaseMs);if(this.#h.size>=this.#E.maxEntries)this.#s();if(this.#h.size>=this.#E.maxEntries)return this.#t();let x={key:E,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:_,detached:!1};return this.#h.set(E,x),this.#x(x,f.probeLeaseMs)}#x(f,_){let E=this,T=Math.max(Sf,Math.min(q(_,Sf),If));return{preflight:()=>E.#c(f),check:()=>E.#P(f,T),recordSuccess:(x)=>E.#U(x,"success"),recordFailure:(x,h)=>E.#U(x,"failure",h),recordNeutral:(x)=>E.#U(x,"neutral"),abandon:(x)=>E.#b(x),snapshot:()=>E.#O(f)}}#t(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let _=Object.freeze({kind:"noop"});return f.#R.set(_,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:_}},recordSuccess:(_)=>f.#M(_),recordFailure:(_)=>f.#M(_),recordNeutral:(_)=>f.#M(_),abandon:(_)=>f.#b(_),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#M(f){let _=this.#R.get(f);if(_?.kind==="noop")_.settled=!0;return}#c(f){let _=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=_,this.#Y(f,_),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??_;return _<T?this.#A(f,T-_):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return{eligible:!0};let E=Math.max(1,(f.probeLeaseExpiresAt??_+Af)-_);return this.#A(f,Math.min(Af,E))}#A(f,_){let{allowed:E,...T}=this.#H(f,_);return{eligible:!1,...T}}#P(f,_){let E=this.#_();if(f.detached)return this.#t().check();if(f.lastTouchedAt=E,this.#Y(f,E),f.state==="closed")return this.#S(f,"regular");if(f.state==="open"){let x=f.nextProbeAt??E;if(E<x)return this.#H(f,x-E);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return this.#D(f,E,_);let T=Math.max(1,(f.probeLeaseExpiresAt??E+Af)-E);return this.#H(f,Math.min(Af,T))}#S(f,_,E){let T=Object.freeze({kind:_});return this.#R.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:_,...E!==void 0?{probeLeaseId:E}:{},settled:!1}),{allowed:!0,probe:_==="probe",token:T}}#D(f,_,E){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=_+E,f.lastTouchedAt=_;let x=this.#S(f,"probe",T),h=f.lastFailure??{reason:"server_error"};return{...x,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:ff(f.samples)}}#H(f,_){let E=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(_)),nextProbeAt:this.#T()+Math.max(0,Math.ceil(_)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:ff(f.samples)}}#U(f,_,E){let T=this.#R.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let x=T.entry;if(x.detached||T.generation!==x.generation||T.kind==="regular"&&x.state!=="closed"||T.kind==="probe"&&(x.state!=="half_open"||T.probeLeaseId!==x.probeLeaseId))return;let h=this.#_();if(x.lastTouchedAt=h,T.kind==="probe"){if(_==="failure"&&E)return this.#u(x,E,h,"reopened");return this.#C(x)}if(_==="neutral")return;if(this.#j(x,_==="failure",h),_!=="failure"||!E)return;let u=ff(x.samples),S=x.samples.length===0?0:u/x.samples.length;if(x.samples.length>=this.#E.minSamples&&S>=this.#E.errorRateThreshold)return this.#u(x,E,h,"opened");return}#u(f,_,E,T){let x={reason:_.reason,...u_(_.statusCode)!==void 0?{statusCode:u_(_.statusCode)}:{},...c_(_.retryAfterMs)!==void 0?{retryAfterMs:c_(_.retryAfterMs)}:{}},h=x.retryAfterMs??0,u=Math.max(f.configuredOpenDurationMs,h);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=u,f.nextProbeAt=E+u,f.lastFailure=x,{phase:T,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},retryAfterMs:u,nextProbeAt:this.#T()+u,openDurationMs:u,sampleCount:f.samples.length,failureCount:ff(f.samples)}}#C(f){let _=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#b(f){let _=this.#R.get(f);if(!_||_.settled)return!1;if(_.settled=!0,_.kind==="noop")return!0;let E=_.entry;if(!E||E.detached||_.kind!=="probe"||_.generation!==E.generation||_.probeLeaseId!==E.probeLeaseId)return!1;return E.probeLeaseId=void 0,E.probeLeaseExpiresAt=void 0,E.lastTouchedAt=this.#_(),!0}#j(f,_,E){if(this.#Y(f,E),f.samples.length>=this.#E.maxWindowEntries)f.samples.shift();f.samples.push({at:E,failure:_})}#Y(f,_){let E=_-this.#E.windowMs,T=0;while(T<f.samples.length&&f.samples[T].at<E)T++;if(T>0)f.samples.splice(0,T)}#O(f){if(!f.detached)this.#Y(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:ff(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#N(f){for(let[_,E]of this.#h)if(E.state==="closed"&&f-E.lastTouchedAt>this.#E.idleTtlMs)this.#V(_,E)}#s(){let f;for(let _ of this.#h.values())if(_.state==="closed"&&(!f||_.lastTouchedAt<f.lastTouchedAt))f=_;if(f)this.#V(f.key,f)}#V(f,_){_.detached=!0,this.#h.delete(f)}}var P_;function H_(){return P_??=new D_,P_}import{randomBytes as pE}from"node:crypto";var U_=16,Y_=128,N_=32,O_=3,b_=16,s_=96,V_=24,C_=12,j_=16,B_=4,X_=4,z_=67108864,I_=33554432,J_=12,W_=2,$_=2,k_=1,K_=15000,L_=30000;class Ef extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,_,E,T,x,h,u,S){super(f==="queue_full"?`Provider request admission ${_} ${T} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${_} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=_;this.requestClass=E;this.resource=T;this.inFlight=x;this.limit=h;this.queued=u;this.maxWaitMs=S;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function Tf(f){return f instanceof Ef||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function B(f,_,E){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return _;return Math.min(f,E)}function mE(f){let _=B(f.globalMaxInFlight,U_,U_),E=B(f.globalMaxPending,Y_,Y_),T=B(f.domainMaxPending,N_,N_),x=Math.min(B(f.ownerMaxInFlight,O_,O_),_),h=Math.min(B(f.ownerMaxPending,b_,b_),E),u=Math.min(B(f.nonForegroundGlobalMaxPending,Math.min(s_,Math.max(1,Math.floor(E*3/4))),s_),E),S=Math.min(B(f.nonForegroundDomainMaxPending,Math.min(V_,Math.max(1,Math.floor(T*3/4))),V_),T),t=Math.min(B(f.nonForegroundOwnerMaxPending,Math.min(C_,Math.max(1,Math.floor(h*3/4))),C_),h),c=Math.min(B(f.internalGlobalMaxPending,Math.min(j_,Math.max(1,Math.floor(E/8))),j_),u),M=Math.min(B(f.internalDomainMaxPending,Math.min(B_,Math.max(1,Math.floor(T/8))),B_),S),R=Math.min(B(f.internalOwnerMaxPending,Math.min(X_,Math.max(1,Math.floor(h/4))),X_),t),D=B(f.globalMaxPendingBytes,Q,Q),Y=Math.min(B(f.domainMaxPendingBytes,z_,z_),D),z=Math.min(B(f.ownerMaxPendingBytes,I_,I_),D),k=Math.min(B(f.nonForegroundGlobalMaxInFlight,Math.min(J_,_),J_),_),L=Math.min(B(f.nonForegroundOwnerMaxInFlight,Math.min(W_,x),W_),x),K=Math.min(B(f.internalGlobalMaxInFlight,Math.min($_,_),$_),_),Hf=B(f.internalDomainMaxInFlight,k_,k_),xf=B(f.agingMs,L_,L_);return{globalMaxInFlight:_,globalMaxPending:E,domainMaxPending:T,ownerMaxInFlight:x,ownerMaxPending:h,nonForegroundGlobalMaxPending:u,nonForegroundDomainMaxPending:S,nonForegroundOwnerMaxPending:t,internalGlobalMaxPending:c,internalDomainMaxPending:M,internalOwnerMaxPending:R,globalMaxPendingBytes:D,domainMaxPendingBytes:Y,ownerMaxPendingBytes:z,nonForegroundGlobalMaxInFlight:k,nonForegroundOwnerMaxInFlight:L,internalGlobalMaxInFlight:K,internalDomainMaxInFlight:Hf,agingMs:xf}}function G_(f,_){if(!f.trim())throw Error(`${_} must not be blank`)}function qE(f){if(G_(f.sessionId,"sessionId"),G_(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<uf||f.scope.maxConcurrent>cf)throw Error(`maxConcurrent must be between ${uf} and ${cf}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>Q)throw Error(`maxPendingBytes must be between 1 and ${Q}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>Q+1)throw Error(`pendingBytes must be between 1 and ${Q+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Pf)throw Error(`maxWaitMs must be 0-${Pf}`)}function Wf(f,_){if(_!==void 0)return _;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function lE(f,_){return Rf(f,_,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class Q_{#h;#R;#f;#_=[];#T=new Map;#E=new Map;#x=0;#t=0;#M=0;#c=0;#A=0;#P=0;#S=0;#D=0;#H=1;#U=0;#u=!1;constructor(f={}){this.#h=f.processSecret?new Uint8Array(f.processSecret):pE(32),this.#R=f.now??(()=>performance.now()),this.#f=mE(f)}admit(f){if(qE(f),this.#u)throw this.#z("closed",f,{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw Wf(f.signal);let _=lE(f.scope,this.#h),E=this.#T.get(_),T=this.#E.get(f.ownerId),x=E??this.#j(f.scope.maxConcurrent),h=T??this.#Y();if(this.#_.length===0&&this.#O(x,h,f.requestClass)){if(!E)this.#T.set(_,x);if(!T)this.#E.set(f.ownerId,h),this.#H++;let D=this.#s(_,f.ownerId,f.requestClass),Y=this.#Q(f,0);return{ready:Promise.resolve(D),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let u=this.#C(f,x,h);if(u)throw this.#z("queue_full",f,u,this.#_.length);let S=this.#N(x,h,f.requestClass);if(f.maxWaitMs===0)throw this.#z("wait_timeout",f,S,this.#_.length);if(!E)this.#T.set(_,x);if(!T)this.#E.set(f.ownerId,h),this.#H++;let t,c,M=new Promise((D,Y)=>{t=D,c=Y});M.catch(()=>{return});let R={domainKey:_,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#R(),signal:f.signal,resolve:t,reject:c,settled:!1,admitted:!1};if(f.signal)R.abortListener=()=>this.#I(R,Wf(f.signal)),f.signal.addEventListener("abort",R.abortListener,{once:!0});return R.timer=setTimeout(()=>this.#L(R),f.maxWaitMs),R.timer.unref?.(),this.#_.push(R),this.#b(x,h,R),this.#B(),{ready:M,getSnapshot:()=>this.#K(R),cancel:(D)=>this.#I(R,Wf(f.signal,D))}}close(){if(this.#u)return;this.#u=!0;for(let f of[...this.#_]){let _=this.#T.get(f.domainKey),E=this.#E.get(f.ownerId),T=_&&E?this.#N(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};this.#X(f,new Ef("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:this.#x,queued:this.#_.length,pendingBytes:this.#P,nonForegroundInFlight:this.#t,internalInFlight:this.#M,nonForegroundQueued:this.#c,internalQueued:this.#A,nonForegroundPendingBytes:this.#S,internalPendingBytes:this.#D,domainCount:this.#T.size,ownerCount:this.#E.size,closed:this.#u}}#C(f,_,E){let T=(M,R,D)=>R>=D?{scope:M,resource:"pending_count",inFlight:R,limit:D}:void 0;if(f.requestClass==="internal"){let M=T("class",this.#A,this.#f.internalGlobalMaxPending)??T("class",E.internalQueued,this.#f.internalOwnerMaxPending)??T("class",_.internalQueued,this.#f.internalDomainMaxPending);if(M)return M}if(f.requestClass!=="foreground"){let M=T("class",this.#c,this.#f.nonForegroundGlobalMaxPending)??T("class",E.nonForegroundQueued,this.#f.nonForegroundOwnerMaxPending)??T("class",_.nonForegroundQueued,this.#f.nonForegroundDomainMaxPending);if(M)return M}let x=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",E.queued,this.#f.ownerMaxPending)??T("domain",_.queued,this.#f.domainMaxPending);if(x)return x;let h=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),u=Math.min(h,this.#f.domainMaxPendingBytes),S=Math.min(h,this.#f.ownerMaxPendingBytes),t=(M,R)=>f.pendingBytes>R-M,c=(M)=>{if(M==="owner")return{scope:M,resource:"pending_bytes",inFlight:E.inFlight,limit:this.#f.ownerMaxInFlight};if(M==="domain")return{scope:M,resource:"pending_bytes",inFlight:_.inFlight,limit:_.maxConcurrent};return{scope:M,resource:"pending_bytes",inFlight:this.#x,limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let M=Math.max(1,Math.floor(h/8)),R=Math.max(1,Math.floor(u/4)),D=Math.max(1,Math.floor(S/4));if(t(this.#D,M)||t(E.internalPendingBytes,D)||t(_.internalPendingBytes,R))return c("class")}if(f.requestClass!=="foreground"){let M=Math.max(1,Math.floor(h*3/4)),R=Math.max(1,Math.floor(u*3/4)),D=Math.max(1,Math.floor(S/2));if(t(this.#S,M)||t(E.nonForegroundPendingBytes,D)||t(_.nonForegroundPendingBytes,R))return c("class")}if(t(this.#P,h))return c("global");if(t(E.pendingBytes,S))return c("owner");if(t(_.pendingBytes,u))return c("domain");return}#b(f,_,E){if(f.queued++,_.queued++,this.#P+=E.pendingBytes,f.pendingBytes+=E.pendingBytes,_.pendingBytes+=E.pendingBytes,E.requestClass!=="foreground")this.#c++,f.nonForegroundQueued++,_.nonForegroundQueued++,this.#S+=E.pendingBytes,f.nonForegroundPendingBytes+=E.pendingBytes,_.nonForegroundPendingBytes+=E.pendingBytes;if(E.requestClass==="internal")this.#A++,f.internalQueued++,_.internalQueued++,this.#D+=E.pendingBytes,f.internalPendingBytes+=E.pendingBytes,_.internalPendingBytes+=E.pendingBytes}#j(f){return{maxConcurrent:f,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#Y(){return{order:this.#H,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#O(f,_,E){if(this.#x>=this.#f.globalMaxInFlight)return!1;if(f.inFlight>=f.maxConcurrent)return!1;if(_.inFlight>=this.#f.ownerMaxInFlight)return!1;if(E==="foreground")return!0;if(this.#t>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(_.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=T)return!1;if(E!=="internal")return!0;return this.#M<this.#f.internalGlobalMaxInFlight&&f.internalInFlight<this.#f.internalDomainMaxInFlight}#N(f,_,E){if(_.inFlight>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:_.inFlight,limit:this.#f.ownerMaxInFlight};if(E!=="foreground"&&_.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:_.nonForegroundInFlight,limit:this.#f.nonForegroundOwnerMaxInFlight};if(f.inFlight>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent};if(E!=="foreground"){let T=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=T)return{scope:"class",resource:"stream",inFlight:f.nonForegroundInFlight,limit:T}}if(E==="internal"&&f.internalInFlight>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.internalInFlight,limit:this.#f.internalDomainMaxInFlight};if(this.#x>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};if(E!=="foreground"&&this.#t>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#t,limit:this.#f.nonForegroundGlobalMaxInFlight};if(E==="internal"&&this.#M>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#M,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent}}#s(f,_,E){let T=this.#T.get(f),x=this.#E.get(_);if(!T||!x)throw Error("Provider admission accounting state is unavailable");if(this.#x++,T.inFlight++,x.inFlight++,E!=="foreground")this.#t++,T.nonForegroundInFlight++,x.nonForegroundInFlight++;if(E==="internal")this.#M++,T.internalInFlight++,x.internalInFlight++;let h=!1;return{release:()=>{if(h)return;h=!0,this.#V(f,_,E)}}}#V(f,_,E){let T=this.#T.get(f),x=this.#E.get(_);if(this.#x=Math.max(0,this.#x-1),T)T.inFlight=Math.max(0,T.inFlight-1);if(x)x.inFlight=Math.max(0,x.inFlight-1);if(E!=="foreground"){if(this.#t=Math.max(0,this.#t-1),T)T.nonForegroundInFlight=Math.max(0,T.nonForegroundInFlight-1);if(x)x.nonForegroundInFlight=Math.max(0,x.nonForegroundInFlight-1)}if(E==="internal"){if(this.#M=Math.max(0,this.#M-1),T)T.internalInFlight=Math.max(0,T.internalInFlight-1);if(x)x.internalInFlight=Math.max(0,x.internalInFlight-1)}this.#W(f,_),this.#B()}#B(){if(this.#u)return;while(this.#_.length>0){let f=this.#R(),_=new Map;for(let[S,t]of this.#_.entries()){let c=this.#T.get(t.domainKey),M=this.#E.get(t.ownerId);if(c===void 0||M===void 0||!this.#O(c,M,t.requestClass))continue;let R=this.#$(t,f),D=_.get(t.ownerId);if(!D||R<D.rank||R===D.rank&&S<D.index)_.set(t.ownerId,{pending:t,rank:R,index:S})}let E=[..._.values()].filter(({pending:S})=>{let t=this.#T.get(S.domainKey),c=this.#E.get(S.ownerId);return t!==void 0&&c!==void 0&&this.#O(t,c,S.requestClass)}).map(({pending:S,rank:t})=>({pending:S,rank:t,order:this.#E.get(S.ownerId).order}));if(E.length===0)return;let T=Math.min(...E.map((S)=>S.rank)),x=E.filter((S)=>S.rank===T),u=x.filter((S)=>S.order>this.#U).sort((S,t)=>S.order-t.order)[0]??x.sort((S,t)=>S.order-t.order)[0];this.#k(u.pending,u.order)}}#$(f,_){let E=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,_-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,E-T)}#k(f,_){if(!this.#J(f,!1))return;f.settled=!0,f.admitted=!0,this.#U=_;let E=this.#s(f.domainKey,f.ownerId,f.requestClass);f.permit=E,f.resolve(E)}#L(f){let _=this.#T.get(f.domainKey),E=this.#E.get(f.ownerId),T=_&&E?this.#N(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};this.#X(f,new Ef("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#I(f,_){this.#X(f,_)}#X(f,_){if(!this.#J(f))return;f.settled=!0,f.reject(_),this.#B()}#J(f,_=!0){if(f.settled||f.admitted)return!1;let E=this.#_.indexOf(f);if(E<0)return!1;this.#_.splice(E,1);let T=this.#T.get(f.domainKey),x=this.#E.get(f.ownerId);if(T&&x)this.#G(T,x,f);if(this.#Z(f),_)this.#W(f.domainKey,f.ownerId);return!0}#G(f,_,E){if(f.queued=Math.max(0,f.queued-1),_.queued=Math.max(0,_.queued-1),this.#P=Math.max(0,this.#P-E.pendingBytes),f.pendingBytes=Math.max(0,f.pendingBytes-E.pendingBytes),_.pendingBytes=Math.max(0,_.pendingBytes-E.pendingBytes),E.requestClass!=="foreground")this.#c=Math.max(0,this.#c-1),f.nonForegroundQueued=Math.max(0,f.nonForegroundQueued-1),_.nonForegroundQueued=Math.max(0,_.nonForegroundQueued-1),this.#S=Math.max(0,this.#S-E.pendingBytes),f.nonForegroundPendingBytes=Math.max(0,f.nonForegroundPendingBytes-E.pendingBytes),_.nonForegroundPendingBytes=Math.max(0,_.nonForegroundPendingBytes-E.pendingBytes);if(E.requestClass==="internal")this.#A=Math.max(0,this.#A-1),f.internalQueued=Math.max(0,f.internalQueued-1),_.internalQueued=Math.max(0,_.internalQueued-1),this.#D=Math.max(0,this.#D-E.pendingBytes),f.internalPendingBytes=Math.max(0,f.internalPendingBytes-E.pendingBytes),_.internalPendingBytes=Math.max(0,_.internalPendingBytes-E.pendingBytes)}#Z(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#W(f,_){let E=this.#T.get(f);if(E&&E.inFlight===0&&E.queued===0)this.#T.delete(f);let T=this.#E.get(_);if(T&&T.inFlight===0&&T.queued===0)this.#E.delete(_)}#K(f){let _=Math.max(0,Math.floor(this.#R()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#x,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs};let E=this.#T.get(f.domainKey),T=this.#E.get(f.ownerId),x=E&&T?this.#N(E,T,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:x.resource,scope:x.scope,reason:"capacity",queuePosition:this.#F(f,x.scope),queueDepth:this.#_.length,inFlight:x.inFlight,limit:x.limit,waitMs:_,maxWaitMs:f.maxWaitMs}}#Q(f,_){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#x,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs}}#F(f,_){let E=this.#_.filter((T)=>{switch(_){case"owner":return T.ownerId===f.ownerId;case"domain":return T.domainKey===f.domainKey;case"class":return T.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,E.indexOf(f)+1)}#z(f,_,E,T){return new Ef(f,E.scope,_.requestClass,E.resource,E.inFlight,E.limit,T,_.maxWaitMs)}}var Z_;function F_(){return Z_??=new Q_,Z_}function v_(f,_={}){let E=_.maxBytes??134217728,T=_.maxNodes??1e5;if(!Number.isSafeInteger(E)||E<=0||E>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(T)||T<=0)throw Error("maxNodes must be a positive safe integer");let x=new WeakSet,h=0,u=0,S=!1,t=(M)=>{if(S||M<=0)return;if(!Number.isSafeInteger(M)||M>E-h){h=E+1,S=!0;return}h+=M},c=(M)=>{if(S)return;if(u+=1,u>T){t(E+1);return}if(M===null){t(4);return}switch(typeof M){case"string":t(Buffer.byteLength(M,"utf8"));return;case"number":case"bigint":t(8);return;case"boolean":t(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(x.has(M))return;if(x.add(M),ArrayBuffer.isView(M)){t(32+M.byteLength);return}if(M instanceof ArrayBuffer){t(32+M.byteLength);return}if(M instanceof Date){t(40);return}if(M instanceof RegExp){t(32+Buffer.byteLength(M.source,"utf8"));return}if(M instanceof Map){t(32);for(let[R,D]of M)if(c(R),c(D),S)return;return}if(M instanceof Set){t(32);for(let R of M)if(c(R),S)return;return}if(M instanceof WeakMap||M instanceof WeakSet){t(32);return}if(Array.isArray(M)){t(16);for(let R of M)if(c(R),S)return;return}t(32);for(let R of Reflect.ownKeys(M)){if(typeof R!=="string")continue;let D=Object.getOwnPropertyDescriptor(M,R);if(!D?.enumerable||!("value"in D))continue;if(t(8+Buffer.byteLength(R,"utf8")),c(D.value),S)return}};return c(f),h}function o_(f){return v_([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:Q})}var w_=new WeakSet;class l extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,_){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=_;this.name="ProviderRecoveryBudgetExceededError"}}class Gf 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 yE=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],aE=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],gE=["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 p_(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function rE(f){let _=p_(f);return aE.some((E)=>_.includes(E))}function Zf(f){if(f!==null&&typeof f==="object")w_.add(f)}function Tx(f){return f!==null&&typeof f==="object"&&w_.has(f)}function eE(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function dE(f){if(f===null||typeof f!=="object")return;let _=f;for(let E of["status","statusCode"]){let T=_[E];if(typeof T==="number"&&Number.isInteger(T))return T}return}function nE(f){let _=f.match(/^(?:error:\s*)?(\d{3})\b/),E=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(_?.[1]??E?.[1]);return Number.isInteger(T)?T:void 0}function y(f,_){let E=p_(f),T=eE(f);if(T==="STREAM_IDLE_TIMEOUT"||T==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||E.includes("request aborted")||E==="aborted")return{retryable:!1};if(yE.some((h)=>E.includes(h))||rE(f))return{retryable:!1};if(_?.shouldRetry==="false")return{retryable:!1,statusCode:_.statusCode};if(T==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let x=_?.statusCode??dE(f)??nE(E);if(_?.shouldRetry==="true")return{retryable:!0,reason:x===429?"rate_limit":x===408||x===409?"timeout":"server_error",statusCode:x};if(x===429)return{retryable:!0,reason:"rate_limit",statusCode:x};if(x===408||x===409)return{retryable:!0,reason:"timeout",statusCode:x};if(x!==void 0&&x>=500&&x<=599)return{retryable:!0,reason:"server_error",statusCode:x};if(T==="PROVIDER_STREAM_CLOSED"||E.includes("stream closed before completion")||E.includes("ended without")||E.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:x};if(gE.some((h)=>E.includes(h)))return{retryable:!0,reason:"transport",statusCode:x};if(E.includes("timeout")||E.includes("timed out")||E.includes("temporarily unavailable")||E.includes("upstream_error")||E.includes("overloaded")||E.includes("rate limit")||E.includes("too many requests")||E.includes("service unavailable")||E.includes("server error")||E.includes("internal error")||E.includes("please retry")||E.includes("try your request again"))return{retryable:!0,reason:E.includes("rate")||E.includes("too many")?"rate_limit":E.includes("timeout")||E.includes("timed out")?"timeout":"server_error",statusCode:x};return{retryable:!1,statusCode:x}}function Kf(f,_){if(!f)return;if(f.retryAfterMs!==void 0){let x=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(x))return Math.max(0,x)}if(f.retryAfter===void 0)return;let E=Number.parseFloat(f.retryAfter);if(Number.isFinite(E))return Math.max(0,E*1000);let T=Date.parse(f.retryAfter);return Number.isFinite(T)?Math.max(0,T-_):void 0}function m_(f,_,E={}){let T=E.now??Date.now(),x=E.maxDelayMs??60000,h=Kf(_,T);if(h!==void 0)return Math.min(Math.ceil(h),x);let u=Math.max(0,f-1),S=E.maxExponentialDelayMs??8000,t=Math.min(500*2**u,S),c=Math.max(0,Math.min(1,E.random??Math.random())),M=t*(0.75+c*0.25);return Math.min(Math.round(M),x)}function y_(f,_){let E=f.onPayload;f.onPayload=async(T,x)=>{let h=E?await E(T,x):T;return _(h===void 0?T:h,x)}}function iE(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function Qf(f,_,E){if(!f.enablePromptCaching)return"none";if(E&&_.api==="openai-completions"&&!_.baseUrl.includes("api.openai.com"))return"long";return"short"}function fT(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function _T(f,_,E,T){let x=T?void 0:iE(E);if(!x){if(_.api==="anthropic-messages")f.thinkingEnabled=!1;if(_.api==="google-generative-ai"||_.api==="google-vertex")f.thinking={enabled:!1};return}switch(_.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=x;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:fT(x)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=x;break;default:f.reasoningEffort=x}}function ET(f,_,E){if(!E)return;switch(_){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:E};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:E}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:E};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function TT(f,_,E){let T=E.serviceTier;if(!T)return;if(_.api==="openai-responses"||_.api==="openai-codex-responses"||_.api==="azure-openai-responses"){f.serviceTier=T;return}if(_.api!=="openai-completions"&&!(_.api==="anthropic-messages"&&T==="fast"))return;y_(f,(x)=>{if(!x||typeof x!=="object"||Array.isArray(x))return x;return _.api==="anthropic-messages"?{...x,speed:"fast"}:{...x,service_tier:T}})}function xT(f,_,E){let T=E.responseVerbosity;if(!T)return;if(l_(_,T),_.api==="openai-codex-responses"){f.textVerbosity=T;return}y_(f,(x)=>{if(!x||typeof x!=="object"||Array.isArray(x))return x;if(_.api==="openai-completions")return{...x,verbosity:T};let h="text"in x&&x.text&&typeof x.text==="object"&&!Array.isArray(x.text)?x.text:{};return{...x,text:{...h,verbosity:T}}})}function a_(f,_,E,T,x=!1){let h={apiKey:f.apiKey,headers:f.customHeaders,signal:E,temperature:T?.temperature??f.temperature??0,maxTokens:T?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:Qf(f,_,T?.providerSessionId),sessionId:T?.providerSessionId};if(_T(h,_,f,x),ET(h,_.api,T?.toolChoice?.toolName),TT(h,_,f),xT(h,_,f),_.api==="azure-openai-responses")h.azureBaseUrl=f.baseUrl,h.azureApiVersion=f.apiVersion,h.azureDeploymentName=_.id;return h}function q_(f,_){let E=_.get("x-should-retry");return{statusCode:f,..._.get("retry-after")!==null?{retryAfter:_.get("retry-after")??void 0}:{},..._.get("retry-after-ms")!==null?{retryAfterMs:_.get("retry-after-ms")??void 0}:{},...E==="true"||E==="false"?{shouldRetry:E}:{}}}var hT=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function g_(f,_,E){let T=f.onResponse;if(f.onResponse=async(h,u)=>{let S=new Headers(h.headers);E(q_(h.status,S)),await T?.(h,u)},!hT.has(_.api)||typeof globalThis.fetch!=="function")return;let x=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(h,u)=>{let S=await x(h,u);return E(q_(S.status,S.headers)),S}}function r_(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 Df=300000,tT=30000;class e_ 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 d_ extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function Ff(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function MT(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Df}function RT(f,_){if(_===0)return;let E=_!==void 0&&_>0?_:tT;return Math.max(1,Math.min(E,Math.floor(f/2)))}function AT(f,_,E){if(E?.aborted)return Promise.reject(Ff(E));return new Promise((T,x)=>{let h=!1,u=()=>{clearTimeout(M),E?.removeEventListener("abort",c)},S=(R)=>{if(h)return;h=!0,u(),T(R)},t=(R)=>{if(h)return;h=!0,u(),x(R instanceof Error?R:Error(String(R)))},c=()=>{if(E)t(Ff(E))},M=setTimeout(()=>S({kind:"timer"}),Math.max(0,_));if(E?.addEventListener("abort",c,{once:!0}),E?.aborted){c();return}f.then((R)=>S({kind:"next",result:R}),t)})}async function*ST(f,_,E){let T=MT(_),x=RT(T,_.stallWarningMs);if(_.signal?.aborted)throw Ff(_.signal);let h=Date.now(),u=Promise.resolve().then(()=>f.next()),S;for(;;){let c=await AT(u,(S?T:x??T)-(Date.now()-h),_.signal);if(c.kind==="next"){if(S)yield{...S,phase:"recovered",durationMs:Math.max(S.durationMs,Date.now()-h)};return c.result}if(!S&&x!==void 0){E.stallCount++,S={phase:"detected",stallCount:E.stallCount,durationMs:x,warningAfterMs:x,timeoutMs:T,outputStarted:E.outputStarted},yield S;continue}let M=new e_(T);throw _.abort?.(M),M}}async function*n_(f,_,E,T,x={}){let u=f.stream(_,E,T)[Symbol.asyncIterator](),S=0,t=!1,c={stallCount:0,outputStarted:!1};try{while(!0){let M=ST(u,x,c),R=await M.next();while(!R.done)yield{providerStall:R.value},R=await M.next();let D=R.value;if(D.done)throw new d_;let Y=D.value;switch(Y.type){case"text_delta":c.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":c.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":c.outputStarted=!0,yield{toolCalls:[{index:S++,id:Y.toolCall.id,type:"function",function:{name:Y.toolCall.name,arguments:JSON.stringify(Y.toolCall.arguments)}}]};break;case"done":t=!0,yield{finishReason:Y.reason,usage:r_(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!t)Promise.resolve(u.return?.()).catch(()=>{return})}}var vf=m("Chat"),uT=1;function cT(f,_){let E=_.provider===f.provider,T=E&&_.channel===void 0,x=_.channel;return{...f,provider:_.provider,model:_.model,apiKey:x?.apiKey??(T?f.apiKey:void 0),baseUrl:x?.baseUrl??(T?f.baseUrl:void 0),temperature:x?.temperature??f.temperature,maxOutputTokens:x?.maxOutputTokens??(T?f.maxOutputTokens:void 0),timeout:x?.timeout??f.timeout,streamIdleTimeout:x?.streamIdleTimeout??f.streamIdleTimeout,apiVersion:x?.apiVersion??(T?f.apiVersion:void 0),customHeaders:x?.customHeaders??(T?f.customHeaders:void 0),enablePromptCaching:x?.enablePromptCaching??(T?f.enablePromptCaching:void 0),serviceTier:E?f.serviceTier:void 0,responseVerbosity:E?f.responseVerbosity:void 0,fallbackModels:void 0}}function PT(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((_)=>_.type==="image_url"))}function DT(f){let E=f.findLast((T)=>{let x=T.metadata;return x!==null&&typeof x==="object"&&!Array.isArray(x)&&x.isCompactSummary===!0})?.metadata;return E!==null&&typeof E==="object"&&!Array.isArray(E)&&typeof E.parentId==="string"?E.parentId:""}function HT(f,_){let E=y(f,_);if(!E.retryable||!E.reason)return;let T=E.statusCode;switch(E.reason){case"rate_limit":if(T!==429)return;break;case"server_error":if(T===void 0||T<500||T>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let x=Kf(_,Date.now());return{reason:E.reason,...T!==void 0?{statusCode:T}:{},...x!==void 0?{retryAfterMs:x}:{}}}function of(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class mf{config;models;model;promptCacheBreakMonitor=new Bf;admissionFallbackOwnerId=`pi-service-${process.pid}-${uT++}`;constructor(f){let _=jf(f);this.config={...f,maxContextTokens:_.model.contextWindow,maxOutputTokens:f.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,vf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,_,E,T){let x="",h="",u=[],S,t;for await(let c of this.streamChat(f,_,E,T)){x+=c.content??"",h+=c.reasoningContent??"";for(let M of c.toolCalls??[])if(M.id&&M.type==="function"&&M.function?.name)u.push(M);S=c.usage??S,t=c.finishReason??t}return{content:x,...h?{reasoningContent:h}:{},...u.length>0?{toolCalls:u}:{},usage:S,finishReason:t}}async*streamChat(f,_,E,T){let x=T?.toolChoice?.toolName;if(x&&!_?.some((A)=>A.name===x))throw Error(`Required tool is unavailable: ${x}`);let h=x_(f);if(h.some((A)=>PT(A))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let u=Boolean(x)||h_(h),S=await T_(h,this.model,_,E,x),t=(A,P)=>{let s=T?.providerSessionId;if(!s||!A.usage)return A;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(s),A;let N=Qf(this.config,P,s),U=this.promptCacheBreakMonitor.observe({sessionId:s,modelIdentity:`${P.provider}\x00${P.api}\x00${P.id}`,context:S,retention:N,contextEpoch:DT(h),policy:{baseUrl:P.baseUrl??this.config.baseUrl??"",retention:N,requiredTool:x??"",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:A.usage});if(!U)return A;return vf.warn("[PiAIChatService] Prompt cache break detected",{reason:U.reason,previousCacheReadTokens:U.previousCacheReadTokens,cacheReadTokens:U.cacheReadTokens,tokenDrop:U.tokenDrop,callNumber:U.callNumber}),{...A,usage:{...A.usage,promptCacheBreak:U}}},c=o_({messages:h,context:S,tools:_,requestOptions:T}),M=T?.providerRecovery;if(M&&!fE(M.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let R=M?.mode==="bounded_foreground"&&M.budgetMs>0?{budgetMs:M.budgetMs,startedAt:void 0}:void 0,D=R?"bounded_foreground":"standard",Y=this.config.maxRetries??2,z=this.config.maxRetries??(R?i_:2),k=R!==void 0&&this.config.maxRetries===void 0,L=0,K,Hf=this.config.providerCircuitRegistry??H_(),xf=this.config.providerCircuitBreakerOpenMs??Xf,_E=Math.max(Sf,Math.min(this.config.streamIdleTimeout??Df,If)),EE=this.config.providerRequestAdmissionScheduler??F_(),TE=this.config.providerRequestConcurrency??$f,qf=this.config.providerRequestAdmissionMs??kf,xE=this.config.providerRequestPendingBytes??Lf,Uf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},hE=(A,P)=>Hf.get({provider:A.provider,api:A.api,baseUrl:A.baseUrl??P.baseUrl??"",model:A.id,serviceTier:P.serviceTier,apiVersion:P.apiVersion,apiKey:P.apiKey,customHeaders:P.customHeaders,openDurationMs:xf,probeLeaseMs:_E}),tE=(A,P)=>({provider:A.provider,api:A.api,baseUrl:A.baseUrl??P.baseUrl??"",model:A.id,serviceTier:P.serviceTier,apiVersion:P.apiVersion,apiKey:P.apiKey,customHeaders:P.customHeaders,maxConcurrent:TE,maxPendingBytes:xE}),C=(A=Date.now())=>{if(!R)return;let P=R.startedAt===void 0?0:Math.min(R.budgetMs,Math.max(0,A-R.startedAt));return{recoveryBudgetMs:R.budgetMs,recoveryElapsedMs:P,recoveryRemainingMs:Math.max(0,R.budgetMs-P)}},F=()=>({mode:D,...C()??{}}),lf=()=>{if(R&&R.startedAt===void 0)R.startedAt=Date.now()},v=()=>{let A=C();return new l(R?.budgetMs??0,A?.recoveryElapsedMs??0)},a=()=>!k||L<z+1,Yf=(A,P)=>{let{state:s,...N}=P;return{phase:A,...N,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}},yf=(A)=>({phase:"rejected",requestClass:A.requestClass,resource:A.resource,scope:A.scope,reason:A.reason,queuePosition:0,queueDepth:Math.max(0,A.queued),inFlight:Math.max(0,A.inFlight),limit:Math.max(0,A.limit),waitMs:A.reason==="wait_timeout"?A.maxWaitMs:0,maxWaitMs:A.maxWaitMs,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),ME=async function*(A,P){let s=C()?.recoveryRemainingMs,N=s!==void 0&&R?.startedAt!==void 0?Math.min(qf,s):qf,U;try{U=EE.admit({scope:tE(A,P),sessionId:Uf.sessionId,ownerId:Uf.ownerId,requestClass:Uf.requestClass,maxWaitMs:N,pendingBytes:c,signal:E})}catch(O){if(Tf(O)){if(O.reason==="wait_timeout"&&R?.startedAt!==void 0&&(C()?.recoveryRemainingMs??0)<=0)throw v();yield{providerAdmission:yf(O)}}throw O}let J=U.getSnapshot();if(J.state==="admitted")return await U.ready;yield{providerAdmission:Yf("queued",J)};let Z=U.ready.then((O)=>({kind:"ready",permit:O}),(O)=>({kind:"error",error:O}));while(!0){let O=U.getSnapshot(),b=Math.max(1,Math.min(K_,Math.max(1,N-O.waitMs))),X,j=new Promise((o)=>{X=setTimeout(()=>o({kind:"heartbeat"}),b),X.unref?.()}),W=await Promise.race([Z,j]);if(X)clearTimeout(X);if(W.kind==="heartbeat"){yield{providerAdmission:Yf("queued",U.getSnapshot())};continue}if(W.kind==="error"){if(Tf(W.error)){if(W.error.reason==="wait_timeout"&&R?.startedAt!==void 0&&(C()?.recoveryRemainingMs??0)<=0)throw v();yield{providerAdmission:yf(W.error)}}throw W.error}return yield{providerAdmission:Yf("admitted",U.getSnapshot())},W.permit}},RE=(A,P)=>{if(!a())throw v();if(k)L++;K=void 0;let s=new AbortController,N=E?__(E,s.signal):s.signal,U=typeof P.timeout==="number"&&Number.isFinite(P.timeout)&&P.timeout>0?Math.max(1,Math.floor(P.timeout)):void 0,J;if(R?.startedAt!==void 0){let b=C()?.recoveryRemainingMs??0;if(b<=0)throw v();J={remainingMs:b,error:new l(R.budgetMs,R.budgetMs)}}let Z=a_(P,A,N,T,u);g_(Z,A,(b)=>{K=b});let O=n_(this.models,A,S,Z,{idleTimeoutMs:P.streamIdleTimeout??Df,signal:N,abort:(b)=>s.abort(b)});return async function*(){let b,X;try{if(U!==void 0&&(J===void 0||U<J.remainingMs)){let j=new Gf(U);b=setTimeout(()=>s.abort(j),U),b.unref?.()}if(J){let j=J;X=setTimeout(()=>s.abort(j.error),j.remainingMs),X.unref?.()}yield*O}finally{if(b)clearTimeout(b);if(X)clearTimeout(X)}}()},af=this,p=(A)=>({phase:A.phase,reason:A.reason,...A.statusCode!==void 0?{statusCode:A.statusCode}:{},...A.retryAfterMs!==void 0?{retryAfterMs:A.retryAfterMs}:{},...A.nextProbeAt!==void 0?{nextProbeAt:A.nextProbeAt}:{},openDurationMs:A.openDurationMs,sampleCount:A.sampleCount,failureCount:A.failureCount,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),gf=(A,P)=>({phase:A,reason:P.reason,...P.statusCode!==void 0?{statusCode:P.statusCode}:{},retryAfterMs:P.retryAfterMs,...P.nextProbeAt!==void 0?{nextProbeAt:P.nextProbeAt}:{},openDurationMs:P.openDurationMs,sampleCount:P.sampleCount,failureCount:P.failureCount,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),AE=(A)=>({phase:"probe",reason:A.reason??"server_error",...A.statusCode!==void 0?{statusCode:A.statusCode}:{},openDurationMs:A.openDurationMs??xf,...A.sampleCount!==void 0?{sampleCount:A.sampleCount}:{},...A.failureCount!==void 0?{failureCount:A.failureCount}:{},...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),Nf=(A,P,s)=>({providerRetry:{phase:"exhausted",attempt:A,maxRetries:z,reason:P,...s!==void 0?{statusCode:s}:{},...F(),exhaustedBy:"recovery_budget"}}),rf=async function*(A,P,s,N,U){let J,Z=!1,O,b,X=hE(A,P);for(let j=0;j<=N;j++){if(!a())break;let W,o;while(!W){let H=X.preflight();while(!H.eligible){if(O=H.reason,b=H.statusCode,!R||!U){let G=gf("rejected",H);throw yield{providerCircuit:G},new _f(G)}lf();let V=C()?.recoveryRemainingMs??0;if(V<=0){let G=v();throw yield Nf(k?Math.max(0,L-1):j,H.reason,H.statusCode),G}yield{providerCircuit:gf("waiting",H)};let w=Math.min(Math.max(1,H.retryAfterMs),wf,V);if(await d(w,E,{throwOnAbort:!0}),(C()?.recoveryRemainingMs??0)<=0){let G=v();throw yield Nf(k?Math.max(0,L-1):j,H.reason,H.statusCode),G}H=X.preflight()}try{o=yield*ME(A,P)}catch($){if($ instanceof l)yield Nf(k?Math.max(0,L-1):j,O??"timeout",b);throw $}let I=X.check();if(I.allowed)W=I;else o.release(),o=void 0}let g=W.token;if(W.probe)yield{providerCircuit:AE(W)};try{let H=!1,I=!1;for await(let $ of RE(A,P)){if($.providerStall){yield $;continue}let V=k?L-1:j;if(V>0&&O&&!H)H=!0,yield{providerRetry:{phase:"recovered",attempt:V,maxRetries:z,reason:O,...b!==void 0?{statusCode:b}:{},...F()}};if(!I){I=!0;let w=X.recordSuccess(g);if(w)yield{providerCircuit:p(w)}}Z=!0,s(),yield t($,A)}if(!I){let $=X.recordSuccess(g);if($)yield{providerCircuit:p($)}}return}catch(H){if(o?.release(),J=H,af.logIdleTimeout(H,Z,A),await af.handleAbort(E),H instanceof l){if(Z)throw Zf(H),H;throw yield{providerRetry:{phase:"exhausted",attempt:k?Math.max(0,L-1):j,maxRetries:z,reason:O??"timeout",...b!==void 0?{statusCode:b}:{},...F(),exhaustedBy:"recovery_budget"}},H}let I=y(H,K);if(Z)throw Zf(H),H;let $=HT(H,K),V=$?X.recordFailure(g,$):K&&!of(H)?X.recordNeutral(g):void 0;if(V)yield{providerCircuit:p(V)};if(!I.retryable||!I.reason){if(j>0&&O)yield{providerRetry:{phase:"exhausted",attempt:k?Math.max(0,L-1):j,maxRetries:z,reason:O,...b!==void 0?{statusCode:b}:{},...F()}};throw H}O=I.reason,b=I.statusCode;let w=j<N&&a();if(V&&V.phase!=="closed"&&w&&(!R||!U)){let G={...p(V),phase:"rejected"};throw yield{providerCircuit:G},new _f(G)}if(w){lf();let G=k?L:j+1,uE=m_(G,K,R?{maxDelayMs:pf,maxExponentialDelayMs:pf}:void 0),df=V&&V.phase!=="closed"?V.retryAfterMs??0:0;if(R&&df>0&&V)yield{providerCircuit:{...p(V),phase:"waiting"}};let cE=C(),bf=Math.max(uE,df),r=R?Math.min(bf,cE?.recoveryRemainingMs??bf):bf,tf={attempt:G,maxRetries:z,reason:I.reason,...I.statusCode!==void 0?{statusCode:I.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...tf,delayMs:r,nextRetryAt:Date.now()+r,...F()}},R){let e=r;while(e>0){let nf=Math.min(e,wf);if(await d(nf,E,{throwOnAbort:!0}),e-=nf,(C()?.recoveryRemainingMs??0)<=0){let Mf=v();throw yield{providerRetry:{phase:"exhausted",...tf,...F(),exhaustedBy:"recovery_budget"}},Mf}if(e>0){if(V&&V.phase!=="closed"&&V.nextProbeAt!==void 0){let Mf=Math.max(0,V.nextProbeAt-Date.now());if(Mf>0)yield{providerCircuit:{...p(V),phase:"waiting",retryAfterMs:Mf}}}yield{providerRetry:{phase:"waiting",...tf,delayMs:r,nextRetryAt:Date.now()+e,...F()}}}}}else await d(r,E,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...tf,...F()}}}else yield{providerRetry:{phase:"exhausted",attempt:k?Math.max(0,L-1):j,maxRetries:z,reason:I.reason,...I.statusCode!==void 0?{statusCode:I.statusCode}:{},...F(),...R&&(U||!a())?{exhaustedBy:"attempt_limit"}:{}}}}finally{X.abandon(g),o?.release()}}throw J},Of,ef=!1,hf=this.config.fallbackModels??[],SE=R&&hf.length>0?Math.min(Y,z):z;try{for await(let A of rf(this.model,this.config,()=>{ef=!0},SE,hf.length===0))yield A;return}catch(A){if(Of=A,ef||!Tf(A)&&!Jf(A)&&!of(A)&&!y(A,K).retryable)throw A}for(let[A,P]of hf.entries()){if(!a())break;yield{modelFallback:!0};let s=!1;try{let N=cT(this.config,P),U=R_(N,P),J=A===hf.length-1,Z=R&&!J?Math.min(Y,z):z;for await(let O of rf(U,N,()=>{s=!0},Z,J))yield O;return}catch(N){if(Of=N,s||!Tf(N)&&!Jf(N)&&!of(N)&&!y(N,K).retryable)throw N}}throw Of}async handleAbort(f){if(f?.aborted)await d(0,f,{throwOnAbort:!0})}logIdleTimeout(f,_,E){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;vf.warn("[PiAIChatService] Provider stream idle timeout",{provider:E.provider,model:E.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:_})}getConfig(){return{...this.config}}updateConfig(f){let _={...this.config,...f},E=jf(_);this.config={..._,maxContextTokens:E.model.contextWindow,maxOutputTokens:_.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model}}var UT=m("Service");async function zx(f){let _=f;if(_.provider){let E=f_(_.provider);if(Object.keys(E).length>0)_={..._,customHeaders:{...E,..._.customHeaders}},UT.debug(`Injected ${_.provider} specific headers:`,Object.keys(E))}return YT(_)}function YT(f){return new mf(f)}
|
|
5
|
-
export{bT as Yd,CT as Zd,__ as _d,Tf as $d,v_ as ae,rE as be,Tx as ce,mf as de,zx as ee};
|
package/dist/chunk-8gzm51m8.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ee as a}from"./chunk-0f8nn2h1.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{a as createChatServiceAsync};
|