blade-code 0.10.136 → 0.10.138
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-03zfvfen.js +10 -0
- package/dist/{chunk-82x77b2p.js → chunk-14j2dbd6.js} +2 -2
- package/dist/{chunk-24rsvr6e.js → chunk-16648v5c.js} +1 -1
- package/dist/{chunk-77x1rrz9.js → chunk-1bqatrxs.js} +1 -1
- package/dist/chunk-23c4pys6.js +23 -0
- package/dist/{chunk-hx10bph0.js → chunk-2m79vd9p.js} +1 -1
- package/dist/{chunk-w2n1vwzg.js → chunk-2t0wp7gm.js} +2 -2
- package/dist/chunk-303b3x5q.js +1 -0
- package/dist/{chunk-wzkh3e6a.js → chunk-3eskgvpy.js} +1 -1
- package/dist/chunk-3g2z6hae.js +1 -0
- package/dist/chunk-3t5r41yh.js +1 -0
- package/dist/{chunk-ntd69c0k.js → chunk-516adpx6.js} +1 -1
- package/dist/{chunk-9z9v8v4j.js → chunk-56py3ryh.js} +1 -1
- package/dist/chunk-59980a8h.js +1 -0
- package/dist/{chunk-6rvrx275.js → chunk-5bfvdy62.js} +2 -2
- package/dist/chunk-5gy3x011.js +1 -0
- package/dist/{chunk-q0s3gcjm.js → chunk-5j68055h.js} +1 -1
- package/dist/{chunk-91pb41e7.js → chunk-5v1pjexj.js} +1 -1
- package/dist/chunk-5xgyx25z.js +2 -0
- package/dist/{chunk-bdtpq7j9.js → chunk-65c3vjwm.js} +1 -1
- package/dist/{chunk-wj16pvvn.js → chunk-6ezffjq1.js} +1 -1
- package/dist/{chunk-kbnxbb23.js → chunk-6qhbdcse.js} +2 -2
- package/dist/{chunk-nzwh9v6t.js → chunk-7j4s1nrc.js} +1 -1
- package/dist/chunk-7vdf66jp.js +171 -0
- package/dist/chunk-8cnxy251.js +1 -0
- package/dist/chunk-8cqm87j5.js +1 -0
- package/dist/chunk-8py443a5.js +1 -0
- package/dist/{chunk-yacv7f7h.js → chunk-8rccn1y2.js} +1 -1
- package/dist/{chunk-v2qxszks.js → chunk-92n2p24j.js} +2 -2
- package/dist/{chunk-r51afpkk.js → chunk-9m7d3ajv.js} +1 -1
- package/dist/{chunk-mq1mk3v5.js → chunk-a5hkv8er.js} +2 -2
- package/dist/chunk-ar85hxx2.js +5 -0
- package/dist/{chunk-mm1atkae.js → chunk-atdq9btn.js} +2 -2
- package/dist/{chunk-fnc97xg7.js → chunk-awheqy52.js} +2 -2
- package/dist/{chunk-sv5z5sna.js → chunk-az08pq83.js} +1 -1
- package/dist/chunk-bq6d0v5b.js +2 -0
- package/dist/{chunk-c85xvthj.js → chunk-byeq45rv.js} +1 -1
- package/dist/{chunk-g4vgnxh4.js → chunk-d11mqbqk.js} +1 -1
- package/dist/{chunk-vvawhvea.js → chunk-d64b7wta.js} +1 -1
- package/dist/chunk-ddcz0nwv.js +1 -0
- package/dist/{chunk-jc28ddt0.js → chunk-dv2m2xe5.js} +1 -1
- package/dist/chunk-e71y87zg.js +1 -0
- package/dist/{chunk-1p9sjb8d.js → chunk-earhezc8.js} +1 -1
- package/dist/{chunk-qm96k94k.js → chunk-ec7ykyqz.js} +3 -3
- package/dist/{chunk-ffh4c30x.js → chunk-egadh3e9.js} +1 -1
- package/dist/{chunk-jb8stg10.js → chunk-fbrdcveb.js} +1 -1
- package/dist/{chunk-1pmvyqed.js → chunk-fndqbf45.js} +1 -1
- package/dist/chunk-ft1bdqbs.js +3 -0
- package/dist/{chunk-hqwpnb0x.js → chunk-gcg56vaw.js} +2 -2
- package/dist/chunk-h2gp7smy.js +1 -0
- package/dist/{chunk-46jmq302.js → chunk-he0f6h5q.js} +1 -1
- package/dist/{chunk-tev70rzj.js → chunk-hrcz179j.js} +2 -2
- package/dist/{chunk-qjydadex.js → chunk-j21hez8g.js} +5 -5
- package/dist/{chunk-c5rfnzhf.js → chunk-j58wrt5n.js} +4 -4
- package/dist/{chunk-s3a017q7.js → chunk-jb4hmk56.js} +2 -2
- package/dist/{chunk-zy2etr3v.js → chunk-jy7k2dwm.js} +2 -2
- package/dist/{chunk-xtngc0th.js → chunk-k10d8t4f.js} +1 -1
- package/dist/chunk-mc2mr1kn.js +2 -0
- package/dist/{chunk-0qq64xqm.js → chunk-mjnkxem3.js} +4 -4
- package/dist/chunk-n2tfj82m.js +1 -0
- package/dist/{chunk-1cbaqh71.js → chunk-nnas8tdt.js} +2 -2
- package/dist/{chunk-gdnyt8a7.js → chunk-npc7jt96.js} +1 -1
- package/dist/{chunk-mxe4pr8t.js → chunk-nqts5by0.js} +2 -2
- package/dist/chunk-nyw686sf.js +6 -0
- package/dist/chunk-pty1ncam.js +6 -0
- package/dist/chunk-qdjqbgts.js +1 -0
- package/dist/{chunk-cgkbdh2m.js → chunk-r7bv1hmq.js} +1 -1
- package/dist/{chunk-f7hsagj6.js → chunk-rhwkvx96.js} +1 -1
- package/dist/{chunk-na3nregt.js → chunk-t88sfhjj.js} +1 -1
- package/dist/{chunk-13sdjfks.js → chunk-v2fewxvw.js} +2 -2
- package/dist/chunk-wv1mnf2m.js +1 -0
- package/dist/{chunk-sy0vxdc3.js → chunk-y66f1t18.js} +387 -387
- package/dist/{chunk-5sknjz9b.js → chunk-yvmexv2c.js} +1 -1
- package/dist/{chunk-g45camrd.js → chunk-z9qv0d6k.js} +1 -1
- package/dist/{chunk-z3hpstky.js → chunk-zx78c1an.js} +1 -1
- package/dist/web/assets/ChatView-CZLmEMBO.js +63 -0
- package/dist/web/assets/{CodeBlockHighlighter-41xRPXs2.js → CodeBlockHighlighter-6-iPmomS.js} +1 -1
- package/dist/web/assets/{FilePreview-lcc_hL7J.js → FilePreview-D0aSwNF3.js} +7 -7
- package/dist/web/assets/{KanbanBoard-BHgM338V.js → KanbanBoard-xPziptbY.js} +2 -2
- package/dist/web/assets/{MarkdownRenderer-BMAuTkc6.js → MarkdownRenderer-TWNqhwrr.js} +3 -3
- package/dist/web/assets/{ScrollArea-DJq2Kdpi.js → ScrollArea-CSQyGeWr.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-DSe8ePBJ.js → SessionHistorySurface-PRpOrUav.js} +1 -1
- package/dist/web/assets/{SettingsModal-Cih4bWul.js → SettingsModal-Ds-Uf-3r.js} +5 -10
- package/dist/web/assets/{Sidebar-DnWlUKmO.js → Sidebar-D6VyjkRY.js} +2 -2
- package/dist/web/assets/{TaskSwitcher-D3mrXv_i.js → TaskSwitcher-BEsAgt0k.js} +1 -1
- package/dist/web/assets/{TerminalPanel-BNKHhBVM.js → TerminalPanel-C_2lnmKH.js} +1 -1
- package/dist/web/assets/{archive-Dof4YpyT.js → archive-CPBIxP8f.js} +1 -1
- package/dist/web/assets/{arrow-left-DGFXaGox.js → arrow-left-z3DhPgf-.js} +1 -1
- package/dist/web/assets/{calendar-clock-BoxUNOvH.js → calendar-clock-tYt1E6zR.js} +1 -1
- package/dist/web/assets/{chevron-right-Brb1rhaA.js → chevron-right-BGTvSaVS.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-N-VshXV_.js → chevrons-up-down-Jw3ElnjQ.js} +1 -1
- package/dist/web/assets/{clock-3-gdZEKe2U.js → clock-3-v0h4RrLK.js} +1 -1
- package/dist/web/assets/{copy-d9M8JUfQ.js → copy-CF3TUa0u.js} +1 -1
- package/dist/web/assets/{download-CQ-Pwfq0.js → download-ZG8PfhmH.js} +1 -1
- package/dist/web/assets/{external-link-GRAtjoO2.js → external-link-BKCjDDt-.js} +1 -1
- package/dist/web/assets/{folder-CqLD0IBh.js → folder-M-NM2bQG.js} +1 -1
- package/dist/web/assets/index-DC2p1vGD.css +1 -0
- package/dist/web/assets/index-VQVOzFZT.js +203 -0
- package/dist/web/assets/{pause-BqsFgQi0.js → pause-CP_wlUro.js} +1 -1
- package/dist/web/assets/{pencil-Ca9289F-.js → pencil-U3n9D8ed.js} +1 -1
- package/dist/web/assets/{play-DmEPnYDS.js → play-NBWnc2gU.js} +1 -1
- package/dist/web/assets/{plus-kIBLgk0p.js → plus-CmPqJgff.js} +1 -1
- package/dist/web/assets/session-events-DKjIMNKI.js +29 -0
- package/dist/web/assets/{settings-BuSrJl6s.js → settings-CVFpbh_y.js} +1 -1
- package/dist/web/assets/team-B9Na0Ocd.js +6 -0
- package/dist/web/assets/{teamService-B7Fp8Oyg.js → teamService-ZQZLqsjy.js} +1 -1
- package/dist/web/assets/{terminal-Qkr_gcNu.js → terminal-BdmigqIS.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-1dscf8xj.js +0 -23
- package/dist/chunk-1n5d6b5k.js +0 -1
- package/dist/chunk-1qdemrkr.js +0 -1
- package/dist/chunk-83nxcfz3.js +0 -1
- package/dist/chunk-9y7j565j.js +0 -6
- package/dist/chunk-acsfh1cw.js +0 -5
- package/dist/chunk-as8stb2j.js +0 -10
- package/dist/chunk-azaqc1b6.js +0 -1
- package/dist/chunk-e1warjkn.js +0 -171
- package/dist/chunk-g13jmewd.js +0 -1
- package/dist/chunk-g7h0peka.js +0 -3
- package/dist/chunk-gq7fdc8c.js +0 -2
- package/dist/chunk-gwjah260.js +0 -1
- package/dist/chunk-n238rdz8.js +0 -1
- package/dist/chunk-nfzad4te.js +0 -2
- package/dist/chunk-pnanbvn3.js +0 -1
- package/dist/chunk-pz91qga3.js +0 -1
- package/dist/chunk-s4b1r3my.js +0 -1
- package/dist/chunk-t6cajkaj.js +0 -6
- package/dist/chunk-tah2002b.js +0 -1
- package/dist/chunk-tzfd2fza.js +0 -1
- package/dist/chunk-v3veeja5.js +0 -1
- package/dist/chunk-vptn8fhx.js +0 -2
- package/dist/chunk-wj813rcc.js +0 -1
- package/dist/web/assets/ChatView-Bc9twpWM.js +0 -63
- package/dist/web/assets/index-CPpIFWLG.css +0 -1
- package/dist/web/assets/index-DiRs2_w4.js +0 -203
- package/dist/web/assets/session-events-BqQQkbAN.js +0 -29
- package/dist/web/assets/team-QZ9byb3E.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Oj as a,Pj as b,Qj as c,Rj as d,Sj as e,Tj as f}from"./chunk-2t0wp7gm.js";import"./chunk-516adpx6.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jg as a}from"./chunk-ar85hxx2.js";import"./chunk-bq6d0v5b.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";export{a as createChatServiceAsync};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$e as r,Ke as a,Le as b,Me as c,Ne as d,Oe as e,Pe as f,Qe as g,Re as h,Se as i,Te as j,Ue as k,Ve as l,We as m,Xe as n,Ye as o,Ze as p,_e as q}from"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import"./chunk-1bqatrxs.js";import"./chunk-ft1bdqbs.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";export{h as syncSession,j as syncAllAcpRemoteScopes,k as syncAll,i as syncAcpRemoteScope,r as searchProjectionText,f as resetProjectionDbCache,l as removeSessionFromProjection,m as rebuildProjectionIndex,q as readSessionSurfaceHistoryPage,o as readSessionSurfaceCatalogRevision,p as readSessionSurfaceCatalogPage,n as readSessionSurfaceCandidates,g as projectSessionSurfaceSummaryFields,c as getSessionSurfaceHistoryByteLimit,e as getProjectionDb,d as getIndexDbPath,a as __setProjectionIOForTesting,b as __resetProjectionIOForTesting};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-516adpx6.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Jf as N}from"./chunk-mjnkxem3.js";import{rh as $}from"./chunk-ec7ykyqz.js";import{Vi as _}from"./chunk-dv2m2xe5.js";import{tj as Y,vj as Z}from"./chunk-ft1bdqbs.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
|
|
4
|
-
export{O as
|
|
4
|
+
export{O as rf,y as sf,j as tf,C as uf};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Bk as $,Zj as F}from"./chunk-t88sfhjj.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
|
|
2
2
|
`,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
|
|
3
3
|
export{_ as j};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{bf as w0,cf as hT}from"./chunk-awheqy52.js";import{vh as MT}from"./chunk-1bqatrxs.js";import{vj as yT}from"./chunk-ft1bdqbs.js";import{Dk as RT,Zj as X0,fk as E,hk as D,ik as i,kk as c,lk as j0,mk as bT,nk as ST,ok as fT,sk as k,uk as D0,vk as a}from"./chunk-t88sfhjj.js";import{Ek as Z0}from"./chunk-516adpx6.js";import{createHash as F_}from"node:crypto";import{readdir as k0,stat as A0}from"node:fs/promises";import G0 from"node:path";import{createHash as oT,randomBytes as u0}from"node:crypto";import{chmod as p0,link as rT,lstat as p,mkdir as eT,open as l,readdir as l0,realpath as v0,unlink as U0}from"node:fs/promises";import K from"node:path";function dT(){return typeof globalThis.Bun<"u"}function sT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.prepare($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>T.pragma($,{simple:!0}),close:()=>T.close()}}function aT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.query($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>{let _=T.query(`PRAGMA ${$}`).get();if(!_)return;let G=Object.values(_);return G.length===1?G[0]:_},close:()=>T.close()}}function tT(T){return[`PRAGMA busy_timeout=${T};`,"PRAGMA journal_mode=WAL;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
|
|
2
2
|
`)}async function t(T,$={}){let _=$.busyTimeoutMs??5000;if(!Number.isSafeInteger(_)||_<0)return null;let G=null;try{if(dT()){let{Database:Y}=await import("bun:sqlite");G=aT(new Y(T))}else{let Q=(await import("better-sqlite3")).default;G=sT(new Q(T))}return G.exec(tT(_)),G}catch{try{G?.close()}catch{}return null}}var T$="surface-workspaces-v1",n0=/^[a-f0-9]{64}$/,$$=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,_$=1024,G$=".surface-workspaces-v1.capacity.sqlite",i0=/^\.tmp-acp-remote-workspace-([1-9][0-9]*)-[a-f0-9]{32}\.pending$/;class H extends Error{name="AcpRemoteWorkspaceReferenceError";code;retryable;constructor(T){let $=T==="session_surface_not_found"?{message:"Session surface was not found",retryable:!1}:T==="session_surface_capacity"?{message:"Session surface capacity is exhausted",retryable:!0}:{message:"Session surface state is invalid",retryable:!1};super($.message);this.code=T,this.retryable=$.retryable,Object.setPrototypeOf(this,new.target.prototype)}}var P,o=new Map;function c0(T){return K.join(String(T),T$)}async function d0(T,$){let _=D($);if(i(_.collisionIdentity)!==String(T))throw new H("session_surface_state_invalid");let G=a0(_.exactIdentity),X=c0(T);return await Y$(T,X),X$(X,()=>Q$(X,async()=>{await B$(X);let Y=await s0(T,X,!0),Q=Y.recordsByDigest.get(G);if(Q)return Q.workspaceRef;if(Y.recordsByDigest.size>=_$)throw new H("session_surface_capacity");let Z=K.join(X,`${G}.json`),U=new Set(Y.workspaceRefToDigest.keys());for(let V=0;V<32;V+=1){let g=M$();if(U.has(g))continue;return J$(T,X,Z,_,{version:1,exactIdentityDigest:G,workspaceRef:g})}throw new H("session_surface_state_invalid")}))}async function X$(T,$){let _=o.get(T)??Promise.resolve(),G=()=>{return},X=new Promise((Q)=>{G=Q}),Y=_.catch(()=>{return}).then(()=>X);o.set(T,Y),await _.catch(()=>{return});try{return await $()}finally{if(G(),o.get(T)===Y)o.delete(T)}}async function Y$(T,$){try{await V0($,String(T))}catch(_){if(x(_)!=="ENOENT"){if(_ instanceof H)throw _;throw new H("session_surface_state_invalid")}try{await eT($,{recursive:!1,mode:448})}catch(G){if(x(G)!=="EEXIST")throw new H("session_surface_state_invalid")}await V0($,String(T)),await h(String(T))}}async function Q$(T,$){await P?.beforeCapacityLockAttempt?.();let _=await Z$(T),G=!1,X,Y,Q;try{_.database.exec("BEGIN IMMEDIATE;"),G=!0,await P?.afterCapacityLockAcquired?.(),Q={value:await $()}}catch(Z){X=Z}if(G)try{await U$(_),_.database.exec("ROLLBACK;")}catch(Z){Y=Z}try{_.database.close()}catch(Z){if(!G)Y=Z}if(await _.identityHandle.close().catch(()=>{return}),Y!==void 0)throw new H("session_surface_state_invalid");if(X instanceof H)throw X;if(X!==void 0||!Q)throw new H("session_surface_state_invalid");return Q.value}async function Z$(T){let $=K.join(T,G$),_=null,G;try{let X=!1;try{let Q=await l($,"wx",384);X=!0,await Q.sync(),await Q.close()}catch(Q){if(x(Q)!=="EEXIST")throw Q}if(await m($,T),X)await h(T);G=await l($,"r"),await n(G,$,T);let Y=await G.stat({bigint:!0});if(_=await t($,{busyTimeoutMs:30000}),!_)throw new H("session_surface_state_invalid");if(_.exec("PRAGMA locking_mode=NORMAL;"),_.exec("PRAGMA synchronous=FULL;"),_.exec("PRAGMA busy_timeout=30000;"),process.platform!=="win32")await p0($,384);return await n(G,$,T),await V$($,T),{database:_,identity:Y,identityHandle:G,path:$}}catch(X){await G?.close().catch(()=>{return});try{_?.close()}catch{}if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}async function U$(T){await n(T.identityHandle,T.path,K.dirname(T.path));let $=await T.identityHandle.stat({bigint:!0});if(!B0(T.identity,$))throw new H("session_surface_state_invalid")}async function V$(T,$){for(let _ of["-journal","-shm","-wal"]){let G=`${T}${_}`;try{if(process.platform!=="win32")await p0(G,384);await m(G,$)}catch(X){if(x(X)!=="ENOENT"){if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}}}async function B$(T){let $=await l0(T,{withFileTypes:!0}),_=!1;for(let G of $){if(!i0.test(G.name))continue;let X=K.join(T,G.name);await m(X,T),await U0(X),_=!0}if(_)await h(T)}async function s0(T,$,_){try{await V0($,String(T))}catch(Q){if(!_&&x(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};if(Q instanceof H)throw Q;throw new H("session_surface_state_invalid")}let G;try{G=await l0($,{withFileTypes:!0})}catch(Q){if(!_&&x(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};throw new H("session_surface_state_invalid")}let X=new Map,Y=new Map;for(let Q of G){if(i0.test(Q.name)){await m(K.join($,Q.name),$);continue}if(!Q.name.endsWith(".json"))continue;let Z=K.basename(Q.name,".json");if(!n0.test(Z))throw new H("session_surface_state_invalid");let U=K.join($,Q.name),V=await g$(U,$);if(V.exactIdentityDigest!==Z)throw new H("session_surface_state_invalid");if(X.has(Z))throw new H("session_surface_state_invalid");let g=Y.get(V.workspaceRef);if(g&&g!==Z)throw new H("session_surface_state_invalid");X.set(Z,V),Y.set(V.workspaceRef,Z)}return{recordsByDigest:X,workspaceRefToDigest:Y}}async function g$(T,$){let _;try{await m(T,$),_=await l(T,"r"),await n(_,T,$);let G=await _.readFile({encoding:"utf8"});return H$(G)}catch(G){if(G instanceof H&&G.code==="session_surface_not_found")throw G;if(x(G)==="ENOENT")throw new H("session_surface_not_found");throw new H("session_surface_state_invalid")}finally{await _?.close()}}function H$(T){let $;try{$=JSON.parse(T)}catch{throw new H("session_surface_state_invalid")}if(!O$($))throw new H("session_surface_state_invalid");return $}function O$(T){if(!T||typeof T!=="object"||Array.isArray(T))return!1;let $=T,_=Object.keys($).sort();if(_.length!==3||_[0]!=="exactIdentityDigest"||_[1]!=="version"||_[2]!=="workspaceRef")return!1;return $.version===1&&typeof $.exactIdentityDigest==="string"&&n0.test($.exactIdentityDigest)&&typeof $.workspaceRef==="string"&&$$.test($.workspaceRef)}function a0(T){return oT("sha256").update(`acp-remote-workspace-exact-identity\x00${T}`).digest("hex")}function M$(){return`acp-remote-workspace:${u0(32).toString("base64url")}`}function C$(){return`.tmp-acp-remote-workspace-${process.pid}-${u0(16).toString("hex")}.pending`}async function V0(T,$){if(K.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await p(T);if(_.isSymbolicLink()||!_.isDirectory())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=t0(_.mode);if(process.platform!=="win32"&&G!==448)throw new H("session_surface_state_invalid");await g0(T,$,K.basename(T))}async function m(T,$){if(K.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await p(T);if(_.isSymbolicLink()||!_.isFile())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=t0(_.mode);if(process.platform!=="win32"&&G!==384)throw new H("session_surface_state_invalid");await g0(T,$,K.basename(T))}async function n(T,$,_){let[G,X]=await Promise.all([T.stat({bigint:!0}),p($,{bigint:!0})]);if(K.dirname($)!==_||X.isSymbolicLink()||!X.isFile()||!G.isFile()||X.dev!==G.dev||X.ino!==G.ino)throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&(Number(X.uid)!==process.getuid()||Number(G.uid)!==process.getuid()))throw new H("session_surface_state_invalid");let Y=Number(X.mode&BigInt(511)),Q=Number(G.mode&BigInt(511));if(process.platform!=="win32"&&(Y!==384||Q!==384))throw new H("session_surface_state_invalid");await g0($,_,K.basename($))}async function g0(T,$,_){let G=await v0(T),X=await v0($);if(G!==K.join(X,_))throw new H("session_surface_state_invalid")}async function h(T){if(!F$(process.platform))return;try{if(P?.syncDirectory){await P.syncDirectory(T);return}await L$(T)}catch{throw new H("session_surface_state_invalid")}}function F$(T){return T!=="win32"}async function L$(T){let $=await l(T,"r");try{await $.sync()}finally{await $.close()}}async function J$(T,$,_,G,X){let Y=K.join($,C$()),Q,Z,U=!1,V=!1,g,O;try{Q=await l(Y,"wx",384),await Q.writeFile(JSON.stringify(X),"utf8"),await Q.sync(),await n(Q,Y,$),Z=await Q.stat({bigint:!0}),await Q.close(),Q=void 0,await P?.beforePublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y});try{await rT(Y,_),U=!0}catch(M){if(x(M)!=="EEXIST")throw M;g=await N$(T,G)}if(U){let M=await p(_,{bigint:!0});if(!Z||!B0(Z,M))throw new H("session_surface_state_invalid");await m(_,$),await h($),V=!0,g=X.workspaceRef;try{await P?.afterPublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y})}catch{}}}catch(M){O=M}finally{await Q?.close().catch(()=>{return})}if(O!==void 0&&U&&!V&&Z)try{let M=await p(_,{bigint:!0});if(B0(Z,M))await U0(_),await h($)}catch{}try{if(await U0(Y),!V)await h($)}catch(M){if(x(M)!=="ENOENT"&&O===void 0&&!V)O=M}if(O instanceof H)throw O;if(O!==void 0||g===void 0)throw new H("session_surface_state_invalid");return g}async function N$(T,$){let _=c0(T),G=await s0(T,_,!0),X=a0(D($).exactIdentity),Y=G.recordsByDigest.get(X);if(!Y)throw new H("session_surface_state_invalid");return Y.workspaceRef}function B0(T,$){return BigInt(T.dev)===BigInt($.dev)&&BigInt(T.ino)===BigInt($.ino)}function x(T){return T!==null&&typeof T==="object"&&"code"in T&&typeof T.code==="string"?T.code:void 0}function t0(T){return typeof T==="bigint"?Number(T&BigInt(511)):T&511}import*as f from"node:path";var $T=50,_T=100,z$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),I$=new Set(["high","medium","low"]),GT=/^[A-Za-z0-9_-]+$/,K$=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,W$=/^acp-remote-exact-path:[a-f0-9]{64}$/;function XT(T){return typeof T==="string"&&K$.test(T)&&Number.isFinite(Date.parse(T))}function o0(T){return typeof T==="string"&&f.isAbsolute(T)}function r0(T){return typeof T==="string"&&W$.test(T)}function j$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function k$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function A$(T){try{if(!GT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($);if(_.version!==1||_.kind!==void 0&&_.kind!=="local"||typeof _.includeSubagents!=="boolean"||_.archived!==void 0&&typeof _.archived!=="boolean"||!(_.cwd===null||o0(_.cwd))||!XT(_.lastMessageTime)||!o0(_.projectPath)||!k(_.sessionId))throw Error("invalid");return{version:1,kind:"local",cwd:_.cwd===null?null:f.resolve(_.cwd),includeSubagents:_.includeSubagents,archived:_.archived??!1,lastMessageTime:_.lastMessageTime,projectPath:f.resolve(_.projectPath),sessionId:_.sessionId}}catch{throw Error("Invalid session cursor")}}function x$(T){try{if(!GT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($),G=Object.keys(_),X=new Set(["version","kind","exactIdentity","includeSubagents","archived","lastMessageTime","workspaceIdentity","sessionId"]);if(G.some((Y)=>!X.has(Y))||_.version!==1||_.kind!=="remote"||typeof _.includeSubagents!=="boolean"||typeof _.archived!=="boolean"||!(_.exactIdentity===null||r0(_.exactIdentity))||!XT(_.lastMessageTime)||!r0(_.workspaceIdentity)||!k(_.sessionId))throw Error("invalid");return{version:1,kind:"remote",exactIdentity:_.exactIdentity??null,includeSubagents:_.includeSubagents,archived:_.archived,lastMessageTime:_.lastMessageTime,workspaceIdentity:_.workspaceIdentity,sessionId:_.sessionId}}catch{throw Error("Invalid remote session cursor")}}function v(T){let $="";for(let _=0;_<T.length;_+=1)$+=T.charCodeAt(_).toString(16).padStart(4,"0");return $}function E$(T){if(!T.cursor)return;let $=A$(T.cursor);if($.cwd!==T.cwd||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Session cursor scope does not match this query");return $}function q$(T){if(!T.cursor)return;let $=x$(T.cursor);if($.exactIdentity!==T.exactIdentity||T.exactIdentity!==null&&$.workspaceIdentity!==T.exactIdentity||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Remote session cursor scope does not match this query");return $}function n_(T={}){let{cwd:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T;if($!==void 0&&!f.isAbsolute($))throw Error("Session catalog cwd must be absolute");let Q=G===void 0?$T:G;if(!Number.isInteger(Q)||Q<1||Q>_T)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:$===void 0?null:f.resolve($),cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function i_(T={}){let{descriptor:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T,Q=G===void 0?$T:G;if(!Number.isInteger(Q)||Q<1||Q>_T)throw Error("Session catalog limit must be an integer from 1 to 100");return{descriptor:$,exactIdentity:$?.exactIdentity??null,cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function c_(T={}){let $=e0(T.taskStatus,z$,"task status"),_=e0(T.taskPriority,I$,"task priority"),G=TT(T.taskDueAfter,"taskDueAfter"),X=TT(T.taskDueBefore,"taskDueBefore");return D$(G,X),{...$?{taskStatuses:$}:{},..._?{taskPriorities:_}:{},...G?{taskDueAfter:G}:{},...X?{taskDueBefore:X}:{}}}function e0(T,$,_){if(T===void 0)return;let G=Array.isArray(T)?T:[T];if(G.length===0)return;let X=new Set;for(let Y of G){if(typeof Y!=="string"||!$.has(Y))throw Error(`Invalid session ${_} filter`);X.add(Y)}return[...X].sort()}function TT(T,$){if(T===void 0)return;if(typeof T!=="string"||!Number.isFinite(Date.parse(T)))throw Error(`Invalid session ${$} filter`);return new Date(T).toISOString()}function D$(T,$){if(T!==void 0&&$!==void 0&&T>$)throw Error("Session task due range is inverted")}function w$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.projectPath<$.projectPath)return-1;if(T.projectPath>$.projectPath)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function b$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.workspaceIdentity<$.workspaceIdentity)return-1;if(T.workspaceIdentity>$.workspaceIdentity)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function d_(T,$){let _=[...T],G=E$($);if(G)_=_.filter((Q)=>w$(Q,{sessionId:G.sessionId,projectPath:G.projectPath,lastMessageTime:G.lastMessageTime})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:j$({version:1,kind:"local",cwd:$.cwd,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,projectPath:Y.projectPath,sessionId:Y.sessionId})}}function s_(T,$){let _=[...T],G=q$($);if(G)_=_.filter((Q)=>b$(Q,{sessionId:G.sessionId,projectPath:Q.projectPath,lastMessageTime:G.lastMessageTime,workspaceIdentity:G.workspaceIdentity})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:k$({version:1,kind:"remote",exactIdentity:$.exactIdentity,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,workspaceIdentity:Y.workspaceIdentity,sessionId:Y.sessionId})}}function S$(T){return T.type==="message_created"||T.type==="token_budget_handoff_recorded"||T.type==="part_created"||T.type==="part_updated"||T.type==="turn_started"||T.type==="turn_completed"||T.type==="turn_aborted"||T.type==="turn_recovery_acknowledged"||T.type==="interaction_requested"||T.type==="interaction_responded"||T.type==="interaction_recovered"||T.type==="review_started"||T.type==="review_completed"}function H0(T){return T.type==="message_created"&&T.data.role==="user"&&(T.data.inboxMessageId!==void 0||T.data.parentMessageId===void 0)}function O0(T,$){let _=T.find((G)=>H0(G)&&G.data.messageId===$);if(!_)throw Error(`Rewind checkpoint not found: ${$}`);return{messageId:$,preview:YT(T,$),createdAt:_.data.createdAt}}function YT(T,$){let _=T.flatMap((G)=>{if(G.type!=="part_created"||G.data.messageId!==$)return[];if(G.data.partType==="text"){let X=G.data.payload;return typeof X.text==="string"?[X.text]:[]}if(G.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(_.length<=160)return _;return`${_.slice(0,160)}...`}function QT(T,$){O0(T,$);let _=T.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),G=T[_],X=G?.type==="message_created"?G.data.inboxMessageId:void 0,Y=new Set(T.flatMap((Q)=>Q.type==="turn_started"&&X&&Q.data.inputMessageIds?.includes(X)?[Q.data.turnId]:[]));return T.filter((Q,Z)=>{if((Q.type==="turn_started"||Q.type==="turn_completed"||Q.type==="turn_aborted"||Q.type==="turn_recovery_acknowledged")&&Y.has(Q.data.turnId))return!1;return Z<_||!S$(Q)})}function u(T){let $=[];for(let _ of T){if(_.type!=="session_rewound"){$.push(_);continue}if(O0($,_.data.targetMessageId),_.data.mode!=="code")$=QT($,_.data.targetMessageId)}return $}function t_(T){let $=u(T);return $.filter(H0).map((_)=>({messageId:_.data.messageId,preview:YT($,_.data.messageId),createdAt:_.data.createdAt})).reverse()}function o_(T,$){let _=u(T),G=O0(_,$),X=_.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),Y=_.slice(X);return{checkpoint:G,projectedEntries:QT(_,$),removedTurns:Y.filter(H0).length,snapshotMessageIds:Y.flatMap((Q)=>Q.type==="part_created"&&Q.data.partType==="tool_call"?[Q.data.partId]:[])}}import{createHash as i$}from"node:crypto";var e_={clientVisible:!1};function ZT(T){if(T.metadata&&typeof T.metadata==="object"&&!Array.isArray(T.metadata)&&T.metadata.clientVisible===!1)return!1;return!(T.role==="user"&&typeof T.content==="string"&&T.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&T.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{StringDecoder as y$}from"node:string_decoder";var $1=1048576;function M0(T,$){let _=$;while(_<T.length&&(T[_]&192)===128)_+=1;return _}class C0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor(T=1048576){this.maxBytes=T;if(!Number.isSafeInteger(T)||T<=0)throw Error("maxBytes must be a positive safe integer")}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);if($.length===0)return;if(this.totalBytes+=$.length,$.length>this.maxBytes){this.retainOversizedChunkTail($);return}this.chunks.push($),this.retainedBytes+=$.length,this.trimToLimit(),this.compactChunks()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),retainedBytes:this.retainedBytes,omittedBytes:this.omittedBytes,totalBytes:this.totalBytes}}consume(){let T=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,T}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail(T){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let $=M0(T,T.length-this.maxBytes);if(this.omittedBytes+=$,$===T.length)return;let _=Buffer.from(T.subarray($));this.chunks.push(_),this.retainedBytes=_.length}trimToLimit(){let T=!1;while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let _=this.retainedBytes-this.maxBytes;if($.length<=_){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length,T=!0;continue}let G=M0($,_);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G,T=!0}if(T)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let T=this.chunks[0];if(T.length===0){this.chunks.shift();continue}let $=M0(T,0);if($===0)return;if(this.retainedBytes-=$,this.omittedBytes+=$,$===T.length)this.chunks.shift();else{this.chunks[0]=T.subarray($);return}}}compactChunks(){if(this.chunks.length<=32)return;let T=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,T.length>0)this.chunks.push(T)}}var r={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},R={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},UT={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},f$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},R$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:r,summaryTemplate:(T)=>`Successfully processed ${T} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:r,summaryTemplate:(T)=>`Package operation completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:R,summaryTemplate:(T)=>`Build completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:UT},{pattern:/^git\s+(status|branch|remote)/i,config:R},{pattern:/^git\s+(log|diff|show)/i,config:UT},{pattern:/^(ls|dir|tree)\s+/i,config:R,summaryTemplate:(T)=>`Listed ${T} items`},{pattern:/^find\s+/i,config:R,summaryTemplate:(T)=>`Found ${T} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:R,summaryTemplate:(T)=>`Found ${T} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:r,summaryTemplate:(T)=>`Docker operation completed (${T} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:r,summaryTemplate:(T)=>`Python package operation completed (${T} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:R,summaryTemplate:(T)=>`Rust operation completed (${T} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:R,summaryTemplate:(T)=>`Go operation completed (${T} lines)`}];function VT(T,$,_){let G=$,X=_??T.length;if(G>0){let Y=T.charCodeAt(G);if(Y>=56320&&Y<=57343)G+=1}if(X<T.length){let Y=T.charCodeAt(X-1);if(Y>=55296&&Y<=56319)X-=1}return T.slice(G,X)}class F0{static getConfigForCommand(T){for(let{pattern:$,config:_,summaryTemplate:G}of R$)if($.test(T))return{config:_,summaryTemplate:G};return{config:f$}}static truncate(T,$){let{config:_,summaryTemplate:G}=this.getConfigForCommand($);return this.truncateWithConfig(T,_,G)}static truncateWithConfig(T,$,_){let G=T.length,X=T.split(`
|
|
3
3
|
`),Y=X.length;if(Y<=$.maxLines&&G<=$.maxChars)return{content:T,truncated:!1,originalLines:Y,originalChars:G};let Q=X.slice(0,$.keepHead),Z=X.slice(-$.keepTail),U=Y-$.keepHead-$.keepTail,V=Q.join(`
|
|
4
4
|
`);if(V+=`
|
|
@@ -335,4 +335,4 @@ ranked_archive AS (
|
|
|
335
335
|
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
336
336
|
WHERE parts_fts MATCH ? AND source_kind = 'local'
|
|
337
337
|
ORDER BY timestamp DESC LIMIT ?`,Z=T.prepare(Q);return _?Z.all(Y,_,G):Z.all(Y,G)}
|
|
338
|
-
export{d0 as
|
|
338
|
+
export{d0 as ie,u as je,t_ as ke,o_ as le,d as me,j as ne,v as oe,E$ as pe,q$ as qe,n_ as re,i_ as se,c_ as te,w$ as ue,b$ as ve,d_ as we,s_ as xe,e_ as ye,ZT as ze,$1 as Ae,C0 as Be,F0 as Ce,U1 as De,V1 as Ee,B1 as Fe,CT as Ge,FT as He,J0 as Ie,KT as Je,y1 as Ke,h1 as Le,P1 as Me,vT as Ne,K_ as Oe,W_ as Pe,pT as Qe,DT as Re,w_ as Se,m1 as Te,b_ as Ue,v1 as Ve,u1 as We,p1 as Xe,f_ as Ye,l1 as Ze,n1 as _e,i1 as $e};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{lg as wf}from"./chunk-bq6d0v5b.js";import{$i as yf,Zi as t_,_i as lf,aj as R_,bj as $f,dj as Lf,fj as Hf,hj as g,ij as Kf,kj as Uf,lj as Cf,nj as s}from"./chunk-fbrdcveb.js";import{vj as a}from"./chunk-ft1bdqbs.js";import{Fj as DE,Hj as zf}from"./chunk-jb4hmk56.js";import{Kj as nE}from"./chunk-65c3vjwm.js";var B_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},tE=(f)=>B_[f]||{};var b_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function cf(f){return typeof f==="string"&&b_.has(f)}function LT(f){if(!f.aborted)return;if(cf(f.reason))return f.reason;return"user-cancel"}function ZT(f){if(cf(f))return!0;if(!(f instanceof Error))return!1;if(f.name==="AbortError")return!0;if(f instanceof DOMException&&f.name==="AbortError")return!0;if(f.message.includes("aborted"))return!0;return!1}function RE(...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[A,M]of h)A.removeEventListener("abort",M)};h.set(x,N)}for(let[x,N]of h)x.addEventListener("abort",N,{once:!0});return T.signal}function _f(f,E,_){let T=_?.throwOnAbort??!1;if(E?.aborted){if(T)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((h,x)=>{let N,A=setTimeout(()=>{if(E&&N)E.removeEventListener("abort",N);h()},f);if(E)N=()=>{if(clearTimeout(A),T)x(new DOMException("Aborted","AbortError"));else h()},E.addEventListener("abort",N,{once:!0})})}var O_=a("Chat"),V_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function AE(f){if(typeof f==="string")return f;return f.filter((E)=>E.type==="text").map((E)=>E.text).join(`
|
|
2
|
+
`)}function j_(f){if(!f)return{};try{let E=JSON.parse(f);return E&&typeof E==="object"&&!Array.isArray(E)?E:{}}catch{return O_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function X_(f){let E=f.match(/^data:([^;,]+);base64,(.+)$/s);return E?{mimeType:E[1],data:E[2]}:void 0}async function c_(f,E){let _=X_(f);if(_)return{type:"image",..._};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let T=await fetch(f,{signal:E});if(!T.ok)throw Error(`Failed to load image ${f}: HTTP ${T.status}`);return{type:"image",mimeType:T.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await T.arrayBuffer()).toString("base64")}}async function PE(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 ME(f,E,_,T,h){let x=f.filter((S)=>S.role==="system").map((S)=>AE(S.content)).filter(Boolean).join(`
|
|
3
|
+
|
|
4
|
+
`),N=[],A=E.input.includes("image");for(let S of f){if(S.role==="system")continue;if(S.role==="user"){let t=typeof S.content==="string"?S.content:await PE(S.content,A,T);N.push({role:"user",content:t,timestamp:Date.now()});continue}if(S.role==="assistant"){let t=[];if(S.reasoningContent?.trim())t.push({type:"thinking",thinking:S.reasoningContent});let P=AE(S.content);if(P)t.push({type:"text",text:P});for(let D of S.tool_calls??[]){if(!("function"in D))continue;t.push({type:"toolCall",id:D.id,name:D.function.name,arguments:j_(D.function.arguments)})}N.push({role:"assistant",content:t,api:E.api,provider:E.provider,model:E.id,usage:V_,stopReason:S.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}N.push({role:"toolResult",toolCallId:S.tool_call_id??"",toolName:S.name??"unknown",content:typeof S.content==="string"?[{type:"text",text:S.content}]:await PE(S.content,A,T),isError:!1,timestamp:Date.now()})}let M=_?.filter((S)=>!h||S.name===h).map((S)=>({name:S.name,description:S.description,parameters:S.parameters,constrainedSampling:S.constrainedSampling})).sort((S,t)=>S.name<t.name?-1:S.name>t.name?1:0);return{...x?{systemPrompt:x}:{},messages:N,...M?.length?{tools:M}:{}}}function NE(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 A=new Set(h.map((t)=>t.id)),M=x.filter((t)=>t.tool_call_id&&A.has(t.tool_call_id)),S=new Set(M.map((t)=>t.tool_call_id));if(A.size===h.length&&M.length===A.size&&S.size===A.size)E.push(T,...M);_=N-1}return E}function uE(f){return f.some((E)=>E.role==="assistant"&&Boolean(E.tool_calls?.length)&&!E.reasoningContent?.trim())}function IE(f,E){return{...f,...E.baseUrl?{baseUrl:DE(f.api,E.baseUrl)}:{},...E.maxOutputTokens?{maxTokens:E.maxOutputTokens}:{}}}function Jf(f){let E=f.modelCatalog??zf();return{models:E.models,model:IE(E.getModel(f.provider,f.model),f)}}function HE(f,E){let _=f.modelCatalog??zf();return IE(_.getModel(E.provider,E.model),f)}import{createHash as z_}from"node:crypto";var J_=32,W_=1000,$_=512,L_=2000,G_=0.1,k_=0.05,Z_=0.9,Q_=300000,K_=3600000;class Wf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let E=f.now??Date.now(),_=C_(f,E),T=this.sessions.get(f.sessionId);if(_.callCount=(T?.callCount??0)+1,this.touch(f.sessionId,_),T&&_.contextEpoch!==T.contextEpoch)return;if(!T||T.cacheReadTokens<W_)return;let h=T.cacheReadTokens-_.cacheReadTokens,x=Math.min(L_,Math.max($_,T.cacheReadTokens*G_));if(h<x||_.cacheReadTokens>=T.cacheReadTokens*(1-k_))return;let N=_.modelIdentity!==T.modelIdentity,A=_.systemHash!==T.systemHash,M=_.toolsHash!==T.toolsHash,S=_.policyHash!==T.policyHash;if(!(N||A||M||S)&&_.promptTokens<T.promptTokens*Z_)return;let P=Math.max(0,E-T.recordedAt),D=T.retention==="long"?K_:Q_,Y=N?"model_changed":A?"system_prompt_changed":M?"tools_changed":S?"request_policy_changed":P>=D?"ttl_expired":"server_side",$=F_(T,_);return{reason:Y,previousCacheReadTokens:T.cacheReadTokens,cacheReadTokens:_.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:h,elapsedMs:P,callNumber:_.callCount,systemPromptChanged:A,systemCharDelta:_.systemChars-T.systemChars,toolsChanged:M,addedToolCount:$.added,removedToolCount:$.removed,changedToolCount:$.changed,modelChanged:N,requestPolicyChanged:S}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,E){this.sessions.delete(f),this.sessions.set(f,E);while(this.sessions.size>J_){let _=this.sessions.keys().next().value;if(_===void 0)break;this.sessions.delete(_)}}}function C_(f,E){let _=[...f.tools??f.context.tools??[]].map((T)=>({identityHash:Tf(T.name),contractHash:Tf(hf(T))})).sort((T,h)=>T.identityHash<h.identityHash?-1:T.identityHash>h.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:Tf(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:Tf(hf(_)),toolFingerprints:_,policyHash:Tf(hf(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:E,callCount:1}}function F_(f,E){let _=new Map(f.toolFingerprints.map((h)=>[h.identityHash,h.contractHash])),T=new Map(E.toolFingerprints.map((h)=>[h.identityHash,h.contractHash]));return{added:[...T.keys()].filter((h)=>!_.has(h)).length,removed:[..._.keys()].filter((h)=>!T.has(h)).length,changed:[...T].filter(([h,x])=>_.has(h)&&_.get(h)!==x).length}}function hf(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(hf).join(",")}]`;let E=f;return`{${Object.keys(E).sort().map((_)=>`${JSON.stringify(_)}:${hf(E[_])}`).join(",")}}`}function Tf(f){return z_("sha256").update(f).digest("hex")}import{randomBytes as o_}from"node:crypto";import{createHmac as v_}from"node:crypto";function s_(f){try{let E=new URL(f);if(E.hash="",E.hostname=E.hostname.toLowerCase(),E.searchParams.sort(),E.pathname!=="/")E.pathname=E.pathname.replace(/\/+$/,"");return E.toString()}catch{return f.trim().replace(/\/+$/,"")}}function w_(f){if(!f)return[];return Object.entries(f).map(([E,_])=>[E.trim().toLowerCase(),_.trim()]).sort(([E],[_])=>E.localeCompare(_))}function uf(f,E,_){let T=JSON.stringify([f.provider.trim(),String(f.api).trim(),s_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",w_(f.customHeaders),_]);return v_("sha256",Buffer.from(E)).update(T).digest("hex")}var p_=60000,m_=4,q_=0.8;var If=300000,Gf=600000;var UE=128,YE=256,g_=1800000,Df=50;class tf extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function Rf(f){return f instanceof tf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function d(f,E){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:E}function l_(f,E){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:E}function y_(f,E){return uf(f,E,{providerCircuitOpenDurationMs:f.openDurationMs})}function xf(f){let E=0;for(let _ of f)if(_.failure)E++;return E}function BE(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function bE(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Lf)}class VE{#x=new Map;#t=new WeakMap;#f;#_;#h;#T;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):o_(32),this.#_=f.now??(()=>performance.now()),this.#h=f.wallNow??f.now??Date.now,this.#T={maxEntries:Math.min(d(f.maxEntries,UE),UE),maxWindowEntries:Math.min(d(f.maxWindowEntries,YE),YE),windowMs:d(f.windowMs,p_),minSamples:d(f.minSamples,m_),errorRateThreshold:l_(f.errorRateThreshold,q_),idleTtlMs:d(f.idleTtlMs,g_)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#A();let E=this.#_();this.#B(E);let _=y_(f,this.#f),T=this.#x.get(_);if(T)return T.lastTouchedAt=E,this.#E(T,f.probeLeaseMs);if(this.#x.size>=this.#T.maxEntries)this.#I();if(this.#x.size>=this.#T.maxEntries)return this.#A();let h={key:_,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:E,detached:!1};return this.#x.set(_,h),this.#E(h,f.probeLeaseMs)}#E(f,E){let _=this,T=Math.max(If,Math.min(d(E,If),Gf));return{preflight:()=>_.#P(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:()=>_.#X(f)}}#A(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let E=Object.freeze({kind:"noop"});return f.#t.set(E,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:E}},recordSuccess:(E)=>f.#M(E),recordFailure:(E)=>f.#M(E),recordNeutral:(E)=>f.#M(E),abandon:(E)=>f.#N(E),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#M(f){let E=this.#t.get(f);if(E?.kind==="noop")E.settled=!0;return}#P(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+Df)-E);return this.#U(f,Math.min(Df,_))}#U(f,E){let{allowed:_,...T}=this.#S(f,E);return{eligible:!1,...T}}#b(f,E){let _=this.#_();if(f.detached)return this.#A().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.#S(f,h-_);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return this.#O(f,_,E);let T=Math.max(1,(f.probeLeaseExpiresAt??_+Df)-_);return this.#S(f,Math.min(Df,T))}#Y(f,E,_){let T=Object.freeze({kind:E});return this.#t.set(T,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:E,..._!==void 0?{probeLeaseId:_}:{},settled:!1}),{allowed:!0,probe:E==="probe",token:T}}#O(f,E,_){let T=f.nextProbeLeaseId++;f.probeLeaseId=T,f.probeLeaseExpiresAt=E+_,f.lastTouchedAt=E;let h=this.#Y(f,"probe",T),x=f.lastFailure??{reason:"server_error"};return{...h,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:xf(f.samples)}}#S(f,E){let _=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(E)),nextProbeAt:this.#h()+Math.max(0,Math.ceil(E)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:xf(f.samples)}}#R(f,E,_){let T=this.#t.get(f);if(!T||T.settled)return;if(T.settled=!0,T.kind==="noop"||!T.entry)return;let h=T.entry;if(h.detached||T.generation!==h.generation||T.kind==="regular"&&h.state!=="closed"||T.kind==="probe"&&(h.state!=="half_open"||T.probeLeaseId!==h.probeLeaseId))return;let x=this.#_();if(h.lastTouchedAt=x,T.kind==="probe"){if(E==="failure"&&_)return this.#D(h,_,x,"reopened");return this.#V(h)}if(E==="neutral")return;if(this.#j(h,E==="failure",x),E!=="failure"||!_)return;let N=xf(h.samples),A=h.samples.length===0?0:N/h.samples.length;if(h.samples.length>=this.#T.minSamples&&A>=this.#T.errorRateThreshold)return this.#D(h,_,x,"opened");return}#D(f,E,_,T){let h={reason:E.reason,...BE(E.statusCode)!==void 0?{statusCode:BE(E.statusCode)}:{},...bE(E.retryAfterMs)!==void 0?{retryAfterMs:bE(E.retryAfterMs)}:{}},x=h.retryAfterMs??0,N=Math.max(f.configuredOpenDurationMs,x);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=N,f.nextProbeAt=_+N,f.lastFailure=h,{phase:T,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},retryAfterMs:N,nextProbeAt:this.#h()+N,openDurationMs:N,sampleCount:f.samples.length,failureCount:xf(f.samples)}}#V(f){let E=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#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}#j(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)}#X(f){if(!f.detached)this.#u(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:xf(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#B(f){for(let[E,_]of this.#x)if(_.state==="closed"&&f-_.lastTouchedAt>this.#T.idleTtlMs)this.#H(E,_)}#I(){let f;for(let E of this.#x.values())if(E.state==="closed"&&(!f||E.lastTouchedAt<f.lastTouchedAt))f=E;if(f)this.#H(f.key,f)}#H(f,E){E.detached=!0,this.#x.delete(f)}}var OE;function jE(){return OE??=new VE,OE}import{randomBytes as a_}from"node:crypto";var d_=16,XE=128,cE=32,e_=3,zE=16,JE=96,WE=24,$E=12,LE=16,GE=4,kE=4,ZE=67108864,QE=33554432,n_=12,r_=2,KE=2,CE=1,oE=15000,FE=30000;function kf(){return{foreground:0,background:0,internal:0}}function Zf(){return{inFlight:kf(),queued:kf(),pendingBytes:kf()}}function U(f){return f.foreground+f.background+f.internal}function W(f){return f.background+f.internal}function vE(f){return f.inFlight.foreground===0&&f.inFlight.background===0&&f.inFlight.internal===0&&f.queued.foreground===0&&f.queued.background===0&&f.queued.internal===0&&f.pendingBytes.foreground===0&&f.pendingBytes.background===0&&f.pendingBytes.internal===0}class Af extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,E,_,T,h,x,N,A){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=A;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function l(f){return f instanceof Af||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 i_(f){let E=z(f.globalMaxInFlight,d_,Number.MAX_SAFE_INTEGER),_=z(f.globalMaxPending,XE,XE),T=z(f.domainMaxPending,cE,cE),h=Math.min(z(f.ownerMaxInFlight,e_,Number.MAX_SAFE_INTEGER),E),x=Math.min(z(f.ownerMaxPending,zE,zE),_),N=Math.min(z(f.nonForegroundGlobalMaxPending,Math.min(JE,Math.max(1,Math.floor(_*3/4))),JE),_),A=Math.min(z(f.nonForegroundDomainMaxPending,Math.min(WE,Math.max(1,Math.floor(T*3/4))),WE),T),M=Math.min(z(f.nonForegroundOwnerMaxPending,Math.min($E,Math.max(1,Math.floor(x*3/4))),$E),x),S=Math.min(z(f.internalGlobalMaxPending,Math.min(LE,Math.max(1,Math.floor(_/8))),LE),N),t=Math.min(z(f.internalDomainMaxPending,Math.min(GE,Math.max(1,Math.floor(T/8))),GE),A),P=Math.min(z(f.internalOwnerMaxPending,Math.min(kE,Math.max(1,Math.floor(x/4))),kE),M),D=z(f.globalMaxPendingBytes,s,s),Y=Math.min(z(f.domainMaxPendingBytes,ZE,ZE),D),$=Math.min(z(f.ownerMaxPendingBytes,QE,QE),D),Q=Math.min(z(f.nonForegroundGlobalMaxInFlight,Math.min(n_,E),E),E),K=Math.min(z(f.nonForegroundOwnerMaxInFlight,Math.min(r_,h),h),h),F=Math.min(z(f.internalGlobalMaxInFlight,Math.min(KE,E),KE),E),Bf=z(f.internalDomainMaxInFlight,CE,CE),Pf=z(f.agingMs,FE,FE);return{globalMaxInFlight:E,globalMaxPending:_,domainMaxPending:T,ownerMaxInFlight:h,ownerMaxPending:x,nonForegroundGlobalMaxPending:N,nonForegroundDomainMaxPending:A,nonForegroundOwnerMaxPending:M,internalGlobalMaxPending:S,internalDomainMaxPending:t,internalOwnerMaxPending:P,globalMaxPendingBytes:D,domainMaxPendingBytes:Y,ownerMaxPendingBytes:$,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:F,internalDomainMaxInFlight:Bf,agingMs:Pf,classLimitsEnabled:f.classLimitsEnabled!==!1}}function sE(f,E){if(!f.trim())throw Error(`${E} must not be blank`)}function fT(f){if(sE(f.sessionId,"sessionId"),sE(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<Hf||f.scope.maxConcurrent>g)throw Error(`maxConcurrent must be between ${Hf} and ${g}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>s)throw Error(`maxPendingBytes must be between 1 and ${s}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>s+1)throw Error(`pendingBytes must be between 1 and ${s+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Uf)throw Error(`maxWaitMs must be 0-${Uf}`)}function Qf(f,E){if(E!==void 0)return E;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function ET(f,E){return uf(f,E,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class pE{#x;#t;#f;#_=[];#h=new Map;#T=new Map;#E=Zf();#A=1;#M=0;#P=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):a_(32),this.#t=f.now??(()=>performance.now()),this.#f=i_(f)}admit(f){if(fT(f),this.#P)throw this.#c("closed",f,{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw Qf(f.signal);let E=ET(f.scope,this.#x),_=this.#h.get(E),T=this.#T.get(f.ownerId),h=_??this.#Y(f.scope.maxConcurrent),x=T??this.#O();if(this.#_.length===0&&this.#S(h,x,f.requestClass)){if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#A++;let D=this.#D(E,f.ownerId,f.requestClass),Y=this.#L(f,0);return{ready:Promise.resolve(D),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let N=this.#U(f,h,x);if(N)throw this.#c("queue_full",f,N,this.#_.length);let A=this.#R(h,x,f.requestClass);if(f.maxWaitMs===0)throw this.#c("wait_timeout",f,A,this.#_.length);if(!_)this.#h.set(E,h);if(!T)this.#T.set(f.ownerId,x),this.#A++;let M,S,t=new Promise((D,Y)=>{M=D,S=Y});t.catch(()=>{return});let P={domainKey:E,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:M,reject:S,settled:!1,admitted:!1};if(f.signal)P.abortListener=()=>this.#B(P,Qf(f.signal)),f.signal.addEventListener("abort",P.abortListener,{once:!0});return P.timer=setTimeout(()=>this.#X(P),f.maxWaitMs),P.timer.unref?.(),this.#_.push(P),this.#b(h,x,P),this.#N(),{ready:t,getSnapshot:()=>this.#$(P),cancel:(D)=>this.#B(P,Qf(f.signal,D))}}close(){if(this.#P)return;this.#P=!0;for(let f of[...this.#_]){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#I(f,new Af("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.#P}}#U(f,E,_){let T=(t,P,D)=>P>=D?{scope:t,resource:"pending_count",inFlight:P,limit:D}:void 0;if(this.#f.classLimitsEnabled&&f.requestClass==="internal"){let t=T("class",this.#E.queued.internal,this.#f.internalGlobalMaxPending)??T("class",_.counters.queued.internal,this.#f.internalOwnerMaxPending)??T("class",E.counters.queued.internal,this.#f.internalDomainMaxPending);if(t)return t}if(this.#f.classLimitsEnabled&&f.requestClass!=="foreground"){let t=T("class",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),A=Math.min(x,this.#f.ownerMaxPendingBytes),M=(t,P)=>f.pendingBytes>P-t,S=(t)=>{if(t==="owner")return{scope:t,resource:"pending_bytes",inFlight:U(_.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(t==="domain")return{scope:t,resource:"pending_bytes",inFlight:U(E.counters.inFlight),limit:E.maxConcurrent};return{scope:t,resource:"pending_bytes",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let t=Math.max(1,Math.floor(x/8)),P=Math.max(1,Math.floor(N/4)),D=Math.max(1,Math.floor(A/4));if(M(this.#E.pendingBytes.internal,t)||M(_.counters.pendingBytes.internal,D)||M(E.counters.pendingBytes.internal,P))return S("class")}if(f.requestClass!=="foreground"){let t=Math.max(1,Math.floor(x*3/4)),P=Math.max(1,Math.floor(N*3/4)),D=Math.max(1,Math.floor(A/2));if(M(W(this.#E.pendingBytes),t)||M(W(_.counters.pendingBytes),D)||M(W(E.counters.pendingBytes),P))return S("class")}if(M(U(this.#E.pendingBytes),x))return S("global");if(M(U(_.counters.pendingBytes),A))return S("owner");if(M(U(E.counters.pendingBytes),N))return S("domain");return}#b(f,E,_){let{requestClass:T,pendingBytes:h}=_;this.#E.queued[T]++,f.counters.queued[T]++,E.counters.queued[T]++,this.#E.pendingBytes[T]+=h,f.counters.pendingBytes[T]+=h,E.counters.pendingBytes[T]+=h}#Y(f){return{maxConcurrent:f,counters:Zf()}}#O(){return{order:this.#A,counters:Zf()}}#S(f,E,_){if(U(this.#E.inFlight)>=this.#f.globalMaxInFlight)return!1;if(U(f.counters.inFlight)>=f.maxConcurrent)return!1;if(U(E.counters.inFlight)>=this.#f.ownerMaxInFlight)return!1;if(_==="foreground"||!this.#f.classLimitsEnabled)return!0;if(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}}#D(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(!T||!h)throw Error("Provider admission accounting state is unavailable");this.#E.inFlight[_]++,T.counters.inFlight[_]++,h.counters.inFlight[_]++;let x=!1;return{release:()=>{if(x)return;x=!0,this.#V(f,E,_)}}}#V(f,E,_){let T=this.#h.get(f),h=this.#T.get(E);if(this.#E.inFlight[_]--,T)T.counters.inFlight[_]--;if(h)h.counters.inFlight[_]--;this.#z(f,E),this.#N()}#N(){if(this.#P)return;while(this.#_.length>0){let f=this.#t(),E=new Map;for(let[A,M]of this.#_.entries()){let S=this.#h.get(M.domainKey),t=this.#T.get(M.ownerId);if(S===void 0||t===void 0||!this.#S(S,t,M.requestClass))continue;let P=this.#j(M,f),D=E.get(M.ownerId);if(!D||P<D.rank||P===D.rank&&A<D.index)E.set(M.ownerId,{pending:M,rank:P,index:A})}let _=[...E.values()].filter(({pending:A})=>{let M=this.#h.get(A.domainKey),S=this.#T.get(A.ownerId);return M!==void 0&&S!==void 0&&this.#S(M,S,A.requestClass)}).map(({pending:A,rank:M})=>({pending:A,rank:M,order:this.#T.get(A.ownerId).order}));if(_.length===0)return;let T=Math.min(..._.map((A)=>A.rank)),h=_.filter((A)=>A.rank===T),N=h.filter((A)=>A.order>this.#M).sort((A,M)=>A.order-M.order)[0]??h.sort((A,M)=>A.order-M.order)[0];this.#u(N.pending,N.order)}}#j(f,E){let _=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,T=Math.floor(Math.max(0,E-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,_-T)}#u(f,E){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#M=E;let _=this.#D(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#X(f){let E=this.#h.get(f.domainKey),_=this.#T.get(f.ownerId),T=E&&_?this.#R(E,_,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight};this.#I(f,new Af("wait_timeout",T.scope,f.requestClass,T.resource,T.inFlight,T.limit,this.#_.length,f.maxWaitMs))}#B(f,E){this.#I(f,E)}#I(f,E){if(!this.#H(f))return;f.settled=!0,f.reject(E),this.#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(_&&vE(_.counters))this.#h.delete(f);let T=this.#T.get(E);if(T&&vE(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.#G(f,h.scope),queueDepth:this.#_.length,inFlight:h.inFlight,limit:h.limit,waitMs:E,maxWaitMs:f.maxWaitMs}}#L(f,E){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:U(this.#E.inFlight),limit:this.#f.globalMaxInFlight,waitMs:E,maxWaitMs:f.maxWaitMs}}#G(f,E){let _=this.#_.filter((T)=>{switch(E){case"owner":return T.ownerId===f.ownerId;case"domain":return T.domainKey===f.domainKey;case"class":return T.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,_.indexOf(f)+1)}#c(f,E,_,T){return new Af(f,_.scope,E.requestClass,_.resource,_.inFlight,_.limit,T,E.maxWaitMs)}}var wE;function mE(f={}){return wE??=new pE(f),wE}var qE=new WeakSet;class e 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 Ff extends Error{timeoutMs;code="PROVIDER_REQUEST_DEADLINE_EXCEEDED";constructor(f){super(`Provider request deadline exceeded after ${f}ms`);this.timeoutMs=f;this.name="ProviderRequestDeadlineExceededError"}}var _T=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],TT=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],hT=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function gE(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function xT(f){let E=gE(f);return TT.some((_)=>E.includes(_))}function vf(f){if(f!==null&&typeof f==="object")qE.add(f)}function Rh(f){return f!==null&&typeof f==="object"&&qE.has(f)}function tT(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function RT(f){if(f===null||typeof f!=="object")return;let E=f;for(let _ of["status","statusCode"]){let T=E[_];if(typeof T==="number"&&Number.isInteger(T))return T}return}function AT(f){let E=f.match(/^(?:error:\s*)?(\d{3})\b/),_=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),T=Number(E?.[1]??_?.[1]);return Number.isInteger(T)?T:void 0}function o(f,E){let _=gE(f),T=tT(f);if(T==="STREAM_IDLE_TIMEOUT"||T==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||_.includes("request aborted")||_==="aborted")return{retryable:!1};if(_T.some((x)=>_.includes(x))||xT(f))return{retryable:!1};if(E?.shouldRetry==="false")return{retryable:!1,statusCode:E.statusCode};if(T==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let h=E?.statusCode??RT(f)??AT(_);if(E?.shouldRetry==="true")return{retryable:!0,reason:h===429?"rate_limit":h===408||h===409?"timeout":"server_error",statusCode:h};if(h===429)return{retryable:!0,reason:"rate_limit",statusCode:h};if(h===408||h===409)return{retryable:!0,reason:"timeout",statusCode:h};if(h!==void 0&&h>=500&&h<=599)return{retryable:!0,reason:"server_error",statusCode:h};if(T==="PROVIDER_STREAM_CLOSED"||_.includes("stream closed before completion")||_.includes("ended without")||_.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:h};if(hT.some((x)=>_.includes(x)))return{retryable:!0,reason:"transport",statusCode:h};if(_.includes("timeout")||_.includes("timed out")||_.includes("temporarily unavailable")||_.includes("upstream_error")||_.includes("overloaded")||_.includes("rate limit")||_.includes("too many requests")||_.includes("service unavailable")||_.includes("server error")||_.includes("internal error")||_.includes("please retry")||_.includes("try your request again"))return{retryable:!0,reason:_.includes("rate")||_.includes("too many")?"rate_limit":_.includes("timeout")||_.includes("timed out")?"timeout":"server_error",statusCode:h};return{retryable:!1,statusCode:h}}function sf(f,E){if(!f)return;if(f.retryAfterMs!==void 0){let h=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(h))return Math.max(0,h)}if(f.retryAfter===void 0)return;let _=Number.parseFloat(f.retryAfter);if(Number.isFinite(_))return Math.max(0,_*1000);let T=Date.parse(f.retryAfter);return Number.isFinite(T)?Math.max(0,T-E):void 0}function lE(f,E,_={}){let T=_.now??Date.now(),h=_.maxDelayMs??60000,x=sf(E,T);if(x!==void 0)return Math.min(Math.ceil(x),h);let N=Math.max(0,f-1),A=_.maxExponentialDelayMs??8000,M=Math.min(500*2**N,A),S=Math.max(0,Math.min(1,_.random??Math.random())),t=M*(0.75+S*0.25);return Math.min(Math.round(t),h)}function of(f,E){return{provider:wf(f),model:wf(E)}}function yE(f,E){if(l(f))return{source:"admission",reason:f.reason};if(Rf(f))return{source:"circuit",reason:f.circuit.reason,...f.circuit.statusCode!==void 0?{statusCode:f.circuit.statusCode}:{}};if(f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT")return{source:"stall",reason:"timeout"};let _=o(f,E);if(_.retryable&&_.reason)return{source:"retry",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{}};throw Error("Provider fallback trigger is not classified")}function aE(f,E={}){let _=E.maxBytes??134217728,T=E.maxNodes??1e5;if(!Number.isSafeInteger(_)||_<=0||_>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(T)||T<=0)throw Error("maxNodes must be a positive safe integer");let h=new WeakSet,x=0,N=0,A=!1,M=(t)=>{if(A||t<=0)return;if(!Number.isSafeInteger(t)||t>_-x){x=_+1,A=!0;return}x+=t},S=(t)=>{if(A)return;if(N+=1,N>T){M(_+1);return}if(t===null){M(4);return}switch(typeof t){case"string":M(Buffer.byteLength(t,"utf8"));return;case"number":case"bigint":M(8);return;case"boolean":M(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(h.has(t))return;if(h.add(t),ArrayBuffer.isView(t)){M(32+t.byteLength);return}if(t instanceof ArrayBuffer){M(32+t.byteLength);return}if(t instanceof Date){M(40);return}if(t instanceof RegExp){M(32+Buffer.byteLength(t.source,"utf8"));return}if(t instanceof Map){M(32);for(let[P,D]of t)if(S(P),S(D),A)return;return}if(t instanceof Set){M(32);for(let P of t)if(S(P),A)return;return}if(t instanceof WeakMap||t instanceof WeakSet){M(32);return}if(Array.isArray(t)){M(16);for(let P of t)if(S(P),A)return;return}M(32);for(let P of Reflect.ownKeys(t)){if(typeof P!=="string")continue;let D=Object.getOwnPropertyDescriptor(t,P);if(!D?.enumerable||!("value"in D))continue;if(M(8+Buffer.byteLength(P,"utf8")),S(D.value),A)return}};return S(f),x}function dE(f){return aE([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}function rE(f,E){let _=f.onPayload;f.onPayload=async(T,h)=>{let x=_?await _(T,h):T;return E(x===void 0?T:x,h)}}function PT(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function pf(f,E,_){if(!f.enablePromptCaching)return"none";if(_&&E.api==="openai-completions"&&!E.baseUrl.includes("api.openai.com"))return"long";return"short"}function ST(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function MT(f,E,_,T){let h=T?void 0:PT(_);if(!h){if(E.api==="anthropic-messages")f.thinkingEnabled=!1;if(E.api==="google-generative-ai"||E.api==="google-vertex")f.thinking={enabled:!1};return}switch(E.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=h;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:ST(h)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=h;break;default:f.reasoningEffort=h}}function NT(f,E,_){if(!_)return;switch(E){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:_};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:_}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:_};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function uT(f,E,_){let T=_.serviceTier;if(!T)return;if(E.api==="openai-responses"||E.api==="openai-codex-responses"||E.api==="azure-openai-responses"){f.serviceTier=T;return}if(E.api!=="openai-completions"&&!(E.api==="anthropic-messages"&&T==="fast"))return;rE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;return E.api==="anthropic-messages"?{...h,speed:"fast"}:{...h,service_tier:T}})}function DT(f,E,_){let T=_.responseVerbosity;if(!T)return;if(nE(E,T),E.api==="openai-codex-responses"){f.textVerbosity=T;return}rE(f,(h)=>{if(!h||typeof h!=="object"||Array.isArray(h))return h;if(E.api==="openai-completions")return{...h,verbosity:T};let x="text"in h&&h.text&&typeof h.text==="object"&&!Array.isArray(h.text)?h.text:{};return{...h,text:{...x,verbosity:T}}})}function iE(f,E,_,T,h=!1){let x={apiKey:f.apiKey,headers:f.customHeaders,signal:_,temperature:T?.temperature??f.temperature??0,maxTokens:T?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:pf(f,E,T?.providerSessionId),sessionId:T?.providerSessionId};if(MT(x,E,f,h),NT(x,E.api,T?.toolChoice?.toolName),uT(x,E,f),DT(x,E,f),E.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=E.id;return x}function eE(f,E){let _=E.get("x-should-retry");return{statusCode:f,...E.get("retry-after")!==null?{retryAfter:E.get("retry-after")??void 0}:{},...E.get("retry-after-ms")!==null?{retryAfterMs:E.get("retry-after-ms")??void 0}:{},..._==="true"||_==="false"?{shouldRetry:_}:{}}}var IT=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function f_(f,E,_){let T=f.onResponse;if(f.onResponse=async(x,N)=>{let A=new Headers(x.headers);_(eE(x.status,A)),await T?.(x,N)},!IT.has(E.api)||typeof globalThis.fetch!=="function")return;let h=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(x,N)=>{let A=await h(x,N);return _(eE(A.status,A.headers)),A}}function E_(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Yf=300000,HT=30000;class __ extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(f){super(`Provider stream idle timeout after ${f}ms without an event`);this.timeoutMs=f;this.name="StreamIdleTimeoutError"}}class T_ extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function mf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function UT(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Yf}function YT(f,E){if(E===0)return;let _=E!==void 0&&E>0?E:HT;return Math.max(1,Math.min(_,Math.floor(f/2)))}function BT(f,E,_){if(_?.aborted)return Promise.reject(mf(_));return new Promise((T,h)=>{let x=!1,N=()=>{clearTimeout(t),_?.removeEventListener("abort",S)},A=(P)=>{if(x)return;x=!0,N(),T(P)},M=(P)=>{if(x)return;x=!0,N(),h(P instanceof Error?P:Error(String(P)))},S=()=>{if(_)M(mf(_))},t=setTimeout(()=>A({kind:"timer"}),Math.max(0,E));if(_?.addEventListener("abort",S,{once:!0}),_?.aborted){S();return}f.then((P)=>A({kind:"next",result:P}),M)})}async function*bT(f,E,_){let T=UT(E),h=YT(T,E.stallWarningMs);if(E.signal?.aborted)throw mf(E.signal);let x=Date.now(),N=Promise.resolve().then(()=>f.next()),A;for(;;){let S=await BT(N,(A?T:h??T)-(Date.now()-x),E.signal);if(S.kind==="next"){if(A)yield{...A,phase:"recovered",durationMs:Math.max(A.durationMs,Date.now()-x)};return S.result}if(!A&&h!==void 0){_.stallCount++,A={phase:"detected",stallCount:_.stallCount,durationMs:h,warningAfterMs:h,timeoutMs:T,outputStarted:_.outputStarted},yield A;continue}let t=new __(T);throw E.abort?.(t),t}}async function*h_(f,E,_,T,h={}){let N=f.stream(E,_,T)[Symbol.asyncIterator](),A=0,M=!1,S={stallCount:0,outputStarted:!1};try{while(!0){let t=bT(N,h,S),P=await t.next();while(!P.done)yield{providerStall:P.value},P=await t.next();let D=P.value;if(D.done)throw new T_;let Y=D.value;switch(Y.type){case"text_delta":S.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":S.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":S.outputStarted=!0,yield{toolCalls:[{index:A++,id:Y.toolCall.id,type:"function",function:{name:Y.toolCall.name,arguments:JSON.stringify(Y.toolCall.arguments)}}]};break;case"done":M=!0,yield{finishReason:Y.reason,usage:E_(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!M)Promise.resolve(N.return?.()).catch(()=>{return})}}var qf=a("Chat"),OT=1;function VT(f,E){let _=E.provider===f.provider,T=_&&E.channel===void 0,h=E.channel;return{...f,provider:E.provider,model:E.model,apiKey:h?.apiKey??(T?f.apiKey:void 0),baseUrl:h?.baseUrl??(T?f.baseUrl:void 0),temperature:h?.temperature??f.temperature,maxOutputTokens:h?.maxOutputTokens??(T?f.maxOutputTokens:void 0),timeout:h?.timeout??f.timeout,streamIdleTimeout:h?.streamIdleTimeout??f.streamIdleTimeout,apiVersion:h?.apiVersion??(T?f.apiVersion:void 0),customHeaders:h?.customHeaders??(T?f.customHeaders:void 0),enablePromptCaching:h?.enablePromptCaching??(T?f.enablePromptCaching:void 0),serviceTier:_?f.serviceTier:void 0,responseVerbosity:_?f.responseVerbosity:void 0,fallbackModels:void 0}}function jT(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((E)=>E.type==="image_url"))}function XT(f){let _=f.findLast((T)=>{let h=T.metadata;return h!==null&&typeof h==="object"&&!Array.isArray(h)&&h.isCompactSummary===!0})?.metadata;return _!==null&&typeof _==="object"&&!Array.isArray(_)&&typeof _.parentId==="string"?_.parentId:""}function cT(f,E){let _=o(f,E);if(!_.retryable||!_.reason)return;let T=_.statusCode;switch(_.reason){case"rate_limit":if(T!==429)return;break;case"server_error":if(T===void 0||T<500||T>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let h=sf(E,Date.now());return{reason:_.reason,...T!==void 0?{statusCode:T}:{},...h!==void 0?{retryAfterMs:h}:{}}}function gf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class af{config;models;model;promptCacheBreakMonitor=new Wf;providerAdmissionScheduler;admissionFallbackOwnerId=`pi-service-${process.pid}-${OT++}`;constructor(f){let E=Jf(f);this.config={...f,maxContextTokens:E.model.contextWindow,maxOutputTokens:f.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model,this.providerAdmissionScheduler=x_(this.config),qf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,E,_,T){let h="",x="",N=[],A,M;for await(let S of this.streamChat(f,E,_,T)){h+=S.content??"",x+=S.reasoningContent??"";for(let t of S.toolCalls??[])if(t.id&&t.type==="function"&&t.function?.name)N.push(t);A=S.usage??A,M=S.finishReason??M}return{content:h,...x?{reasoningContent:x}:{},...N.length>0?{toolCalls:N}:{},usage:A,finishReason:M}}async*streamChat(f,E,_,T){let h=T?.toolChoice?.toolName;if(h&&!E?.some((R)=>R.name===h))throw Error(`Required tool is unavailable: ${h}`);let x=NE(f);if(x.some((R)=>jT(R))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let N=Boolean(h)||uE(x),A=await ME(x,this.model,E,_,h),M=(R,u)=>{let V=T?.providerSessionId;if(!V||!R.usage)return R;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(V),R;let B=pf(this.config,u,V),I=this.promptCacheBreakMonitor.observe({sessionId:V,modelIdentity:`${u.provider}\x00${u.api}\x00${u.id}`,context:A,retention:B,contextEpoch:XT(x),policy:{baseUrl:u.baseUrl??this.config.baseUrl??"",retention:B,requiredTool:h??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:T?.temperature??this.config.temperature??0,maxOutputTokens:T?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:R.usage});if(!I)return R;return qf.warn("[PiAIChatService] Prompt cache break detected",{reason:I.reason,previousCacheReadTokens:I.previousCacheReadTokens,cacheReadTokens:I.cacheReadTokens,tokenDrop:I.tokenDrop,callNumber:I.callNumber}),{...R,usage:{...R.usage,promptCacheBreak:I}}},S=dE({messages:x,context:A,tools:E,requestOptions:T}),t=T?.providerRecovery;if(t&&!R_(t.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let P=t?.mode==="bounded_foreground"&&t.budgetMs>0?{budgetMs:t.budgetMs,startedAt:void 0}:void 0,D=P?"bounded_foreground":"standard",Y=this.config.maxRetries??2,$=this.config.maxRetries??(P?t_:2),Q=P!==void 0&&this.config.maxRetries===void 0,K=0,F,Bf=this.config.providerCircuitRegistry??jE(),Pf=this.config.providerCircuitBreakerOpenMs??$f,A_=Math.max(If,Math.min(this.config.streamIdleTimeout??Yf,Gf)),df=this.providerAdmissionScheduler,P_=this.config.providerRequestConcurrency??g,ef=this.config.providerRequestAdmissionMs??Kf,S_=this.config.providerRequestPendingBytes??Cf,bf=T?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},M_=(R,u)=>Bf.get({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,openDurationMs:Pf,probeLeaseMs:A_}),N_=(R,u)=>({provider:R.provider,api:R.api,baseUrl:R.baseUrl??u.baseUrl??"",model:R.id,serviceTier:u.serviceTier,apiVersion:u.apiVersion,apiKey:u.apiKey,customHeaders:u.customHeaders,maxConcurrent:P_,maxPendingBytes:S_}),X=(R=Date.now())=>{if(!P)return;let u=P.startedAt===void 0?0:Math.min(P.budgetMs,Math.max(0,R-P.startedAt));return{recoveryBudgetMs:P.budgetMs,recoveryElapsedMs:u,recoveryRemainingMs:Math.max(0,P.budgetMs-u)}},w=()=>({mode:D,...X()??{}}),nf=()=>{if(P&&P.startedAt===void 0)P.startedAt=Date.now()},p=()=>{let R=X();return new e(P?.budgetMs??0,R?.recoveryElapsedMs??0)},n=()=>!Q||K<$+1,Of=(R,u)=>{let{state:V,...B}=u;return{phase:R,...B,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}},rf=(R)=>({phase:"rejected",requestClass:R.requestClass,resource:R.resource,scope:R.scope,reason:R.reason,queuePosition:0,queueDepth:Math.max(0,R.queued),inFlight:Math.max(0,R.inFlight),limit:Math.max(0,R.limit),waitMs:R.reason==="wait_timeout"?R.maxWaitMs:0,maxWaitMs:R.maxWaitMs,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),u_=async function*(R,u){if(!df)return{release:()=>{return}};let V=X()?.recoveryRemainingMs,B=V!==void 0&&P?.startedAt!==void 0?Math.min(ef,V):ef,I;try{I=df.admit({scope:N_(R,u),sessionId:bf.sessionId,ownerId:bf.ownerId,requestClass:bf.requestClass,maxWaitMs:B,pendingBytes:S,signal:_})}catch(b){if(l(b)){if(b.reason==="wait_timeout"&&P?.startedAt!==void 0&&(X()?.recoveryRemainingMs??0)<=0)throw p();yield{providerAdmission:rf(b)}}throw b}let G=I.getSnapshot();if(G.state==="admitted")return await I.ready;yield{providerAdmission:Of("queued",G)};let v=I.ready.then((b)=>({kind:"ready",permit:b}),(b)=>({kind:"error",error:b}));while(!0){let b=I.getSnapshot(),O=Math.max(1,Math.min(oE,Math.max(1,B-b.waitMs))),J,c=new Promise((m)=>{J=setTimeout(()=>m({kind:"heartbeat"}),O),J.unref?.()}),k=await Promise.race([v,c]);if(J)clearTimeout(J);if(k.kind==="heartbeat"){yield{providerAdmission:Of("queued",I.getSnapshot())};continue}if(k.kind==="error"){if(l(k.error)){if(k.error.reason==="wait_timeout"&&P?.startedAt!==void 0&&(X()?.recoveryRemainingMs??0)<=0)throw p();yield{providerAdmission:rf(k.error)}}throw k.error}return yield{providerAdmission:Of("admitted",I.getSnapshot())},k.permit}},D_=(R,u)=>{if(!n())throw p();if(Q)K++;F=void 0;let V=new AbortController,B=_?RE(_,V.signal):V.signal,I=typeof u.timeout==="number"&&Number.isFinite(u.timeout)&&u.timeout>0?Math.max(1,Math.floor(u.timeout)):void 0,G;if(P?.startedAt!==void 0){let O=X()?.recoveryRemainingMs??0;if(O<=0)throw p();G={remainingMs:O,error:new e(P.budgetMs,P.budgetMs)}}let v=iE(u,R,B,T,N);f_(v,R,(O)=>{F=O});let b=h_(this.models,R,A,v,{idleTimeoutMs:u.streamIdleTimeout??Yf,signal:B,abort:(O)=>V.abort(O)});return async function*(){let O,J;try{if(I!==void 0&&(G===void 0||I<G.remainingMs)){let c=new Ff(I);O=setTimeout(()=>V.abort(c),I),O.unref?.()}if(G){let c=G;J=setTimeout(()=>V.abort(c.error),c.remainingMs),J.unref?.()}yield*b}finally{if(O)clearTimeout(O);if(J)clearTimeout(J)}}()},fE=this,y=(R)=>({phase:R.phase,reason:R.reason,...R.statusCode!==void 0?{statusCode:R.statusCode}:{},...R.retryAfterMs!==void 0?{retryAfterMs:R.retryAfterMs}:{},...R.nextProbeAt!==void 0?{nextProbeAt:R.nextProbeAt}:{},openDurationMs:R.openDurationMs,sampleCount:R.sampleCount,failureCount:R.failureCount,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),EE=(R,u)=>({phase:R,reason:u.reason,...u.statusCode!==void 0?{statusCode:u.statusCode}:{},retryAfterMs:u.retryAfterMs,...u.nextProbeAt!==void 0?{nextProbeAt:u.nextProbeAt}:{},openDurationMs:u.openDurationMs,sampleCount:u.sampleCount,failureCount:u.failureCount,...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),I_=(R)=>({phase:"probe",reason:R.reason??"server_error",...R.statusCode!==void 0?{statusCode:R.statusCode}:{},openDurationMs:R.openDurationMs??Pf,...R.sampleCount!==void 0?{sampleCount:R.sampleCount}:{},...R.failureCount!==void 0?{failureCount:R.failureCount}:{},...X()?{recoveryRemainingMs:X()?.recoveryRemainingMs}:{}}),Vf=(R,u,V)=>({providerRetry:{phase:"exhausted",attempt:R,maxRetries:$,reason:u,...V!==void 0?{statusCode:V}:{},...w(),exhaustedBy:"recovery_budget"}}),_E=async function*(R,u,V,B,I){let G,v=!1,b,O,J=M_(R,u);for(let c=0;c<=B;c++){if(!n())break;let k,m;while(!k){let H=J.preflight();while(!H.eligible){if(b=H.reason,O=H.statusCode,!P||!I){let C=EE("rejected",H);throw yield{providerCircuit:C},new tf(C)}nf();let j=X()?.recoveryRemainingMs??0;if(j<=0){let C=p();throw yield Vf(Q?Math.max(0,K-1):c,H.reason,H.statusCode),C}yield{providerCircuit:EE("waiting",H)};let q=Math.min(Math.max(1,H.retryAfterMs),lf,j);if(await _f(q,_,{throwOnAbort:!0}),(X()?.recoveryRemainingMs??0)<=0){let C=p();throw yield Vf(Q?Math.max(0,K-1):c,H.reason,H.statusCode),C}H=J.preflight()}try{m=yield*u_(R,u)}catch(Z){if(Z instanceof e)yield Vf(Q?Math.max(0,K-1):c,b??"timeout",O);throw Z}let L=J.check();if(L.allowed)k=L;else m.release(),m=void 0}let i=k.token;if(k.probe)yield{providerCircuit:I_(k)};try{let H=!1,L=!1;for await(let Z of D_(R,u)){if(Z.providerStall){yield Z;continue}let j=Q?K-1:c;if(j>0&&b&&!H)H=!0,yield{providerRetry:{phase:"recovered",attempt:j,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...w()}};if(!L){L=!0;let q=J.recordSuccess(i);if(q)yield{providerCircuit:y(q)}}v=!0,V(),yield M(Z,R)}if(!L){let Z=J.recordSuccess(i);if(Z)yield{providerCircuit:y(Z)}}return}catch(H){if(m?.release(),G=H,fE.logIdleTimeout(H,v,R),await fE.handleAbort(_),H instanceof e){if(v)throw vf(H),H;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:$,reason:b??"timeout",...O!==void 0?{statusCode:O}:{},...w(),exhaustedBy:"recovery_budget"}},H}let L=o(H,F);if(v)throw vf(H),H;let Z=cT(H,F),j=Z?J.recordFailure(i,Z):F&&!gf(H)?J.recordNeutral(i):void 0;if(j)yield{providerCircuit:y(j)};if(!L.retryable||!L.reason){if(c>0&&b)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...w()}};throw H}b=L.reason,O=L.statusCode;let q=c<B&&n();if(j&&j.phase!=="closed"&&q&&(!P||!I)){let C={...y(j),phase:"rejected"};throw yield{providerCircuit:C},new tf(C)}if(q){nf();let C=Q?K:c+1,U_=lE(C,F,P?{maxDelayMs:yf,maxExponentialDelayMs:yf}:void 0),hE=j&&j.phase!=="closed"?j.retryAfterMs??0:0;if(P&&hE>0&&j)yield{providerCircuit:{...y(j),phase:"waiting"}};let Y_=X(),Xf=Math.max(U_,hE),ff=P?Math.min(Xf,Y_?.recoveryRemainingMs??Xf):Xf,Mf={attempt:C,maxRetries:$,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Mf,delayMs:ff,nextRetryAt:Date.now()+ff,...w()}},P){let Ef=ff;while(Ef>0){let xE=Math.min(Ef,lf);if(await _f(xE,_,{throwOnAbort:!0}),Ef-=xE,(X()?.recoveryRemainingMs??0)<=0){let Nf=p();throw yield{providerRetry:{phase:"exhausted",...Mf,...w(),exhaustedBy:"recovery_budget"}},Nf}if(Ef>0){if(j&&j.phase!=="closed"&&j.nextProbeAt!==void 0){let Nf=Math.max(0,j.nextProbeAt-Date.now());if(Nf>0)yield{providerCircuit:{...y(j),phase:"waiting",retryAfterMs:Nf}}}yield{providerRetry:{phase:"waiting",...Mf,delayMs:ff,nextRetryAt:Date.now()+Ef,...w()}}}}}else await _f(ff,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Mf,...w()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):c,maxRetries:$,reason:L.reason,...L.statusCode!==void 0?{statusCode:L.statusCode}:{},...w(),...P&&(I||!n())?{exhaustedBy:"attempt_limit"}:{}}}}finally{J.abandon(i),m?.release()}}throw G},Sf,TE=!1,jf=this.model,r=this.config.fallbackModels??[],H_=P&&r.length>0?Math.min(Y,$):$;try{for await(let R of _E(this.model,this.config,()=>{TE=!0},H_,r.length===0))yield R;return}catch(R){if(Sf=R,TE||!l(R)&&!Rf(R)&&!gf(R)&&!o(R,F).retryable)throw R}for(let[R,u]of r.entries()){if(!n())break;let V=!1;try{let B=VT(this.config,u),I=HE(B,u);yield{modelFallback:{from:of(jf.provider,jf.id),to:of(I.provider,I.id),candidate:R+1,candidateCount:r.length,trigger:yE(Sf,F)}},jf=I;let G=R===r.length-1,v=P&&!G?Math.min(Y,$):$;for await(let b of _E(I,B,()=>{V=!0},v,G))yield b;return}catch(B){if(Sf=B,V||!l(B)&&!Rf(B)&&!gf(B)&&!o(B,F).retryable)throw B}}throw Sf}async handleAbort(f){if(f?.aborted)await _f(0,f,{throwOnAbort:!0})}logIdleTimeout(f,E,_){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;qf.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},_=Jf(E);this.config={...E,maxContextTokens:_.model.contextWindow,maxOutputTokens:E.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,this.providerAdmissionScheduler=x_(this.config)}}function x_(f){if(f.providerRequestAdmissionScheduler)return f.providerRequestAdmissionScheduler;if(f.providerRequestConcurrency===void 0&&f.providerGlobalConcurrency===void 0&&f.providerOwnerConcurrency===void 0)return;let E=f.providerGlobalConcurrency??Number.MAX_SAFE_INTEGER,_=f.providerOwnerConcurrency??Number.MAX_SAFE_INTEGER;return mE({globalMaxInFlight:E,ownerMaxInFlight:_,nonForegroundGlobalMaxInFlight:E,nonForegroundOwnerMaxInFlight:_,internalGlobalMaxInFlight:E,internalDomainMaxInFlight:f.providerRequestConcurrency??g,classLimitsEnabled:!1})}var zT=a("Service");async function mh(f){let E=f;if(E.provider){let _=tE(E.provider);if(Object.keys(_).length>0)E={...E,customHeaders:{..._,...E.customHeaders}},zT.debug(`Injected ${E.provider} specific headers:`,Object.keys(_))}return JT(E)}function JT(f){return new af(f)}
|
|
5
|
+
export{LT as _f,ZT as $f,RE as ag,_f as bg,l as cg,xT as dg,Rh as eg,o as fg,lE as gg,aE as hg,af as ig,mh as jg};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Mi as K}from"./chunk-npc7jt96.js";import{Ni as wt,Oi as ft}from"./chunk-mc2mr1kn.js";import{Vi as I}from"./chunk-dv2m2xe5.js";import{Wi as tt,Xi as Dt,Yi as Bt,aj as Gt,bj as et,cj as Kt,dj as Ht,ej as Yt,fj as cn,gj as Ft,hj as qt,ij as Mt,jj as Vt,kj as Jt,lj as _t,mj as Qt,nj as jt,oj as Wt,pj as Zt,qj as kt,rj as yt}from"./chunk-fbrdcveb.js";import{vj as Un,xj as bn,yj as _n,zj as T}from"./chunk-ft1bdqbs.js";import{Ej as zt,Hj as v}from"./chunk-jb4hmk56.js";import{Pj as xn,Qj as Cn}from"./chunk-2t0wp7gm.js";import{Wj as a}from"./chunk-jy7k2dwm.js";import{Zj as Ln}from"./chunk-t88sfhjj.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await b.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -41,4 +41,4 @@ ${e.map((M)=>` - ${M}`).join(`
|
|
|
41
41
|
]
|
|
42
42
|
}
|
|
43
43
|
`)}}function W_(n,t={}){let e={...n};if(t.debug!==void 0)e.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);e.currentModelId=t.model}if(t.yolo===!0)e.permissionMode="yolo";else if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)e.maxQueuedTasks=t.maxQueuedTasks;if(t.maxQueuedTaskBytes!==void 0)e.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)e.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)e.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;if(t.maxResidentSessionProjections!==void 0)e.maxResidentSessionProjections=t.maxResidentSessionProjections;if(t.sessionProjectionIdleMs!==void 0)e.sessionProjectionIdleMs=t.sessionProjectionIdleMs;return e.systemPrompt=t.systemPrompt,e.appendSystemPrompt=t.appendSystemPrompt,e.model=t.model,e.resumeSessionId=t.sessionId,e.forkSession=t.forkSession,e.allowedTools=t.allowedTools,e.disallowedTools=t.disallowedTools,e.mcpConfigPaths=t.mcpConfig,e.strictMcpConfig=t.strictMcpConfig,e.addDirs=t.addDir,e.outputFormat=t.outputFormat,e.inputFormat=t.inputFormat,e.print=t.print,e.includePartialMessages=t.includePartialMessages,e.replayUserMessages=t.replayUserMessages,e.agentsConfig=t.agents,e.settingSources=t.settingSources,e}
|
|
44
|
-
export{B as
|
|
44
|
+
export{B as wh,nn as xh,f as yh,En as zh,hn as Ah,C as Bh,ot as Ch,VM as Dh,W as Eh,jM as Fh,WM as Gh,ZM as Hh,ct as Ih,Ce as Jh,kM as Kh,he as Lh,yM as Mh,Pt as Nh,n_ as Oh,t_ as Ph,M_ as Qh,__ as Rh,r_ as Sh,Ct as Th,S_ as Uh,E_ as Vh,u_ as Wh,o_ as Xh,Y as Yh,Rn as Zh,F as _h,q as $h,Xn as ai,V as bi,TM as ci,sM as di,J as ei,Q as fi,h as gi,xM as hi,zn as ii,Dn as ji,hM as ki,Bn as li,Gn as mi,Kn as ni,Hn as oi,Yn as pi,Fn as qi,XM as ri,qn as si,Vn as ti,Jn as ui,Qn as vi,jn as wi,Wn as xi,Zn as yi,kn as zi,yn as Ai,ln as Bi,vn as Ci,nt as Di,s as Ei,d as Fi,Le as Gi,z as Hi,l as Ii,X as Ji,W_ as Ki};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{A as
|
|
1
|
+
import{Aj as k,Cj as w,zj as b}from"./chunk-ft1bdqbs.js";function g(j){return b.Object(j,{additionalProperties:!1})}var W=b.String({pattern:"^acp-remote-workspace:[A-Za-z0-9_-]{43}$"}),I=b.Optional(b.Integer({minimum:1,maximum:100})),x=b.String({minLength:1,maxLength:200,pattern:"^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$"}),A=k(b.Union([g({version:b.Literal(2),sessionId:x,workspace:g({kind:b.Literal("local"),projectPath:b.String({minLength:1})})}),g({version:b.Literal(2),sessionId:x,workspace:g({kind:b.Literal("acp-remote"),workspaceRef:W})})])),C=k(w(["history-only","owner-offline","owner-mismatch","archived","surface-not-supported","capability-not-advertised"])),X=k(g({connection:w(["local","online","offline"]),history:g({read:b.Boolean(),fork:b.Boolean()}),turn:g({start:b.Boolean(),reason:b.Optional(C)}),files:g({readText:b.Boolean(),writeText:b.Boolean(),browse:w(["none","known-files","tree"]),reason:b.Optional(C)}),terminal:g({mode:w(["none","command","interactive"]),owner:w(["none","local","acp-remote"]),reason:b.Optional(C)})})),Y=k(g({id:b.String({pattern:"^surface-message:[0-9]+:.+$"}),role:w(["user","assistant"]),content:b.String(),timestamp:b.String({minLength:1}),truncated:b.Optional(b.Boolean())})),Z=w(["queued","running","completed","failed","cancelled","interrupted"]),_=w(["posix","win32"]),$=w(["subagent","fork"]),D=b.String({minLength:1}),J=b.String({minLength:1}),z=40,H=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-](\d{2}):(\d{2}))$/,M="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}Z$";function T(j){return j%4===0&&(j%100!==0||j%400===0)}function R(j,q){if(q===2)return T(j)?29:28;return[4,6,9,11].includes(q)?30:31}function d(j){if(j===void 0||j.length<20||j.length>z)return;let q=H.exec(j);if(!q)return;let L=Number(q[1]),B=Number(q[2]),E=Number(q[3]),N=Number(q[4]),O=Number(q[5]),P=Number(q[6]),Q=q[8],U=Number(q[9]),V=Number(q[10]);if(B<1||B>12||E<1||E>R(L,B)||N>23||O>59||P>59||Q!=="Z"&&(U>23||V>59))return;let F=Date.parse(j);if(!Number.isFinite(F))return;let G=new Date(F).toISOString();return G.length===24?G:void 0}var S=b.Refine(b.String({minLength:24,maxLength:24,pattern:M}),(j)=>d(j)===j,()=>"must be a canonical ISO instant"),K=k(g({locator:A,displayCwd:b.String({minLength:1}),pathStyle:b.Optional(_),title:b.Optional(b.String()),rootId:x,parentId:b.Optional(x),relationType:b.Optional($),taskStatus:Z,taskCompletedAt:b.Optional(S),messageCount:b.Integer({minimum:0}),firstMessageTime:b.String({minLength:1}),lastMessageTime:b.String({minLength:1}),hasErrors:b.Boolean(),archivedAt:b.Optional(b.String({minLength:1})),selectedModelId:b.Optional(b.String({minLength:1})),capabilities:X})),p=k(w(["invalid_session_surface_request","invalid_session_locator","session_surface_not_found","workspace_binding_mismatch","session_surface_cursor_invalid","session_surface_snapshot_changed","session_surface_read_only","session_surface_capability_unavailable","session_surface_capacity","session_surface_unavailable","session_surface_state_invalid"])),i=k(g({error:g({code:p,message:b.String({minLength:1}),retryable:b.Boolean()})})),s=k(g({sessions:b.Array(K),nextCursor:b.Optional(D)})),f=k(g({messages:b.Array(Y),olderCursor:b.Optional(D),snapshot:J,truncated:b.Boolean()})),v=k(g({locator:A,limit:I})),l=k(g({session:K,history:f})),r=k(g({locator:A,cursor:D,expectedSnapshot:J,limit:I})),n=k(g({locator:A}));
|
|
2
|
+
export{A as af,Y as bf,d as cf,K as df,i as ef,s as ff,f as gf,v as hf,l as if,r as jf,n as kf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
function v(b){switch(b){case"default":case"ignore":case void 0:return"default";case"acceptEdits":return"autoEdit";case"dontAsk":case"bypassPermissions":return"yolo";case"plan":return"plan";default:return"default"}}
|
|
2
|
-
export{v as
|
|
2
|
+
export{v as oh};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Aj as K,Cj as j,zj as b}from"./chunk-ft1bdqbs.js";var L=256,Z=128,p=1e6,$=86400000,G=8640000000000000,g=b.Integer({minimum:0,maximum:p}),f=b.Integer({minimum:0,maximum:$}),q=b.Integer({minimum:0,maximum:G}),x=b.String({minLength:1,maxLength:L,pattern:"^(?!.*://)[^\x00-\x1F]+$"}),H=j(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),U=j(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),F=b.Object({provider:x,model:x},{additionalProperties:!1}),J=j(["rate_limit","server_error","timeout","transport","stream_closed"]),s=b.Union([b.Object({source:b.Literal("retry"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("circuit"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("admission"),reason:j(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),b.Object({source:b.Literal("stall"),reason:b.Literal("timeout")},{additionalProperties:!1})]),T=b.Object({from:F,to:F,candidate:b.Integer({minimum:1,maximum:p}),candidateCount:b.Integer({minimum:1,maximum:p}),trigger:s},{additionalProperties:!1}),X=b.Object({attempt:g,maxRetries:g,statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),delayMs:b.Optional(f),recoveryBudgetMs:b.Optional(f),recoveryElapsedMs:b.Optional(f),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),Y=b.Object({requestClass:j(["foreground","background","internal"]),scope:j(["global","domain","owner","class"]),resource:j(["stream","pending_count","pending_bytes"]),queuePosition:g,queueDepth:g,inFlight:g,limit:g,waitMs:f,maxWaitMs:f,recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),z=b.Object({phase:j(["opened","reopened","waiting","probe","rejected"]),statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),retryAfterMs:b.Optional(f),nextProbeAt:b.Optional(q),openDurationMs:f,sampleCount:b.Optional(g),failureCount:b.Optional(g),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),C=b.Object({stallCount:g,durationMs:f,warningAfterMs:f,timeoutMs:f,outputStarted:b.Boolean()},{additionalProperties:!1}),I=b.Object({activity:U,reason:H,updatedAt:q,nextActionAt:b.Optional(q),retry:b.Optional(X),admission:b.Optional(Y),circuit:b.Optional(z),stall:b.Optional(C),fallback:b.Optional(T)},{additionalProperties:!1}),N=K(b.Object({version:b.Literal(1),generation:b.String({minLength:1,maxLength:Z,pattern:"^[^\x00-\x1F]+$"}),revision:g,snapshot:b.Union([I,b.Null()])},{additionalProperties:!1}));function V(Q){let k=[...Q].filter((W)=>{let w=W.codePointAt(0)??0;return w>31&&w!==127}).join("").trim().slice(0,L);if(!k)throw Error("Provider recovery identity is empty");if(k.includes("://"))throw Error("Provider recovery identity cannot be a URL");return k}
|
|
2
|
+
export{N as kg,V as lg};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Qa as H}from"./chunk-
|
|
1
|
+
import{Qa as H}from"./chunk-2m79vd9p.js";import"./chunk-3eskgvpy.js";import"./chunk-zx78c1an.js";import{Sf as $,Yf as T}from"./chunk-mjnkxem3.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import"./chunk-atdq9btn.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import{Vi as k}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{V as I}from"./chunk-
|
|
1
|
+
import{V as I}from"./chunk-y66f1t18.js";import{be as M}from"./chunk-nqts5by0.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 B,$ as C,V as D,x as E,i as F,K as G};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
|
|
2
|
-
export{s as
|
|
2
|
+
export{s as pg,g as qg};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{If as a,Jf as b,Kf as c,Lf as d,Mf as e,Nf as f,Of as g,Pf as h,Qf as i,Rf as j,Sf as k,Tf as l,Uf as m,Vf as n,Wf as o,Xf as p,Yf as q}from"./chunk-mjnkxem3.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-atdq9btn.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as Si,D as Ti,P as Ui,V as Vi};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ng as a,Og as b,Pg as c,Qg as d,Rg as e,Sg as f,Tg as g,Ug as h,Vg as i,Wg as j,Xg as k}from"./chunk-nnas8tdt.js";import"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import"./chunk-atdq9btn.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{promises as B}from"node:fs";import q from"node:path";import{LRUCache as H}from"lru-cache";var K=512,Z=new H({max:K});async function L(x){let b=x;while(!0){try{return await B.lstat(q.join(b,".git")),b}catch(V){if(V.code!=="ENOENT")return}let F=q.dirname(b);if(F===b)return;b=F}}async function M(x){let b=q.join(x,".git"),F=await B.lstat(b);if(F.isDirectory())return x;if(!F.isFile())return;let V=await B.readFile(b,"utf8"),J=/^gitdir:\s*(.+)\s*$/im.exec(V);if(!J)return;let Q=await B.realpath(q.isAbsolute(J[1])?J[1]:q.resolve(x,J[1])),Y=Q;try{let z=(await B.readFile(q.join(Q,"commondir"),"utf8")).trim();if(z)Y=await B.realpath(q.resolve(Q,z))}catch(z){if(z.code!=="ENOENT")throw z}return q.basename(Y)===".git"?B.realpath(q.dirname(Y)):void 0}async function N(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x),F=Z.get(b);if(F)return F;let V=b;try{let Q=await L(b);if(Q){let Y=await M(Q),z=q.relative(Q,b);if(Y&&(z===""||!z.startsWith(`..${q.sep}`)&&z!==".."&&!q.isAbsolute(z))){let $=q.resolve(Y,z);V=await B.realpath($).catch(()=>$)}}}catch{}let J={projectPath:b,trustRoot:V};return Z.set(b,J),J}async function S(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x);Z.delete(b)}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as Xj,S as Yj};
|