blade-code 0.10.63 → 0.10.65

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 (106) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-kxrss9sv.js → chunk-015t2dey.js} +1 -1
  3. package/dist/chunk-0h74p1h8.js +1 -0
  4. package/dist/chunk-18nkg8hr.js +1 -0
  5. package/dist/chunk-197qz36b.js +1 -0
  6. package/dist/{chunk-khkhsaan.js → chunk-1jm8njkw.js} +1 -1
  7. package/dist/{chunk-y8r2knxm.js → chunk-1vt7e9e7.js} +2 -2
  8. package/dist/chunk-2vdq0fav.js +1 -0
  9. package/dist/{chunk-87jz5600.js → chunk-2yxdneb9.js} +1 -1
  10. package/dist/chunk-4a75gwa1.js +1 -0
  11. package/dist/{chunk-rwy763tf.js → chunk-4t89y8nj.js} +1 -1
  12. package/dist/{chunk-jk8bqc5b.js → chunk-53tb8vvv.js} +2 -2
  13. package/dist/{chunk-6x1g554w.js → chunk-57gp2px5.js} +1 -1
  14. package/dist/{chunk-3tednchw.js → chunk-5gjqdbxb.js} +2 -2
  15. package/dist/{chunk-69rc9hw6.js → chunk-5ha0vf37.js} +1 -1
  16. package/dist/{chunk-w4sp56dn.js → chunk-5ntrhs8k.js} +1 -1
  17. package/dist/{chunk-6rg6mngq.js → chunk-5qaacj3x.js} +1 -1
  18. package/dist/{chunk-cz68x56m.js → chunk-6tacv9rs.js} +2 -2
  19. package/dist/chunk-76ks3ygm.js +10 -0
  20. package/dist/{chunk-ej6h16ae.js → chunk-793067rd.js} +2 -2
  21. package/dist/{chunk-7b467h8k.js → chunk-7mdbwjxj.js} +1 -1
  22. package/dist/chunk-8wvk5rgg.js +1 -0
  23. package/dist/{chunk-xsx1av03.js → chunk-98qmtexa.js} +34 -34
  24. package/dist/{chunk-cr154zrx.js → chunk-98vestg4.js} +1 -1
  25. package/dist/{chunk-cq77ah56.js → chunk-9ebwtazz.js} +1 -1
  26. package/dist/{chunk-94d8hhqc.js → chunk-9yvw5xy3.js} +2 -2
  27. package/dist/{chunk-6g3qzz9h.js → chunk-a1m7wr7r.js} +1 -1
  28. package/dist/chunk-a49dy92d.js +140 -0
  29. package/dist/{chunk-cm9mph7j.js → chunk-aphcj8rz.js} +1 -1
  30. package/dist/{chunk-av10vmxk.js → chunk-arzhhj0e.js} +1 -1
  31. package/dist/chunk-b7p7ywe6.js +1 -0
  32. package/dist/{chunk-2xbmkyb2.js → chunk-bnp9asmd.js} +1 -1
  33. package/dist/{chunk-b19f55s7.js → chunk-ca5mm1gk.js} +1 -1
  34. package/dist/chunk-cxc2q3yy.js +1 -0
  35. package/dist/{chunk-wy4pn9sk.js → chunk-czb954vz.js} +1 -1
  36. package/dist/{chunk-kjvntyr5.js → chunk-d39xaa7w.js} +1 -1
  37. package/dist/{chunk-atqnan6x.js → chunk-e11kmyt3.js} +1 -1
  38. package/dist/{chunk-9r0yebs1.js → chunk-edd8n5r0.js} +1 -1
  39. package/dist/{chunk-2z3xe3rw.js → chunk-eg5mh9m9.js} +1 -1
  40. package/dist/{chunk-1jc7d3nt.js → chunk-eharmsjt.js} +2 -2
  41. package/dist/{chunk-9rjaem5f.js → chunk-ejsggxs4.js} +2 -2
  42. package/dist/chunk-fv3aggr5.js +1 -0
  43. package/dist/chunk-fz60jh3y.js +2 -0
  44. package/dist/{chunk-fp1h8wdh.js → chunk-gafk33py.js} +1 -1
  45. package/dist/{chunk-0jxh2zq5.js → chunk-h127mgg2.js} +2 -2
  46. package/dist/{chunk-detkh4dd.js → chunk-hbbpe5f0.js} +1 -1
  47. package/dist/{chunk-0ft3egjr.js → chunk-j6w1vf2q.js} +2 -2
  48. package/dist/{chunk-d1t91jgz.js → chunk-k4t45b64.js} +1 -1
  49. package/dist/{chunk-95hvy6dn.js → chunk-ka2kn5bs.js} +2 -2
  50. package/dist/chunk-ky32s7az.js +2 -0
  51. package/dist/chunk-m19xed90.js +1 -0
  52. package/dist/chunk-m6a1c1tg.js +8 -0
  53. package/dist/chunk-mr5c4yzr.js +1 -0
  54. package/dist/{chunk-8ekk8pa7.js → chunk-ngmajm4h.js} +1 -1
  55. package/dist/{chunk-8b1ehxzh.js → chunk-pfmmvpfh.js} +3 -3
  56. package/dist/chunk-pr8a6xfm.js +1 -0
  57. package/dist/chunk-pwehsv52.js +159 -0
  58. package/dist/{chunk-eeac8teg.js → chunk-r94jtbd2.js} +1 -1
  59. package/dist/{chunk-ng0tkmrn.js → chunk-rabt8yyf.js} +2 -2
  60. package/dist/{chunk-j8akkmc8.js → chunk-rd7jwwse.js} +1 -1
  61. package/dist/{chunk-1hb0rt7n.js → chunk-s16x4qkb.js} +1 -1
  62. package/dist/{chunk-83wm4akj.js → chunk-s1xp6g8m.js} +1 -1
  63. package/dist/{chunk-hpehkz2x.js → chunk-sbpb7pcc.js} +2 -2
  64. package/dist/{chunk-2xsrqsk9.js → chunk-svczh6hn.js} +2 -2
  65. package/dist/chunk-tb4jmrkp.js +2 -0
  66. package/dist/chunk-w4eskwzj.js +1 -0
  67. package/dist/{chunk-fp2fh7cn.js → chunk-wzkr0p09.js} +2 -2
  68. package/dist/{chunk-j9snkjpe.js → chunk-y51v2jvh.js} +2 -2
  69. package/dist/chunk-y8zk4r3y.js +1 -0
  70. package/dist/{chunk-k4ermznt.js → chunk-yrtmkb4a.js} +1 -1
  71. package/dist/{chunk-pdrqnywp.js → chunk-z228cmc5.js} +1 -1
  72. package/dist/{chunk-6fdvffcc.js → chunk-zpwasxzh.js} +2 -2
  73. package/dist/chunk-zxwdtn6q.js +112 -0
  74. package/dist/web/assets/{ChatView-B6IO9U-D.js → ChatView-Jfq-sqKG.js} +2 -2
  75. package/dist/web/assets/{CodeBlockHighlighter-DVGtFQgX.js → CodeBlockHighlighter-C9DvlG-V.js} +1 -1
  76. package/dist/web/assets/{FilePreview-C-8_o7yw.js → FilePreview-YPtQcXr3.js} +1 -1
  77. package/dist/web/assets/{MarkdownRenderer-D04IKQhF.js → MarkdownRenderer-CpUKw2Gk.js} +3 -3
  78. package/dist/web/assets/{SettingsModal-BMoZLVEe.js → SettingsModal-BfDHa4xn.js} +1 -1
  79. package/dist/web/assets/{TaskSwitcher-CIuCEbvU.js → TaskSwitcher-DacXxQcV.js} +1 -1
  80. package/dist/web/assets/{TerminalPanel-fTk9D5hU.js → TerminalPanel-CDq3_gCr.js} +1 -1
  81. package/dist/web/assets/index-t4mGaG1Z.js +11 -0
  82. package/dist/web/index.html +1 -1
  83. package/package.json +1 -1
  84. package/dist/chunk-0d1197b9.js +0 -1
  85. package/dist/chunk-2yws8pqt.js +0 -1
  86. package/dist/chunk-5sk6v1et.js +0 -10
  87. package/dist/chunk-86gc2mqb.js +0 -1
  88. package/dist/chunk-8an49nbn.js +0 -204
  89. package/dist/chunk-9c31jemm.js +0 -1
  90. package/dist/chunk-9kmtcgm6.js +0 -2
  91. package/dist/chunk-adz2756v.js +0 -111
  92. package/dist/chunk-cx05we7e.js +0 -1
  93. package/dist/chunk-dpzx4mgb.js +0 -1
  94. package/dist/chunk-dq9ya06q.js +0 -1
  95. package/dist/chunk-g0n88mhg.js +0 -1
  96. package/dist/chunk-m0t7g2vg.js +0 -1
  97. package/dist/chunk-nnbfk60b.js +0 -1
  98. package/dist/chunk-nnc1abkf.js +0 -1
  99. package/dist/chunk-q7pznpyh.js +0 -1
  100. package/dist/chunk-qs4erqd0.js +0 -2
  101. package/dist/chunk-tf4p1778.js +0 -1
  102. package/dist/chunk-ttkwrqtp.js +0 -2
  103. package/dist/chunk-vhckw5e7.js +0 -1
  104. package/dist/chunk-wwsg165p.js +0 -116
  105. package/dist/chunk-yagna3ws.js +0 -8
  106. package/dist/web/assets/index-CO5sUiJn.js +0 -11
@@ -1,5 +1,5 @@
1
- import{Bg as Cf,Cg as $f,Eg as K,og as e_,pg as vf,qg as Ff,rg as n_,sg as jf,ug as Bf,wg as Jf,xg as Af,yg as Sf,zg as Wf}from"./chunk-8ekk8pa7.js";import{Lg as a}from"./chunk-y8r2knxm.js";import{Pg as T_,Rg as sf}from"./chunk-1jc7d3nt.js";import{Ug as m_}from"./chunk-fp1h8wdh.js";var SE={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},ef=(f)=>SE[f]||{};var CE=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Nf(f){return typeof f==="string"&&CE.has(f)}function Ut(f){if(!f.aborted)return;if(Nf(f.reason))return f.reason;return"user-cancel"}function Ot(f){if(Nf(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 nf(...f){let _=f.filter(Boolean);if(_.length===0)return new AbortController().signal;if(_.length===1)return _[0];let E=AbortSignal;if(typeof E.any==="function")return E.any(_);for(let h of _)if(h.aborted)return h;let t=new AbortController,T=new Map;for(let h of _){let S=()=>{t.abort(h.reason);for(let[A,x]of T)A.removeEventListener("abort",x)};T.set(h,S)}for(let[h,S]of T)h.addEventListener("abort",S,{once:!0});return t.signal}function d(f,_,E){let t=E?.throwOnAbort??!1;if(_?.aborted){if(t)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((T,h)=>{let S,A=setTimeout(()=>{if(_&&S)_.removeEventListener("abort",S);T()},f);if(_)S=()=>{if(clearTimeout(A),t)h(new DOMException("Aborted","AbortError"));else T()},_.addEventListener("abort",S,{once:!0})})}var PE=a("Chat"),uE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Of(f){if(typeof f==="string")return f;return f.filter((_)=>_.type==="text").map((_)=>_.text).join(`
1
+ import{Ag as Ff,Bg as n_,Cg as jf,Eg as Bf,Gg as Jf,Hg as Af,Ig as Sf,Jg as Wf,Lg as Cf,Mg as $f,Og as K,yg as e_,zg as vf}from"./chunk-ngmajm4h.js";import{Vg as a}from"./chunk-1vt7e9e7.js";import{$g as sf,Zg as T_}from"./chunk-eharmsjt.js";import{ch as m_}from"./chunk-gafk33py.js";var SE={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},ef=(f)=>SE[f]||{};var CE=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Nf(f){return typeof f==="string"&&CE.has(f)}function Ut(f){if(!f.aborted)return;if(Nf(f.reason))return f.reason;return"user-cancel"}function Ot(f){if(Nf(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 nf(...f){let _=f.filter(Boolean);if(_.length===0)return new AbortController().signal;if(_.length===1)return _[0];let E=AbortSignal;if(typeof E.any==="function")return E.any(_);for(let h of _)if(h.aborted)return h;let t=new AbortController,T=new Map;for(let h of _){let S=()=>{t.abort(h.reason);for(let[A,x]of T)A.removeEventListener("abort",x)};T.set(h,S)}for(let[h,S]of T)h.addEventListener("abort",S,{once:!0});return t.signal}function d(f,_,E){let t=E?.throwOnAbort??!1;if(_?.aborted){if(t)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((T,h)=>{let S,A=setTimeout(()=>{if(_&&S)_.removeEventListener("abort",S);T()},f);if(_)S=()=>{if(clearTimeout(A),t)h(new DOMException("Aborted","AbortError"));else T()},_.addEventListener("abort",S,{once:!0})})}var PE=a("Chat"),uE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Of(f){if(typeof f==="string")return f;return f.filter((_)=>_.type==="text").map((_)=>_.text).join(`
2
2
  `)}function DE(f){if(!f)return{};try{let _=JSON.parse(f);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return PE.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function bE(f){let _=f.match(/^data:([^;,]+);base64,(.+)$/s);return _?{mimeType:_[1],data:_[2]}:void 0}async function HE(f,_){let E=bE(f);if(E)return{type:"image",...E};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let t=await fetch(f,{signal:_});if(!t.ok)throw Error(`Failed to load image ${f}: HTTP ${t.status}`);return{type:"image",mimeType:t.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await t.arrayBuffer()).toString("base64")}}async function __(f,_,E,t,T){let h=f.filter((x)=>x.role==="system").map((x)=>Of(x.content)).filter(Boolean).join(`
3
3
 
4
4
  `),S=[];for(let x of f){if(x.role==="system")continue;if(x.role==="user"){let C=_.input.includes("image"),c=typeof x.content==="string"?x.content:await Promise.all(x.content.map((R)=>R.type==="text"?Promise.resolve({type:"text",text:R.text}):C?HE(R.image_url.url,t):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));S.push({role:"user",content:c,timestamp:Date.now()});continue}if(x.role==="assistant"){let C=[];if(x.reasoningContent?.trim())C.push({type:"thinking",thinking:x.reasoningContent});let c=Of(x.content);if(c)C.push({type:"text",text:c});for(let R of x.tool_calls??[]){if(!("function"in R))continue;C.push({type:"toolCall",id:R.id,name:R.function.name,arguments:DE(R.function.arguments)})}S.push({role:"assistant",content:C,api:_.api,provider:_.provider,model:_.id,usage:uE,stopReason:x.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}S.push({role:"toolResult",toolCallId:x.tool_call_id??"",toolName:x.name??"unknown",content:[{type:"text",text:Of(x.content)}],isError:!1,timestamp:Date.now()})}let A=E?.filter((x)=>!T||x.name===T).map((x)=>({name:x.name,description:x.description,parameters:x.parameters,constrainedSampling:x.constrainedSampling})).sort((x,C)=>x.name<C.name?-1:x.name>C.name?1:0);return{...h?{systemPrompt:h}:{},messages:S,...A?.length?{tools:A}:{}}}function E_(f){let _=[];for(let E=0;E<f.length;E++){let t=f[E];if(t.role==="tool")continue;let T=t.role==="assistant"&&t.tool_calls?.length?t.tool_calls:void 0;if(!T){_.push(t);continue}let h=[],S=E+1;while(S<f.length&&f[S].role==="tool")h.push(f[S++]);let A=new Set(T.map((c)=>c.id)),x=h.filter((c)=>c.tool_call_id&&A.has(c.tool_call_id)),C=new Set(x.map((c)=>c.tool_call_id));if(A.size===T.length&&x.length===A.size&&C.size===A.size)_.push(t,...x);E=S-1}return _}function t_(f){return f.some((_)=>_.role==="assistant"&&Boolean(_.tool_calls?.length)&&!_.reasoningContent?.trim())}function h_(f,_){return{...f,..._.baseUrl?{baseUrl:T_(f.api,_.baseUrl)}:{},..._.maxOutputTokens?{maxTokens:_.maxOutputTokens}:{}}}function kf(f){let _=f.modelCatalog??sf();return{models:_.models,model:h_(_.getModel(f.provider,f.model),f)}}function x_(f,_){let E=f.modelCatalog??sf();return h_(E.getModel(_.provider,_.model),f)}import{createHash as UE}from"node:crypto";var YE=32,NE=1000,OE=512,sE=2000,kE=0.1,VE=0.05,jE=0.9,BE=300000,XE=3600000;class Vf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let _=f.now??Date.now(),E=zE(f,_),t=this.sessions.get(f.sessionId);if(E.callCount=(t?.callCount??0)+1,this.touch(f.sessionId,E),t&&E.contextEpoch!==t.contextEpoch)return;if(!t||t.cacheReadTokens<NE)return;let T=t.cacheReadTokens-E.cacheReadTokens,h=Math.min(sE,Math.max(OE,t.cacheReadTokens*kE));if(T<h||E.cacheReadTokens>=t.cacheReadTokens*(1-VE))return;let S=E.modelIdentity!==t.modelIdentity,A=E.systemHash!==t.systemHash,x=E.toolsHash!==t.toolsHash,C=E.policyHash!==t.policyHash;if(!(S||A||x||C)&&E.promptTokens<t.promptTokens*jE)return;let R=Math.max(0,_-t.recordedAt),u=t.retention==="long"?XE:BE,H=S?"model_changed":A?"system_prompt_changed":x?"tools_changed":C?"request_policy_changed":R>=u?"ttl_expired":"server_side",X=IE(t,E);return{reason:H,previousCacheReadTokens:t.cacheReadTokens,cacheReadTokens:E.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:T,elapsedMs:R,callNumber:E.callCount,systemPromptChanged:A,systemCharDelta:E.systemChars-t.systemChars,toolsChanged:x,addedToolCount:X.added,removedToolCount:X.removed,changedToolCount:X.changed,modelChanged:S,requestPolicyChanged:C}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,_){this.sessions.delete(f),this.sessions.set(f,_);while(this.sessions.size>YE){let E=this.sessions.keys().next().value;if(E===void 0)break;this.sessions.delete(E)}}}function zE(f,_){let E=[...f.tools??f.context.tools??[]].map((t)=>({identityHash:e(t.name),contractHash:e(n(t))})).sort((t,T)=>t.identityHash<T.identityHash?-1:t.identityHash>T.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:e(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:e(n(E)),toolFingerprints:E,policyHash:e(n(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:_,callCount:1}}function IE(f,_){let E=new Map(f.toolFingerprints.map((T)=>[T.identityHash,T.contractHash])),t=new Map(_.toolFingerprints.map((T)=>[T.identityHash,T.contractHash]));return{added:[...t.keys()].filter((T)=>!E.has(T)).length,removed:[...E.keys()].filter((T)=>!t.has(T)).length,changed:[...t].filter(([T,h])=>E.has(T)&&E.get(T)!==h).length}}function n(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(n).join(",")}]`;let _=f;return`{${Object.keys(_).sort().map((E)=>`${JSON.stringify(E)}:${n(_[E])}`).join(",")}}`}function e(f){return UE("sha256").update(f).digest("hex")}import{randomBytes as LE}from"node:crypto";import{createHmac as JE}from"node:crypto";function WE(f){try{let _=new URL(f);if(_.hash="",_.hostname=_.hostname.toLowerCase(),_.searchParams.sort(),_.pathname!=="/")_.pathname=_.pathname.replace(/\/+$/,"");return _.toString()}catch{return f.trim().replace(/\/+$/,"")}}function $E(f){if(!f)return[];return Object.entries(f).map(([_,E])=>[_.trim().toLowerCase(),E.trim()]).sort(([_],[E])=>_.localeCompare(E))}function cf(f,_,E){let t=JSON.stringify([f.provider.trim(),String(f.api).trim(),WE(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",$E(f.customHeaders),E]);return JE("sha256",Buffer.from(_)).update(t).digest("hex")}var GE=60000,ZE=4,KE=0.8;var Mf=300000,Xf=600000;var c_=128,R_=256,QE=1800000,Rf=50;class ff 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 zf(f){return f instanceof ff||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function m(f,_){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:_}function oE(f,_){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:_}function vE(f,_){return cf(f,_,{providerCircuitOpenDurationMs:f.openDurationMs})}function i(f){let _=0;for(let E of f)if(E.failure)_++;return _}function M_(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function A_(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Bf)}class C_{#h=new Map;#R=new WeakMap;#f;#_;#t;#E;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):LE(32),this.#_=f.now??(()=>performance.now()),this.#t=f.wallNow??f.now??Date.now,this.#E={maxEntries:Math.min(m(f.maxEntries,c_),c_),maxWindowEntries:Math.min(m(f.maxWindowEntries,R_),R_),windowMs:m(f.windowMs,GE),minSamples:m(f.minSamples,ZE),errorRateThreshold:oE(f.errorRateThreshold,KE),idleTtlMs:m(f.idleTtlMs,QE)}}get size(){return this.#h.size}get(f){if(f.openDurationMs===0)return this.#x();let _=this.#_();this.#U(_);let E=vE(f,this.#f),t=this.#h.get(E);if(t)return t.lastTouchedAt=_,this.#T(t,f.probeLeaseMs);if(this.#h.size>=this.#E.maxEntries)this.#O();if(this.#h.size>=this.#E.maxEntries)return this.#x();let T={key:E,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:_,detached:!1};return this.#h.set(E,T),this.#T(T,f.probeLeaseMs)}#T(f,_){let E=this,t=Math.max(Mf,Math.min(m(_,Mf),Xf));return{preflight:()=>E.#C(f),check:()=>E.#P(f,t),recordSuccess:(T)=>E.#b(T,"success"),recordFailure:(T,h)=>E.#b(T,"failure",h),recordNeutral:(T)=>E.#b(T,"neutral"),abandon:(T)=>E.#N(T),snapshot:()=>E.#Y(f)}}#x(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let _=Object.freeze({kind:"noop"});return f.#R.set(_,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:_}},recordSuccess:(_)=>f.#c(_),recordFailure:(_)=>f.#c(_),recordNeutral:(_)=>f.#c(_),abandon:(_)=>f.#N(_),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#c(f){let _=this.#R.get(f);if(_?.kind==="noop")_.settled=!0;return}#C(f){let _=this.#_();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=_,this.#H(f,_),f.state==="closed")return{eligible:!0};if(f.state==="open"){let t=f.nextProbeAt??_;return _<t?this.#M(f,t-_):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return{eligible:!0};let E=Math.max(1,(f.probeLeaseExpiresAt??_+Rf)-_);return this.#M(f,Math.min(Rf,E))}#M(f,_){let{allowed:E,...t}=this.#D(f,_);return{eligible:!1,...t}}#P(f,_){let E=this.#_();if(f.detached)return this.#x().check();if(f.lastTouchedAt=E,this.#H(f,E),f.state==="closed")return this.#A(f,"regular");if(f.state==="open"){let T=f.nextProbeAt??E;if(E<T)return this.#D(f,T-E);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return this.#u(f,E,_);let t=Math.max(1,(f.probeLeaseExpiresAt??E+Rf)-E);return this.#D(f,Math.min(Rf,t))}#A(f,_,E){let t=Object.freeze({kind:_});return this.#R.set(t,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:_,...E!==void 0?{probeLeaseId:E}:{},settled:!1}),{allowed:!0,probe:_==="probe",token:t}}#u(f,_,E){let t=f.nextProbeLeaseId++;f.probeLeaseId=t,f.probeLeaseExpiresAt=_+E,f.lastTouchedAt=_;let T=this.#A(f,"probe",t),h=f.lastFailure??{reason:"server_error"};return{...T,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:i(f.samples)}}#D(f,_){let E=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(_)),nextProbeAt:this.#t()+Math.max(0,Math.ceil(_)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:i(f.samples)}}#b(f,_,E){let t=this.#R.get(f);if(!t||t.settled)return;if(t.settled=!0,t.kind==="noop"||!t.entry)return;let T=t.entry;if(T.detached||t.generation!==T.generation||t.kind==="regular"&&T.state!=="closed"||t.kind==="probe"&&(T.state!=="half_open"||t.probeLeaseId!==T.probeLeaseId))return;let h=this.#_();if(T.lastTouchedAt=h,t.kind==="probe"){if(_==="failure"&&E)return this.#S(T,E,h,"reopened");return this.#k(T)}if(_==="neutral")return;if(this.#V(T,_==="failure",h),_!=="failure"||!E)return;let S=i(T.samples),A=T.samples.length===0?0:S/T.samples.length;if(T.samples.length>=this.#E.minSamples&&A>=this.#E.errorRateThreshold)return this.#S(T,E,h,"opened");return}#S(f,_,E,t){let T={reason:_.reason,...M_(_.statusCode)!==void 0?{statusCode:M_(_.statusCode)}:{},...A_(_.retryAfterMs)!==void 0?{retryAfterMs:A_(_.retryAfterMs)}:{}},h=T.retryAfterMs??0,S=Math.max(f.configuredOpenDurationMs,h);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=S,f.nextProbeAt=E+S,f.lastFailure=T,{phase:t,reason:T.reason,...T.statusCode!==void 0?{statusCode:T.statusCode}:{},retryAfterMs:S,nextProbeAt:this.#t()+S,openDurationMs:S,sampleCount:f.samples.length,failureCount:i(f.samples)}}#k(f){let _=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#N(f){let _=this.#R.get(f);if(!_||_.settled)return!1;if(_.settled=!0,_.kind==="noop")return!0;let E=_.entry;if(!E||E.detached||_.kind!=="probe"||_.generation!==E.generation||_.probeLeaseId!==E.probeLeaseId)return!1;return E.probeLeaseId=void 0,E.probeLeaseExpiresAt=void 0,E.lastTouchedAt=this.#_(),!0}#V(f,_,E){if(this.#H(f,E),f.samples.length>=this.#E.maxWindowEntries)f.samples.shift();f.samples.push({at:E,failure:_})}#H(f,_){let E=_-this.#E.windowMs,t=0;while(t<f.samples.length&&f.samples[t].at<E)t++;if(t>0)f.samples.splice(0,t)}#Y(f){if(!f.detached)this.#H(f,this.#_());return{state:f.state,sampleCount:f.samples.length,failureCount:i(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#U(f){for(let[_,E]of this.#h)if(E.state==="closed"&&f-E.lastTouchedAt>this.#E.idleTtlMs)this.#s(_,E)}#O(){let f;for(let _ of this.#h.values())if(_.state==="closed"&&(!f||_.lastTouchedAt<f.lastTouchedAt))f=_;if(f)this.#s(f.key,f)}#s(f,_){_.detached=!0,this.#h.delete(f)}}var S_;function P_(){return S_??=new C_,S_}import{randomBytes as FE}from"node:crypto";var u_=16,D_=128,b_=32,H_=3,U_=16,Y_=96,N_=24,O_=12,s_=16,k_=4,V_=4,j_=67108864,B_=33554432,X_=12,z_=2,I_=2,J_=1,G_=15000,W_=30000;class _f extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,_,E,t,T,h,S,A){super(f==="queue_full"?`Provider request admission ${_} ${t} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${_} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=_;this.requestClass=E;this.resource=t;this.inFlight=T;this.limit=h;this.queued=S;this.maxWaitMs=A;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function Ef(f){return f instanceof _f||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function j(f,_,E){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return _;return Math.min(f,E)}function pE(f){let _=j(f.globalMaxInFlight,u_,u_),E=j(f.globalMaxPending,D_,D_),t=j(f.domainMaxPending,b_,b_),T=Math.min(j(f.ownerMaxInFlight,H_,H_),_),h=Math.min(j(f.ownerMaxPending,U_,U_),E),S=Math.min(j(f.nonForegroundGlobalMaxPending,Math.min(Y_,Math.max(1,Math.floor(E*3/4))),Y_),E),A=Math.min(j(f.nonForegroundDomainMaxPending,Math.min(N_,Math.max(1,Math.floor(t*3/4))),N_),t),x=Math.min(j(f.nonForegroundOwnerMaxPending,Math.min(O_,Math.max(1,Math.floor(h*3/4))),O_),h),C=Math.min(j(f.internalGlobalMaxPending,Math.min(s_,Math.max(1,Math.floor(E/8))),s_),S),c=Math.min(j(f.internalDomainMaxPending,Math.min(k_,Math.max(1,Math.floor(t/8))),k_),A),R=Math.min(j(f.internalOwnerMaxPending,Math.min(V_,Math.max(1,Math.floor(h/4))),V_),x),u=j(f.globalMaxPendingBytes,K,K),H=Math.min(j(f.domainMaxPendingBytes,j_,j_),u),X=Math.min(j(f.ownerMaxPendingBytes,B_,B_),u),W=Math.min(j(f.nonForegroundGlobalMaxInFlight,Math.min(X_,_),X_),_),$=Math.min(j(f.nonForegroundOwnerMaxInFlight,Math.min(z_,T),z_),T),Z=Math.min(j(f.internalGlobalMaxInFlight,Math.min(I_,_),I_),_),uf=j(f.internalDomainMaxInFlight,J_,J_),tf=j(f.agingMs,W_,W_);return{globalMaxInFlight:_,globalMaxPending:E,domainMaxPending:t,ownerMaxInFlight:T,ownerMaxPending:h,nonForegroundGlobalMaxPending:S,nonForegroundDomainMaxPending:A,nonForegroundOwnerMaxPending:x,internalGlobalMaxPending:C,internalDomainMaxPending:c,internalOwnerMaxPending:R,globalMaxPendingBytes:u,domainMaxPendingBytes:H,ownerMaxPendingBytes:X,nonForegroundGlobalMaxInFlight:W,nonForegroundOwnerMaxInFlight:$,internalGlobalMaxInFlight:Z,internalDomainMaxInFlight:uf,agingMs:tf}}function $_(f,_){if(!f.trim())throw Error(`${_} must not be blank`)}function aE(f){if($_(f.sessionId,"sessionId"),$_(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<Af||f.scope.maxConcurrent>Sf)throw Error(`maxConcurrent must be between ${Af} and ${Sf}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>K)throw Error(`maxPendingBytes must be between 1 and ${K}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>K+1)throw Error(`pendingBytes must be between 1 and ${K+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Cf)throw Error(`maxWaitMs must be 0-${Cf}`)}function If(f,_){if(_!==void 0)return _;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function mE(f,_){return cf(f,_,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class Z_{#h;#R;#f;#_=[];#t=new Map;#E=new Map;#T=0;#x=0;#c=0;#C=0;#M=0;#P=0;#A=0;#u=0;#D=1;#b=0;#S=!1;constructor(f={}){this.#h=f.processSecret?new Uint8Array(f.processSecret):FE(32),this.#R=f.now??(()=>performance.now()),this.#f=pE(f)}admit(f){if(aE(f),this.#S)throw this.#X("closed",f,{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight},this.#_.length);if(f.signal?.aborted)throw If(f.signal);let _=mE(f.scope,this.#h),E=this.#t.get(_),t=this.#E.get(f.ownerId),T=E??this.#V(f.scope.maxConcurrent),h=t??this.#H();if(this.#_.length===0&&this.#Y(T,h,f.requestClass)){if(!E)this.#t.set(_,T);if(!t)this.#E.set(f.ownerId,h),this.#D++;let u=this.#O(_,f.ownerId,f.requestClass),H=this.#Q(f,0);return{ready:Promise.resolve(u),getSnapshot:()=>({...H}),cancel:()=>{H={...H}}}}let S=this.#k(f,T,h);if(S)throw this.#X("queue_full",f,S,this.#_.length);let A=this.#U(T,h,f.requestClass);if(f.maxWaitMs===0)throw this.#X("wait_timeout",f,A,this.#_.length);if(!E)this.#t.set(_,T);if(!t)this.#E.set(f.ownerId,h),this.#D++;let x,C,c=new Promise((u,H)=>{x=u,C=H});c.catch(()=>{return});let R={domainKey:_,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#R(),signal:f.signal,resolve:x,reject:C,settled:!1,admitted:!1};if(f.signal)R.abortListener=()=>this.#z(R,If(f.signal)),f.signal.addEventListener("abort",R.abortListener,{once:!0});return R.timer=setTimeout(()=>this.#L(R),f.maxWaitMs),R.timer.unref?.(),this.#_.push(R),this.#N(T,h,R),this.#j(),{ready:c,getSnapshot:()=>this.#K(R),cancel:(u)=>this.#z(R,If(f.signal,u))}}close(){if(this.#S)return;this.#S=!0;for(let f of[...this.#_]){let _=this.#t.get(f.domainKey),E=this.#E.get(f.ownerId),t=_&&E?this.#U(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};this.#B(f,new _f("closed",t.scope,f.requestClass,t.resource,t.inFlight,t.limit,this.#_.length,f.maxWaitMs))}}getStats(){return{inFlight:this.#T,queued:this.#_.length,pendingBytes:this.#P,nonForegroundInFlight:this.#x,internalInFlight:this.#c,nonForegroundQueued:this.#C,internalQueued:this.#M,nonForegroundPendingBytes:this.#A,internalPendingBytes:this.#u,domainCount:this.#t.size,ownerCount:this.#E.size,closed:this.#S}}#k(f,_,E){let t=(c,R,u)=>R>=u?{scope:c,resource:"pending_count",inFlight:R,limit:u}:void 0;if(f.requestClass==="internal"){let c=t("class",this.#M,this.#f.internalGlobalMaxPending)??t("class",E.internalQueued,this.#f.internalOwnerMaxPending)??t("class",_.internalQueued,this.#f.internalDomainMaxPending);if(c)return c}if(f.requestClass!=="foreground"){let c=t("class",this.#C,this.#f.nonForegroundGlobalMaxPending)??t("class",E.nonForegroundQueued,this.#f.nonForegroundOwnerMaxPending)??t("class",_.nonForegroundQueued,this.#f.nonForegroundDomainMaxPending);if(c)return c}let T=t("global",this.#_.length,this.#f.globalMaxPending)??t("owner",E.queued,this.#f.ownerMaxPending)??t("domain",_.queued,this.#f.domainMaxPending);if(T)return T;let h=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),S=Math.min(h,this.#f.domainMaxPendingBytes),A=Math.min(h,this.#f.ownerMaxPendingBytes),x=(c,R)=>f.pendingBytes>R-c,C=(c)=>{if(c==="owner")return{scope:c,resource:"pending_bytes",inFlight:E.inFlight,limit:this.#f.ownerMaxInFlight};if(c==="domain")return{scope:c,resource:"pending_bytes",inFlight:_.inFlight,limit:_.maxConcurrent};return{scope:c,resource:"pending_bytes",inFlight:this.#T,limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let c=Math.max(1,Math.floor(h/8)),R=Math.max(1,Math.floor(S/4)),u=Math.max(1,Math.floor(A/4));if(x(this.#u,c)||x(E.internalPendingBytes,u)||x(_.internalPendingBytes,R))return C("class")}if(f.requestClass!=="foreground"){let c=Math.max(1,Math.floor(h*3/4)),R=Math.max(1,Math.floor(S*3/4)),u=Math.max(1,Math.floor(A/2));if(x(this.#A,c)||x(E.nonForegroundPendingBytes,u)||x(_.nonForegroundPendingBytes,R))return C("class")}if(x(this.#P,h))return C("global");if(x(E.pendingBytes,A))return C("owner");if(x(_.pendingBytes,S))return C("domain");return}#N(f,_,E){if(f.queued++,_.queued++,this.#P+=E.pendingBytes,f.pendingBytes+=E.pendingBytes,_.pendingBytes+=E.pendingBytes,E.requestClass!=="foreground")this.#C++,f.nonForegroundQueued++,_.nonForegroundQueued++,this.#A+=E.pendingBytes,f.nonForegroundPendingBytes+=E.pendingBytes,_.nonForegroundPendingBytes+=E.pendingBytes;if(E.requestClass==="internal")this.#M++,f.internalQueued++,_.internalQueued++,this.#u+=E.pendingBytes,f.internalPendingBytes+=E.pendingBytes,_.internalPendingBytes+=E.pendingBytes}#V(f){return{maxConcurrent:f,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#H(){return{order:this.#D,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#Y(f,_,E){if(this.#T>=this.#f.globalMaxInFlight)return!1;if(f.inFlight>=f.maxConcurrent)return!1;if(_.inFlight>=this.#f.ownerMaxInFlight)return!1;if(E==="foreground")return!0;if(this.#x>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(_.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let t=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=t)return!1;if(E!=="internal")return!0;return this.#c<this.#f.internalGlobalMaxInFlight&&f.internalInFlight<this.#f.internalDomainMaxInFlight}#U(f,_,E){if(_.inFlight>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:_.inFlight,limit:this.#f.ownerMaxInFlight};if(E!=="foreground"&&_.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:_.nonForegroundInFlight,limit:this.#f.nonForegroundOwnerMaxInFlight};if(f.inFlight>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent};if(E!=="foreground"){let t=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=t)return{scope:"class",resource:"stream",inFlight:f.nonForegroundInFlight,limit:t}}if(E==="internal"&&f.internalInFlight>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.internalInFlight,limit:this.#f.internalDomainMaxInFlight};if(this.#T>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};if(E!=="foreground"&&this.#x>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#x,limit:this.#f.nonForegroundGlobalMaxInFlight};if(E==="internal"&&this.#c>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#c,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent}}#O(f,_,E){let t=this.#t.get(f),T=this.#E.get(_);if(!t||!T)throw Error("Provider admission accounting state is unavailable");if(this.#T++,t.inFlight++,T.inFlight++,E!=="foreground")this.#x++,t.nonForegroundInFlight++,T.nonForegroundInFlight++;if(E==="internal")this.#c++,t.internalInFlight++,T.internalInFlight++;let h=!1;return{release:()=>{if(h)return;h=!0,this.#s(f,_,E)}}}#s(f,_,E){let t=this.#t.get(f),T=this.#E.get(_);if(this.#T=Math.max(0,this.#T-1),t)t.inFlight=Math.max(0,t.inFlight-1);if(T)T.inFlight=Math.max(0,T.inFlight-1);if(E!=="foreground"){if(this.#x=Math.max(0,this.#x-1),t)t.nonForegroundInFlight=Math.max(0,t.nonForegroundInFlight-1);if(T)T.nonForegroundInFlight=Math.max(0,T.nonForegroundInFlight-1)}if(E==="internal"){if(this.#c=Math.max(0,this.#c-1),t)t.internalInFlight=Math.max(0,t.internalInFlight-1);if(T)T.internalInFlight=Math.max(0,T.internalInFlight-1)}this.#J(f,_),this.#j()}#j(){if(this.#S)return;while(this.#_.length>0){let f=this.#R(),_=new Map;for(let[A,x]of this.#_.entries()){let C=this.#t.get(x.domainKey),c=this.#E.get(x.ownerId);if(C===void 0||c===void 0||!this.#Y(C,c,x.requestClass))continue;let R=this.#W(x,f),u=_.get(x.ownerId);if(!u||R<u.rank||R===u.rank&&A<u.index)_.set(x.ownerId,{pending:x,rank:R,index:A})}let E=[..._.values()].filter(({pending:A})=>{let x=this.#t.get(A.domainKey),C=this.#E.get(A.ownerId);return x!==void 0&&C!==void 0&&this.#Y(x,C,A.requestClass)}).map(({pending:A,rank:x})=>({pending:A,rank:x,order:this.#E.get(A.ownerId).order}));if(E.length===0)return;let t=Math.min(...E.map((A)=>A.rank)),T=E.filter((A)=>A.rank===t),S=T.filter((A)=>A.order>this.#b).sort((A,x)=>A.order-x.order)[0]??T.sort((A,x)=>A.order-x.order)[0];this.#$(S.pending,S.order)}}#W(f,_){let E=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,t=Math.floor(Math.max(0,_-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,E-t)}#$(f,_){if(!this.#I(f,!1))return;f.settled=!0,f.admitted=!0,this.#b=_;let E=this.#O(f.domainKey,f.ownerId,f.requestClass);f.permit=E,f.resolve(E)}#L(f){let _=this.#t.get(f.domainKey),E=this.#E.get(f.ownerId),t=_&&E?this.#U(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};this.#B(f,new _f("wait_timeout",t.scope,f.requestClass,t.resource,t.inFlight,t.limit,this.#_.length,f.maxWaitMs))}#z(f,_){this.#B(f,_)}#B(f,_){if(!this.#I(f))return;f.settled=!0,f.reject(_),this.#j()}#I(f,_=!0){if(f.settled||f.admitted)return!1;let E=this.#_.indexOf(f);if(E<0)return!1;this.#_.splice(E,1);let t=this.#t.get(f.domainKey),T=this.#E.get(f.ownerId);if(t&&T)this.#G(t,T,f);if(this.#Z(f),_)this.#J(f.domainKey,f.ownerId);return!0}#G(f,_,E){if(f.queued=Math.max(0,f.queued-1),_.queued=Math.max(0,_.queued-1),this.#P=Math.max(0,this.#P-E.pendingBytes),f.pendingBytes=Math.max(0,f.pendingBytes-E.pendingBytes),_.pendingBytes=Math.max(0,_.pendingBytes-E.pendingBytes),E.requestClass!=="foreground")this.#C=Math.max(0,this.#C-1),f.nonForegroundQueued=Math.max(0,f.nonForegroundQueued-1),_.nonForegroundQueued=Math.max(0,_.nonForegroundQueued-1),this.#A=Math.max(0,this.#A-E.pendingBytes),f.nonForegroundPendingBytes=Math.max(0,f.nonForegroundPendingBytes-E.pendingBytes),_.nonForegroundPendingBytes=Math.max(0,_.nonForegroundPendingBytes-E.pendingBytes);if(E.requestClass==="internal")this.#M=Math.max(0,this.#M-1),f.internalQueued=Math.max(0,f.internalQueued-1),_.internalQueued=Math.max(0,_.internalQueued-1),this.#u=Math.max(0,this.#u-E.pendingBytes),f.internalPendingBytes=Math.max(0,f.internalPendingBytes-E.pendingBytes),_.internalPendingBytes=Math.max(0,_.internalPendingBytes-E.pendingBytes)}#Z(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#J(f,_){let E=this.#t.get(f);if(E&&E.inFlight===0&&E.queued===0)this.#t.delete(f);let t=this.#E.get(_);if(t&&t.inFlight===0&&t.queued===0)this.#E.delete(_)}#K(f){let _=Math.max(0,Math.floor(this.#R()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#T,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs};let E=this.#t.get(f.domainKey),t=this.#E.get(f.ownerId),T=E&&t?this.#U(E,t,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.#o(f,T.scope),queueDepth:this.#_.length,inFlight:T.inFlight,limit:T.limit,waitMs:_,maxWaitMs:f.maxWaitMs}}#Q(f,_){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#_.length,inFlight:this.#T,limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs}}#o(f,_){let E=this.#_.filter((t)=>{switch(_){case"owner":return t.ownerId===f.ownerId;case"domain":return t.domainKey===f.domainKey;case"class":return t.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,E.indexOf(f)+1)}#X(f,_,E,t){return new _f(f,E.scope,_.requestClass,E.resource,E.inFlight,E.limit,t,_.maxWaitMs)}}var L_;function K_(){return L_??=new Z_,L_}function Q_(f,_={}){let E=_.maxBytes??134217728,t=_.maxNodes??1e5;if(!Number.isSafeInteger(E)||E<=0||E>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(t)||t<=0)throw Error("maxNodes must be a positive safe integer");let T=new WeakSet,h=0,S=0,A=!1,x=(c)=>{if(A||c<=0)return;if(!Number.isSafeInteger(c)||c>E-h){h=E+1,A=!0;return}h+=c},C=(c)=>{if(A)return;if(S+=1,S>t){x(E+1);return}if(c===null){x(4);return}switch(typeof c){case"string":x(Buffer.byteLength(c,"utf8"));return;case"number":case"bigint":x(8);return;case"boolean":x(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(T.has(c))return;if(T.add(c),ArrayBuffer.isView(c)){x(32+c.byteLength);return}if(c instanceof ArrayBuffer){x(32+c.byteLength);return}if(c instanceof Date){x(40);return}if(c instanceof RegExp){x(32+Buffer.byteLength(c.source,"utf8"));return}if(c instanceof Map){x(32);for(let[R,u]of c)if(C(R),C(u),A)return;return}if(c instanceof Set){x(32);for(let R of c)if(C(R),A)return;return}if(c instanceof WeakMap||c instanceof WeakSet){x(32);return}if(Array.isArray(c)){x(16);for(let R of c)if(C(R),A)return;return}x(32);for(let R of Reflect.ownKeys(c)){if(typeof R!=="string")continue;let u=Object.getOwnPropertyDescriptor(c,R);if(!u?.enumerable||!("value"in u))continue;if(x(8+Buffer.byteLength(R,"utf8")),C(u.value),A)return}};return C(f),h}function o_(f){return Q_([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:K})}var v_=new WeakSet;class w extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,_){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=_;this.name="ProviderRecoveryBudgetExceededError"}}class Lf 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 wE=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],qE=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],lE=["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 F_(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function yE(f){let _=F_(f);return qE.some((E)=>_.includes(E))}function Gf(f){if(f!==null&&typeof f==="object")v_.add(f)}function _T(f){return f!==null&&typeof f==="object"&&v_.has(f)}function gE(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function rE(f){if(f===null||typeof f!=="object")return;let _=f;for(let E of["status","statusCode"]){let t=_[E];if(typeof t==="number"&&Number.isInteger(t))return t}return}function dE(f){let _=f.match(/^(?:error:\s*)?(\d{3})\b/),E=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),t=Number(_?.[1]??E?.[1]);return Number.isInteger(t)?t:void 0}function q(f,_){let E=F_(f),t=gE(f);if(t==="STREAM_IDLE_TIMEOUT"||t==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||E.includes("request aborted")||E==="aborted")return{retryable:!1};if(wE.some((h)=>E.includes(h))||yE(f))return{retryable:!1};if(_?.shouldRetry==="false")return{retryable:!1,statusCode:_.statusCode};if(t==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let T=_?.statusCode??rE(f)??dE(E);if(_?.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(t==="PROVIDER_STREAM_CLOSED"||E.includes("stream closed before completion")||E.includes("ended without")||E.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:T};if(lE.some((h)=>E.includes(h)))return{retryable:!0,reason:"transport",statusCode:T};if(E.includes("timeout")||E.includes("timed out")||E.includes("temporarily unavailable")||E.includes("upstream_error")||E.includes("overloaded")||E.includes("rate limit")||E.includes("too many requests")||E.includes("service unavailable")||E.includes("server error")||E.includes("internal error")||E.includes("please retry")||E.includes("try your request again"))return{retryable:!0,reason:E.includes("rate")||E.includes("too many")?"rate_limit":E.includes("timeout")||E.includes("timed out")?"timeout":"server_error",statusCode:T};return{retryable:!1,statusCode:T}}function Zf(f,_){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 E=Number.parseFloat(f.retryAfter);if(Number.isFinite(E))return Math.max(0,E*1000);let t=Date.parse(f.retryAfter);return Number.isFinite(t)?Math.max(0,t-_):void 0}function p_(f,_,E={}){let t=E.now??Date.now(),T=E.maxDelayMs??60000,h=Zf(_,t);if(h!==void 0)return Math.min(Math.ceil(h),T);let S=Math.max(0,f-1),A=E.maxExponentialDelayMs??8000,x=Math.min(500*2**S,A),C=Math.max(0,Math.min(1,E.random??Math.random())),c=x*(0.75+C*0.25);return Math.min(Math.round(c),T)}function w_(f,_){let E=f.onPayload;f.onPayload=async(t,T)=>{let h=E?await E(t,T):t;return _(h===void 0?t:h,T)}}function eE(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function Kf(f,_,E){if(!f.enablePromptCaching)return"none";if(E&&_.api==="openai-completions"&&!_.baseUrl.includes("api.openai.com"))return"long";return"short"}function nE(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function iE(f,_,E,t){let T=t?void 0:eE(E);if(!T){if(_.api==="anthropic-messages")f.thinkingEnabled=!1;if(_.api==="google-generative-ai"||_.api==="google-vertex")f.thinking={enabled:!1};return}switch(_.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=T;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:nE(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 ft(f,_,E){if(!E)return;switch(_){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:E};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:E}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:E};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function _t(f,_,E){let t=E.serviceTier;if(!t)return;if(_.api==="openai-responses"||_.api==="openai-codex-responses"||_.api==="azure-openai-responses"){f.serviceTier=t;return}if(_.api!=="openai-completions"&&!(_.api==="anthropic-messages"&&t==="fast"))return;w_(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;return _.api==="anthropic-messages"?{...T,speed:"fast"}:{...T,service_tier:t}})}function Et(f,_,E){let t=E.responseVerbosity;if(!t)return;if(m_(_,t),_.api==="openai-codex-responses"){f.textVerbosity=t;return}w_(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;if(_.api==="openai-completions")return{...T,verbosity:t};let h="text"in T&&T.text&&typeof T.text==="object"&&!Array.isArray(T.text)?T.text:{};return{...T,text:{...h,verbosity:t}}})}function q_(f,_,E,t,T=!1){let h={apiKey:f.apiKey,headers:f.customHeaders,signal:E,temperature:t?.temperature??f.temperature??0,maxTokens:t?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:Kf(f,_,t?.providerSessionId),sessionId:t?.providerSessionId};if(iE(h,_,f,T),ft(h,_.api,t?.toolChoice?.toolName),_t(h,_,f),Et(h,_,f),_.api==="azure-openai-responses")h.azureBaseUrl=f.baseUrl,h.azureApiVersion=f.apiVersion,h.azureDeploymentName=_.id;return h}function a_(f,_){let E=_.get("x-should-retry");return{statusCode:f,..._.get("retry-after")!==null?{retryAfter:_.get("retry-after")??void 0}:{},..._.get("retry-after-ms")!==null?{retryAfterMs:_.get("retry-after-ms")??void 0}:{},...E==="true"||E==="false"?{shouldRetry:E}:{}}}var tt=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function l_(f,_,E){let t=f.onResponse;if(f.onResponse=async(h,S)=>{let A=new Headers(h.headers);E(a_(h.status,A)),await t?.(h,S)},!tt.has(_.api)||typeof globalThis.fetch!=="function")return;let T=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(h,S)=>{let A=await T(h,S);return E(a_(A.status,A.headers)),A}}function y_(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 Pf=300000,Tt=30000;class g_ 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 r_ extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function Qf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function ht(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Pf}function xt(f,_){if(_===0)return;let E=_!==void 0&&_>0?_:Tt;return Math.max(1,Math.min(E,Math.floor(f/2)))}function ct(f,_,E){if(E?.aborted)return Promise.reject(Qf(E));return new Promise((t,T)=>{let h=!1,S=()=>{clearTimeout(c),E?.removeEventListener("abort",C)},A=(R)=>{if(h)return;h=!0,S(),t(R)},x=(R)=>{if(h)return;h=!0,S(),T(R instanceof Error?R:Error(String(R)))},C=()=>{if(E)x(Qf(E))},c=setTimeout(()=>A({kind:"timer"}),Math.max(0,_));if(E?.addEventListener("abort",C,{once:!0}),E?.aborted){C();return}f.then((R)=>A({kind:"next",result:R}),x)})}async function*Rt(f,_,E){let t=ht(_),T=xt(t,_.stallWarningMs);if(_.signal?.aborted)throw Qf(_.signal);let h=Date.now(),S=Promise.resolve().then(()=>f.next()),A;for(;;){let C=await ct(S,(A?t:T??t)-(Date.now()-h),_.signal);if(C.kind==="next"){if(A)yield{...A,phase:"recovered",durationMs:Math.max(A.durationMs,Date.now()-h)};return C.result}if(!A&&T!==void 0){E.stallCount++,A={phase:"detected",stallCount:E.stallCount,durationMs:T,warningAfterMs:T,timeoutMs:t,outputStarted:E.outputStarted},yield A;continue}let c=new g_(t);throw _.abort?.(c),c}}async function*d_(f,_,E,t,T={}){let S=f.stream(_,E,t)[Symbol.asyncIterator](),A=0,x=!1,C={stallCount:0,outputStarted:!1};try{while(!0){let c=Rt(S,T,C),R=await c.next();while(!R.done)yield{providerStall:R.value},R=await c.next();let u=R.value;if(u.done)throw new r_;let H=u.value;switch(H.type){case"text_delta":C.outputStarted=!0,yield{content:H.delta};break;case"thinking_delta":C.outputStarted=!0,yield{reasoningContent:H.delta};break;case"toolcall_end":C.outputStarted=!0,yield{toolCalls:[{index:A++,id:H.toolCall.id,type:"function",function:{name:H.toolCall.name,arguments:JSON.stringify(H.toolCall.arguments)}}]};break;case"done":x=!0,yield{finishReason:H.reason,usage:y_(H.message.usage)};return;case"error":throw Error(H.error.errorMessage??`Request ${H.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!x)Promise.resolve(S.return?.()).catch(()=>{return})}}var of=a("Chat"),Mt=1;function At(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((_)=>_.type==="image_url"))}function St(f){let E=f.findLast((t)=>{let T=t.metadata;return T!==null&&typeof T==="object"&&!Array.isArray(T)&&T.isCompactSummary===!0})?.metadata;return E!==null&&typeof E==="object"&&!Array.isArray(E)&&typeof E.parentId==="string"?E.parentId:""}function Ct(f,_){let E=q(f,_);if(!E.retryable||!E.reason)return;let t=E.statusCode;switch(E.reason){case"rate_limit":if(t!==429)return;break;case"server_error":if(t===void 0||t<500||t>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let T=Zf(_,Date.now());return{reason:E.reason,...t!==void 0?{statusCode:t}:{},...T!==void 0?{retryAfterMs:T}:{}}}function Pt(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class pf{config;models;model;promptCacheBreakMonitor=new Vf;admissionFallbackOwnerId=`pi-service-${process.pid}-${Mt++}`;constructor(f){let _=kf(f);this.config={...f,maxContextTokens:_.model.contextWindow,maxOutputTokens:f.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,of.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,_,E,t){let T="",h="",S=[],A,x;for await(let C of this.streamChat(f,_,E,t)){T+=C.content??"",h+=C.reasoningContent??"";for(let c of C.toolCalls??[])if(c.id&&c.type==="function"&&c.function?.name)S.push(c);A=C.usage??A,x=C.finishReason??x}return{content:T,...h?{reasoningContent:h}:{},...S.length>0?{toolCalls:S}:{},usage:A,finishReason:x}}async*streamChat(f,_,E,t){let T=t?.toolChoice?.toolName;if(T&&!_?.some((M)=>M.name===T))throw Error(`Required tool is unavailable: ${T}`);let h=E_(f);if(h.some((M)=>At(M))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let S=Boolean(T)||t_(h),A=await __(h,this.model,_,E,T),x=(M,P)=>{let k=t?.providerSessionId;if(!k||!M.usage)return M;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(k),M;let D=Kf(this.config,P,k),N=this.promptCacheBreakMonitor.observe({sessionId:k,modelIdentity:`${P.provider}\x00${P.api}\x00${P.id}`,context:A,retention:D,contextEpoch:St(h),policy:{baseUrl:P.baseUrl??this.config.baseUrl??"",retention:D,requiredTool:T??"",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:M.usage});if(!N)return M;return of.warn("[PiAIChatService] Prompt cache break detected",{reason:N.reason,previousCacheReadTokens:N.previousCacheReadTokens,cacheReadTokens:N.cacheReadTokens,tokenDrop:N.tokenDrop,callNumber:N.callNumber}),{...M,usage:{...M.usage,promptCacheBreak:N}}},C=o_({messages:h,context:A,tools:_,requestOptions:t}),c=t?.providerRecovery;if(c&&!n_(c.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let R=c?.mode==="bounded_foreground"&&c.budgetMs>0?{budgetMs:c.budgetMs,startedAt:void 0}:void 0,u=R?"bounded_foreground":"standard",H=this.config.maxRetries??2,X=this.config.maxRetries??(R?e_:2),W=R!==void 0&&this.config.maxRetries===void 0,$=0,Z,uf=this.config.providerCircuitRegistry??P_(),tf=this.config.providerCircuitBreakerOpenMs??jf,i_=Math.max(Mf,Math.min(this.config.streamIdleTimeout??Pf,Xf)),fE=this.config.providerRequestAdmissionScheduler??K_(),_E=this.config.providerRequestConcurrency??Jf,af=this.config.providerRequestAdmissionMs??Wf,EE=this.config.providerRequestPendingBytes??$f,Df=t?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},tE=(M)=>uf.get({provider:M.provider,api:M.api,baseUrl:M.baseUrl??this.config.baseUrl??"",model:M.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,openDurationMs:tf,probeLeaseMs:i_}),TE=(M)=>({provider:M.provider,api:M.api,baseUrl:M.baseUrl??this.config.baseUrl??"",model:M.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,maxConcurrent:_E,maxPendingBytes:EE}),s=(M=Date.now())=>{if(!R)return;let P=R.startedAt===void 0?0:Math.min(R.budgetMs,Math.max(0,M-R.startedAt));return{recoveryBudgetMs:R.budgetMs,recoveryElapsedMs:P,recoveryRemainingMs:Math.max(0,R.budgetMs-P)}},Q=()=>({mode:u,...s()??{}}),mf=()=>{if(R&&R.startedAt===void 0)R.startedAt=Date.now()},o=()=>{let M=s();return new w(R?.budgetMs??0,M?.recoveryElapsedMs??0)},l=()=>!W||$<X+1,bf=(M,P)=>{let{state:k,...D}=P;return{phase:M,...D,...s()?{recoveryRemainingMs:s()?.recoveryRemainingMs}:{}}},wf=(M)=>({phase:"rejected",requestClass:M.requestClass,resource:M.resource,scope:M.scope,reason:M.reason,queuePosition:0,queueDepth:Math.max(0,M.queued),inFlight:Math.max(0,M.inFlight),limit:Math.max(0,M.limit),waitMs:M.reason==="wait_timeout"?M.maxWaitMs:0,maxWaitMs:M.maxWaitMs,...s()?{recoveryRemainingMs:s()?.recoveryRemainingMs}:{}}),hE=async function*(M){let P=s()?.recoveryRemainingMs,k=P!==void 0&&R?.startedAt!==void 0?Math.min(af,P):af,D;try{D=fE.admit({scope:TE(M),sessionId:Df.sessionId,ownerId:Df.ownerId,requestClass:Df.requestClass,maxWaitMs:k,pendingBytes:C,signal:E})}catch(U){if(Ef(U)){if(U.reason==="wait_timeout"&&R?.startedAt!==void 0&&(s()?.recoveryRemainingMs??0)<=0)throw o();yield{providerAdmission:wf(U)}}throw U}let N=D.getSnapshot();if(N.state==="admitted")return await D.ready;yield{providerAdmission:bf("queued",N)};let G=D.ready.then((U)=>({kind:"ready",permit:U}),(U)=>({kind:"error",error:U}));while(!0){let U=D.getSnapshot(),Y=Math.max(1,Math.min(G_,Math.max(1,k-U.waitMs))),B,V=new Promise((v)=>{B=setTimeout(()=>v({kind:"heartbeat"}),Y),B.unref?.()}),I=await Promise.race([G,V]);if(B)clearTimeout(B);if(I.kind==="heartbeat"){yield{providerAdmission:bf("queued",D.getSnapshot())};continue}if(I.kind==="error"){if(Ef(I.error)){if(I.error.reason==="wait_timeout"&&R?.startedAt!==void 0&&(s()?.recoveryRemainingMs??0)<=0)throw o();yield{providerAdmission:wf(I.error)}}throw I.error}return yield{providerAdmission:bf("admitted",D.getSnapshot())},I.permit}},xE=(M)=>{if(!l())throw o();if(W)$++;Z=void 0;let P=new AbortController,k=E?nf(E,P.signal):P.signal,D=typeof this.config.timeout==="number"&&Number.isFinite(this.config.timeout)&&this.config.timeout>0?Math.max(1,Math.floor(this.config.timeout)):void 0,N;if(R?.startedAt!==void 0){let Y=s()?.recoveryRemainingMs??0;if(Y<=0)throw o();N={remainingMs:Y,error:new w(R.budgetMs,R.budgetMs)}}let G=q_(this.config,M,k,t,S);l_(G,M,(Y)=>{Z=Y});let U=d_(this.models,M,A,G,{idleTimeoutMs:this.config.streamIdleTimeout??Pf,signal:k,abort:(Y)=>P.abort(Y)});return async function*(){let Y,B;try{if(D!==void 0&&(N===void 0||D<N.remainingMs)){let V=new Lf(D);Y=setTimeout(()=>P.abort(V),D),Y.unref?.()}if(N){let V=N;B=setTimeout(()=>P.abort(V.error),V.remainingMs),B.unref?.()}yield*U}finally{if(Y)clearTimeout(Y);if(B)clearTimeout(B)}}()},qf=this,p=(M)=>({phase:M.phase,reason:M.reason,...M.statusCode!==void 0?{statusCode:M.statusCode}:{},...M.retryAfterMs!==void 0?{retryAfterMs:M.retryAfterMs}:{},...M.nextProbeAt!==void 0?{nextProbeAt:M.nextProbeAt}:{},openDurationMs:M.openDurationMs,sampleCount:M.sampleCount,failureCount:M.failureCount,...s()?{recoveryRemainingMs:s()?.recoveryRemainingMs}:{}}),lf=(M,P)=>({phase:M,reason:P.reason,...P.statusCode!==void 0?{statusCode:P.statusCode}:{},retryAfterMs:P.retryAfterMs,...P.nextProbeAt!==void 0?{nextProbeAt:P.nextProbeAt}:{},openDurationMs:P.openDurationMs,sampleCount:P.sampleCount,failureCount:P.failureCount,...s()?{recoveryRemainingMs:s()?.recoveryRemainingMs}:{}}),cE=(M)=>({phase:"probe",reason:M.reason??"server_error",...M.statusCode!==void 0?{statusCode:M.statusCode}:{},openDurationMs:M.openDurationMs??tf,...M.sampleCount!==void 0?{sampleCount:M.sampleCount}:{},...M.failureCount!==void 0?{failureCount:M.failureCount}:{},...s()?{recoveryRemainingMs:s()?.recoveryRemainingMs}:{}}),Hf=(M,P,k)=>({providerRetry:{phase:"exhausted",attempt:M,maxRetries:X,reason:P,...k!==void 0?{statusCode:k}:{},...Q(),exhaustedBy:"recovery_budget"}}),yf=async function*(M,P,k,D){let N,G=!1,U,Y,B=tE(M);for(let V=0;V<=k;V++){if(!l())break;let I,v;while(!I){let b=B.preflight();while(!b.eligible){if(U=b.reason,Y=b.statusCode,!R||!D){let L=lf("rejected",b);throw yield{providerCircuit:L},new ff(L)}mf();let O=s()?.recoveryRemainingMs??0;if(O<=0){let L=o();throw yield Hf(W?Math.max(0,$-1):V,b.reason,b.statusCode),L}yield{providerCircuit:lf("waiting",b)};let F=Math.min(Math.max(1,b.retryAfterMs),vf,O);if(await d(F,E,{throwOnAbort:!0}),(s()?.recoveryRemainingMs??0)<=0){let L=o();throw yield Hf(W?Math.max(0,$-1):V,b.reason,b.statusCode),L}b=B.preflight()}try{v=yield*hE(M)}catch(J){if(J instanceof w)yield Hf(W?Math.max(0,$-1):V,U??"timeout",Y);throw J}let z=B.check();if(z.allowed)I=z;else v.release(),v=void 0}let y=I.token;if(I.probe)yield{providerCircuit:cE(I)};try{let b=!1,z=!1;for await(let J of xE(M)){if(J.providerStall){yield J;continue}let O=W?$-1:V;if(O>0&&U&&!b)b=!0,yield{providerRetry:{phase:"recovered",attempt:O,maxRetries:X,reason:U,...Y!==void 0?{statusCode:Y}:{},...Q()}};if(!z){z=!0;let F=B.recordSuccess(y);if(F)yield{providerCircuit:p(F)}}G=!0,P(),yield x(J,M)}if(!z){let J=B.recordSuccess(y);if(J)yield{providerCircuit:p(J)}}return}catch(b){if(v?.release(),N=b,qf.logIdleTimeout(b,G,M),await qf.handleAbort(E),b instanceof w){if(G)throw Gf(b),b;throw yield{providerRetry:{phase:"exhausted",attempt:W?Math.max(0,$-1):V,maxRetries:X,reason:U??"timeout",...Y!==void 0?{statusCode:Y}:{},...Q(),exhaustedBy:"recovery_budget"}},b}let z=q(b,Z);if(G)throw Gf(b),b;let J=Ct(b,Z),O=J?B.recordFailure(y,J):Z&&!Pt(b)?B.recordNeutral(y):void 0;if(O)yield{providerCircuit:p(O)};if(!z.retryable||!z.reason){if(V>0&&U)yield{providerRetry:{phase:"exhausted",attempt:W?Math.max(0,$-1):V,maxRetries:X,reason:U,...Y!==void 0?{statusCode:Y}:{},...Q()}};throw b}U=z.reason,Y=z.statusCode;let F=V<k&&l();if(O&&O.phase!=="closed"&&F&&(!R||!D)){let L={...p(O),phase:"rejected"};throw yield{providerCircuit:L},new ff(L)}if(F){mf();let L=W?$:V+1,ME=p_(L,Z,R?{maxDelayMs:Ff,maxExponentialDelayMs:Ff}:void 0),rf=O&&O.phase!=="closed"?O.retryAfterMs??0:0;if(R&&rf>0&&O)yield{providerCircuit:{...p(O),phase:"waiting"}};let AE=s(),Yf=Math.max(ME,rf),g=R?Math.min(Yf,AE?.recoveryRemainingMs??Yf):Yf,hf={attempt:L,maxRetries:X,reason:z.reason,...z.statusCode!==void 0?{statusCode:z.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...hf,delayMs:g,nextRetryAt:Date.now()+g,...Q()}},R){let r=g;while(r>0){let df=Math.min(r,vf);if(await d(df,E,{throwOnAbort:!0}),r-=df,(s()?.recoveryRemainingMs??0)<=0){let xf=o();throw yield{providerRetry:{phase:"exhausted",...hf,...Q(),exhaustedBy:"recovery_budget"}},xf}if(r>0){if(O&&O.phase!=="closed"&&O.nextProbeAt!==void 0){let xf=Math.max(0,O.nextProbeAt-Date.now());if(xf>0)yield{providerCircuit:{...p(O),phase:"waiting",retryAfterMs:xf}}}yield{providerRetry:{phase:"waiting",...hf,delayMs:g,nextRetryAt:Date.now()+r,...Q()}}}}}else await d(g,E,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...hf,...Q()}}}else yield{providerRetry:{phase:"exhausted",attempt:W?Math.max(0,$-1):V,maxRetries:X,reason:z.reason,...z.statusCode!==void 0?{statusCode:z.statusCode}:{},...Q(),...R&&(D||!l())?{exhaustedBy:"attempt_limit"}:{}}}}finally{B.abandon(y),v?.release()}}throw N},Uf,gf=!1,Tf=this.config.fallbackModels??[],RE=R&&Tf.length>0?Math.min(H,X):X;try{for await(let M of yf(this.model,()=>{gf=!0},RE,Tf.length===0))yield M;return}catch(M){if(Uf=M,gf||!Ef(M)&&!zf(M)&&!q(M,Z).retryable)throw M}for(let[M,P]of Tf.entries()){if(!l())break;yield{modelFallback:!0};let k=!1;try{let D=x_(this.config,P),N=M===Tf.length-1,G=R&&!N?Math.min(H,X):X;for await(let U of yf(D,()=>{k=!0},G,N))yield U;return}catch(D){if(Uf=D,k||!Ef(D)&&!zf(D)&&!q(D,Z).retryable)throw D}}throw Uf}async handleAbort(f){if(f?.aborted)await d(0,f,{throwOnAbort:!0})}logIdleTimeout(f,_,E){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;of.warn("[PiAIChatService] Provider stream idle timeout",{provider:E.provider,model:E.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:_})}getConfig(){return{...this.config}}updateConfig(f){let _={...this.config,...f},E=kf(_);this.config={..._,maxContextTokens:E.model.contextWindow,maxOutputTokens:_.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model}}var ut=a("Service");async function jT(f){let _=f;if(_.provider){let E=ef(_.provider);if(Object.keys(E).length>0)_={..._,customHeaders:{...E,..._.customHeaders}},ut.debug(`Injected ${_.provider} specific headers:`,Object.keys(E))}return Dt(_)}function Dt(f){return new pf(f)}
5
- export{Ut as Md,Ot as Nd,nf as Od,Ef as Pd,Q_ as Qd,yE as Rd,_T as Sd,pf as Td,jT as Ud};
5
+ export{Ut as Wd,Ot as Xd,nf as Yd,Ef as Zd,Q_ as _d,yE as $d,_T as ae,pf as be,jT as ce};
@@ -15,4 +15,4 @@ More specific user instructions about presentation take precedence for that resp
15
15
  <communication_style>
16
16
  ${h.prompt}
17
17
  </communication_style>`}
18
- export{R as He,z as Ie,H as Je,W as Ke,Z as Le};
18
+ export{R as Re,z as Se,H as Te,W as Ue,Z as Ve};
@@ -1,4 +1,4 @@
1
- import{Ce as j1,De as L0,Ee as F1}from"./chunk-d1t91jgz.js";import{Ie as WO,Je as IO}from"./chunk-detkh4dd.js";import{Me as B1}from"./chunk-2xbmkyb2.js";import{Ne as b0,Pe as J0}from"./chunk-8b1ehxzh.js";import{Rf as z0,Sf as $O,Wf as I0}from"./chunk-2xsrqsk9.js";import{_f as u,ag as L,dg as P1}from"./chunk-7b467h8k.js";import{kg as M}from"./chunk-kjvntyr5.js";import{Lg as k,Mg as z}from"./chunk-y8r2knxm.js";import{Zg as g0}from"./chunk-6fdvffcc.js";import{dh as N}from"./chunk-ej6h16ae.js";import Y1 from"node:path";import QO from"node:path";import R0 from"node:fs";import X0 from"node:os";import R from"node:path";import EO from"yaml";var Q4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function Z4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var NO=`# Goal Completion Verifier
1
+ import{Me as j1,Ne as L0,Oe as F1}from"./chunk-k4t45b64.js";import{Se as WO,Te as IO}from"./chunk-hbbpe5f0.js";import{We as B1}from"./chunk-bnp9asmd.js";import{Xe as b0,Ze as J0}from"./chunk-pfmmvpfh.js";import{$f as z0,ag as $O,eg as I0}from"./chunk-svczh6hn.js";import{ig as u,kg as L,ng as P1}from"./chunk-7mdbwjxj.js";import{ug as M}from"./chunk-d39xaa7w.js";import{Vg as k,Wg as z}from"./chunk-1vt7e9e7.js";import{hh as g0}from"./chunk-zpwasxzh.js";import{nh as N}from"./chunk-793067rd.js";import Y1 from"node:path";import QO from"node:path";import R0 from"node:fs";import X0 from"node:os";import R from"node:path";import EO from"yaml";var Q4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function Z4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var NO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -707,4 +707,4 @@ ${Z.join(`
707
707
  </${Q}>`:"";return{content:q,files:[...O],references:O.map(n$),triggerPaths:[...$],contentBytes:Buffer.byteLength(q,"utf8"),provenanceSha256:w0(O.map((K)=>`${K.id}:${K.contentSha256}`).join(`
708
708
  `))}}function BO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let q=O[J];if(!q)continue;let K=Buffer.byteLength(q.content,"utf8");if(K>Q)continue;Z.push(q),Q-=K}return Z.reverse()}class d{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=K1(O),this.definitions=Object.freeze([...$].sort(G1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=w0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
709
709
  `))}static empty(O){return new d(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new d(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=k$){if(this.definitions.length===0)return K0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&q1(J.scopeDirectory,Q));return K0(BO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=P$){if(this.definitions.length===0)return K0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),q=[...new Set($.map((G)=>L1(S.relative(this.projectRoot,K1(G)))).filter(X1))].sort(),K=new Map;for(let G of q)for(let W of this.definitions){if(Q.has(W.id))continue;if(!q1(W.scopeDirectory,G))continue;if(W.conditional){let Y=S.posix.relative(W.scopeDirectory||".",G);if(!W.patterns?.some((V)=>zO(V,{dot:!0})(Y)))continue}else if(q1(W.scopeDirectory,J))continue;K.set(W.id,W)}let X=BO([...K.values()].sort(G1),Z);return K0(X,q,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return K0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(G1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=L1(S.relative(this.projectRoot,K1(O)));if($&&!X1($))throw Error("Project instruction source is outside the catalog root");return $}}async function i$(O,$){let Q=await m.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>FO)throw Error(`Project rule exceeds ${FO} bytes`);let Z=await m.realpath($),J=L1(S.relative(O,Z));if(!X1(J))throw Error("Project rule escapes its repository root");let q=await m.readFile(Z,"utf8");if(SO(q))throw Error("Project rule contains hidden control characters");let K=h$(q),X=K.content.trim();if(!X)throw Error("Project rule content must not be empty");let G=l$(K.data.paths),W=s$(J),Y=w0(JSON.stringify({relativePath:J,patterns:G??[],content:X}));return{id:`${W.source}:${w0(J).slice(0,20)}`,relativePath:J,source:W.source,kind:W.kind,scopeDirectory:W.scopeDirectory,priority:W.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:X,contentSha256:Y}}async function MO(O,$){let Q=c$(O);if(!$.projectTrusted)return d.empty(Q);let Z=await m.realpath(Q),J=f$.stream([...g$],{cwd:Z,absolute:!0,dot:!0,deep:d$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...u$]}),q=[];for await(let W of J)if(q.push(W.toString()),q.length>HO)throw Error(`Project rule catalog exceeds ${HO} files`);q.sort();let K=new Set(q.filter((W)=>S.basename(W)==="AGENTS.override.md").map((W)=>S.dirname(W))),X=[],G=0;for(let W of q){if(S.basename(W)==="AGENTS.md"&&K.has(S.dirname(W)))continue;try{let Y=await i$(Z,W);if(G+=Buffer.byteLength(Y.content,"utf8"),G>VO)throw Error(`Project rule catalog exceeds ${VO} bytes`);X.push(Y)}catch(Y){p$.warn(`[ProjectRules] Ignoring rule: ${Y instanceof Error?Y.message:String(Y)}`)}}return new d(Z,X)}var bO=32,D0=64;class AO extends Error{capacity=D0;constructor(){super(`Workspace agent resource capacity is full (${D0})`);this.name="WorkspaceAgentResourceCapacityError"}}var x=new Map,W1=0,xO=[];async function o$(O){let $=await N.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await J1(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function a$(O){let $={...O};for(let Q of Object.values(b0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function o2(O){xO=[...new Set(O.map(($)=>Y1.resolve($)))]}function _O(O,$){JO(O,$.plugins),C.releaseInstance(O,$.subagents),P.releaseInstance({cwd:O},$.skills),_.releaseInstance(O,$.commands),D.releaseInstance(O,$.plugins)}function TO(O){_O(O.workspaceRoot,O)}function q0(){while(x.size>bO){let O=!1;for(let[$,Q]of x){if(!Q.resources||Q.users>0)continue;if(x.get($)!==Q)continue;x.delete($),TO(Q.resources),O=!0;break}if(!O)return}}function t$(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),q0()}).unref?.()}async function r$(O,$){let Q=await N.getInstance().getStatus(O),Z=o(O),J=g({cwd:O}),q=_.getInstance(O),K=Q0(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),q.isInitialized()?void 0:q.initialize(O),K.isInitialized()?void 0:K.initialize(O,[...$.cliPluginDirs??xO])]),A0(O),await Q1(O);let X=await J1(O,{projectTrusted:Q.state==="trusted",plugins:K.getActive()}),G=await MO(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:q,plugins:K,communicationStyles:X,projectRules:G}}catch(X){throw _O(O,{subagents:Z,skills:J,commands:q,plugins:K}),X}}function e$(O,$){let Q={generation:W1,users:0};return Q.promise=r$(O,$).then((Z)=>{if(Q.generation!==W1||x.get(O)!==Q)return TO(Z),Z;return Q.resources=Z,q0(),Z},(Z)=>{if(x.get(O)===Q)x.delete(O);throw Z}),x.set(O,Q),Q}async function wO(O,$){let Q=Y1.resolve(O),Z=x.get(Q);if(!Z){if(q0(),x.size>=D0)throw new AO;Z=e$(Q,$)}else x.delete(Q),x.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(q){throw Z.users=Math.max(0,Z.users-1),q0(),q}return{entry:Z,resources:J}}async function DO(O,$){if(!$)return;A0(O.workspaceRoot),await Q1(O.workspaceRoot),await o$(O)}async function a2(O,$={}){let Q=await wO(O,$);try{return await DO(Q.resources,$.reconcilePlugins),Q.resources}finally{t$(Q.entry)}}async function t2(O,$,Q={}){let Z=await wO(O,Q);try{return await DO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),q0()}}function r2(){let O=0,$=0;for(let Q of x.values()){if(Q.resources)O++;$+=Q.users}return{capacity:bO,activeCapacity:D0,entries:x.size,initialized:O,inFlight:x.size-O,activeUsers:$}}function e2(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:Y1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??IO.snapshot(),projectRules:O.projectRules?.snapshot()??d.empty($),hooks:a$("hooks"in O&&O.hooks?O.hooks:J0.getInstance().getConfig($))}}function O5(){W1++;for(let[O,$]of x)if($.resources)A0(O);x.clear(),C.resetInstances(),P.resetInstance(),_.resetInstance(),D.resetInstance()}
710
- export{Q4 as be,Z4 as ce,V1 as de,L4 as ee,X4 as fe,o as ge,_4 as he,I1 as ie,g as je,_ as ke,t0 as le,M0 as me,D as ne,Q0 as oe,Q1 as pe,A0 as qe,d as re,bO as se,D0 as te,AO as ue,o$ as ve,o2 as we,a2 as xe,t2 as ye,r2 as ze,e2 as Ae,O5 as Be};
710
+ export{Q4 as le,Z4 as me,V1 as ne,L4 as oe,X4 as pe,o as qe,_4 as re,I1 as se,g as te,_ as ue,t0 as ve,M0 as we,D as xe,Q0 as ye,Q1 as ze,A0 as Ae,d as Be,bO as Ce,D0 as De,AO as Ee,o$ as Fe,o2 as Ge,a2 as He,t2 as Ie,r2 as Je,e2 as Ke,O5 as Le};
@@ -1,2 +1,2 @@
1
1
  var i="verification",E="goal-verification",e="review";function t(n){return n==="verification"||n==="goal-verification"}function o(n){return t(n)||n==="review"}
2
- export{i as Ce,E as De,e as Ee,t as Fe,o as Ge};
2
+ export{i as Me,E as Ne,e as Oe,t as Pe,o as Qe};
@@ -1,2 +1,2 @@
1
- import{$g as h,Zg as d}from"./chunk-6fdvffcc.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},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",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
- export{q as Zc,w as _c};
1
+ import{hh as d,jh as h}from"./chunk-zpwasxzh.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},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",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
+ export{q as hd,w as id};
@@ -0,0 +1,2 @@
1
+ import{kg as J,lg as $,mg as U,ng as B}from"./chunk-7mdbwjxj.js";import{og as v,pg as h,qg as u}from"./chunk-fz60jh3y.js";import{Vg as i}from"./chunk-1vt7e9e7.js";import{xh as s}from"./chunk-6tacv9rs.js";var O=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],r={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},E=new Map;function D(Q,Z,W){let K=new Set;for(let X of Q.split(",")){let[Y,V]=X.split("/"),G=V?Number.parseInt(V,10):1;if(!Number.isInteger(G)||G<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=W;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[k,t]=Y.split("-");j=Number.parseInt(k,10),H=Number.parseInt(t,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>W||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let k=j;k<=H;k+=G)K.add(k)}return K}function R(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[W,K,X,Y,V]=Z,G=D(V,O[4].min,O[4].max),j=new Set([...G].map((H)=>H===7?0:H));return{minutes:D(W,O[0].min,O[0].max),hours:D(K,O[1].min,O[1].max),daysOfMonth:D(X,O[2].min,O[2].max),months:D(Y,O[3].min,O[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:V.trim()!=="*"}}function T(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let W=E.get(Z);if(!W)W=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),E.set(Z,W);let K=Object.fromEntries(W.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(K.minute),hour:Number(K.hour),dayOfMonth:Number(K.day),month:Number(K.month),dayOfWeek:r[K.weekday]??-1}}function y(Q,Z,W){let K=T(Z,W);if(!Q.minutes.has(K.minute))return!1;if(!Q.hours.has(K.hour))return!1;if(!Q.months.has(K.month))return!1;let X=Q.daysOfMonth.has(K.dayOfMonth),Y=Q.daysOfWeek.has(K.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function p(Q,Z,W){let K=R(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(y(K,X,W))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var S={s:1000,m:60000,h:3600000,d:86400000};function zJ(Q){let W=Q.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!W)return null;let K=Number.parseInt(W[1],10);if(!Number.isInteger(K)||K<=0)return null;let X=W[2]||"m";return K*S[X]}function e(Q){for(let Z of["d","h","m","s"]){let W=S[Z];if(Q%W===0)return`${Q/W}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,W){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return p(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((W??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let K=new Date(Q.runAt);if(Number.isNaN(K.getTime()))return null;return K.getTime()>Z.getTime()?K:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(R(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function AJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?e(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as LJ,readFile as PJ}from"node:fs/promises";import a from"node:path";import{nanoid as MJ}from"nanoid";import IJ from"write-file-atomic";var w=$(B(["default","autoEdit","yolo","plan"]));var N=$(B(["user","assistant","system","tool"])),JJ=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),d=J.Union([J.String(),J.Array(JJ)]),xJ=$(J.Object({id:J.String(),role:N,content:d,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),QJ=$(B(["queued","running","completed","failed","cancelled","interrupted"])),F=$(B(["local","worktree"])),q=$(B(["high","medium","low"])),x=$(B(["feature","bug","maintenance","research"])),ZJ=$(B(["applied","discarded","conflicted"])),$J=$(J.Object({status:ZJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),BJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),KJ=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),fJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array(KJ,{maxItems:100}),truncated:J.Boolean()})),WJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),XJ=$(J.Object({name:J.String(),type:B(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(WJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(B(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),CJ=$(J.Object({serverName:J.String(),mode:B(["form","url"]),message:J.String(),fields:J.Optional(J.Array(XJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),YJ=$(J.Object({type:B(["permission","question","elicitation"]),requestId:J.String()})),HJ=$(J.Object({code:B(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","capacity","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean(),resource:J.Optional(B(["pending_count","pending_bytes","resident_runtimes"]))})),L=$(B(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(B(["auto","standard","fast","flex"])),M=$(B(["auto","low","medium","high"])),b=$(J.Union([B(["auto","pragmatic","friendly","explanatory"]),J.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(B(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:U(QJ,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(HJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskPriority:J.Optional(q),taskKind:J.Optional(x),taskDueAt:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional($J),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(BJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(YJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),EJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),RJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),SJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),lJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:B(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),completionVerification:J.Optional(J.Object({attempt:J.Integer({minimum:1}),status:B(["pending","pass","fail","partial"]),requestedAt:J.String(),completedAt:J.Optional(J.String()),verifierSessionId:J.Optional(J.String()),summary:J.Optional(J.String()),evidenceSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),createdAt:J.String(),updatedAt:J.String()})),m=$(J.Object({role:N,content:d,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),hJ=$(J.Object({session:z,messages:J.Array(m)})),c=$(B(["conversation","code","both"])),jJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),uJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:U(c,"conversation")})),dJ=$(J.Object({checkpoint:jJ,mode:c,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(m)})),UJ=B(["running","completed","failed","cancelled"]),l=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:UJ,background:J.Boolean(),rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),restartRecovery:J.Optional(J.Object({outcome:B(["completed","interrupted","failed"]),recoveredAt:J.Number()})),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(B(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),mJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),cJ=$(J.Object({source:l,session:l})),gJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),nJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),oJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),sJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),g=J.Object({type:B(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:h})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),n=J.Record(J.String(),J.Unknown()),iJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),taskPriority:U(q,"medium"),taskKind:U(x,"feature"),taskDueAt:J.Optional(J.String({minLength:1,maxLength:64})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default"),attachments:J.Optional(J.Array(g,{maxItems:v})),outputSchema:J.Optional(n)})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),taskPriority:J.Optional(q),taskKind:J.Optional(x),taskDueAt:J.Optional(J.Union([J.String({minLength:1,maxLength:64}),J.Null()]))})),tJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:B(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),rJ=$(J.Object({action:B(["apply","discard"])})),f=$(J.Object({kind:B(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),kJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default")})),C=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:f,dispatch:kJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(B(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),TJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:f,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default"),enabled:U(J.Boolean(),!0)})),yJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(f),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),pJ=$(J.Object({schedules:J.Array(C)})),eJ=$(J.Object({content:J.String({maxLength:u}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(g,{maxItems:v})),outputSchema:J.Optional(n)})),VJ=B(["completed","failed","aborted","timed_out","spawn_error"]),GJ=$(J.Object({version:J.Literal(1),command:J.String(),status:VJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),JQ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),QQ=$(J.Object({executionId:J.String(),messageId:J.String(),record:GJ,auxiliary:J.Boolean(),delivery:J.Optional(B(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),ZQ=$(J.Object({projectPath:J.String(),kind:B(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),$Q=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),BQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),KQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(B(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:B(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),OJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:B(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),WQ=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(B(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(B(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(B(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(OJ,{maxItems:36})),input:J.Optional(J.Array(B(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),XQ=$(B(["vs-dark","vs-light","hc-black"])),bJ=$(B(["light","dark","system"])),wJ=$(J.Object({language:J.String(),codeTheme:J.String(),uiTheme:bJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),YQ=$(J.Partial(wJ));var o=i("Service"),DJ=1;function FJ(){return a.join(s(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=FJ()){this.filePath=Q}async readFile(){try{let Q=await PJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let W=[],K=0;for(let X of Z.schedules){let Y=C.safeParse(X);if(Y.success)W.push(Y.data);else K+=1}if(K>0)o.warn(`[ScheduleStore] Ignored ${K} invalid persisted schedule(s)`);return W}catch(Q){let Z=Q;if(Z.code!=="ENOENT")o.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await LJ(a.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:DJ,schedules:Q};await IJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((W)=>W.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,W=_(Z);if(W)throw Error(W);let K=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=K.getTime())throw Error("once trigger runAt must be in the future");let X=K.toISOString(),Y=A(Z,K),V={id:MJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},G=await this.readFile();return G.push(V),await this.writeFile(G),V})}async update(Q,Z){return this.serializeWrite(async()=>{let W=await this.readFile(),K=W.findIndex((H)=>H.id===Q);if(K===-1)return;let X=W[K];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,k=_(H);if(k)throw Error(k);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},V=!X.enabled,G=Y.enabled,j=Z.trigger!==void 0;if((j||V&&G)&&Z.nextRunAt===void 0){let H=new Date,k=A(Y.trigger,H);if(Y.nextRunAt=k?k.toISOString():null,j)Y.expiresAt=null}return W[K]=Y,await this.writeFile(W),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),W=Z.filter((K)=>K.id!==Q);if(W.length===Z.length)return!1;return await this.writeFile(W),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var IQ=I.getInstance();
2
+ export{zJ as xa,A as ya,_ as za,AJ as Aa,fJ as Ba,z as Ca,uJ as Da,mJ as Ea,iJ as Fa,aJ as Ga,tJ as Ha,rJ as Ia,C as Ja,TJ as Ka,yJ as La,pJ as Ma,eJ as Na,JQ as Oa,ZQ as Pa,I as Qa,IQ as Ra};
@@ -0,0 +1 @@
1
+ import{ce as a}from"./chunk-h127mgg2.js";import"./chunk-ngmajm4h.js";import"./chunk-1vt7e9e7.js";import"./chunk-eharmsjt.js";import"./chunk-gafk33py.js";import"./chunk-6tacv9rs.js";import"./chunk-arzhhj0e.js";export{a as createChatServiceAsync};