blade-code 0.10.42 → 0.10.43
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-dx7xefys.js → chunk-0qsssahq.js} +1 -1
- package/dist/{chunk-ecw74d2s.js → chunk-26wse17p.js} +2 -2
- package/dist/{chunk-3xx2ebr7.js → chunk-2eddqgnh.js} +1 -1
- package/dist/{chunk-hypq4t4z.js → chunk-2yvte5a7.js} +1 -1
- package/dist/chunk-32g59k4p.js +8 -0
- package/dist/{chunk-1whfdz08.js → chunk-372mmzj3.js} +1 -1
- package/dist/{chunk-fye8eghq.js → chunk-3bpxvanm.js} +2 -2
- package/dist/chunk-3y784b9c.js +1 -0
- package/dist/{chunk-1yjzj2d0.js → chunk-56qew7w0.js} +2 -2
- package/dist/chunk-5wzjdfde.js +1 -0
- package/dist/chunk-6ch7a6xf.js +44 -0
- package/dist/chunk-6cx4t8r6.js +1 -0
- package/dist/chunk-6skymhz5.js +1 -0
- package/dist/{chunk-kfv4mdcm.js → chunk-7fqsgdee.js} +2 -2
- package/dist/{chunk-jz2gkqdt.js → chunk-7s5hw0gr.js} +7 -7
- package/dist/{chunk-5zr3w30g.js → chunk-7sna3js9.js} +1 -1
- package/dist/chunk-8vsx6m43.js +10 -0
- package/dist/{chunk-020hgyg7.js → chunk-8vtyatd6.js} +1 -1
- package/dist/{chunk-f90ybvrs.js → chunk-9rrced3b.js} +1 -1
- package/dist/{chunk-wm944thh.js → chunk-ag5ea7ce.js} +22 -22
- package/dist/{chunk-qb49rm5q.js → chunk-bct3s5vs.js} +1 -1
- package/dist/{chunk-0qf7h4n2.js → chunk-bvf9syb2.js} +2 -2
- package/dist/chunk-c3020yav.js +22 -0
- package/dist/{chunk-sw3p1ygn.js → chunk-c8ddch38.js} +68 -68
- package/dist/{chunk-dr4et3gj.js → chunk-c9s4n31b.js} +1 -1
- package/dist/{chunk-f542fh7g.js → chunk-cxzx7j0p.js} +1 -1
- package/dist/{chunk-z60w7p8a.js → chunk-d5x5wknc.js} +1 -1
- package/dist/{chunk-8b2bpfnt.js → chunk-dcp5gg6q.js} +3 -3
- package/dist/{chunk-mt7fn8cv.js → chunk-e1vyznkn.js} +3 -3
- package/dist/{chunk-1e9866ye.js → chunk-egczvfsv.js} +2 -2
- package/dist/{chunk-anwm8rp3.js → chunk-f4sp074f.js} +1 -1
- package/dist/chunk-fer18bbe.js +1 -0
- package/dist/{chunk-t2mc97k7.js → chunk-fhnkyqfb.js} +2 -2
- package/dist/{chunk-3v2sgvzt.js → chunk-fk4wbmv6.js} +2 -2
- package/dist/chunk-fzqsea19.js +1 -0
- package/dist/{chunk-pm9kt54d.js → chunk-hcm55r3d.js} +1 -1
- package/dist/{chunk-m8s208g3.js → chunk-hfrcwkc8.js} +1 -1
- package/dist/chunk-j7edwwg1.js +2 -0
- package/dist/{chunk-d2fce0vk.js → chunk-jpz805fs.js} +2 -2
- package/dist/chunk-k87p7x1e.js +1 -0
- package/dist/{chunk-jv9zg1fw.js → chunk-kfpzrmq7.js} +1 -1
- package/dist/chunk-m8a2qj5c.js +1 -0
- package/dist/{chunk-18wnstzp.js → chunk-m8ss9rmx.js} +1 -1
- package/dist/{chunk-te95z52n.js → chunk-mrsc4a55.js} +1 -1
- package/dist/{chunk-4rmdfme3.js → chunk-n7dvqbrc.js} +1 -1
- package/dist/{chunk-ex21hxqf.js → chunk-nsrghqdx.js} +1 -1
- package/dist/chunk-nwzjmcxq.js +1 -0
- package/dist/chunk-nynfqgsj.js +6 -0
- package/dist/chunk-pyk2ey7y.js +1 -0
- package/dist/{chunk-mpymjr7j.js → chunk-q78s028m.js} +1 -1
- package/dist/{chunk-m3dvta6k.js → chunk-qb0sqh29.js} +2 -2
- package/dist/chunk-qmcj20g2.js +1 -0
- package/dist/chunk-qnxgzyyx.js +2 -0
- package/dist/{chunk-0jsy9eav.js → chunk-qp2z1r7y.js} +1 -1
- package/dist/{chunk-7gjb405q.js → chunk-rwjm6p0f.js} +1 -1
- package/dist/chunk-s9s9daak.js +1 -0
- package/dist/{chunk-jf6mkx0j.js → chunk-skb4h36j.js} +1 -1
- package/dist/{chunk-6d0hphtd.js → chunk-sqd5ge5s.js} +1 -1
- package/dist/{chunk-xkg84094.js → chunk-t2r7tqn0.js} +2 -2
- package/dist/{chunk-vc32qrmq.js → chunk-tpa75y39.js} +1 -1
- package/dist/chunk-txkrtgcd.js +2 -0
- package/dist/{chunk-y75y911b.js → chunk-v9tzhe90.js} +2 -2
- package/dist/{chunk-yqxyy3w2.js → chunk-vbpykrxd.js} +2 -2
- package/dist/{chunk-mp637mb6.js → chunk-w5ayh9b8.js} +2 -2
- package/dist/{chunk-7pmpm5yq.js → chunk-wwvb6znp.js} +1 -1
- package/dist/{chunk-brwdd5kp.js → chunk-x2vqgssm.js} +2 -2
- package/dist/chunk-y6tkxqjx.js +2 -0
- package/dist/{chunk-4k37vmxh.js → chunk-yk9pxkc1.js} +1 -1
- package/dist/{chunk-q6n6rqzs.js → chunk-yqy000kg.js} +2 -2
- package/dist/chunk-yt9qer14.js +1 -0
- package/dist/{chunk-8csfb83y.js → chunk-yypnfmed.js} +2 -2
- package/dist/chunk-z1aqe7ms.js +1 -0
- package/dist/web/assets/{ChatView-DBgMoUrW.js → ChatView-CyxiCTbL.js} +3 -3
- package/dist/web/assets/{CodeBlockHighlighter-DLFQUVD6.js → CodeBlockHighlighter-Bb3gIeQv.js} +1 -1
- package/dist/web/assets/{FilePreview--1qHdJP_.js → FilePreview-BXg9VaTv.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DcVHyjtl.js → MarkdownRenderer-vxpqGt4L.js} +3 -3
- package/dist/web/assets/{SettingsModal-BM6SPUXW.js → SettingsModal-4L1nPkh0.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-B5VYY_QG.js → TaskSwitcher-DKSqTLK1.js} +1 -1
- package/dist/web/assets/{TerminalPanel-XWA1jGs8.js → TerminalPanel-Bv9PDclr.js} +1 -1
- package/dist/web/assets/{index-B8y5_J0i.js → index-Bz4W1-8a.js} +3 -3
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-5hbm5e24.js +0 -44
- package/dist/chunk-74sxsd1h.js +0 -1
- package/dist/chunk-78jy2kby.js +0 -1
- package/dist/chunk-7qd6xqjs.js +0 -1
- package/dist/chunk-8wg7g98v.js +0 -10
- package/dist/chunk-c53hc8ze.js +0 -1
- package/dist/chunk-dgs04r04.js +0 -2
- package/dist/chunk-h9fkttf1.js +0 -2
- package/dist/chunk-hkmgrdxc.js +0 -1
- package/dist/chunk-katrmbxc.js +0 -1
- package/dist/chunk-m4ya7qqd.js +0 -1
- package/dist/chunk-n6c6k87j.js +0 -1
- package/dist/chunk-ppxn94za.js +0 -1
- package/dist/chunk-rf7hdke7.js +0 -1
- package/dist/chunk-rjjjgcw4.js +0 -1
- package/dist/chunk-vsaqjbm2.js +0 -6
- package/dist/chunk-wcxsm922.js +0 -2
- package/dist/chunk-wn23bvs0.js +0 -1
- package/dist/chunk-wtczk025.js +0 -22
- package/dist/chunk-yatvtpft.js +0 -1
- package/dist/chunk-za6zyd82.js +0 -8
- package/dist/chunk-zhrc510s.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-hfrcwkc8.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
|
|
2
|
-
export{G as
|
|
2
|
+
export{G as Ke,F as Le,R as Me,v as Ne};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Sg as S}from"./chunk-vbpykrxd.js";import{hh as f}from"./chunk-hfrcwkc8.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
|
|
2
2
|
export{_ as a,u as b,g as c,C as d,V as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Fb as HJ}from"./chunk-te95z52n.js";import{Gb as l0,Nb as O6,Ob as U6,Pb as $2,Qb as J2,Xb as H6,dc as C$,nc as y0,pc as G2,qc as X1,rc as O2,yc as f$}from"./chunk-wm944thh.js";import{Dc as t,Gc as D6,Hc as O0}from"./chunk-1yjzj2d0.js";import{Hd as T6}from"./chunk-7pmpm5yq.js";import{Id as ZJ,Jd as C0,Kd as a6,Nd as WJ,Od as q2,Qd as Y6}from"./chunk-1e9866ye.js";import{ue as v0,ve as A0,ye as YJ}from"./chunk-vc32qrmq.js";import{He as Z$}from"./chunk-mt7fn8cv.js";import{Uf as a}from"./chunk-jv9zg1fw.js";import{tg as G0}from"./chunk-t2mc97k7.js";import{Hg as G6}from"./chunk-yqxyy3w2.js";import{Pg as H$,Rg as a2,Sg as z0,Tg as K1,Vg as L6,Xg as q6}from"./chunk-m3dvta6k.js";import{Yg as _8}from"./chunk-m8s208g3.js";function $$($){return $.role==="system"&&Array.isArray($.content)}function e0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class a${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find($$);if(this._contextualSystemMessages=$.messages.filter(e0),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!$$(W)&&!e0(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!e0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter($$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!$$(J)&&!e0(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(e0),this._history=$.filter((J)=>!$$(J)&&!e0(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function x2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function h2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import i0 from"node:path";var wJ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),LJ=/^(LD_.+|DYLD_.+|PATH)$/,R2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function S$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(!wJ.has(K))break;J=Y}return J}function m4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(LJ.test(K))break;J=Y}return J}var qJ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function I1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of qJ){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function s$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){Z+=X,H=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function C2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let H=$[Y];if(W){W=!1;continue}if(H==="\\"&&!J){W=!0;continue}if(H==="'"&&!Z){J=!J;continue}if(H==='"'&&!J){Z=!Z;continue}if(J)continue;if(H==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(H==="`")return!0;if(Z)continue;if(H==="|")return!0;if(H===">"||H==="<")return!0;if(H==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function A$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){if(H=!0,Y){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,H=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var GJ=new Set(["npm","pnpm","yarn","bun"]),I2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),OJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function UJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function yJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function FJ($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=A$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let H=Y[1];if(!H||H==="-")return;let K=i0.isAbsolute(H)?i0.resolve(H):i0.resolve(Z,H);if(!l0.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function J$($,J){let Z=S$(yJ($)),W=s$(Z);if(!W||C2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:FJ(Z,W,J);if(!Y)return!1;let H=A$(Y);if(H.length===0||H.some((z)=>[...OJ].some((j)=>z===j||z.startsWith(`${j}=`))))return!1;let[K,X,Q]=H;if(GJ.has(K??""))return UJ(X==="run"?Q:X)||X==="--test";if((K==="npx"||K==="bunx")&&I2.has(X??""))return!0;if(I2.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function l4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!i0.isAbsolute($);let Z=i0.isAbsolute($)?i0.resolve($):i0.resolve(J,$);return l0.isWithinWorkspace(Z,J)}var v1=G0("Agent"),_J=3;function p1($,J,Z){if($!=="length")return{action:"none"};if(J>=_J)return{action:"truncated"};if(x2(Z)==="stop")return v1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var bJ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],NJ=/```[\s\S]{50,}```/,v2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",PJ=2;function g1($,J,Z=!0){if(!$||J>=PJ)return{action:"none"};if(!Z&&NJ.test($))return{action:"retry",prompt:v2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(bJ.some((K)=>K.test(W)))return{action:"retry",prompt:v2};return{action:"none"}}var SJ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],p2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},AJ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},EJ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",fJ="Required verification did not run successfully before the retry limit.",TJ=3;function m2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&J$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let H of Y)if(typeof H==="string"&&J$(H,W))$.add(H)}function m1($,J,Z){if(!$||!SJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(p2).filter((Q)=>p2[Q].test($)),Y=[...J],H=W.filter((Q)=>!Y.some((z)=>AJ[Q].test(z)));if(W.length>0?H.length===0:Y.some((Q)=>J$(Q)))return{action:"none"};if(Z>=TJ)return{action:"fail",message:fJ};let X=W.length>1&&H.length>0?` Missing successful verification categories: ${H.join(", ")}.`:"";return{action:"retry",prompt:`${EJ}${X}`}}var kJ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],u2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function d2($){return typeof $==="string"&&u2.some((J)=>J.test($))}var xJ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],MJ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function hJ($){if(typeof $!=="string")return;if(MJ.some((J)=>J.test($)))return"multiple-allowed";return xJ.some((J)=>J.test($))?"required":void 0}function e$($){for(let J of $){let Z=hJ(J);if(Z!==void 0)return Z==="required"}return!1}var RJ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",CJ="Required delegation did not complete before the retry limit.",IJ=3;function c2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=e$(W),H=!1;if(!Y)for(let K of W){if(u2.some((X)=>X.test(K)))break;if(kJ.some((X)=>X.test(K))){H=!0;break}}if(W.length===0||!Y&&!H||J.has("Task"))return{action:"none"};if(Z>=IJ)return{action:"fail",message:CJ};return{action:"retry",prompt:RJ}}var vJ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],pJ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],gJ=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function i2($){return gJ.reduce((J,Z)=>J.replace(Z," "),$)}function $1($){if(typeof $!=="string")return!1;let J=i2($);return vJ.some((Z)=>Z.test(J))}var mJ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",uJ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",dJ="Required worktree lifecycle did not complete before the retry limit.",cJ=3;function l2($,J,Z){if(!$)return{action:"none"};let W=i2($);if(!$1(W))return{action:"none"};let Y=pJ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let H=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!H)return{action:"none"};if(Z>=cJ)return{action:"fail",message:dJ};return{action:"retry",tool:H,prompt:H==="EnterWorktree"?mJ:uJ}}var g2=30000;async function u1($){try{let Z=Z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??a(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((H)=>{W=setTimeout(()=>H("timeout"),g2)});try{let H=await Promise.race([Z,Y]);if(H==="timeout")return v1.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=H;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return v1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function iJ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var lJ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function rJ($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function nJ($){let J=$;for(let Q of lJ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let H=Y.slice(0,60),K=H.lastIndexOf(" ");return`${(K>36?H.slice(0,K):H).trimEnd()}…`}function r2($){return nJ(rJ($))}import{EventEmitter as oJ}from"events";import n2 from"node:path";function d1($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=d1($);return JSON.stringify([J.projectPath,J.sessionId])}function Y5($,J){return o2($)===o2(J)}class W$ extends oJ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!W$.instance)W$.instance=new W$;return W$.instance}publish($,J,Z,W){let Y=d1($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var E$=W$.getInstance();var M0=G0("Agent"),J1=new Set;async function aJ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(J1.has(Z))return;if(J1.size>=5000)J1.clear();J1.add(Z);try{let W=$.workspaceRoot,Y=await f$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let H=r2(J);if(!H)return;await f$.updateSessionMetadata(Z,Y.projectPath,{title:H}),E$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:H})}catch(W){M0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var c1=`<turn_aborted>
|
|
1
|
+
import{Hb as HJ}from"./chunk-mrsc4a55.js";import{Ac as f$,Ib as l0,Pb as O6,Qb as U6,Rb as $2,Sb as J2,Zb as H6,fc as C$,pc as y0,rc as G2,sc as X1,tc as O2}from"./chunk-ag5ea7ce.js";import{Fc as t,Ic as D6,Jc as O0}from"./chunk-56qew7w0.js";import{Jd as T6}from"./chunk-wwvb6znp.js";import{Kd as ZJ,Ld as C0,Md as a6,Pd as WJ,Qd as q2,Sd as Y6}from"./chunk-egczvfsv.js";import{Ae as YJ,we as v0,xe as A0}from"./chunk-tpa75y39.js";import{Je as Z$}from"./chunk-e1vyznkn.js";import{dg as a}from"./chunk-kfpzrmq7.js";import{Eg as G0}from"./chunk-fhnkyqfb.js";import{Sg as G6}from"./chunk-vbpykrxd.js";import{_g as H$,ah as a2,bh as z0,ch as K1,eh as L6,gh as q6}from"./chunk-qb0sqh29.js";import{hh as _8}from"./chunk-hfrcwkc8.js";function $$($){return $.role==="system"&&Array.isArray($.content)}function e0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class a${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find($$);if(this._contextualSystemMessages=$.messages.filter(e0),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!$$(W)&&!e0(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!e0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter($$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!$$(J)&&!e0(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(e0),this._history=$.filter((J)=>!$$(J)&&!e0(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function x2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function h2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import i0 from"node:path";var wJ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),LJ=/^(LD_.+|DYLD_.+|PATH)$/,R2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function S$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(!wJ.has(K))break;J=Y}return J}function m4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(LJ.test(K))break;J=Y}return J}var qJ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function I1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of qJ){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function s$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){Z+=X,H=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function C2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let H=$[Y];if(W){W=!1;continue}if(H==="\\"&&!J){W=!0;continue}if(H==="'"&&!Z){J=!J;continue}if(H==='"'&&!J){Z=!Z;continue}if(J)continue;if(H==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(H==="`")return!0;if(Z)continue;if(H==="|")return!0;if(H===">"||H==="<")return!0;if(H==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function A$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){if(H=!0,Y){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,H=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var GJ=new Set(["npm","pnpm","yarn","bun"]),I2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),OJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function UJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function yJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function FJ($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=A$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let H=Y[1];if(!H||H==="-")return;let K=i0.isAbsolute(H)?i0.resolve(H):i0.resolve(Z,H);if(!l0.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function J$($,J){let Z=S$(yJ($)),W=s$(Z);if(!W||C2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:FJ(Z,W,J);if(!Y)return!1;let H=A$(Y);if(H.length===0||H.some((z)=>[...OJ].some((j)=>z===j||z.startsWith(`${j}=`))))return!1;let[K,X,Q]=H;if(GJ.has(K??""))return UJ(X==="run"?Q:X)||X==="--test";if((K==="npx"||K==="bunx")&&I2.has(X??""))return!0;if(I2.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function l4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!i0.isAbsolute($);let Z=i0.isAbsolute($)?i0.resolve($):i0.resolve(J,$);return l0.isWithinWorkspace(Z,J)}var v1=G0("Agent"),_J=3;function p1($,J,Z){if($!=="length")return{action:"none"};if(J>=_J)return{action:"truncated"};if(x2(Z)==="stop")return v1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var bJ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],NJ=/```[\s\S]{50,}```/,v2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",PJ=2;function g1($,J,Z=!0){if(!$||J>=PJ)return{action:"none"};if(!Z&&NJ.test($))return{action:"retry",prompt:v2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(bJ.some((K)=>K.test(W)))return{action:"retry",prompt:v2};return{action:"none"}}var SJ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],p2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},AJ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},EJ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",fJ="Required verification did not run successfully before the retry limit.",TJ=3;function m2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&J$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let H of Y)if(typeof H==="string"&&J$(H,W))$.add(H)}function m1($,J,Z){if(!$||!SJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(p2).filter((Q)=>p2[Q].test($)),Y=[...J],H=W.filter((Q)=>!Y.some((z)=>AJ[Q].test(z)));if(W.length>0?H.length===0:Y.some((Q)=>J$(Q)))return{action:"none"};if(Z>=TJ)return{action:"fail",message:fJ};let X=W.length>1&&H.length>0?` Missing successful verification categories: ${H.join(", ")}.`:"";return{action:"retry",prompt:`${EJ}${X}`}}var kJ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],u2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function d2($){return typeof $==="string"&&u2.some((J)=>J.test($))}var xJ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],MJ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function hJ($){if(typeof $!=="string")return;if(MJ.some((J)=>J.test($)))return"multiple-allowed";return xJ.some((J)=>J.test($))?"required":void 0}function e$($){for(let J of $){let Z=hJ(J);if(Z!==void 0)return Z==="required"}return!1}var RJ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",CJ="Required delegation did not complete before the retry limit.",IJ=3;function c2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=e$(W),H=!1;if(!Y)for(let K of W){if(u2.some((X)=>X.test(K)))break;if(kJ.some((X)=>X.test(K))){H=!0;break}}if(W.length===0||!Y&&!H||J.has("Task"))return{action:"none"};if(Z>=IJ)return{action:"fail",message:CJ};return{action:"retry",prompt:RJ}}var vJ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],pJ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],gJ=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function i2($){return gJ.reduce((J,Z)=>J.replace(Z," "),$)}function $1($){if(typeof $!=="string")return!1;let J=i2($);return vJ.some((Z)=>Z.test(J))}var mJ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",uJ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",dJ="Required worktree lifecycle did not complete before the retry limit.",cJ=3;function l2($,J,Z){if(!$)return{action:"none"};let W=i2($);if(!$1(W))return{action:"none"};let Y=pJ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let H=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!H)return{action:"none"};if(Z>=cJ)return{action:"fail",message:dJ};return{action:"retry",tool:H,prompt:H==="EnterWorktree"?mJ:uJ}}var g2=30000;async function u1($){try{let Z=Z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??a(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((H)=>{W=setTimeout(()=>H("timeout"),g2)});try{let H=await Promise.race([Z,Y]);if(H==="timeout")return v1.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=H;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return v1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function iJ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var lJ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function rJ($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function nJ($){let J=$;for(let Q of lJ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let H=Y.slice(0,60),K=H.lastIndexOf(" ");return`${(K>36?H.slice(0,K):H).trimEnd()}…`}function r2($){return nJ(rJ($))}import{EventEmitter as oJ}from"events";import n2 from"node:path";function d1($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=d1($);return JSON.stringify([J.projectPath,J.sessionId])}function Y5($,J){return o2($)===o2(J)}class W$ extends oJ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!W$.instance)W$.instance=new W$;return W$.instance}publish($,J,Z,W){let Y=d1($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var E$=W$.getInstance();var M0=G0("Agent"),J1=new Set;async function aJ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(J1.has(Z))return;if(J1.size>=5000)J1.clear();J1.add(Z);try{let W=$.workspaceRoot,Y=await f$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let H=r2(J);if(!H)return;await f$.updateSessionMetadata(Z,Y.projectPath,{title:H}),E$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:H})}catch(W){M0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var c1=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,r0="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",s2="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class Y$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function n0($){return $.executionEngine?.getContextManager()}async function K0($,J,Z,W=null,Y,H={}){let K=H.required??$.executionEngine!==void 0;try{let X=n0($),Q=typeof Z==="string"?Z.trim()!=="":Z.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(X&&J.sessionId&&Q){let z=await X.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!z)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)aJ(J,Z);return z}if(K&&J.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(X){if(M0.warn("[Loop] 保存用户消息失败:",X),K)throw new Y$("user_message",{cause:X})}return null}async function g($,J,Z,W,Y,H,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=n0($),z=Boolean(Z.trim()||Y?.trim());if(Q&&J.sessionId&&z){let j=await Q.saveMessage(J.sessionId,"assistant",Z,W,H,J.subagentInfo,Y);if(X&&!j)throw Error("Durable assistant-message commit returned no identity");return j}if(X&&J.sessionId&&z)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(M0.warn("[Loop] 保存助手消息失败:",Q),X)throw new Y$("assistant_message",{cause:Q})}return null}async function t2($,J,Z){try{let W=n0($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",c1,Z,void 0,J.subagentInfo)}catch(W){M0.warn("[Loop] 保存中断边界失败:",W)}return null}async function e2($,J,Z,W,Y){try{let H=n0($);if(!H||!J.sessionId||Z.length===0)return null;return await H.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(H){M0.warn("[Loop] 保存 contextual project rules provenance 失败:",H)}return null}async function i1($,J,Z,W,Y,H={}){try{let K=n0($);if(K&&J.sessionId){let X=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo);if(H.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(H.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(M0.warn("[Loop] 保存工具调用失败:",K),H.required)throw K}return null}async function Z1($,J,Z,W,Y,H,K,X,Q,z={}){try{let j=n0($);if(j&&J.sessionId){let q=await j.saveToolResult(J.sessionId,Z,W,Y,H,K,J.subagentInfo,X,Q);if(z.required&&!q)throw Error("Durable tool-result commit returned no identity");return q}if(z.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(j){if(M0.warn("[Loop] 保存工具结果失败:",j),z.required)throw j}return null}async function T$($,J,Z,W,Y={}){try{let H=n0($);if(H&&J.sessionId){let K=await H.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(H){if(M0.warn("[Loop] 保存压缩数据失败:",H),Y.required)throw H}return null}import{createHash as y4}from"node:crypto";import{promises as K8}from"node:fs";import X8 from"node:path";import{nanoid as R0}from"nanoid";import*as i from"node:fs/promises";import*as o0 from"node:path";var $6={enabled:!0,maxIndexLines:200};var sJ="memory",J6="MEMORY.md";class l1{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=H$($);this.memoryDir=o0.join(W,sJ)}this.config={...$6,...J}}async initialize(){if(this.initialized)return;await i.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=o0.join(this.memoryDir,J6);try{let J=await i.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -118,7 +118,7 @@ Full output saved to: ${X}`}catch{return`${J}
|
|
|
118
118
|
|
|
119
119
|
${Y}`}}import{Mutex as M8}from"async-mutex";import{nanoid as h8}from"nanoid";import*as w0 from"node:fs/promises";import*as j6 from"node:path";import{Mutex as G8}from"async-mutex";import O8 from"write-file-atomic";var H1=1,M$=8388608;function V6($,J){let Z={version:H1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
|
|
120
120
|
`}function s1($,J){return $ instanceof Error&&"code"in $&&$.code===J}function U8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function y8($,J,Z){let W;try{W=JSON.parse($)}catch(H){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:H})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==H1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((H)=>{if(!H||typeof H!=="object"||!("id"in H)||typeof H.id!=="string"||!("content"in H)||!U8(H.content)||!("queuedAt"in H)||typeof H.queuedAt!=="number"||"persisted"in H&&typeof H.persisted!=="boolean"||"origin"in H&&H.origin!=="user"&&H.origin!=="background_subagent"||"metadata"in H&&(H.metadata===null||typeof H.metadata!=="object"||Array.isArray(H.metadata))||"outputSchema"in H&&H.outputSchema!==void 0&&(!H.outputSchema||typeof H.outputSchema!=="object"||Array.isArray(H.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let K="outputSchema"in H&&H.outputSchema!==void 0?X1(H.outputSchema).schema:void 0;return{id:H.id,content:H.content,queuedAt:H.queuedAt,..."persisted"in H&&H.persisted===!0?{persisted:!0}:{},..."origin"in H&&H.origin?{origin:H.origin}:{},..."metadata"in H&&H.metadata?{metadata:JSON.parse(JSON.stringify(H.metadata))}:{},...K?{outputSchema:K}:{}}});return{version:H1,sessionId:Z,messages:Y}}function F8($){return new Set($.flatMap((J)=>J.type==="inbox_acknowledged"?J.data.messageIds:[]))}class Q1{workspaceRoot;sessionId;filePath;mutex=new G8;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new Q1($,J,K1($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=V6(this.sessionId,Z);if(Buffer.byteLength(W)>M$)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:H1,sessionId:this.sessionId,messages:[]};try{if((await w0.stat(this.filePath)).size>M$)throw Error(`Steering inbox exceeds ${M$} bytes: ${this.filePath}`);await w0.chmod(this.filePath,384),$=y8(await w0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!s1(Y,"ENOENT"))throw Y}let J=z0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=F8(D6(await w0.readFile(J,"utf8"),J))}catch(Y){if(!s1(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($,J){if(await w0.mkdir(j6.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await w0.unlink(this.filePath).catch((W)=>{if(!s1(W,"ENOENT"))throw W});return}let Z=J??V6(this.sessionId,$);if(Buffer.byteLength(Z)>M$)throw Error(`Steering inbox exceeds ${M$} bytes: ${this.filePath}`);await O8(this.filePath,Z,{encoding:"utf8",mode:384,fsync:!0})}}import*as U0 from"node:fs/promises";import*as y6 from"node:path";import{nanoid as s}from"nanoid";class a0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new O0(z0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=a0.instances.get(Z);if(!W)W=new a0($,J),a0.instances.set(Z,W);return W}static release($,J){a0.instances.delete(`${J}\x00${$}`)}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);E$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($)}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z)await $.onCommitted(W)}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}E$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function Q$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class S0 extends Error{}var b8="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.",N8=20,P8=1e4,S8=1e5,A8=2592000000,w6=128,E8=1e6;function f8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>w6||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>E8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>w6||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function F6($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,H=Y.turnId,K=Y.inputMessageIds,X=Y.turnsCount,Q=Y.toolCallsCount,z=Y.durationMs,j=Array.isArray(K)?K.filter((V)=>typeof V==="string"&&V.length>0&&V.length<=128):[];if(typeof H!=="string"||H.length===0||H.length>128||J!==void 0&&H!==J||!Array.isArray(K)||K.length>N8||j.length!==K.length||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>P8||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>S8||typeof z!=="number"||!Number.isSafeInteger(z)||z<0||z>A8)return;let q;if("goalFinalization"in Y){if(q=f8(Y.goalFinalization),!q)return}return{turnId:H,inputMessageIds:[...new Set(j)],turnsCount:X,toolCallsCount:Q,durationMs:z,...q?{goalFinalization:q}:{}}}function T8($,J){let Z=t($),W=Z.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(W<0)return;for(let Y=Z.length-1;Y>W;Y--){let H=Z[Y];if(H?.type!=="message_created")continue;let K=F6(H,J);if(K)return K}return}function k8($){let J=t($);for(let Z=J.length-1;Z>=0;Z--){let W=J[Z];if(W?.type!=="message_created")continue;let Y=F6(W);if(!Y?.goalFinalization)continue;if(!J.slice(0,Z).some((K)=>K.type==="turn_started"&&K.data.turnId===Y.turnId))continue;return{turnId:Y.turnId,finalization:Y}}return}function t1($,J){let Z=t($),W=J?Z.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===J):-1;if(J&&W<0)return{all:[],orphaned:[]};let Y=new Map,H=new Set,K=new Set;for(let Q of Z.slice(W+1)){if(Q.type==="interaction_requested"){K.add(Q.data.toolCallId);continue}if(Q.type!=="part_created")continue;let z=Q.data.payload&&typeof Q.data.payload==="object"&&!Array.isArray(Q.data.payload)?Q.data.payload:{},j=typeof z.toolCallId==="string"?z.toolCallId:Q.data.partId;if(Q.data.partType==="tool_call")Y.set(j,{toolCallId:j,messageId:Q.data.messageId,toolName:typeof z.toolName==="string"?z.toolName:"unknown",input:z.input??null});else if(Q.data.partType==="tool_result")H.add(j),H.add(Q.data.partId),H.add(Q.data.messageId)}let X=[...Y.values()];return{all:X,orphaned:X.filter((Q)=>!H.has(Q.toolCallId)&&!K.has(Q.toolCallId))}}class I0{projectPath;maxSessions;version;constructor($=a(),J=100,Z=G6()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:s(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:L6(this.projectPath),version:this.version,data:Z}}log($){return a0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=z0(this.projectPath,$);if((await new O0(Z).readAll()).length>0)return;let H=new Date().toISOString(),K={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:H,updatedAt:H},X=this.createEvent("session_created",$,K);await this.log($).commit(X)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=O6;return J}async initialize(){try{let $=H$(this.projectPath);await U0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,H,K){try{await this.ensureSessionCreated($,H);let X=new Date().toISOString(),Q=s(),z={messageId:Q,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:X,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},j=this.createEvent("message_created",$,z),q=J==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:"reasoning",payload:{text:K},createdAt:X})]:[],V=typeof Z==="string"?[this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:"text",payload:{text:Z},createdAt:X})]:Z.map((D)=>this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:D.type==="text"?"text":"image",payload:D.type==="text"?{text:D.text}:{mimeType:x8(D.image_url.url)??"image/png",dataUrl:D.image_url.url},createdAt:X}));return await this.log($).commitBatch([j,...q,...V]),Q}catch(X){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,X),X}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=t(W),H=Y.some((V)=>V.type==="inbox_acknowledged"&&V.data.messageIds.includes(J.inboxMessageId)),K=Y.find((V)=>V.type==="message_created"&&V.data.inboxMessageId===J.inboxMessageId),X=Y.findLast((V)=>{if(V.type!=="part_created"||V.data.partType!=="tool_call"||!V.data.payload||typeof V.data.payload!=="object"||Array.isArray(V.data.payload))return!1;let D=V.data.payload;if(D.toolName!=="Task"||!D.input||typeof D.input!=="object"||Array.isArray(D.input))return!1;let b=D.input,T=b.resume_from??b.resume;return b.run_in_background===!0&&b.subagent_session_id===J.childSessionId&&b.description===J.subagentRef.subagentDescription&&(b.subagent_type===void 0||b.subagent_type===J.subagentRef.subagentType)&&(b.resume_from===void 0||b.resume===void 0||b.resume_from===b.resume)&&(T===void 0?J.subagentRef.subagentResumedFrom===void 0:T===J.subagentRef.subagentResumedFrom)});if(!X)return Z={eligible:!1,acknowledged:H,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(H)return Z={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];let Q=Y.find((V)=>V.type==="part_created"&&V.data.partType==="subtask_ref"&&V.data.payload!==null&&typeof V.data.payload==="object"&&!Array.isArray(V.data.payload)&&V.data.payload.childSessionId===J.childSessionId&&V.data.payload.status===J.subagentRef.subagentStatus);if(K&&Q)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let z=new Date().toISOString(),j=K?.data.messageId??s(),q=[];if(!K){let V={messageId:j,role:"user",inboxMessageId:J.inboxMessageId,createdAt:z,metadata:JSON.parse(JSON.stringify(J.metadata))};q.push(this.createEvent("message_created",$,V)),q.push(this.createEvent("part_created",$,{partId:s(),messageId:j,partType:"text",payload:{text:J.content},createdAt:z}))}if(!Q){let V=Y.findLast((b)=>b.type==="part_created"&&b.data.partType==="subtask_ref"&&b.data.messageId===X.data.messageId&&b.data.payload!==null&&typeof b.data.payload==="object"&&!Array.isArray(b.data.payload)&&b.data.payload.childSessionId===J.childSessionId),D=V?.data.payload&&typeof V.data.payload==="object"&&!Array.isArray(V.data.payload)?V.data.payload:void 0;q.push(this.createEvent("part_created",$,{partId:s(),messageId:X.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof D?.startedAt==="string"?D.startedAt:z,finishedAt:z},createdAt:z}))}return Z={eligible:!0,acknowledged:!1,persisted:q.length>0,messageId:j},q}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=t(Z);if(W.some((H)=>H.type==="turn_started"&&H.data.turnId===J.turnId))throw new S0;let Y=Q$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof S0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=t(W),H=new Set(Y.flatMap((z)=>z.type==="inbox_acknowledged"?z.data.messageIds:[])),K=[...new Set(Z)].filter((z)=>!H.has(z)),X=Y.findLast((z)=>(z.type==="turn_completed"||z.type==="turn_aborted")&&z.data.turnId===J.turnId);if(X){if(X.type==="turn_aborted"||K.length===0)throw new S0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]}let Q=Q$(Y).active;if(!Q||Q.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof S0))throw W}}async saveTurnAbort($,J){await this.saveTurnTerminal($,"turn_aborted",J)}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=t(J),W=Q$(Z).active;return W?t1(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=t(J).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let H=Y.input;return H.run_in_background===!0&&typeof H.subagent_session_id==="string"?[H.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=t(W),H=Q$(Y).active,K=t1(Y);if(!H&&K.orphaned.length===0)throw new S0;let X=H?T8(Y,H.turnId):void 0;if(H&&X&&K.orphaned.length===0){Z={turnId:H.turnId,outcome:"completed",finalization:X};let V=new Set(Y.flatMap((T)=>T.type==="inbox_acknowledged"?T.data.messageIds:[])),D=X.inputMessageIds.filter((T)=>!V.has(T)),b=new Date().toISOString();return[...D.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:D,acknowledgedAt:b})]:[],this.createEvent("turn_completed",$,{turnId:H.turnId,completedAt:b,turnsCount:X.turnsCount,toolCallsCount:X.toolCallsCount,durationMs:X.durationMs})]}Z=H?{turnId:H.turnId,outcome:"aborted"}:void 0;let Q=H?t1(Y,H.turnId).all.length:0,z=new Date().toISOString(),j=H?Date.parse(H.startedAt):Number.NaN,q=K.orphaned.flatMap((V)=>{let D=J.adoptedToolResults?.get(V.toolCallId),b=D?.toolCallId===V.toolCallId&&D.toolName===V.toolName?D:void 0,T=this.createEvent("part_created",$,{partId:V.toolCallId,messageId:b?V.messageId:V.toolCallId,partType:"tool_result",payload:b?{toolCallId:V.toolCallId,toolName:V.toolName,output:b.output,error:b.error??null,...b.metadata===void 0?{}:{metadata:b.metadata}}:{toolCallId:V.toolCallId,toolName:V.toolName,output:null,error:b8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:z});if(!b?.subagentRef)return[T];let A=b.subagentRef;return[T,this.createEvent("part_created",$,{partId:s(),messageId:V.messageId,partType:"subtask_ref",payload:{childSessionId:A.subagentSessionId,agentType:A.subagentType,description:A.subagentDescription??"",status:A.subagentStatus,summary:A.subagentSummary??"",resumedFrom:A.subagentResumedFrom??null,rootAgentId:A.subagentRootId??A.subagentSessionId,resumeDepth:A.subagentResumeDepth??0,verificationVerdict:A.verificationVerdict??null,startedAt:z,finishedAt:z},createdAt:z})]});return H?[...q,this.createEvent("turn_aborted",$,{turnId:H.turnId,cause:"process_restart",abortedAt:z,turnsCount:0,toolCallsCount:Q,durationMs:Number.isFinite(j)?Math.max(0,Date.now()-j):0})]:q})}catch(W){if(!(W instanceof S0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?k8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((H)=>H.type==="interaction_requested"&&H.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((H)=>H.type==="interaction_responded"&&H.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((H)=>H.type==="interaction_responded"&&H.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((H)=>H.type==="interaction_recovered"&&H.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((H)=>H.type==="review_started"&&H.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((H)=>H.type==="review_started"&&!Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===H.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((H)=>H.type==="review_started"&&H.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((H)=>H.type==="review_completed"&&H.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y){try{await this.ensureSessionCreated($,Y);let H=new Date().toISOString(),K=W??s(),X=[];if(!W){let j={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:H};X.push(this.createEvent("message_created",$,j))}let Q=s(),z={partId:Q,messageId:K,partType:"tool_call",payload:{toolCallId:Q,toolName:J,input:Z},createdAt:H};if(X.push(this.createEvent("part_created",$,z)),J==="Task"&&Z&&typeof Z==="object"){let j=Z,q=typeof j.subagent_session_id==="string"?j.subagent_session_id:void 0,V=typeof j.subagent_type==="string"?j.subagent_type:void 0;if(q&&V){let D={partId:s(),messageId:K,partType:"subtask_ref",payload:{childSessionId:q,agentType:V,status:"running",summary:typeof j.description==="string"?j.description:"",startedAt:H},createdAt:H};X.push(this.createEvent("part_created",$,D))}}return await this.log($).commitBatch(X),Q}catch(H){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,H),H}}async saveToolResult($,J,Z,W,Y=null,H,K,X,Q){try{await this.ensureSessionCreated($,K);let z=new Date().toISOString(),j=Y??s();return await this.log($).commitValidatedBatch((q)=>{let V=X?.subagentStatus==="running"?t(q).findLast((k)=>k.type==="part_created"&&k.data.partType==="subtask_ref"&&k.data.payload!==null&&typeof k.data.payload==="object"&&!Array.isArray(k.data.payload)&&k.data.payload.childSessionId===X.subagentSessionId&&(k.data.payload.status==="completed"||k.data.payload.status==="failed"||k.data.payload.status==="cancelled")):void 0,D=V?.data.payload,b=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},T=D?{...b,subagentSessionId:D.childSessionId,subagentType:D.agentType,description:D.description,subagentStatus:D.status,subagentSummary:D.summary,subagentResumedFrom:D.resumedFrom,subagentRootId:D.rootAgentId,subagentResumeDepth:D.resumeDepth,verificationVerdict:D.verificationVerdict}:Q,A=[];if(!Y){let k={messageId:j,role:"assistant",parentMessageId:void 0,createdAt:z};A.push(this.createEvent("message_created",$,k))}let x={partId:J,messageId:j,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:H??null,...T===void 0?{}:{metadata:T}},createdAt:z};if(A.push(this.createEvent("part_created",$,x)),X&&!V){let k=X.subagentStatus==="running"?null:z,W0={partId:s(),messageId:j,partType:"subtask_ref",payload:{childSessionId:X.subagentSessionId,agentType:X.subagentType,description:X.subagentDescription??"",status:X.subagentStatus,summary:X.subagentSummary??"",resumedFrom:X.subagentResumedFrom??null,rootAgentId:X.subagentRootId??X.subagentSessionId,resumeDepth:X.subagentResumeDepth??0,verificationVerdict:X.verificationVerdict??null,startedAt:z,finishedAt:k},createdAt:z};A.push(this.createEvent("part_created",$,W0))}return A}),J}catch(z){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,z),z}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),H=s(),K={messageId:H,role:"system",parentMessageId:W??void 0,createdAt:Y},X=this.buildCompactionMetadata(Z),Q={partId:s(),messageId:H,partType:"summary",payload:{text:J,metadata:X,...Z.replacementMessages?{replacementMessages:U6(Z.replacementMessages)}:{}},createdAt:Y},z=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,Q)];return await this.log($).commitBatch(z),H}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=z0(this.projectPath,$),W=await new O0(J).readAll();return W.length>0?t(W):null}catch{return null}}async loadSession($){try{let J=z0(this.projectPath,$),Z=new O0(J),W=t(await Z.readAll());if(W.length===0)return null;let Y=W.find((H)=>H.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=z0(this.projectPath,$),Z=new O0(J),W=t(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let Q of W){if(Q.type==="message_created")Y.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let z=Y.get(Q.data.messageId);if(z){let j=Q.data.payload;z.content=j.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let z=Y.get(Q.data.messageId);if(z)z.content=z.content?`${z.content}
|
|
121
|
-
[Image]`:"[Image]"}}let H=Array.from(Y.values()),K=W[W.length-1],X=new Date(K.timestamp).getTime();return{messages:H,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=H$(this.projectPath);return(await U0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=z0(this.projectPath,$),Z=new O0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let H=t(Y),K=Y[Y.length-1],X=H.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=z0(this.projectPath,$);await new O0(J).delete(),await U0.unlink(K1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-
|
|
121
|
+
[Image]`:"[Image]"}}let H=Array.from(Y.values()),K=W[W.length-1],X=new Date(K.timestamp).getTime();return{messages:H,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=H$(this.projectPath);return(await U0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=z0(this.projectPath,$),Z=new O0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let H=t(Y),K=Y[Y.length-1],X=H.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=z0(this.projectPath,$);await new O0(J).delete(),await U0.unlink(K1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-z1aqe7ms.js"),H=await W();if(H)Y(H,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,H)=>H.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,J,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let Y=t(W);if(Y.some((X)=>(X.type==="turn_completed"||X.type==="turn_aborted")&&X.data.turnId===Z.turnId))throw new S0;let K=Q$(Y).active;if(!K||K.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return J==="turn_completed"?this.createEvent("turn_completed",$,Z):this.createEvent("turn_aborted",$,Z)})}catch(W){if(!(W instanceof S0))throw W}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=z0(this.projectPath,Z),H=await new O0(W).getStats();J+=H.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=H$(this.projectPath);await U0.mkdir($,{recursive:!0,mode:493});let J=y6.join($,".health-check");return await U0.writeFile(J,"test","utf-8"),await U0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return q6()}}function x8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var _6=131072,b6=new Map;function e1($,J){let Z=`${$}\x00${J}`,W=b6.get(Z);if(!W)W=new M8,b6.set(Z,W);return W}function Z2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>_6)throw Error(`${J} exceeds ${_6} bytes`);return JSON.parse(Z)}function N6($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function R8($,J){return JSON.stringify($)===JSON.stringify(J)}function C8($,J){if($.request.interactionType!=="elicitation")return Z2(J,"Interaction response");return Z2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function P6($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function I8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function v8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
|
|
122
122
|
`)}function p8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let K=v8(J);return{toolOutput:`User answers:
|
|
123
123
|
${K}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
124
124
|
${K}
|
|
@@ -201,4 +201,4 @@ ${E}`}if(typeof M==="object"&&M!==null)M=JSON.stringify(M,null,2);if(typeof M===
|
|
|
201
201
|
${f6(c0)}
|
|
202
202
|
</system-reminder>`,metadata:C$};G.appendControl("user",L);let B=await K0($,Z,L.content,Q,C$);if(B)Q=B}}if(W?.signal?.aborted)return j(K,X.length,W.signal);if(K>=j$&&(XJ||R)){if(I.info(`Warning: 达到轮次上限 ${j$} 轮`),W?.onTurnLimitReached){let L=await W.onTurnLimitReached({turnsCount:K});if(L?.continue){G.writeback();let B="failed",P,_,c;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let N=$.chatService.getConfig(),y=await K$.compact(Z.messages,{trigger:"auto",modelName:N.model,modelProvider:N.provider,maxContextTokens:N.maxContextTokens??0,apiKey:N.apiKey,baseURL:N.baseUrl,actualPreTokens:O1,signal:W?.signal,activeTask:j0,workspaceRoot:Z.workspaceRoot||a(),sessionId:Z.sessionId});if(y.usage)yield{kind:"token_usage",usage:G1(y.usage,N.maxContextTokens??0)};let S={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
203
203
|
|
|
204
|
-
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},M=[...y.compactedMessages,S];P=y.success?"llm":"fallback",_=y.preTokens,c=y.postTokens,await T$($,Z,y.summary,{trigger:"auto",reason:"turn_limit",strategy:P,preTokens:y.preTokens,postTokens:y.postTokens,filesIncluded:y.filesIncluded,replacementMessages:M},{required:$.executionEngine!==void 0}),Z.messages=M,G.replaceHistory(Z.messages),B=y.success?"completed":"fallback"}catch(N){throw I.error("[Loop] 轮次上限压缩失败,停止继续执行:",N),N}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:B,strategy:P,preTokens:_,postTokens:c}}K=0;continue}return{success:!0,finalMessage:L?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}return{success:!1,error:{type:"max_turns_exceeded",message:R?`子代理已达到轮次上限 (${j$} 轮)。`:`已达到轮次上限 (${j$} 轮)。`},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}}}catch(O){if(O instanceof Y$)try{let U=Z.sessionId?await f$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):B0;G.restoreDurableHistory(U)}catch(U){I.error("[Loop] Failed to reload durable context after message commit failure:",U),G.restoreDurableHistory(B0)}throw O}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((O)=>{let U=O.metadata;return U!==null&&typeof U==="object"&&!Array.isArray(U)&&U.transientGoalContinuation===!0});G.writeback()}}catch(q){if(C0(q))return j(K,X.length,W?.signal);if(q instanceof Y$)return{success:!1,error:{type:"message_persistence_failed",message:q.message},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}};let V=f4(q);return I.error(`API 调用失败: ${V}`),{success:!1,error:{type:"api_error",message:V,details:q},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}}}finally{if(z)Z.messages.push({role:"system",content:c1}),await t2($,Z,Q)}}export{l1 as
|
|
204
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},M=[...y.compactedMessages,S];P=y.success?"llm":"fallback",_=y.preTokens,c=y.postTokens,await T$($,Z,y.summary,{trigger:"auto",reason:"turn_limit",strategy:P,preTokens:y.preTokens,postTokens:y.postTokens,filesIncluded:y.filesIncluded,replacementMessages:M},{required:$.executionEngine!==void 0}),Z.messages=M,G.replaceHistory(Z.messages),B=y.success?"completed":"fallback"}catch(N){throw I.error("[Loop] 轮次上限压缩失败,停止继续执行:",N),N}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:B,strategy:P,preTokens:_,postTokens:c}}K=0;continue}return{success:!0,finalMessage:L?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}return{success:!1,error:{type:"max_turns_exceeded",message:R?`子代理已达到轮次上限 (${j$} 轮)。`:`已达到轮次上限 (${j$} 轮)。`},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}}}catch(O){if(O instanceof Y$)try{let U=Z.sessionId?await f$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):B0;G.restoreDurableHistory(U)}catch(U){I.error("[Loop] Failed to reload durable context after message commit failure:",U),G.restoreDurableHistory(B0)}throw O}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((O)=>{let U=O.metadata;return U!==null&&typeof U==="object"&&!Array.isArray(U)&&U.transientGoalContinuation===!0});G.writeback()}}catch(q){if(C0(q))return j(K,X.length,W?.signal);if(q instanceof Y$)return{success:!1,error:{type:"message_persistence_failed",message:q.message},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}};let V=f4(q);return I.error(`API 调用失败: ${V}`),{success:!1,error:{type:"api_error",message:V,details:q},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}}}finally{if(z)Z.messages.push({role:"system",content:c1}),await t2($,Z,Q)}}export{l1 as Pa,S$ as Qa,m4 as Ra,I1 as Sa,s$ as Ta,Q$ as Ua,d1 as Va,o2 as Wa,Y5 as Xa,E$ as Ya,a0 as Za,I0 as _a,yJ as $a,J$ as ab,l4 as bb,p1 as cb,g1 as db,m2 as eb,u1 as fb,c6 as gb,i6 as hb,r6 as ib,$$ as jb,a$ as kb,iJ as lb,K0 as mb,g as nb,i1 as ob,Z1 as pb,T$ as qb,h0 as rb,K$ as sb,Q1 as tb,e as ub,q1 as vb,s6 as wb,t6 as xb,e6 as yb,U4 as zb,w2 as Ab,KJ as Bb,C4 as Cb};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ne as YO}from"./chunk-cxzx7j0p.js";import{Tf as qO,Vf as S,Yf as y}from"./chunk-m8ss9rmx.js";import{dg as K}from"./chunk-kfpzrmq7.js";import{Eg as XO}from"./chunk-fhnkyqfb.js";import{Yg as n}from"./chunk-q78s028m.js";import{fh as r}from"./chunk-qb0sqh29.js";import{hh as w}from"./chunk-hfrcwkc8.js";var N;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(N||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import _ from"node:path";import{nanoid as z}from"nanoid";var C={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import jO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import h from"node:path";import{Mutex as WO}from"async-mutex";import SO from"write-file-atomic";var k=1,GO=1048576,VO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function LO(O){let q={};for(let Q of Object.values(N)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(N))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(LO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new WO;filePath;constructor(O=h.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let J;try{J=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let W=J.projects[Z];if(!W)return{...X,state:"untrusted"};return{...X,state:W.digest===$?"trusted":"modified",trustedDigest:W.digest,trustedAt:W.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:k,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>GO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==k)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!h.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!VO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:k,projects:Z}}async writeStore(O){let q=h.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await SO(this.filePath,`${JSON.stringify(O,null,2)}
|
|
2
2
|
`,{mode:384}),await j.chmod(this.filePath,384)}}class T extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function e(O,q={}){let Q;try{Q=new URL(O)}catch{throw new T(`Invalid URL: ${O}`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw new T(`Only http/https supported, got: ${Q.protocol}`);let Z=Q.hostname.toLowerCase();if(zO(Z,q.allowedHosts))return;if(Q.protocol==="http:"&&!q.allowHttp)throw new T(`HTTP (non-TLS) blocked for ${Z}; use https:// or add to allowedHosts`);if(BO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(AO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function zO(O,q){if(!q||q.length===0)return!1;return q.some((Q)=>{let Z=Q.toLowerCase();if(Z===O)return!0;if(Z.startsWith("*.")){let Y=Z.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function BO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function AO(O){let q=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!q)return!1;let[Q,Z]=q.slice(1).map(Number);if(Q===10)return!0;if(Q===172&&Z>=16&&Z<=31)return!0;if(Q===192&&Z===168)return!0;if(Q===169&&Z===254)return!0;return!1}function OO(O){if(!O)return{};let q={};for(let[Q,Z]of Object.entries(O))q[Q]=Z.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,$)=>{return process.env[$]??`\${${$}}`});return q}var KO=S.Object({hookEventName:S.Literal("PreToolUse"),permissionDecision:S.Optional(S.Enum(m)),permissionDecisionReason:S.Optional(S.String()),updatedInput:S.Optional(S.Record(S.String(),S.Unknown()))}),PO=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),_O=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),UO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),bO=S.Object({hookEventName:S.Literal("PermissionRequest"),permissionDecision:S.Optional(y(["approve","deny","ask"])),permissionDecisionReason:S.Optional(S.String())}),QO=S.Record(S.String(),S.Union([S.String(),S.Number(),S.Boolean(),S.Array(S.String(),{maxItems:100})]),{maxProperties:32}),NO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),MO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),wO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),CO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),EO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([KO,PO,_O,UO,bO,NO,MO,TO,wO,CO])),suppressOutput:S.Optional(S.Boolean())});function ZO(O){return qO(EO,O)}class p{parse(O,q,Q){if(O.timedOut){let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let Z=this.tryParseJSON(O.stdout);if(Z){let Y=ZO(Z);if(!Y.success){let X="error"in Y?Y.error.message:"Unknown validation error",J=Q?.failureBehavior||"ignore",W=`Invalid hook output JSON: ${X}`;if(J==="deny")return{success:!1,blocking:!0,error:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(J==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${W}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let $=Y.data;if($.decision?.behavior==="block")return{success:!1,blocking:!0,error:$.systemMessage||"Hook blocked execution",output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};if($.decision?.behavior==="async")return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}return this.parseByExitCode(O,q,Q)}parseByExitCode(O,q,Q){let Z=O.exitCode;switch(Z){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 124:{let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}default:{let Y=Q?.failureBehavior||"ignore",$=O.stderr||O.stdout||`Hook failed with exit code ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${$}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}}}tryParseJSON(O){try{let q=O.trim();if(!q)return null;let Q=q.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Q)return null;return JSON.parse(Q[1])}catch{return null}}}class l{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let q=this.maxSize-this.content.length;this.content+=O.substring(0,q)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class u{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,q,Q,Z){let Y=JSON.stringify(q);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let $=this.createSafeEnv(q,Q.environment),{child:X,processTree:J}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),W=new l(this.MAX_STDOUT_SIZE),G=new l(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{W.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await J.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,R)=>{let F=!1,V=!1,B,P=()=>{return B??=J.terminate(),B},b=null,H=()=>{if(b&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",b),b=null},I=setTimeout(()=>{F=!0,P()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(I),H(),F)await P();L({stdout:W.getContent(),stderr:G.getContent(),exitCode:F?124:f??1,timedOut:F})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(I),H(),R(f)}),Q.abortSignal){if(b=()=>{if(V)return;V=!0,clearTimeout(I),H(),P().then(()=>{L({stdout:W.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",b),Q.abortSignal.aborted)b()}})}createSafeEnv(O,q={}){return{...q,PATH:q.PATH??process.env.PATH??"",HOME:q.HOME??process.env.HOME??"",USER:q.USER??process.env.USER??"",SHELL:q.SHELL??process.env.SHELL??"/bin/sh",BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:""}}}var $O=XO("Execution"),DO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',Elicitation:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',ElicitationResult:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class x{processExecutor=new u;outputParser=new p;chatServiceCache=new Map;sessionModelResources=new Map;sessionEnvironments=new Map;trustWarnings=new Set;bindSessionModelResources(O,q,Q){for(let Z of q)this.sessionModelResources.set(this.sessionResourceKey(O,Z),Q),this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q.config.env)}bindSessionEnvironment(O,q,Q){for(let Z of q)this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q)}async unbindSessionModelResources(O,q){for(let Q of q){let Z=this.sessionResourceKey(O,Q);this.sessionModelResources.delete(Z),this.sessionEnvironments.delete(Z);let Y=`${Z}\x00`;for(let[$,X]of this.chatServiceCache){if(!$.startsWith(Y))continue;this.chatServiceCache.delete($),await X.dispose?.()}}}async executePreToolHooks(O,q,Q){if(O.length===0)return{decision:"allow"};let Z="tool_input"in q?q.tool_input:{},Y=[];for(let $ of O)try{let X={...q,...Z&&{tool_input:Z}},J=await this.executeHook($,X,Q);if(!J.success){if(J.blocking)return{decision:"deny",reason:J.error};if(J.needsConfirmation)return{decision:"ask",reason:J.warning||J.error};if(J.warning)Y.push(J.warning);continue}let W=J.output?.hookSpecificOutput;if(W&&"permissionDecision"in W){switch(W.permissionDecision){case"deny":return{decision:"deny",reason:W.permissionDecisionReason};case"ask":return{decision:"ask",reason:W.permissionDecisionReason};case"allow":break}if("updatedInput"in W&&W.updatedInput)Z={...Z,...W.updatedInput}}}catch(X){let J=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${J}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:J};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${J}. Continue?`}}return{decision:"allow",modifiedInput:Z,warning:Y.length>0?Y.join(`
|
|
3
3
|
`):void 0}}async executePostToolHooks(O,q,Q){if(O.length===0)return{};let Z=Q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,q,Q,Z),$=[],X=void 0,J=[];for(let W of Y){if(!W.success&&W.warning){J.push(W.warning);continue}let G=W.output?.hookSpecificOutput;if(G&&"additionalContext"in G){if(G.additionalContext)$.push(G.additionalContext);if("updatedOutput"in G&&G.updatedOutput!==void 0)X=G.updatedOutput}}return{additionalContext:$.length>0?$.join(`
|
|
4
4
|
|
|
@@ -25,7 +25,7 @@ import{Le as YO}from"./chunk-f542fh7g.js";import{If as qO,Kf as S,Nf as y}from".
|
|
|
25
25
|
`):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let J of O)try{let W=await this.executeHook(J,q,Q);if(!W.success){if(W.warning)Y.push(W.warning);continue}if(W.output?.suppressOutput){$=!0;break}if(W.stdout&&W.stdout.trim())X=W.stdout.trim()}catch(W){let G=W instanceof Error?W.message:String(W);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
|
|
26
26
|
`):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
|
|
27
27
|
`):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
|
|
28
|
-
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-
|
|
28
|
+
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-pyk2ey7y.js"),{createChatServiceAsync:J}=await import("./chunk-6cx4t8r6.js"),{resolveModelConfig:W}=await import("./chunk-fer18bbe.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-qmcj20g2.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
|
|
29
29
|
|
|
30
30
|
`+`## 评估指令
|
|
31
31
|
${O.prompt}
|
|
@@ -42,4 +42,4 @@ ${O.prompt}
|
|
|
42
42
|
`+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
|
|
43
43
|
`+`- 如果没有发现问题,使用 "approve"
|
|
44
44
|
`+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(O){let q=O.trim(),Q=q.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(Q)return Q[1].trim();return q}async executeHooksConcurrently(O,q,Q,Z){let Y=[],$=new Set;for(let X of O){if($.size>=Z)await Promise.race($);let J=this.executeHook(X,q,Q).catch((G)=>({success:!1,blocking:!1,error:G instanceof Error?G.message:String(G),hook:X})),W=J.then(()=>{$.delete(W)}).catch(()=>{$.delete(W)});$.add(W),Y.push(J)}return Promise.all(Y)}}async function yO(O,q){let Q=O.body?.getReader();if(!Q)return"";let Z=new TextDecoder,Y=0,$="";while(!0){let{value:X,done:J}=await Q.read();if(J)break;if(Y+=X.byteLength,Y>q){try{Q.cancel()}catch{}$+=Z.decode(X.slice(0,q-(Y-X.byteLength)));break}$+=Z.decode(X,{stream:!0})}return $+=Z.decode(),$}import a from"picomatch";var HO=/^([A-Za-z0-9_|]+)\((.+)\)$/;class i{matches(O,q){if(!O)return!0;if(O.tools&&q.toolName){if(!this.matchTools(O.tools,q))return!1}if(O.paths){let Q=q.filePaths??(q.filePath?[q.filePath]:[]);if(Q.length===0||!Q.some((Z)=>this.matchPaths(O.paths,Z)))return!1}if(O.commands&&q.command){if(!this.matchCommands(O.commands,q.command))return!1}return!0}matchTools(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchToolWithParams(Q,q));return this.matchToolWithParams(O,q)}matchPaths(O,q){if(Array.isArray(O))return O.some((Z)=>{return a(Z)(q)});return a(O)(q)}matchCommands(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchPattern(q,Q));return this.matchPattern(q,O)}matchToolWithParams(O,q){let{toolName:Q,command:Z,filePath:Y}=q,$=HO.exec(O);if(!$)return this.matchPattern(Q,O);let[,X,J]=$;if(!this.matchPattern(Q,X))return!1;let W=this.getArgValues(Q,Z,q.filePaths??(Y?[Y]:[]));if(W.length===0)return!1;return W.some((G)=>this.matchGlobOrPattern(G,J))}getArgValues(O,q,Q=[]){if(O==="Bash"||O==="BashTool")return q?[q]:[];if(["Read","Edit","Write","ApplyPatch","Glob","Grep"].includes(O))return Q;return q?[q]:Q}matchGlobOrPattern(O,q){if(/[*?[\]{}!]/.test(q))try{return a(q,{bash:!0,dot:!0})(O)}catch{}if(q.endsWith("*")){let Q=q.slice(0,-1);return O.startsWith(Q)}return O===q}matchPattern(O,q){if(q==="*")return!0;if(!q.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(q))return O===q;if(q.includes("|"))return q.split("|").map((Z)=>Z.trim()).includes(O);try{return new RegExp(q).test(O)}catch{return O===q}}}class U{static instance=null;config=C;executor=new x;guard=new d;matcher=new i;processDisabled=!1;disabledSessions=new Set;sessionStateAliases=new Map;projectConfigs=new Map;sessionConfigs=new Map;managedFunctionMatchers={};constructor(){}static getInstance(){if(!U.instance)U.instance=new U;return U.instance}bindSessionModelResources(O,q,Q){this.executor.bindSessionModelResources(O,q,Q)}bindSessionEnvironment(O,q,Q){this.executor.bindSessionEnvironment(O,q,Q)}bindSessionConfig(O,q,Q){let Z=this.sessionConfigKey(O,q[0]??K()),Y=this.disabledSessions.has(Z);for(let $ of q){let X=this.sessionConfigKey(O,$);if(Y||=this.disabledSessions.has(X),this.sessionStateAliases.set(X,Z),this.sessionConfigs.set(X,this.snapshotConfig(Q)),X!==Z)this.disabledSessions.delete(X)}if(Y)this.disabledSessions.add(Z)}async unbindSessionModelResources(O,q){let Q=new Set;for(let Z of q){let Y=this.sessionConfigKey(O,Z);Q.add(this.sessionStateAliases.get(Y)??Y),this.sessionConfigs.delete(Y),this.sessionStateAliases.delete(Y),this.disabledSessions.delete(Y)}for(let Z of Q)this.disabledSessions.delete(Z);await this.executor.unbindSessionModelResources(O,q)}static resetInstance(){U.instance?.cleanup(),U.instance=null}loadConfig(O,q=K()){let Q=E(C,O),Z=c();Q=E(Q,Z);let Y=_.resolve(q);if(Y===_.resolve(K()))this.config=Q;this.projectConfigs.set(Y,Q)}isEnabled(O=K(),q){if(!(q?this.getExecutionConfig(q,O):this.getConfig(O)).enabled)return!1;if(this.processDisabled)return!1;if(q&&this.disabledSessions.has(this.sessionStateKey(q,O)))return!1;return!0}disable(){this.processDisabled=!0,console.log("[HookManager] Hooks disabled for this process")}enable(){this.processDisabled=!1,console.log("[HookManager] Hooks enabled for this process")}disableSession(O,q){this.disabledSessions.add(this.sessionStateKey(O,q))}enableSession(O,q){this.disabledSessions.delete(this.sessionStateKey(O,q))}isSessionEnabled(O,q){return this.isEnabled(q,O)}isSessionPaused(O,q){return this.disabledSessions.has(this.sessionStateKey(O,q))}getConfig(O=K()){let q=_.resolve(O),Q=this.projectConfigs.get(q);if(Q)return Q;if(q===_.resolve(K()))return this.config;return{...C,enabled:!1}}getExecutionConfig(O,q){return this.sessionConfigs.get(this.sessionConfigKey(O,q))??this.getConfig(q)}isExecutionEnabled(O,q,Q){return O.enabled===!0&&!this.processDisabled&&!this.disabledSessions.has(this.sessionStateKey(q,Q))}sessionStateKey(O,q){let Q=this.sessionConfigKey(O,q);return this.sessionStateAliases.get(Q)??Q}sessionConfigKey(O,q){return`${O}\x00${_.resolve(q)}`}snapshotConfig(O){let q=E(C,O);for(let Q of Object.values(N))q[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((Y)=>({...Y}))}));return q}inheritProjectConfig(O,q){this.projectConfigs.set(_.resolve(q),this.getConfig(O))}getTrustStatus(O=K()){return A.getInstance().getStatus(O,this.getConfig(O))}trustProject(O=K(),q){return A.getInstance().trust(O,this.getConfig(O),q)}revokeProjectTrust(O=K()){return A.getInstance().revoke(O,this.getConfig(O))}registerFunction(O,q,Q,Z){let Y={type:"function",handler:Q,timeout:Z?.timeout},$={name:Z?.name??`inline-${O}-${Date.now()}`,matcher:q,hooks:[Y]};if(Z?.projectDir){let J=_.resolve(Z.projectDir),W=this.getConfig(J),G=W[O]??[];return W[O]=[...G,$],this.projectConfigs.set(J,W),()=>{let L=W[O];if(!L)return;W[O]=L.filter((R)=>R!==$)}}let X=this.managedFunctionMatchers[O]??[];return this.managedFunctionMatchers[O]=[...X,$],()=>{let J=this.managedFunctionMatchers[O]??[];this.managedFunctionMatchers[O]=J.filter((W)=>W!==$)}}async reloadConfig(O=K()){let q=await import("node:fs/promises"),Q=await import("node:path");try{let Z=Q.join(O,".blade","settings.local.json"),Y=await q.readFile(Z,"utf-8"),$=JSON.parse(Y);if($.hooks)this.loadConfig($.hooks,O)}catch{}}async executePreToolHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"allow"};if(Z.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(q,"PreToolUse"))return{decision:"allow"};let $={hook_event_name:"PreToolUse",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"allow"};let J={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{let W=await this.executor.executePreToolHooks(X,$,J);if(this.guard.markExecuted(q,"PreToolUse"),Z.permissionMode==="yolo"){if(W.decision==="deny")return W;return{decision:"allow",modifiedInput:W.modifiedInput,warning:W.warning,reason:W.reason}}return W}catch(W){return console.error("[HookManager] Error executing PreToolUse hooks:",W),{decision:"allow",warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executePostToolHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(q,"PostToolUse"))return{};let X={hook_event_name:"PostToolUse",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,tool_response:Z,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(J.length===0)return{};let W={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{let G=await this.executor.executePostToolHooks(J,X,W);return this.guard.markExecuted(q,"PostToolUse"),G}catch(G){return console.error("[HookManager] Error executing PostToolUse hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}finally{this.guard.cleanup(q)}}async executeStopHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{shouldStop:!0};let Q={hook_event_name:"Stop",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},Z=this.getMatchingHooks("Stop",{},q);if(Z.length===0)return{shouldStop:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing Stop hooks:",$),{shouldStop:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSubagentStopHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{shouldStop:!0};let Z={hook_event_name:"SubagentStop",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,agent_type:O,task_description:q.taskDescription,success:q.success,result_summary:q.resultSummary,error:q.error},Y=this.getMatchingHooks("SubagentStop",{},Q);if(Y.length===0)return{shouldStop:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing SubagentStop hooks:",X),{shouldStop:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePermissionRequestHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"ask"};let $={hook_event_name:"PermissionRequest",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"ask"};let J={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,J)}catch(W){return console.error("[HookManager] Error executing PermissionRequest hooks:",W),{decision:"ask",warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeUserPromptSubmitHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{proceed:!0};let Z={hook_event_name:"UserPromptSubmit",hook_execution_id:z(),timestamp:new Date().toISOString(),user_prompt:O,has_images:q.hasImages,image_count:q.imageCount,project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{},Q);if(Y.length===0)return{proceed:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",X),{proceed:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeSessionStartHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{proceed:!0};let Q={hook_event_name:"SessionStart",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},Z=this.getMatchingHooks("SessionStart",{},q);if(Z.length===0)return{proceed:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing SessionStart hooks:",$),{proceed:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSessionEndHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"SessionEnd",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,reason:O},Y=this.getMatchingHooks("SessionEnd",{},Q);if(Y.length===0)return{};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,Z,$),{}}catch(X){return console.error("[HookManager] Error executing SessionEnd hooks:",X),{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolUseFailureHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};let X={hook_event_name:"PostToolUseFailure",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,error:Z,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(J.length===0)return{};let W={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(J,X,W)}catch(G){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeNotificationHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{suppress:!1,message:q};let Y={hook_event_name:"Notification",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,notification_type:O,title:Q.title,message:q},$=this.getMatchingHooks("Notification",{},Z);if($.length===0)return{suppress:!1,message:q};let X={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeNotificationHooks($,Y,X)}catch(J){return console.error("[HookManager] Error executing Notification hooks:",J),{suppress:!1,message:q,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeElicitationHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"Elicitation",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,server_name:O.serverName,mode:O.mode,message:O.message,requested_schema:O.requestedSchema,url:O.url,elicitation_id:O.elicitationId};return this.executeElicitationHookChain("Elicitation",Z,q,Q)}async executeElicitationResultHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{};let Y={hook_event_name:"ElicitationResult",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,server_name:O.serverName,mode:O.mode,elicitation_id:O.elicitationId,action:q.action,content:q.content};return this.executeElicitationHookChain("ElicitationResult",Y,Q,Z)}async executeElicitationHookChain(O,q,Q,Z){let Y=this.getMatchingHooks(O,{},Z);if(Y.length===0)return{};let $={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeElicitationHooks(Y,q,$)}catch(X){return{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeCompactionHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{blockCompaction:!1};let Z={hook_event_name:"Compaction",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,trigger:O,messages_before:q.messagesBefore,tokens_before:q.tokensBefore},Y=this.getMatchingHooks("Compaction",{},Q);if(Y.length===0)return{blockCompaction:!1};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeCompactionHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing Compaction hooks:",X),{blockCompaction:!1,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}getMatchingHooks(O,q,Q){let Z=[...Q[O]??[],...this.managedFunctionMatchers[O]??[]],Y=[];for(let $ of Z)if(this.matcher.matches($.matcher,q))Y.push(...$.hooks);return Y}extractFilePaths(O){let q=[],Q=["file_path","path","filePath","source","target"];for(let Z of Q){let Y=O[Z];if(typeof Y==="string")q.push(Y)}if(typeof O.patch==="string"){for(let Z of O.patch.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm))if(Z[1])q.push(Z[1]);for(let Z of O.patch.matchAll(/^\*\*\* Move to: (.+)$/gm))if(Z[1])q.push(Z[1])}return[...new Set(q)]}extractCommand(O,q){if(O==="Bash"||O==="BashTool"){let Q=q.command;if(typeof Q==="string")return Q}return}cleanup(){this.guard.cleanupAll(),this.disabledSessions.clear(),this.sessionStateAliases.clear()}}
|
|
45
|
-
export{N as
|
|
45
|
+
export{N as He,o as Ie,U as Je};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{hg as y_,ig as Qf,jg as Kf,kg as g_,lg as zf,ng as Wf,pg as Hf,qg as hf,rg as Rf,sg as $f,ug as Sf,vg as Gf,xg as I}from"./chunk-yk9pxkc1.js";import{Eg as q}from"./chunk-fhnkyqfb.js";import{Ig as ef,Kg as Cf}from"./chunk-26wse17p.js";import{Ng as v_}from"./chunk-hcm55r3d.js";var ME={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},af=(f)=>ME[f]||{};var AE=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&AE.has(f)}function nE(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function ET(f){if(Vf(f))return!0;if(!(f instanceof Error))return!1;if(f.name==="AbortError")return!0;if(f instanceof DOMException&&f.name==="AbortError")return!0;if(f.message.includes("aborted"))return!0;return!1}function yf(...f){let _=f.filter(Boolean);if(_.length===0)return new AbortController().signal;if(_.length===1)return _[0];let E=AbortSignal;if(typeof E.any==="function")return E.any(_);for(let A of _)if(A.aborted)return A;let T=new AbortController,x=new Map;for(let A of _){let Y=()=>{T.abort(A.reason);for(let[R,h]of x)R.removeEventListener("abort",h)};x.set(A,Y)}for(let[A,Y]of x)A.addEventListener("abort",Y,{once:!0});return T.signal}function d(f,_,E){let T=E?.throwOnAbort??!1;if(_?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((x,A)=>{let Y,R=setTimeout(()=>{if(_&&Y)_.removeEventListener("abort",Y);x()},f);if(_)Y=()=>{if(clearTimeout(R),T)A(new DOMException("Aborted","AbortError"));else x()},_.addEventListener("abort",Y,{once:!0})})}var hE=q("Chat"),RE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function bf(f){if(typeof f==="string")return f;return f.filter((_)=>_.type==="text").map((_)=>_.text).join(`
|
|
2
2
|
`)}function SE(f){if(!f)return{};try{let _=JSON.parse(f);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return hE.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function YE(f){let _=f.match(/^data:([^;,]+);base64,(.+)$/s);return _?{mimeType:_[1],data:_[2]}:void 0}async function PE(f,_){let E=YE(f);if(E)return{type:"image",...E};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:_});if(!T.ok)throw Error(`Failed to load image ${f}: HTTP ${T.status}`);return{type:"image",mimeType:T.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await T.arrayBuffer()).toString("base64")}}async function of(f,_,E,T,x){let A=f.filter((h)=>h.role==="system").map((h)=>bf(h.content)).filter(Boolean).join(`
|
|
3
3
|
|
|
4
4
|
`),Y=[];for(let h of f){if(h.role==="system")continue;if(h.role==="user"){let U=_.input.includes("image"),M=typeof h.content==="string"?h.content:await Promise.all(h.content.map((P)=>P.type==="text"?Promise.resolve({type:"text",text:P.text}):U?PE(P.image_url.url,T):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));Y.push({role:"user",content:M,timestamp:Date.now()});continue}if(h.role==="assistant"){let U=[];if(h.reasoningContent?.trim())U.push({type:"thinking",thinking:h.reasoningContent});let M=bf(h.content);if(M)U.push({type:"text",text:M});for(let P of h.tool_calls??[]){if(!("function"in P))continue;U.push({type:"toolCall",id:P.id,name:P.function.name,arguments:SE(P.function.arguments)})}Y.push({role:"assistant",content:U,api:_.api,provider:_.provider,model:_.id,usage:RE,stopReason:h.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}Y.push({role:"toolResult",toolCallId:h.tool_call_id??"",toolName:h.name??"unknown",content:[{type:"text",text:bf(h.content)}],isError:!1,timestamp:Date.now()})}let R=E?.filter((h)=>!x||h.name===x).map((h)=>({name:h.name,description:h.description,parameters:h.parameters,constrainedSampling:h.constrainedSampling}));return{...A?{systemPrompt:A}:{},messages:Y,...R?.length?{tools:R}:{}}}function df(f){let _=[];for(let E=0;E<f.length;E++){let T=f[E];if(T.role==="tool")continue;let x=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!x){_.push(T);continue}let A=[],Y=E+1;while(Y<f.length&&f[Y].role==="tool")A.push(f[Y++]);let R=new Set(x.map((M)=>M.id)),h=A.filter((M)=>M.tool_call_id&&R.has(M.tool_call_id)),U=new Set(h.map((M)=>M.tool_call_id));if(R.size===x.length&&h.length===R.size&&U.size===R.size)_.push(T,...h);E=Y-1}return _}function rf(f){return f.some((_)=>_.role==="assistant"&&Boolean(_.tool_calls?.length)&&!_.reasoningContent?.trim())}function nf(f,_){return{...f,..._.baseUrl?{baseUrl:ef(f.api,_.baseUrl)}:{},..._.maxOutputTokens?{maxTokens:_.maxOutputTokens}:{}}}function jf(f){let _=f.modelCatalog??Cf();return{models:_.models,model:nf(_.getModel(f.provider,f.model),f)}}function f_(f,_){let E=f.modelCatalog??Cf();return nf(E.getModel(_.provider,_.model),f)}import{randomBytes as OE}from"node:crypto";import{createHmac as UE}from"node:crypto";function uE(f){try{let _=new URL(f);if(_.hash="",_.hostname=_.hostname.toLowerCase(),_.searchParams.sort(),_.pathname!=="/")_.pathname=_.pathname.replace(/\/+$/,"");return _.toString()}catch{return f.trim().replace(/\/+$/,"")}}function DE(f){if(!f)return[];return Object.entries(f).map(([_,E])=>[_.trim().toLowerCase(),E.trim()]).sort(([_],[E])=>_.localeCompare(E))}function xf(f,_,E){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),uE(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",DE(f.customHeaders),E]);return UE("sha256",Buffer.from(_)).update(T).digest("hex")}var NE=60000,BE=4,VE=0.8;var Af=300000,Xf=600000;var __=128,E_=256,bE=1800000,Mf=50;class e extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function Jf(f){return f instanceof e||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function m(f,_){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:_}function CE(f,_){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:_}function jE(f,_){return xf(f,_,{providerCircuitOpenDurationMs:f.openDurationMs})}function r(f){let _=0;for(let E of f)if(E.failure)_++;return _}function T_(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function x_(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Wf)}class A_{#M=new Map;#R=new WeakMap;#f;#_;#T;#E;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):OE(32),this.#_=f.now??(()=>performance.now()),this.#T=f.wallNow??f.now??Date.now,this.#E={maxEntries:Math.min(m(f.maxEntries,__),__),maxWindowEntries:Math.min(m(f.maxWindowEntries,E_),E_),windowMs:m(f.windowMs,NE),minSamples:m(f.minSamples,BE),errorRateThreshold:CE(f.errorRateThreshold,VE),idleTtlMs:m(f.idleTtlMs,bE)}}get size(){return this.#M.size}get(f){if(f.openDurationMs===0)return this.#A();let _=this.#_();this.#V(_);let E=jE(f,this.#f),T=this.#M.get(E);if(T)return T.lastTouchedAt=_,this.#x(T,f.probeLeaseMs);if(this.#M.size>=this.#E.maxEntries)this.#j();if(this.#M.size>=this.#E.maxEntries)return this.#A();let x={key:E,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:_,detached:!1};return this.#M.set(E,x),this.#x(x,f.probeLeaseMs)}#x(f,_){let E=this,T=Math.max(Af,Math.min(m(_,Af),Xf));return{preflight:()=>E.#U(f),check:()=>E.#u(f,T),recordSuccess:(x)=>E.#N(x,"success"),recordFailure:(x,A)=>E.#N(x,"failure",A),recordNeutral:(x)=>E.#N(x,"neutral"),abandon:(x)=>E.#C(x),snapshot:()=>E.#b(f)}}#A(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let _=Object.freeze({kind:"noop"});return f.#R.set(_,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:_}},recordSuccess:(_)=>f.#h(_),recordFailure:(_)=>f.#h(_),recordNeutral:(_)=>f.#h(_),abandon:(_)=>f.#C(_),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#h(f){let _=this.#R.get(f);if(_?.kind==="noop")_.settled=!0;return}#U(f){let _=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=_,this.#B(f,_),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??_;return _<T?this.#S(f,T-_):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return{eligible:!0};let E=Math.max(1,(f.probeLeaseExpiresAt??_+Mf)-_);return this.#S(f,Math.min(Mf,E))}#S(f,_){let{allowed:E,...T}=this.#O(f,_);return{eligible:!1,...T}}#u(f,_){let E=this.#_();if(f.detached)return this.#A().check();if(f.lastTouchedAt=E,this.#B(f,E),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let x=f.nextProbeAt??E;if(E<x)return this.#O(f,x-E);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return this.#D(f,E,_);let T=Math.max(1,(f.probeLeaseExpiresAt??E+Mf)-E);return this.#O(f,Math.min(Mf,T))}#Y(f,_,E){let T=Object.freeze({kind:_});return this.#R.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:_,...E!==void 0?{probeLeaseId:E}:{},settled:!1}),{allowed:!0,probe:_==="probe",token:T}}#D(f,_,E){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=_+E,f.lastTouchedAt=_;let x=this.#Y(f,"probe",T),A=f.lastFailure??{reason:"server_error"};return{...x,reason:A.reason,...A.statusCode!==void 0?{statusCode:A.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:r(f.samples)}}#O(f,_){let E=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(_)),nextProbeAt:this.#T()+Math.max(0,Math.ceil(_)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:r(f.samples)}}#N(f,_,E){let T=this.#R.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let x=T.entry;if(x.detached||T.generation!==x.generation||T.kind==="regular"&&x.state!=="closed"||T.kind==="probe"&&(x.state!=="half_open"||T.probeLeaseId!==x.probeLeaseId))return;let A=this.#_();if(x.lastTouchedAt=A,T.kind==="probe"){if(_==="failure"&&E)return this.#P(x,E,A,"reopened");return this.#W(x)}if(_==="neutral")return;if(this.#X(x,_==="failure",A),_!=="failure"||!E)return;let Y=r(x.samples),R=x.samples.length===0?0:Y/x.samples.length;if(x.samples.length>=this.#E.minSamples&&R>=this.#E.errorRateThreshold)return this.#P(x,E,A,"opened");return}#P(f,_,E,T){let x={reason:_.reason,...T_(_.statusCode)!==void 0?{statusCode:T_(_.statusCode)}:{},...x_(_.retryAfterMs)!==void 0?{retryAfterMs:x_(_.retryAfterMs)}:{}},A=x.retryAfterMs??0,Y=Math.max(f.configuredOpenDurationMs,A);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=Y,f.nextProbeAt=E+Y,f.lastFailure=x,{phase:T,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},retryAfterMs:Y,nextProbeAt:this.#T()+Y,openDurationMs:Y,sampleCount:f.samples.length,failureCount:r(f.samples)}}#W(f){let _=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#C(f){let _=this.#R.get(f);if(!_||_.settled)return!1;if(_.settled=!0,_.kind==="noop")return!0;let E=_.entry;if(!E||E.detached||_.kind!=="probe"||_.generation!==E.generation||_.probeLeaseId!==E.probeLeaseId)return!1;return E.probeLeaseId=void 0,E.probeLeaseExpiresAt=void 0,E.lastTouchedAt=this.#_(),!0}#X(f,_,E){if(this.#B(f,E),f.samples.length>=this.#E.maxWindowEntries)f.samples.shift();f.samples.push({at:E,failure:_})}#B(f,_){let E=_-this.#E.windowMs,T=0;while(T<f.samples.length&&f.samples[T].at<E)T++;if(T>0)f.samples.splice(0,T)}#b(f){if(!f.detached)this.#B(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:r(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#V(f){for(let[_,E]of this.#M)if(E.state==="closed"&&f-E.lastTouchedAt>this.#E.idleTtlMs)this.#z(_,E)}#j(){let f;for(let _ of this.#M.values())if(_.state==="closed"&&(!f||_.lastTouchedAt<f.lastTouchedAt))f=_;if(f)this.#z(f.key,f)}#z(f,_){_.detached=!0,this.#M.delete(f)}}var M_;function h_(){return M_??=new A_,M_}import{randomBytes as zE}from"node:crypto";var R_=16,S_=128,Y_=32,P_=3,U_=16,u_=96,D_=24,O_=12,N_=16,B_=4,V_=4,b_=67108864,C_=33554432,j_=12,z_=2,W_=2,X_=1,$_=15000,J_=30000;class i extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,_,E,T,x,A,Y,R){super(f==="queue_full"?`Provider request admission ${_} ${T} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${_} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=_;this.requestClass=E;this.resource=T;this.inFlight=x;this.limit=A;this.queued=Y;this.maxWaitMs=R;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function n(f){return f instanceof i||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function j(f,_,E){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return _;return Math.min(f,E)}function WE(f){let _=j(f.globalMaxInFlight,R_,R_),E=j(f.globalMaxPending,S_,S_),T=j(f.domainMaxPending,Y_,Y_),x=Math.min(j(f.ownerMaxInFlight,P_,P_),_),A=Math.min(j(f.ownerMaxPending,U_,U_),E),Y=Math.min(j(f.nonForegroundGlobalMaxPending,Math.min(u_,Math.max(1,Math.floor(E*3/4))),u_),E),R=Math.min(j(f.nonForegroundDomainMaxPending,Math.min(D_,Math.max(1,Math.floor(T*3/4))),D_),T),h=Math.min(j(f.nonForegroundOwnerMaxPending,Math.min(O_,Math.max(1,Math.floor(A*3/4))),O_),A),U=Math.min(j(f.internalGlobalMaxPending,Math.min(N_,Math.max(1,Math.floor(E/8))),N_),Y),M=Math.min(j(f.internalDomainMaxPending,Math.min(B_,Math.max(1,Math.floor(T/8))),B_),R),P=Math.min(j(f.internalOwnerMaxPending,Math.min(V_,Math.max(1,Math.floor(A/4))),V_),h),u=j(f.globalMaxPendingBytes,I,I),D=Math.min(j(f.domainMaxPendingBytes,b_,b_),u),G=Math.min(j(f.ownerMaxPendingBytes,C_,C_),u),L=Math.min(j(f.nonForegroundGlobalMaxInFlight,Math.min(j_,_),j_),_),Q=Math.min(j(f.nonForegroundOwnerMaxInFlight,Math.min(z_,x),z_),x),Pf=Math.min(j(f.internalGlobalMaxInFlight,Math.min(W_,_),W_),_),ff=j(f.internalDomainMaxInFlight,X_,X_),Uf=j(f.agingMs,J_,J_);return{globalMaxInFlight:_,globalMaxPending:E,domainMaxPending:T,ownerMaxInFlight:x,ownerMaxPending:A,nonForegroundGlobalMaxPending:Y,nonForegroundDomainMaxPending:R,nonForegroundOwnerMaxPending:h,internalGlobalMaxPending:U,internalDomainMaxPending:M,internalOwnerMaxPending:P,globalMaxPendingBytes:u,domainMaxPendingBytes:D,ownerMaxPendingBytes:G,nonForegroundGlobalMaxInFlight:L,nonForegroundOwnerMaxInFlight:Q,internalGlobalMaxInFlight:Pf,internalDomainMaxInFlight:ff,agingMs:Uf}}function k_(f,_){if(!f.trim())throw Error(`${_} must not be blank`)}function XE(f){if(k_(f.sessionId,"sessionId"),k_(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<hf||f.scope.maxConcurrent>Rf)throw Error(`maxConcurrent must be between ${hf} and ${Rf}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>I)throw Error(`maxPendingBytes must be between 1 and ${I}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>I+1)throw Error(`pendingBytes must be between 1 and ${I+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Sf)throw Error(`maxWaitMs must be 0-${Sf}`)}function kf(f,_){if(_!==void 0)return _;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function JE(f,_){return xf(f,_,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class G_{#M;#R;#f;#_=[];#T=new Map;#E=new Map;#x=0;#A=0;#h=0;#U=0;#S=0;#u=0;#Y=0;#D=0;#O=1;#N=0;#P=!1;constructor(f={}){this.#M=f.processSecret?new Uint8Array(f.processSecret):zE(32),this.#R=f.now??(()=>performance.now()),this.#f=WE(f)}admit(f){if(XE(f),this.#P)throw this.#H("closed",f,{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw kf(f.signal);let _=JE(f.scope,this.#M),E=this.#T.get(_),T=this.#E.get(f.ownerId),x=E??this.#X(f.scope.maxConcurrent),A=T??this.#B();if(this.#_.length===0&&this.#b(x,A,f.requestClass)){if(!E)this.#T.set(_,x);if(!T)this.#E.set(f.ownerId,A),this.#O++;let u=this.#j(_,f.ownerId,f.requestClass),D=this.#v(f,0);return{ready:Promise.resolve(u),getSnapshot:()=>({...D}),cancel:()=>{D={...D}}}}let Y=this.#W(f,x,A);if(Y)throw this.#H("queue_full",f,Y,this.#_.length);let R=this.#V(x,A,f.requestClass);if(f.maxWaitMs===0)throw this.#H("wait_timeout",f,R,this.#_.length);if(!E)this.#T.set(_,x);if(!T)this.#E.set(f.ownerId,A),this.#O++;let h,U,M=new Promise((u,D)=>{h=u,U=D});M.catch(()=>{return});let P={domainKey:_,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#R(),signal:f.signal,resolve:h,reject:U,settled:!1,admitted:!1};if(f.signal)P.abortListener=()=>this.#$(P,kf(f.signal)),f.signal.addEventListener("abort",P.abortListener,{once:!0});return P.timer=setTimeout(()=>this.#Q(P),f.maxWaitMs),P.timer.unref?.(),this.#_.push(P),this.#C(x,A,P),this.#J(),{ready:M,getSnapshot:()=>this.#F(P),cancel:(u)=>this.#$(P,kf(f.signal,u))}}close(){if(this.#P)return;this.#P=!0;for(let f of[...this.#_]){let _=this.#T.get(f.domainKey),E=this.#E.get(f.ownerId),T=_&&E?this.#V(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};this.#k(f,new i("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:this.#x,queued:this.#_.length,pendingBytes:this.#u,nonForegroundInFlight:this.#A,internalInFlight:this.#h,nonForegroundQueued:this.#U,internalQueued:this.#S,nonForegroundPendingBytes:this.#Y,internalPendingBytes:this.#D,domainCount:this.#T.size,ownerCount:this.#E.size,closed:this.#P}}#W(f,_,E){let T=(M,P,u)=>P>=u?{scope:M,resource:"pending_count",inFlight:P,limit:u}:void 0;if(f.requestClass==="internal"){let M=T("class",this.#S,this.#f.internalGlobalMaxPending)??T("class",E.internalQueued,this.#f.internalOwnerMaxPending)??T("class",_.internalQueued,this.#f.internalDomainMaxPending);if(M)return M}if(f.requestClass!=="foreground"){let M=T("class",this.#U,this.#f.nonForegroundGlobalMaxPending)??T("class",E.nonForegroundQueued,this.#f.nonForegroundOwnerMaxPending)??T("class",_.nonForegroundQueued,this.#f.nonForegroundDomainMaxPending);if(M)return M}let x=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",E.queued,this.#f.ownerMaxPending)??T("domain",_.queued,this.#f.domainMaxPending);if(x)return x;let A=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),Y=Math.min(A,this.#f.domainMaxPendingBytes),R=Math.min(A,this.#f.ownerMaxPendingBytes),h=(M,P)=>f.pendingBytes>P-M,U=(M)=>{if(M==="owner")return{scope:M,resource:"pending_bytes",inFlight:E.inFlight,limit:this.#f.ownerMaxInFlight};if(M==="domain")return{scope:M,resource:"pending_bytes",inFlight:_.inFlight,limit:_.maxConcurrent};return{scope:M,resource:"pending_bytes",inFlight:this.#x,limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let M=Math.max(1,Math.floor(A/8)),P=Math.max(1,Math.floor(Y/4)),u=Math.max(1,Math.floor(R/4));if(h(this.#D,M)||h(E.internalPendingBytes,u)||h(_.internalPendingBytes,P))return U("class")}if(f.requestClass!=="foreground"){let M=Math.max(1,Math.floor(A*3/4)),P=Math.max(1,Math.floor(Y*3/4)),u=Math.max(1,Math.floor(R/2));if(h(this.#Y,M)||h(E.nonForegroundPendingBytes,u)||h(_.nonForegroundPendingBytes,P))return U("class")}if(h(this.#u,A))return U("global");if(h(E.pendingBytes,R))return U("owner");if(h(_.pendingBytes,Y))return U("domain");return}#C(f,_,E){if(f.queued++,_.queued++,this.#u+=E.pendingBytes,f.pendingBytes+=E.pendingBytes,_.pendingBytes+=E.pendingBytes,E.requestClass!=="foreground")this.#U++,f.nonForegroundQueued++,_.nonForegroundQueued++,this.#Y+=E.pendingBytes,f.nonForegroundPendingBytes+=E.pendingBytes,_.nonForegroundPendingBytes+=E.pendingBytes;if(E.requestClass==="internal")this.#S++,f.internalQueued++,_.internalQueued++,this.#D+=E.pendingBytes,f.internalPendingBytes+=E.pendingBytes,_.internalPendingBytes+=E.pendingBytes}#X(f){return{maxConcurrent:f,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#B(){return{order:this.#O,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#b(f,_,E){if(this.#x>=this.#f.globalMaxInFlight)return!1;if(f.inFlight>=f.maxConcurrent)return!1;if(_.inFlight>=this.#f.ownerMaxInFlight)return!1;if(E==="foreground")return!0;if(this.#A>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(_.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=T)return!1;if(E!=="internal")return!0;return this.#h<this.#f.internalGlobalMaxInFlight&&f.internalInFlight<this.#f.internalDomainMaxInFlight}#V(f,_,E){if(_.inFlight>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:_.inFlight,limit:this.#f.ownerMaxInFlight};if(E!=="foreground"&&_.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:_.nonForegroundInFlight,limit:this.#f.nonForegroundOwnerMaxInFlight};if(f.inFlight>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent};if(E!=="foreground"){let T=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=T)return{scope:"class",resource:"stream",inFlight:f.nonForegroundInFlight,limit:T}}if(E==="internal"&&f.internalInFlight>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.internalInFlight,limit:this.#f.internalDomainMaxInFlight};if(this.#x>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};if(E!=="foreground"&&this.#A>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#A,limit:this.#f.nonForegroundGlobalMaxInFlight};if(E==="internal"&&this.#h>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#h,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent}}#j(f,_,E){let T=this.#T.get(f),x=this.#E.get(_);if(!T||!x)throw Error("Provider admission accounting state is unavailable");if(this.#x++,T.inFlight++,x.inFlight++,E!=="foreground")this.#A++,T.nonForegroundInFlight++,x.nonForegroundInFlight++;if(E==="internal")this.#h++,T.internalInFlight++,x.internalInFlight++;let A=!1;return{release:()=>{if(A)return;A=!0,this.#z(f,_,E)}}}#z(f,_,E){let T=this.#T.get(f),x=this.#E.get(_);if(this.#x=Math.max(0,this.#x-1),T)T.inFlight=Math.max(0,T.inFlight-1);if(x)x.inFlight=Math.max(0,x.inFlight-1);if(E!=="foreground"){if(this.#A=Math.max(0,this.#A-1),T)T.nonForegroundInFlight=Math.max(0,T.nonForegroundInFlight-1);if(x)x.nonForegroundInFlight=Math.max(0,x.nonForegroundInFlight-1)}if(E==="internal"){if(this.#h=Math.max(0,this.#h-1),T)T.internalInFlight=Math.max(0,T.internalInFlight-1);if(x)x.internalInFlight=Math.max(0,x.internalInFlight-1)}this.#L(f,_),this.#J()}#J(){if(this.#P)return;while(this.#_.length>0){let f=this.#R(),_=new Map;for(let[R,h]of this.#_.entries()){let U=this.#T.get(h.domainKey),M=this.#E.get(h.ownerId);if(U===void 0||M===void 0||!this.#b(U,M,h.requestClass))continue;let P=this.#Z(h,f),u=_.get(h.ownerId);if(!u||P<u.rank||P===u.rank&&R<u.index)_.set(h.ownerId,{pending:h,rank:P,index:R})}let E=[..._.values()].filter(({pending:R})=>{let h=this.#T.get(R.domainKey),U=this.#E.get(R.ownerId);return h!==void 0&&U!==void 0&&this.#b(h,U,R.requestClass)}).map(({pending:R,rank:h})=>({pending:R,rank:h,order:this.#E.get(R.ownerId).order}));if(E.length===0)return;let T=Math.min(...E.map((R)=>R.rank)),x=E.filter((R)=>R.rank===T),Y=x.filter((R)=>R.order>this.#N).sort((R,h)=>R.order-h.order)[0]??x.sort((R,h)=>R.order-h.order)[0];this.#c(Y.pending,Y.order)}}#Z(f,_){let E=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,_-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,E-T)}#c(f,_){if(!this.#G(f,!1))return;f.settled=!0,f.admitted=!0,this.#N=_;let E=this.#j(f.domainKey,f.ownerId,f.requestClass);f.permit=E,f.resolve(E)}#Q(f){let _=this.#T.get(f.domainKey),E=this.#E.get(f.ownerId),T=_&&E?this.#V(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};this.#k(f,new i("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#$(f,_){this.#k(f,_)}#k(f,_){if(!this.#G(f))return;f.settled=!0,f.reject(_),this.#J()}#G(f,_=!0){if(f.settled||f.admitted)return!1;let E=this.#_.indexOf(f);if(E<0)return!1;this.#_.splice(E,1);let T=this.#T.get(f.domainKey),x=this.#E.get(f.ownerId);if(T&&x)this.#K(T,x,f);if(this.#I(f),_)this.#L(f.domainKey,f.ownerId);return!0}#K(f,_,E){if(f.queued=Math.max(0,f.queued-1),_.queued=Math.max(0,_.queued-1),this.#u=Math.max(0,this.#u-E.pendingBytes),f.pendingBytes=Math.max(0,f.pendingBytes-E.pendingBytes),_.pendingBytes=Math.max(0,_.pendingBytes-E.pendingBytes),E.requestClass!=="foreground")this.#U=Math.max(0,this.#U-1),f.nonForegroundQueued=Math.max(0,f.nonForegroundQueued-1),_.nonForegroundQueued=Math.max(0,_.nonForegroundQueued-1),this.#Y=Math.max(0,this.#Y-E.pendingBytes),f.nonForegroundPendingBytes=Math.max(0,f.nonForegroundPendingBytes-E.pendingBytes),_.nonForegroundPendingBytes=Math.max(0,_.nonForegroundPendingBytes-E.pendingBytes);if(E.requestClass==="internal")this.#S=Math.max(0,this.#S-1),f.internalQueued=Math.max(0,f.internalQueued-1),_.internalQueued=Math.max(0,_.internalQueued-1),this.#D=Math.max(0,this.#D-E.pendingBytes),f.internalPendingBytes=Math.max(0,f.internalPendingBytes-E.pendingBytes),_.internalPendingBytes=Math.max(0,_.internalPendingBytes-E.pendingBytes)}#I(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#L(f,_){let E=this.#T.get(f);if(E&&E.inFlight===0&&E.queued===0)this.#T.delete(f);let T=this.#E.get(_);if(T&&T.inFlight===0&&T.queued===0)this.#E.delete(_)}#F(f){let _=Math.max(0,Math.floor(this.#R()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#x,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs};let E=this.#T.get(f.domainKey),T=this.#E.get(f.ownerId),x=E&&T?this.#V(E,T,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#x,limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:x.resource,scope:x.scope,reason:"capacity",queuePosition:this.#t(f,x.scope),queueDepth:this.#_.length,inFlight:x.inFlight,limit:x.limit,waitMs:_,maxWaitMs:f.maxWaitMs}}#v(f,_){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#x,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs}}#t(f,_){let E=this.#_.filter((T)=>{switch(_){case"owner":return T.ownerId===f.ownerId;case"domain":return T.domainKey===f.domainKey;case"class":return T.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,E.indexOf(f)+1)}#H(f,_,E,T){return new i(f,E.scope,_.requestClass,E.resource,E.inFlight,E.limit,T,_.maxWaitMs)}}var H_;function L_(){return H_??=new G_,H_}function Z_(f,_={}){let E=_.maxBytes??134217728,T=_.maxNodes??1e5;if(!Number.isSafeInteger(E)||E<=0||E>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(T)||T<=0)throw Error("maxNodes must be a positive safe integer");let x=new WeakSet,A=0,Y=0,R=!1,h=(M)=>{if(R||M<=0)return;if(!Number.isSafeInteger(M)||M>E-A){A=E+1,R=!0;return}A+=M},U=(M)=>{if(R)return;if(Y+=1,Y>T){h(E+1);return}if(M===null){h(4);return}switch(typeof M){case"string":h(Buffer.byteLength(M,"utf8"));return;case"number":case"bigint":h(8);return;case"boolean":h(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(x.has(M))return;if(x.add(M),ArrayBuffer.isView(M)){h(32+M.byteLength);return}if(M instanceof ArrayBuffer){h(32+M.byteLength);return}if(M instanceof Date){h(40);return}if(M instanceof RegExp){h(32+Buffer.byteLength(M.source,"utf8"));return}if(M instanceof Map){h(32);for(let[P,u]of M)if(U(P),U(u),R)return;return}if(M instanceof Set){h(32);for(let P of M)if(U(P),R)return;return}if(M instanceof WeakMap||M instanceof WeakSet){h(32);return}if(Array.isArray(M)){h(16);for(let P of M)if(U(P),R)return;return}h(32);for(let P of Reflect.ownKeys(M)){if(typeof P!=="string")continue;let u=Object.getOwnPropertyDescriptor(M,P);if(!u?.enumerable||!("value"in u))continue;if(h(8+Buffer.byteLength(P,"utf8")),U(u.value),R)return}};return U(f),A}function c_(f){return Z_([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:I})}var Q_=new WeakSet;class s extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,_){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=_;this.name="ProviderRecoveryBudgetExceededError"}}var kE=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],HE=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],$E=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function K_(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function GE(f){let _=K_(f);return HE.some((E)=>_.includes(E))}function Lf(f){if(f!==null&&typeof f==="object")Q_.add(f)}function KT(f){return f!==null&&typeof f==="object"&&Q_.has(f)}function LE(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function ZE(f){if(f===null||typeof f!=="object")return;let _=f;for(let E of["status","statusCode"]){let T=_[E];if(typeof T==="number"&&Number.isInteger(T))return T}return}function cE(f){let _=f.match(/^(?:error:\s*)?(\d{3})\b/),E=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(_?.[1]??E?.[1]);return Number.isInteger(T)?T:void 0}function l(f,_){let E=K_(f),T=LE(f);if(T==="STREAM_IDLE_TIMEOUT"||T==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||E.includes("request aborted")||E==="aborted")return{retryable:!1};if(kE.some((A)=>E.includes(A))||GE(f))return{retryable:!1};if(_?.shouldRetry==="false")return{retryable:!1,statusCode:_.statusCode};let x=_?.statusCode??ZE(f)??cE(E);if(_?.shouldRetry==="true")return{retryable:!0,reason:x===429?"rate_limit":x===408||x===409?"timeout":"server_error",statusCode:x};if(x===429)return{retryable:!0,reason:"rate_limit",statusCode:x};if(x===408||x===409)return{retryable:!0,reason:"timeout",statusCode:x};if(x!==void 0&&x>=500&&x<=599)return{retryable:!0,reason:"server_error",statusCode:x};if(T==="PROVIDER_STREAM_CLOSED"||E.includes("stream closed before completion")||E.includes("ended without")||E.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:x};if($E.some((A)=>E.includes(A)))return{retryable:!0,reason:"transport",statusCode:x};if(E.includes("timeout")||E.includes("timed out")||E.includes("temporarily unavailable")||E.includes("upstream_error")||E.includes("overloaded")||E.includes("rate limit")||E.includes("too many requests")||E.includes("service unavailable")||E.includes("server error")||E.includes("internal error")||E.includes("please retry")||E.includes("try your request again"))return{retryable:!0,reason:E.includes("rate")||E.includes("too many")?"rate_limit":E.includes("timeout")||E.includes("timed out")?"timeout":"server_error",statusCode:x};return{retryable:!1,statusCode:x}}function Zf(f,_){if(!f)return;if(f.retryAfterMs!==void 0){let x=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(x))return Math.max(0,x)}if(f.retryAfter===void 0)return;let E=Number.parseFloat(f.retryAfter);if(Number.isFinite(E))return Math.max(0,E*1000);let T=Date.parse(f.retryAfter);return Number.isFinite(T)?Math.max(0,T-_):void 0}function I_(f,_,E={}){let T=E.now??Date.now(),x=E.maxDelayMs??60000,A=Zf(_,T);if(A!==void 0)return Math.min(Math.ceil(A),x);let Y=Math.max(0,f-1),R=E.maxExponentialDelayMs??8000,h=Math.min(500*2**Y,R),U=Math.max(0,Math.min(1,E.random??Math.random())),M=h*(0.75+U*0.25);return Math.min(Math.round(M),x)}function t_(f,_){let E=f.onPayload;f.onPayload=async(T,x)=>{let A=E?await E(T,x):T;return _(A===void 0?T:A,x)}}function QE(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function KE(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function IE(f,_,E,T){let x=T?void 0:QE(E);if(!x){if(_.api==="anthropic-messages")f.thinkingEnabled=!1;if(_.api==="google-generative-ai"||_.api==="google-vertex")f.thinking={enabled:!1};return}switch(_.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=x;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:KE(x)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=x;break;default:f.reasoningEffort=x}}function FE(f,_,E){if(!E)return;switch(_){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:E};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:E}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:E};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function vE(f,_,E){let T=E.serviceTier;if(!T)return;if(_.api==="openai-responses"||_.api==="openai-codex-responses"||_.api==="azure-openai-responses"){f.serviceTier=T;return}if(_.api!=="openai-completions"&&!(_.api==="anthropic-messages"&&T==="fast"))return;t_(f,(x)=>{if(!x||typeof x!=="object"||Array.isArray(x))return x;return _.api==="anthropic-messages"?{...x,speed:"fast"}:{...x,service_tier:T}})}function tE(f,_,E){let T=E.responseVerbosity;if(!T)return;if(v_(_,T),_.api==="openai-codex-responses"){f.textVerbosity=T;return}t_(f,(x)=>{if(!x||typeof x!=="object"||Array.isArray(x))return x;if(_.api==="openai-completions")return{...x,verbosity:T};let A="text"in x&&x.text&&typeof x.text==="object"&&!Array.isArray(x.text)?x.text:{};return{...x,text:{...A,verbosity:T}}})}function w_(f,_,E,T,x=!1){let A={apiKey:f.apiKey,headers:f.customHeaders,signal:E,temperature:T?.temperature??f.temperature??0,maxTokens:T?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:f.enablePromptCaching?"short":"none"};if(IE(A,_,f,x),FE(A,_.api,T?.toolChoice?.toolName),vE(A,_,f),tE(A,_,f),_.api==="azure-openai-responses")A.azureBaseUrl=f.baseUrl,A.azureApiVersion=f.apiVersion,A.azureDeploymentName=_.id;return A}function F_(f,_){let E=_.get("x-should-retry");return{statusCode:f,..._.get("retry-after")!==null?{retryAfter:_.get("retry-after")??void 0}:{},..._.get("retry-after-ms")!==null?{retryAfterMs:_.get("retry-after-ms")??void 0}:{},...E==="true"||E==="false"?{shouldRetry:E}:{}}}var wE=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function p_(f,_,E){let T=f.onResponse;if(f.onResponse=async(A,Y)=>{let R=new Headers(A.headers);E(F_(A.status,R)),await T?.(A,Y)},!wE.has(_.api)||typeof globalThis.fetch!=="function")return;let x=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(A,Y)=>{let R=await x(A,Y);return E(F_(R.status,R.headers)),R}}function q_(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Yf=300000,pE=30000;class m_ extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(f){super(`Provider stream idle timeout after ${f}ms without an event`);this.timeoutMs=f;this.name="StreamIdleTimeoutError"}}class s_ extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function cf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function qE(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Yf}function mE(f,_){if(_===0)return;let E=_!==void 0&&_>0?_:pE;return Math.max(1,Math.min(E,Math.floor(f/2)))}function sE(f,_,E){if(E?.aborted)return Promise.reject(cf(E));return new Promise((T,x)=>{let A=!1,Y=()=>{clearTimeout(M),E?.removeEventListener("abort",U)},R=(P)=>{if(A)return;A=!0,Y(),T(P)},h=(P)=>{if(A)return;A=!0,Y(),x(P instanceof Error?P:Error(String(P)))},U=()=>{if(E)h(cf(E))},M=setTimeout(()=>R({kind:"timer"}),Math.max(0,_));if(E?.addEventListener("abort",U,{once:!0}),E?.aborted){U();return}f.then((P)=>R({kind:"next",result:P}),h)})}async function*lE(f,_,E){let T=qE(_),x=mE(T,_.stallWarningMs);if(_.signal?.aborted)throw cf(_.signal);let A=Date.now(),Y=Promise.resolve().then(()=>f.next()),R;for(;;){let U=await sE(Y,(R?T:x??T)-(Date.now()-A),_.signal);if(U.kind==="next"){if(R)yield{...R,phase:"recovered",durationMs:Math.max(R.durationMs,Date.now()-A)};return U.result}if(!R&&x!==void 0){E.stallCount++,R={phase:"detected",stallCount:E.stallCount,durationMs:x,warningAfterMs:x,timeoutMs:T,outputStarted:E.outputStarted},yield R;continue}let M=new m_(T);throw _.abort?.(M),M}}async function*l_(f,_,E,T,x={}){let Y=f.stream(_,E,T)[Symbol.asyncIterator](),R=0,h=!1,U={stallCount:0,outputStarted:!1};try{while(!0){let M=lE(Y,x,U),P=await M.next();while(!P.done)yield{providerStall:P.value},P=await M.next();let u=P.value;if(u.done)throw new s_;let D=u.value;switch(D.type){case"text_delta":U.outputStarted=!0,yield{content:D.delta};break;case"thinking_delta":U.outputStarted=!0,yield{reasoningContent:D.delta};break;case"toolcall_end":U.outputStarted=!0,yield{toolCalls:[{index:R++,id:D.toolCall.id,type:"function",function:{name:D.toolCall.name,arguments:JSON.stringify(D.toolCall.arguments)}}]};break;case"done":h=!0,yield{finishReason:D.reason,usage:q_(D.message.usage)};return;case"error":throw Error(D.error.errorMessage??`Request ${D.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!h)Promise.resolve(Y.return?.()).catch(()=>{return})}}var a_=q("Chat"),aE=1;function yE(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((_)=>_.type==="image_url"))}function gE(f,_){let E=l(f,_);if(!E.retryable||!E.reason)return;let T=E.statusCode;switch(E.reason){case"rate_limit":if(T!==429)return;break;case"server_error":if(T===void 0||T<500||T>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let x=Zf(_,Date.now());return{reason:E.reason,...T!==void 0?{statusCode:T}:{},...x!==void 0?{retryAfterMs:x}:{}}}function oE(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class If{config;models;model;admissionFallbackOwnerId=`pi-service-${process.pid}-${aE++}`;constructor(f){let _=jf(f);this.config={...f,maxContextTokens:_.model.contextWindow,maxOutputTokens:f.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,a_.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,_,E,T){let x="",A="",Y=[],R,h;for await(let U of this.streamChat(f,_,E,T)){x+=U.content??"",A+=U.reasoningContent??"";for(let M of U.toolCalls??[])if(M.id&&M.type==="function"&&M.function?.name)Y.push(M);R=U.usage??R,h=U.finishReason??h}return{content:x,...A?{reasoningContent:A}:{},...Y.length>0?{toolCalls:Y}:{},usage:R,finishReason:h}}async*streamChat(f,_,E,T){let x=T?.toolChoice?.toolName;if(x&&!_?.some((S)=>S.name===x))throw Error(`Required tool is unavailable: ${x}`);let A=df(f);if(A.some((S)=>yE(S))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let Y=Boolean(x)||rf(A),R=await of(A,this.model,_,E,x),h=c_({messages:A,context:R,tools:_,requestOptions:T}),U=T?.providerRecovery;if(U&&!g_(U.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let M=U?.mode==="bounded_foreground"&&U.budgetMs>0?{budgetMs:U.budgetMs,startedAt:void 0}:void 0,P=M?"bounded_foreground":"standard",u=this.config.maxRetries??2,D=this.config.maxRetries??(M?y_:2),G=M!==void 0&&this.config.maxRetries===void 0,L=0,Q,Pf=this.config.providerCircuitRegistry??h_(),ff=this.config.providerCircuitBreakerOpenMs??zf,Uf=Math.max(Af,Math.min(this.config.streamIdleTimeout??Yf,Xf)),o_=this.config.providerRequestAdmissionScheduler??L_(),d_=this.config.providerRequestConcurrency??Hf,Ff=this.config.providerRequestAdmissionMs??$f,r_=this.config.providerRequestPendingBytes??Gf,uf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},e_=(S)=>Pf.get({provider:S.provider,api:S.api,baseUrl:S.baseUrl??this.config.baseUrl??"",model:S.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,openDurationMs:ff,probeLeaseMs:Uf}),i_=(S)=>({provider:S.provider,api:S.api,baseUrl:S.baseUrl??this.config.baseUrl??"",model:S.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,maxConcurrent:d_,maxPendingBytes:r_}),C=(S=Date.now())=>{if(!M)return;let O=M.startedAt===void 0?0:Math.min(M.budgetMs,Math.max(0,S-M.startedAt));return{recoveryBudgetMs:M.budgetMs,recoveryElapsedMs:O,recoveryRemainingMs:Math.max(0,M.budgetMs-O)}},F=()=>({mode:P,...C()??{}}),vf=()=>{if(M&&M.startedAt===void 0)M.startedAt=Date.now()},v=()=>{let S=C();return new s(M?.budgetMs??0,S?.recoveryElapsedMs??0)},a=()=>!G||L<D+1,Df=(S,O)=>{let{state:W,...V}=O;return{phase:S,...V,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}},tf=(S)=>({phase:"rejected",requestClass:S.requestClass,resource:S.resource,scope:S.scope,reason:S.reason,queuePosition:0,queueDepth:Math.max(0,S.queued),inFlight:Math.max(0,S.inFlight),limit:Math.max(0,S.limit),waitMs:S.reason==="wait_timeout"?S.maxWaitMs:0,maxWaitMs:S.maxWaitMs,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),n_=async function*(S){let O=C()?.recoveryRemainingMs,W=O!==void 0&&M?.startedAt!==void 0?Math.min(Ff,O):Ff,V;try{V=o_.admit({scope:i_(S),sessionId:uf.sessionId,ownerId:uf.ownerId,requestClass:uf.requestClass,maxWaitMs:W,pendingBytes:h,signal:E})}catch(N){if(n(N)){if(N.reason==="wait_timeout"&&M?.startedAt!==void 0&&(C()?.recoveryRemainingMs??0)<=0)throw v();yield{providerAdmission:tf(N)}}throw N}let c=V.getSnapshot();if(c.state==="admitted")return await V.ready;yield{providerAdmission:Df("queued",c)};let K=V.ready.then((N)=>({kind:"ready",permit:N}),(N)=>({kind:"error",error:N}));while(!0){let N=V.getSnapshot(),J=Math.max(1,Math.min($_,Math.max(1,W-N.waitMs))),k,X=new Promise((t)=>{k=setTimeout(()=>t({kind:"heartbeat"}),J),k.unref?.()}),H=await Promise.race([K,X]);if(k)clearTimeout(k);if(H.kind==="heartbeat"){yield{providerAdmission:Df("queued",V.getSnapshot())};continue}if(H.kind==="error"){if(n(H.error)){if(H.error.reason==="wait_timeout"&&M?.startedAt!==void 0&&(C()?.recoveryRemainingMs??0)<=0)throw v();yield{providerAdmission:tf(H.error)}}throw H.error}return yield{providerAdmission:Df("admitted",V.getSnapshot())},H.permit}},fE=(S)=>{if(!a())throw v();if(G)L++;Q=void 0;let O=new AbortController,W=E?yf(E,O.signal):O.signal,V;if(M?.startedAt!==void 0){let N=C()?.recoveryRemainingMs??0;if(N<=0)throw v();let J=new s(M.budgetMs,M.budgetMs);V=setTimeout(()=>O.abort(J),N),V.unref?.()}let c=w_(this.config,S,W,T,Y);p_(c,S,(N)=>{Q=N});let K=l_(this.models,S,R,c,{idleTimeoutMs:this.config.streamIdleTimeout??Yf,signal:W,abort:(N)=>O.abort(N)});return async function*(){try{yield*K}finally{if(V)clearTimeout(V)}}()},wf=this,p=(S)=>({phase:S.phase,reason:S.reason,...S.statusCode!==void 0?{statusCode:S.statusCode}:{},...S.retryAfterMs!==void 0?{retryAfterMs:S.retryAfterMs}:{},...S.nextProbeAt!==void 0?{nextProbeAt:S.nextProbeAt}:{},openDurationMs:S.openDurationMs,sampleCount:S.sampleCount,failureCount:S.failureCount,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),pf=(S,O)=>({phase:S,reason:O.reason,...O.statusCode!==void 0?{statusCode:O.statusCode}:{},retryAfterMs:O.retryAfterMs,...O.nextProbeAt!==void 0?{nextProbeAt:O.nextProbeAt}:{},openDurationMs:O.openDurationMs,sampleCount:O.sampleCount,failureCount:O.failureCount,...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),_E=(S)=>({phase:"probe",reason:S.reason??"server_error",...S.statusCode!==void 0?{statusCode:S.statusCode}:{},openDurationMs:S.openDurationMs??ff,...S.sampleCount!==void 0?{sampleCount:S.sampleCount}:{},...S.failureCount!==void 0?{failureCount:S.failureCount}:{},...C()?{recoveryRemainingMs:C()?.recoveryRemainingMs}:{}}),Of=(S,O,W)=>({providerRetry:{phase:"exhausted",attempt:S,maxRetries:D,reason:O,...W!==void 0?{statusCode:W}:{},...F(),exhaustedBy:"recovery_budget"}}),qf=async function*(S,O,W,V){let c,K=!1,N,J,k=e_(S);for(let X=0;X<=W;X++){if(!a())break;let H,t;while(!H){let B=k.preflight();while(!B.eligible){if(N=B.reason,J=B.statusCode,!M||!V){let Z=pf("rejected",B);throw yield{providerCircuit:Z},new e(Z)}vf();let b=C()?.recoveryRemainingMs??0;if(b<=0){let Z=v();throw yield Of(G?Math.max(0,L-1):X,B.reason,B.statusCode),Z}yield{providerCircuit:pf("waiting",B)};let w=Math.min(Math.max(1,B.retryAfterMs),Qf,b);if(await d(w,E,{throwOnAbort:!0}),(C()?.recoveryRemainingMs??0)<=0){let Z=v();throw yield Of(G?Math.max(0,L-1):X,B.reason,B.statusCode),Z}B=k.preflight()}try{t=yield*n_(S)}catch($){if($ instanceof s)yield Of(G?Math.max(0,L-1):X,N??"timeout",J);throw $}let z=k.check();if(z.allowed)H=z;else t.release(),t=void 0}let y=H.token;if(H.probe)yield{providerCircuit:_E(H)};try{let B=!1,z=!1;for await(let $ of fE(S)){if($.providerStall){yield $;continue}let b=G?L-1:X;if(b>0&&N&&!B)B=!0,yield{providerRetry:{phase:"recovered",attempt:b,maxRetries:D,reason:N,...J!==void 0?{statusCode:J}:{},...F()}};if(!z){z=!0;let w=k.recordSuccess(y);if(w)yield{providerCircuit:p(w)}}K=!0,O(),yield $}if(!z){let $=k.recordSuccess(y);if($)yield{providerCircuit:p($)}}return}catch(B){if(t?.release(),c=B,wf.logIdleTimeout(B,K,S),await wf.handleAbort(E),B instanceof s){if(K)throw Lf(B),B;throw yield{providerRetry:{phase:"exhausted",attempt:G?Math.max(0,L-1):X,maxRetries:D,reason:N??"timeout",...J!==void 0?{statusCode:J}:{},...F(),exhaustedBy:"recovery_budget"}},B}let z=l(B,Q);if(K)throw Lf(B),B;let $=gE(B,Q),b=$?k.recordFailure(y,$):Q&&!oE(B)?k.recordNeutral(y):void 0;if(b)yield{providerCircuit:p(b)};if(!z.retryable||!z.reason){if(X>0&&N)yield{providerRetry:{phase:"exhausted",attempt:G?Math.max(0,L-1):X,maxRetries:D,reason:N,...J!==void 0?{statusCode:J}:{},...F()}};throw B}N=z.reason,J=z.statusCode;let w=X<W&&a();if(b&&b.phase!=="closed"&&w&&(!M||!V)){let Z={...p(b),phase:"rejected"};throw yield{providerCircuit:Z},new e(Z)}if(w){vf();let Z=G?L:X+1,TE=I_(Z,Q,M?{maxDelayMs:Kf,maxExponentialDelayMs:Kf}:void 0),sf=b&&b.phase!=="closed"?b.retryAfterMs??0:0;if(M&&sf>0&&b)yield{providerCircuit:{...p(b),phase:"waiting"}};let xE=C(),Bf=Math.max(TE,sf),g=M?Math.min(Bf,xE?.recoveryRemainingMs??Bf):Bf,Ef={attempt:Z,maxRetries:D,reason:z.reason,...z.statusCode!==void 0?{statusCode:z.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Ef,delayMs:g,nextRetryAt:Date.now()+g,...F()}},M){let o=g;while(o>0){let lf=Math.min(o,Qf);if(await d(lf,E,{throwOnAbort:!0}),o-=lf,(C()?.recoveryRemainingMs??0)<=0){let Tf=v();throw yield{providerRetry:{phase:"exhausted",...Ef,...F(),exhaustedBy:"recovery_budget"}},Tf}if(o>0){if(b&&b.phase!=="closed"&&b.nextProbeAt!==void 0){let Tf=Math.max(0,b.nextProbeAt-Date.now());if(Tf>0)yield{providerCircuit:{...p(b),phase:"waiting",retryAfterMs:Tf}}}yield{providerRetry:{phase:"waiting",...Ef,delayMs:g,nextRetryAt:Date.now()+o,...F()}}}}}else await d(g,E,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Ef,...F()}}}else yield{providerRetry:{phase:"exhausted",attempt:G?Math.max(0,L-1):X,maxRetries:D,reason:z.reason,...z.statusCode!==void 0?{statusCode:z.statusCode}:{},...F(),...M&&(V||!a())?{exhaustedBy:"attempt_limit"}:{}}}}finally{k.abandon(y),t?.release()}}throw c},Nf,mf=!1,_f=this.config.fallbackModels??[],EE=M&&_f.length>0?Math.min(u,D):D;try{for await(let S of qf(this.model,()=>{mf=!0},EE,_f.length===0))yield S;return}catch(S){if(Nf=S,mf||!n(S)&&!Jf(S)&&!l(S,Q).retryable)throw S}for(let[S,O]of _f.entries()){if(!a())break;yield{modelFallback:!0};let W=!1;try{let V=f_(this.config,O),c=S===_f.length-1,K=M&&!c?Math.min(u,D):D;for await(let N of qf(V,()=>{W=!0},K,c))yield N;return}catch(V){if(Nf=V,W||!n(V)&&!Jf(V)&&!l(V,Q).retryable)throw V}}throw Nf}async handleAbort(f){if(f?.aborted)await d(0,f,{throwOnAbort:!0})}logIdleTimeout(f,_,E){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;a_.warn("[PiAIChatService] Provider stream idle timeout",{provider:E.provider,model:E.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:_})}getConfig(){return{...this.config}}updateConfig(f){let _={...this.config,...f},E=jf(_);this.config={..._,maxContextTokens:E.model.contextWindow,maxOutputTokens:_.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model}}var dE=q("Service");async function Tx(f){let _=f;if(_.provider){let E=af(_.provider);if(Object.keys(E).length>0)_={..._,customHeaders:{...E,..._.customHeaders}},dE.debug(`Injected ${_.provider} specific headers:`,Object.keys(E))}return rE(_)}function rE(f){return new If(f)}
|
|
5
|
-
export{nE as
|
|
5
|
+
export{nE as Kd,ET as Ld,yf as Md,n as Nd,Z_ as Od,GE as Pd,KT as Qd,If as Rd,Tx as Sd};
|