blade-code 0.10.67 → 0.10.68
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/chunk-0f8nn2h1.js +5 -0
- package/dist/{chunk-8t2xknh6.js → chunk-1r3zgzsk.js} +1 -1
- package/dist/{chunk-amaxww4b.js → chunk-1rg4p2v1.js} +1 -1
- package/dist/{chunk-8mr5vydg.js → chunk-2xz8kw3r.js} +1 -1
- package/dist/{chunk-wr60s2qh.js → chunk-3b0z45ej.js} +1 -1
- package/dist/{chunk-6am7zz57.js → chunk-3hmvp733.js} +1 -1
- package/dist/{chunk-gayy8vky.js → chunk-3mm2n48d.js} +3 -3
- package/dist/{chunk-7agkmjm7.js → chunk-4khwmc1s.js} +1 -1
- package/dist/{chunk-eq99gcj8.js → chunk-8gzm51m8.js} +1 -1
- package/dist/{chunk-gak96awp.js → chunk-8y7wvqx4.js} +1 -1
- package/dist/{chunk-gvxpdb2v.js → chunk-9jpksycv.js} +1 -1
- package/dist/{chunk-nacssmem.js → chunk-a6bg3tyj.js} +1 -1
- package/dist/{chunk-pv576mrv.js → chunk-ab7awwm7.js} +1 -1
- package/dist/{chunk-nrh7qjat.js → chunk-b760m6w5.js} +1 -1
- package/dist/{chunk-7pxpwkeg.js → chunk-c8nx34eq.js} +1 -1
- package/dist/{chunk-k5a3n7q5.js → chunk-cw72ydsc.js} +1 -1
- package/dist/{chunk-5kz804w9.js → chunk-e1dqxg53.js} +1 -1
- package/dist/{chunk-vavy5dw8.js → chunk-e5a9jxnw.js} +1 -1
- package/dist/chunk-edgd965j.js +1 -0
- package/dist/chunk-efemjy9y.js +2 -0
- package/dist/{chunk-p0gyfy9p.js → chunk-ektjpv2v.js} +1 -1
- package/dist/{chunk-w5jdnsyz.js → chunk-f1qvcn1z.js} +1 -1
- package/dist/{chunk-2wz3mf50.js → chunk-f2xng5g1.js} +1 -1
- package/dist/{chunk-eqqxr26g.js → chunk-fknvpxg5.js} +1 -1
- package/dist/{chunk-0aja46wq.js → chunk-gkf4j7hd.js} +1 -1
- package/dist/{chunk-fs6ashcf.js → chunk-j7tweh9y.js} +1 -1
- package/dist/{chunk-37g8mh93.js → chunk-kg9kvbg4.js} +1 -1
- package/dist/{chunk-696t7mzc.js → chunk-kwykw1mk.js} +1 -1
- package/dist/{chunk-3j8q6yrf.js → chunk-mmfrypfb.js} +1 -1
- package/dist/{chunk-pf6ftbra.js → chunk-msh36mac.js} +2 -2
- package/dist/{chunk-zd05g5qs.js → chunk-n728g0r7.js} +1 -1
- package/dist/{chunk-te88v4a8.js → chunk-q48ksbhx.js} +1 -1
- package/dist/{chunk-yq2891kc.js → chunk-q4adr6y2.js} +1 -1
- package/dist/{chunk-kccs7c9r.js → chunk-shhnxq90.js} +1 -1
- package/dist/{chunk-tb363yj8.js → chunk-tqfp6grc.js} +1 -1
- package/dist/{chunk-2a9rndk2.js → chunk-tqr5w9br.js} +1 -1
- package/dist/chunk-tqvxyrab.js +6 -0
- package/dist/{chunk-38x7njj5.js → chunk-vmd7skd7.js} +1 -1
- package/dist/{chunk-yy6h97k0.js → chunk-w67k19a1.js} +1 -1
- package/dist/{chunk-rbdd49vr.js → chunk-y1cv193c.js} +1 -1
- package/dist/chunk-z1784103.js +1 -0
- package/package.json +1 -1
- package/dist/chunk-2kkpn41a.js +0 -5
- package/dist/chunk-53xbkvk1.js +0 -6
- package/dist/chunk-cn9jekw9.js +0 -1
- package/dist/chunk-f99n8812.js +0 -2
- package/dist/chunk-gn3fxtkj.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{rd as W}from"./chunk-
|
|
2
|
+
import{rd as W}from"./chunk-q48ksbhx.js";import{ud as F,vd as M}from"./chunk-bjqjdw34.js";import"./chunk-e1dqxg53.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-ektjpv2v.js";import"./chunk-m57w4p91.js";import"./chunk-a6bg3tyj.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{vg as N,wg as B}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Wg as T}from"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-1rg4p2v1.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import{Bh as J}from"./chunk-hcv17986.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function c(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function m(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function t(){if(c(E)){let{getVersion:K}=await import("./chunk-n728g0r7.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-kg9kvbg4.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-e7pssnr9.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-gkf4j7hd.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-2xz8kw3r.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-8y7wvqx4.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-edgd965j.js"),import("./chunk-3b0z45ej.js"),import("./chunk-msh36mac.js"),import("./chunk-bbcb9jzb.js"),import("./chunk-e5a9jxnw.js"),import("./chunk-50jthhfq.js"),import("./chunk-1z9wct9w.js"),import("./chunk-mmfrypfb.js"),import("./chunk-fknvpxg5.js"),import("./chunk-shhnxq90.js")]),A=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),p&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-z1784103.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-ab7awwm7.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
|
|
@@ -0,0 +1,5 @@
|
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ke as a,le as b,me as c}from"./chunk-
|
|
1
|
+
import{ke as a,le as b,me as c}from"./chunk-tqfp6grc.js";import"./chunk-a6bg3tyj.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-1rg4p2v1.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -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.68",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,4 +1,4 @@
|
|
|
1
|
-
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-
|
|
1
|
+
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-c8nx34eq.js";import{N as M,V as y}from"./chunk-3mm2n48d.js";import"./chunk-3hmvp733.js";import"./chunk-5147jh26.js";import{pb as h,yb as A}from"./chunk-q4adr6y2.js";import"./chunk-th4jjfgm.js";import{Nc as U,zc as w}from"./chunk-f1qvcn1z.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{jd as C}from"./chunk-vmd7skd7.js";import{ld as I,md as S,nd as v}from"./chunk-tqvxyrab.js";import{od as O}from"./chunk-s7jsadnc.js";import"./chunk-bjqjdw34.js";import{Ld as P}from"./chunk-e1dqxg53.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-0f8nn2h1.js";import"./chunk-efemjy9y.js";import"./chunk-yn51162x.js";import"./chunk-tqfp6grc.js";import"./chunk-cw72ydsc.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-ektjpv2v.js";import"./chunk-m57w4p91.js";import"./chunk-a6bg3tyj.js";import{ig as F}from"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as z}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-1rg4p2v1.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
2
|
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
3
|
`);else j.io.stdout.write(`${j.response}
|
|
4
4
|
`)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ld as a,md as b,nd as c}from"./chunk-
|
|
1
|
+
import{ld as a,md as b,nd as c}from"./chunk-tqvxyrab.js";import"./chunk-s7jsadnc.js";import"./chunk-e1dqxg53.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zvz2cnt4.js";import"./chunk-a6bg3tyj.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-1rg4p2v1.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Hb as Xt,Ib as bn,Jb as Tn,Kb as fn}from"./chunk-th4jjfgm.js";import{Rc as jt}from"./chunk-0wxkymqv.js";import{$e as Bt}from"./chunk-
|
|
1
|
+
import{Hb as Xt,Ib as bn,Jb as Tn,Kb as fn}from"./chunk-th4jjfgm.js";import{Rc as jt}from"./chunk-0wxkymqv.js";import{$e as Bt}from"./chunk-ektjpv2v.js";import{Bf as yn,Cf as Ht,Df as Ut,Ef as h,Ff as qt,ef as xt,ff as tn,gf as en,hf as zt,if as U,jf as rn,kf as gt,lf as mt,nf as dn,of as En,pf as B,qf as on,rf as pn,sf as cn,tf as lt,uf as un,vf as Mn,wf as wn,yf as S}from"./chunk-a6bg3tyj.js";import{kg as X,mg as x}from"./chunk-v0rsz1rt.js";import{wg as vt}from"./chunk-k0pa8874.js";import{jh as nn,kh as sn}from"./chunk-1rg4p2v1.js";import{Bh as ss}from"./chunk-hcv17986.js";import{EventEmitter as hs}from"events";import Bn from"node:path";function An(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 _n(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||`验证失败:${An(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:_n(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;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}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 Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!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{oa as R,pa as g0,ua as g3,va as w9,wa as h0}from"./chunk-
|
|
1
|
+
import{oa as R,pa as g0,ua as g3,va as w9,wa as h0}from"./chunk-3hmvp733.js";import{Aa as l4,Ra as jJ,xa as bJ,za as AJ}from"./chunk-5147jh26.js";import{$a as $7,Db as g9,Gb as u9,Sa as L$,Ta as V1,Ua as X9,Va as l$,Wa as n8,Xa as Q9,Ya as s8,Za as V9,_a as z9,db as Q0,fb as u2,ib as s2,kb as l6,lb as e2,mb as $5,pb as Y$,vb as B5,wb as C3,xb as o7}from"./chunk-q4adr6y2.js";import{Bc as v3,Fc as h9,Kc as H3,Lc as O3,Mb as H0,Nb as N1,Nc as r,Ob as y$,Pb as V2,Qb as s4,Rb as o2,Sb as t2,jc as G5,kc as D0,lc as t0,uc as e4,vc as m0,wc as z1,xc as G3,yc as K3}from"./chunk-f1qvcn1z.js";import{Oc as g,Pc as W7,Qc as X7,Rc as y2}from"./chunk-0wxkymqv.js";import{Sc as TJ,Vc as CJ,cd as RJ,id as PJ}from"./chunk-zdxxqchm.js";import{td as pZ,ud as mZ}from"./chunk-bjqjdw34.js";import{Gd as Z5,Hd as _0,Id as f,Ld as F0,Md as m2,Nd as G1,Od as T$,Pd as X4,Qd as m$,Rd as y9,Wd as U1}from"./chunk-e1dqxg53.js";import{Xd as O$}from"./chunk-0j22w4wh.js";import{$d as x9,ae as k9,de as L3,ee as d2}from"./chunk-0f8nn2h1.js";import{ge as R0,he as v$}from"./chunk-efemjy9y.js";import{ie as P3}from"./chunk-yn51162x.js";import{ke as X3,le as U3,me as Q3}from"./chunk-tqfp6grc.js";import{Ae as O5,Be as s$,Ce as e$,De as z3,He as A4,Je as P0,Ke as X$,Me as p2,Ne as _3,ne as i2,oe as r2,qe as n2,re as a2,se as H1,te as G7,ve as z$,we as s0,xe as i0,ye as y5,ze as W1}from"./chunk-cw72ydsc.js";import{Pe as K1,Re as J$,Se as R2}from"./chunk-hat9v5c5.js";import{Te as a3,Ve as V3,We as z5,Xe as cZ}from"./chunk-cdy9efgm.js";import{$e as A0,Ze as g4}from"./chunk-ektjpv2v.js";import{af as $2,bf as t4,cf as Z2,df as $1}from"./chunk-m57w4p91.js";import{$f as R9,Af as W9,Gf as r$,Jf as t8,Tf as b9,Uf as A9,Vf as j9,Wf as M9,Xf as Y4,Yf as T9,Zf as M$,_f as C9,ag as P9,cg as qZ,eg as B3,ff as CZ,fg as W3,gg as X0,kf as RZ,mf as v4,rf as h3,vf as PZ,xf as Z3,zf as Y9}from"./chunk-a6bg3tyj.js";import{jg as Y1}from"./chunk-h0ft81a3.js";import{kg as K2,lg as f5,mg as _,ng as B7,og as S,pg as l}from"./chunk-v0rsz1rt.js";import{rg as n7,sg as a7}from"./chunk-xz6y0w4n.js";import{ug as q2,wg as C}from"./chunk-k0pa8874.js";import{Xg as i}from"./chunk-98n2rxmq.js";import{ah as J3,bh as Y3}from"./chunk-ypqp368c.js";import{ch as t3,fh as r3}from"./chunk-t8xmh4w2.js";import{jh as ZJ}from"./chunk-1rg4p2v1.js";import{ph as k0}from"./chunk-t2gq918a.js";import{sh as Q2,uh as A$,wh as $3,xh as KZ,zh as Z0}from"./chunk-ppsvzgs5.js";import{Bh as n0}from"./chunk-hcv17986.js";import{randomUUID as P5}from"crypto";import{randomUUID as iJ}from"node:crypto";var mJ=String.raw`
|
|
2
2
|
const { spawn } = require('node:child_process');
|
|
3
3
|
const [ownerPidValue, command, ...args] = process.argv.slice(1);
|
|
4
4
|
const ownerPid = Number(ownerPidValue);
|
|
@@ -782,7 +782,7 @@ ${V0}
|
|
|
782
782
|
</approved-plan>
|
|
783
783
|
|
|
784
784
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof H==="string")Y0=H+k;else Y0=[...H,{type:"text",text:k}]}P=yield*this.runLoop(Y0,O,{...A,inputMessageId:void 0})}if(!this.sessionRuntime||!b)return P;let v=await this.sessionRuntime.recordGoalProgress({tokens:P.metadata?.tokensUsed??0,elapsedMs:P.metadata?.duration??0});if(v)yield{kind:"goal_updated",goal:v};if(!P.success||O.signal?.aborted){if(v=await this.sessionRuntime.pauseActiveGoal(O.signal?.aborted?"goal paused after user cancellation":P.error?.message??"goal paused after turn failure"),v)yield{kind:"goal_updated",goal:v}}if(P.success&&!O.signal?.aborted&&L<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(b,O.signal);let $0=P.success&&!O.signal?.aborted&&L<20,I=OU(P);if(N=await this.sessionRuntime.finishTurn(b,{continuePending:$0,...I?{acknowledgeInput:!0}:{},outcome:P.success&&!O.signal?.aborted?{status:"completed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}:{status:"aborted",cause:O.signal?.aborted?"cancelled":"failed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}}),N){L++,F=!0,B=!1,E=null,H="",D=void 0,q=T(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:j()};continue}if(!P.success||O.signal?.aborted)return P;if(v=await this.sessionRuntime.getGoal(),!v||v.status!=="active"&&v.status!=="verifying")return P;if(E=await this.sessionRuntime.beginGoalContinuation(),!E)return P;N=await this.sessionRuntime.beginTurn("goal"),F=!1,B=!0,H=Q6(E),D=void 0,q=void 0,yield{kind:"goal_continuation_started",goal:E,continuation:E.continuationCount},yield{kind:"goal_updated",goal:E}}}finally{if(this.sessionRuntime&&N)await this.sessionRuntime.finishTurn(N)}}let z=typeof Q==="string"?Q:Q.filter((H)=>H.type==="text").map((H)=>H.text).join(`
|
|
785
|
-
`),G={id:this.generateTaskId(),type:"simple",prompt:z};return{success:!0,finalMessage:(await this.executeTask(G)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-
|
|
785
|
+
`),G={id:this.generateTaskId(),type:"simple",prompt:z};return{success:!0,finalMessage:(await this.executeTask(G)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-4khwmc1s.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await d$({projectPath:Z.workspaceRoot||C(),mode:"plan",includeEnvironment:!0,environmentOptions:I9,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=S1($);else{let X=$.filter((U)=>U.type==="text");if(X.length>0){let U=X[0];W=$.map((Q)=>Q===U?{type:"text",text:S1(U.text)}:Q)}else W=[{type:"text",text:S1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||C());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await d$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:I9,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return u9(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,U=J.output,Q={success:X,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],z=g9(Y,Q);if(z)V.push(z);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await d$({projectPath:this.sessionRuntime?.workspaceRoot??C(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await c2({sessionId:"default",configDir:Z0(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await D2({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=h0.createIsolated({artifactWriter:new P1(`legacy-${HU()}`)});this.legacyMcpRegistry=Z;for(let[X,U]of Object.entries($))try{p.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,U),p.debug(`MCP server "${X}" connected`)}catch(Q){p.warn(`Warning: MCP server "${X}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(y1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await P0(C());if(this.agentResources=p2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
786
786
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;p.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let W=this.buildAttachmentText(Y);if(!W)return $;return[...$,{type:"text",text:W}]}catch(Y){return p.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let W of $)if(W.type==="file"){let X=W.metadata?.lineRange?` (lines ${W.metadata.lineRange.start}${W.metadata.lineRange.end?`-${W.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${W.path}"${X?` range="${X}"`:""}>`,W.content,"</file>")}else if(W.type==="directory")Z.push(`<directory path="${W.path}">`,W.content,"</directory>");else if(W.type==="error")J.push(`- @${W.path}: ${W.error}`);let Y="";if(Z.length>0)Y+=`
|
|
787
787
|
|
|
788
788
|
<system-reminder>
|
|
@@ -1583,7 +1583,7 @@ ${J}
|
|
|
1583
1583
|
`)),{success:!0,message:"Schedules listed",content:V.join(`
|
|
1584
1584
|
`)}}case"create":{let Q=yG(X);if("error"in Q)return Y.sendMessage(`创建失败:${Q.error}`),{success:!1,error:Q.error};let V={prompt:Q.prompt,projectPath:U,trigger:Q.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let z=await $.create(V),G=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${z.id}\`
|
|
1585
1585
|
${l4(z.trigger)} · 下次运行: ${G}`),{success:!0,message:`Schedule ${z.id} created`}}catch(z){let G=z instanceof Error?z.message:String(z);return Y.sendMessage(`创建失败:${G}`),{success:!1,error:G}}}case"remove":case"rm":{let Q=X[0];if(!Q)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(Q);return Y.sendMessage(V?`[OK] 已删除 \`${Q}\``:`未找到 \`${Q}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let Q=X[0];if(!Q)return Y.sendMessage(`用法:/schedule ${W} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(Q,W==="enable");return Y.sendMessage(V?`[OK] 已${W==="enable"?"启用":"停用"} \`${Q}\``:`未找到 \`${Q}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let Q=X[0];if(!Q)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await xG(Q),Y.sendMessage(`[OK] 已触发 \`${Q}\``),{success:!0,message:"Schedule triggered"}}catch(V){let z=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${z}`),{success:!1,error:z}}}default:return Y.sendMessage(`未知子命令: ${W}
|
|
1586
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var MJ=hG();import*as w1 from"node:fs/promises";import*as L1 from"node:path";async function SJ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,U=X??Q2(W??C());if(!X){let H=await gG($,W??C(),J,Y);if(H)return H}let Q;try{Q=(await w1.readdir(U)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>L1.join(U,O))}catch{return[]}let z=(await Promise.all(Q.map(async(H)=>{try{let O=await w1.stat(H);return{path:H,mtime:O.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,O)=>O.mtime-H.mtime).map((H)=>H.path),G=[],K=Y?$:$.toLowerCase();for(let H of z){if(G.length>=J)break;let O=L1.basename(H,".jsonl"),F=await uG(H,K,Y,O);if(G.push(...F),G.length>=J){G.length=J;break}}return G}async function gG($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-kmarzy98.js"),X=await RJ();if(!X)return null;let{SessionService:U}=await import("./chunk-
|
|
1586
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var MJ=hG();import*as w1 from"node:fs/promises";import*as L1 from"node:path";async function SJ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,U=X??Q2(W??C());if(!X){let H=await gG($,W??C(),J,Y);if(H)return H}let Q;try{Q=(await w1.readdir(U)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>L1.join(U,O))}catch{return[]}let z=(await Promise.all(Q.map(async(H)=>{try{let O=await w1.stat(H);return{path:H,mtime:O.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,O)=>O.mtime-H.mtime).map((H)=>H.path),G=[],K=Y?$:$.toLowerCase();for(let H of z){if(G.length>=J)break;let O=L1.basename(H,".jsonl"),F=await uG(H,K,Y,O);if(G.push(...F),G.length>=J){G.length=J;break}}return G}async function gG($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-kmarzy98.js"),X=await RJ();if(!X)return null;let{SessionService:U}=await import("./chunk-9jpksycv.js");await W(X,U.projectionDeriverForSearch());let Q=L1.resolve(Z),V=PJ(X,$,Q,J*4),z=Y?$:$.toLowerCase(),G=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let H=i4(K.text,z,Y,K.session_id,K.role,K.timestamp??void 0,0);if(H)G.push(H);if(G.length>=J)break}return G}catch{return null}}async function uG($,Z,J,Y){try{let W=await w1.readFile($,"utf8"),U=W.split(`
|
|
1587
1587
|
`).flatMap((K,H)=>{if(!K.trim())return[];try{return[{event:JSON.parse(K),index:H}]}catch{return[]}});if(!U.some(({event:K})=>K.type==="session_created"))return mG(U,Z,J,Y);let V=new Map(U.flatMap(({event:K,index:H})=>typeof K.id==="string"?[[K.id,H+1]]:[])),z=TJ(CJ(W,$)),G=new Map;for(let K of z){if(K.type==="message_created"&&(K.data.role==="user"||K.data.role==="assistant"))G.set(K.data.messageId,{role:K.data.role,content:[],timestamp:K.timestamp,lineNumber:V.get(K.id)??0});if(K.type==="part_created"&&K.data.partType==="text"){let H=G.get(K.data.messageId),O=K.data.payload.text;if(H&&typeof O==="string")H.content.push(O)}}return[...G.values()].flatMap((K)=>{let H=i4(K.content.join(" "),Z,J,Y,K.role,K.timestamp,K.lineNumber);return H?[H]:[]})}catch{return[]}}function mG($,Z,J,Y){return $.flatMap(({event:W,index:X})=>{if(W.type!=="message")return[];let U=W.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let Q=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((z)=>typeof z==="object"&&z!==null&&z.type==="text"&&typeof z.text==="string").map((z)=>z.text).join(" "):"",V=i4(Q,Z,J,Y,U.role,typeof W.timestamp==="string"?W.timestamp:void 0,X+1);return V?[V]:[]})}function i4($,Z,J,Y,W,X,U){if(!$)return;let Q=J?$:$.toLowerCase();if(!Q.includes(Z))return;let V=Q.indexOf(Z),z=Math.max(0,V-80),G=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:W,content:(z>0?"...":"")+$.slice(z,G).replace(/\n/g," ")+(G<$.length?"...":""),timestamp:X,lineNumber:U}}function fJ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1588
1588
|
`];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",W=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${W} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1589
1589
|
`)}var dG={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=h(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let W=await SJ(Y,{maxResults:15,projectPath:Z.cwd}),X=fJ(W);return J.sendMessage(X),{success:!0,message:`found ${W.length} results`,data:{matches:W.length}}}catch(W){let X=W instanceof Error?W.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},kJ=dG;var pG={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await X$(J,async(Y)=>{await Y.skills.refresh(),e$(J),await s$(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return f().addAssistantMessage(Y),{success:!1,error:Y}}}},vJ=pG;import cG from"node:path";function b5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function IJ($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function yJ($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function lG($,Z){let J=h(Z),Y=$[0],W=a.getInstance(),X=e.getInstance(),U=Z.sessionId??"",Q=Z.sessionId?{sessionId:Z.sessionId,projectPath:cG.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let O=$[1],F=$.slice(2).join(" ").trim();if(!O||!F)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let B=await Z.subagents.resume(O,F),q=`Resumed \`${O}\` as \`${B.session.id}\` (depth ${B.session.resumeDepth}).`;return J.sendMessage(q),{success:!0,message:q,data:{action:"subagent_resumed",sourceAgentId:O,subagent:B.session}}}if(Y==="clean"){let O=X.cleanupExpiredSessionsForParent(Q??U,0);return J.sendMessage(`已清理 ${O} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${O} agent sessions`}}let V=[`**后台任务列表**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ab as m,Bb as n,Cb as o,Eb as p,Fb as q,Gb as r,gb as a,hb as b,jb as c,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,zb as l}from"./chunk-
|
|
1
|
+
import{Ab as m,Bb as n,Cb as o,Eb as p,Fb as q,Gb as r,gb as a,hb as b,jb as c,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,zb as l}from"./chunk-q4adr6y2.js";import"./chunk-th4jjfgm.js";import"./chunk-f1qvcn1z.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import"./chunk-0j22w4wh.js";import"./chunk-0f8nn2h1.js";import"./chunk-yn51162x.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-ektjpv2v.js";import"./chunk-m57w4p91.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-1rg4p2v1.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ee as a}from"./chunk-
|
|
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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{s as Pz,t as xz}from"./chunk-
|
|
1
|
+
import{s as Pz,t as xz}from"./chunk-tqr5w9br.js";import{u as E}from"./chunk-kwykw1mk.js";import{A as Hz,v as Nz,w as $z,x as Qz,y as Wz,z as Yz}from"./chunk-b760m6w5.js";import{E as N,N as e,Q as zz,R as Jz,V as Zz,ja as jz,ka as Xz,la as Dz,ma as Lz}from"./chunk-3mm2n48d.js";import{wa as qz}from"./chunk-3hmvp733.js";import"./chunk-5147jh26.js";import{db as n,pb as t,yb as s}from"./chunk-q4adr6y2.js";import{Hb as M}from"./chunk-th4jjfgm.js";import{Ac as a,Cc as x,Fc as o,Kc as R,Nc as F,_b as m,ic as d,jc as v,oc as l,rc as i,tc as r,zc as k}from"./chunk-f1qvcn1z.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as Ez}from"./chunk-q48ksbhx.js";import"./chunk-bjqjdw34.js";import{Ld as _z,Md as Oz}from"./chunk-e1dqxg53.js";import"./chunk-v508x7cg.js";import{Xd as I}from"./chunk-0j22w4wh.js";import{$d as p}from"./chunk-0f8nn2h1.js";import"./chunk-efemjy9y.js";import{ie as Az}from"./chunk-yn51162x.js";import"./chunk-tqfp6grc.js";import"./chunk-cw72ydsc.js";import"./chunk-hat9v5c5.js";import{Te as Rz}from"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-ektjpv2v.js";import"./chunk-m57w4p91.js";import{Lf as wz,Of as Kz}from"./chunk-a6bg3tyj.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as h,rg as c,sg as S}from"./chunk-xz6y0w4n.js";import{wg as Fz}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Xg as T}from"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import{ch as Uz,fh as Vz}from"./chunk-t8xmh4w2.js";import"./chunk-1rg4p2v1.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import{Readable as uz,Writable as gz}from"node:stream";import*as b from"@agentclientprotocol/sdk";import Gz from"node:path";import{PROTOCOL_VERSION as Cz,RequestError as fz}from"@agentclientprotocol/sdk";import{RequestError as yz}from"@agentclientprotocol/sdk";import{nanoid as y}from"nanoid";var B=T("Agent");function g(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function hz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:g(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:g("headers"in z?z.headers:void 0)};return null}function Sz(z){let Z={};for(let J of z){let Y=hz(J);if(Y)Z[J.name]=Y}return Z}function Bz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function Mz(z){let Z=a(z.metadata);return Z?[{type:"text",text:k(Z)}]:Bz(z.content)}function kz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function Iz(z){if(!p(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...d("capacity"),resource:z.resource}}class P{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Hz({maxPendingItems:$z,maxPendingBytes:Qz,writeTimeoutMs:Wz,signal:J.signal,sizeOf:(W)=>Buffer.byteLength(JSON.stringify(W)),write:async(W)=>{await J.sessionUpdate(W)},onFailure:(W)=>this.handleUpdateEgressFailure(W)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([F.loadSession(this.id,this.cwd),F.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await F.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Zz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(B.debug(`[AcpSession ${this.id}] Initializing...`),await F.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),B.debug(`[AcpSession ${this.id}] ACP service context initialized`),await s.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?Sz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await e.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,Q)=>{let j=await J.execute(W,{cwd:Q.cwd,env:Q.env,timeout:Q.timeoutMs,signal:Q.signal,allowLocalFallback:!1,onOutput:(X)=>Q.onOutput?.("stdout",X)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Xz(this.cwd),B.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=n.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.schedulePendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!r(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of Mz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);B.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{B.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await this.runtime.rewindSession(Q);return this.messages=[...j.messages],this.contextMessages=await this.loadModelContextOr(j.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),j}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=!1,D,G=(U)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:U.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:U.result?.message||U.result?.error||`Subagent ${U.status}`}}]})},L=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(U)=>{if(X)G(U);else D=U}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.session.id,status:"in_progress",title:`Resuming ${L.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${L.source.id} at depth ${L.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),X=!0,D)G(D);return L}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,X)},complete:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,X)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,j)},getLogs:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,j)},setLoggingLevel:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,j)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(L)=>{if(L.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.toolCall.id,status:"in_progress",title:`Review: ${L.toolCall.function.name}`,content:[],kind:this.mapToolKind(L.toolKind)});else if(L.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.toolCall.id,status:L.result.success?"completed":"failed",content:[]})}}),D=await X.completion,G=(await E.list(this.cwd,this.id)).find((L)=>L.start.reviewId===X.reviewId);if(!G)throw Error(`Review not found: ${X.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:X.reviewId,status:D.status,findings:D.findings.length,content:m(G.start,D)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,X)=>{let D=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,G=this.mapToolKind(X);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:G})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Dz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await F.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let W=Y.content||Y.message;if(W)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){return B.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=Lz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)).map((H)=>{let W;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)W=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;W=W?`${W} | ${Q}`:Q}return{name:H.name,description:H.description,input:W?{hint:W}:void 0}});B.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),B.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){B.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,W=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((L)=>L.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=o(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let L=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!L.accepted)throw Error(L.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(B.debug(`[AcpSession ${this.id}] Queued steering for active turn (${L.queued})`),L.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let j=new AbortController,X=!1,D,G=new Promise((L)=>{D=L});this.pendingPrompt=j,this.pendingPromptCompletion=G;try{if(B.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),jz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,j.signal)}let L={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:j.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},U=await t(this.agent.chatStream(Y,L,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let V=$.toolCall,O=V.function.name;if(O===x)break;let A=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let q=JSON.parse(V.function.arguments),K=q.resume_from??q.resume;if(typeof K==="string")w=`Resuming ${String(q.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:A});break}case"tool_progress":{let V=$.toolCall;if(V.function.name===x)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let V=$.toolCall;if(V.function.name===x)break;let O=$.result,A=[],w=O.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let K of w.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;A.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))A.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,Tz=Jz(i(zz(K,O),l));A.push({type:"content",content:{type:"text",text:Tz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))A.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let q=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:q,content:A});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Hc as a,Ic as b,Jc as c,Kc as d,Lc as e,Mc as f,Nc as g}from"./chunk-
|
|
1
|
+
import{Hc as a,Ic as b,Jc as c,Kc as d,Lc as e,Mc as f,Nc as g}from"./chunk-f1qvcn1z.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import"./chunk-yn51162x.js";import"./chunk-cdy9efgm.js";import"./chunk-m57w4p91.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-98n2rxmq.js";import"./chunk-t8xmh4w2.js";import"./chunk-1rg4p2v1.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.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,4 +1,4 @@
|
|
|
1
|
-
import{jg as Y}from"./chunk-h0ft81a3.js";import{kg as Tn,lg as F,mg as o}from"./chunk-v0rsz1rt.js";import{qg as ct,rg as bt}from"./chunk-xz6y0w4n.js";import{wg as a}from"./chunk-k0pa8874.js";import{Dg as gt,Eg as Jn,Fg as it,Gg as Ct,Hg as Rt,Ig as On,Jg as zt,Kg as Bt,Lg as kn,Mg as Ut,Ng as Kt,Og as yn,Pg as Ht,Qg as Yt,Rg as qt,Sg as Vt,Tg as Gt,xg as Zn,yg as Xt,zg as pt}from"./chunk-6pyktfa4.js";import{Xg as dn}from"./chunk-98n2rxmq.js";import{_g as $t,bh as J}from"./chunk-ypqp368c.js";import{jh as an,kh as xn}from"./chunk-
|
|
1
|
+
import{jg as Y}from"./chunk-h0ft81a3.js";import{kg as Tn,lg as F,mg as o}from"./chunk-v0rsz1rt.js";import{qg as ct,rg as bt}from"./chunk-xz6y0w4n.js";import{wg as a}from"./chunk-k0pa8874.js";import{Dg as gt,Eg as Jn,Fg as it,Gg as Ct,Hg as Rt,Ig as On,Jg as zt,Kg as Bt,Lg as kn,Mg as Ut,Ng as Kt,Og as yn,Pg as Ht,Qg as Yt,Rg as qt,Sg as Vt,Tg as Gt,xg as Zn,yg as Xt,zg as pt}from"./chunk-6pyktfa4.js";import{Xg as dn}from"./chunk-98n2rxmq.js";import{_g as $t,bh as J}from"./chunk-ypqp368c.js";import{jh as an,kh as xn}from"./chunk-1rg4p2v1.js";import{ph as h}from"./chunk-t2gq918a.js";import{zh as mn}from"./chunk-ppsvzgs5.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function C(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var K=async(n,t)=>{C(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(C(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as v}from"node:crypto";import tM from"node:http";import{auth as An}from"@modelcontextprotocol/sdk/client/auth.js";import MM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as k,promises as P}from"node:fs";import y from"node:path";import Jt from"write-file-atomic";var on=1,Ot=1048576,kt=5000,yt=50,jt=/^[a-f0-9]{64}$/,Ft=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),lt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),vt=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(Ft),tokens:o.Optional(lt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(vt),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),un=o.Object({version:o.Literal(on),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function nM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function j(n){return structuredClone(n)}function En(n){if(Object.keys(n.credentials).some((t)=>!jt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=mn()){this.stateRoot=y.join(n,"mcp"),this.tokenFilePath=y.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?j(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?j(e):null);if(r)M.credentials[n]=F(sn,r);else delete M.credentials[n];return r?j(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=Tn(un,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return En(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:on,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(un,n);En(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=y.join(this.stateRoot,".oauth-credentials.lock"),t=Zt(),M=Date.now()+kt;while(Date.now()<M)try{let e=await P.open(n,k.O_CREAT|k.O_EXCL|k.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((r)=>setTimeout(r,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await P.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!nM(M.pid))await P.unlink(n)}}var cn="127.0.0.1",bn=7777,wn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Pn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|