blade-code 0.10.39 → 0.10.41

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.
Files changed (102) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-zwt7f9ab.js → chunk-01jt0mpr.js} +1 -1
  3. package/dist/{chunk-r1wyfnk8.js → chunk-0hqsdbkr.js} +1 -1
  4. package/dist/chunk-1j2sf8mc.js +1 -0
  5. package/dist/chunk-1kwm2m6t.js +1 -0
  6. package/dist/{chunk-kah7p2zm.js → chunk-22h5kh4z.js} +1 -1
  7. package/dist/{chunk-kth1ra8z.js → chunk-27w2k6t7.js} +7 -7
  8. package/dist/{chunk-shxg223c.js → chunk-2bm55evt.js} +2 -2
  9. package/dist/{chunk-gkc69333.js → chunk-358zaryv.js} +2 -2
  10. package/dist/{chunk-qggnvzkc.js → chunk-3p32k12g.js} +1 -1
  11. package/dist/chunk-4ekrbk2w.js +2 -0
  12. package/dist/{chunk-9s2c9awb.js → chunk-4mdy9d43.js} +1 -1
  13. package/dist/{chunk-nh43dgpd.js → chunk-5sbewyjn.js} +2 -2
  14. package/dist/chunk-5w8edqbt.js +1 -0
  15. package/dist/{chunk-fjcmx039.js → chunk-5ygv33qe.js} +2 -2
  16. package/dist/{chunk-56vs8ewy.js → chunk-5zf8204m.js} +1 -1
  17. package/dist/chunk-62jaf7ej.js +22 -0
  18. package/dist/chunk-6a3c496e.js +1 -0
  19. package/dist/{chunk-sd8ptaz2.js → chunk-6dma8han.js} +2 -2
  20. package/dist/chunk-6fe9kq17.js +1 -0
  21. package/dist/{chunk-7ptkstyx.js → chunk-8xfzbv9v.js} +1 -1
  22. package/dist/{chunk-29abk8tj.js → chunk-9neq5xrb.js} +2 -2
  23. package/dist/{chunk-b5g5mfq1.js → chunk-adgx9vd7.js} +57 -57
  24. package/dist/chunk-asnzpfzh.js +10 -0
  25. package/dist/chunk-atdeg922.js +2 -0
  26. package/dist/{chunk-93jx06kq.js → chunk-b5b8fb9y.js} +1 -1
  27. package/dist/{chunk-5ajyr2am.js → chunk-bdxaz350.js} +1 -1
  28. package/dist/{chunk-22pmyhp9.js → chunk-bw7fgs2n.js} +1 -1
  29. package/dist/{chunk-b1pz71cr.js → chunk-ck8sw2zp.js} +1 -1
  30. package/dist/chunk-d61673v7.js +5 -0
  31. package/dist/{chunk-59v0kdc9.js → chunk-djr17h80.js} +45 -45
  32. package/dist/{chunk-qp6k78yb.js → chunk-dp9xzsja.js} +1 -1
  33. package/dist/{chunk-79gk29st.js → chunk-eg5sz4bw.js} +1 -1
  34. package/dist/{chunk-ckfc7j7m.js → chunk-ens8nsge.js} +1 -1
  35. package/dist/{chunk-f3xwk6be.js → chunk-f4bx2n1y.js} +3 -3
  36. package/dist/chunk-f7y4m3y0.js +1 -0
  37. package/dist/chunk-fnz5g9ac.js +1 -0
  38. package/dist/{chunk-3rjmkaey.js → chunk-fxw1q5j5.js} +1 -1
  39. package/dist/{chunk-byekf2bq.js → chunk-fz55cnws.js} +2 -2
  40. package/dist/{chunk-6360fg4j.js → chunk-g9re8v25.js} +1 -1
  41. package/dist/{chunk-a7pvtxvz.js → chunk-gbbnjzy8.js} +1 -1
  42. package/dist/{chunk-4yxavv7j.js → chunk-hjkdc185.js} +1 -1
  43. package/dist/chunk-kjn0yaqw.js +1 -0
  44. package/dist/chunk-m883e8d4.js +1 -0
  45. package/dist/chunk-mx5s93np.js +6 -0
  46. package/dist/{chunk-hq18c6r9.js → chunk-n0ebpwxd.js} +1 -1
  47. package/dist/chunk-nhzdkxnx.js +2 -0
  48. package/dist/{chunk-zg6drp32.js → chunk-npgt73cg.js} +1 -1
  49. package/dist/{chunk-ksd1532x.js → chunk-nsawkccy.js} +1 -1
  50. package/dist/chunk-p54vmne8.js +1 -0
  51. package/dist/{chunk-g9a3ht1x.js → chunk-q87nwpsb.js} +1 -1
  52. package/dist/chunk-qy9qkvwe.js +1 -0
  53. package/dist/chunk-s8f8amvg.js +1 -0
  54. package/dist/{chunk-n52vvqfj.js → chunk-sfbprf9r.js} +1 -1
  55. package/dist/{chunk-xvgfbahj.js → chunk-t80e2bms.js} +1 -1
  56. package/dist/{chunk-v11r4ahz.js → chunk-tsskar00.js} +1 -1
  57. package/dist/{chunk-kbmw1can.js → chunk-v80xem15.js} +1 -1
  58. package/dist/chunk-w07gb3h0.js +6 -0
  59. package/dist/{chunk-m6mp65n0.js → chunk-w1vcjwbx.js} +4 -4
  60. package/dist/{chunk-tdqz02hf.js → chunk-wk0vpgwk.js} +234 -234
  61. package/dist/{chunk-mjcgy285.js → chunk-wvc6bx0t.js} +1 -1
  62. package/dist/{chunk-e09g9a7d.js → chunk-x04xb9g3.js} +1 -1
  63. package/dist/chunk-x5s68axq.js +44 -0
  64. package/dist/{chunk-a14dy6yc.js → chunk-xs7w13na.js} +1 -1
  65. package/dist/{chunk-0evyrnx0.js → chunk-y30kw6gj.js} +1 -1
  66. package/dist/{chunk-4eg9qnxt.js → chunk-yhw0pvyt.js} +2 -2
  67. package/dist/{chunk-xs8v8nhj.js → chunk-yxwargqc.js} +1 -1
  68. package/dist/chunk-z15h0370.js +1 -0
  69. package/dist/{chunk-aesdm7cg.js → chunk-zracmha2.js} +1 -1
  70. package/dist/web/assets/{ChatView-BY2JoPwW.js → ChatView-BP89vdT_.js} +9 -9
  71. package/dist/web/assets/{CodeBlockHighlighter-BIeXOc6N.js → CodeBlockHighlighter-UnjC3KVk.js} +1 -1
  72. package/dist/web/assets/{FilePreview-CLfqslxP.js → FilePreview-D0BiZowf.js} +1 -1
  73. package/dist/web/assets/{MarkdownRenderer-D-iAfBPN.js → MarkdownRenderer-CPu_rkPT.js} +3 -3
  74. package/dist/web/assets/{SettingsModal-D9SfF3HV.js → SettingsModal-CM9pcJas.js} +1 -1
  75. package/dist/web/assets/{TaskSwitcher-CKYCrKc2.js → TaskSwitcher-BOCm7kPO.js} +1 -1
  76. package/dist/web/assets/{TerminalPanel-Bj4qKgM6.js → TerminalPanel-CUZ4slSS.js} +1 -1
  77. package/dist/web/assets/{index-Dwm-v3BV.js → index-CthLsVgC.js} +7 -7
  78. package/dist/web/assets/{session-events-Yagzv-3E.js → session-events-109FkhOM.js} +5 -5
  79. package/dist/web/index.html +2 -2
  80. package/package.json +1 -1
  81. package/dist/chunk-1kbn1ypd.js +0 -1
  82. package/dist/chunk-3m0c6znc.js +0 -44
  83. package/dist/chunk-6yd3j5v5.js +0 -2
  84. package/dist/chunk-7b68psjh.js +0 -1
  85. package/dist/chunk-83mfrs3p.js +0 -5
  86. package/dist/chunk-99n3w3tg.js +0 -1
  87. package/dist/chunk-9q7v4ad9.js +0 -1
  88. package/dist/chunk-a51m3ysp.js +0 -1
  89. package/dist/chunk-bvdk0hb2.js +0 -2
  90. package/dist/chunk-bzymtpc8.js +0 -22
  91. package/dist/chunk-ekfxm6g8.js +0 -1
  92. package/dist/chunk-g2m6y08q.js +0 -1
  93. package/dist/chunk-gq29vpef.js +0 -6
  94. package/dist/chunk-gsx7sw92.js +0 -6
  95. package/dist/chunk-gvkb3mrd.js +0 -1
  96. package/dist/chunk-jc498kjk.js +0 -10
  97. package/dist/chunk-m88j03bm.js +0 -1
  98. package/dist/chunk-p2t4gj7w.js +0 -1
  99. package/dist/chunk-skxst3ya.js +0 -1
  100. package/dist/chunk-thstqcg3.js +0 -2
  101. package/dist/chunk-ya6xazne.js +0 -1
  102. package/dist/chunk-zjzz2mh9.js +0 -1
@@ -0,0 +1,10 @@
1
+ import{f as T,g as W,h as X,i as Y}from"./chunk-w1vcjwbx.js";import"./chunk-t80e2bms.js";import"./chunk-5zf8204m.js";import"./chunk-yxwargqc.js";import"./chunk-nsawkccy.js";import"./chunk-wk0vpgwk.js";import"./chunk-wvc6bx0t.js";import"./chunk-v80xem15.js";import"./chunk-adgx9vd7.js";import"./chunk-5cgyevqj.js";import"./chunk-zracmha2.js";import"./chunk-qgez5vw6.js";import"./chunk-bdxaz350.js";import{$c as R}from"./chunk-hjkdc185.js";import"./chunk-y30kw6gj.js";import{vd as Q}from"./chunk-27w2k6t7.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-d61673v7.js";import"./chunk-4ekrbk2w.js";import"./chunk-fxw1q5j5.js";import"./chunk-yhw0pvyt.js";import"./chunk-6dma8han.js";import"./chunk-n0ebpwxd.js";import"./chunk-01jt0mpr.js";import"./chunk-ens8nsge.js";import"./chunk-f4bx2n1y.js";import"./chunk-tsskar00.js";import"./chunk-x5s68axq.js";import"./chunk-gbbnjzy8.js";import"./chunk-b5b8fb9y.js";import"./chunk-atdeg922.js";import"./chunk-g9re8v25.js";import"./chunk-nhzdkxnx.js";import"./chunk-fz55cnws.js";import"./chunk-5ygv33qe.js";import"./chunk-x04xb9g3.js";import{Bg as M}from"./chunk-358zaryv.js";import"./chunk-5sbewyjn.js";import"./chunk-npgt73cg.js";import"./chunk-9neq5xrb.js";import"./chunk-22h5kh4z.js";import m from"chalk";import K from"open";var A=`
2
+ ____ _ _
3
+ | __ )| | __ _ __| | ___
4
+ | _ \\| |/ _\` |/ _\` |/ _ \\
5
+ | |_) | | (_| | (_| | __/
6
+ |____/|_|\\__,_|\\__,_|\\___|
7
+ `,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
8
+ `));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
9
+ `)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
10
+ `));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as If,T as Jf,A as Kf};
@@ -1,2 +1,2 @@
1
1
  import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
2
- export{a as Bf,f as Cf,l as Df,x as Ef,b as Ff,V as Gf};
2
+ export{a as Cf,f as Df,l as Ef,x as Ff,b as Gf,V as Hf};
@@ -1,4 +1,4 @@
1
- import{ag as i}from"./chunk-byekf2bq.js";import{Dg as j,Eg as n,vg as o,xg as C,zg as L}from"./chunk-29abk8tj.js";import{Fg as I}from"./chunk-kah7p2zm.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
1
+ import{ng as i}from"./chunk-fz55cnws.js";import{Ig as o,Kg as C,Mg as L,Qg as j,Rg as n}from"./chunk-9neq5xrb.js";import{Sg as I}from"./chunk-22h5kh4z.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
2
2
  `),W=!_.endsWith(`
3
3
  `),$=[];for(let[H,k]of R.entries())try{let M=V_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E=await V.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map(x).join(`
4
4
  `)}
@@ -1 +1 @@
1
- import{Mc as a,Nc as b,Oc as c,Pc as d,Qc as e,Rc as f,Sc as g,Tc as h}from"./chunk-5ajyr2am.js";import"./chunk-byekf2bq.js";import"./chunk-29abk8tj.js";import"./chunk-kah7p2zm.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
1
+ import{Mc as a,Nc as b,Oc as c,Pc as d,Qc as e,Rc as f,Sc as g,Tc as h}from"./chunk-bdxaz350.js";import"./chunk-fz55cnws.js";import"./chunk-9neq5xrb.js";import"./chunk-22h5kh4z.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
@@ -1,2 +1,2 @@
1
- import{og as d,qg as h}from"./chunk-gkc69333.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{Bg as d,Dg as h}from"./chunk-358zaryv.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as Uc,w as Vc};
@@ -0,0 +1,5 @@
1
+ import{$f as Uf,Sf as ax,Tf as uf,Uf as cf,Vf as ox,Wf as kf,Yf as Sf,_f as Kf,ag as hf,bg as Qf,dg as Df,eg as bf,gg as B}from"./chunk-nhzdkxnx.js";import{ng as t}from"./chunk-fz55cnws.js";import{rg as ef,tg as Zf}from"./chunk-5ygv33qe.js";import{wg as wx}from"./chunk-x04xb9g3.js";var P_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},sf=(f)=>P_[f]||{};var E_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Gf(f){return typeof f==="string"&&E_.has(f)}function P0(f){if(!f.aborted)return;if(Gf(f.reason))return f.reason;return"user-cancel"}function h0(f){if(Gf(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 af(...f){let x=f.filter(Boolean);if(x.length===0)return new AbortController().signal;if(x.length===1)return x[0];let _=AbortSignal;if(typeof _.any==="function")return _.any(x);for(let P of x)if(P.aborted)return P;let M=new AbortController,T=new Map;for(let P of x){let D=()=>{M.abort(P.reason);for(let[U,E]of T)U.removeEventListener("abort",E)};T.set(P,D)}for(let[P,D]of T)P.addEventListener("abort",D,{once:!0});return M.signal}function r(f,x,_){let M=_?.throwOnAbort??!1;if(x?.aborted){if(M)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((T,P)=>{let D,U=setTimeout(()=>{if(x&&D)x.removeEventListener("abort",D);T()},f);if(x)D=()=>{if(clearTimeout(U),M)P(new DOMException("Aborted","AbortError"));else T()},x.addEventListener("abort",D,{once:!0})})}var U_=t("Chat"),h_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Yf(f){if(typeof f==="string")return f;return f.filter((x)=>x.type==="text").map((x)=>x.text).join(`
2
+ `)}function D_(f){if(!f)return{};try{let x=JSON.parse(f);return x&&typeof x==="object"&&!Array.isArray(x)?x:{}}catch{return U_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function R_(f){let x=f.match(/^data:([^;,]+);base64,(.+)$/s);return x?{mimeType:x[1],data:x[2]}:void 0}async function V_(f,x){let _=R_(f);if(_)return{type:"image",..._};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let M=await fetch(f,{signal:x});if(!M.ok)throw Error(`Failed to load image ${f}: HTTP ${M.status}`);return{type:"image",mimeType:M.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await M.arrayBuffer()).toString("base64")}}async function df(f,x,_,M,T){let P=f.filter((E)=>E.role==="system").map((E)=>Yf(E.content)).filter(Boolean).join(`
3
+
4
+ `),D=[];for(let E of f){if(E.role==="system")continue;if(E.role==="user"){let V=x.input.includes("image"),A=typeof E.content==="string"?E.content:await Promise.all(E.content.map((R)=>R.type==="text"?Promise.resolve({type:"text",text:R.text}):V?V_(R.image_url.url,M):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));D.push({role:"user",content:A,timestamp:Date.now()});continue}if(E.role==="assistant"){let V=[];if(E.reasoningContent?.trim())V.push({type:"thinking",thinking:E.reasoningContent});let A=Yf(E.content);if(A)V.push({type:"text",text:A});for(let R of E.tool_calls??[]){if(!("function"in R))continue;V.push({type:"toolCall",id:R.id,name:R.function.name,arguments:D_(R.function.arguments)})}D.push({role:"assistant",content:V,api:x.api,provider:x.provider,model:x.id,usage:h_,stopReason:E.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}D.push({role:"toolResult",toolCallId:E.tool_call_id??"",toolName:E.name??"unknown",content:[{type:"text",text:Yf(E.content)}],isError:!1,timestamp:Date.now()})}let U=_?.filter((E)=>!T||E.name===T).map((E)=>({name:E.name,description:E.description,parameters:E.parameters,constrainedSampling:E.constrainedSampling}));return{...P?{systemPrompt:P}:{},messages:D,...U?.length?{tools:U}:{}}}function rf(f){let x=[];for(let _=0;_<f.length;_++){let M=f[_];if(M.role==="tool")continue;let T=M.role==="assistant"&&M.tool_calls?.length?M.tool_calls:void 0;if(!T){x.push(M);continue}let P=[],D=_+1;while(D<f.length&&f[D].role==="tool")P.push(f[D++]);let U=new Set(T.map((A)=>A.id)),E=P.filter((A)=>A.tool_call_id&&U.has(A.tool_call_id)),V=new Set(E.map((A)=>A.tool_call_id));if(U.size===T.length&&E.length===U.size&&V.size===U.size)x.push(M,...E);_=D-1}return x}function nf(f){return f.some((x)=>x.role==="assistant"&&Boolean(x.tool_calls?.length)&&!x.reasoningContent?.trim())}function fx(f,x){return{...f,...x.baseUrl?{baseUrl:ef(f.api,x.baseUrl)}:{},...x.maxOutputTokens?{maxTokens:x.maxOutputTokens}:{}}}function Cf(f){let x=f.modelCatalog??Zf();return{models:x.models,model:fx(x.getModel(f.provider,f.model),f)}}function xx(f,x){let _=f.modelCatalog??Zf();return fx(_.getModel(x.provider,x.model),f)}import{randomBytes as W_}from"node:crypto";import{createHmac as j_}from"node:crypto";function z_(f){try{let x=new URL(f);if(x.hash="",x.hostname=x.hostname.toLowerCase(),x.searchParams.sort(),x.pathname!=="/")x.pathname=x.pathname.replace(/\/+$/,"");return x.toString()}catch{return f.trim().replace(/\/+$/,"")}}function H_(f){if(!f)return[];return Object.entries(f).map(([x,_])=>[x.trim().toLowerCase(),_.trim()]).sort(([x],[_])=>x.localeCompare(_))}function Af(f,x,_){let M=JSON.stringify([f.provider.trim(),String(f.api).trim(),z_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",H_(f.customHeaders),_]);return j_("sha256",Buffer.from(x)).update(M).digest("hex")}var $_=60000,X_=4,G_=0.8;var Ef=300000,Jf=600000;var _x=128,Mx=256,Y_=1800000,Pf=50;class n 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 Nf(f){return f instanceof n||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function l(f,x){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:x}function Z_(f,x){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:x}function C_(f,x){return Af(f,x,{providerCircuitOpenDurationMs:f.openDurationMs})}function i(f){let x=0;for(let _ of f)if(_.failure)x++;return x}function Tx(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function Ax(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Sf)}class Ex{#A=new Map;#U=new WeakMap;#f;#x;#M;#_;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):W_(32),this.#x=f.now??(()=>performance.now()),this.#M=f.wallNow??f.now??Date.now,this.#_={maxEntries:Math.min(l(f.maxEntries,_x),_x),maxWindowEntries:Math.min(l(f.maxWindowEntries,Mx),Mx),windowMs:l(f.windowMs,$_),minSamples:l(f.minSamples,X_),errorRateThreshold:Z_(f.errorRateThreshold,G_),idleTtlMs:l(f.idleTtlMs,Y_)}}get size(){return this.#A.size}get(f){if(f.openDurationMs===0)return this.#P();let x=this.#x();this.#X(x);let _=C_(f,this.#f),M=this.#A.get(_);if(M)return M.lastTouchedAt=x,this.#T(M,f.probeLeaseMs);if(this.#A.size>=this.#_.maxEntries)this.#Z();if(this.#A.size>=this.#_.maxEntries)return this.#P();let T={key:_,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:x,detached:!1};return this.#A.set(_,T),this.#T(T,f.probeLeaseMs)}#T(f,x){let _=this,M=Math.max(Ef,Math.min(l(x,Ef),Jf));return{preflight:()=>_.#V(f),check:()=>_.#j(f,M),recordSuccess:(T)=>_.#W(T,"success"),recordFailure:(T,P)=>_.#W(T,"failure",P),recordNeutral:(T)=>_.#W(T,"neutral"),abandon:(T)=>_.#Y(T),snapshot:()=>_.#G(f)}}#P(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let x=Object.freeze({kind:"noop"});return f.#U.set(x,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:x}},recordSuccess:(x)=>f.#E(x),recordFailure:(x)=>f.#E(x),recordNeutral:(x)=>f.#E(x),abandon:(x)=>f.#Y(x),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#E(f){let x=this.#U.get(f);if(x?.kind==="noop")x.settled=!0;return}#V(f){let x=this.#x();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=x,this.#$(f,x),f.state==="closed")return{eligible:!0};if(f.state==="open"){let M=f.nextProbeAt??x;return x<M?this.#h(f,M-x):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&x>=f.probeLeaseExpiresAt)return{eligible:!0};let _=Math.max(1,(f.probeLeaseExpiresAt??x+Pf)-x);return this.#h(f,Math.min(Pf,_))}#h(f,x){let{allowed:_,...M}=this.#H(f,x);return{eligible:!1,...M}}#j(f,x){let _=this.#x();if(f.detached)return this.#P().check();if(f.lastTouchedAt=_,this.#$(f,_),f.state==="closed")return this.#D(f,"regular");if(f.state==="open"){let T=f.nextProbeAt??_;if(_<T)return this.#H(f,T-_);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.#z(f,_,x);let M=Math.max(1,(f.probeLeaseExpiresAt??_+Pf)-_);return this.#H(f,Math.min(Pf,M))}#D(f,x,_){let M=Object.freeze({kind:x});return this.#U.set(M,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:x,..._!==void 0?{probeLeaseId:_}:{},settled:!1}),{allowed:!0,probe:x==="probe",token:M}}#z(f,x,_){let M=f.nextProbeLeaseId++;f.probeLeaseId=M,f.probeLeaseExpiresAt=x+_,f.lastTouchedAt=x;let T=this.#D(f,"probe",M),P=f.lastFailure??{reason:"server_error"};return{...T,reason:P.reason,...P.statusCode!==void 0?{statusCode:P.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:i(f.samples)}}#H(f,x){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(x)),nextProbeAt:this.#M()+Math.max(0,Math.ceil(x)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:i(f.samples)}}#W(f,x,_){let M=this.#U.get(f);if(!M||M.settled)return;if(M.settled=!0,M.kind==="noop"||!M.entry)return;let T=M.entry;if(T.detached||M.generation!==T.generation||M.kind==="regular"&&T.state!=="closed"||M.kind==="probe"&&(T.state!=="half_open"||M.probeLeaseId!==T.probeLeaseId))return;let P=this.#x();if(T.lastTouchedAt=P,M.kind==="probe"){if(x==="failure"&&_)return this.#R(T,_,P,"reopened");return this.#k(T)}if(x==="neutral")return;if(this.#S(T,x==="failure",P),x!=="failure"||!_)return;let D=i(T.samples),U=T.samples.length===0?0:D/T.samples.length;if(T.samples.length>=this.#_.minSamples&&U>=this.#_.errorRateThreshold)return this.#R(T,_,P,"opened");return}#R(f,x,_,M){let T={reason:x.reason,...Tx(x.statusCode)!==void 0?{statusCode:Tx(x.statusCode)}:{},...Ax(x.retryAfterMs)!==void 0?{retryAfterMs:Ax(x.retryAfterMs)}:{}},P=T.retryAfterMs??0,D=Math.max(f.configuredOpenDurationMs,P);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=D,f.nextProbeAt=_+D,f.lastFailure=T,{phase:M,reason:T.reason,...T.statusCode!==void 0?{statusCode:T.statusCode}:{},retryAfterMs:D,nextProbeAt:this.#M()+D,openDurationMs:D,sampleCount:f.samples.length,failureCount:i(f.samples)}}#k(f){let x=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:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#Y(f){let x=this.#U.get(f);if(!x||x.settled)return!1;if(x.settled=!0,x.kind==="noop")return!0;let _=x.entry;if(!_||_.detached||x.kind!=="probe"||x.generation!==_.generation||x.probeLeaseId!==_.probeLeaseId)return!1;return _.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.lastTouchedAt=this.#x(),!0}#S(f,x,_){if(this.#$(f,_),f.samples.length>=this.#_.maxWindowEntries)f.samples.shift();f.samples.push({at:_,failure:x})}#$(f,x){let _=x-this.#_.windowMs,M=0;while(M<f.samples.length&&f.samples[M].at<_)M++;if(M>0)f.samples.splice(0,M)}#G(f){if(!f.detached)this.#$(f,this.#x());return{state:f.state,sampleCount:f.samples.length,failureCount:i(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#X(f){for(let[x,_]of this.#A)if(_.state==="closed"&&f-_.lastTouchedAt>this.#_.idleTtlMs)this.#C(x,_)}#Z(){let f;for(let x of this.#A.values())if(x.state==="closed"&&(!f||x.lastTouchedAt<f.lastTouchedAt))f=x;if(f)this.#C(f.key,f)}#C(f,x){x.detached=!0,this.#A.delete(f)}}var Px;function Ux(){return Px??=new Ex,Px}import{randomBytes as k_}from"node:crypto";var hx=16,Dx=128,Rx=32,Vx=3,jx=16,zx=96,Hx=24,Wx=12,$x=16,Xx=4,Gx=4,Yx=67108864,Zx=33554432,Cx=12,kx=2,Sx=2,Jx=1,Qx=15000,Nx=30000;class e extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,x,_,M,T,P,D,U){super(f==="queue_full"?`Provider request admission ${x} ${M} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${x} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=x;this.requestClass=_;this.resource=M;this.inFlight=T;this.limit=P;this.queued=D;this.maxWaitMs=U;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function ff(f){return f instanceof e||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function Z(f,x,_){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return x;return Math.min(f,_)}function S_(f){let x=Z(f.globalMaxInFlight,hx,hx),_=Z(f.globalMaxPending,Dx,Dx),M=Z(f.domainMaxPending,Rx,Rx),T=Math.min(Z(f.ownerMaxInFlight,Vx,Vx),x),P=Math.min(Z(f.ownerMaxPending,jx,jx),_),D=Math.min(Z(f.nonForegroundGlobalMaxPending,Math.min(zx,Math.max(1,Math.floor(_*3/4))),zx),_),U=Math.min(Z(f.nonForegroundDomainMaxPending,Math.min(Hx,Math.max(1,Math.floor(M*3/4))),Hx),M),E=Math.min(Z(f.nonForegroundOwnerMaxPending,Math.min(Wx,Math.max(1,Math.floor(P*3/4))),Wx),P),V=Math.min(Z(f.internalGlobalMaxPending,Math.min($x,Math.max(1,Math.floor(_/8))),$x),D),A=Math.min(Z(f.internalDomainMaxPending,Math.min(Xx,Math.max(1,Math.floor(M/8))),Xx),U),R=Math.min(Z(f.internalOwnerMaxPending,Math.min(Gx,Math.max(1,Math.floor(P/4))),Gx),E),j=Z(f.globalMaxPendingBytes,B,B),z=Math.min(Z(f.domainMaxPendingBytes,Yx,Yx),j),Q=Math.min(Z(f.ownerMaxPendingBytes,Zx,Zx),j),b=Math.min(Z(f.nonForegroundGlobalMaxInFlight,Math.min(Cx,x),Cx),x),u=Math.min(Z(f.nonForegroundOwnerMaxInFlight,Math.min(kx,T),kx),T),Vf=Math.min(Z(f.internalGlobalMaxInFlight,Math.min(Sx,x),Sx),x),xf=Z(f.internalDomainMaxInFlight,Jx,Jx),jf=Z(f.agingMs,Nx,Nx);return{globalMaxInFlight:x,globalMaxPending:_,domainMaxPending:M,ownerMaxInFlight:T,ownerMaxPending:P,nonForegroundGlobalMaxPending:D,nonForegroundDomainMaxPending:U,nonForegroundOwnerMaxPending:E,internalGlobalMaxPending:V,internalDomainMaxPending:A,internalOwnerMaxPending:R,globalMaxPendingBytes:j,domainMaxPendingBytes:z,ownerMaxPendingBytes:Q,nonForegroundGlobalMaxInFlight:b,nonForegroundOwnerMaxInFlight:u,internalGlobalMaxInFlight:Vf,internalDomainMaxInFlight:xf,agingMs:jf}}function Ox(f,x){if(!f.trim())throw Error(`${x} must not be blank`)}function J_(f){if(Ox(f.sessionId,"sessionId"),Ox(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<Uf||f.scope.maxConcurrent>hf)throw Error(`maxConcurrent must be between ${Uf} and ${hf}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>B)throw Error(`maxPendingBytes must be between 1 and ${B}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>B+1)throw Error(`pendingBytes must be between 1 and ${B+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Df)throw Error(`maxWaitMs must be 0-${Df}`)}function Of(f,x){if(x!==void 0)return x;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function N_(f,x){return Af(f,x,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class bx{#A;#U;#f;#x=[];#M=new Map;#_=new Map;#T=0;#P=0;#E=0;#V=0;#h=0;#j=0;#D=0;#z=0;#H=1;#W=0;#R=!1;constructor(f={}){this.#A=f.processSecret?new Uint8Array(f.processSecret):k_(32),this.#U=f.now??(()=>performance.now()),this.#f=S_(f)}admit(f){if(J_(f),this.#R)throw this.#O("closed",f,{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight},this.#x.length);if(f.signal?.aborted)throw Of(f.signal);let x=N_(f.scope,this.#A),_=this.#M.get(x),M=this.#_.get(f.ownerId),T=_??this.#S(f.scope.maxConcurrent),P=M??this.#$();if(this.#x.length===0&&this.#G(T,P,f.requestClass)){if(!_)this.#M.set(x,T);if(!M)this.#_.set(f.ownerId,P),this.#H++;let j=this.#Z(x,f.ownerId,f.requestClass),z=this.#v(f,0);return{ready:Promise.resolve(j),getSnapshot:()=>({...z}),cancel:()=>{z={...z}}}}let D=this.#k(f,T,P);if(D)throw this.#O("queue_full",f,D,this.#x.length);let U=this.#X(T,P,f.requestClass);if(f.maxWaitMs===0)throw this.#O("wait_timeout",f,U,this.#x.length);if(!_)this.#M.set(x,T);if(!M)this.#_.set(f.ownerId,P),this.#H++;let E,V,A=new Promise((j,z)=>{E=j,V=z});A.catch(()=>{return});let R={domainKey:x,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#U(),signal:f.signal,resolve:E,reject:V,settled:!1,admitted:!1};if(f.signal)R.abortListener=()=>this.#K(R,Of(f.signal)),f.signal.addEventListener("abort",R.abortListener,{once:!0});return R.timer=setTimeout(()=>this.#B(R),f.maxWaitMs),R.timer.unref?.(),this.#x.push(R),this.#Y(T,P,R),this.#J(),{ready:A,getSnapshot:()=>this.#F(R),cancel:(j)=>this.#K(R,Of(f.signal,j))}}close(){if(this.#R)return;this.#R=!0;for(let f of[...this.#x]){let x=this.#M.get(f.domainKey),_=this.#_.get(f.ownerId),M=x&&_?this.#X(x,_,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};this.#N(f,new e("closed",M.scope,f.requestClass,M.resource,M.inFlight,M.limit,this.#x.length,f.maxWaitMs))}}getStats(){return{inFlight:this.#T,queued:this.#x.length,pendingBytes:this.#j,nonForegroundInFlight:this.#P,internalInFlight:this.#E,nonForegroundQueued:this.#V,internalQueued:this.#h,nonForegroundPendingBytes:this.#D,internalPendingBytes:this.#z,domainCount:this.#M.size,ownerCount:this.#_.size,closed:this.#R}}#k(f,x,_){let M=(A,R,j)=>R>=j?{scope:A,resource:"pending_count",inFlight:R,limit:j}:void 0;if(f.requestClass==="internal"){let A=M("class",this.#h,this.#f.internalGlobalMaxPending)??M("class",_.internalQueued,this.#f.internalOwnerMaxPending)??M("class",x.internalQueued,this.#f.internalDomainMaxPending);if(A)return A}if(f.requestClass!=="foreground"){let A=M("class",this.#V,this.#f.nonForegroundGlobalMaxPending)??M("class",_.nonForegroundQueued,this.#f.nonForegroundOwnerMaxPending)??M("class",x.nonForegroundQueued,this.#f.nonForegroundDomainMaxPending);if(A)return A}let T=M("global",this.#x.length,this.#f.globalMaxPending)??M("owner",_.queued,this.#f.ownerMaxPending)??M("domain",x.queued,this.#f.domainMaxPending);if(T)return T;let P=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),D=Math.min(P,this.#f.domainMaxPendingBytes),U=Math.min(P,this.#f.ownerMaxPendingBytes),E=(A,R)=>f.pendingBytes>R-A,V=(A)=>{if(A==="owner")return{scope:A,resource:"pending_bytes",inFlight:_.inFlight,limit:this.#f.ownerMaxInFlight};if(A==="domain")return{scope:A,resource:"pending_bytes",inFlight:x.inFlight,limit:x.maxConcurrent};return{scope:A,resource:"pending_bytes",inFlight:this.#T,limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let A=Math.max(1,Math.floor(P/8)),R=Math.max(1,Math.floor(D/4)),j=Math.max(1,Math.floor(U/4));if(E(this.#z,A)||E(_.internalPendingBytes,j)||E(x.internalPendingBytes,R))return V("class")}if(f.requestClass!=="foreground"){let A=Math.max(1,Math.floor(P*3/4)),R=Math.max(1,Math.floor(D*3/4)),j=Math.max(1,Math.floor(U/2));if(E(this.#D,A)||E(_.nonForegroundPendingBytes,j)||E(x.nonForegroundPendingBytes,R))return V("class")}if(E(this.#j,P))return V("global");if(E(_.pendingBytes,U))return V("owner");if(E(x.pendingBytes,D))return V("domain");return}#Y(f,x,_){if(f.queued++,x.queued++,this.#j+=_.pendingBytes,f.pendingBytes+=_.pendingBytes,x.pendingBytes+=_.pendingBytes,_.requestClass!=="foreground")this.#V++,f.nonForegroundQueued++,x.nonForegroundQueued++,this.#D+=_.pendingBytes,f.nonForegroundPendingBytes+=_.pendingBytes,x.nonForegroundPendingBytes+=_.pendingBytes;if(_.requestClass==="internal")this.#h++,f.internalQueued++,x.internalQueued++,this.#z+=_.pendingBytes,f.internalPendingBytes+=_.pendingBytes,x.internalPendingBytes+=_.pendingBytes}#S(f){return{maxConcurrent:f,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#$(){return{order:this.#H,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#G(f,x,_){if(this.#T>=this.#f.globalMaxInFlight)return!1;if(f.inFlight>=f.maxConcurrent)return!1;if(x.inFlight>=this.#f.ownerMaxInFlight)return!1;if(_==="foreground")return!0;if(this.#P>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(x.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let M=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=M)return!1;if(_!=="internal")return!0;return this.#E<this.#f.internalGlobalMaxInFlight&&f.internalInFlight<this.#f.internalDomainMaxInFlight}#X(f,x,_){if(x.inFlight>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:x.inFlight,limit:this.#f.ownerMaxInFlight};if(_!=="foreground"&&x.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:x.nonForegroundInFlight,limit:this.#f.nonForegroundOwnerMaxInFlight};if(f.inFlight>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent};if(_!=="foreground"){let M=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=M)return{scope:"class",resource:"stream",inFlight:f.nonForegroundInFlight,limit:M}}if(_==="internal"&&f.internalInFlight>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.internalInFlight,limit:this.#f.internalDomainMaxInFlight};if(this.#T>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};if(_!=="foreground"&&this.#P>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#P,limit:this.#f.nonForegroundGlobalMaxInFlight};if(_==="internal"&&this.#E>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#E,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent}}#Z(f,x,_){let M=this.#M.get(f),T=this.#_.get(x);if(!M||!T)throw Error("Provider admission accounting state is unavailable");if(this.#T++,M.inFlight++,T.inFlight++,_!=="foreground")this.#P++,M.nonForegroundInFlight++,T.nonForegroundInFlight++;if(_==="internal")this.#E++,M.internalInFlight++,T.internalInFlight++;let P=!1;return{release:()=>{if(P)return;P=!0,this.#C(f,x,_)}}}#C(f,x,_){let M=this.#M.get(f),T=this.#_.get(x);if(this.#T=Math.max(0,this.#T-1),M)M.inFlight=Math.max(0,M.inFlight-1);if(T)T.inFlight=Math.max(0,T.inFlight-1);if(_!=="foreground"){if(this.#P=Math.max(0,this.#P-1),M)M.nonForegroundInFlight=Math.max(0,M.nonForegroundInFlight-1);if(T)T.nonForegroundInFlight=Math.max(0,T.nonForegroundInFlight-1)}if(_==="internal"){if(this.#E=Math.max(0,this.#E-1),M)M.internalInFlight=Math.max(0,M.internalInFlight-1);if(T)T.internalInFlight=Math.max(0,T.internalInFlight-1)}this.#b(f,x),this.#J()}#J(){if(this.#R)return;while(this.#x.length>0){let f=this.#U(),x=new Map;for(let[U,E]of this.#x.entries()){let V=this.#M.get(E.domainKey),A=this.#_.get(E.ownerId);if(V===void 0||A===void 0||!this.#G(V,A,E.requestClass))continue;let R=this.#L(E,f),j=x.get(E.ownerId);if(!j||R<j.rank||R===j.rank&&U<j.index)x.set(E.ownerId,{pending:E,rank:R,index:U})}let _=[...x.values()].filter(({pending:U})=>{let E=this.#M.get(U.domainKey),V=this.#_.get(U.ownerId);return E!==void 0&&V!==void 0&&this.#G(E,V,U.requestClass)}).map(({pending:U,rank:E})=>({pending:U,rank:E,order:this.#_.get(U.ownerId).order}));if(_.length===0)return;let M=Math.min(..._.map((U)=>U.rank)),T=_.filter((U)=>U.rank===M),D=T.filter((U)=>U.order>this.#W).sort((U,E)=>U.order-E.order)[0]??T.sort((U,E)=>U.order-E.order)[0];this.#I(D.pending,D.order)}}#L(f,x){let _=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,M=Math.floor(Math.max(0,x-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,_-M)}#I(f,x){if(!this.#Q(f,!1))return;f.settled=!0,f.admitted=!0,this.#W=x;let _=this.#Z(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#B(f){let x=this.#M.get(f.domainKey),_=this.#_.get(f.ownerId),M=x&&_?this.#X(x,_,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};this.#N(f,new e("wait_timeout",M.scope,f.requestClass,M.resource,M.inFlight,M.limit,this.#x.length,f.maxWaitMs))}#K(f,x){this.#N(f,x)}#N(f,x){if(!this.#Q(f))return;f.settled=!0,f.reject(x),this.#J()}#Q(f,x=!0){if(f.settled||f.admitted)return!1;let _=this.#x.indexOf(f);if(_<0)return!1;this.#x.splice(_,1);let M=this.#M.get(f.domainKey),T=this.#_.get(f.ownerId);if(M&&T)this.#u(M,T,f);if(this.#c(f),x)this.#b(f.domainKey,f.ownerId);return!0}#u(f,x,_){if(f.queued=Math.max(0,f.queued-1),x.queued=Math.max(0,x.queued-1),this.#j=Math.max(0,this.#j-_.pendingBytes),f.pendingBytes=Math.max(0,f.pendingBytes-_.pendingBytes),x.pendingBytes=Math.max(0,x.pendingBytes-_.pendingBytes),_.requestClass!=="foreground")this.#V=Math.max(0,this.#V-1),f.nonForegroundQueued=Math.max(0,f.nonForegroundQueued-1),x.nonForegroundQueued=Math.max(0,x.nonForegroundQueued-1),this.#D=Math.max(0,this.#D-_.pendingBytes),f.nonForegroundPendingBytes=Math.max(0,f.nonForegroundPendingBytes-_.pendingBytes),x.nonForegroundPendingBytes=Math.max(0,x.nonForegroundPendingBytes-_.pendingBytes);if(_.requestClass==="internal")this.#h=Math.max(0,this.#h-1),f.internalQueued=Math.max(0,f.internalQueued-1),x.internalQueued=Math.max(0,x.internalQueued-1),this.#z=Math.max(0,this.#z-_.pendingBytes),f.internalPendingBytes=Math.max(0,f.internalPendingBytes-_.pendingBytes),x.internalPendingBytes=Math.max(0,x.internalPendingBytes-_.pendingBytes)}#c(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}#b(f,x){let _=this.#M.get(f);if(_&&_.inFlight===0&&_.queued===0)this.#M.delete(f);let M=this.#_.get(x);if(M&&M.inFlight===0&&M.queued===0)this.#_.delete(x)}#F(f){let x=Math.max(0,Math.floor(this.#U()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#x.length,inFlight:this.#T,limit:this.#f.globalMaxInFlight,waitMs:x,maxWaitMs:f.maxWaitMs};let _=this.#M.get(f.domainKey),M=this.#_.get(f.ownerId),T=_&&M?this.#X(_,M,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:T.resource,scope:T.scope,reason:"capacity",queuePosition:this.#w(f,T.scope),queueDepth:this.#x.length,inFlight:T.inFlight,limit:T.limit,waitMs:x,maxWaitMs:f.maxWaitMs}}#v(f,x){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#x.length,inFlight:this.#T,limit:this.#f.globalMaxInFlight,waitMs:x,maxWaitMs:f.maxWaitMs}}#w(f,x){let _=this.#x.filter((M)=>{switch(x){case"owner":return M.ownerId===f.ownerId;case"domain":return M.domainKey===f.domainKey;case"class":return M.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,_.indexOf(f)+1)}#O(f,x,_,M){return new e(f,_.scope,x.requestClass,_.resource,_.inFlight,_.limit,M,x.maxWaitMs)}}var Kx;function Lx(){return Kx??=new bx,Kx}var O_=1e5,K_=4,Q_=4,Ix=8,b_=16,v=32,L_=8;function I_(f,x={}){let _=x.maxBytes??B,M=x.maxNodes??O_;if(!Number.isSafeInteger(_)||_<=0||_>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(M)||M<=0)throw Error("maxNodes must be a positive safe integer");let T=new WeakSet,P=0,D=0,U=!1,E=(A)=>{if(U||A<=0)return;if(!Number.isSafeInteger(A)||A>_-P){P=_+1,U=!0;return}P+=A},V=(A)=>{if(U)return;if(D+=1,D>M){E(_+1);return}if(A===null){E(K_);return}switch(typeof A){case"string":E(Buffer.byteLength(A,"utf8"));return;case"number":case"bigint":E(Ix);return;case"boolean":E(Q_);return;case"undefined":case"function":case"symbol":return;case"object":break}if(T.has(A))return;if(T.add(A),ArrayBuffer.isView(A)){E(v+A.byteLength);return}if(A instanceof ArrayBuffer){E(v+A.byteLength);return}if(A instanceof Date){E(v+Ix);return}if(A instanceof RegExp){E(v+Buffer.byteLength(A.source,"utf8"));return}if(A instanceof Map){E(v);for(let[R,j]of A)if(V(R),V(j),U)return;return}if(A instanceof Set){E(v);for(let R of A)if(V(R),U)return;return}if(A instanceof WeakMap||A instanceof WeakSet){E(v);return}if(Array.isArray(A)){E(b_);for(let R of A)if(V(R),U)return;return}E(v);for(let R of Reflect.ownKeys(A)){if(typeof R!=="string")continue;let j=Object.getOwnPropertyDescriptor(A,R);if(!j?.enumerable||!("value"in j))continue;if(E(L_+Buffer.byteLength(R,"utf8")),V(j.value),U)return}};return V(f),P}function Bx(f){return I_([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:B})}var ux=new WeakSet;class y extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,x){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=x;this.name="ProviderRecoveryBudgetExceededError"}}var B_=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],u_=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],c_=["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 cx(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function F_(f){let x=cx(f);return u_.some((_)=>x.includes(_))}function Lf(f){if(f!==null&&typeof f==="object")ux.add(f)}function w0(f){return f!==null&&typeof f==="object"&&ux.has(f)}function v_(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function w_(f){if(f===null||typeof f!=="object")return;let x=f;for(let _ of["status","statusCode"]){let M=x[_];if(typeof M==="number"&&Number.isInteger(M))return M}return}function q_(f){let x=f.match(/^(?:error:\s*)?(\d{3})\b/),_=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),M=Number(x?.[1]??_?.[1]);return Number.isInteger(M)?M:void 0}function g(f,x){let _=cx(f),M=v_(f);if(M==="STREAM_IDLE_TIMEOUT"||M==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||_.includes("request aborted")||_==="aborted")return{retryable:!1};if(B_.some((P)=>_.includes(P))||F_(f))return{retryable:!1};if(x?.shouldRetry==="false")return{retryable:!1,statusCode:x.statusCode};let T=x?.statusCode??w_(f)??q_(_);if(x?.shouldRetry==="true")return{retryable:!0,reason:T===429?"rate_limit":T===408||T===409?"timeout":"server_error",statusCode:T};if(T===429)return{retryable:!0,reason:"rate_limit",statusCode:T};if(T===408||T===409)return{retryable:!0,reason:"timeout",statusCode:T};if(T!==void 0&&T>=500&&T<=599)return{retryable:!0,reason:"server_error",statusCode:T};if(M==="PROVIDER_STREAM_CLOSED"||_.includes("stream closed before completion")||_.includes("ended without")||_.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:T};if(c_.some((P)=>_.includes(P)))return{retryable:!0,reason:"transport",statusCode:T};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:T};return{retryable:!1,statusCode:T}}function If(f,x){if(!f)return;if(f.retryAfterMs!==void 0){let T=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(T))return Math.max(0,T)}if(f.retryAfter===void 0)return;let _=Number.parseFloat(f.retryAfter);if(Number.isFinite(_))return Math.max(0,_*1000);let M=Date.parse(f.retryAfter);return Number.isFinite(M)?Math.max(0,M-x):void 0}function Fx(f,x,_={}){let M=_.now??Date.now(),T=_.maxDelayMs??60000,P=If(x,M);if(P!==void 0)return Math.min(Math.ceil(P),T);let D=Math.max(0,f-1),U=_.maxExponentialDelayMs??8000,E=Math.min(500*2**D,U),V=Math.max(0,Math.min(1,_.random??Math.random())),A=E*(0.75+V*0.25);return Math.min(Math.round(A),T)}function qx(f,x){let _=f.onPayload;f.onPayload=async(M,T)=>{let P=_?await _(M,T):M;return x(P===void 0?M:P,T)}}function p_(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function m_(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function t_(f,x,_,M){let T=M?void 0:p_(_);if(!T){if(x.api==="anthropic-messages")f.thinkingEnabled=!1;if(x.api==="google-generative-ai"||x.api==="google-vertex")f.thinking={enabled:!1};return}switch(x.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=T;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:m_(T)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=T;break;default:f.reasoningEffort=T}}function l_(f,x,_){if(!_)return;switch(x){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 y_(f,x,_){let M=_.serviceTier;if(!M)return;if(x.api==="openai-responses"||x.api==="openai-codex-responses"||x.api==="azure-openai-responses"){f.serviceTier=M;return}if(x.api!=="openai-completions"&&!(x.api==="anthropic-messages"&&M==="fast"))return;qx(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;return x.api==="anthropic-messages"?{...T,speed:"fast"}:{...T,service_tier:M}})}function g_(f,x,_){let M=_.responseVerbosity;if(!M)return;if(wx(x,M),x.api==="openai-codex-responses"){f.textVerbosity=M;return}qx(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;if(x.api==="openai-completions")return{...T,verbosity:M};let P="text"in T&&T.text&&typeof T.text==="object"&&!Array.isArray(T.text)?T.text:{};return{...T,text:{...P,verbosity:M}}})}function px(f,x,_,M,T=!1){let P={apiKey:f.apiKey,headers:f.customHeaders,signal:_,temperature:M?.temperature??f.temperature??0,maxTokens:M?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:f.enablePromptCaching?"short":"none"};if(t_(P,x,f,T),l_(P,x.api,M?.toolChoice?.toolName),y_(P,x,f),g_(P,x,f),x.api==="azure-openai-responses")P.azureBaseUrl=f.baseUrl,P.azureApiVersion=f.apiVersion,P.azureDeploymentName=x.id;return P}function vx(f,x){let _=x.get("x-should-retry");return{statusCode:f,...x.get("retry-after")!==null?{retryAfter:x.get("retry-after")??void 0}:{},...x.get("retry-after-ms")!==null?{retryAfterMs:x.get("retry-after-ms")??void 0}:{},..._==="true"||_==="false"?{shouldRetry:_}:{}}}var s_=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function mx(f,x,_){let M=f.onResponse;if(f.onResponse=async(P,D)=>{let U=new Headers(P.headers);_(vx(P.status,U)),await M?.(P,D)},!s_.has(x.api)||typeof globalThis.fetch!=="function")return;let T=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(P,D)=>{let U=await T(P,D);return _(vx(U.status,U.headers)),U}}function tx(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 Rf=300000,a_=30000;class lx 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 yx extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function Bf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function o_(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Rf}function d_(f,x){if(x===0)return;let _=x!==void 0&&x>0?x:a_;return Math.max(1,Math.min(_,Math.floor(f/2)))}function r_(f,x,_){if(_?.aborted)return Promise.reject(Bf(_));return new Promise((M,T)=>{let P=!1,D=()=>{clearTimeout(A),_?.removeEventListener("abort",V)},U=(R)=>{if(P)return;P=!0,D(),M(R)},E=(R)=>{if(P)return;P=!0,D(),T(R instanceof Error?R:Error(String(R)))},V=()=>{if(_)E(Bf(_))},A=setTimeout(()=>U({kind:"timer"}),Math.max(0,x));if(_?.addEventListener("abort",V,{once:!0}),_?.aborted){V();return}f.then((R)=>U({kind:"next",result:R}),E)})}async function*i_(f,x,_){let M=o_(x),T=d_(M,x.stallWarningMs);if(x.signal?.aborted)throw Bf(x.signal);let P=Date.now(),D=Promise.resolve().then(()=>f.next()),U;for(;;){let V=await r_(D,(U?M:T??M)-(Date.now()-P),x.signal);if(V.kind==="next"){if(U)yield{...U,phase:"recovered",durationMs:Math.max(U.durationMs,Date.now()-P)};return V.result}if(!U&&T!==void 0){_.stallCount++,U={phase:"detected",stallCount:_.stallCount,durationMs:T,warningAfterMs:T,timeoutMs:M,outputStarted:_.outputStarted},yield U;continue}let A=new lx(M);throw x.abort?.(A),A}}async function*gx(f,x,_,M,T={}){let D=f.stream(x,_,M)[Symbol.asyncIterator](),U=0,E=!1,V={stallCount:0,outputStarted:!1};try{while(!0){let A=i_(D,T,V),R=await A.next();while(!R.done)yield{providerStall:R.value},R=await A.next();let j=R.value;if(j.done)throw new yx;let z=j.value;switch(z.type){case"text_delta":V.outputStarted=!0,yield{content:z.delta};break;case"thinking_delta":V.outputStarted=!0,yield{reasoningContent:z.delta};break;case"toolcall_end":V.outputStarted=!0,yield{toolCalls:[{index:U++,id:z.toolCall.id,type:"function",function:{name:z.toolCall.name,arguments:JSON.stringify(z.toolCall.arguments)}}]};break;case"done":E=!0,yield{finishReason:z.reason,usage:tx(z.message.usage)};return;case"error":throw Error(z.error.errorMessage??`Request ${z.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!E)Promise.resolve(D.return?.()).catch(()=>{return})}}var sx=t("Chat"),n_=1;function e_(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((x)=>x.type==="image_url"))}function f0(f,x){let _=g(f,x);if(!_.retryable||!_.reason)return;let M=_.statusCode;switch(_.reason){case"rate_limit":if(M!==429)return;break;case"server_error":if(M===void 0||M<500||M>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let T=If(x,Date.now());return{reason:_.reason,...M!==void 0?{statusCode:M}:{},...T!==void 0?{retryAfterMs:T}:{}}}function x0(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class Ff{config;models;model;admissionFallbackOwnerId=`pi-service-${process.pid}-${n_++}`;constructor(f){let x=Cf(f);this.config={...f,maxContextTokens:x.model.contextWindow,maxOutputTokens:f.maxOutputTokens??x.model.maxTokens},this.models=x.models,this.model=x.model,sx.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,x,_,M){let T="",P="",D=[],U,E;for await(let V of this.streamChat(f,x,_,M)){T+=V.content??"",P+=V.reasoningContent??"";for(let A of V.toolCalls??[])if(A.id&&A.type==="function"&&A.function?.name)D.push(A);U=V.usage??U,E=V.finishReason??E}return{content:T,...P?{reasoningContent:P}:{},...D.length>0?{toolCalls:D}:{},usage:U,finishReason:E}}async*streamChat(f,x,_,M){let T=M?.toolChoice?.toolName;if(T&&!x?.some((h)=>h.name===T))throw Error(`Required tool is unavailable: ${T}`);let P=rf(f);if(P.some((h)=>e_(h))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let D=Boolean(T)||nf(P),U=await df(P,this.model,x,_,T),E=Bx({messages:P,context:U,tools:x,requestOptions:M}),V=M?.providerRecovery;if(V&&!ox(V.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let A=V?.mode==="bounded_foreground"&&V.budgetMs>0?{budgetMs:V.budgetMs,startedAt:void 0}:void 0,R=A?"bounded_foreground":"standard",j=this.config.maxRetries??2,z=this.config.maxRetries??(A?ax:2),Q=A!==void 0&&this.config.maxRetries===void 0,b=0,u,Vf=this.config.providerCircuitRegistry??Ux(),xf=this.config.providerCircuitBreakerOpenMs??kf,jf=Math.max(Ef,Math.min(this.config.streamIdleTimeout??Rf,Jf)),dx=this.config.providerRequestAdmissionScheduler??Lx(),rx=this.config.providerRequestConcurrency??Kf,vf=this.config.providerRequestAdmissionMs??Qf,ix=this.config.providerRequestPendingBytes??bf,zf=M?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},nx=(h)=>Vf.get({provider:h.provider,api:h.api,baseUrl:h.baseUrl??this.config.baseUrl??"",model:h.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,openDurationMs:xf,probeLeaseMs:jf}),ex=(h)=>({provider:h.provider,api:h.api,baseUrl:h.baseUrl??this.config.baseUrl??"",model:h.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,maxConcurrent:rx,maxPendingBytes:ix}),Y=(h=Date.now())=>{if(!A)return;let H=A.startedAt===void 0?0:Math.min(A.budgetMs,Math.max(0,h-A.startedAt));return{recoveryBudgetMs:A.budgetMs,recoveryElapsedMs:H,recoveryRemainingMs:Math.max(0,A.budgetMs-H)}},F=()=>({mode:R,...Y()??{}}),wf=()=>{if(A&&A.startedAt===void 0)A.startedAt=Date.now()},w=()=>{let h=Y();return new y(A?.budgetMs??0,h?.recoveryElapsedMs??0)},s=()=>!Q||b<z+1,Hf=(h,H)=>{let{state:k,...X}=H;return{phase:h,...X,...Y()?{recoveryRemainingMs:Y()?.recoveryRemainingMs}:{}}},qf=(h)=>({phase:"rejected",requestClass:h.requestClass,resource:h.resource,scope:h.scope,reason:h.reason,queuePosition:0,queueDepth:Math.max(0,h.queued),inFlight:Math.max(0,h.inFlight),limit:Math.max(0,h.limit),waitMs:h.reason==="wait_timeout"?h.maxWaitMs:0,maxWaitMs:h.maxWaitMs,...Y()?{recoveryRemainingMs:Y()?.recoveryRemainingMs}:{}}),f_=async function*(h){let H=Y()?.recoveryRemainingMs,k=H!==void 0&&A?.startedAt!==void 0?Math.min(vf,H):vf,X;try{X=dx.admit({scope:ex(h),sessionId:zf.sessionId,ownerId:zf.ownerId,requestClass:zf.requestClass,maxWaitMs:k,pendingBytes:E,signal:_})}catch(W){if(ff(W)){if(W.reason==="wait_timeout"&&A?.startedAt!==void 0&&(Y()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:qf(W)}}throw W}let I=X.getSnapshot();if(I.state==="admitted")return await X.ready;yield{providerAdmission:Hf("queued",I)};let c=X.ready.then((W)=>({kind:"ready",permit:W}),(W)=>({kind:"error",error:W}));while(!0){let W=X.getSnapshot(),J=Math.max(1,Math.min(Qx,Math.max(1,k-W.waitMs))),N,S=new Promise((q)=>{N=setTimeout(()=>q({kind:"heartbeat"}),J),N.unref?.()}),O=await Promise.race([c,S]);if(N)clearTimeout(N);if(O.kind==="heartbeat"){yield{providerAdmission:Hf("queued",X.getSnapshot())};continue}if(O.kind==="error"){if(ff(O.error)){if(O.error.reason==="wait_timeout"&&A?.startedAt!==void 0&&(Y()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:qf(O.error)}}throw O.error}return yield{providerAdmission:Hf("admitted",X.getSnapshot())},O.permit}},x_=(h)=>{if(!s())throw w();if(Q)b++;u=void 0;let H=new AbortController,k=_?af(_,H.signal):H.signal,X;if(A?.startedAt!==void 0){let W=Y()?.recoveryRemainingMs??0;if(W<=0)throw w();let J=new y(A.budgetMs,A.budgetMs);X=setTimeout(()=>H.abort(J),W),X.unref?.()}let I=px(this.config,h,k,M,D);mx(I,h,(W)=>{u=W});let c=gx(this.models,h,U,I,{idleTimeoutMs:this.config.streamIdleTimeout??Rf,signal:k,abort:(W)=>H.abort(W)});return async function*(){try{yield*c}finally{if(X)clearTimeout(X)}}()},pf=this,m=(h)=>({phase:h.phase,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},...h.retryAfterMs!==void 0?{retryAfterMs:h.retryAfterMs}:{},...h.nextProbeAt!==void 0?{nextProbeAt:h.nextProbeAt}:{},openDurationMs:h.openDurationMs,sampleCount:h.sampleCount,failureCount:h.failureCount,...Y()?{recoveryRemainingMs:Y()?.recoveryRemainingMs}:{}}),mf=(h,H)=>({phase:h,reason:H.reason,...H.statusCode!==void 0?{statusCode:H.statusCode}:{},retryAfterMs:H.retryAfterMs,...H.nextProbeAt!==void 0?{nextProbeAt:H.nextProbeAt}:{},openDurationMs:H.openDurationMs,sampleCount:H.sampleCount,failureCount:H.failureCount,...Y()?{recoveryRemainingMs:Y()?.recoveryRemainingMs}:{}}),__=(h)=>({phase:"probe",reason:h.reason??"server_error",...h.statusCode!==void 0?{statusCode:h.statusCode}:{},openDurationMs:h.openDurationMs??xf,...h.sampleCount!==void 0?{sampleCount:h.sampleCount}:{},...h.failureCount!==void 0?{failureCount:h.failureCount}:{},...Y()?{recoveryRemainingMs:Y()?.recoveryRemainingMs}:{}}),Wf=(h,H,k)=>({providerRetry:{phase:"exhausted",attempt:h,maxRetries:z,reason:H,...k!==void 0?{statusCode:k}:{},...F(),exhaustedBy:"recovery_budget"}}),tf=async function*(h,H,k,X){let I,c=!1,W,J,N=nx(h);for(let S=0;S<=k;S++){if(!s())break;let O,q;while(!O){let $=N.preflight();while(!$.eligible){if(W=$.reason,J=$.statusCode,!A||!X){let L=mf("rejected",$);throw yield{providerCircuit:L},new n(L)}wf();let G=Y()?.recoveryRemainingMs??0;if(G<=0){let L=w();throw yield Wf(Q?Math.max(0,b-1):S,$.reason,$.statusCode),L}yield{providerCircuit:mf("waiting",$)};let p=Math.min(Math.max(1,$.retryAfterMs),uf,G);if(await r(p,_,{throwOnAbort:!0}),(Y()?.recoveryRemainingMs??0)<=0){let L=w();throw yield Wf(Q?Math.max(0,b-1):S,$.reason,$.statusCode),L}$=N.preflight()}try{q=yield*f_(h)}catch(K){if(K instanceof y)yield Wf(Q?Math.max(0,b-1):S,W??"timeout",J);throw K}let C=N.check();if(C.allowed)O=C;else q.release(),q=void 0}let a=O.token;if(O.probe)yield{providerCircuit:__(O)};try{let $=!1,C=!1;for await(let K of x_(h)){if(K.providerStall){yield K;continue}let G=Q?b-1:S;if(G>0&&W&&!$)$=!0,yield{providerRetry:{phase:"recovered",attempt:G,maxRetries:z,reason:W,...J!==void 0?{statusCode:J}:{},...F()}};if(!C){C=!0;let p=N.recordSuccess(a);if(p)yield{providerCircuit:m(p)}}c=!0,H(),yield K}if(!C){let K=N.recordSuccess(a);if(K)yield{providerCircuit:m(K)}}return}catch($){if(q?.release(),I=$,pf.logIdleTimeout($,c,h),await pf.handleAbort(_),$ instanceof y){if(c)throw Lf($),$;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,b-1):S,maxRetries:z,reason:W??"timeout",...J!==void 0?{statusCode:J}:{},...F(),exhaustedBy:"recovery_budget"}},$}let C=g($,u);if(c)throw Lf($),$;let K=f0($,u),G=K?N.recordFailure(a,K):u&&!x0($)?N.recordNeutral(a):void 0;if(G)yield{providerCircuit:m(G)};if(!C.retryable||!C.reason){if(S>0&&W)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,b-1):S,maxRetries:z,reason:W,...J!==void 0?{statusCode:J}:{},...F()}};throw $}W=C.reason,J=C.statusCode;let p=S<k&&s();if(G&&G.phase!=="closed"&&p&&(!A||!X)){let L={...m(G),phase:"rejected"};throw yield{providerCircuit:L},new n(L)}if(p){wf();let L=Q?b:S+1,T_=Fx(L,u,A?{maxDelayMs:cf,maxExponentialDelayMs:cf}:void 0),yf=G&&G.phase!=="closed"?G.retryAfterMs??0:0;if(A&&yf>0&&G)yield{providerCircuit:{...m(G),phase:"waiting"}};let A_=Y(),Xf=Math.max(T_,yf),o=A?Math.min(Xf,A_?.recoveryRemainingMs??Xf):Xf,Mf={attempt:L,maxRetries:z,reason:C.reason,...C.statusCode!==void 0?{statusCode:C.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Mf,delayMs:o,nextRetryAt:Date.now()+o,...F()}},A){let d=o;while(d>0){let gf=Math.min(d,uf);if(await r(gf,_,{throwOnAbort:!0}),d-=gf,(Y()?.recoveryRemainingMs??0)<=0){let Tf=w();throw yield{providerRetry:{phase:"exhausted",...Mf,...F(),exhaustedBy:"recovery_budget"}},Tf}if(d>0){if(G&&G.phase!=="closed"&&G.nextProbeAt!==void 0){let Tf=Math.max(0,G.nextProbeAt-Date.now());if(Tf>0)yield{providerCircuit:{...m(G),phase:"waiting",retryAfterMs:Tf}}}yield{providerRetry:{phase:"waiting",...Mf,delayMs:o,nextRetryAt:Date.now()+d,...F()}}}}}else await r(o,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Mf,...F()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,b-1):S,maxRetries:z,reason:C.reason,...C.statusCode!==void 0?{statusCode:C.statusCode}:{},...F(),...A&&(X||!s())?{exhaustedBy:"attempt_limit"}:{}}}}finally{N.abandon(a),q?.release()}}throw I},$f,lf=!1,_f=this.config.fallbackModels??[],M_=A&&_f.length>0?Math.min(j,z):z;try{for await(let h of tf(this.model,()=>{lf=!0},M_,_f.length===0))yield h;return}catch(h){if($f=h,lf||!ff(h)&&!Nf(h)&&!g(h,u).retryable)throw h}for(let[h,H]of _f.entries()){if(!s())break;yield{modelFallback:!0};let k=!1;try{let X=xx(this.config,H),I=h===_f.length-1,c=A&&!I?Math.min(j,z):z;for await(let W of tf(X,()=>{k=!0},c,I))yield W;return}catch(X){if($f=X,k||!ff(X)&&!Nf(X)&&!g(X,u).retryable)throw X}}throw $f}async handleAbort(f){if(f?.aborted)await r(0,f,{throwOnAbort:!0})}logIdleTimeout(f,x,_){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;sx.warn("[PiAIChatService] Provider stream idle timeout",{provider:_.provider,model:_.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:x})}getConfig(){return{...this.config}}updateConfig(f){let x={...this.config,...f},_=Cf(x);this.config={...x,maxContextTokens:_.model.contextWindow,maxOutputTokens:x.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model}}var _0=t("Service");async function EM(f){let x=f;if(x.provider){let _=sf(x.provider);if(Object.keys(_).length>0)x={...x,customHeaders:{..._,...x.customHeaders}},_0.debug(`Injected ${x.provider} specific headers:`,Object.keys(_))}return M0(x)}function M0(f){return new Ff(f)}
5
+ export{P0 as Hd,h0 as Id,af as Jd,ff as Kd,F_ as Ld,w0 as Md,Ff as Nd,EM as Od};