blade-code 0.10.126 → 0.10.128
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-0ktte40x.js +185 -0
- package/dist/{chunk-85bamng3.js → chunk-10w2pj3r.js} +1 -1
- package/dist/{chunk-1b2dkwpv.js → chunk-12hdakw4.js} +2 -2
- package/dist/chunk-1acb8fwq.js +120 -0
- package/dist/{chunk-1s7gj546.js → chunk-1aw643j2.js} +2 -2
- package/dist/{chunk-6kwg4hcv.js → chunk-1xg7qx35.js} +1 -1
- package/dist/chunk-3pwqqk7w.js +1 -0
- package/dist/chunk-3q7g9206.js +1 -0
- package/dist/{chunk-a4angs22.js → chunk-41byj2h8.js} +2 -2
- package/dist/{chunk-8zftskf2.js → chunk-562w5zc6.js} +1 -1
- package/dist/chunk-5x56nka1.js +1 -0
- package/dist/{chunk-c39pbp9r.js → chunk-60he05xs.js} +1 -1
- package/dist/{chunk-1g0d9yw0.js → chunk-6m4sqwj0.js} +2 -2
- package/dist/{chunk-0pnbvv81.js → chunk-6v2hhgka.js} +2 -2
- package/dist/chunk-7hajkvde.js +1 -0
- package/dist/{chunk-wcsgnadz.js → chunk-85jv1sr7.js} +1 -1
- package/dist/{chunk-adkpwx6c.js → chunk-8hd4vd20.js} +1 -1
- package/dist/{chunk-cw2b3383.js → chunk-96w8ay2h.js} +1 -1
- package/dist/{chunk-z95yvxga.js → chunk-9hnfz9bx.js} +1 -1
- package/dist/{chunk-ytrj8hcr.js → chunk-9n90djh7.js} +1 -1
- package/dist/chunk-9wptwfmg.js +1 -0
- package/dist/{chunk-g6gp6m3m.js → chunk-a7gghhvn.js} +20 -20
- package/dist/{chunk-fstn3r6d.js → chunk-ap01rwg0.js} +1 -1
- package/dist/{chunk-sv833k2e.js → chunk-atema2rc.js} +2 -2
- package/dist/{chunk-nz2cgjww.js → chunk-b408cqg1.js} +2 -2
- package/dist/{chunk-7n7swtwg.js → chunk-c47db31j.js} +2 -2
- package/dist/chunk-cm8fy1jn.js +1 -0
- package/dist/chunk-dp4r5bay.js +1 -0
- package/dist/chunk-dtxza4zh.js +1 -0
- package/dist/{chunk-0zzh482s.js → chunk-ektgnqmh.js} +1 -1
- package/dist/{chunk-qkdbfqfd.js → chunk-fa0pyv9k.js} +1 -1
- package/dist/{chunk-xvn80fge.js → chunk-fgbqm2jh.js} +1 -1
- package/dist/{chunk-w7n73ag8.js → chunk-gxwkwkhp.js} +1 -1
- package/dist/chunk-hd7bxzvy.js +1 -0
- package/dist/chunk-hks48s9k.js +1 -0
- package/dist/chunk-hmncnf7p.js +1 -0
- package/dist/chunk-j6fj679p.js +10 -0
- package/dist/{chunk-t7ymt22d.js → chunk-jxc67ydz.js} +2 -2
- package/dist/{chunk-23vx90g5.js → chunk-jy0vfp8a.js} +1 -1
- package/dist/chunk-m8czdpyg.js +1 -0
- package/dist/{chunk-dekgf9sw.js → chunk-mkvvyq49.js} +2 -2
- package/dist/{chunk-hmwz31tc.js → chunk-mm05y2c5.js} +1 -1
- package/dist/{chunk-xdvn6yrd.js → chunk-mvgmsjwq.js} +1 -1
- package/dist/{chunk-dh03cybw.js → chunk-n4q6fvqe.js} +2 -2
- package/dist/{chunk-z1c87ay4.js → chunk-n8w1jxsh.js} +1 -1
- package/dist/{chunk-y94239bb.js → chunk-nx8xb7dm.js} +1 -1
- package/dist/{chunk-fnsq6hk0.js → chunk-p2rxrxct.js} +3 -3
- package/dist/{chunk-g7k5n1mn.js → chunk-p5awnndq.js} +1 -1
- package/dist/{chunk-8ne1ce9c.js → chunk-p7349xay.js} +1 -1
- package/dist/{chunk-zm2bbagg.js → chunk-pq6g92cz.js} +1 -1
- package/dist/{chunk-z1zr4wts.js → chunk-q3y3s16v.js} +1 -1
- package/dist/{chunk-g2jx4y8f.js → chunk-qm632an7.js} +1 -1
- package/dist/{chunk-68sf54n4.js → chunk-r04vwtej.js} +2 -2
- package/dist/chunk-rz2wc93t.js +171 -0
- package/dist/{chunk-8qp8v96d.js → chunk-s7axaw78.js} +1 -1
- package/dist/chunk-s7peh6kf.js +2 -0
- package/dist/{chunk-2xezz3nt.js → chunk-skv2gb99.js} +1 -1
- package/dist/{chunk-s6562rsq.js → chunk-ted1hyvb.js} +1 -1
- package/dist/chunk-v4nqv1pr.js +1708 -0
- package/dist/{chunk-9hm3hy8d.js → chunk-ws6gtw33.js} +1 -1
- package/dist/chunk-wtmhqy5s.js +1 -0
- package/dist/{chunk-b16dacc5.js → chunk-xejvs1fk.js} +1 -1
- package/dist/chunk-xnstybjm.js +2 -0
- package/dist/chunk-xpdtg9h9.js +23 -0
- package/dist/{chunk-ye4wyq1k.js → chunk-xshrj2nd.js} +1 -1
- package/dist/{chunk-hbafhk9y.js → chunk-xzfc1s6k.js} +1 -1
- package/dist/{chunk-cw990f6x.js → chunk-y93nqyqd.js} +2 -2
- package/dist/{chunk-pezzyyyk.js → chunk-yqpej45c.js} +2 -2
- package/dist/chunk-yqqeh12b.js +2 -0
- package/dist/{chunk-1zqaq7vw.js → chunk-yysqw1cq.js} +1 -1
- package/dist/chunk-z2jwm4s8.js +1 -0
- package/dist/{chunk-q265drks.js → chunk-z3hpstky.js} +1 -1
- package/dist/{chunk-2t6b962t.js → chunk-zfyg3888.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-24teyrer.js +0 -1703
- package/dist/chunk-2j2mnzdg.js +0 -2
- package/dist/chunk-4fvszzr7.js +0 -1
- package/dist/chunk-54f7t2g3.js +0 -1
- package/dist/chunk-5yzs98v1.js +0 -1
- package/dist/chunk-9rj1may5.js +0 -1
- package/dist/chunk-9tzjwffn.js +0 -1
- package/dist/chunk-9xzw649r.js +0 -2
- package/dist/chunk-a61wskp5.js +0 -1
- package/dist/chunk-ahfe3knk.js +0 -23
- package/dist/chunk-ay1w6zhg.js +0 -118
- package/dist/chunk-cd5krb6m.js +0 -1
- package/dist/chunk-epn7zsj1.js +0 -1
- package/dist/chunk-g2q3p5bd.js +0 -1
- package/dist/chunk-k3pe267k.js +0 -171
- package/dist/chunk-mzxwhhnc.js +0 -1
- package/dist/chunk-n3hf4p1c.js +0 -1
- package/dist/chunk-rmazdhb2.js +0 -1
- package/dist/chunk-tqjrt537.js +0 -1
- package/dist/chunk-vcfk6q9q.js +0 -1
- package/dist/chunk-xnbzrh8b.js +0 -140
- package/dist/chunk-ybc41bb2.js +0 -10
- package/dist/chunk-z4rx2bgb.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as L3,f as w3}from"./chunk-8zftskf2.js";import{i as BX,j as AX,k as bX}from"./chunk-8ne1ce9c.js";import{v as P9,w as M9,x as T8}from"./chunk-ytrj8hcr.js";import{$ as I9,F as bY,J as vX,L as m4,M as v4,N as _Y,T as e9,U as $Y,Z as g$,aa as S9,ca as JY,ea as j2,fa as V3,ga as j3,ja as E3,ka as h3,oa as rJ,pa as xY,ra as gY,sa as mY,ta as VX,ua as m9,wa as p9,ya as PY}from"./chunk-24teyrer.js";import"./chunk-zm2bbagg.js";import{Ga as e6,Ha as $3,Ia as J3,La as DX}from"./chunk-c39pbp9r.js";import{Na as s9}from"./chunk-z1zr4wts.js";import{Hb as t9,Qb as I4,ub as o9,vb as n9}from"./chunk-k3pe267k.js";import{$b as m2}from"./chunk-sca5q3tt.js";import{Fd as D9,Gd as C4,Hd as v9,Jd as A8,Rd as V2,Ud as x0,ed as u9,od as b9,pd as z2,td as R9,yd as C9}from"./chunk-ay1w6zhg.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import{xe as LX}from"./chunk-1b2dkwpv.js";import{Be as X1,ye as p2,ze as R8}from"./chunk-1s7gj546.js";import"./chunk-pezzyyyk.js";import{Fe as Y2,Ge as W$,He as k1,Ie as zJ,Je as w8,Ke as y9,Le as B6,Me as SJ,Ne as q3,Oe as A6,Pe as Q2,Qe as _$,Re as kX,Se as F$,Te as FX,Ue as K4,Ve as h2,Ye as h9,df as G$}from"./chunk-t7ymt22d.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-7n7swtwg.js";import{tf as kJ}from"./chunk-dh03cybw.js";import"./chunk-8qp8v96d.js";import"./chunk-z4rx2bgb.js";import{Ff as S8,If as o3,Nf as v3,Wf as fX}from"./chunk-g6gp6m3m.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import{sg as NJ,ug as D$}from"./chunk-fnsq6hk0.js";import"./chunk-2t6b962t.js";import{Hh as IX,Mh as D3,Nh as SX}from"./chunk-0pnbvv81.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import{Wh as O2,Xh as b8,Zh as HJ}from"./chunk-2j2mnzdg.js";import{ci as U$}from"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import{Bi as CX,Ei as S1}from"./chunk-68sf54n4.js";import{Gi as H3,Hi as W3,Ki as _1}from"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import{Wi as Z3}from"./chunk-nz2cgjww.js";import{Zi as lJ}from"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import{ij as R4}from"./chunk-9xzw649r.js";import{kj as _J}from"./chunk-hmwz31tc.js";import{useMemoizedFn as L4}from"ahooks";import{useEffect as gK,useState as w4}from"react";import{useMemoizedFn as z$}from"ahooks";import WX from"ansi-escapes";import{Box as M1,useStdout as fK}from"ink";import{useEffect as y1,useMemo as DK,useRef as $8,useState as vK}from"react";import{useShallow as EX}from"zustand/react/shallow";import{useStore as jX}from"zustand";function U0($){return jX(Q2,$)}var hX=[],K2=()=>U0(($)=>$.session.sessionId),Y1=()=>U0(($)=>$.session.workspaceRoot),Z8=()=>U0(($)=>$.session.messages),aJ=()=>U0(($)=>$.session.clearCount),iJ=()=>U0(($)=>$.session.isCompacting),oJ=()=>U0(($)=>$.session.tokenUsage.estimatedCostUsd),nJ=()=>U0(($)=>{let{totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}=$.session.tokenUsage;return rJ({totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}).hitRate}),tJ=()=>U0(($)=>$.session.providerCircuit),sJ=()=>U0(($)=>$.session.providerAdmission),eJ=()=>U0(($)=>$.session.providerRetry),$9=()=>U0(($)=>$.session.providerStall),J9=()=>U0(($)=>$.session.actionStationarity),C1=()=>U0(($)=>$.session.actions),Y9=()=>U0(($)=>{let{totalTokens:J,maxContextTokens:X}=$.session.tokenUsage;if(X<=0)return 100;let Y=Math.max(0,100-J/X*100);return Math.round(Y)}),X9=()=>U0(($)=>$.app.initializationStatus),Z9=()=>U0(($)=>$.app.initializationError),Q8=()=>U0(($)=>$.app.activeModal),Q9=()=>U0(($)=>$.app.tasks),K9=()=>U0(($)=>$.app.modelEditorTarget),U9=()=>U0(($)=>$.app.sessionSelectorData),G9=()=>U0(($)=>$.app.awaitingSecondCtrlC),I1=()=>U0(($)=>$.app.actions),K8=()=>U0(($)=>$.app.sideConversation),q9=()=>U0(($)=>$.app.teams),U8=()=>U0(($)=>$.app.initializationStatus==="ready"),z9=()=>U0(($)=>$.app.tasks.length>0),U2=()=>U0(($)=>$.config.config?.permissionMode||"default"),O9=()=>U0(($)=>$.config.config?.models??hX),G8=()=>U0(($)=>{let J=$.config.config;if(!J)return;let X=J.currentModelId;return J.models.find((Z)=>Z.id===X)??J.models[0]}),q8=()=>U0(($)=>$.config.config?.currentModelId),_9=()=>U0(($)=>$.config.config?.agentTeamsEnabled===!0),k0=()=>U0(($)=>{return W$.getTheme()}),N9=()=>U0(($)=>$.config.config?.codeTheme??"default"),K$=()=>U0(($)=>$.focus.currentFocus),H9=()=>U0(($)=>$.focus.actions),G2=()=>U0(($)=>$.command.isProcessing),W9=()=>U0(($)=>$.command.actions),q2=()=>U0(($)=>$.command.pendingCommands),F9=()=>U0(($)=>$.command.recoveredSteeringCount),z8=()=>U0(($)=>$.app.reasoningEffort!=="off"),O8=()=>U0(($)=>$.app.reasoningEffort),_8=()=>U0(($)=>$.app.serviceTier),N8=()=>U0(($)=>$.app.responseVerbosity),H8=()=>U0(($)=>$.app.communicationStyle),W8=()=>U0(($)=>$.session.currentThinkingContent),L9=()=>U0(($)=>$.session.thinkingExpanded),F8=()=>U0(($)=>$.session.currentStreamingMessageId),L8=()=>U0(EX(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),w9=()=>U0(($)=>$.session.finalizingStreamingMessageId),B9=()=>U0(($)=>$.session.historyExpanded),A9=()=>U0(($)=>$.session.expandedMessageCount);import{useMemoizedFn as O1}from"ahooks";import{useEffect as u1,useMemo as UZ,useRef as I8}from"react";function gX($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class B4{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((X)=>{this.handleUnexpectedFailure(X,$)})})}catch(X){this.handleUnexpectedFailure(X,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},X=new AbortController,Y=this.wakeEpoch,Z=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=X;let Q=await this.options.run(X.signal);if(this.disposed||$!==this.generation||this.activeAttemptToken!==J)return;if(this.activeAttemptToken=null,this.activeRunController=null,Q.status==="completed"){let K=this.wakeEpoch!==Y;if(this.clearEpisode(),K)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==Z)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let X=z2($.taskFailure),Y=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Y||!gX($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,X);return}let Z=M9({sessionIdentity:Y,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(Z.phase!=="retry_scheduled"){this.terminate(Z.phase,this.attempt,X);return}this.requested=!0,this.waitingForIdle=!1;let Q={},K=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},Z.delayMs);this.retryTimer={handle:K,token:Q},K.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),z2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},X=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),b9("timeout"),"pending-resume-recovery-deadline-exceeded")},P9);this.deadlineTimer={handle:X,token:J},X.unref?.()}terminate($,J,X,Y){let Z=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.activeAttemptToken=null,this.activeRunController=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Y)Z?.abort(Y);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:X})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class D2{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)w8(J,$.extraContent);y9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function mX($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let K=JSON.parse(Y.responseBody)?.error?.message;if(K){let U=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function pX($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function xX($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function B8($){let J=pX($),X=xX($),Y;if(X)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=mX($);return{displayMessage:Y,isAbort:J,isVisionNotSupported:X}}import{appendFileSync as cX,mkdirSync as uX,writeFileSync as dX}from"node:fs";import lX from"node:os";import A4 from"node:path";var T9=null;function rX(){let $=process.env.BLADE_STORAGE_ROOT||A4.join(lX.homedir(),".blade");return A4.join($,"logs","stream-debug.log")}function aX($){if(T9===$)return;let J=A4.dirname($);uX(J,{recursive:!0,mode:493}),dX($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
1
|
+
import{e as L3,f as w3}from"./chunk-562w5zc6.js";import{i as BX,j as AX,k as bX}from"./chunk-p7349xay.js";import{v as P9,w as M9,x as T8}from"./chunk-9n90djh7.js";import{$ as I9,F as bY,J as vX,L as m4,M as v4,N as _Y,T as e9,U as $Y,Z as g$,aa as S9,ca as JY,ea as j2,fa as V3,ga as j3,ja as E3,ka as h3,oa as rJ,pa as xY,ra as gY,sa as mY,ta as VX,ua as m9,wa as p9,ya as PY}from"./chunk-v4nqv1pr.js";import"./chunk-pq6g92cz.js";import{Ga as e6,Ha as $3,Ia as J3,La as DX}from"./chunk-60he05xs.js";import{Na as s9}from"./chunk-q3y3s16v.js";import{Hb as t9,Qb as I4,ub as o9,vb as n9}from"./chunk-rz2wc93t.js";import{$b as m2}from"./chunk-sca5q3tt.js";import{Dd as C9,Ld as D9,Md as C4,Nd as v9,Pd as A8,Xd as V2,_d as x0,jd as u9,td as b9,ud as z2,yd as R9}from"./chunk-1acb8fwq.js";import"./chunk-z3hpstky.js";import"./chunk-0ktte40x.js";import{Le as LX}from"./chunk-12hdakw4.js";import{Me as p2,Ne as R8,Pe as X1}from"./chunk-1aw643j2.js";import"./chunk-yqpej45c.js";import{$e as q3,Te as Y2,Ue as W$,Ve as k1,We as zJ,Xe as w8,Ye as y9,Ze as B6,_e as SJ,af as A6,bf as Q2,cf as _$,df as kX,ef as F$,ff as FX,gf as K4,hf as h2,kf as h9,rf as G$}from"./chunk-jxc67ydz.js";import"./chunk-v508x7cg.js";import"./chunk-xshrj2nd.js";import"./chunk-c47db31j.js";import{Hf as kJ}from"./chunk-n4q6fvqe.js";import"./chunk-s7axaw78.js";import"./chunk-yqqeh12b.js";import{Uf as S8,Xf as o3,ag as v3,jg as fX}from"./chunk-a7gghhvn.js";import"./chunk-ektgnqmh.js";import"./chunk-8hd4vd20.js";import"./chunk-10w2pj3r.js";import{Ig as NJ,Kg as D$}from"./chunk-p2rxrxct.js";import"./chunk-zfyg3888.js";import{Xh as IX,ai as D3,bi as SX}from"./chunk-6v2hhgka.js";import"./chunk-nx8xb7dm.js";import"./chunk-96w8ay2h.js";import{ki as O2,li as b8,ni as HJ}from"./chunk-s7peh6kf.js";import{si as U$}from"./chunk-ted1hyvb.js";import"./chunk-xzfc1s6k.js";import{Ri as CX,Ui as S1}from"./chunk-r04vwtej.js";import{Wi as H3,Xi as W3,_i as _1}from"./chunk-atema2rc.js";import"./chunk-gxwkwkhp.js";import{kj as Z3}from"./chunk-b408cqg1.js";import{nj as lJ}from"./chunk-6m4sqwj0.js";import"./chunk-1xg7qx35.js";import{qj as R4}from"./chunk-xnstybjm.js";import{Wj as _J}from"./chunk-mm05y2c5.js";import{useMemoizedFn as L4}from"ahooks";import{useEffect as gK,useState as w4}from"react";import{useMemoizedFn as z$}from"ahooks";import WX from"ansi-escapes";import{Box as M1,useStdout as fK}from"ink";import{useEffect as y1,useMemo as DK,useRef as $8,useState as vK}from"react";import{useShallow as EX}from"zustand/react/shallow";import{useStore as jX}from"zustand";function U0($){return jX(Q2,$)}var hX=[],K2=()=>U0(($)=>$.session.sessionId),Y1=()=>U0(($)=>$.session.workspaceRoot),Z8=()=>U0(($)=>$.session.messages),aJ=()=>U0(($)=>$.session.clearCount),iJ=()=>U0(($)=>$.session.isCompacting),oJ=()=>U0(($)=>$.session.tokenUsage.estimatedCostUsd),nJ=()=>U0(($)=>{let{totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}=$.session.tokenUsage;return rJ({totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}).hitRate}),tJ=()=>U0(($)=>$.session.providerCircuit),sJ=()=>U0(($)=>$.session.providerAdmission),eJ=()=>U0(($)=>$.session.providerRetry),$9=()=>U0(($)=>$.session.providerStall),J9=()=>U0(($)=>$.session.actionStationarity),C1=()=>U0(($)=>$.session.actions),Y9=()=>U0(($)=>{let{totalTokens:J,maxContextTokens:X}=$.session.tokenUsage;if(X<=0)return 100;let Y=Math.max(0,100-J/X*100);return Math.round(Y)}),X9=()=>U0(($)=>$.app.initializationStatus),Z9=()=>U0(($)=>$.app.initializationError),Q8=()=>U0(($)=>$.app.activeModal),Q9=()=>U0(($)=>$.app.tasks),K9=()=>U0(($)=>$.app.modelEditorTarget),U9=()=>U0(($)=>$.app.sessionSelectorData),G9=()=>U0(($)=>$.app.awaitingSecondCtrlC),I1=()=>U0(($)=>$.app.actions),K8=()=>U0(($)=>$.app.sideConversation),q9=()=>U0(($)=>$.app.teams),U8=()=>U0(($)=>$.app.initializationStatus==="ready"),z9=()=>U0(($)=>$.app.tasks.length>0),U2=()=>U0(($)=>$.config.config?.permissionMode||"default"),O9=()=>U0(($)=>$.config.config?.models??hX),G8=()=>U0(($)=>{let J=$.config.config;if(!J)return;let X=J.currentModelId;return J.models.find((Z)=>Z.id===X)??J.models[0]}),q8=()=>U0(($)=>$.config.config?.currentModelId),_9=()=>U0(($)=>$.config.config?.agentTeamsEnabled===!0),k0=()=>U0(($)=>{return W$.getTheme()}),N9=()=>U0(($)=>$.config.config?.codeTheme??"default"),K$=()=>U0(($)=>$.focus.currentFocus),H9=()=>U0(($)=>$.focus.actions),G2=()=>U0(($)=>$.command.isProcessing),W9=()=>U0(($)=>$.command.actions),q2=()=>U0(($)=>$.command.pendingCommands),F9=()=>U0(($)=>$.command.recoveredSteeringCount),z8=()=>U0(($)=>$.app.reasoningEffort!=="off"),O8=()=>U0(($)=>$.app.reasoningEffort),_8=()=>U0(($)=>$.app.serviceTier),N8=()=>U0(($)=>$.app.responseVerbosity),H8=()=>U0(($)=>$.app.communicationStyle),W8=()=>U0(($)=>$.session.currentThinkingContent),L9=()=>U0(($)=>$.session.thinkingExpanded),F8=()=>U0(($)=>$.session.currentStreamingMessageId),L8=()=>U0(EX(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),w9=()=>U0(($)=>$.session.finalizingStreamingMessageId),B9=()=>U0(($)=>$.session.historyExpanded),A9=()=>U0(($)=>$.session.expandedMessageCount);import{useMemoizedFn as O1}from"ahooks";import{useEffect as u1,useMemo as UZ,useRef as I8}from"react";function gX($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class B4{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((X)=>{this.handleUnexpectedFailure(X,$)})})}catch(X){this.handleUnexpectedFailure(X,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},X=new AbortController,Y=this.wakeEpoch,Z=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=X;let Q=await this.options.run(X.signal);if(this.disposed||$!==this.generation||this.activeAttemptToken!==J)return;if(this.activeAttemptToken=null,this.activeRunController=null,Q.status==="completed"){let K=this.wakeEpoch!==Y;if(this.clearEpisode(),K)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==Z)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let X=z2($.taskFailure),Y=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Y||!gX($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,X);return}let Z=M9({sessionIdentity:Y,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(Z.phase!=="retry_scheduled"){this.terminate(Z.phase,this.attempt,X);return}this.requested=!0,this.waitingForIdle=!1;let Q={},K=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},Z.delayMs);this.retryTimer={handle:K,token:Q},K.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),z2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},X=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),b9("timeout"),"pending-resume-recovery-deadline-exceeded")},P9);this.deadlineTimer={handle:X,token:J},X.unref?.()}terminate($,J,X,Y){let Z=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.activeAttemptToken=null,this.activeRunController=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Y)Z?.abort(Y);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:X})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class D2{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)w8(J,$.extraContent);y9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function mX($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let K=JSON.parse(Y.responseBody)?.error?.message;if(K){let U=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function pX($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function xX($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function B8($){let J=pX($),X=xX($),Y;if(X)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=mX($);return{displayMessage:Y,isAbort:J,isVisionNotSupported:X}}import{appendFileSync as cX,mkdirSync as uX,writeFileSync as dX}from"node:fs";import lX from"node:os";import A4 from"node:path";var T9=null;function rX(){let $=process.env.BLADE_STORAGE_ROOT||A4.join(lX.homedir(),".blade");return A4.join($,"logs","stream-debug.log")}function aX($){if(T9===$)return;let J=A4.dirname($);uX(J,{recursive:!0,mode:493}),dX($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
2
2
|
`),T9=$}function b4($,J,X){try{let Y=rX();aX(Y);let Z=new Date().toISOString(),Q=X?` | ${JSON.stringify(X)}`:"",K=`[${Z}] [${$}] ${J}${Q}
|
|
3
3
|
`;cX(Y,K)}catch{}}var v2=S1("UI");function M4($,J){if(J.state==="requires_attention"){let X=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:X?"An interrupted tool may have partially completed":"A completed tool may already have changed external state",detail:`${J.turnId} · inspect workspace, processes, and external state before retrying`});return}$.addToolMessage(J.state==="completed"?"Recovered completed turn":"Resuming interrupted turn",{toolName:"Runtime Recovery",phase:"complete",summary:J.state==="completed"?"The durable final response was recovered":"No tool execution was recorded before interruption",detail:J.turnId})}function k9($,J){let X=$.streamSession??new D2({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)});return(Y)=>{switch(Y.kind){case"content_delta":if(Y.delta.length>0)J.outputStarted=!0;if(!X.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=Y.delta.length,b4("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:Y.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(Y.delta);break;case"thinking_delta":if(Y.delta.length>0)J.outputStarted=!0;if(!X.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(Y.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),v2.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:X.isFinalized,signalAborted:$.signal.aborted}),b4("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:X.isFinalized,signalAborted:$.signal.aborted}),X.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),X.discard();break;case"provider_admission":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderAdmission(Y.phase==="queued"?Q:null);break}case"provider_circuit":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderCircuit(Y.phase==="closed"?null:Q);break}case"provider_retry":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderRetry(Y.phase==="recovered"?null:Q);break}case"provider_stall":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderStall(Y.phase==="detected"?Q:null);break}case"action_stationarity":{let{kind:Z,...Q}=Y;$.sessionActions.setActionStationarity(Y.phase==="recovered"?null:Q);break}case"turn_recovery":{M4($.sessionActions,Y.assessment);break}case"tool_start":{J.toolExecutionStarted=!0;let Z=Y.toolCall;if(!("function"in Z))break;if(Z.function.name===A8)break;if(v2.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:Y.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let Q=JSON.parse(Z.function.arguments),K=I9(Z.function.name,Q);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:Q})}catch(Q){v2.error("[loopEventHandler] onToolStart error:",Q)}break}case"tool_progress":{J.toolExecutionStarted=!0;let Z=Y.toolCall;if(!("function"in Z))break;if(Z.function.name===A8)break;let Q=Y.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((Y.update.progress??0)/Y.update.total*100)))}%`:"",K=`${Z.function.name}${Q}: ${Y.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...Y.update.admission?{admission:Y.update.admission}:{}});break}case"tool_result":{J.toolExecutionStarted=!0;let Z=Y.toolCall;if(!("function"in Z))break;if(Z.function.name===A8)break;v2.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:Y.result.success});let Q=C9(S9(Z.function.name,Y.result),R9);$.sessionActions.addToolMessage(Q.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:Q.summary,detail:Q.detail});break}case"structured_output":J.outputStarted=!0,$.sessionActions.replaceLastAssistantMessage(JSON.stringify(Y.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(Y.usage);break;case"compaction":if($.sessionActions.setCompacting(Y.phase==="start"),Y.phase==="end"){if($.sessionActions.resetContextUsage(),Y.outcome!=="failed")J.compactionCount=(J.compactionCount??0)+1}break;case"turn_start":v2.debug("[loopEventHandler] turn_start",{turn:Y.turn,maxTurns:Y.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:Y.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),X.startTurn();break;case"task_update":$.appActions.setTasks(Y.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(Y.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${Y.revision}: +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[Y.added.length>0?`Added: ${Y.added.join(", ")}`:"",Y.removed.length>0?`Removed: ${Y.removed.join(", ")}`:"",Y.updated.length>0?`Updated: ${Y.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
4
4
|
`)});break}case"mcp_content_changed":{let Z=`MCP ${Y.contentKind} r${Y.revision}: +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[Y.added.length>0?`Added: ${Y.added.join(", ")}`:"",Y.removed.length>0?`Removed: ${Y.removed.join(", ")}`:"",Y.updated.length>0?`Updated: ${Y.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{aj as N,dj as M}from"./chunk-gxwkwkhp.js";import{qj as H}from"./chunk-xnstybjm.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
|
|
2
2
|
`,{mode:384}),await Z.chmod(this.filePath,384)}}var q="openai-compatible",G="anthropic-compatible",D="https://api.openai.com/v1",V="https://api.anthropic.com",A=128000,C=32768,t={input:0,output:0,cacheRead:0,cacheWrite:0},f=["openai","anthropic","deepseek","google","moonshotai","moonshotai-cn","zai","zai-coding-cn"];class L{credentials;models;compatibleModels=new Map;anthropicCompatibleModels=new Map;customProviderConfigs=new Map;customProviderModels=new Map;reservedProviderIds=new Set;constructor(u=new Q){this.credentials=u,this.models=_({credentials:u});for(let $ of P())this.models.setProvider($);this.installOpenAICompatibleProvider(),this.installAnthropicCompatibleProvider();for(let $ of this.models.getProviders())this.reservedProviderIds.add($.id)}async listProviders(){return Promise.all(this.models.getProviders().map(async(u)=>{let $=u.getModels(),h=this.customProviderConfigs.get(u.id),b=this.getFactoryWireApi(u.id);return{id:u.id,name:u.name,modelCount:$.length,defaultBaseUrl:u.baseUrl??$[0]?.baseUrl,supportsApiKey:Boolean(u.auth.apiKey),supportsOAuth:Boolean(u.auth.oauth),configured:b?!1:Boolean(await this.models.checkAuth(u.id)),custom:Boolean(h),factoryWireApi:b,wireApi:h?.wireApi,apiKeyEnv:h?.apiKeyEnv}}))}listModels(u){return this.models.getModels(u).map(($)=>this.toCatalogEntry($))}getModel(u,$){let h=this.models.getModel(u,$);if(!h&&u===q)this.registerOpenAICompatibleModel($),h=this.models.getModel(u,$);if(!h&&u===G)this.registerAnthropicCompatibleModel($),h=this.models.getModel(u,$);if(!h&&this.customProviderConfigs.has(u))this.registerCustomProviderModel(u,$),h=this.models.getModel(u,$);if(!h)throw Error(`Unknown pi-ai model: ${u}/${$}`);return h}resolveConfig(u){let $=this.getModel(u.provider,u.model),h=u.overrides;return{...$,...h?.baseUrl?{baseUrl:J($.api,h.baseUrl)}:{},...h?.maxOutputTokens?{maxTokens:h.maxOutputTokens}:{}}}async setApiKey(u,$){this.requireProvider(u),await this.credentials.modify(u,async()=>({type:"api_key",key:$}))}async clearCredential(u){this.requireProvider(u),await this.credentials.delete(u)}async isConfigured(u){return this.requireProvider(u),Boolean(await this.models.checkAuth(u))}isReservedProviderId(u){return this.reservedProviderIds.has(u)}configureModelProviders(u,$){for(let h of this.customProviderConfigs.keys())this.models.deleteProvider(h);this.customProviderConfigs.clear(),this.customProviderModels.clear();for(let[h,b]of Object.entries(u)){let w=$.filter((k)=>k.provider===h).map((k)=>k.model);this.registerModelProvider(h,b,w)}}registerModelProvider(u,$,h=[]){if(this.isReservedProviderId(u))throw Error(`modelProviders.${u}: built-in provider ids cannot be overridden`);let b=X(u,$);if(b.length>0)throw Error(b.join("; "));let w={...$,name:$.name.trim(),baseUrl:J($.wireApi,$.baseUrl),...$.apiKeyEnv?{apiKeyEnv:$.apiKeyEnv.trim()}:{}};this.customProviderConfigs.set(u,w);let k=new Map;for(let y of new Set(h)){let W=y.trim();if(!W)continue;k.set(W,this.createCompatibleModel(u,W,w.wireApi,w.baseUrl))}this.customProviderModels.set(u,k),this.installCustomProvider(u)}unregisterModelProvider(u){if(!this.customProviderConfigs.has(u))return;this.customProviderConfigs.delete(u),this.customProviderModels.delete(u),this.models.deleteProvider(u)}requireProvider(u){if(!this.models.getProvider(u))throw Error(`Unknown pi-ai provider: ${u}`)}registerOpenAICompatibleModel(u){let $=u.trim();if(!$)throw Error("OpenAI-compatible model ID must not be empty");if(this.compatibleModels.has($))return;let h=this.createCompatibleModel(q,$,"openai-completions",D);this.compatibleModels.set($,h),this.installOpenAICompatibleProvider()}registerAnthropicCompatibleModel(u){let $=u.trim();if(!$)throw Error("Anthropic-compatible model ID must not be empty");if(this.anthropicCompatibleModels.has($))return;let h=this.createCompatibleModel(G,$,"anthropic-messages",V);this.anthropicCompatibleModels.set($,h),this.installAnthropicCompatibleProvider()}registerCustomProviderModel(u,$){let h=$.trim();if(!h)throw Error("Custom provider model ID must not be empty");let b=this.customProviderConfigs.get(u),w=this.customProviderModels.get(u);if(!b||!w||w.has(h))return;w.set(h,this.createCompatibleModel(u,h,b.wireApi,b.baseUrl)),this.installCustomProvider(u)}createCompatibleModel(u,$,h,b){let w=this.models.getModels().filter((y)=>y.provider!==u&&!this.customProviderConfigs.has(y.provider)&&y.id===$),k=f.flatMap((y)=>w.filter((W)=>W.provider===y))[0]??w[0];return{id:$,name:k?.name??$,api:h,provider:u,baseUrl:b,reasoning:k?.reasoning??!1,input:k?[...k.input]:["text"],cost:{...t},contextWindow:k?.contextWindow??A,maxTokens:k?.maxTokens??C,...k?.thinkingLevelMap?{thinkingLevelMap:{...k.thinkingLevelMap}}:{}}}installOpenAICompatibleProvider(){this.models.setProvider(Y({id:q,name:"Custom OpenAI Endpoint",baseUrl:D,auth:{apiKey:x("OpenAI-compatible API key",["OPENAI_COMPATIBLE_API_KEY","BLADE_API_KEY"])},models:[...this.compatibleModels.values()],api:U()}))}installAnthropicCompatibleProvider(){this.models.setProvider(Y({id:G,name:"Custom Anthropic Endpoint",baseUrl:V,auth:{apiKey:x("Anthropic-compatible API key",["ANTHROPIC_API_KEY","BLADE_API_KEY"])},models:[...this.anthropicCompatibleModels.values()],api:F()}))}installCustomProvider(u){let $=this.customProviderConfigs.get(u),h=this.customProviderModels.get(u);if(!$||!h)return;let b=$.apiKeyEnv?[$.apiKeyEnv]:[];this.models.setProvider(Y({id:u,name:$.name,baseUrl:$.baseUrl,auth:{apiKey:x(`${$.name} API key`,b)},models:[...h.values()],api:$.wireApi==="anthropic-messages"?F():U()}))}getFactoryWireApi(u){if(u===q)return"openai-completions";if(u===G)return"anthropic-messages";return}toCatalogEntry(u){return{id:u.id,name:u.name,provider:u.provider,api:u.api,baseUrl:u.baseUrl,reasoning:u.reasoning,supportedReasoningEfforts:E(u),supportedServiceTiers:M(u),supportedResponseVerbosities:N(u),input:[...u.input],contextWindow:u.contextWindow,maxTokens:u.maxTokens,cost:{...u.cost}}}}var S;function hu(){return S??=new L,S}
|
|
3
|
-
export{K as
|
|
3
|
+
export{K as Wi,X as Xi,J as Yi,L as Zi,hu as _i};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.
|
|
2
|
-
export{y as
|
|
1
|
+
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.128",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
|
|
2
|
+
export{y as fj,p as gj,v as hj,g as ij,f as jj,w as kj};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ai as Jf,Ci as Wf,Ei as If,Gi as q,Hi as Qf,Ji as Df,Ki as Kf,Mi as s,wi as __,xi as mf,yi as qf,zi as T_}from"./chunk-xzfc1s6k.js";import{Ui as l}from"./chunk-r04vwtej.js";import{Yi as SE,_i as jf}from"./chunk-atema2rc.js";import{bj as aE}from"./chunk-gxwkwkhp.js";var D_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},TE=(f)=>D_[f]||{};var H_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&H_.has(f)}function zT(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function $T(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 hE(...f){let E=f.filter(Boolean);if(E.length===0)return new AbortController().signal;if(E.length===1)return E[0];let _=AbortSignal;if(typeof _.any==="function")return _.any(E);for(let x of E)if(x.aborted)return x;let T=new AbortController,h=new Map;for(let x of E){let N=()=>{T.abort(x.reason);for(let[P,S]of h)P.removeEventListener("abort",S)};h.set(x,N)}for(let[x,N]of h)x.addEventListener("abort",N,{once:!0});return T.signal}function ff(f,E,_){let T=_?.throwOnAbort??!1;if(E?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((h,x)=>{let N,P=setTimeout(()=>{if(E&&N)E.removeEventListener("abort",N);h()},f);if(E)N=()=>{if(clearTimeout(P),T)x(new DOMException("Aborted","AbortError"));else h()},E.addEventListener("abort",N,{once:!0})})}var U_=l("Chat"),Y_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function xE(f){if(typeof f==="string")return f;return f.filter((E)=>E.type==="text").map((E)=>E.text).join(`
|
|
2
2
|
`)}function b_(f){if(!f)return{};try{let E=JSON.parse(f);return E&&typeof E==="object"&&!Array.isArray(E)?E:{}}catch{return U_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function B_(f){let E=f.match(/^data:([^;,]+);base64,(.+)$/s);return E?{mimeType:E[1],data:E[2]}:void 0}async function c_(f,E){let _=B_(f);if(_)return{type:"image",..._};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:E});if(!T.ok)throw Error(`Failed to load image ${f}: HTTP ${T.status}`);return{type:"image",mimeType:T.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await T.arrayBuffer()).toString("base64")}}async function tE(f,E,_){return Promise.all(f.map((T)=>T.type==="text"?Promise.resolve({type:"text",text:T.text}):E?c_(T.image_url.url,_):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})))}async function PE(f,E,_,T,h){let x=f.filter((A)=>A.role==="system").map((A)=>xE(A.content)).filter(Boolean).join(`
|
|
3
3
|
|
|
4
4
|
`),N=[],P=E.input.includes("image");for(let A of f){if(A.role==="system")continue;if(A.role==="user"){let t=typeof A.content==="string"?A.content:await tE(A.content,P,T);N.push({role:"user",content:t,timestamp:Date.now()});continue}if(A.role==="assistant"){let t=[];if(A.reasoningContent?.trim())t.push({type:"thinking",thinking:A.reasoningContent});let M=xE(A.content);if(M)t.push({type:"text",text:M});for(let I of A.tool_calls??[]){if(!("function"in I))continue;t.push({type:"toolCall",id:I.id,name:I.function.name,arguments:b_(I.function.arguments)})}N.push({role:"assistant",content:t,api:E.api,provider:E.provider,model:E.id,usage:Y_,stopReason:A.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}N.push({role:"toolResult",toolCallId:A.tool_call_id??"",toolName:A.name??"unknown",content:typeof A.content==="string"?[{type:"text",text:A.content}]:await tE(A.content,P,T),isError:!1,timestamp:Date.now()})}let S=_?.filter((A)=>!h||A.name===h).map((A)=>({name:A.name,description:A.description,parameters:A.parameters,constrainedSampling:A.constrainedSampling})).sort((A,t)=>A.name<t.name?-1:A.name>t.name?1:0);return{...x?{systemPrompt:x}:{},messages:N,...S?.length?{tools:S}:{}}}function ME(f){let E=[];for(let _=0;_<f.length;_++){let T=f[_];if(T.role==="tool")continue;let h=T.role==="assistant"&&T.tool_calls?.length?T.tool_calls:void 0;if(!h){E.push(T);continue}let x=[],N=_+1;while(N<f.length&&f[N].role==="tool")x.push(f[N++]);let P=new Set(h.map((t)=>t.id)),S=x.filter((t)=>t.tool_call_id&&P.has(t.tool_call_id)),A=new Set(S.map((t)=>t.tool_call_id));if(P.size===h.length&&S.length===P.size&&A.size===P.size)E.push(T,...S);_=N-1}return E}function AE(f){return f.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function NE(f,E){return{...f,...E.baseUrl?{baseUrl:SE(f.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function Xf(f){let E=f.modelCatalog??jf();return{models:E.models,model:NE(E.getModel(f.provider,f.model),f)}}function uE(f,E){let _=f.modelCatalog??jf();return NE(_.getModel(E.provider,E.model),f)}import{createHash as O_}from"node:crypto";var V_=32,j_=1000,X_=512,z_=2000,J_=0.1,W_=0.05,$_=0.9,k_=300000,L_=3600000;class zf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let E=f.now??Date.now(),_=G_(f,E),T=this.sessions.get(f.sessionId);if(_.callCount=(T?.callCount??0)+1,this.touch(f.sessionId,_),T&&_.contextEpoch!==T.contextEpoch)return;if(!T||T.cacheReadTokens<j_)return;let h=T.cacheReadTokens-_.cacheReadTokens,x=Math.min(z_,Math.max(X_,T.cacheReadTokens*J_));if(h<x||_.cacheReadTokens>=T.cacheReadTokens*(1-W_))return;let N=_.modelIdentity!==T.modelIdentity,P=_.systemHash!==T.systemHash,S=_.toolsHash!==T.toolsHash,A=_.policyHash!==T.policyHash;if(!(N||P||S||A)&&_.promptTokens<T.promptTokens*$_)return;let M=Math.max(0,E-T.recordedAt),I=T.retention==="long"?L_:k_,Y=N?"model_changed":P?"system_prompt_changed":S?"tools_changed":A?"request_policy_changed":M>=I?"ttl_expired":"server_side",$=Z_(T,_);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:_.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:h,elapsedMs:M,callNumber:_.callCount,systemPromptChanged:P,systemCharDelta:_.systemChars-T.systemChars,toolsChanged:S,addedToolCount:$.added,removedToolCount:$.removed,changedToolCount:$.changed,modelChanged:N,requestPolicyChanged:A}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,E){this.sessions.delete(f),this.sessions.set(f,E);while(this.sessions.size>V_){let _=this.sessions.keys().next().value;if(_===void 0)break;this.sessions.delete(_)}}}function G_(f,E){let _=[...f.tools??f.context.tools??[]].map((T)=>({identityHash:Ef(T.name),contractHash:Ef(_f(T))})).sort((T,h)=>T.identityHash<h.identityHash?-1:T.identityHash>h.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:Ef(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:Ef(_f(_)),toolFingerprints:_,policyHash:Ef(_f(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:E,callCount:1}}function Z_(f,E){let _=new Map(f.toolFingerprints.map((h)=>[h.identityHash,h.contractHash])),T=new Map(E.toolFingerprints.map((h)=>[h.identityHash,h.contractHash]));return{added:[...T.keys()].filter((h)=>!_.has(h)).length,removed:[..._.keys()].filter((h)=>!T.has(h)).length,changed:[...T].filter(([h,x])=>_.has(h)&&_.get(h)!==x).length}}function _f(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(_f).join(",")}]`;let E=f;return`{${Object.keys(E).sort().map((_)=>`${JSON.stringify(_)}:${_f(E[_])}`).join(",")}}`}function Ef(f){return O_("sha256").update(f).digest("hex")}import{randomBytes as F_}from"node:crypto";import{createHmac as Q_}from"node:crypto";function K_(f){try{let E=new URL(f);if(E.hash="",E.hostname=E.hostname.toLowerCase(),E.searchParams.sort(),E.pathname!=="/")E.pathname=E.pathname.replace(/\/+$/,"");return E.toString()}catch{return f.trim().replace(/\/+$/,"")}}function C_(f){if(!f)return[];return Object.entries(f).map(([E,_])=>[E.trim().toLowerCase(),_.trim()]).sort(([E],[_])=>E.localeCompare(_))}function Sf(f,E,_){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),K_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",C_(f.customHeaders),_]);return Q_("sha256",Buffer.from(E)).update(T).digest("hex")}var o_=60000,s_=4,v_=0.8;var uf=300000,$f=600000;var IE=128,DE=256,w_=1800000,Nf=50;class hf 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 kf(f){return f instanceof hf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function a(f,E){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:E}function p_(f,E){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:E}function m_(f,E){return Sf(f,E,{providerCircuitOpenDurationMs:f.openDurationMs})}function Tf(f){let E=0;for(let _ of f)if(_.failure)E++;return E}function HE(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function UE(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Wf)}class bE{#x=new Map;#t=new WeakMap;#f;#_;#h;#T;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):F_(32),this.#_=f.now??(()=>performance.now()),this.#h=f.wallNow??f.now??Date.now,this.#T={maxEntries:Math.min(a(f.maxEntries,IE),IE),maxWindowEntries:Math.min(a(f.maxWindowEntries,DE),DE),windowMs:a(f.windowMs,o_),minSamples:a(f.minSamples,s_),errorRateThreshold:p_(f.errorRateThreshold,v_),idleTtlMs:a(f.idleTtlMs,w_)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#P();let E=this.#_();this.#b(E);let _=m_(f,this.#f),T=this.#x.get(_);if(T)return T.lastTouchedAt=E,this.#E(T,f.probeLeaseMs);if(this.#x.size>=this.#T.maxEntries)this.#D();if(this.#x.size>=this.#T.maxEntries)return this.#P();let h={key:_,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:E,detached:!1};return this.#x.set(_,h),this.#E(h,f.probeLeaseMs)}#E(f,E){let _=this,T=Math.max(uf,Math.min(a(E,uf),$f));return{preflight:()=>_.#M(f),check:()=>_.#B(f,T),recordSuccess:(h)=>_.#R(h,"success"),recordFailure:(h,x)=>_.#R(h,"failure",x),recordNeutral:(h)=>_.#R(h,"neutral"),abandon:(h)=>_.#N(h),snapshot:()=>_.#j(f)}}#P(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let E=Object.freeze({kind:"noop"});return f.#t.set(E,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:E}},recordSuccess:(E)=>f.#S(E),recordFailure:(E)=>f.#S(E),recordNeutral:(E)=>f.#S(E),abandon:(E)=>f.#N(E),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#S(f){let E=this.#t.get(f);if(E?.kind==="noop")E.settled=!0;return}#M(f){let E=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=E,this.#u(f,E),f.state==="closed")return{eligible:!0};if(f.state==="open"){let T=f.nextProbeAt??E;return E<T?this.#U(f,T-E):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return{eligible:!0};let _=Math.max(1,(f.probeLeaseExpiresAt??E+Nf)-E);return this.#U(f,Math.min(Nf,_))}#U(f,E){let{allowed:_,...T}=this.#A(f,E);return{eligible:!1,...T}}#B(f,E){let _=this.#_();if(f.detached)return this.#P().check();if(f.lastTouchedAt=_,this.#u(f,_),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let h=f.nextProbeAt??_;if(_<h)return this.#A(f,h-_);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return this.#c(f,_,E);let T=Math.max(1,(f.probeLeaseExpiresAt??_+Nf)-_);return this.#A(f,Math.min(Nf,T))}#Y(f,E,_){let T=Object.freeze({kind:E});return this.#t.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:E,..._!==void 0?{probeLeaseId:_}:{},settled:!1}),{allowed:!0,probe:E==="probe",token:T}}#c(f,E,_){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=E+_,f.lastTouchedAt=E;let h=this.#Y(f,"probe",T),x=f.lastFailure??{reason:"server_error"};return{...h,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#A(f,E){let _=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(E)),nextProbeAt:this.#h()+Math.max(0,Math.ceil(E)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#R(f,E,_){let T=this.#t.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let h=T.entry;if(h.detached||T.generation!==h.generation||T.kind==="regular"&&h.state!=="closed"||T.kind==="probe"&&(h.state!=="half_open"||T.probeLeaseId!==h.probeLeaseId))return;let x=this.#_();if(h.lastTouchedAt=x,T.kind==="probe"){if(E==="failure"&&_)return this.#I(h,_,x,"reopened");return this.#O(h)}if(E==="neutral")return;if(this.#V(h,E==="failure",x),E!=="failure"||!_)return;let N=Tf(h.samples),P=h.samples.length===0?0:N/h.samples.length;if(h.samples.length>=this.#T.minSamples&&P>=this.#T.errorRateThreshold)return this.#I(h,_,x,"opened");return}#I(f,E,_,T){let h={reason:E.reason,...HE(E.statusCode)!==void 0?{statusCode:HE(E.statusCode)}:{},...UE(E.retryAfterMs)!==void 0?{retryAfterMs:UE(E.retryAfterMs)}:{}},x=h.retryAfterMs??0,N=Math.max(f.configuredOpenDurationMs,x);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=N,f.nextProbeAt=_+N,f.lastFailure=h,{phase:T,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},retryAfterMs:N,nextProbeAt:this.#h()+N,openDurationMs:N,sampleCount:f.samples.length,failureCount:Tf(f.samples)}}#O(f){let E=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#N(f){let E=this.#t.get(f);if(!E||E.settled)return!1;if(E.settled=!0,E.kind==="noop")return!0;let _=E.entry;if(!_||_.detached||E.kind!=="probe"||E.generation!==_.generation||E.probeLeaseId!==_.probeLeaseId)return!1;return _.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.lastTouchedAt=this.#_(),!0}#V(f,E,_){if(this.#u(f,_),f.samples.length>=this.#T.maxWindowEntries)f.samples.shift();f.samples.push({at:_,failure:E})}#u(f,E){let _=E-this.#T.windowMs,T=0;while(T<f.samples.length&&f.samples[T].at<_)T++;if(T>0)f.samples.splice(0,T)}#j(f){if(!f.detached)this.#u(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:Tf(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#b(f){for(let[E,_]of this.#x)if(_.state==="closed"&&f-_.lastTouchedAt>this.#T.idleTtlMs)this.#H(E,_)}#D(){let f;for(let E of this.#x.values())if(E.state==="closed"&&(!f||E.lastTouchedAt<f.lastTouchedAt))f=E;if(f)this.#H(f.key,f)}#H(f,E){E.detached=!0,this.#x.delete(f)}}var YE;function BE(){return YE??=new bE,YE}import{randomBytes as q_}from"node:crypto";var g_=16,cE=128,OE=32,l_=3,VE=16,jE=96,XE=24,zE=12,JE=16,WE=4,$E=4,kE=67108864,LE=33554432,a_=12,y_=2,GE=2,ZE=1,oE=15000,QE=30000;function Lf(){return{foreground:0,background:0,internal:0}}function Gf(){return{inFlight:Lf(),queued:Lf(),pendingBytes:Lf()}}function U(f){return f.foreground+f.background+f.internal}function W(f){return f.background+f.internal}function KE(f){return f.inFlight.foreground===0&&f.inFlight.background===0&&f.inFlight.internal===0&&f.queued.foreground===0&&f.queued.background===0&&f.queued.internal===0&&f.pendingBytes.foreground===0&&f.pendingBytes.background===0&&f.pendingBytes.internal===0}class xf extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,E,_,T,h,x,N,P){super(f==="queue_full"?`Provider request admission ${E} ${T} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${E} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=E;this.requestClass=_;this.resource=T;this.inFlight=h;this.limit=x;this.queued=N;this.maxWaitMs=P;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function tf(f){return f instanceof xf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function z(f,E,_){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return E;return Math.min(f,_)}function e_(f){let E=z(f.globalMaxInFlight,g_,Number.MAX_SAFE_INTEGER),_=z(f.globalMaxPending,cE,cE),T=z(f.domainMaxPending,OE,OE),h=Math.min(z(f.ownerMaxInFlight,l_,Number.MAX_SAFE_INTEGER),E),x=Math.min(z(f.ownerMaxPending,VE,VE),_),N=Math.min(z(f.nonForegroundGlobalMaxPending,Math.min(jE,Math.max(1,Math.floor(_*3/4))),jE),_),P=Math.min(z(f.nonForegroundDomainMaxPending,Math.min(XE,Math.max(1,Math.floor(T*3/4))),XE),T),S=Math.min(z(f.nonForegroundOwnerMaxPending,Math.min(zE,Math.max(1,Math.floor(x*3/4))),zE),x),A=Math.min(z(f.internalGlobalMaxPending,Math.min(JE,Math.max(1,Math.floor(_/8))),JE),N),t=Math.min(z(f.internalDomainMaxPending,Math.min(WE,Math.max(1,Math.floor(T/8))),WE),P),M=Math.min(z(f.internalOwnerMaxPending,Math.min($E,Math.max(1,Math.floor(x/4))),$E),S),I=z(f.globalMaxPendingBytes,s,s),Y=Math.min(z(f.domainMaxPendingBytes,kE,kE),I),$=Math.min(z(f.ownerMaxPendingBytes,LE,LE),I),Q=Math.min(z(f.nonForegroundGlobalMaxInFlight,Math.min(a_,E),E),E),K=Math.min(z(f.nonForegroundOwnerMaxInFlight,Math.min(y_,h),h),h),o=Math.min(z(f.internalGlobalMaxInFlight,Math.min(GE,E),GE),E),Uf=z(f.internalDomainMaxInFlight,ZE,ZE),Rf=z(f.agingMs,QE,QE);return{globalMaxInFlight:E,globalMaxPending:_,domainMaxPending:T,ownerMaxInFlight:h,ownerMaxPending:x,nonForegroundGlobalMaxPending:N,nonForegroundDomainMaxPending:P,nonForegroundOwnerMaxPending:S,internalGlobalMaxPending:A,internalDomainMaxPending:t,internalOwnerMaxPending:M,globalMaxPendingBytes:I,domainMaxPendingBytes:Y,ownerMaxPendingBytes:$,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:o,internalDomainMaxInFlight:Uf,agingMs:Rf,classLimitsEnabled:f.classLimitsEnabled!==!1}}function CE(f,E){if(!f.trim())throw Error(`${E} must not be blank`)}function d_(f){if(CE(f.sessionId,"sessionId"),CE(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<If||f.scope.maxConcurrent>q)throw Error(`maxConcurrent must be between ${If} and ${q}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>s)throw Error(`maxPendingBytes must be between 1 and ${s}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>s+1)throw Error(`pendingBytes must be between 1 and ${s+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Df)throw Error(`maxWaitMs must be 0-${Df}`)}function Zf(f,E){if(E!==void 0)return E;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function n_(f,E){return Sf(f,E,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class sE{#x;#t;#f;#_=[];#h=new Map;#T=new Map;#E=Gf();#P=1;#S=0;#M=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):q_(32),this.#t=f.now??(()=>performance.now()),this.#f=e_(f)}admit(f){if(d_(f),this.#M)throw this.#X("closed",f,{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw Zf(f.signal);let E=n_(f.scope,this.#x),_=this.#h.get(E),T=this.#T.get(f.ownerId),h=_??this.#Y(f.scope.maxConcurrent),x=T??this.#c();if(this.#_.length===0&&this.#A(h,x,f.requestClass)){if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let I=this.#I(E,f.ownerId,f.requestClass),Y=this.#k(f,0);return{ready:Promise.resolve(I),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let N=this.#U(f,h,x);if(N)throw this.#X("queue_full",f,N,this.#_.length);let P=this.#R(h,x,f.requestClass);if(f.maxWaitMs===0)throw this.#X("wait_timeout",f,P,this.#_.length);if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#P++;let S,A,t=new Promise((I,Y)=>{S=I,A=Y});t.catch(()=>{return});let M={domainKey:E,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:S,reject:A,settled:!1,admitted:!1};if(f.signal)M.abortListener=()=>this.#b(M,Zf(f.signal)),f.signal.addEventListener("abort",M.abortListener,{once:!0});return M.timer=setTimeout(()=>this.#j(M),f.maxWaitMs),M.timer.unref?.(),this.#_.push(M),this.#B(h,x,M),this.#N(),{ready:t,getSnapshot:()=>this.#$(M),cancel:(I)=>this.#b(M,Zf(f.signal,I))}}close(){if(this.#M)return;this.#M=!0;for(let f of[...this.#_]){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new xf("closed",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:U(this.#E.inFlight),queued:this.#_.length,pendingBytes:U(this.#E.pendingBytes),nonForegroundInFlight:W(this.#E.inFlight),internalInFlight:this.#E.inFlight.internal,nonForegroundQueued:W(this.#E.queued),internalQueued:this.#E.queued.internal,nonForegroundPendingBytes:W(this.#E.pendingBytes),internalPendingBytes:this.#E.pendingBytes.internal,domainCount:this.#h.size,ownerCount:this.#T.size,closed:this.#M}}#U(f,E,_){let T=(t,M,I)=>M>=I?{scope:t,resource:"pending_count",inFlight:M,limit:I}:void 0;if(this.#f.classLimitsEnabled&&f.requestClass==="internal"){let t=T("class",this.#E.queued.internal,this.#f.internalGlobalMaxPending)??T("class",_.counters.queued.internal,this.#f.internalOwnerMaxPending)??T("class",E.counters.queued.internal,this.#f.internalDomainMaxPending);if(t)return t}if(this.#f.classLimitsEnabled&&f.requestClass!=="foreground"){let t=T("class",W(this.#E.queued),this.#f.nonForegroundGlobalMaxPending)??T("class",W(_.counters.queued),this.#f.nonForegroundOwnerMaxPending)??T("class",W(E.counters.queued),this.#f.nonForegroundDomainMaxPending);if(t)return t}let h=T("global",this.#_.length,this.#f.globalMaxPending)??T("owner",U(_.counters.queued),this.#f.ownerMaxPending)??T("domain",U(E.counters.queued),this.#f.domainMaxPending);if(h)return h;let x=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),N=Math.min(x,this.#f.domainMaxPendingBytes),P=Math.min(x,this.#f.ownerMaxPendingBytes),S=(t,M)=>f.pendingBytes>M-t,A=(t)=>{if(t==="owner")return{scope:t,resource:"pending_bytes",inFlight:U(_.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(t==="domain")return{scope:t,resource:"pending_bytes",inFlight:U(E.counters.inFlight),limit:E.maxConcurrent};return{scope:t,resource:"pending_bytes",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let t=Math.max(1,Math.floor(x/8)),M=Math.max(1,Math.floor(N/4)),I=Math.max(1,Math.floor(P/4));if(S(this.#E.pendingBytes.internal,t)||S(_.counters.pendingBytes.internal,I)||S(E.counters.pendingBytes.internal,M))return A("class")}if(f.requestClass!=="foreground"){let t=Math.max(1,Math.floor(x*3/4)),M=Math.max(1,Math.floor(N*3/4)),I=Math.max(1,Math.floor(P/2));if(S(W(this.#E.pendingBytes),t)||S(W(_.counters.pendingBytes),I)||S(W(E.counters.pendingBytes),M))return A("class")}if(S(U(this.#E.pendingBytes),x))return A("global");if(S(U(_.counters.pendingBytes),P))return A("owner");if(S(U(E.counters.pendingBytes),N))return A("domain");return}#B(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]++,f.counters.queued[T]++,E.counters.queued[T]++,this.#E.pendingBytes[T]+=h,f.counters.pendingBytes[T]+=h,E.counters.pendingBytes[T]+=h}#Y(f){return{maxConcurrent:f,counters:Gf()}}#c(){return{order:this.#P,counters:Gf()}}#A(f,E,_){if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return!1;if(U(f.counters.inFlight)>=f.maxConcurrent)return!1;if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return!1;if(_==="foreground"||!this.#f.classLimitsEnabled)return!0;if(W(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(W(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let T=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=T)return!1;if(_!=="internal")return!0;return this.#E.inFlight.internal<this.#f.internalGlobalMaxInFlight&&f.counters.inFlight.internal<this.#f.internalDomainMaxInFlight}#R(f,E,_){if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:U(E.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&W(E.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(E.counters.inFlight),limit:this.#f.nonForegroundOwnerMaxInFlight};if(U(f.counters.inFlight)>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent};if(this.#f.classLimitsEnabled&&_!=="foreground"){let T=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=T)return{scope:"class",resource:"stream",inFlight:W(f.counters.inFlight),limit:T}}if(this.#f.classLimitsEnabled&&_==="internal"&&f.counters.inFlight.internal>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.counters.inFlight.internal,limit:this.#f.internalDomainMaxInFlight};if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};if(this.#f.classLimitsEnabled&&_!=="foreground"&&W(this.#E.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(this.#E.inFlight),limit:this.#f.nonForegroundGlobalMaxInFlight};if(this.#f.classLimitsEnabled&&_==="internal"&&this.#E.inFlight.internal>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#E.inFlight.internal,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent}}#I(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(!T||!h)throw Error("Provider admission accounting state is unavailable");this.#E.inFlight[_]++,T.counters.inFlight[_]++,h.counters.inFlight[_]++;let x=!1;return{release:()=>{if(x)return;x=!0,this.#O(f,E,_)}}}#O(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(this.#E.inFlight[_]--,T)T.counters.inFlight[_]--;if(h)h.counters.inFlight[_]--;this.#z(f,E),this.#N()}#N(){if(this.#M)return;while(this.#_.length>0){let f=this.#t(),E=new Map;for(let[P,S]of this.#_.entries()){let A=this.#h.get(S.domainKey),t=this.#T.get(S.ownerId);if(A===void 0||t===void 0||!this.#A(A,t,S.requestClass))continue;let M=this.#V(S,f),I=E.get(S.ownerId);if(!I||M<I.rank||M===I.rank&&P<I.index)E.set(S.ownerId,{pending:S,rank:M,index:P})}let _=[...E.values()].filter(({pending:P})=>{let S=this.#h.get(P.domainKey),A=this.#T.get(P.ownerId);return S!==void 0&&A!==void 0&&this.#A(S,A,P.requestClass)}).map(({pending:P,rank:S})=>({pending:P,rank:S,order:this.#T.get(P.ownerId).order}));if(_.length===0)return;let T=Math.min(..._.map((P)=>P.rank)),h=_.filter((P)=>P.rank===T),N=h.filter((P)=>P.order>this.#S).sort((P,S)=>P.order-S.order)[0]??h.sort((P,S)=>P.order-S.order)[0];this.#u(N.pending,N.order)}}#V(f,E){let _=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,E-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,_-T)}#u(f,E){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#S=E;let _=this.#I(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#j(f){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new xf("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#b(f,E){this.#D(f,E)}#D(f,E){if(!this.#H(f))return;f.settled=!0,f.reject(E),this.#N()}#H(f,E=!0){if(f.settled||f.admitted)return!1;let _=this.#_.indexOf(f);if(_<0)return!1;this.#_.splice(_,1);let T=this.#h.get(f.domainKey),h=this.#T.get(f.ownerId);if(T&&h)this.#J(T,h,f);if(this.#W(f),E)this.#z(f.domainKey,f.ownerId);return!0}#J(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]--,f.counters.queued[T]--,E.counters.queued[T]--,this.#E.pendingBytes[T]-=h,f.counters.pendingBytes[T]-=h,E.counters.pendingBytes[T]-=h}#W(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}#z(f,E){let _=this.#h.get(f);if(_&&KE(_.counters))this.#h.delete(f);let T=this.#T.get(E);if(T&&KE(T.counters))this.#T.delete(E)}#$(f){let E=Math.max(0,Math.floor(this.#t()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs};let _=this.#h.get(f.domainKey),T=this.#T.get(f.ownerId),h=_&&T?this.#R(_,T,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:h.resource,scope:h.scope,reason:"capacity",queuePosition:this.#L(f,h.scope),queueDepth:this.#_.length,inFlight:h.inFlight,limit:h.limit,waitMs:E,maxWaitMs:f.maxWaitMs}}#k(f,E){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs}}#L(f,E){let _=this.#_.filter((T)=>{switch(E){case"owner":return T.ownerId===f.ownerId;case"domain":return T.domainKey===f.domainKey;case"class":return T.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,_.indexOf(f)+1)}#X(f,E,_,T){return new xf(f,_.scope,E.requestClass,_.resource,_.inFlight,_.limit,T,E.maxWaitMs)}}var FE;function vE(f={}){return FE??=new sE(f),FE}function wE(f,E={}){let _=E.maxBytes??134217728,T=E.maxNodes??1e5;if(!Number.isSafeInteger(_)||_<=0||_>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(T)||T<=0)throw Error("maxNodes must be a positive safe integer");let h=new WeakSet,x=0,N=0,P=!1,S=(t)=>{if(P||t<=0)return;if(!Number.isSafeInteger(t)||t>_-x){x=_+1,P=!0;return}x+=t},A=(t)=>{if(P)return;if(N+=1,N>T){S(_+1);return}if(t===null){S(4);return}switch(typeof t){case"string":S(Buffer.byteLength(t,"utf8"));return;case"number":case"bigint":S(8);return;case"boolean":S(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(h.has(t))return;if(h.add(t),ArrayBuffer.isView(t)){S(32+t.byteLength);return}if(t instanceof ArrayBuffer){S(32+t.byteLength);return}if(t instanceof Date){S(40);return}if(t instanceof RegExp){S(32+Buffer.byteLength(t.source,"utf8"));return}if(t instanceof Map){S(32);for(let[M,I]of t)if(A(M),A(I),P)return;return}if(t instanceof Set){S(32);for(let M of t)if(A(M),P)return;return}if(t instanceof WeakMap||t instanceof WeakSet){S(32);return}if(Array.isArray(t)){S(16);for(let M of t)if(A(M),P)return;return}S(32);for(let M of Reflect.ownKeys(t)){if(typeof M!=="string")continue;let I=Object.getOwnPropertyDescriptor(t,M);if(!I?.enumerable||!("value"in I))continue;if(S(8+Buffer.byteLength(M,"utf8")),A(I.value),P)return}};return A(f),x}function pE(f){return wE([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}var mE=new WeakSet;class y extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,E){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=E;this.name="ProviderRecoveryBudgetExceededError"}}class Cf extends Error{timeoutMs;code="PROVIDER_REQUEST_DEADLINE_EXCEEDED";constructor(f){super(`Provider request deadline exceeded after ${f}ms`);this.timeoutMs=f;this.name="ProviderRequestDeadlineExceededError"}}var r_=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],i_=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],fT=["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 qE(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function ET(f){let E=qE(f);return i_.some((_)=>E.includes(_))}function Ff(f){if(f!==null&&typeof f==="object")mE.add(f)}function Ph(f){return f!==null&&typeof f==="object"&&mE.has(f)}function _T(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function TT(f){if(f===null||typeof f!=="object")return;let E=f;for(let _ of["status","statusCode"]){let T=E[_];if(typeof T==="number"&&Number.isInteger(T))return T}return}function hT(f){let E=f.match(/^(?:error:\s*)?(\d{3})\b/),_=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(E?.[1]??_?.[1]);return Number.isInteger(T)?T:void 0}function e(f,E){let _=qE(f),T=_T(f);if(T==="STREAM_IDLE_TIMEOUT"||T==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||_.includes("request aborted")||_==="aborted")return{retryable:!1};if(r_.some((x)=>_.includes(x))||ET(f))return{retryable:!1};if(E?.shouldRetry==="false")return{retryable:!1,statusCode:E.statusCode};if(T==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let h=E?.statusCode??TT(f)??hT(_);if(E?.shouldRetry==="true")return{retryable:!0,reason:h===429?"rate_limit":h===408||h===409?"timeout":"server_error",statusCode:h};if(h===429)return{retryable:!0,reason:"rate_limit",statusCode:h};if(h===408||h===409)return{retryable:!0,reason:"timeout",statusCode:h};if(h!==void 0&&h>=500&&h<=599)return{retryable:!0,reason:"server_error",statusCode:h};if(T==="PROVIDER_STREAM_CLOSED"||_.includes("stream closed before completion")||_.includes("ended without")||_.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:h};if(fT.some((x)=>_.includes(x)))return{retryable:!0,reason:"transport",statusCode:h};if(_.includes("timeout")||_.includes("timed out")||_.includes("temporarily unavailable")||_.includes("upstream_error")||_.includes("overloaded")||_.includes("rate limit")||_.includes("too many requests")||_.includes("service unavailable")||_.includes("server error")||_.includes("internal error")||_.includes("please retry")||_.includes("try your request again"))return{retryable:!0,reason:_.includes("rate")||_.includes("too many")?"rate_limit":_.includes("timeout")||_.includes("timed out")?"timeout":"server_error",statusCode:h};return{retryable:!1,statusCode:h}}function of(f,E){if(!f)return;if(f.retryAfterMs!==void 0){let h=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(h))return Math.max(0,h)}if(f.retryAfter===void 0)return;let _=Number.parseFloat(f.retryAfter);if(Number.isFinite(_))return Math.max(0,_*1000);let T=Date.parse(f.retryAfter);return Number.isFinite(T)?Math.max(0,T-E):void 0}function gE(f,E,_={}){let T=_.now??Date.now(),h=_.maxDelayMs??60000,x=of(E,T);if(x!==void 0)return Math.min(Math.ceil(x),h);let N=Math.max(0,f-1),P=_.maxExponentialDelayMs??8000,S=Math.min(500*2**N,P),A=Math.max(0,Math.min(1,_.random??Math.random())),t=S*(0.75+A*0.25);return Math.min(Math.round(t),h)}function yE(f,E){let _=f.onPayload;f.onPayload=async(T,h)=>{let x=_?await _(T,h):T;return E(x===void 0?T:x,h)}}function xT(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function sf(f,E,_){if(!f.enablePromptCaching)return"none";if(_&&E.api==="openai-completions"&&!E.baseUrl.includes("api.openai.com"))return"long";return"short"}function tT(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function RT(f,E,_,T){let h=T?void 0:xT(_);if(!h){if(E.api==="anthropic-messages")f.thinkingEnabled=!1;if(E.api==="google-generative-ai"||E.api==="google-vertex")f.thinking={enabled:!1};return}switch(E.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=h;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:tT(h)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=h;break;default:f.reasoningEffort=h}}function PT(f,E,_){if(!_)return;switch(E){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:_};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:_}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:_};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function MT(f,E,_){let T=_.serviceTier;if(!T)return;if(E.api==="openai-responses"||E.api==="openai-codex-responses"||E.api==="azure-openai-responses"){f.serviceTier=T;return}if(E.api!=="openai-completions"&&!(E.api==="anthropic-messages"&&T==="fast"))return;yE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;return E.api==="anthropic-messages"?{...h,speed:"fast"}:{...h,service_tier:T}})}function AT(f,E,_){let T=_.responseVerbosity;if(!T)return;if(aE(E,T),E.api==="openai-codex-responses"){f.textVerbosity=T;return}yE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;if(E.api==="openai-completions")return{...h,verbosity:T};let x="text"in h&&h.text&&typeof h.text==="object"&&!Array.isArray(h.text)?h.text:{};return{...h,text:{...x,verbosity:T}}})}function eE(f,E,_,T,h=!1){let x={apiKey:f.apiKey,headers:f.customHeaders,signal:_,temperature:T?.temperature??f.temperature??0,maxTokens:T?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:sf(f,E,T?.providerSessionId),sessionId:T?.providerSessionId};if(RT(x,E,f,h),PT(x,E.api,T?.toolChoice?.toolName),MT(x,E,f),AT(x,E,f),E.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=E.id;return x}function lE(f,E){let _=E.get("x-should-retry");return{statusCode:f,...E.get("retry-after")!==null?{retryAfter:E.get("retry-after")??void 0}:{},...E.get("retry-after-ms")!==null?{retryAfterMs:E.get("retry-after-ms")??void 0}:{},..._==="true"||_==="false"?{shouldRetry:_}:{}}}var ST=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function dE(f,E,_){let T=f.onResponse;if(f.onResponse=async(x,N)=>{let P=new Headers(x.headers);_(lE(x.status,P)),await T?.(x,N)},!ST.has(E.api)||typeof globalThis.fetch!=="function")return;let h=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(x,N)=>{let P=await h(x,N);return _(lE(P.status,P.headers)),P}}function nE(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 Hf=300000,NT=30000;class rE 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 iE extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function vf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function uT(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Hf}function IT(f,E){if(E===0)return;let _=E!==void 0&&E>0?E:NT;return Math.max(1,Math.min(_,Math.floor(f/2)))}function DT(f,E,_){if(_?.aborted)return Promise.reject(vf(_));return new Promise((T,h)=>{let x=!1,N=()=>{clearTimeout(t),_?.removeEventListener("abort",A)},P=(M)=>{if(x)return;x=!0,N(),T(M)},S=(M)=>{if(x)return;x=!0,N(),h(M instanceof Error?M:Error(String(M)))},A=()=>{if(_)S(vf(_))},t=setTimeout(()=>P({kind:"timer"}),Math.max(0,E));if(_?.addEventListener("abort",A,{once:!0}),_?.aborted){A();return}f.then((M)=>P({kind:"next",result:M}),S)})}async function*HT(f,E,_){let T=uT(E),h=IT(T,E.stallWarningMs);if(E.signal?.aborted)throw vf(E.signal);let x=Date.now(),N=Promise.resolve().then(()=>f.next()),P;for(;;){let A=await DT(N,(P?T:h??T)-(Date.now()-x),E.signal);if(A.kind==="next"){if(P)yield{...P,phase:"recovered",durationMs:Math.max(P.durationMs,Date.now()-x)};return A.result}if(!P&&h!==void 0){_.stallCount++,P={phase:"detected",stallCount:_.stallCount,durationMs:h,warningAfterMs:h,timeoutMs:T,outputStarted:_.outputStarted},yield P;continue}let t=new rE(T);throw E.abort?.(t),t}}async function*f_(f,E,_,T,h={}){let N=f.stream(E,_,T)[Symbol.asyncIterator](),P=0,S=!1,A={stallCount:0,outputStarted:!1};try{while(!0){let t=HT(N,h,A),M=await t.next();while(!M.done)yield{providerStall:M.value},M=await t.next();let I=M.value;if(I.done)throw new iE;let Y=I.value;switch(Y.type){case"text_delta":A.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":A.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":A.outputStarted=!0,yield{toolCalls:[{index:P++,id:Y.toolCall.id,type:"function",function:{name:Y.toolCall.name,arguments:JSON.stringify(Y.toolCall.arguments)}}]};break;case"done":S=!0,yield{finishReason:Y.reason,usage:nE(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!S)Promise.resolve(N.return?.()).catch(()=>{return})}}var wf=l("Chat"),UT=1;function YT(f,E){let _=E.provider===f.provider,T=_&&E.channel===void 0,h=E.channel;return{...f,provider:E.provider,model:E.model,apiKey:h?.apiKey??(T?f.apiKey:void 0),baseUrl:h?.baseUrl??(T?f.baseUrl:void 0),temperature:h?.temperature??f.temperature,maxOutputTokens:h?.maxOutputTokens??(T?f.maxOutputTokens:void 0),timeout:h?.timeout??f.timeout,streamIdleTimeout:h?.streamIdleTimeout??f.streamIdleTimeout,apiVersion:h?.apiVersion??(T?f.apiVersion:void 0),customHeaders:h?.customHeaders??(T?f.customHeaders:void 0),enablePromptCaching:h?.enablePromptCaching??(T?f.enablePromptCaching:void 0),serviceTier:_?f.serviceTier:void 0,responseVerbosity:_?f.responseVerbosity:void 0,fallbackModels:void 0}}function bT(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((E)=>E.type==="image_url"))}function BT(f){let _=f.findLast((T)=>{let h=T.metadata;return h!==null&&typeof h==="object"&&!Array.isArray(h)&&h.isCompactSummary===!0})?.metadata;return _!==null&&typeof _==="object"&&!Array.isArray(_)&&typeof _.parentId==="string"?_.parentId:""}function cT(f,E){let _=e(f,E);if(!_.retryable||!_.reason)return;let T=_.statusCode;switch(_.reason){case"rate_limit":if(T!==429)return;break;case"server_error":if(T===void 0||T<500||T>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let h=of(E,Date.now());return{reason:_.reason,...T!==void 0?{statusCode:T}:{},...h!==void 0?{retryAfterMs:h}:{}}}function pf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class gf{config;models;model;promptCacheBreakMonitor=new zf;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${UT++}`;constructor(f){let E=Xf(f);this.config={...f,maxContextTokens:E.model.contextWindow,maxOutputTokens:f.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model,this.providerAdmissionScheduler=E_(this.config),wf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,E,_,T){let h="",x="",N=[],P,S;for await(let A of this.streamChat(f,E,_,T)){h+=A.content??"",x+=A.reasoningContent??"";for(let t of A.toolCalls??[])if(t.id&&t.type==="function"&&t.function?.name)N.push(t);P=A.usage??P,S=A.finishReason??S}return{content:h,...x?{reasoningContent:x}:{},...N.length>0?{toolCalls:N}:{},usage:P,finishReason:S}}async*streamChat(f,E,_,T){let h=T?.toolChoice?.toolName;if(h&&!E?.some((R)=>R.name===h))throw Error(`Required tool is unavailable: ${h}`);let x=ME(f);if(x.some((R)=>bT(R))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let N=Boolean(h)||AE(x),P=await PE(x,this.model,E,_,h),S=(R,u)=>{let O=T?.providerSessionId;if(!O||!R.usage)return R;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(O),R;let b=sf(this.config,u,O),H=this.promptCacheBreakMonitor.observe({sessionId:O,modelIdentity:`${u.provider}\x00${u.api}\x00${u.id}`,context:P,retention:b,contextEpoch:BT(x),policy:{baseUrl:u.baseUrl??this.config.baseUrl??"",retention:b,requiredTool:h??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:T?.temperature??this.config.temperature??0,maxOutputTokens:T?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:R.usage});if(!H)return R;return wf.warn("[PiAIChatService] Prompt cache break detected",{reason:H.reason,previousCacheReadTokens:H.previousCacheReadTokens,cacheReadTokens:H.cacheReadTokens,tokenDrop:H.tokenDrop,callNumber:H.callNumber}),{...R,usage:{...R.usage,promptCacheBreak:H}}},A=pE({messages:x,context:P,tools:E,requestOptions:T}),t=T?.providerRecovery;if(t&&!T_(t.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let M=t?.mode==="bounded_foreground"&&t.budgetMs>0?{budgetMs:t.budgetMs,startedAt:void 0}:void 0,I=M?"bounded_foreground":"standard",Y=this.config.maxRetries??2,$=this.config.maxRetries??(M?__:2),Q=M!==void 0&&this.config.maxRetries===void 0,K=0,o,Uf=this.config.providerCircuitRegistry??BE(),Rf=this.config.providerCircuitBreakerOpenMs??Jf,h_=Math.max(uf,Math.min(this.config.streamIdleTimeout??Hf,$f)),lf=this.providerAdmissionScheduler,x_=this.config.providerRequestConcurrency??q,af=this.config.providerRequestAdmissionMs??Qf,t_=this.config.providerRequestPendingBytes??Kf,Yf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},R_=(R,u)=>Uf.get({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,openDurationMs:Rf,probeLeaseMs:h_}),P_=(R,u)=>({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,maxConcurrent:x_,maxPendingBytes:t_}),j=(R=Date.now())=>{if(!M)return;let u=M.startedAt===void 0?0:Math.min(M.budgetMs,Math.max(0,R-M.startedAt));return{recoveryBudgetMs:M.budgetMs,recoveryElapsedMs:u,recoveryRemainingMs:Math.max(0,M.budgetMs-u)}},v=()=>({mode:I,...j()??{}}),yf=()=>{if(M&&M.startedAt===void 0)M.startedAt=Date.now()},w=()=>{let R=j();return new y(M?.budgetMs??0,R?.recoveryElapsedMs??0)},d=()=>!Q||K<$+1,bf=(R,u)=>{let{state:O,...b}=u;return{phase:R,...b,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}},ef=(R)=>({phase:"rejected",requestClass:R.requestClass,resource:R.resource,scope:R.scope,reason:R.reason,queuePosition:0,queueDepth:Math.max(0,R.queued),inFlight:Math.max(0,R.inFlight),limit:Math.max(0,R.limit),waitMs:R.reason==="wait_timeout"?R.maxWaitMs:0,maxWaitMs:R.maxWaitMs,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),M_=async function*(R,u){if(!lf)return{release:()=>{return}};let O=j()?.recoveryRemainingMs,b=O!==void 0&&M?.startedAt!==void 0?Math.min(af,O):af,H;try{H=lf.admit({scope:P_(R,u),sessionId:Yf.sessionId,ownerId:Yf.ownerId,requestClass:Yf.requestClass,maxWaitMs:b,pendingBytes:A,signal:_})}catch(B){if(tf(B)){if(B.reason==="wait_timeout"&&M?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:ef(B)}}throw B}let L=H.getSnapshot();if(L.state==="admitted")return await H.ready;yield{providerAdmission:bf("queued",L)};let F=H.ready.then((B)=>({kind:"ready",permit:B}),(B)=>({kind:"error",error:B}));while(!0){let B=H.getSnapshot(),c=Math.max(1,Math.min(oE,Math.max(1,b-B.waitMs))),J,X=new Promise((p)=>{J=setTimeout(()=>p({kind:"heartbeat"}),c),J.unref?.()}),G=await Promise.race([F,X]);if(J)clearTimeout(J);if(G.kind==="heartbeat"){yield{providerAdmission:bf("queued",H.getSnapshot())};continue}if(G.kind==="error"){if(tf(G.error)){if(G.error.reason==="wait_timeout"&&M?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:ef(G.error)}}throw G.error}return yield{providerAdmission:bf("admitted",H.getSnapshot())},G.permit}},A_=(R,u)=>{if(!d())throw w();if(Q)K++;o=void 0;let O=new AbortController,b=_?hE(_,O.signal):O.signal,H=typeof u.timeout==="number"&&Number.isFinite(u.timeout)&&u.timeout>0?Math.max(1,Math.floor(u.timeout)):void 0,L;if(M?.startedAt!==void 0){let c=j()?.recoveryRemainingMs??0;if(c<=0)throw w();L={remainingMs:c,error:new y(M.budgetMs,M.budgetMs)}}let F=eE(u,R,b,T,N);dE(F,R,(c)=>{o=c});let B=f_(this.models,R,P,F,{idleTimeoutMs:u.streamIdleTimeout??Hf,signal:b,abort:(c)=>O.abort(c)});return async function*(){let c,J;try{if(H!==void 0&&(L===void 0||H<L.remainingMs)){let X=new Cf(H);c=setTimeout(()=>O.abort(X),H),c.unref?.()}if(L){let X=L;J=setTimeout(()=>O.abort(X.error),X.remainingMs),J.unref?.()}yield*B}finally{if(c)clearTimeout(c);if(J)clearTimeout(J)}}()},df=this,g=(R)=>({phase:R.phase,reason:R.reason,...R.statusCode!==void 0?{statusCode:R.statusCode}:{},...R.retryAfterMs!==void 0?{retryAfterMs:R.retryAfterMs}:{},...R.nextProbeAt!==void 0?{nextProbeAt:R.nextProbeAt}:{},openDurationMs:R.openDurationMs,sampleCount:R.sampleCount,failureCount:R.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),nf=(R,u)=>({phase:R,reason:u.reason,...u.statusCode!==void 0?{statusCode:u.statusCode}:{},retryAfterMs:u.retryAfterMs,...u.nextProbeAt!==void 0?{nextProbeAt:u.nextProbeAt}:{},openDurationMs:u.openDurationMs,sampleCount:u.sampleCount,failureCount:u.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),S_=(R)=>({phase:"probe",reason:R.reason??"server_error",...R.statusCode!==void 0?{statusCode:R.statusCode}:{},openDurationMs:R.openDurationMs??Rf,...R.sampleCount!==void 0?{sampleCount:R.sampleCount}:{},...R.failureCount!==void 0?{failureCount:R.failureCount}:{},...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),Bf=(R,u,O)=>({providerRetry:{phase:"exhausted",attempt:R,maxRetries:$,reason:u,...O!==void 0?{statusCode:O}:{},...v(),exhaustedBy:"recovery_budget"}}),rf=async function*(R,u,O,b,H){let L,F=!1,B,c,J=R_(R,u);for(let X=0;X<=b;X++){if(!d())break;let G,p;while(!G){let D=J.preflight();while(!D.eligible){if(B=D.reason,c=D.statusCode,!M||!H){let C=nf("rejected",D);throw yield{providerCircuit:C},new hf(C)}yf();let V=j()?.recoveryRemainingMs??0;if(V<=0){let C=w();throw yield Bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}yield{providerCircuit:nf("waiting",D)};let m=Math.min(Math.max(1,D.retryAfterMs),mf,V);if(await ff(m,_,{throwOnAbort:!0}),(j()?.recoveryRemainingMs??0)<=0){let C=w();throw yield Bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}D=J.preflight()}try{p=yield*M_(R,u)}catch(Z){if(Z instanceof y)yield Bf(Q?Math.max(0,K-1):X,B??"timeout",c);throw Z}let k=J.check();if(k.allowed)G=k;else p.release(),p=void 0}let n=G.token;if(G.probe)yield{providerCircuit:S_(G)};try{let D=!1,k=!1;for await(let Z of A_(R,u)){if(Z.providerStall){yield Z;continue}let V=Q?K-1:X;if(V>0&&B&&!D)D=!0,yield{providerRetry:{phase:"recovered",attempt:V,maxRetries:$,reason:B,...c!==void 0?{statusCode:c}:{},...v()}};if(!k){k=!0;let m=J.recordSuccess(n);if(m)yield{providerCircuit:g(m)}}F=!0,O(),yield S(Z,R)}if(!k){let Z=J.recordSuccess(n);if(Z)yield{providerCircuit:g(Z)}}return}catch(D){if(p?.release(),L=D,df.logIdleTimeout(D,F,R),await df.handleAbort(_),D instanceof y){if(F)throw Ff(D),D;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:B??"timeout",...c!==void 0?{statusCode:c}:{},...v(),exhaustedBy:"recovery_budget"}},D}let k=e(D,o);if(F)throw Ff(D),D;let Z=cT(D,o),V=Z?J.recordFailure(n,Z):o&&!pf(D)?J.recordNeutral(n):void 0;if(V)yield{providerCircuit:g(V)};if(!k.retryable||!k.reason){if(X>0&&B)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:B,...c!==void 0?{statusCode:c}:{},...v()}};throw D}B=k.reason,c=k.statusCode;let m=X<b&&d();if(V&&V.phase!=="closed"&&m&&(!M||!H)){let C={...g(V),phase:"rejected"};throw yield{providerCircuit:C},new hf(C)}if(m){yf();let C=Q?K:X+1,u_=gE(C,o,M?{maxDelayMs:qf,maxExponentialDelayMs:qf}:void 0),EE=V&&V.phase!=="closed"?V.retryAfterMs??0:0;if(M&&EE>0&&V)yield{providerCircuit:{...g(V),phase:"waiting"}};let I_=j(),Of=Math.max(u_,EE),r=M?Math.min(Of,I_?.recoveryRemainingMs??Of):Of,Mf={attempt:C,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Mf,delayMs:r,nextRetryAt:Date.now()+r,...v()}},M){let i=r;while(i>0){let _E=Math.min(i,mf);if(await ff(_E,_,{throwOnAbort:!0}),i-=_E,(j()?.recoveryRemainingMs??0)<=0){let Af=w();throw yield{providerRetry:{phase:"exhausted",...Mf,...v(),exhaustedBy:"recovery_budget"}},Af}if(i>0){if(V&&V.phase!=="closed"&&V.nextProbeAt!==void 0){let Af=Math.max(0,V.nextProbeAt-Date.now());if(Af>0)yield{providerCircuit:{...g(V),phase:"waiting",retryAfterMs:Af}}}yield{providerRetry:{phase:"waiting",...Mf,delayMs:r,nextRetryAt:Date.now()+i,...v()}}}}}else await ff(r,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Mf,...v()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{},...v(),...M&&(H||!d())?{exhaustedBy:"attempt_limit"}:{}}}}finally{J.abandon(n),p?.release()}}throw L},cf,fE=!1,Pf=this.config.fallbackModels??[],N_=M&&Pf.length>0?Math.min(Y,$):$;try{for await(let R of rf(this.model,this.config,()=>{fE=!0},N_,Pf.length===0))yield R;return}catch(R){if(cf=R,fE||!tf(R)&&!kf(R)&&!pf(R)&&!e(R,o).retryable)throw R}for(let[R,u]of Pf.entries()){if(!d())break;yield{modelFallback:!0};let O=!1;try{let b=YT(this.config,u),H=uE(b,u),L=R===Pf.length-1,F=M&&!L?Math.min(Y,$):$;for await(let B of rf(H,b,()=>{O=!0},F,L))yield B;return}catch(b){if(cf=b,O||!tf(b)&&!kf(b)&&!pf(b)&&!e(b,o).retryable)throw b}}throw cf}async handleAbort(f){if(f?.aborted)await ff(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;wf.warn("[PiAIChatService] Provider stream idle timeout",{provider:_.provider,model:_.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:E})}getConfig(){return{...this.config}}updateConfig(f){let E={...this.config,...f},_=Xf(E);this.config={...E,maxContextTokens:_.model.contextWindow,maxOutputTokens:E.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,this.providerAdmissionScheduler=E_(this.config)}}function E_(f){if(f.providerRequestAdmissionScheduler)return f.providerRequestAdmissionScheduler;if(f.providerRequestConcurrency===void 0&&f.providerGlobalConcurrency===void 0&&f.providerOwnerConcurrency===void 0)return;let E=f.providerGlobalConcurrency??Number.MAX_SAFE_INTEGER,_=f.providerOwnerConcurrency??Number.MAX_SAFE_INTEGER;return vE({globalMaxInFlight:E,ownerMaxInFlight:_,nonForegroundGlobalMaxInFlight:E,nonForegroundOwnerMaxInFlight:_,internalGlobalMaxInFlight:E,internalDomainMaxInFlight:f.providerRequestConcurrency??q,classLimitsEnabled:!1})}var OT=l("Service");async function Zh(f){let E=f;if(E.provider){let _=TE(E.provider);if(Object.keys(_).length>0)E={...E,customHeaders:{..._,...E.customHeaders}},OT.debug(`Injected ${E.provider} specific headers:`,Object.keys(_))}return VT(E)}function VT(f){return new gf(f)}
|
|
5
|
-
export{zT as
|
|
5
|
+
export{zT as tf,$T as uf,hE as vf,ff as wf,tf as xf,wE as yf,ET as zf,Ph as Af,e as Bf,gE as Cf,gf as Df,Zh as Ef};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ge as a,He as b}from"./chunk-mkvvyq49.js";import"./chunk-b408cqg1.js";import"./chunk-mm05y2c5.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ff as a,Gf as b,Hf as c}from"./chunk-n4q6fvqe.js";import"./chunk-s7axaw78.js";import"./chunk-atema2rc.js";import"./chunk-gxwkwkhp.js";import"./chunk-xnstybjm.js";import"./chunk-mm05y2c5.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{fj as a,gj as b,hj as c,ij as d,jj as e,kj as f}from"./chunk-b408cqg1.js";import"./chunk-mm05y2c5.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var n="verification",r="goal-verification",o="review";function e(t){return t==="verification"||t==="goal-verification"}function i(t){return e(t)||t==="review"}var s=["active","verifying","paused","blocked","usage_limited","budget_limited","complete"],c=["pending","pass","fail","partial"],l=4000,p=3,S=["unable_to_proceed","stopping_here","internal_wait","self_deferral","handoff"],u=3,_=["waiting_dependency","same_task_no_effect","repeated_deferral"],d=3;
|
|
2
|
-
export{n as
|
|
2
|
+
export{n as pg,r as qg,o as rg,e as sg,i as tg,s as ug,c as vg,l as wg,p as xg,S as yg,u as zg,_ as Ag,d as Bg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{S as I}from"./chunk-
|
|
1
|
+
import{S as I}from"./chunk-v4nqv1pr.js";import{_d as M}from"./chunk-1acb8fwq.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
|
|
2
2
|
export{C as y,$ as z,V as A,x as B,i as C,K as D};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{g as i}from"./chunk-
|
|
1
|
+
import{g as i}from"./chunk-skv2gb99.js";import{si as s}from"./chunk-ted1hyvb.js";import"./chunk-xnstybjm.js";import"./chunk-mm05y2c5.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
|
|
2
2
|
${e.path}`}).join(`
|
|
3
3
|
`)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as $i,p as aj,u as bj,S as cj,c as dj,l as ej};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Kf as a,Lf as b,Mf as c,Nf as d}from"./chunk-yqqeh12b.js";import"./chunk-6v2hhgka.js";import"./chunk-nx8xb7dm.js";import"./chunk-96w8ay2h.js";import"./chunk-s7peh6kf.js";import"./chunk-ted1hyvb.js";import"./chunk-xzfc1s6k.js";import"./chunk-r04vwtej.js";import"./chunk-atema2rc.js";import"./chunk-gxwkwkhp.js";import"./chunk-b408cqg1.js";import"./chunk-6m4sqwj0.js";import"./chunk-1xg7qx35.js";import"./chunk-xnstybjm.js";import"./chunk-mm05y2c5.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ae as g,Be as h,Ce as i,De as j,Ee as k,Fe as l,ue as a,ve as b,we as c,xe as d,ye as e,ze as f}from"./chunk-0ktte40x.js";import"./chunk-r04vwtej.js";import"./chunk-xnstybjm.js";import"./chunk-mm05y2c5.js";export{f as syncSession,h as syncAllAcpRemoteScopes,i as syncAll,g as syncAcpRemoteScope,l as searchProjectionText,e as resetProjectionDbCache,j as removeSessionFromProjection,k as rebuildProjectionIndex,d as getProjectionDb,c as getIndexDbPath,a as __setProjectionIOForTesting,b as __resetProjectionIOForTesting};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ud as a,Vd as b,Wd as c,Xd as d,Yd as e,Zd as f,_d as g}from"./chunk-1acb8fwq.js";import"./chunk-z3hpstky.js";import"./chunk-0ktte40x.js";import"./chunk-s7axaw78.js";import"./chunk-8hd4vd20.js";import"./chunk-zfyg3888.js";import"./chunk-s7peh6kf.js";import"./chunk-ted1hyvb.js";import"./chunk-r04vwtej.js";import"./chunk-gxwkwkhp.js";import"./chunk-b408cqg1.js";import"./chunk-xnstybjm.js";import"./chunk-mm05y2c5.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-p5awnndq.js";import"./chunk-562w5zc6.js";import"./chunk-skv2gb99.js";import"./chunk-85jv1sr7.js";import"./chunk-9n90djh7.js";import"./chunk-fa0pyv9k.js";import"./chunk-v4nqv1pr.js";import"./chunk-pq6g92cz.js";import"./chunk-60he05xs.js";import"./chunk-q3y3s16v.js";import"./chunk-rz2wc93t.js";import"./chunk-sca5q3tt.js";import"./chunk-1acb8fwq.js";import"./chunk-z3hpstky.js";import"./chunk-0ktte40x.js";import{Ne as R}from"./chunk-1aw643j2.js";import"./chunk-yqpej45c.js";import{hf as Q}from"./chunk-jxc67ydz.js";import"./chunk-v508x7cg.js";import"./chunk-xshrj2nd.js";import"./chunk-c47db31j.js";import"./chunk-n4q6fvqe.js";import"./chunk-s7axaw78.js";import"./chunk-yqqeh12b.js";import"./chunk-a7gghhvn.js";import"./chunk-ektgnqmh.js";import"./chunk-8hd4vd20.js";import"./chunk-10w2pj3r.js";import"./chunk-p2rxrxct.js";import"./chunk-zfyg3888.js";import"./chunk-6v2hhgka.js";import"./chunk-nx8xb7dm.js";import"./chunk-96w8ay2h.js";import"./chunk-s7peh6kf.js";import"./chunk-ted1hyvb.js";import"./chunk-xzfc1s6k.js";import"./chunk-r04vwtej.js";import"./chunk-atema2rc.js";import"./chunk-gxwkwkhp.js";import{gj as M}from"./chunk-b408cqg1.js";import"./chunk-6m4sqwj0.js";import"./chunk-1xg7qx35.js";import"./chunk-xnstybjm.js";import"./chunk-mm05y2c5.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
+
____ _ _
|
|
3
|
+
| __ )| | __ _ __| | ___
|
|
4
|
+
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
+
| |_) | | (_| | (_| | __/
|
|
6
|
+
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
+
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
+
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
+
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
+
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|