dal-code 1.0.56 → 1.0.58

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 (132) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/bundle/chunks/{anthropic-messages-HHQLDDZH.js → anthropic-messages-FOIJU7LX.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-S7VKEJTH.js → azure-openai-responses-7NBJZKX5.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-QCT6OHUR.js → chunk-3QG7FIE4.js} +1 -1
  6. package/dist/bundle/chunks/chunk-4BOWD7PQ.js +1 -0
  7. package/dist/bundle/chunks/{chunk-UULAEZ3H.js → chunk-4PBY6OYS.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-BIY5HTFI.js → chunk-5MF5GEDD.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-3XMZ5UC3.js → chunk-B7KZDIWA.js} +1 -1
  10. package/dist/bundle/chunks/chunk-C5ELI234.js +17 -0
  11. package/dist/bundle/chunks/{chunk-RX6CC5RH.js → chunk-CCU76UL3.js} +443 -472
  12. package/dist/bundle/chunks/{chunk-PH42AQ66.js → chunk-DVEPGKL5.js} +1 -1
  13. package/dist/bundle/chunks/chunk-G5AMLGXC.js +1 -0
  14. package/dist/bundle/chunks/chunk-HF334NQU.js +21 -0
  15. package/dist/bundle/chunks/{chunk-Z64M4Q7A.js → chunk-IONGABQF.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-F37JXTCY.js → chunk-JK74OC6W.js} +1 -1
  17. package/dist/bundle/chunks/chunk-JUUJCOIR.js +7 -0
  18. package/dist/bundle/chunks/chunk-JXAFVEE4.js +17 -0
  19. package/dist/bundle/chunks/chunk-LMZYTWXD.js +14 -0
  20. package/dist/bundle/chunks/chunk-NJDCSLWK.js +1 -0
  21. package/dist/bundle/chunks/{chunk-BCFLC6CK.js → chunk-NYSVXLKF.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-P4IBZA6D.js → chunk-PMFHJN7I.js} +1 -1
  23. package/dist/bundle/chunks/chunk-QFBU27TM.js +30 -0
  24. package/dist/bundle/chunks/{chunk-SZZVJTVX.js → chunk-QU2VEHMW.js} +1 -1
  25. package/dist/bundle/chunks/chunk-SCZEDPDC.js +9 -0
  26. package/dist/bundle/chunks/{chunk-VGMP27KM.js → chunk-T5PI6B5P.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-ZR6PGIL7.js → chunk-X7I3V6OA.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-3HGUIN22.js → chunk-XQF5XDEM.js} +2 -2
  29. package/dist/bundle/chunks/{cli-TVPE43YN.js → cli-NQ7B7BGV.js} +1 -1
  30. package/dist/bundle/chunks/{cli-NGGC23SK.js → cli-RY666QAD.js} +1 -1
  31. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-RK2YCJXC.js → cloudflare-workers-ai-system-one-CFGOMWWZ.js} +1 -1
  32. package/dist/bundle/chunks/{execute-MGTKJB44.js → execute-NJRE4WBO.js} +2 -2
  33. package/dist/bundle/chunks/{google-generative-ai-ZPA4VBXP.js → google-generative-ai-ZA2RHPNE.js} +1 -1
  34. package/dist/bundle/chunks/{google-vertex-IWHW2RX7.js → google-vertex-Y2GRWOK7.js} +1 -1
  35. package/dist/bundle/chunks/{llama-cpp-classify-FXJM52Q3.js → llama-cpp-classify-G2JDOFHY.js} +1 -1
  36. package/dist/bundle/chunks/{mcp-RLFUDVHN.js → mcp-45D7KCZZ.js} +1 -1
  37. package/dist/bundle/chunks/{mistral-conversations-JXVPTO5Y.js → mistral-conversations-MLV32BRV.js} +1 -1
  38. package/dist/bundle/chunks/{office-RTREQQ7W.js → office-UBOUFRAU.js} +1 -1
  39. package/dist/bundle/chunks/{openai-codex-responses-EYW27UUE.js → openai-codex-responses-BDK3PY6G.js} +1 -1
  40. package/dist/bundle/chunks/{openai-completions-ROBKXDOC.js → openai-completions-BLXHKAB3.js} +1 -1
  41. package/dist/bundle/chunks/{openai-decisions-4T5LPJRA.js → openai-decisions-IGVID576.js} +1 -1
  42. package/dist/bundle/chunks/{openai-responses-ZVFZ75QW.js → openai-responses-KHZOEDF2.js} +1 -1
  43. package/dist/bundle/chunks/{openrouter-images-6VJYTLAX.js → openrouter-images-SA6PUASF.js} +1 -1
  44. package/dist/bundle/chunks/{pi-messages-Y6HBOGKH.js → pi-messages-3VAOLQ2Y.js} +1 -1
  45. package/dist/bundle/chunks/{review-USSKCVWP.js → review-RZXLHPUZ.js} +2 -2
  46. package/dist/bundle/chunks/{router-4JLK3BTT.js → router-YBVXODIL.js} +1 -1
  47. package/dist/bundle/chunks/runtime-FNCZJKOC.js +1 -0
  48. package/dist/bundle/chunks/sdk-X6RX7FNE.js +1 -0
  49. package/dist/bundle/chunks/{sync-UCHKAOUU.js → sync-CRV6BXXC.js} +3 -3
  50. package/dist/bundle/chunks/{typesafe-system-one-XPDE7VYD.js → typesafe-system-one-ER3DLYNF.js} +1 -1
  51. package/dist/bundle/chunks/usage-LMRFS2HV.js +1 -0
  52. package/dist/bundle/chunks/virtual-modules-XIUNRFOZ.js +1 -0
  53. package/dist/bundle/cli-runtime.js +1 -1
  54. package/dist/bundle/index.js +1 -1
  55. package/dist/bundle/rpc-entry.js +1 -1
  56. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  57. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  58. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  59. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  60. package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
  61. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  62. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  63. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  64. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  65. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  66. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  67. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  68. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  69. package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
  70. package/dist/node_modules/@dalcode/dal-learn/src/engine.js +3 -3
  71. package/dist/node_modules/@dalcode/dal-learn/src/index.js +11 -11
  72. package/dist/node_modules/@dalcode/dal-learn/src/lessons.js +4 -4
  73. package/dist/node_modules/@dalcode/dal-learn/src/project-map.js +2 -2
  74. package/dist/node_modules/@dalcode/dal-learn/src/signals.js +6 -6
  75. package/dist/node_modules/@dalcode/dal-learn/src/store.js +3 -3
  76. package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
  77. package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -6
  78. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  79. package/dist/node_modules/@dalcode/dal-pi-kit/dist/agent-dir.js +1 -0
  80. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
  81. package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
  82. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  83. package/dist/node_modules/@dalcode/dal-pi-kit/src/agent-dir.js +1 -0
  84. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
  85. package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
  86. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  87. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  88. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  89. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  90. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  91. package/dist/node_modules/@dalcode/dal-router/package.json +6 -6
  92. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  93. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  94. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  95. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  96. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  97. package/dist/node_modules/@dalcode/dal-sync/package.json +4 -4
  98. package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -4
  99. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  100. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  101. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  102. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  103. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  104. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  105. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  106. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  107. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  108. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -1
  109. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -1
  110. package/dist/node_modules/@earendil-works/pi-ai/package.json +3 -3
  111. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  112. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  113. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  114. package/dist/node_modules/@earendil-works/pi-schema/package.json +1 -1
  115. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  116. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  117. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  118. package/examples/extensions/gondolin/package-lock.json +2 -2
  119. package/examples/extensions/gondolin/package.json +1 -1
  120. package/examples/extensions/with-deps/package-lock.json +2 -2
  121. package/examples/extensions/with-deps/package.json +1 -1
  122. package/npm-shrinkwrap.json +2 -2
  123. package/package.json +1 -1
  124. package/dist/bundle/chunks/chunk-3YGHTGYM.js +0 -7
  125. package/dist/bundle/chunks/chunk-MKMLENQD.js +0 -17
  126. package/dist/bundle/chunks/chunk-SE42OS3U.js +0 -21
  127. package/dist/bundle/chunks/chunk-T3TEURLR.js +0 -30
  128. package/dist/bundle/chunks/chunk-XTN2LDU3.js +0 -9
  129. package/dist/bundle/chunks/runtime-G7F6UQLA.js +0 -1
  130. package/dist/bundle/chunks/sdk-CEIRR6KD.js +0 -1
  131. package/dist/bundle/chunks/usage-3ACOJWR3.js +0 -1
  132. package/dist/bundle/chunks/virtual-modules-P4JE2EA6.js +0 -1
@@ -0,0 +1,14 @@
1
+ var Yt=Object.defineProperty;var o=(e,t)=>Yt(e,"name",{value:t,configurable:!0});import{createRequire as Vt}from"node:module";const ks=Vt(import.meta.url);import{getProviderEnvValue as qt}from"./chunk-7DDKXS2Q.js";import{ToolCallArgumentsStream as Ht}from"./chunk-FFMDRXC4.js";import{calculateCost as Kt,createProvider as Jt}from"./chunk-5MF5GEDD.js";import{createAssistantMessageEventStream as be}from"./chunk-4LDEEFCY.js";import{getSystemMessageText as Xt}from"./chunk-JK74OC6W.js";function Zt(e,t){return{name:e,login:o(async r=>{r.signal.throwIfAborted();let n=await r.prompt({type:"secret",message:`Enter ${e}`});return r.signal.throwIfAborted(),{type:"api_key",key:n}},"login"),resolve:o(async({ctx:r,credential:n,signal:i})=>{if(i.throwIfAborted(),n?.key)return{auth:{apiKey:n.key},env:n.env,source:"stored credential"};for(let s of t){let a=await r.env(s);if(i.throwIfAborted(),a)return{auth:{apiKey:a},source:s}}},"resolve")}}o(Zt,"envApiKeyAuth");function Qt(e){let t,r=o(()=>(t??=e.load(),t),"loaded");return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:o(async(n,i)=>(await r()).login(n,i),"login"),refresh:o(async(n,i)=>(await r()).refresh(n,i),"refresh"),toAuth:o(async n=>(await r()).toAuth(n),"toAuth")}}o(Qt,"lazyOAuth");var er=60*6e4,tr=30*6e4,Oe=.05,ke=.15;function rr(e){if(!(e<=1e4))return Math.max(1,Math.floor(Math.min(e*.9,e-1e4)))}o(rr,"getCacheWarmingDelayMs");function nr(e,t){let r=t?.cacheRetention??(qt("PI_CACHE_RETENTION",t?.env)==="long"?"long":"short");if(r==="none")return;let n=e.promptCache?.[r];return n===void 0?void 0:n*1e3}o(nr,"getPromptCacheTtlMs");function ir(e,t){return!t?.reasoning||e.api!=="anthropic-messages"?!0:e.compat?.forceAdaptiveThinking===!0}o(ir,"isCacheWarmingReplayable");function sr(e,t){return{...e,maxTokens:1,disableContinuation:!0,maxRetries:0,signal:t}}o(sr,"getCacheWarmingRequestOptions");function or(e,t,r){let n=ie(e,{cacheRead:t}),i=ie(e,e.cost.cacheWrite>0?{cacheWrite:t}:{input:t}),s=ie(e,{cacheRead:t,output:1}),a=Math.max(0,i-n),f=r==="idle"?ke:1,u=t>0&&(n>0||i>0),c=f*a-s;return{phase:r,warmCost:s,missCost:a,continuationProbability:f,expectedSavings:c,economicsAvailable:u,action:c>=Oe?"warm":"stop"}}o(or,"evaluateCacheWarming");function ie(e,t){let r={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},...t};return Kt(e,r).total}o(ie,"price");var Ee="faux",xe="faux",we="faux-1",ar="Faux Model",fr="http://localhost:0",ur=3,Re=5,V={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function _e(e){return{type:"text",text:e}}o(_e,"fauxText");function cr(e){return{type:"thinking",thinking:e}}o(cr,"fauxThinking");function lr(e,t,r={}){return{type:"toolCall",id:r.id??se("tool"),name:e,arguments:t}}o(lr,"fauxToolCall");function dr(e){return typeof e=="string"?[_e(e)]:Array.isArray(e)?e:[e]}o(dr,"normalizeFauxAssistantContent");function hr(e,t={}){return{role:"assistant",content:dr(e),api:Ee,provider:xe,model:we,usage:V,stopReason:t.stopReason??"stop",...t.deferred===void 0?{}:{deferred:t.deferred},...t.errorMessage===void 0?{}:{errorMessage:t.errorMessage},...t.responseId===void 0?{}:{responseId:t.responseId},timestamp:t.timestamp??Date.now()}}o(hr,"fauxAssistantMessage");function Ne(e){return Math.ceil(e.length/4)}o(Ne,"estimateTokens");function se(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}o(se,"randomId");function $e(e){return typeof e=="string"?e:e.map(t=>t.type==="text"?t.text:`[image:${t.mimeType}:${t.data.length}]`).join(`
2
+ `)}o($e,"contentToText");function Se(e){return e.map(t=>t.type==="text"?t.text:t.type==="thinking"?t.thinking:`${t.name}:${JSON.stringify(t.arguments)}`).join(`
3
+ `)}o(Se,"assistantContentToText");function pr(e){return[e.toolName,...e.content.map(t=>$e([t]))].join(`
4
+ `)}o(pr,"toolResultToText");function mr(e){return e.role==="system"?[Xt(e),...e.toolsRemoved?.map(t=>`tool-:${JSON.stringify(t)}`)??[],...e.toolsAdded?.map(t=>`tool+:${JSON.stringify(t)}`)??[]].filter(t=>t.length>0).join(`
5
+ `):e.role==="user"?$e(e.content):e.role==="assistant"?Se(e.content):pr(e)}o(mr,"messageToText");function Ce(e,t=e.length){let r=t>0?(t-1)*2:0;for(let n=0;n<t;n++)r+=e[n].length;return r}o(Ce,"joinedLength");function yr(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;let n=o(i=>r===i.length?"":(r>0?`
6
+
7
+ `:"")+i.slice(r).join(`
8
+
9
+ `),"rest");return Ce(e,r)+gr(n(e),n(t))}o(yr,"commonPromptPrefixLength");function gr(e,t){let r=Math.min(e.length,t.length),n=0;for(;n<r&&e[n]===t[n];)n++;return n}o(gr,"commonPrefixLength");function Pe(e,t,r,n){let i=t.messages.map(h=>`${h.role}:${mr(h)}`),s=Ce(i),a=Math.ceil(s/4),f=Ne(Se(e.content)),u=a,c=0,l=0,d=r?.sessionId;if(d&&r?.cacheRetention!=="none"){let h=n.get(d);if(h){let m=yr(h,i);c=Math.ceil(m/4),l=Math.max(0,a-c)}else l=a;u=0,n.set(d,i)}return{...e,usage:{input:u,output:f,cacheRead:c,cacheWrite:l,totalTokens:u+f+c+l,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}o(Pe,"withUsageEstimate");function oe(e,t,r){let n=[],i=0;for(;i<e.length;){let s=t+Math.floor(Math.random()*(r-t+1)),a=Math.max(1,s*4);n.push(e.slice(i,i+a)),i+=a}return n.length>0?n:[""]}o(oe,"splitStringByTokenSize");function Ir(e,t,r,n){let i=structuredClone(e);return{...i,api:t,provider:r,model:n,timestamp:i.timestamp??Date.now(),usage:i.usage??V}}o(Ir,"cloneMessage");function Te(e,t){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:V,stopReason:"deferred",deferred:t,timestamp:Date.now()}}o(Te,"createDeferredMessage");function q(e,t,r,n){return{role:"assistant",content:[],api:t,provider:r,model:n,usage:V,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}o(q,"createErrorMessage");function L(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}o(L,"createAbortedMessage");function ae(e,t){if(!t||t<=0)return new Promise(n=>queueMicrotask(n));let r=Ne(e)/t*1e3;return new Promise(n=>setTimeout(n,r))}o(ae,"scheduleChunk");async function H(e,t,r,n,i,s){let a={...t,content:[],stopReason:"pending"};if(s?.aborted){let f=L(a);e.push({type:"error",reason:"aborted",error:f}),e.end(f);return}e.push({type:"start",partial:{...a}});for(let f=0;f<t.content.length;f++){if(s?.aborted){let l=L(a);e.push({type:"error",reason:"aborted",error:l}),e.end(l);return}let u=t.content[f];if(u.type==="thinking"){a.content=[...a.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:f,partial:{...a}});for(let l of oe(u.thinking,r,n)){if(await ae(l,i),s?.aborted){let d=L(a);e.push({type:"error",reason:"aborted",error:d}),e.end(d);return}a.content[f].thinking+=l,e.push({type:"thinking_delta",contentIndex:f,delta:l,partial:{...a}})}e.push({type:"thinking_end",contentIndex:f,content:u.thinking,partial:{...a}});continue}if(u.type==="text"){a.content=[...a.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:f,partial:{...a}});for(let l of oe(u.text,r,n)){if(await ae(l,i),s?.aborted){let d=L(a);e.push({type:"error",reason:"aborted",error:d}),e.end(d);return}a.content[f].text+=l,e.push({type:"text_delta",contentIndex:f,delta:l,partial:{...a}})}e.push({type:"text_end",contentIndex:f,content:u.text,partial:{...a}});continue}a.content=[...a.content,{type:"toolCall",id:u.id,name:u.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:f,partial:{...a}});let c=new Ht;for(let l of oe(JSON.stringify(u.arguments),r,n)){if(await ae(l,i),s?.aborted){let d=L(a);e.push({type:"error",reason:"aborted",error:d}),e.end(d);return}a.content[f].arguments=c.append(l),e.push({type:"toolcall_delta",contentIndex:f,delta:l,partial:{...a}})}a.content[f].arguments=u.arguments,e.push({type:"toolcall_end",contentIndex:f,toolCall:u,partial:{...a}})}if(t.stopReason==="pending")throw new Error("Faux response ended without a stop reason");if(t.stopReason==="error"||t.stopReason==="aborted"){e.push({type:"error",reason:t.stopReason,error:t}),e.end(t);return}e.push({type:"done",reason:t.stopReason,message:t}),e.end(t)}o(H,"streamWithDeltas");function Me(e){let t=e.api??se(Ee),r=e.provider??xe,n=Math.max(1,Math.min(e.tokenSize?.min??ur,e.tokenSize?.max??Re)),i=Math.max(n,e.tokenSize?.max??Re),s=[],a=e.tokensPerSecond,f={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},u=new Map,c=new Map,l=(e.models?.length?e.models:[{id:we,name:ar,reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:16384}]).map(y=>({id:y.id,name:y.name??y.id,api:t,provider:r,baseUrl:fr,reasoning:y.reasoning??!1,input:y.input??["text","image"],inputLimits:y.inputLimits,cost:y.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:y.contextWindow??128e3,maxTokens:y.maxTokens??16384})),d=o(async(y,I,b,A)=>{let g=typeof y=="function"?await y(I,b,f,A):y;return Pe(Ir(g,t,r,A.id),I,b,u)},"resolveResponse"),h=o((y,I,b)=>{let A=be(),g=s.shift();return f.callCount++,queueMicrotask(async()=>{try{if(await b?.onResponse?.({status:200,headers:{}},y),!g){let k=q(new Error("No more faux responses queued"),t,r,y.id);k=Pe(k,I,b,u),A.push({type:"error",reason:"error",error:k}),A.end(k);return}if(b?.deferred){let k={provider:y.provider,modelId:y.id,api:y.api,id:se("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};c.set(k.id,{handle:k,step:g,context:I,options:b,model:y,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await H(A,Te(y,k),n,i,a,b.signal);return}let N=await d(g,I,b,y);await H(A,N,n,i,a,b?.signal)}catch(N){let k=q(N,t,r,y.id);A.push({type:"error",reason:"error",error:k}),A.end(k)}}),A},"stream"),m=o((y,I,b)=>h(y,I,b),"streamSimple"),w=o((y,I,b)=>{let A=be();return f.deferredFetchCount++,queueMicrotask(async()=>{try{await b?.onResponse?.({status:200,headers:{}},y);let g=c.get(I.id);if(!g||g.handle.provider!==I.provider||g.handle.modelId!==I.modelId||g.handle.api!==I.api)throw new Error(`Unknown faux deferred response: ${I.id}`);if(g.cancelled)throw new Error(`Faux deferred response was cancelled: ${I.id}`);if(g.pendingFetches>0){g.pendingFetches--,await H(A,Te(y,g.handle),n,i,a,b?.signal);return}if(!g.final){let{deferred:N,signal:k,onResponse:As,...Gt}=g.options??{};try{g.final=await d(g.step,g.context,Gt,g.model)}catch(Wt){g.final=q(Wt,t,r,g.model.id)}}await H(A,g.final,n,i,a,b?.signal)}catch(g){let N=q(g,t,r,y.id);A.push({type:"error",reason:"error",error:N}),A.end(N)}}),A},"fetchDeferred"),j=o(async(y,I,b)=>{f.cancelledDeferred.push(structuredClone(I));let A=c.get(I.id);A&&(A.cancelled=!0),await b?.onResponse?.({status:200,headers:{}},y)},"cancelDeferred");function ne(y){return y?l.find(I=>I.id===y):l[0]}return o(ne,"getModel"),{api:t,provider:r,models:l,stream:h,streamSimple:m,fetchDeferred:w,cancelDeferred:j,getModel:ne,state:f,setResponses(y){s=[...y]},appendResponses(y){s.push(...y)},getPendingResponseCount(){return s.length}}}o(Me,"createFauxCore");function Ar(e={}){let t=Me(e);return{provider:Jt({id:t.provider,auth:{apiKey:{name:"Faux",resolve:o(async()=>({auth:{}}),"resolve")}},models:t.models,api:{stream:t.stream,streamSimple:t.streamSimple,fetchDeferred:t.fetchDeferred,cancelDeferred:t.cancelDeferred}}),api:t.api,models:t.models,getModel:t.getModel,state:t.state,setResponses:t.setResponses,appendResponses:t.appendResponses,getPendingResponseCount:t.getPendingResponseCount}}o(Ar,"fauxProvider");var je=[/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/context window exceeded/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^(?:[\w -]+ API error \(413\):|413(?:\s|:|$))/i],br=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,Or=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function kr(e,t){return!!(e.stopReason==="error"&&e.errorMessage&&!Or.some(r=>r.test(e.errorMessage))&&(je.some(r=>r.test(e.errorMessage))||e.provider==="cerebras"&&br.test(e.errorMessage))||t&&e.stopReason==="stop"&&e.usage.input+e.usage.cacheRead>t||t&&e.stopReason==="length"&&e.usage.output===0&&e.usage.input+e.usage.cacheRead>=t*.99)}o(kr,"isContextOverflow");var Er=4096,xr=.9;function wr(e,t,r){if(e.stopReason!=="length"||t<=0||e.usage.output>=t)return!1;if(r===void 0||r<=0||!e.content.some(i=>i.type==="text"&&i.text.trim()!==""||i.type==="toolCall"))return!0;let n=e.usage;return n.input+n.cacheRead+n.cacheWrite+n.output+Er>=r*xr}o(wr,"isRecoverableLength");function Rr(){return[...je]}o(Rr,"getOverflowPatterns");function _r(e={}){return{type:"string",...e}}o(_r,"str");function Nr(e={}){return{type:"number",...e}}o(Nr,"num");function $r(e={}){return{type:"integer",...e}}o($r,"int");function Sr(e={}){return{type:"boolean",...e}}o(Sr,"bool");function Cr(e={}){return{type:"null",...e}}o(Cr,"nul");function Pr(e,t={}){return{enum:e,...t}}o(Pr,"oneOf");function Tr(e,t={}){return{anyOf:e,...t}}o(Tr,"union");function Mr(e,t={}){return{type:"array",items:e,...t}}o(Mr,"arr");var Le=class{static{o(this,"Optional")}schema;constructor(e){this.schema=e}};function jr(e){return new Le(e)}o(jr,"opt");function Lr(e,t={}){let{open:r,...n}=t,i={},s=[];for(let[a,f]of Object.entries(e))f instanceof Le?i[a]=f.schema:(i[a]=f,s.push(a));return{type:"object",properties:i,...s.length>0?{required:s}:{},...r===!0?{}:{additionalProperties:!1},...n}}o(Lr,"obj");var C=o(()=>!0,"ALWAYS"),fe=o(()=>!1,"NEVER"),Fe=o(e=>typeof e=="string","IS_STRING"),Ue=o(e=>Number.isFinite(e),"IS_NUMBER"),De=o(e=>Number.isInteger(e),"IS_INTEGER"),ve=o(e=>typeof e=="boolean","IS_BOOLEAN"),ze=o(e=>e===null,"IS_NULL"),Be=o(e=>Array.isArray(e),"IS_ARRAY"),Fr=o(e=>e instanceof Uint8Array,"IS_BYTES"),Ur=o(e=>typeof e=="bigint","IS_BIGINT"),Dr=o(e=>e===void 0,"IS_UNDEFINED"),Ge=o(e=>O(e),"IS_OBJECT");function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Uint8Array)}o(O,"isObject");var K=new Map([["string",Fe],["number",Ue],["integer",De],["boolean",ve],["null",ze],["array",Be],["object",Ge],["bytes",Fr],["bigint",Ur],["undefined",Dr]]),We=new WeakMap([[Fe,[1,void 0]],[Ue,[2,void 0]],[De,[3,void 0]],[ve,[4,void 0]],[ze,[5,void 0]],[C,[6,void 0]]]);function Ye(e){return We.get(e)}o(Ye,"leafOf");function P(e,t,r){return We.set(r,[e,t]),r}o(P,"leaf");var Ve=class{static{o(this,"Bounds")}min;max;xmin;xmax;constructor(e,t,r,n){this.min=e,this.max=t,this.xmin=r,this.xmax=n}};function ue(e,t,r){switch(e){case 1:return typeof t=="string";case 2:return Number.isFinite(t);case 3:return Number.isInteger(t);case 4:return typeof t=="boolean";case 5:return t===null;case 7:return t===r;case 8:{let n=r;for(let i=0;i<n.length;i++)if(n[i]===t)return!0;return!1}case 9:return(ce(t)&r)!==0;case 10:return Number.isInteger(t)&&qe(t,r);case 11:return Number.isFinite(t)&&qe(t,r);case 12:return typeof t=="string"&&Z(t,r.min,r.max);case 13:return typeof t=="string"&&r.test(t);default:return!0}}o(ue,"leafOk");function qe(e,t){return e>=t.min&&e<=t.max&&e>t.xmin&&e<t.xmax}o(qe,"inBounds");var J=0,He=1,F=2,Ke=15,U=16,Je=32;function X(e){switch(e.length){case 0:return C;case 1:return e[0];case 2:{let[t,r]=e;return n=>t(n)&&r(n)}case 3:{let[t,r,n]=e;return i=>t(i)&&r(i)&&n(i)}default:return t=>{for(let r=0;r<e.length;r++)if(!e[r](t))return!1;return!0}}}o(X,"and");function vr(e){return t=>e.check(t)}o(vr,"indirect");function Xe(e,t,r){return n=>{e.push(t);let i=r(n);return e.pop(),i}}o(Xe,"scopedCheck");function zr(e){return e.length===1?(typeof e[0]=="string"?K.get(e[0]):void 0)??fe:Qe(Ze(e))}o(zr,"typeCheck");var Br=new Map([["string",1],["number",2],["integer",4],["boolean",8],["null",16],["array",32],["object",64],["bytes",128],["bigint",256],["undefined",512]]);function Ze(e){let t=0;for(let r of e)typeof r=="string"&&(t|=Br.get(r)??0);return t}o(Ze,"typeMask");function ce(e){switch(typeof e){case"string":return 1;case"number":return Number.isInteger(e)?6:Number.isFinite(e)?2:0;case"boolean":return 8;case"object":return e===null?16:Array.isArray(e)?32:e instanceof Uint8Array?128:64;case"bigint":return 256;case"undefined":return 512;default:return 0}}o(ce,"typeBits");function Qe(e){return P(9,e,t=>(ce(t)&e)!==0)}o(Qe,"maskCheck");function Gr(e,t){if(t.length===0)return Qe(e);let r=t.length===1?t[0]:ot(t);return n=>(ce(n)&e)!==0||r(n)}o(Gr,"maskedAnyCheck");function Wr(e,t){return r=>r instanceof Uint8Array&&r.length>=e&&r.length<=t}o(Wr,"bytesCheck");function le(e){let t=0;for(let r=0;r<e.length;r++,t++){let n=e.charCodeAt(r);if(n>=55296&&n<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343&&r++}}return t}o(le,"codePoints");function Z(e,t,r){let n=e.length;return n<t||n<2*t&&le(e)<t?!1:n<=r||le(e)<=r}o(Z,"lengthOk");function Yr(e,t,r,n,i){return n!==void 0&&t===0&&r===Number.POSITIVE_INFINITY&&i===void 0?e?P(13,n,s=>typeof s=="string"&&n.test(s)):s=>typeof s!="string"||n.test(s):n===void 0&&i===void 0?e?P(12,new Ve(t,r,0,0),s=>typeof s=="string"&&Z(s,t,r)):s=>typeof s!="string"||Z(s,t,r):s=>typeof s!="string"?!e:Z(s,t,r)&&(n===void 0||n.test(s))&&(i===void 0||i(s))}o(Yr,"stringCheck");function Vr(e,t,r,n,i,s){let a=o(f=>typeof f!="number"&&typeof f!="bigint"?e===0:(e===3?typeof f!="bigint":e!==0&&!Number.isFinite(f))||e===2&&!Number.isInteger(f)?!1:f>=t&&f<=r&&f>n&&f<i&&(s===void 0||et(f,s)),"check");return e===0||e===3||s!==void 0||!(typeof t=="number"&&typeof r=="number"&&typeof n=="number"&&typeof i=="number")?a:P(e===2?10:11,new Ve(t,r,n,i),a)}o(Vr,"numberCheck");function et(e,t){if(typeof e=="bigint"||typeof t=="bigint"){if(typeof e=="number"&&!Number.isInteger(e)||typeof t=="number"&&!Number.isInteger(t))return!1;let f=BigInt(t);return f!==0n&&BigInt(e)%f===0n}let r=e/t;if(Number.isInteger(r))return!0;if(!Number.isFinite(r))return e%t===0;let[n,i]=tt(e),[s,a]=tt(t);return i>=a?n*10n**BigInt(i-a)%s===0n:n%(s*10n**BigInt(a-i))===0n}o(et,"isMultiple");function tt(e){let[t,r="0"]=Math.abs(e).toString().split("e"),n=t.indexOf("."),i=n<0?0:t.length-n-1;return[BigInt(t.replace(".","")),Number(r)-i]}o(tt,"decimal");function qr(e,t){return t?r=>O(r)&&e(r):r=>!O(r)||e(r)}o(qr,"guardObject");function Hr(e,t){return t?r=>Array.isArray(r)&&e(r):r=>!Array.isArray(r)||e(r)}o(Hr,"guardArray");function Kr(e,t,r,n){let i=e.length;return s=>{if(n!==J&&!O(s))return n===F;let a=s,f=0,u=0;for(let c in a){let l=u;if(e[l]!==c){for(l=0;l<i&&e[l]!==c;)l+=3;if(l===i){if(r)return!1;continue}}u=l+3;let d=a[c],h=e[l+2];if(d===void 0&&!(h&U))continue;let m=h&Ke;if(m!==0?!ue(m,d,e[l+1]):!e[l+1](d))return!1;h&U&&f++}return f===t}}o(Kr,"declaredObject");function Jr(e,t,r,n,i,s){let a=n.length>0||i!==void 0?new Set(t):void 0;return f=>{if(s!==J&&!O(f))return s===F;let u=f;for(let c=0;c<e.length;c+=3){let l=e[c],d=u[l],h=e[c+2];if(d===void 0&&!(h&U&&Object.hasOwn(u,l))||h&Je&&!Object.hasOwn(u,l)){if(h&U)return!1;continue}let m=h&Ke;if(m!==0?!ue(m,d,e[c+1]):!e[c+1](d))return!1}for(let c=0;c<r.length;c++)if(!Object.hasOwn(u,r[c]))return!1;if(a===void 0)return!0;for(let c of Object.keys(u)){let l=a.has(c);for(let d=0;d<n.length;d++)if(n[d][0].test(c)&&(l=!0,!n[d][1](u[c])))return!1;if(!l&&i!==void 0&&!i(u[c]))return!1}return!0}}o(Jr,"openObject");function Xr(e){return t=>{for(let r in t)if(!e(r))return!1;return!0}}o(Xr,"propertyNamesCheck");function Zr(e,t){return r=>{let n=0;for(let i in r)n++;return n>=e&&n<=t}}o(Zr,"propertyCountCheck");function Qr(e){return t=>{let r=t;for(let[n,i]of e)if(Object.hasOwn(r,n)){for(let s of i)if(!Object.hasOwn(r,s))return!1}return!0}}o(Qr,"dependentRequiredCheck");function en(e){return t=>{for(let[r,n]of e)if(Object.hasOwn(t,r)&&!n(t))return!1;return!0}}o(en,"dependentSchemasCheck");var tn=[0,void 0];function rt(e,t,r,n,i){let s=n.length,[a,f]=(i===void 0?void 0:Ye(i))??tn;return u=>{if(!Array.isArray(u))return e===F;let c=u.length;if(c<t||c>r)return!1;let l=c<s?c:s;for(let d=0;d<l;d++)if(!n[d](u[d]))return!1;if(i===void 0)return!0;if(a!==0){for(let d=s;d<c;d++)if(!ue(a,u[d],f))return!1;return!0}for(let d=s;d<c;d++)if(!i(u[d]))return!1;return!0}}o(rt,"listCheck");function rn(e,t){return rt(J,0,Number.POSITIVE_INFINITY,e,t)}o(rn,"itemsCheck");function nn(e,t){return r=>r.length>=e&&r.length<=t}o(nn,"lengthCheck");function nt(e,t,r){return n=>{let i=n,s=0;for(let a=0;a<i.length;a++)if(e(i[a])&&++s>r)return!1;return s>=t}}o(nt,"containsCheck");function it(e){let t=e;for(let r=1;r<t.length;r++)for(let n=0;n<r;n++)if(D(t[r],t[n]))return!1;return!0}o(it,"uniqueCheck");function de(e){let t=e.filter(i=>typeof i!="object"||i===null);if(t.length===e.length&&t.length<=8)return P(8,t,i=>{for(let s=0;s<t.length;s++)if(t[s]===i)return!0;return!1});let r=new Set(t),n=e.filter(i=>typeof i=="object"&&i!==null);return i=>r.has(i)||typeof i=="object"&&n.some(s=>D(i,s))}o(de,"enumCheck");function st(e){return typeof e!="object"||e===null?P(7,e,t=>t===e):t=>D(t,e)}o(st,"constCheck");function ot(e){return t=>{for(let r=0;r<e.length;r++)if(e[r](t))return!0;return!1}}o(ot,"anyCheck");function sn(e){return t=>{let r=0;for(let n=0;n<e.length;n++)if(e[n](t)&&++r>1)return!1;return r===1}}o(sn,"oneCheck");function on(e){return t=>!e(t)}o(on,"notCheck");function an(e,t,r){return n=>e(n)?t(n):r(n)}o(an,"ifCheck");function fn(e,t,r){return n=>{if(!O(n))return!1;let i=n[e];for(let s=0;s<t.length;s++)if(t[s]===i)return r[s](n);return!1}}o(fn,"taggedCheck");function D(e,t){if(e===t)return!0;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return!1;let r=Array.isArray(e);if(r!==Array.isArray(t))return!1;if(r){let a=e,f=t;if(a.length!==f.length)return!1;for(let u=0;u<a.length;u++)if(!D(a[u],f[u]))return!1;return!0}let n=e,i=t,s=Object.keys(n);if(s.length!==Object.keys(i).length)return!1;for(let a of s)if(!Object.hasOwn(i,a)||!D(n[a],i[a]))return!1;return!0}o(D,"deepEqual");var Q="https://json-schema.invalid/root.json",un=class{static{o(this,"Resolver")}draft;rootBase=Q;baseOf=new Map;dynamicAnchors=new Map;root;options;registry=new Map;rejectUnresolved;unresolved=new Set;resources=new Map;anchors=new Map;indexed=!1;constructor(e,t){this.draft=t.draft==="7"?"7":"2020-12",this.root=e,this.options=t,this.rejectUnresolved=t.unresolvedRefs==="reject"}baseFor(e,t){let r=this.baseOf.get(e);if(r!==void 0)return r;let n=e.$id;return typeof n!="string"?t:!this.indexed&&(this.ensureIndexed(),r=this.baseOf.get(e),r!==void 0)?r:this.draft==="7"&&(typeof e.$ref=="string"||n.startsWith("#"))?t:S($(n,t))}ensureIndexed(){if(!this.indexed){this.indexed=!0;for(let[e,t]of Object.entries(this.options.schemas??{}))this.registry.set(S($(e,Q)),t);this.resources.set(Q,this.root),this.index(this.root,Q)}}resolve(e,t){if(this.ensureIndexed(),!this.rejectUnresolved)return this.find(e,t);try{return this.find(e,t)}catch{return this.unresolved.add($(e,t)),{node:!1,base:t}}}isUnresolved(e,t){return this.unresolved.has($(e,t))}find(e,t){let r=$(e,t),n=S(r),i=r.length>n.length?decodeURIComponent(r.slice(n.length+1)):"",s=this.resources.has(n)?this.resources.get(n):this.load(n);if(s===void 0)throw new Error(`Unresolved $ref ${e} (no schema registered for ${n})`);if(i==="")return{node:s,base:n};if(i.startsWith("/"))return this.pointer(s,n,i);let a=this.anchors.get(`${n}#${i}`);if(a===void 0)throw new Error(`Unresolved $ref ${e} (no anchor ${i} in ${n})`);return{node:a,base:this.baseOf.get(a)??n}}isResource(e,t){return this.ensureIndexed(),this.resources.get(t)===e}index(e,t){if(!p(e)||this.baseOf.has(e))return;let r=t,n=this.draft==="7"&&typeof e.$ref=="string";if(!n&&typeof e.$id=="string")if(this.draft==="7"&&e.$id.startsWith("#"))this.anchors.set(S(r)+e.$id,e);else{let i=$(e.$id,r);r=S(i),this.resources.set(r,e),i.length>r.length+1&&this.anchors.set(i,e)}if(this.baseOf.set(e,r),!n){this.draft!=="7"&&(typeof e.$anchor=="string"&&this.anchors.set(`${r}#${e.$anchor}`,e),typeof e.$dynamicAnchor=="string"&&(this.anchors.set(`${r}#${e.$dynamicAnchor}`,e),this.dynamicAnchors.set(`${r}#${e.$dynamicAnchor}`,e)));for(let i of cn)this.index(e[i],r);for(let i of ln){let s=e[i];if(p(s))for(let a of Object.keys(s))this.index(s[a],r)}for(let i of dn){let s=e[i];if(Array.isArray(s))for(let a of s)this.index(a,r)}}}load(e){let t=this.registry.get(e);if(t!==void 0)return this.resources.set(e,t),this.index(t,e),t}pointer(e,t,r){let n=e,i=t;for(let s of r.split("/").slice(1)){let a=s.replace(/~1/g,"/").replace(/~0/g,"~");if(n=typeof n=="object"&&n!==null&&Object.hasOwn(n,a)?n[a]:void 0,n===void 0)throw new Error(`Unresolved $ref #${r} in ${t}`);typeof n=="object"&&n!==null&&(i=this.baseOf.get(n)??i)}return{node:n,base:i}}},cn=["additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems","additionalItems","contentSchema","items"],ln=["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"],dn=["allOf","anyOf","oneOf","prefixItems","items"];function p(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(p,"isSchemaObject");function $(e,t){try{return new URL(e,t).href}catch{return e.startsWith("#")?S(t)+e:e}}o($,"resolveUri");function S(e){let t=e.indexOf("#");return t<0?e:e.slice(0,t)}o(S,"documentOf");function _(e){let t=ee.get(e)?.deref();if(t!==void 0)return t;let r;try{r=new RegExp(e,"u")}catch{r=new RegExp(e)}return ee.set(e,new WeakRef(r)),hn.register(r,e),r}o(_,"sharedRegex");var ee=new Map,hn=new FinalizationRegistry(e=>{ee.get(e)?.deref()===void 0&&ee.delete(e)}),pn=class{static{o(this,"Coercer")}c;schema;entered=[];cuts=0;memo=void 0;constructor(e,t){this.c=e,this.schema=t}coerce(e){let t=this.c.r.rootBase,r=this.dropOptionalNulls(e,this.schema,t);return this.coerceTypes(this.convertOnly(r),this.schema,t)}convertOnly(e){try{return this.convert(this.schema,this.c.r.rootBase,e)}finally{this.memo=void 0,this.cuts=0}}reenter(e,t,r,n){let i=this.entered;for(let u=0;u<i.length;u+=2)if(i[u]===e&&Object.is(i[u+1],r))return this.cuts++,r;let s=n?this.memo?.get(e):void 0;if(s?.has(r))return s.get(r);let a=this.cuts;i.push(e,r);let f;try{f=this.convert(e,t,r)}finally{i.length-=2}if(n&&this.cuts===a){this.memo??=new Map;let u=this.memo.get(e);u===void 0&&(u=new Map,this.memo.set(e,u)),u.set(r,f)}return f}passes(e,t,r){try{return this.c.check(e,this.baseOf(e,t))(r)}catch{return}}baseOf(e,t){return p(e)?this.c.r.baseFor(e,t):t}dropOptionalNulls(e,t,r){if(!p(t))return e;let n=this.baseOf(t,r);if(Array.isArray(e))return te(e,(l,d)=>{let h=at(t,d);return h===void 0?l:this.dropOptionalNulls(l,h,n)});if(!re(e))return e;let i=p(t.properties)?t.properties:{},s=p(t.patternProperties)?Object.entries(t.patternProperties).map(([l,d])=>[_(l),d]):[],a=p(t.additionalProperties)?t.additionalProperties:void 0;if(s.length===0&&a===void 0&&!p(t.properties))return e;let f=new Set(Array.isArray(t.required)?t.required:[]),u,c=o((l,d)=>{d!==(u??e)[l]&&(u??={...e},u[l]=d)},"set");for(let[l,d]of Object.entries(i)){if(!Object.hasOwn(e,l))continue;let h=p(d)&&typeof d.$ref=="string";if(e[l]===null&&!f.has(l)&&!h&&this.passes(d,n,null)===!1){u??={...e},delete u[l];continue}c(l,this.dropOptionalNulls(e[l],d,n))}if(s.length>0||a!==void 0)for(let l of Object.keys(e)){let d=Object.hasOwn(i,l);for(let[h,m]of s)h.test(l)&&(d=!0,c(l,this.dropOptionalNulls((u??e)[l],m,n)));!d&&a!==void 0&&c(l,this.dropOptionalNulls(e[l],a,n))}return u??e}convert(e,t,r){if(!p(e))return r;let n=this.baseOf(e,t);if(typeof e.$ref=="string"){let i;try{i=this.c.r.resolve(e.$ref,n)}catch{return r}return p(i.node)?this.reenter(i.node,i.base,r,!0):r}return this.convertNode(e,n,r)}convertNode(e,t,r){if(Object.hasOwn(e,"const"))return ft(e.const,r);if(Array.isArray(e.enum))return this.convertEnum(e,e.enum,t,r);if(Array.isArray(e.anyOf))return this.convertUnion(e,e.anyOf,t,r);if(Array.isArray(e.oneOf))return this.convertUnion(e,e.oneOf,t,r);if(Array.isArray(e.allOf)){let n=r;for(let i of e.allOf)n=this.convert(i,t,n);return this.convertMembers(e,t,n)}switch(e.type){case"string":return T(ut(r),r);case"number":return T(he(r),r);case"integer":{let n=he(r);return n===void 0?r:Math.trunc(n.value)}case"boolean":return T(pt(r),r);case"null":return T(yn(r),r);case"bigint":return T(ht(r),r);case"undefined":return T(mn(r),r);case"array":return this.convertArray(e,t,r);case"object":return this.convertObject(e,t,r);case void 0:return e.properties!==void 0||e.patternProperties!==void 0?this.convertObject(e,t,r):e.items!==void 0||e.prefixItems!==void 0?this.convertArray(e,t,r):r;default:return r}}convertEnum(e,t,r,n){if(t.some(i=>i===n))return n;for(let i of t){let s=ft(i,n);if(s!==n&&this.passes(e,r,s)===!0)return s}return n}convertUnion(e,t,r,n){if(t.some(i=>this.passes(i,r,n)===!0))return this.convertMembers(e,r,n);for(let i of t){let s=this.convertMembers(e,r,this.convert(i,r,n));if(this.passes(e,r,s)===!0)return s}return this.convertMembers(e,r,n)}convertMembers(e,t,r){return e.properties!==void 0||e.patternProperties!==void 0||e.additionalProperties!==void 0?this.convertObject(e,t,r):r}convertArray(e,t,r){let n=Array.isArray(e.items)?e.items:Array.isArray(e.prefixItems)?e.prefixItems:void 0;if(n!==void 0){if(!Array.isArray(r))return r;let s=Array.isArray(e.items)?void 0:e.items;return te(r,(a,f)=>{let u=f<n.length?n[f]:s;return u===void 0?a:this.convert(u,t,a)})}if(Array.isArray(r))return e.items===void 0?r:te(r,s=>this.convert(e.items,t,s));let i=e.items;return[p(i)?this.reenter(i,t,r,!1):r]}convertObject(e,t,r){if(!re(r))return r;let n=p(e.properties)?e.properties:{},i=p(e.patternProperties)?Object.entries(e.patternProperties).map(([f,u])=>[_(f),u]):[],s=p(e.additionalProperties)?e.additionalProperties:void 0,a;for(let f of Object.keys(r)){if(r[f]===void 0)continue;let u=r[f],c=Object.hasOwn(n,f);c&&(u=this.convert(n[f],t,u));for(let[l,d]of i)l.test(f)&&(c=!0,u=this.convert(d,t,u));!c&&s!==void 0&&(u=this.convert(s,t,u)),u!==r[f]&&(a??={...r},a[f]=u)}return a??r}coerceTypes(e,t,r){if(!p(t))return e;let n=this.baseOf(t,r),i=e;if(Array.isArray(t.allOf))for(let f of t.allOf)i=this.coerceTypes(i,f,n);Array.isArray(t.anyOf)&&(i=this.coerceUnion(i,t.anyOf,n)),Array.isArray(t.oneOf)&&(i=this.coerceUnion(i,t.oneOf,n));let s=gn(t),a=s.length>1&&s.some(f=>In(i,f));if(s.length>0&&!a)for(let f of s){let u=An(i,f);if(u!==i){i=u;break}}return s.includes("object")&&re(i)&&(i=this.coerceProperties(i,t,n)),s.includes("array")&&Array.isArray(i)&&(i=this.coerceItems(i,t,n)),i}coerceUnion(e,t,r){for(let n of t)if(this.passes(n,r,e)===!0)return e;for(let n of t){let i=this.coerceTypes(e,n,r);if(this.passes(n,r,i)===!0)return i}return e}coerceProperties(e,t,r){let n=p(t.properties)?t.properties:{},i=p(t.patternProperties)?Object.entries(t.patternProperties).map(([u,c])=>[_(u),c]):[],s=p(t.additionalProperties)?t.additionalProperties:void 0,a,f=o((u,c)=>{c!==(a??e)[u]&&(a??={...e},a[u]=c)},"set");for(let[u,c]of Object.entries(n))u in e&&f(u,this.coerceTypes(e[u],c,r));for(let u of Object.keys(e)){let c=Object.hasOwn(n,u);for(let[l,d]of i)l.test(u)&&(c=!0,f(u,this.coerceTypes((a??e)[u],d,r)));!c&&s!==void 0&&f(u,this.coerceTypes(e[u],s,r))}return a??e}coerceItems(e,t,r){return te(e,(n,i)=>{let s=at(t,i);return p(s)?this.coerceTypes(n,s,r):n})}};function at(e,t){return Array.isArray(e.items)?e.items[t]:Array.isArray(e.prefixItems)&&t<e.prefixItems.length?e.prefixItems[t]:e.items}o(at,"itemSchemaAt");function te(e,t){let r;for(let n=0;n<e.length;n++){let i=t(e[n],n);i!==e[n]&&(r??=e.slice(),r[n]=i)}return r??e}o(te,"mapItems");function T(e,t){return e===void 0?t:e.value}o(T,"orValue");function ft(e,t){if(e===t)return t;let r=typeof e=="string"?ut(t):typeof e=="number"?he(t):typeof e=="boolean"?pt(t):typeof e=="bigint"?ht(t):void 0;return r!==void 0&&r.value===e?r.value:t}o(ft,"convertLiteral");function ut(e){if(typeof e=="bigint"||typeof e=="boolean"||v(e))return{value:String(e)};if(e===null)return{value:"null"};if(typeof e=="string")return{value:e};if(e===void 0)return{value:""}}o(ut,"tryString");var ct=BigInt(Number.MAX_SAFE_INTEGER),lt=BigInt(Number.MIN_SAFE_INTEGER);function he(e){if(typeof e=="bigint")return e<=ct&&e>=lt?{value:Number(e)}:void 0;if(typeof e=="boolean")return{value:e?1:0};if(v(e))return{value:e};if(e==null)return{value:0};if(typeof e!="string")return;let t=+e;if(Number.isFinite(t))return{value:t};let r=e.toLowerCase();if(r==="false")return{value:0};if(r==="true")return{value:1};let n=dt(e);return n!==void 0&&n<=ct&&n>=lt?{value:Number(n)}:void 0}o(he,"tryNumber");function dt(e){if(/^-?(0|[1-9]\d*)n$/.test(e))return BigInt(e.slice(0,-1));if(/^-?(0|[1-9]\d*)\.\d+$/.test(e))return BigInt(e.split(".")[0]);if(/^-?(0|[1-9]\d*)$/.test(e))return BigInt(e)}o(dt,"bigIntOfString");function ht(e){if(typeof e=="bigint")return{value:e};if(typeof e=="boolean")return{value:e?1n:0n};if(v(e))return{value:BigInt(Math.trunc(e))};if(e==null)return{value:0n};if(typeof e!="string")return;let t=dt(e);if(t!==void 0)return{value:t};let r=e.toLowerCase();return r==="false"?{value:0n}:r==="true"?{value:1n}:void 0}o(ht,"tryBigInt");function mn(e){if(e==null||e===0n||e===!1||e===0)return{value:void 0};if(typeof e!="string")return;let t=e.toLowerCase();return t==="undefined"||t==="null"||e===""||e==="0"?{value:void 0}:void 0}o(mn,"tryUndefined");function pt(e){if(typeof e=="bigint")return e===0n?{value:!1}:e===1n?{value:!0}:void 0;if(typeof e=="boolean")return{value:e};if(v(e))return e===0?{value:!1}:e===1?{value:!0}:void 0;if(e==null)return{value:!1};if(typeof e!="string")return;let t=e.toLowerCase();if(t==="false"||e==="0")return{value:!1};if(t==="true"||e==="1")return{value:!0}}o(pt,"tryBoolean");function yn(e){if(typeof e=="bigint")return e===0n?{value:null}:void 0;if(typeof e=="boolean")return e===!1?{value:null}:void 0;if(v(e))return e===0?{value:null}:void 0;if(e==null)return{value:null};if(typeof e!="string")return;let t=e.toLowerCase();return t==="undefined"||t==="null"||e===""||e==="0"?{value:null}:void 0}o(yn,"tryNull");function v(e){return typeof e=="number"&&Number.isFinite(e)}o(v,"isFiniteNumber");function gn(e){return typeof e.type=="string"?[e.type]:Array.isArray(e.type)?e.type.filter(t=>typeof t=="string"):[]}o(gn,"typesOf");function In(e,t){switch(t){case"number":return Number.isFinite(e);case"integer":return typeof e=="number"&&Number.isInteger(e);case"boolean":return typeof e=="boolean";case"string":return typeof e=="string";case"null":return e===null;case"bigint":return typeof e=="bigint";case"undefined":return e===void 0;case"array":return Array.isArray(e);case"object":return re(e);default:return!1}}o(In,"matchesType");function An(e,t){switch(t){case"number":case"integer":{if(e===null)return 0;if(typeof e=="string"&&e.trim()!==""){let r=Number(e);if(t==="number"?Number.isFinite(r):Number.isInteger(r))return r}return typeof e=="boolean"?e?1:0:e}case"boolean":return e===null?!1:e==="true"||e===1?!0:e==="false"||e===0?!1:e;case"string":return e===null?"":typeof e=="number"||typeof e=="boolean"?String(e):e;case"null":return e===""||e===0||e===!1?null:e;default:return e}}o(An,"coercePrimitive");function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(re,"isPlainObject");function z(){return{props:null,allProps:!1,items:0,allItems:!1,indexes:null}}o(z,"newAnnotations");function pe(e,t){if(t.props!==null)for(let r of t.props)mt(e,r);if(e.allProps||=t.allProps,t.items>e.items&&(e.items=t.items),e.allItems||=t.allItems,t.indexes!==null)for(let r of t.indexes)yt(e,r)}o(pe,"merge");function mt(e,t){e.props===null&&(e.props=new Set),e.props.add(t)}o(mt,"addProp");function yt(e,t){e.indexes===null&&(e.indexes=new Set),e.indexes.add(t)}o(yt,"addIndex");var bn=o(()=>!0,"ANNOTATING_TRUE"),On=o(()=>!1,"ANNOTATING_FALSE");function kn(e){return(t,r)=>e.check(t,r)}o(kn,"indirectAnnotating");function En(e){return t=>e(t)}o(En,"ignoreAnnotations");function xn(e){return t=>e(t,z())}o(xn,"withFreshAnnotations");function gt(e,t,r){return(n,i)=>{e.push(t);let s=r(n,i);return e.pop(),s}}o(gt,"scopedAnnotating");function wn(e){return(t,r)=>{let n=z();return e(t,n)?(pe(r,n),!0):!1}}o(wn,"isolateAnnotations");function Rn(e,t){return(r,n)=>{if(!e(r))return!1;for(let i=0;i<t.length;i++)if(!t[i](r,n))return!1;return!0}}o(Rn,"annotateAll");function _n(e,t,r){let n=new Set(e.map(([i])=>i));return(i,s)=>{if(!O(i))return!0;let a=[];for(let[f,u]of e)if(Object.hasOwn(i,f)){if(!u(i[f]))return!1;a.push(f)}for(let f of Object.keys(i)){let u=n.has(f);for(let[c,l]of t)if(c.test(f)){if(!l(i[f]))return!1;u=!0,a.push(f)}if(!u&&r!==void 0){if(!r(i[f]))return!1;a.push(f)}}for(let f of a)mt(s,f);return!0}}o(_n,"annotateObject");function Nn(e,t,r,n,i){return(s,a)=>{if(!Array.isArray(s))return!0;let f=Math.min(s.length,e.length);for(let u=0;u<f;u++)if(!e[u](s[u]))return!1;if(t!==void 0){for(let u=e.length;u<s.length;u++)if(!t(s[u]))return!1;a.allItems=!0}if(f>a.items&&(a.items=f),r!==void 0){let u=0;for(let c=0;c<s.length;c++)r(s[c])&&(u++,yt(a,c));if(u<n||u>i)return!1}return!0}}o(Nn,"annotateArray");function It(e,t){return(r,n)=>{let i=0;for(let s of e){let a=z();s(r,a)&&(i++,pe(n,a))}return t?i===1:i>0}}o(It,"annotateAny");function $n(e,t,r){return(n,i)=>{let s=z();return e(n,s)?(pe(i,s),t===void 0||t(n,i)):r===void 0||r(n,i)}}o($n,"annotateIf");function Sn(e,t){return(r,n)=>!O(r)||!Object.hasOwn(r,e)||t(r,n)}o(Sn,"annotateDependent");function Cn(e){return(t,r)=>{if(!O(t)||r.allProps)return!0;for(let n of Object.keys(t))if(!(r.props?.has(n)??!1)&&!e(t[n]))return!1;return r.allProps=!0,!0}}o(Cn,"unevaluatedProperties");function Pn(e){return(t,r)=>{if(!Array.isArray(t)||r.allItems)return!0;for(let n=r.items;n<t.length;n++)if(!(r.indexes?.has(n)??!1)&&!e(t[n]))return!1;return r.allItems=!0,!0}}o(Pn,"unevaluatedItems");var At=Symbol("restart"),bt=class{static{o(this,"Compiler")}r;draft;formats;dynamic;schema;scope;cache=new Map;annotatingCache=new Map;constructor(e,t,r){this.schema=e,this.r=new un(e,t),this.draft=this.r.draft,this.formats=t.formats,this.dynamic=r,this.scope=[]}root(){return this.check(this.schema,this.r.rootBase)}check(e,t){if(e===!0)return C;if(e===!1)return fe;if(!p(e))throw new Error(`A schema must be an object or a boolean, got ${JSON.stringify(e)}`);let r=this.cache.get(e);if(r!==void 0)return r;let n=this.bareType(e);if(n!==void 0)return n;let i={check:void 0};this.cache.set(e,vr(i));let s=this.build(e,this.r.baseFor(e,t));return i.check=s,this.cache.set(e,s),s}build(e,t){if(this.draft==="7"&&typeof e.$ref=="string")return this.ref(e.$ref,t);if(this.draft!=="7"&&(e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0))return xn(this.annotating(e,t));let r=this.plain(e,t);return this.dynamic&&this.r.isResource(e,t)?Xe(this.scope,t,r):r}bareType(e){let t;for(let r in e)if(r==="type")t=e.type;else if(!Ot.has(r))return;return t===void 0?C:typeof t=="string"?K.get(t):void 0}plain(e,t){let r=[],n=e.type===void 0?void 0:Array.isArray(e.type)?e.type:[e.type],i=n?.length===1?n[0]:void 0,s=!1;if(i==="bytes")r.push(Wr(E(e.minLength)??0,E(e.maxLength)??Number.POSITIVE_INFINITY)),s=!0;else{let a=this.stringGroup(e,i==="string");a!==void 0&&r.push(a);let f=i==="number"||i==="integer"||i==="bigint",u=i==="number"?1:i==="integer"?2:i==="bigint"?3:0,c=this.numberGroup(e,u);c!==void 0&&r.push(c);let l=this.objectGroup(e,t,i==="object");l!==void 0&&r.push(l);let d=this.arrayGroup(e,t,i==="array");d!==void 0&&r.push(d),s=i==="string"&&a!==void 0||f&&c!==void 0||i==="object"&&l!==void 0||i==="array"&&d!==void 0}return n!==void 0&&!s&&r.unshift(zr(n)),this.inPlace(e,t,r),X(r)}inPlace(e,t,r){if(Array.isArray(e.enum)&&r.push(de(e.enum)),Object.hasOwn(e,"const")&&r.push(st(e.const)),Array.isArray(e.allOf)&&r.push(X(e.allOf.map(n=>this.check(n,t)))),Array.isArray(e.anyOf)&&r.push(this.union(e.anyOf,t,!1)),Array.isArray(e.oneOf)&&r.push(this.union(e.oneOf,t,!0)),e.not!==void 0&&r.push(on(this.check(e.not,t))),e.if!==void 0&&(e.then!==void 0||e.else!==void 0)){let n=e.then===void 0?C:this.check(e.then,t),i=e.else===void 0?C:this.check(e.else,t);r.push(an(this.check(e.if,t),n,i))}typeof e.$ref=="string"&&r.push(this.ref(e.$ref,t)),this.draft!=="7"&&typeof e.$dynamicRef=="string"&&r.push(this.dynamicRef(e.$dynamicRef,t))}union(e,t,r){let n=o(()=>e.map(i=>this.check(i,t)),"checks");return jn(e,r)??this.tagged(e,t)??(r?sn(n()):Ln(n()))}ref(e,t){let r=this.r.resolve(e,t),n=this.check(r.node,r.base);return this.dynamic&&r.base!==t?Xe(this.scope,r.base,n):n}dynamicRef(e,t){let r=this.bookended(e,t);if(r===void 0)return this.ref(e,t);let{initial:n,name:i}=r,s=this.check(n.node,n.base),a=this.dynamicLookup(i,(u,c)=>this.check(u,c)),f=this.scope;return u=>{for(let c=0;c<f.length;c++){let l=a(f[c]);if(l!==null)return l(u)}return s(u)}}bookended(e,t){let r=this.r.resolve(e,t),n=$(e,t),i=n.slice(S(n).length+1),s=p(r.node)&&r.node.$dynamicAnchor===i;if(!(i===""||i.startsWith("/")||!s)){if(!this.dynamic)throw At;return{initial:r,name:i}}}dynamicLookup(e,t){let r=new Map;return n=>{let i=`${n}#${e}`,s=r.get(i);if(s===void 0){let a=this.r.dynamicAnchors.get(i);s=a===void 0?null:t(a,this.r.baseOf.get(a)??n),r.set(i,s)}return s}}tagged(e,t){if(e.length<2)return;let r=[];for(let i of e){if(!p(i))return;let s=typeof i.$ref=="string"&&Object.keys(i).length===1?i.$ref:void 0,a=s===void 0?i:this.r.resolve(s,this.r.baseFor(i,t)).node;if(!p(a))return;r.push(a)}let n=r[0].properties;if(p(n))for(let i of Object.keys(n)){let s=r.map(a=>Un(a,i));if(!(s.some(a=>a===void 0)||new Set(s).size!==s.length))return fn(i,s,e.map(a=>this.check(a,t)))}}stringGroup(e,t){let r=E(e.minLength)??0,n=E(e.maxLength)??Number.POSITIVE_INFINITY,i=typeof e.pattern=="string"?_(e.pattern):void 0,s=this.formats!==void 0&&typeof e.format=="string"&&Object.hasOwn(this.formats,e.format)?this.formats[e.format]:void 0;if(!(r===0&&n===Number.POSITIVE_INFINITY&&i===void 0&&s===void 0))return Yr(t,r,n,i,s)}numberGroup(e,t){let r=B(e.minimum),n=B(e.maximum),i=B(e.exclusiveMinimum),s=B(e.exclusiveMaximum),a=B(e.multipleOf);if([r,n,i,s,a].every(u=>u===void 0))return;let f=Number.POSITIVE_INFINITY;return Vr(t,r??-f,n??f,i??-f,s??f,a)}objectGroup(e,t,r){let n=Tn.every(l=>e[l]===void 0),i=this.objectCore(e,t,n?r?He:F:J);if(i!==void 0&&n)return i;let s=i===void 0?[]:[i];e.propertyNames!==void 0&&s.push(Xr(this.check(e.propertyNames,t)));let a=E(e.minProperties),f=E(e.maxProperties);(a!==void 0||f!==void 0)&&s.push(Zr(a??0,f??Number.POSITIVE_INFINITY));let u=[],c=[];if(this.draft!=="7"){for(let[l,d]of M(e.dependentRequired))Array.isArray(d)&&u.push([l,d]);for(let[l,d]of M(e.dependentSchemas))c.push([l,this.check(d,t)])}for(let[l,d]of M(e.dependencies))Array.isArray(d)?u.push([l,d]):c.push([l,this.check(d,t)]);return u.length>0&&s.push(Qr(u)),c.length>0&&s.push(en(c)),s.length===0?r?Ge:void 0:qr(X(s),r)}objectCore(e,t,r){let n=p(e.properties)?e.properties:{},i=Array.isArray(e.required)?e.required.filter(m=>typeof m=="string"):[],s=p(e.patternProperties)?e.patternProperties:{},a=e.additionalProperties,f=Object.keys(n),u=Object.keys(s);if(f.length+i.length+u.length===0&&(a===void 0||a===!0))return;let c=[];for(let m of f){let w=this.check(n[m],t),j=Ye(w),ne=(j?.[0]??0)|(i.includes(m)?U:0)|(m in Object.prototype?Je:0);c.push(m,j===void 0?w:j[1],ne)}let l=i.filter(m=>!Object.hasOwn(n,m)),d=u.map(m=>[_(m),this.check(s[m],t)]),h=a===void 0||a===!0?void 0:this.check(a,t);if(d.length===0&&l.length===0&&(h===void 0||a===!1)){let m=f.filter(w=>i.includes(w)).length;return Kr(c,m,a===!1,r)}return Jr(c,f,l,d,h,r)}arrayGroup(e,t,r){let n=[],i;Array.isArray(e.items)?(n=e.items,i=e.additionalItems):(this.draft!=="7"&&Array.isArray(e.prefixItems)&&(n=e.prefixItems),i=e.items);let s=n.map(l=>this.check(l,t)),a=i===void 0||i===!0?void 0:this.check(i,t),f=E(e.minItems),u=E(e.maxItems);if(e.contains===void 0&&e.uniqueItems!==!0&&(s.length>0||a!==void 0))return rt(r?He:F,f??0,u??Number.POSITIVE_INFINITY,s,a);let c=[];if((s.length>0||a!==void 0)&&c.push(rn(s,a)),(f!==void 0||u!==void 0)&&c.push(nn(f??0,u??Number.POSITIVE_INFINITY)),e.contains!==void 0){let l=this.draft==="7"?1:E(e.minContains)??1,d=this.draft==="7"?Number.POSITIVE_INFINITY:E(e.maxContains)??Number.POSITIVE_INFINITY;c.push(nt(this.check(e.contains,t),l,d))}return e.uniqueItems===!0&&c.push(it),c.length===0?r?Be:void 0:Hr(X(c),r)}annotating(e,t){if(e===!0)return bn;if(e===!1)return On;if(!p(e))throw new Error(`A schema must be an object or a boolean, got ${JSON.stringify(e)}`);let r=this.annotatingCache.get(e);if(r!==void 0)return r;let n={check:void 0};this.annotatingCache.set(e,kn(n));let i=this.buildAnnotating(e,this.r.baseFor(e,t));return n.check=i,this.annotatingCache.set(e,i),i}buildAnnotating(e,t){let r={},n=!1;for(let u of Object.keys(e))Mn.has(u)?n=!0:r[u]=e[u];let i=this.plain(r,t),s=[];n&&this.annotatingParts(e,t,s);let a=s.length===0?En(i):Rn(i,s),f=e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0?wn(a):a;return this.dynamic&&this.r.isResource(e,t)?gt(this.scope,t,f):f}annotatingParts(e,t,r){if(e.properties!==void 0||e.patternProperties!==void 0||e.additionalProperties!==void 0){let n=M(e.properties).map(([a,f])=>[a,this.check(f,t)]),i=M(e.patternProperties).map(([a,f])=>[_(a),this.check(f,t)]),s=e.additionalProperties===void 0?void 0:this.check(e.additionalProperties,t);r.push(_n(n,i,s))}if(e.prefixItems!==void 0||e.items!==void 0||e.contains!==void 0){let n=Array.isArray(e.prefixItems)?e.prefixItems:Array.isArray(e.items)?e.items:[],i=Array.isArray(e.items)?e.additionalItems:e.items;r.push(Nn(n.map(s=>this.check(s,t)),i===void 0?void 0:this.check(i,t),e.contains===void 0?void 0:this.check(e.contains,t),E(e.minContains)??1,E(e.maxContains)??Number.POSITIVE_INFINITY))}if(Array.isArray(e.allOf))for(let n of e.allOf)r.push(this.annotating(n,t));if(Array.isArray(e.anyOf)&&r.push(It(e.anyOf.map(n=>this.annotating(n,t)),!1)),Array.isArray(e.oneOf)&&r.push(It(e.oneOf.map(n=>this.annotating(n,t)),!0)),e.if!==void 0){let n=e.then===void 0?void 0:this.annotating(e.then,t),i=e.else===void 0?void 0:this.annotating(e.else,t);r.push($n(this.annotating(e.if,t),n,i))}typeof e.$ref=="string"&&r.push(this.annotatingRef(e.$ref,t)),typeof e.$dynamicRef=="string"&&r.push(this.annotatingDynamicRef(e.$dynamicRef,t));for(let[n,i]of M(e.dependentSchemas))r.push(Sn(n,this.annotating(i,t)));e.unevaluatedProperties!==void 0&&r.push(Cn(this.check(e.unevaluatedProperties,t))),e.unevaluatedItems!==void 0&&r.push(Pn(this.check(e.unevaluatedItems,t)))}annotatingRef(e,t){let r=this.r.resolve(e,t),n=this.annotating(r.node,r.base);return this.dynamic&&r.base!==t?gt(this.scope,r.base,n):n}annotatingDynamicRef(e,t){let r=this.bookended(e,t);if(r===void 0)return this.annotatingRef(e,t);let{initial:n,name:i}=r,s=this.annotating(n.node,n.base),a=this.dynamicLookup(i,(u,c)=>this.annotating(u,c)),f=this.scope;return(u,c)=>{for(let l=0;l<f.length;l++){let d=a(f[l]);if(d!==null)return d(u,c)}return s(u,c)}}},Ot=new Set(["$schema","$comment","title","description","default","examples","deprecated","readOnly","writeOnly","$defs","definitions","contentEncoding","contentMediaType","minContains","maxContains","$vocabulary"]),Tn=["propertyNames","minProperties","maxProperties","dependentRequired","dependentSchemas","dependencies"],Mn=new Set(["properties","patternProperties","additionalProperties","prefixItems","items","additionalItems","contains","minContains","maxContains","allOf","anyOf","oneOf","if","then","else","$ref","$dynamicRef","dependentSchemas","unevaluatedProperties","unevaluatedItems"]);function jn(e,t){let r=[];for(let n of e){if(!p(n)||!Object.hasOwn(n,"const"))return;for(let i of Object.keys(n))if(i!=="const"&&!Ot.has(i))return;if(typeof n.const=="object"&&n.const!==null||t&&r.includes(n.const))return;r.push(n.const)}return de(r)}o(jn,"constUnion");function Ln(e){let t=[],r=[];for(let n of e){let i=Fn.get(n);i===void 0?r.push(n):t.push(i)}return t.length===0?ot(r):Gr(Ze(t),r)}o(Ln,"anyOf");var Fn=new Map([...K].map(([e,t])=>[t,e]));function Un(e,t){let r=e.properties;if(e.type!=="object"||!Array.isArray(e.required)||!e.required.includes(t))return;let n=p(r)?r[t]:void 0;if(!(!p(n)||!Object.hasOwn(n,"const")))return typeof n.const=="object"&&n.const!==null?void 0:n.const}o(Un,"tagOf");function B(e){return typeof e=="number"||typeof e=="bigint"?e:void 0}o(B,"bound");function E(e){return typeof e=="number"?e:void 0}o(E,"number");function M(e){return p(e)?Object.entries(e):[]}o(M,"entries");var Dn=class{static{o(this,"Explainer")}c;schema;memo=void 0;constructor(e,t){this.c=e,this.schema=t,e.root()}errors(e){let t=[];try{this.walk(this.schema,this.c.r.rootBase,e,"",t)}finally{this.memo=void 0}return t.length===0&&t.push({path:"",keyword:"schema",message:"invalid"}),t}ok(e,t,r){return this.c.check(e,t)(r)}walk(e,t,r,n,i){if(e===!0)return;if(e===!1){i.push({path:n,keyword:"false",message:"no value is allowed here"});return}if(!p(e))return;let s=this.c.r.baseFor(e,t);if(this.ok(e,s,r))return;let a=i.length,f=o((u,c,l=n)=>{i.push({path:l,keyword:u,message:c})},"push");if(this.c.draft==="7"&&typeof e.$ref=="string"){this.walkRef(e.$ref,s,r,n,i);return}if(e.type!==void 0){let u=Array.isArray(e.type)?e.type:[e.type];if(!u.map(c=>(typeof c=="string"?K.get(c):void 0)??fe).some(c=>c(r))){f("type",`expected ${u.join(" or ")}, got ${zn(r)}`);return}}if(Array.isArray(e.enum)&&!de(e.enum)(r)&&f("enum",`expected one of ${kt(e.enum)}`),Object.hasOwn(e,"const")&&!st(e.const)(r)&&f("const",`expected ${JSON.stringify(e.const)}`),typeof r=="string"&&e.type!=="bytes"&&this.walkString(e,r,f),r instanceof Uint8Array&&e.type==="bytes"&&this.walkBytes(e,r,f),(typeof r=="number"||typeof r=="bigint")&&this.walkNumber(e,r,f),O(r)&&this.walkObject(e,s,r,n,i,f),Array.isArray(r)&&this.walkArray(e,s,r,n,i,f),Array.isArray(e.allOf))for(let u of e.allOf)this.walk(u,s,r,n,i);if(Array.isArray(e.anyOf)&&this.walkUnion(e.anyOf,s,r,n,i,!1),Array.isArray(e.oneOf)&&this.walkUnion(e.oneOf,s,r,n,i,!0),e.not!==void 0&&this.ok(e.not,s,r)&&f("not","must not match the schema in not"),e.if!==void 0){let u=this.ok(e.if,s,r)?e.then:e.else;u!==void 0&&this.walk(u,s,r,n,i)}typeof e.$ref=="string"&&this.walkRef(e.$ref,s,r,n,i),i.length===a&&(e.unevaluatedProperties!==void 0||e.unevaluatedItems!==void 0)&&this.walkUnevaluated(e,s,r,n,i),i.length===a&&typeof e.$dynamicRef=="string"&&f("$dynamicRef","does not match the dynamically referenced schema")}walkRef(e,t,r,n,i){let s=this.c.r.resolve(e,t);if(s.node===!1&&this.c.r.isUnresolved(e,t)){i.push({path:n,keyword:"$ref",message:`unresolved reference ${e}`});return}if(!p(s.node)||typeof r!="object"||r===null){this.walk(s.node,s.base,r,n,i);return}this.memo??=new Map;let a=this.memo.get(s.node),f=a?.get(r);if(f!==void 0&&f.path===n){i.push(...f.errors);return}let u=[];this.walk(s.node,s.base,r,n,u),a===void 0&&(a=new Map,this.memo.set(s.node,a)),a.set(r,{path:n,errors:u}),i.push(...u)}walkString(e,t,r){let n=le(t);typeof e.minLength=="number"&&n<e.minLength&&r("minLength",`expected at least ${e.minLength} characters`),typeof e.maxLength=="number"&&n>e.maxLength&&r("maxLength",`expected at most ${e.maxLength} characters`),typeof e.pattern=="string"&&!_(e.pattern).test(t)&&r("pattern",`expected to match ${e.pattern}`);let i=this.c.formats,s=i!==void 0&&typeof e.format=="string"&&Object.hasOwn(i,e.format)?i[e.format]:void 0;s!==void 0&&!s(t)&&r("format",`expected format ${e.format}`)}walkBytes(e,t,r){typeof e.minLength=="number"&&t.length<e.minLength&&r("minLength",`expected at least ${e.minLength} bytes`),typeof e.maxLength=="number"&&t.length>e.maxLength&&r("maxLength",`expected at most ${e.maxLength} bytes`)}walkNumber(e,t,r){let{minimum:n,maximum:i,exclusiveMinimum:s,exclusiveMaximum:a,multipleOf:f}=e;G(n)&&t<n&&r("minimum",`expected >= ${n}`),G(i)&&t>i&&r("maximum",`expected <= ${i}`),G(s)&&t<=s&&r("exclusiveMinimum",`expected > ${s}`),G(a)&&t>=a&&r("exclusiveMaximum",`expected < ${a}`),G(f)&&!et(t,f)&&r("multipleOf",`expected a multiple of ${f}`)}walkObject(e,t,r,n,i,s){let a=p(e.properties)?e.properties:{},f=Array.isArray(e.required)?e.required:[];for(let d of f){if(typeof d!="string")continue;let h=r[d]===void 0&&Object.hasOwn(a,d)&&this.ok(a[d],t,void 0);(!Object.hasOwn(r,d)||r[d]===void 0&&!h)&&s("required","missing",R(n,d))}for(let d of Object.keys(a))Object.hasOwn(r,d)&&r[d]!==void 0&&this.walk(a[d],t,r[d],R(n,d),i);let u=p(e.patternProperties)?Object.entries(e.patternProperties):[];for(let d of Object.keys(r)){let h=Object.hasOwn(a,d);for(let[m,w]of u)_(m).test(d)&&(h=!0,this.walk(w,t,r[d],R(n,d),i));!h&&e.additionalProperties!==void 0&&(e.additionalProperties===!1?s("additionalProperties","unknown field",R(n,d)):this.walk(e.additionalProperties,t,r[d],R(n,d),i)),e.propertyNames!==void 0&&!this.ok(e.propertyNames,t,d)&&s("propertyNames","invalid property name",R(n,d))}let c=Object.keys(r).length;typeof e.minProperties=="number"&&c<e.minProperties&&s("minProperties",`expected at least ${e.minProperties} properties`),typeof e.maxProperties=="number"&&c>e.maxProperties&&s("maxProperties",`expected at most ${e.maxProperties} properties`);let l={...this.c.draft==="7"||!p(e.dependentRequired)?{}:e.dependentRequired,...p(e.dependencies)?e.dependencies:{}};for(let[d,h]of Object.entries(l))if(Object.hasOwn(r,d))if(!Array.isArray(h))this.walk(h,t,r,n,i);else for(let m of h)Object.hasOwn(r,m)||s("dependentRequired",`required when ${d} is present`,R(n,m));if(this.c.draft!=="7"&&p(e.dependentSchemas))for(let[d,h]of Object.entries(e.dependentSchemas))Object.hasOwn(r,d)&&this.walk(h,t,r,n,i)}walkArray(e,t,r,n,i,s){let a=[],f;Array.isArray(e.items)?(a=e.items,f=e.additionalItems):(this.c.draft!=="7"&&Array.isArray(e.prefixItems)&&(a=e.prefixItems),f=e.items);for(let u=0;u<r.length;u++){let c=u<a.length?a[u]:f;c!==void 0&&this.walk(c,t,r[u],`${n}/${u}`,i)}if(typeof e.minItems=="number"&&r.length<e.minItems&&s("minItems",`expected at least ${e.minItems} items`),typeof e.maxItems=="number"&&r.length>e.maxItems&&s("maxItems",`expected at most ${e.maxItems} items`),e.uniqueItems===!0&&!it(r)&&s("uniqueItems","expected unique items"),e.contains!==void 0){let u=this.c.draft==="7",c=u||typeof e.minContains!="number"?1:e.minContains,l=u||typeof e.maxContains!="number"?Number.POSITIVE_INFINITY:e.maxContains;nt(this.c.check(e.contains,t),c,l)(r)||s("contains",vn(c,l))}}walkUnion(e,t,r,n,i,s){let a=e.filter(l=>this.ok(l,t,r)).length;if(a===1||!s&&a>0)return;let f=s?"oneOf":"anyOf";if(a>1){i.push({path:n,keyword:f,message:"matches more than one alternative"});return}let u=this.tagOf(e,t);if(u!==void 0&&O(r)){let l=u.values.indexOf(r[u.key]);l<0?i.push({path:R(n,u.key),keyword:f,message:`expected one of ${kt(u.values)}`}):this.walk(e[l],t,r,n,i);return}let c;for(let l of e){let d=[];if(this.walk(l,t,r,n,d),d.length===0)continue;let h=O(r)?this.declaredKeys(l,t,r):0;(c===void 0||h>c.declared||h===c.declared&&d[0].path.length>c.errors[0].path.length)&&(c={errors:d,declared:h})}i.push(...c?.errors??[{path:n,keyword:f,message:"matches no alternative"}])}declaredKeys(e,t,r){let n=p(e)&&typeof e.$ref=="string"?this.c.r.resolve(e.$ref,this.c.r.baseFor(e,t)).node:e,i=p(n)&&p(n.properties)?n.properties:{};return Object.keys(r).filter(s=>Object.hasOwn(i,s)).length}tagOf(e,t){let r=e.map(i=>p(i)&&typeof i.$ref=="string"?this.c.r.resolve(i.$ref,this.c.r.baseFor(i,t)).node:i),n=r[0];if(!(!p(n)||!p(n.properties)))for(let i of Object.keys(n.properties)){let s=r.map(a=>{let f=p(a)&&p(a.properties)?a.properties[i]:void 0;return p(f)?f.const:void 0});if(s.every(a=>a!==void 0&&(typeof a!="object"||a===null))&&new Set(s).size===s.length)return{key:i,values:s}}}walkUnevaluated(e,t,r,n,i){let{unevaluatedProperties:s,unevaluatedItems:a,$id:f,...u}=e,c=z();if(this.c.annotating(u,t)(r,c),O(r)&&s!==void 0&&!c.allProps)for(let l of Object.keys(r))c.props?.has(l)||(s===!1?i.push({path:R(n,l),keyword:"unevaluatedProperties",message:"unknown field"}):this.walk(s,t,r[l],R(n,l),i));if(Array.isArray(r)&&a!==void 0&&!c.allItems)for(let l=c.items;l<r.length;l++)c.indexes?.has(l)||(a===!1?i.push({path:`${n}/${l}`,keyword:"unevaluatedItems",message:"unexpected item"}):this.walk(a,t,r[l],`${n}/${l}`,i))}},me=20;function kt(e){return e.length<=me?JSON.stringify(e):`${JSON.stringify(e.slice(0,me)).slice(0,-1)}, ... and ${e.length-me} more]`}o(kt,"listValues");function vn(e,t){return t===Number.POSITIVE_INFINITY?`expected at least ${e} matching ${e===1?"item":"items"}`:e===0?`expected at most ${t} matching ${t===1?"item":"items"}`:`expected between ${e} and ${t} matching items`}o(vn,"containsMessage");function G(e){return typeof e=="number"||typeof e=="bigint"}o(G,"isBound");function R(e,t){return`${e}/${String(t).replace(/~/g,"~0").replace(/\//g,"~1")}`}o(R,"pointer");function zn(e){return e===null?"null":Array.isArray(e)?"array":e instanceof Uint8Array?"bytes":typeof e=="bigint"?"bigint":typeof e=="number"&&Number.isInteger(e)?"integer":typeof e=="number"&&!Number.isFinite(e)?String(e):typeof e}o(zn,"typeName");function Bn(e,t=Gn){let r=Yn(e,t);return t.coerce===!0?new Wn(e,t,r):new Et(e,t,r)}o(Bn,"compile");var Gn=Object.freeze({}),Et=class{static{o(this,"Validator")}check;schema;options;explainer=void 0;constructor(e,t,r){this.check=r,this.schema=e,this.options=t}errors(e){return this.check(e)?[]:(this.explainer??=new Dn(ye(this.schema,this.options),this.schema),this.explainer.errors(e))}validate(e){return this.check(e)?{ok:!0,value:e}:{ok:!1,errors:this.errors(e)}}},Wn=class extends Et{static{o(this,"CoercingValidator")}coercer=void 0;coerce(e){return this.coercer??=new pn(ye(this.schema,this.options),this.schema),this.coercer.coerce(e)}parse(e){return this.validate(this.coerce(e))}};function Yn(e,t){return ye(e,t).root()}o(Yn,"compileCheck");function ye(e,t){let r=new bt(e,t,!1);try{return r.root(),r}catch(n){if(n!==At)throw n;return new bt(e,t,!0)}}o(ye,"compiler");var Vn=[0,31,28,31,30,31,30,31,31,30,31,30,31],qn=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function Hn(e){return e%4===0&&(e%100!==0||e%400===0)}o(Hn,"IsLeapYear");function xt(e){let t=qn.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&Hn(r)?29:Vn[n])}o(xt,"IsDate");var Kn=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function wt(e,t=!0){let r=Kn.exec(e);if(!r||t&&!r[4]&&!r[5])return!1;let n=+r[1],i=+r[2],s=+r[3];if(n>23||i>59||s>60)return!1;if(r[5]){let c=+r[6],l=+r[7];if(c>23||l>59)return!1}if(s<60)return!0;let a=r[5]==="-"?-1:1,f=+(r[6]||0),u=+(r[7]||0);return((n*60+i-a*(f*60+u))%1440+1440)%1440===1439}o(wt,"IsTime");function Jn(e){let t=e.split(/T/i);return t.length===2&&xt(t[0])&&wt(t[1])}o(Jn,"IsDateTime");var Xn=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Zn(e){return Xn.test(e)}o(Zn,"IsDuration");var Qn=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function ei(e){return Qn.test(e)}o(ei,"IsEmail");var ti=/^(?!-).*(?<!-)$/,ri=/^(?!..--)/,ni=/^[a-zA-Z0-9-]*$/,Ns=new RegExp("^\\p{ASCII}*$","u"),ge=/[^\p{ASCII}]/u,ii=/[0-9]/,si=/[\u{0660}-\u{0669}]/u,oi=/[\u{06f0}-\u{06f9}]/u,ai=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,fi=/[\u{002d}\u{002b}]/u,Rt=new RegExp("\\p{Mn}","u"),ui=new RegExp("\\p{Mc}","u"),$s=new RegExp("\\p{Me}","u"),ci=/[\p{Mn}\p{Mc}\p{Me}]/u,_t=new RegExp("\\p{L}","u"),li=new RegExp("\\p{Nd}","u"),di=new RegExp("\\p{Script=Greek}","u"),Nt=new RegExp("\\p{Script=Hebrew}","u"),hi=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,pi=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,$t=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,mi=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,yi=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,gi=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,Ii=new RegExp([ii,oi].map(e=>e.source).join("|"),"u"),Ai=new RegExp([_t,fi,ai,li,Rt,ui,yi,gi].map(e=>e.source).join("|"),"u");function bi(e){return ti.test(e)&&ri.test(e)&&ni.test(e)}o(bi,"IsAsciiLabel");var x=36,W=1,Y=26,Oi=38,ki=700,St=72,Ct=128;function Ie(){throw null}o(Ie,"ThrowDontCare");function Pt(e){return e.toLowerCase().startsWith("xn--")}o(Pt,"IsAcePrefixed");function Tt(e,t,r){e=r?Math.floor(e/ki):e>>1,e+=Math.floor(e/t);let n=0;for(;e>(x-W)*Y>>1;)e=Math.floor(e/(x-W)),n+=x;return n+Math.floor((x-W+1)*e/(e+Oi))}o(Tt,"Adapt");function Mt(e){let t=[],r=Ct,n=0,i=St,s=e.lastIndexOf("-");if(s>0)for(let f=0;f<s;f++){let u=e.charCodeAt(f);u>=128&&Ie(),t.push(u)}let a=s<0?0:s+1;for(;a<e.length;){let f=n,u=1,c=x;for(;;){a>=e.length&&Ie();let d=e.charCodeAt(a++),h;d>=97&&d<=122?h=d-97:d>=48&&d<=57?h=d-48+26:Ie(),n+=h*u;let m=c<=i?W:c>=i+Y?Y:c-i;if(h<m)break;u*=x-m,c+=x}let l=t.length+1;i=Tt(n-f,l,f===0),r+=Math.floor(n/l),n%=l,t.splice(n,0,r),n++}return String.fromCodePoint(...t)}o(Mt,"Decode");function jt(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}o(jt,"DigitToChar");var Ei=new RegExp(ge.source,"gu");function xi(e){let t=e.replace(Ei,""),r=t.length,n=r>0?[t,"-"]:[],i=Array.from(e,c=>c.codePointAt(0)),s=Ct,a=0,f=St,u=r;for(;u<i.length;){let c=1/0;for(let l of i)l>=s&&l<c&&(c=l);a+=(c-s)*(u+1),s=c;for(let l of i)if(l<s&&a++,l===s){let d=a;for(let h=x;;h+=x){let m=h<=f?W:h>=f+Y?Y:h-f;if(d<m)break;let w=m+(d-m)%(x-m);n.push(jt(w)),d=Math.floor((d-m)/(x-m))}n.push(jt(d)),f=Tt(a,u+1,u===r),a=0,u++}a++,s++}return n.join("")}o(xi,"Encode");var wi=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,Lt=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,Ri=/^(?:R|AL|AN)$/;function _i(e){if(Pt(e))try{return Ae(Mt(e.slice(4).toLowerCase()))}catch{return!1}return Ae(e)}o(_i,"HasBidiChars");function Ft(e){let t=String.fromCodePoint(e);return Ii.test(t)?"EN":si.test(t)?"AN":Rt.test(t)?"NSM":Nt.test(t)?"R":pi.test(t)?"AL":_t.test(t)?"L":"ON"}o(Ft,"GetBidiClass");function Ae(e){for(let t of e)if(Ri.test(Ft(t.codePointAt(0))))return!0;return!1}o(Ae,"HasRightToLeftCharacters");function Ut(e){let t=!1,r=Lt,n=!1,i=!1,s=!0;for(let a of e){let f=Ft(a.codePointAt(0));if(s){if(f!=="L"&&f!=="R"&&f!=="AL")return!1;t=f==="R"||f==="AL",r=t?wi:Lt,s=!1}if(!r.test(f))return!1;f==="EN"?n=!0:f==="AN"&&(i=!0)}return!(t&&n&&i)}o(Ut,"SatisfiesBidiRule");function Ni(e){return ge.test(e)&&xi(e).length+4>63}o(Ni,"ExceedsMaxALabelLength");function $i(e){return e[0]==="-"||e[e.length-1]==="-"?!0:e.slice(2).join("").startsWith("--")}o($i,"HasInvalidHyphens");function Dt(e){if(Ni(e)||Ae(e)&&!Ut(e))return!1;let t=[...e],r=t.map(s=>s.codePointAt(0)),n=r.length;if($i(t)||ci.test(t[0]))return!1;let i=!1;for(let s=0;s<n;s++){let a=r[s],f=t[s];if(mi.test(f)||!Ai.test(f))return!1;hi.test(f)&&(i=!0);let u=r[s-1],c=r[s+1];switch(a){case 183:if(u!==108||c!==108)return!1;break;case 885:if(!c||!di.test(t[s+1]))return!1;break;case 1523:case 1524:if(!u||!Nt.test(t[s-1]))return!1;break;case 8204:if(!u||u<128&&!$t.test(t[s-1]))return!1;break;case 8205:if(!u||!$t.test(t[s-1]))return!1;break;case 12539:break}}return!(e.includes("\u30FB")&&!i)}o(Dt,"IsUnicodeLabel");function vt(e){if(!Pt(e))return!1;try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf("-")===0)return!1;let r=Mt(t);return ge.test(r)?Dt(r):!1}catch{return!1}}o(vt,"IsPunyLabel");function Si(e){return e.length>0&&e.length<=63}o(Si,"IsValidLabelLength");function Ci(e){return Si(e)&&(vt(e)||bi(e))}o(Ci,"IsLabel");function Pi(e){return e.length===0||e.length>253||e.charCodeAt(e.length-1)===46?!1:e.split(".").every(t=>Ci(t))}o(Pi,"IsHostname");function Ti(e){return e.length>0&&e.length<=63}o(Ti,"IsValidLabelLength2");function Mi(e){return Ti(e)&&(vt(e)||Dt(e))}o(Mi,"IsLabel2");function ji(e){return e.replace(/[\uff01-\uff5e]/g,t=>String.fromCharCode(t.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}o(ji,"NormalizeHostname");function Li(e){if(e.length===0||e.includes(" "))return!1;let t=ji(e);if(t.length>253)return!1;let r=t.split("."),n=r.some(i=>_i(i));return r.every(i=>Mi(i)&&(!n||Ut(i)))}o(Li,"IsIdnHostname");function Fi(e){return Pi(e)}o(Fi,"IsHostname2");var Ui=/^(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function Di(e){return Ui.test(e.normalize("NFC"))}o(Di,"IsIdnEmail");function vi(e){return Li(e)}o(vi,"IsIdnHostname2");var zi=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Bi(e){return zi.test(e)}o(Bi,"IsIPv4");var Gi=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function Wi(e){return Gi.test(e)}o(Wi,"IsIPv6");var Yi=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,Vi=/[\x00-\x20<>^`{|}\\]/,qi=/%(?![0-9a-fA-F]{2})/;function Hi(e){return e.length<2048?e.replace(Yi,"[::1]"):e}o(Hi,"NarrowIpvFuture");function Ki(e){return Vi.test(e)||qi.test(e)?!1:URL.canParse(Hi(e))}o(Ki,"IsIri");var Ji=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,Xi=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Zi(e){return!Ji.test(e)&&!Xi.test(e)&&URL.canParse(e,"http://example.com")}o(Zi,"IsIriReference");var Qi=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function es(e){return Qi.test(e)}o(es,"IsJsonPointer");var ts=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function rs(e){return ts.test(e)}o(rs,"IsJsonPointerUriFragment");function ns(e){try{return new RegExp(e,"u"),!0}catch{return!1}}o(ns,"IsRegex");var is=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function ss(e){return is.test(e)}o(ss,"IsRelativeJsonPointer");var os=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function as(e){return os.test(e)}o(as,"IsUri");var fs=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function us(e){return fs.test(e)}o(us,"IsUriReference");var cs=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function ls(e){return cs.test(e)}o(ls,"IsUriTemplate");function ds(e){return URL.canParse(e)}o(ds,"IsUrl");var hs=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function ps(e){return hs.test(e)}o(ps,"IsUuid");var ms=Object.freeze({date:xt,"date-time":Jn,duration:Zn,email:ei,hostname:Fi,"idn-email":Di,"idn-hostname":vi,ipv4:Bi,ipv6:Wi,iri:Ki,"iri-reference":Zi,"json-pointer":es,"json-pointer-uri-fragment":rs,regex:ns,"relative-json-pointer":ss,time:wt,uri:as,"uri-reference":us,"uri-template":ls,url:ds,uuid:ps}),zt=new WeakMap;function ys(e){let t=zt.get(e);if(t)return t;let r=Bn(e,{formats:ms,coerce:!0,unresolvedRefs:"reject"});return zt.set(e,r),r}o(ys,"getValidator");function gs(e){return e===""?"root":e.slice(1).split("/").map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")}o(gs,"formatValidationPath");function Is(e,t){let r=e.find(n=>n.name===t.name);if(!r)throw new Error(`Tool "${t.name}" not found`);return Bt(r,t)}o(Is,"validateToolCall");function Bt(e,t){if(t.argumentsError)throw new Error(`Invalid arguments for tool "${t.name}": ${t.argumentsError}`);let r=ys(e.parameters).parse(structuredClone(t.arguments));if(r.ok)return r.value;let n=r.errors.map(s=>` - ${gs(s.path)}: ${s.message}`).join(`
10
+ `),i=`Validation failed for tool "${t.name}":
11
+ ${n}
12
+
13
+ Received arguments:
14
+ ${JSON.stringify(t.arguments,null,2)}`;throw new Error(i)}o(Bt,"validateToolArguments");export{ke as CACHE_WARMING_IDLE_CONTINUATION_PROBABILITY,er as CACHE_WARMING_MAX_AGE_MS,tr as CACHE_WARMING_MAX_IDLE_AGE_MS,Oe as CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS,Mr as arr,Sr as bool,Me as createFauxCore,Zt as envApiKeyAuth,or as evaluateCacheWarming,hr as fauxAssistantMessage,Ar as fauxProvider,_e as fauxText,cr as fauxThinking,lr as fauxToolCall,rr as getCacheWarmingDelayMs,sr as getCacheWarmingRequestOptions,Rr as getOverflowPatterns,nr as getPromptCacheTtlMs,$r as int,ir as isCacheWarmingReplayable,kr as isContextOverflow,wr as isRecoverableLength,Qt as lazyOAuth,Cr as nul,Nr as num,Lr as obj,Pr as oneOf,jr as opt,_r as str,Tr as union,Bt as validateToolArguments,Is as validateToolCall};
@@ -0,0 +1 @@
1
+ var b=Object.defineProperty;var n=(e,r)=>b(e,"name",{value:r,configurable:!0});import{createRequire as y}from"node:module";const D=y(import.meta.url);function d(e){return new RegExp(e.join("|"),"i")}n(d,"buildProviderErrorPattern");var c=d(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","^\\s*(?:error:?\\s*)?402\\b","\\b(?:status|http|code)\\W{0,3}402\\b","payment.?required","insufficient.?(?:balance|credits?|funds)","credit balance is too low","exceeded your current quota","quota.?exhausted","\u4F59\u989D\u4E0D\u8DB3","subscription_sharing_usage_limit_exceeded","subscription_sharing_workplace_individual_usage_limit_exceeded",'"code"\\s*:\\s*"?1308(?![0-9])']),h=d(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])","service.?(?:is.?)?(?:temporarily.?)?unavailable","server.?error","internal.?error","empty response","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","unable to forward upstream","upstream.?request.?failed","upstream_stream_read_error","stream was interrupted","http/?2 stream failed","network.?error","connection.?error","connection.?refused","connection.?lost","connection.?reset","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENETUNREACH","EHOSTUNREACH","premature close","other side closed","fetch failed","request to \\S+ failed, reason:","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","stream disconnected before completion","cut short after the reply had begun","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),R=6e4;function p(e,r){let a=e.baseDelayMs*2**Math.max(0,r-1),t=Number.isSafeInteger(a)?a:Number.MAX_SAFE_INTEGER;return Math.min(t,e.maxAgentDelayMs??R)}n(p,"retryDelayMs");var E=class extends Error{static{n(this,"RetrySleepAbortError")}constructor(){super("Aborted")}};function g(e,r){return new Promise((a,t)=>{if(r?.aborted){t(new E);return}let u=setTimeout(a,e);r?.addEventListener("abort",()=>{clearTimeout(u),t(new E)},{once:!0})})}n(g,"sleep");async function A(e,r,a,t){let u=r?.enabled?r.maxRetries:0,i=0,o;for(;;){let s=await e();if(s.stopReason==="aborted")return o&&await t?.onRetryFinished?.(!1,o.attempt),s;if(s.stopReason!=="error")return o&&await t?.onRetryFinished?.(!0,o.attempt),s;if(i>=u||!f(s))return o&&await t?.onRetryFinished?.(!1,o.attempt,s.errorMessage),s;i++,o={attempt:i,errorMessage:s.errorMessage||"Unknown error"};let l=p(r,i);await t?.onRetryScheduled?.(i,u,l,o.errorMessage);try{await g(l,a)}catch(m){if(await t?.onRetryFinished?.(!1,i,o.errorMessage),m instanceof E){let{errorMessage:T,..._}=s;return{..._,stopReason:"aborted"}}throw m}await t?.onRetryAttemptStart?.()}}n(A,"retryAssistantCall");function f(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let r=e.errorMessage;return c.test(r)?!1:h.test(r)}n(f,"isRetryableAssistantError");var N=d(["network.?error","connection.?error","connection.?refused","connection.?lost","connection.?reset","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENETUNREACH","EHOSTUNREACH","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","premature close","websocket.?closed","websocket.?error","ended without","stream ended before"]);function w(e){return e.stopReason!=="error"||!e.errorMessage||c.test(e.errorMessage)?!1:N.test(e.errorMessage)}n(w,"isNetworkAssistantError");function M(e){return e.stopReason!=="error"||!e.errorMessage?!1:c.test(e.errorMessage)}n(M,"isAccountLimitAssistantError");export{R as DEFAULT_MAX_AGENT_RETRY_DELAY_MS,M as isAccountLimitAssistantError,w as isNetworkAssistantError,f as isRetryableAssistantError,A as retryAssistantCall,p as retryDelayMs};
@@ -1 +1 @@
1
- var R=Object.defineProperty;var o=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createRequire as b}from"node:module";const S=b(import.meta.url);import{retryProviderRequest as w}from"./chunk-ML5DIOWR.js";import{headersToRecord as q,providerHeadersToRecord as k}from"./chunk-UTB4DTYQ.js";import{calculateCost as x}from"./chunk-BIY5HTFI.js";import{getIdentityHeaders as E}from"./chunk-F37JXTCY.js";function $(e,r,a){let i=new Error(`${e} returned ${r.status}`);return i.status=r.status,i.headers=r.headers,i.body=a,i}o($,"httpError");function T(e){let r=new Error(`Request timed out after ${e}ms`);return r.name="TimeoutError",r.status=void 0,r.headers=void 0,r.body="",r}o(T,"timeoutError");function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(m,"isRecord");function _(e,r,a){if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${e} returned an invalid ${a}`);return r}o(_,"requiredNumber");function j(e,r,a,i){return k(E(e,i),{authorization:`Bearer ${r}`,"content-type":"application/json"},e.headers,a)??{}}o(j,"requestHeaders");async function A(e,r,a,i,t,y){if(!t?.apiKey)throw new Error(`No API key for provider: ${a.provider}`);let h=t.apiKey,u=i,d=await t.onPayload?.(u,a);d!==void 0&&(u=d);let l=t.fetch??globalThis.fetch,{response:c,json:p}=await w(async()=>{let s=t.timeoutMs!==void 0?AbortSignal.timeout(t.timeoutMs):void 0,g=t.signal&&s?AbortSignal.any([t.signal,s]):t.signal??s;try{let n=await l(r,{method:"POST",headers:j(a,h,t.headers,t.identity),body:JSON.stringify(u),signal:g});if(!n.ok)throw $(e,n,await n.text());return{response:n,json:await n.json()}}catch(n){throw s?.aborted&&!t.signal?.aborted?T(t.timeoutMs):n}},{maxRetries:t.maxRetries??2,maxRetryDelayMs:t.maxRetryDelayMs,signal:t.signal,noRetryStatuses:y});return await t.onResponse?.({status:c.status,headers:q(c.headers)},a),p}o(A,"postClassifierRequest");function f(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}o(f,"tokenCount");function C(e,r){if(!m(e)||e.input_tokens===void 0&&e.output_tokens===void 0)return;let a=f(e.input_tokens),i=f(e.output_tokens),t={input:a,output:i,cacheRead:0,cacheWrite:0,totalTokens:a+i,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return x(r,t),t}o(C,"parseClassifierUsage");export{m as isRecord,C as parseClassifierUsage,A as postClassifierRequest,_ as requiredNumber};
1
+ var R=Object.defineProperty;var o=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createRequire as b}from"node:module";const S=b(import.meta.url);import{retryProviderRequest as w}from"./chunk-ML5DIOWR.js";import{headersToRecord as q,providerHeadersToRecord as k}from"./chunk-UTB4DTYQ.js";import{calculateCost as x}from"./chunk-5MF5GEDD.js";import{getIdentityHeaders as E}from"./chunk-JK74OC6W.js";function $(e,r,a){let i=new Error(`${e} returned ${r.status}`);return i.status=r.status,i.headers=r.headers,i.body=a,i}o($,"httpError");function T(e){let r=new Error(`Request timed out after ${e}ms`);return r.name="TimeoutError",r.status=void 0,r.headers=void 0,r.body="",r}o(T,"timeoutError");function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(m,"isRecord");function _(e,r,a){if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${e} returned an invalid ${a}`);return r}o(_,"requiredNumber");function j(e,r,a,i){return k(E(e,i),{authorization:`Bearer ${r}`,"content-type":"application/json"},e.headers,a)??{}}o(j,"requestHeaders");async function A(e,r,a,i,t,y){if(!t?.apiKey)throw new Error(`No API key for provider: ${a.provider}`);let h=t.apiKey,u=i,d=await t.onPayload?.(u,a);d!==void 0&&(u=d);let l=t.fetch??globalThis.fetch,{response:c,json:p}=await w(async()=>{let s=t.timeoutMs!==void 0?AbortSignal.timeout(t.timeoutMs):void 0,g=t.signal&&s?AbortSignal.any([t.signal,s]):t.signal??s;try{let n=await l(r,{method:"POST",headers:j(a,h,t.headers,t.identity),body:JSON.stringify(u),signal:g});if(!n.ok)throw $(e,n,await n.text());return{response:n,json:await n.json()}}catch(n){throw s?.aborted&&!t.signal?.aborted?T(t.timeoutMs):n}},{maxRetries:t.maxRetries??2,maxRetryDelayMs:t.maxRetryDelayMs,signal:t.signal,noRetryStatuses:y});return await t.onResponse?.({status:c.status,headers:q(c.headers)},a),p}o(A,"postClassifierRequest");function f(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}o(f,"tokenCount");function C(e,r){if(!m(e)||e.input_tokens===void 0&&e.output_tokens===void 0)return;let a=f(e.input_tokens),i=f(e.output_tokens),t={input:a,output:i,cacheRead:0,cacheWrite:0,totalTokens:a+i,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return x(r,t),t}o(C,"parseClassifierUsage");export{m as isRecord,C as parseClassifierUsage,A as postClassifierRequest,_ as requiredNumber};
@@ -1,4 +1,4 @@
1
- var Oe=Object.defineProperty;var s=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const fr=Le(import.meta.url);import{FileAuthStorageBackend as xe,JSON_RPC_ERROR_CODES as $e,LATEST_PROTOCOL_VERSION as T,McpAuthRequiredError as De,McpClient as He,McpError as Ne,McpHttpError as K,McpSessionExpiredError as Fe,StdioTransport as z,StreamableHttpTransport as Ve,isClientMetadataDocumentCallback as je,isObject as W,mcpNamespace as Be,require_proper_lockfile as qe,resolveConfigValueOrThrow as J,resolveHeadersOrThrow as Ke}from"./chunk-MKMLENQD.js";import{sliceTail as Y}from"./chunk-SE42OS3U.js";import{APP_NAME as Z,VERSION as We,getAgentDir as G}from"./chunk-R47JBGS3.js";import{__toESM as Je}from"./chunk-JXWJOIH4.js";import{homedir as Q}from"node:os";import{basename as Ye,join as Ze,resolve as Ge}from"node:path";import{setTimeout as Qe}from"node:timers/promises";import{pathToFileURL as Xe}from"node:url";import{createHash as et}from"node:crypto";var tt=class{static{s(this,"MemoryOAuthStateStore")}value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},rt=class{static{s(this,"McpOAuthProvider")}redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:e.clientMetadata.response_types??["code"],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=e.clientMetadataDocument,this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new tt,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let t=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(r=>({...r,oauthState:t})),t}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(t=>({...t,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let t=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(r=>{let i={...r,tokens:e};return t===void 0?delete i.tokensExpireAt:i.tokensExpireAt=t,i})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(t=>({...t,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw new Error("No OAuth PKCE code verifier is stored");return e}async invalidateCredentials(e){await this.update(t=>{let r={...t};return(e==="all"||e==="client")&&delete r.clientInformation,(e==="all"||e==="tokens")&&(delete r.tokens,delete r.tokensExpireAt),(e==="all"||e==="verifier")&&delete r.codeVerifier,(e==="all"||e==="discovery")&&delete r.discovery,e==="all"&&delete r.oauthState,r})}async saveDiscoveryState(e){await this.update(t=>({...t,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};function P(e,t,r=()=>{}){let{serverUrl:i,settings:n,clientMetadataDocuments:a}=e;return new rt({serverUrl:i,redirectUrl:t,clientMetadata:{client_name:n.clientName??e.clientName},clientMetadataDocument:I(n,a,t)?o=>{if(!a?.listsRedirectUrl(t))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${t}`);let c=it(i,t,o,a.baseUrl);if(!c&&n.clientRegistration==="cimd")throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');return c}:void 0,clientId:n.clientId,clientSecret:n.clientSecret,store:e.store,onRedirect:r})}s(P,"createOAuthClientProvider");function I(e,t,r){let i=e.clientRegistration??"auto";return i!=="auto"?i==="cimd":!e.clientId&&!e.clientName&&t?.listsRedirectUrl(r)===!0}s(I,"offersClientMetadataDocument");function it(e,t,r,i){if(!r?.client_id_metadata_document_supported||!r.token_endpoint_auth_methods_supported?.includes("none"))return;if(r.authorization_response_iss_parameter_supported)return{url:`${i}/client.json`,redirectUrl:t};let n=new URL(t);return n.pathname=X(n.pathname,e),{url:`${i}/${ee(e)}/client.json`,redirectUrl:n.href}}s(it,"clientMetadataDocument");function X(e,t){return`${e.replace(/\/$/,"")}/${ee(t)}`}s(X,"serverSpecificPath");function ee(e){let t=new URL(e);return t.hash="",et("sha256").update(t.href).digest().subarray(0,9).toString("base64url")}s(ee,"callbackId");function O(e){return e&&"redirect_uris"in e?e.redirect_uris:[]}s(O,"registeredRedirectUrls");var nt=15e3;function te(e=globalThis.fetch){return(t,r)=>{let i=AbortSignal.timeout(nt);return e(t,{...r,signal:r?.signal?AbortSignal.any([r.signal,i]):i})}}s(te,"timedFetch");var re="127.0.0.1",at="/callback",ie=`http://${re}${at}`;function ne(e){let t=e.callbackUrl??ie,r=new URL(t),i=r.hostname.replace(/^\[|\]$/g,""),n=r.port?Number(r.port):e.callbackPort,a;return r.port?a=e.callbackUrl:n!==void 0&&(r.port=String(n),a=r.href),{url:t,host:i==="localhost"?re:i,redirectHost:i,port:n,path:r.pathname,fixedRedirectUrl:a}}s(ne,"loopbackSettings");var _=class extends Error{static{s(this,"OAuthError")}code;errorUri;constructor(e,t,r){super(t||e),this.name="OAuthError",this.code=e,this.errorUri=r}},ae=class extends Error{static{s(this,"OAuthIssuerMismatchError")}expected;received;constructor(e,t){let r=s(i=>i===void 0?"none":JSON.stringify(i),"format");super(`OAuth issuer mismatch: expected ${r(e)}, received ${r(t)}`),this.name="OAuthIssuerMismatchError",this.expected=e,this.received=t}},se=class extends Error{static{s(this,"OAuthInsecureEndpointError")}endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name="OAuthInsecureEndpointError",this.endpoint=e}},st=class extends Error{static{s(this,"OAuthRegistrationError")}status;body;constructor(e,t){super(`OAuth dynamic client registration failed with status ${e}: ${t}`),this.name="OAuthRegistrationError",this.status=e,this.body=t}},v=class extends Error{static{s(this,"McpOAuthAuthorizationRequiredError")}constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},oe=class extends Error{static{s(this,"McpRefreshLockBusyError")}constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function U(e,t){if(!W(e))throw new Error(`Invalid ${t}`);return e}s(U,"object");function S(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}s(S,"compact");function y(e,t){if(typeof e!="string"||e.length===0)throw new Error(`Invalid ${t}`);return e}s(y,"requiredString");function L(e){return e==null||e===""}s(L,"absent");function k(e,t){if(!L(e))return y(e,t)}s(k,"optionalString");function p(e,t){if(e!=null){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`Invalid ${t}`);return[...e]}}s(p,"optionalStrings");function m(e,t){let r=y(e,t);if(!URL.canParse(r)||!ce(new URL(r)))throw new Error(`Invalid ${t}`);return r}s(m,"safeUrl");function ce(e){return e.protocol==="http:"||e.protocol==="https:"}s(ce,"isHttpUrl");function ot(e,t){return L(e)?void 0:m(e,t)}s(ot,"optionalUrl");function ct(e){let t=U(e,"OAuth protected resource metadata");return S({...t,resource:m(t.resource,"OAuth protected resource metadata resource"),authorization_servers:p(t.authorization_servers,"authorization_servers")?.map(r=>m(r,"authorization server URL")),scopes_supported:p(t.scopes_supported,"scopes_supported")})}s(ct,"parseProtectedResourceMetadata");function le(e){let t=U(e,"authorization server metadata"),r=p(t.response_types_supported,"response_types_supported");if(!r)throw new Error("Invalid response_types_supported");return S({...t,issuer:m(t.issuer,"authorization server issuer"),authorization_endpoint:m(t.authorization_endpoint,"authorization endpoint"),token_endpoint:m(t.token_endpoint,"token endpoint"),registration_endpoint:ot(t.registration_endpoint,"registration endpoint"),scopes_supported:p(t.scopes_supported,"scopes_supported"),response_types_supported:r,grant_types_supported:p(t.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:p(t.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:p(t.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof t.client_id_metadata_document_supported=="boolean"?t.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof t.authorization_response_iss_parameter_supported=="boolean"?t.authorization_response_iss_parameter_supported:void 0})}s(le,"parseAuthorizationServerMetadata");function lt(e){let t=U(e,"OAuth token response"),r=L(t.expires_in)?void 0:Number(t.expires_in);if(r!==void 0&&!Number.isFinite(r))throw new Error("Invalid expires_in");return S({access_token:y(t.access_token,"access_token"),token_type:y(t.token_type,"token_type"),expires_in:r,scope:k(t.scope,"scope"),refresh_token:k(t.refresh_token,"refresh_token"),id_token:k(t.id_token,"id_token")})}s(lt,"parseOAuthTokens");function ht(e){let t=U(e,"OAuth client registration response");return S({...t,client_id:y(t.client_id,"client_id"),client_secret:k(t.client_secret,"client_secret"),client_id_issued_at:typeof t.client_id_issued_at=="number"?t.client_id_issued_at:void 0,client_secret_expires_at:typeof t.client_secret_expires_at=="number"?t.client_secret_expires_at:void 0,redirect_uris:p(t.redirect_uris,"redirect_uris")??[]})}s(ht,"parseClientInformation");function R(e){e?.body?.cancel().catch(()=>{})}s(R,"discard");function he(e){return e>=400&&e<500||e===502}s(he,"isDiscoveryMiss");function de(e){return e.endsWith("/")?e.slice(0,-1):e}s(de,"pathSuffix");function E(e,t){let r=e.match(new RegExp(String.raw`(?:^|[,\s])${t}=(?:"([^"]*)"|([^\s,]+))`,"i"));return r?.[1]||r?.[2]||void 0}s(E,"field");function dt(e){if(!e)return{};let t=e.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(t!=="bearer"&&t!=="dpop")return{};let r=E(e,"resource_metadata"),i;if(r)try{i=new URL(r)}catch{}return{resourceMetadataUrl:i,scope:E(e,"scope"),error:E(e,"error"),errorDescription:E(e,"error_description")}}s(dt,"parseWwwAuthenticate");async function M(e,t,r,i){return t(e,{headers:{Accept:"application/json","MCP-Protocol-Version":r},signal:i})}s(M,"fetchMetadata");async function ut(e,t={}){let r=new URL(e),i=t.fetch??globalThis.fetch,n=t.protocolVersion??T,a=await M(t.resourceMetadataUrl?new URL(t.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${de(r.pathname)}`,r.origin),i,n,t.signal);if(!t.resourceMetadataUrl&&r.pathname!=="/"&&he(a.status)&&(R(a),a=await M(new URL("/.well-known/oauth-protected-resource",r.origin),i,n,t.signal)),!a.ok)throw R(a),new Error(`HTTP ${a.status} loading OAuth protected resource metadata`);return ct(await a.json())}s(ut,"discoverProtectedResourceMetadata");function ft(e){let t=new URL(e),r=de(t.pathname),i=[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}];return r&&i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}s(ft,"buildAuthorizationServerDiscoveryUrls");async function ue(e,t={}){let r=t.fetch??globalThis.fetch;for(let{url:i}of ft(e)){let n=await M(i,r,t.protocolVersion??T,t.signal);if(!n.ok){if(R(n),he(n.status))continue;throw new Error(`HTTP ${n.status} loading authorization server metadata from ${i}`)}let a=le(await n.json());if(!t.skipIssuerValidation){let o=String(e),c=s(l=>l.endsWith("/")?l.slice(0,-1):l,"trim");if(c(a.issuer)!==c(o))throw new ae(o,a.issuer)}return a}}s(ue,"discoverAuthorizationServerMetadata");async function pt(e,t={}){let r;try{r=await ut(e,{resourceMetadataUrl:t.resourceMetadataUrl,fetch:t.fetch,signal:t.signal})}catch(n){if(n instanceof TypeError)throw n}if(t.authorizationServerMetadataUrl){let n=t.authorizationServerMetadataUrl,a=await M(n,t.fetch??globalThis.fetch,T,t.signal);if(!a.ok)throw R(a),new Error(`HTTP ${a.status} loading authorization server metadata from ${n}`);let o=le(await a.json());return{authorizationServerUrl:o.issuer,authorizationServerMetadata:o,resourceMetadata:r}}let i=r?.authorization_servers?.[0]??String(new URL("/",e));return{authorizationServerUrl:i,authorizationServerMetadata:await ue(i,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:r}}s(pt,"discoverOAuthServerInfo");function wt(e){let t=new URL(e);return t.hash="",t}s(wt,"resourceUrlFromServerUrl");function gt(e,t){if(!t)return;let r=wt(e),i=new URL(t.resource);if(r.origin!==i.origin)throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);let n=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,a=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`;if(!n.startsWith(a))throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);return t.resource}s(gt,"selectResource");function fe(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}s(fe,"loopback");function mt(e){return e.some(t=>{if(!URL.canParse(t))return!1;let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||fe(r.hostname)})?"native":"web"}s(mt,"applicationType");function pe(e){let t=new URL(e);if(t.protocol!=="https:"&&!fe(t.hostname))throw new se(t.href);return t}s(pe,"secureEndpoint");function _t(e,t){let r="token_endpoint_auth_method"in e?e.token_endpoint_auth_method:void 0;return r&&["client_secret_basic","client_secret_post","none"].includes(r)&&(t.length===0||t.includes(r))?r:t.length===0?e.client_secret?"client_secret_basic":"none":e.client_secret&&t.includes("client_secret_basic")?"client_secret_basic":e.client_secret&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":e.client_secret?"client_secret_post":"none"}s(_t,"selectClientAuthMethod");function vt(e,t,r,i){if(e==="client_secret_basic"){if(!t.client_secret)throw new Error("client_secret_basic requires a client secret");r.set("Authorization",`Basic ${Buffer.from(`${t.client_id}:${t.client_secret}`).toString("base64")}`)}else i.set("client_id",t.client_id),e==="client_secret_post"&&t.client_secret&&i.set("client_secret",t.client_secret)}s(vt,"applyClientAuthentication");async function yt(){let e=crypto.getRandomValues(new Uint8Array(32)),t=Buffer.from(e).toString("base64url"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Buffer.from(r).toString("base64url")}}s(yt,"pkce");async function Ut(e,t){let r=t.metadata;if(r&&!r.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(r?.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let i=new URL(r?.authorization_endpoint??new URL("/authorize",e));if(!ce(i))throw new Error(`Invalid authorization endpoint ${i.href}`);let{verifier:n,challenge:a}=await yt();return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientInformation.client_id),i.searchParams.set("code_challenge",a),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("redirect_uri",String(t.redirectUrl)),t.state&&i.searchParams.set("state",t.state),t.scope&&i.searchParams.set("scope",t.scope),t.scope?.split(/\s+/).includes("offline_access")&&i.searchParams.set("prompt","consent"),t.resource&&i.searchParams.set("resource",t.resource),{authorizationUrl:i,codeVerifier:n}}s(Ut,"startAuthorization");async function we(e,t,r){let i=pe(t.metadata?.token_endpoint??new URL("/token",e)),n=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});t.resource&&r.set("resource",t.resource),t.addClientAuthentication?await t.addClientAuthentication(n,r,i,t.metadata):vt(_t(t.clientInformation,t.metadata?.token_endpoint_auth_methods_supported??[]),t.clientInformation,n,r);let a=await(t.fetch??globalThis.fetch)(i,{method:"POST",headers:n,body:r,signal:t.signal}),o=await a.text(),c;try{c=JSON.parse(o)}catch{}if(W(c)&&typeof c.error=="string")throw new _(c.error,typeof c.error_description=="string"?c.error_description:c.error,typeof c.error_uri=="string"?c.error_uri:void 0);if(!a.ok)throw new _("server_error",`HTTP ${a.status}: ${o}`);return lt(c)}s(we,"tokenRequest");async function St(e,t){let r=t.metadata?.registration_endpoint;if(t.metadata&&!r)throw new Error("Authorization server does not support dynamic client registration");let i=await(t.fetch??globalThis.fetch)(new URL(r??new URL("/register",e)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.clientMetadata,application_type:t.clientMetadata.application_type??mt(t.clientMetadata.redirect_uris),...t.scope?{scope:t.scope}:{}}),signal:t.signal});if(!i.ok)throw new st(i.status,await i.text());return ht(await i.json())}s(St,"registerClient");async function kt(e,t){return we(e,t,new URLSearchParams({grant_type:"authorization_code",code:t.code,code_verifier:t.codeVerifier,redirect_uri:String(t.redirectUrl)}))}s(kt,"exchangeAuthorizationCode");async function Rt(e,t){let r=await we(e,t,new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken}));return{refresh_token:t.refreshToken,...r}}s(Rt,"refreshAuthorization");function ge(e,t){return e.scope===void 0&&t?{...e,scope:t}:e}s(ge,"withScope");function Et(e,t){if(!t)return;let r=[e,t].flatMap(i=>i?.split(/\s+/).filter(Boolean)??[]);return[...new Set(r)].join(" ")}s(Et,"stepUpScope");async function x(e,t,r={}){let i=t.authorizationServerMetadataUrl&&pe(t.authorizationServerMetadataUrl),n=i?void 0:await e.discoveryState?.(),a=n?.authorizationServerUrl?{authorizationServerUrl:n.authorizationServerUrl,authorizationServerMetadata:n.authorizationServerMetadata??await ue(n.authorizationServerUrl,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:n.resourceMetadata}:await pt(t.serverUrl,{resourceMetadataUrl:t.resourceMetadataUrl,authorizationServerMetadataUrl:i,fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal});i||await e.saveDiscoveryState?.({...a,...t.resourceMetadataUrl?{resourceMetadataUrl:t.resourceMetadataUrl.href}:{}});let o=a.authorizationServerMetadata,c=gt(t.serverUrl,a.resourceMetadata),l=t.scope||a.resourceMetadata?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await e.clientInformation();r.storedClientId=h?.client_id;let d=h?void 0:e.clientMetadataDocument?.(o);if(d){let u=new URL(d.url);if(u.protocol!=="https:"||u.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let f=d?.redirectUrl??String(e.redirectUrl);if(t.authorizationCode&&t.authorizationRedirectUrl!==void 0&&f!==t.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${f}, but the authorization request used ${t.authorizationRedirectUrl}`);let w=h??(d&&{client_id:d.url});if(!w){if(t.refreshOnly)return"REDIRECT";if(t.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!e.saveClientInformation)throw new Error("OAuth client information cannot be persisted");w=await St(a.authorizationServerUrl,{metadata:o,clientMetadata:e.clientMetadata,scope:l,fetch:t.fetch,signal:t.signal}),await e.saveClientInformation(w)}let B={metadata:o,clientInformation:w,resource:c,addClientAuthentication:e.addClientAuthentication,fetch:t.fetch,signal:t.signal};if(t.authorizationCode){let u=t.iss;if((u!==void 0||o?.authorization_response_iss_parameter_supported)&&u!==o?.issuer)throw new ae(o?.issuer,u);let Ie=await kt(a.authorizationServerUrl,{...B,code:t.authorizationCode,codeVerifier:await e.codeVerifier(),redirectUrl:f});return await e.saveTokens(ge(Ie,l)),"AUTHORIZED"}let b=t.skipRefresh?void 0:await e.tokens();if(b?.refresh_token)try{let u=await Rt(a.authorizationServerUrl,{...B,refreshToken:b.refresh_token});return await e.saveTokens(ge(u,b.scope)),"AUTHORIZED"}catch(u){if(t.signal?.aborted||u instanceof se||u instanceof _&&u.code!=="server_error")throw u}if(t.refreshOnly)return"REDIRECT";let Pe=await e.state?.(),q=await Ut(a.authorizationServerUrl,{metadata:o,clientInformation:w,redirectUrl:f,scope:l,state:Pe,resource:c});return await e.saveCodeVerifier(q.codeVerifier),await e.redirectToAuthorization(q.authorizationUrl),"REDIRECT"}s(x,"runFlow");async function $(e,t){let r={};try{return await x(e,t,r)}catch(i){if(i instanceof _&&["invalid_client","unauthorized_client"].includes(i.code)){if(t.refreshOnly){if((await e.clientInformation())?.client_id===r.storedClientId)for(let n of["client","tokens","discovery"])await e.invalidateCredentials?.(n)}else await e.invalidateCredentials?.("all");return x(e,t)}if(i instanceof _&&i.code==="invalid_grant")return await e.invalidateCredentials?.("tokens"),x(e,t);throw i}}s($,"authorizeMcp");var Mt=3e4;function At(e){let{store:t,redirectUrl:r}=e,i,n=s((a,o=globalThis.fetch,c)=>(i??=t.withRefreshLock(async()=>{let l=await t.load();if(l?.tokens?.access_token!==a)return;if(!l?.tokens?.refresh_token)throw new v;let h={...e,settings:e.settings()};if(await me(h,l,{fetch:o,challenge:c,redirectUrl:r})==="REDIRECT")throw new v}).finally(()=>{i=void 0}),i),"refresh");return{token:s(async()=>{await i?.catch(()=>{});let a=await t.load(),o=a?.tokens?.access_token;return!(a?.tokensExpireAt!==void 0&&a.tokensExpireAt-Mt<=Date.now())||!a?.tokens?.refresh_token?o:(await n(o).catch(()=>{}),(await t.load())?.tokens?.access_token)},"token"),onUnauthorized:s(async a=>{let o=dt(a.response.headers.get("www-authenticate"));if(e.onChallenge(o),o.error==="insufficient_scope")throw new v;await n(a.token,a.fetch,o)},"onUnauthorized"),settled:s(async()=>{await i?.catch(()=>{})},"settled")}}s(At,"createMcpAuthProvider");async function me(e,t,r={}){let i=[r.redirectUrl,ne(e.settings).fixedRedirectUrl,O(t.clientInformation)[0]].filter(n=>n!==void 0).find(n=>e.clientMetadataDocuments?.listsRedirectUrl(n))??ie;return $(P(e,i),{serverUrl:e.serverUrl,resourceMetadataUrl:r.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl,fetch:te(r.fetch),refreshOnly:!0})}s(me,"refreshStoredTokens");import{createServer as Ct}from"node:http";function bt(e){return e.ok?"Authorization complete. You may close this window.":e.details?`${e.message}
1
+ var Oe=Object.defineProperty;var s=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const fr=Le(import.meta.url);import{FileAuthStorageBackend as xe,JSON_RPC_ERROR_CODES as $e,LATEST_PROTOCOL_VERSION as T,McpAuthRequiredError as De,McpClient as He,McpError as Ne,McpHttpError as K,McpSessionExpiredError as Fe,StdioTransport as z,StreamableHttpTransport as Ve,isClientMetadataDocumentCallback as je,isObject as W,mcpNamespace as Be,require_proper_lockfile as qe,resolveConfigValueOrThrow as J,resolveHeadersOrThrow as Ke}from"./chunk-C5ELI234.js";import{sliceTail as Y}from"./chunk-HF334NQU.js";import{APP_NAME as Z,VERSION as We,getAgentDir as G}from"./chunk-R47JBGS3.js";import{__toESM as Je}from"./chunk-JXWJOIH4.js";import{homedir as Q}from"node:os";import{basename as Ye,join as Ze,resolve as Ge}from"node:path";import{setTimeout as Qe}from"node:timers/promises";import{pathToFileURL as Xe}from"node:url";import{createHash as et}from"node:crypto";var tt=class{static{s(this,"MemoryOAuthStateStore")}value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},rt=class{static{s(this,"McpOAuthProvider")}redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:e.clientMetadata.response_types??["code"],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=e.clientMetadataDocument,this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new tt,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let t=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(r=>({...r,oauthState:t})),t}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(t=>({...t,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let t=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(r=>{let i={...r,tokens:e};return t===void 0?delete i.tokensExpireAt:i.tokensExpireAt=t,i})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(t=>({...t,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw new Error("No OAuth PKCE code verifier is stored");return e}async invalidateCredentials(e){await this.update(t=>{let r={...t};return(e==="all"||e==="client")&&delete r.clientInformation,(e==="all"||e==="tokens")&&(delete r.tokens,delete r.tokensExpireAt),(e==="all"||e==="verifier")&&delete r.codeVerifier,(e==="all"||e==="discovery")&&delete r.discovery,e==="all"&&delete r.oauthState,r})}async saveDiscoveryState(e){await this.update(t=>({...t,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};function P(e,t,r=()=>{}){let{serverUrl:i,settings:n,clientMetadataDocuments:a}=e;return new rt({serverUrl:i,redirectUrl:t,clientMetadata:{client_name:n.clientName??e.clientName},clientMetadataDocument:I(n,a,t)?o=>{if(!a?.listsRedirectUrl(t))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${t}`);let c=it(i,t,o,a.baseUrl);if(!c&&n.clientRegistration==="cimd")throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');return c}:void 0,clientId:n.clientId,clientSecret:n.clientSecret,store:e.store,onRedirect:r})}s(P,"createOAuthClientProvider");function I(e,t,r){let i=e.clientRegistration??"auto";return i!=="auto"?i==="cimd":!e.clientId&&!e.clientName&&t?.listsRedirectUrl(r)===!0}s(I,"offersClientMetadataDocument");function it(e,t,r,i){if(!r?.client_id_metadata_document_supported||!r.token_endpoint_auth_methods_supported?.includes("none"))return;if(r.authorization_response_iss_parameter_supported)return{url:`${i}/client.json`,redirectUrl:t};let n=new URL(t);return n.pathname=X(n.pathname,e),{url:`${i}/${ee(e)}/client.json`,redirectUrl:n.href}}s(it,"clientMetadataDocument");function X(e,t){return`${e.replace(/\/$/,"")}/${ee(t)}`}s(X,"serverSpecificPath");function ee(e){let t=new URL(e);return t.hash="",et("sha256").update(t.href).digest().subarray(0,9).toString("base64url")}s(ee,"callbackId");function O(e){return e&&"redirect_uris"in e?e.redirect_uris:[]}s(O,"registeredRedirectUrls");var nt=15e3;function te(e=globalThis.fetch){return(t,r)=>{let i=AbortSignal.timeout(nt);return e(t,{...r,signal:r?.signal?AbortSignal.any([r.signal,i]):i})}}s(te,"timedFetch");var re="127.0.0.1",at="/callback",ie=`http://${re}${at}`;function ne(e){let t=e.callbackUrl??ie,r=new URL(t),i=r.hostname.replace(/^\[|\]$/g,""),n=r.port?Number(r.port):e.callbackPort,a;return r.port?a=e.callbackUrl:n!==void 0&&(r.port=String(n),a=r.href),{url:t,host:i==="localhost"?re:i,redirectHost:i,port:n,path:r.pathname,fixedRedirectUrl:a}}s(ne,"loopbackSettings");var _=class extends Error{static{s(this,"OAuthError")}code;errorUri;constructor(e,t,r){super(t||e),this.name="OAuthError",this.code=e,this.errorUri=r}},ae=class extends Error{static{s(this,"OAuthIssuerMismatchError")}expected;received;constructor(e,t){let r=s(i=>i===void 0?"none":JSON.stringify(i),"format");super(`OAuth issuer mismatch: expected ${r(e)}, received ${r(t)}`),this.name="OAuthIssuerMismatchError",this.expected=e,this.received=t}},se=class extends Error{static{s(this,"OAuthInsecureEndpointError")}endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name="OAuthInsecureEndpointError",this.endpoint=e}},st=class extends Error{static{s(this,"OAuthRegistrationError")}status;body;constructor(e,t){super(`OAuth dynamic client registration failed with status ${e}: ${t}`),this.name="OAuthRegistrationError",this.status=e,this.body=t}},v=class extends Error{static{s(this,"McpOAuthAuthorizationRequiredError")}constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},oe=class extends Error{static{s(this,"McpRefreshLockBusyError")}constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function U(e,t){if(!W(e))throw new Error(`Invalid ${t}`);return e}s(U,"object");function S(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}s(S,"compact");function y(e,t){if(typeof e!="string"||e.length===0)throw new Error(`Invalid ${t}`);return e}s(y,"requiredString");function L(e){return e==null||e===""}s(L,"absent");function k(e,t){if(!L(e))return y(e,t)}s(k,"optionalString");function p(e,t){if(e!=null){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`Invalid ${t}`);return[...e]}}s(p,"optionalStrings");function m(e,t){let r=y(e,t);if(!URL.canParse(r)||!ce(new URL(r)))throw new Error(`Invalid ${t}`);return r}s(m,"safeUrl");function ce(e){return e.protocol==="http:"||e.protocol==="https:"}s(ce,"isHttpUrl");function ot(e,t){return L(e)?void 0:m(e,t)}s(ot,"optionalUrl");function ct(e){let t=U(e,"OAuth protected resource metadata");return S({...t,resource:m(t.resource,"OAuth protected resource metadata resource"),authorization_servers:p(t.authorization_servers,"authorization_servers")?.map(r=>m(r,"authorization server URL")),scopes_supported:p(t.scopes_supported,"scopes_supported")})}s(ct,"parseProtectedResourceMetadata");function le(e){let t=U(e,"authorization server metadata"),r=p(t.response_types_supported,"response_types_supported");if(!r)throw new Error("Invalid response_types_supported");return S({...t,issuer:m(t.issuer,"authorization server issuer"),authorization_endpoint:m(t.authorization_endpoint,"authorization endpoint"),token_endpoint:m(t.token_endpoint,"token endpoint"),registration_endpoint:ot(t.registration_endpoint,"registration endpoint"),scopes_supported:p(t.scopes_supported,"scopes_supported"),response_types_supported:r,grant_types_supported:p(t.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:p(t.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:p(t.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof t.client_id_metadata_document_supported=="boolean"?t.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof t.authorization_response_iss_parameter_supported=="boolean"?t.authorization_response_iss_parameter_supported:void 0})}s(le,"parseAuthorizationServerMetadata");function lt(e){let t=U(e,"OAuth token response"),r=L(t.expires_in)?void 0:Number(t.expires_in);if(r!==void 0&&!Number.isFinite(r))throw new Error("Invalid expires_in");return S({access_token:y(t.access_token,"access_token"),token_type:y(t.token_type,"token_type"),expires_in:r,scope:k(t.scope,"scope"),refresh_token:k(t.refresh_token,"refresh_token"),id_token:k(t.id_token,"id_token")})}s(lt,"parseOAuthTokens");function ht(e){let t=U(e,"OAuth client registration response");return S({...t,client_id:y(t.client_id,"client_id"),client_secret:k(t.client_secret,"client_secret"),client_id_issued_at:typeof t.client_id_issued_at=="number"?t.client_id_issued_at:void 0,client_secret_expires_at:typeof t.client_secret_expires_at=="number"?t.client_secret_expires_at:void 0,redirect_uris:p(t.redirect_uris,"redirect_uris")??[]})}s(ht,"parseClientInformation");function R(e){e?.body?.cancel().catch(()=>{})}s(R,"discard");function he(e){return e>=400&&e<500||e===502}s(he,"isDiscoveryMiss");function de(e){return e.endsWith("/")?e.slice(0,-1):e}s(de,"pathSuffix");function E(e,t){let r=e.match(new RegExp(String.raw`(?:^|[,\s])${t}=(?:"([^"]*)"|([^\s,]+))`,"i"));return r?.[1]||r?.[2]||void 0}s(E,"field");function dt(e){if(!e)return{};let t=e.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(t!=="bearer"&&t!=="dpop")return{};let r=E(e,"resource_metadata"),i;if(r)try{i=new URL(r)}catch{}return{resourceMetadataUrl:i,scope:E(e,"scope"),error:E(e,"error"),errorDescription:E(e,"error_description")}}s(dt,"parseWwwAuthenticate");async function M(e,t,r,i){return t(e,{headers:{Accept:"application/json","MCP-Protocol-Version":r},signal:i})}s(M,"fetchMetadata");async function ut(e,t={}){let r=new URL(e),i=t.fetch??globalThis.fetch,n=t.protocolVersion??T,a=await M(t.resourceMetadataUrl?new URL(t.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${de(r.pathname)}`,r.origin),i,n,t.signal);if(!t.resourceMetadataUrl&&r.pathname!=="/"&&he(a.status)&&(R(a),a=await M(new URL("/.well-known/oauth-protected-resource",r.origin),i,n,t.signal)),!a.ok)throw R(a),new Error(`HTTP ${a.status} loading OAuth protected resource metadata`);return ct(await a.json())}s(ut,"discoverProtectedResourceMetadata");function ft(e){let t=new URL(e),r=de(t.pathname),i=[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}];return r&&i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}s(ft,"buildAuthorizationServerDiscoveryUrls");async function ue(e,t={}){let r=t.fetch??globalThis.fetch;for(let{url:i}of ft(e)){let n=await M(i,r,t.protocolVersion??T,t.signal);if(!n.ok){if(R(n),he(n.status))continue;throw new Error(`HTTP ${n.status} loading authorization server metadata from ${i}`)}let a=le(await n.json());if(!t.skipIssuerValidation){let o=String(e),c=s(l=>l.endsWith("/")?l.slice(0,-1):l,"trim");if(c(a.issuer)!==c(o))throw new ae(o,a.issuer)}return a}}s(ue,"discoverAuthorizationServerMetadata");async function pt(e,t={}){let r;try{r=await ut(e,{resourceMetadataUrl:t.resourceMetadataUrl,fetch:t.fetch,signal:t.signal})}catch(n){if(n instanceof TypeError)throw n}if(t.authorizationServerMetadataUrl){let n=t.authorizationServerMetadataUrl,a=await M(n,t.fetch??globalThis.fetch,T,t.signal);if(!a.ok)throw R(a),new Error(`HTTP ${a.status} loading authorization server metadata from ${n}`);let o=le(await a.json());return{authorizationServerUrl:o.issuer,authorizationServerMetadata:o,resourceMetadata:r}}let i=r?.authorization_servers?.[0]??String(new URL("/",e));return{authorizationServerUrl:i,authorizationServerMetadata:await ue(i,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:r}}s(pt,"discoverOAuthServerInfo");function wt(e){let t=new URL(e);return t.hash="",t}s(wt,"resourceUrlFromServerUrl");function gt(e,t){if(!t)return;let r=wt(e),i=new URL(t.resource);if(r.origin!==i.origin)throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);let n=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,a=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`;if(!n.startsWith(a))throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);return t.resource}s(gt,"selectResource");function fe(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}s(fe,"loopback");function mt(e){return e.some(t=>{if(!URL.canParse(t))return!1;let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||fe(r.hostname)})?"native":"web"}s(mt,"applicationType");function pe(e){let t=new URL(e);if(t.protocol!=="https:"&&!fe(t.hostname))throw new se(t.href);return t}s(pe,"secureEndpoint");function _t(e,t){let r="token_endpoint_auth_method"in e?e.token_endpoint_auth_method:void 0;return r&&["client_secret_basic","client_secret_post","none"].includes(r)&&(t.length===0||t.includes(r))?r:t.length===0?e.client_secret?"client_secret_basic":"none":e.client_secret&&t.includes("client_secret_basic")?"client_secret_basic":e.client_secret&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":e.client_secret?"client_secret_post":"none"}s(_t,"selectClientAuthMethod");function vt(e,t,r,i){if(e==="client_secret_basic"){if(!t.client_secret)throw new Error("client_secret_basic requires a client secret");r.set("Authorization",`Basic ${Buffer.from(`${t.client_id}:${t.client_secret}`).toString("base64")}`)}else i.set("client_id",t.client_id),e==="client_secret_post"&&t.client_secret&&i.set("client_secret",t.client_secret)}s(vt,"applyClientAuthentication");async function yt(){let e=crypto.getRandomValues(new Uint8Array(32)),t=Buffer.from(e).toString("base64url"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Buffer.from(r).toString("base64url")}}s(yt,"pkce");async function Ut(e,t){let r=t.metadata;if(r&&!r.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(r?.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let i=new URL(r?.authorization_endpoint??new URL("/authorize",e));if(!ce(i))throw new Error(`Invalid authorization endpoint ${i.href}`);let{verifier:n,challenge:a}=await yt();return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientInformation.client_id),i.searchParams.set("code_challenge",a),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("redirect_uri",String(t.redirectUrl)),t.state&&i.searchParams.set("state",t.state),t.scope&&i.searchParams.set("scope",t.scope),t.scope?.split(/\s+/).includes("offline_access")&&i.searchParams.set("prompt","consent"),t.resource&&i.searchParams.set("resource",t.resource),{authorizationUrl:i,codeVerifier:n}}s(Ut,"startAuthorization");async function we(e,t,r){let i=pe(t.metadata?.token_endpoint??new URL("/token",e)),n=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});t.resource&&r.set("resource",t.resource),t.addClientAuthentication?await t.addClientAuthentication(n,r,i,t.metadata):vt(_t(t.clientInformation,t.metadata?.token_endpoint_auth_methods_supported??[]),t.clientInformation,n,r);let a=await(t.fetch??globalThis.fetch)(i,{method:"POST",headers:n,body:r,signal:t.signal}),o=await a.text(),c;try{c=JSON.parse(o)}catch{}if(W(c)&&typeof c.error=="string")throw new _(c.error,typeof c.error_description=="string"?c.error_description:c.error,typeof c.error_uri=="string"?c.error_uri:void 0);if(!a.ok)throw new _("server_error",`HTTP ${a.status}: ${o}`);return lt(c)}s(we,"tokenRequest");async function St(e,t){let r=t.metadata?.registration_endpoint;if(t.metadata&&!r)throw new Error("Authorization server does not support dynamic client registration");let i=await(t.fetch??globalThis.fetch)(new URL(r??new URL("/register",e)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.clientMetadata,application_type:t.clientMetadata.application_type??mt(t.clientMetadata.redirect_uris),...t.scope?{scope:t.scope}:{}}),signal:t.signal});if(!i.ok)throw new st(i.status,await i.text());return ht(await i.json())}s(St,"registerClient");async function kt(e,t){return we(e,t,new URLSearchParams({grant_type:"authorization_code",code:t.code,code_verifier:t.codeVerifier,redirect_uri:String(t.redirectUrl)}))}s(kt,"exchangeAuthorizationCode");async function Rt(e,t){let r=await we(e,t,new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken}));return{refresh_token:t.refreshToken,...r}}s(Rt,"refreshAuthorization");function ge(e,t){return e.scope===void 0&&t?{...e,scope:t}:e}s(ge,"withScope");function Et(e,t){if(!t)return;let r=[e,t].flatMap(i=>i?.split(/\s+/).filter(Boolean)??[]);return[...new Set(r)].join(" ")}s(Et,"stepUpScope");async function x(e,t,r={}){let i=t.authorizationServerMetadataUrl&&pe(t.authorizationServerMetadataUrl),n=i?void 0:await e.discoveryState?.(),a=n?.authorizationServerUrl?{authorizationServerUrl:n.authorizationServerUrl,authorizationServerMetadata:n.authorizationServerMetadata??await ue(n.authorizationServerUrl,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:n.resourceMetadata}:await pt(t.serverUrl,{resourceMetadataUrl:t.resourceMetadataUrl,authorizationServerMetadataUrl:i,fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal});i||await e.saveDiscoveryState?.({...a,...t.resourceMetadataUrl?{resourceMetadataUrl:t.resourceMetadataUrl.href}:{}});let o=a.authorizationServerMetadata,c=gt(t.serverUrl,a.resourceMetadata),l=t.scope||a.resourceMetadata?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await e.clientInformation();r.storedClientId=h?.client_id;let d=h?void 0:e.clientMetadataDocument?.(o);if(d){let u=new URL(d.url);if(u.protocol!=="https:"||u.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let f=d?.redirectUrl??String(e.redirectUrl);if(t.authorizationCode&&t.authorizationRedirectUrl!==void 0&&f!==t.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${f}, but the authorization request used ${t.authorizationRedirectUrl}`);let w=h??(d&&{client_id:d.url});if(!w){if(t.refreshOnly)return"REDIRECT";if(t.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!e.saveClientInformation)throw new Error("OAuth client information cannot be persisted");w=await St(a.authorizationServerUrl,{metadata:o,clientMetadata:e.clientMetadata,scope:l,fetch:t.fetch,signal:t.signal}),await e.saveClientInformation(w)}let B={metadata:o,clientInformation:w,resource:c,addClientAuthentication:e.addClientAuthentication,fetch:t.fetch,signal:t.signal};if(t.authorizationCode){let u=t.iss;if((u!==void 0||o?.authorization_response_iss_parameter_supported)&&u!==o?.issuer)throw new ae(o?.issuer,u);let Ie=await kt(a.authorizationServerUrl,{...B,code:t.authorizationCode,codeVerifier:await e.codeVerifier(),redirectUrl:f});return await e.saveTokens(ge(Ie,l)),"AUTHORIZED"}let b=t.skipRefresh?void 0:await e.tokens();if(b?.refresh_token)try{let u=await Rt(a.authorizationServerUrl,{...B,refreshToken:b.refresh_token});return await e.saveTokens(ge(u,b.scope)),"AUTHORIZED"}catch(u){if(t.signal?.aborted||u instanceof se||u instanceof _&&u.code!=="server_error")throw u}if(t.refreshOnly)return"REDIRECT";let Pe=await e.state?.(),q=await Ut(a.authorizationServerUrl,{metadata:o,clientInformation:w,redirectUrl:f,scope:l,state:Pe,resource:c});return await e.saveCodeVerifier(q.codeVerifier),await e.redirectToAuthorization(q.authorizationUrl),"REDIRECT"}s(x,"runFlow");async function $(e,t){let r={};try{return await x(e,t,r)}catch(i){if(i instanceof _&&["invalid_client","unauthorized_client"].includes(i.code)){if(t.refreshOnly){if((await e.clientInformation())?.client_id===r.storedClientId)for(let n of["client","tokens","discovery"])await e.invalidateCredentials?.(n)}else await e.invalidateCredentials?.("all");return x(e,t)}if(i instanceof _&&i.code==="invalid_grant")return await e.invalidateCredentials?.("tokens"),x(e,t);throw i}}s($,"authorizeMcp");var Mt=3e4;function At(e){let{store:t,redirectUrl:r}=e,i,n=s((a,o=globalThis.fetch,c)=>(i??=t.withRefreshLock(async()=>{let l=await t.load();if(l?.tokens?.access_token!==a)return;if(!l?.tokens?.refresh_token)throw new v;let h={...e,settings:e.settings()};if(await me(h,l,{fetch:o,challenge:c,redirectUrl:r})==="REDIRECT")throw new v}).finally(()=>{i=void 0}),i),"refresh");return{token:s(async()=>{await i?.catch(()=>{});let a=await t.load(),o=a?.tokens?.access_token;return!(a?.tokensExpireAt!==void 0&&a.tokensExpireAt-Mt<=Date.now())||!a?.tokens?.refresh_token?o:(await n(o).catch(()=>{}),(await t.load())?.tokens?.access_token)},"token"),onUnauthorized:s(async a=>{let o=dt(a.response.headers.get("www-authenticate"));if(e.onChallenge(o),o.error==="insufficient_scope")throw new v;await n(a.token,a.fetch,o)},"onUnauthorized"),settled:s(async()=>{await i?.catch(()=>{})},"settled")}}s(At,"createMcpAuthProvider");async function me(e,t,r={}){let i=[r.redirectUrl,ne(e.settings).fixedRedirectUrl,O(t.clientInformation)[0]].filter(n=>n!==void 0).find(n=>e.clientMetadataDocuments?.listsRedirectUrl(n))??ie;return $(P(e,i),{serverUrl:e.serverUrl,resourceMetadataUrl:r.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl,fetch:te(r.fetch),refreshOnly:!0})}s(me,"refreshStoredTokens");import{createServer as Ct}from"node:http";function bt(e){return e.ok?"Authorization complete. You may close this window.":e.details?`${e.message}
2
2
 
3
3
  ${e.details}`:e.message}s(bt,"plainText");var _e=class ze{static{s(this,"_OAuthCallbackServer")}redirectUrl;server;paths;timeoutMs;renderPage;pending=new Map;constructor(t,r,i,n,a){this.server=t,this.redirectUrl=r,this.paths=i,this.timeoutMs=n,this.renderPage=a}static async listen(t={}){let r=t.host??"127.0.0.1",i=t.redirectHost??r,n=t.path??"/callback",a,o=Ct((l,h)=>a?.handle(l.url??"/",h));await new Promise((l,h)=>{o.once("error",h),o.listen(t.port??0,r,()=>{o.off("error",h),l()})});let c=o.address();if(!c||typeof c=="string")throw new Error("OAuth callback server did not bind to TCP");return a=new ze(o,`http://${i.includes(":")?`[${i}]`:i}:${c.port}${n}`,[n,...t.extraPaths??[]],t.timeoutMs??5*6e4,t.renderPage),a}waitForCallback(t,r){if(this.pending.has(t))throw new Error("OAuth state is already pending");return new Promise((i,n)=>{let a=setTimeout(()=>{this.pending.delete(t),n(new Error("OAuth callback timed out"))},this.timeoutMs);this.pending.set(t,{resolve:i,reject:n,timer:a,path:r})})}async close(){for(let r of this.pending.values())clearTimeout(r.timer),r.reject(new Error("OAuth callback server closed"));this.pending.clear();let t=new Promise((r,i)=>{this.server.close(n=>n?i(n):r())});this.server.closeAllConnections(),await t}reply(t,r,i){this.renderPage?(t.writeHead(r,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),t.end(this.renderPage(i))):t.writeHead(r,{"content-type":"text/plain; charset=utf-8"}).end(bt(i))}handle(t,r){let i=new URL(t,this.redirectUrl);if(!this.paths.includes(i.pathname)){this.reply(r,404,{ok:!1,message:"Not found"});return}let n=i.searchParams.get("state"),a=n?this.pending.get(n):void 0;if(!n||!a){this.reply(r,400,{ok:!1,message:"Invalid or expired OAuth state"});return}if(clearTimeout(a.timer),this.pending.delete(n),a.path!==void 0&&i.pathname!==a.path){a.reject(new Error("The authorization response arrived on another redirect URI")),this.reply(r,400,{ok:!1,message:"Unexpected redirect URI"});return}let o=i.searchParams.get("error");if(o){let h=i.searchParams.get("error_description")??o;a.reject(new Error(h)),this.reply(r,200,{ok:!1,message:"Authorization failed. You may close this window.",details:h});return}let c=i.searchParams.get("code");if(!c){a.reject(new Error("OAuth callback did not include an authorization code")),this.reply(r,400,{ok:!1,message:"Missing authorization code"});return}let l=i.searchParams.get("iss");a.resolve({code:c,state:n,...l?{iss:l}:{}}),this.reply(r,200,{ok:!0})}},g=class extends Error{static{s(this,"McpSignInCancelledError")}constructor(){super("Sign-in cancelled"),this.name="McpSignInCancelledError"}};async function Tt(e){if(e.signal?.aborted)throw new g;let t=e.challenge?.error==="insufficient_scope";return!t&&await zt(e)==="AUTHORIZED"?{kind:"authorized"}:D(e.signal,()=>It(e,t))}s(Tt,"startMcpSignIn");async function zt(e){let{store:t,settings:r,challenge:i,redirectUrl:n,signal:a}=e,o=t.withRefreshLock(async()=>{if(a?.aborted)return"REDIRECT";let c=await t.load();return!c?.tokens?.refresh_token||r.clientRegistration==="cimd"&&c.clientInformation&&!r.clientId?"REDIRECT":me(e,c,{challenge:i,redirectUrl:n})});try{return await Pt(a,o)}catch(c){if(c instanceof oe)return"REDIRECT";throw c}}s(zt,"refreshBeforeSignIn");function Pt(e,t){return e?new Promise((r,i)=>{let n=s(()=>i(new g),"abort");e.addEventListener("abort",n,{once:!0}),t.then(r,i).finally(()=>e.removeEventListener("abort",n))}):t}s(Pt,"untilAborted");async function It(e,t){let{store:r,settings:i,redirectUrl:n,challenge:a}=e,o=await r.load();o&&await r.save(Ot(o,e));let c,l=P(e,n,f=>{c=f}),h=Lt(i.scope,t?Et(o?.tokens?.scope,a?.scope):a?.scope);if(await $(l,{...ve(e),scope:h,skipRefresh:!0}),!c)throw new Error("OAuth flow did not produce an authorization URL");let d=c.searchParams.get("scope");return{kind:"redirect",authorizationUrl:c.href,redirectUrl:c.searchParams.get("redirect_uri")??n,state:await l.state(),...d?{scope:d}:{}}}s(It,"startBrowserStep");function Ot(e,t){let{settings:r,redirectUrl:i}=t,n={...e};return delete n.oauthState,r.clientId||(e.clientInformation?r.clientRegistration!=="cimd"&&O(e.clientInformation).includes(i):I(r,t.clientMetadataDocuments,i))||(delete n.clientInformation,delete n.tokens,delete n.tokensExpireAt),n}s(Ot,"stateForSignIn");function Lt(...e){let t=[...new Set(e.flatMap(r=>r?.split(/\s+/).filter(Boolean)??[]))];return t.length>0?t.join(" "):void 0}s(Lt,"mergeScopes");async function xt(e){await D(e.signal,async()=>{let{authorization:t,response:r}=e;if(r.state!==t.state)throw new Error("The authorization response belongs to a different sign-in");if((await e.store.load())?.oauthState!==t.state)throw new Error("Another sign-in to this MCP server started since; sign in again");await $(P(e,e.redirectUrl),{...ve(e),scope:t.scope,authorizationRedirectUrl:t.redirectUrl,authorizationCode:r.code,iss:r.iss})})}s(xt,"completeMcpSignIn");function ve(e){return{serverUrl:e.serverUrl,fetch:te(),signal:e.signal,resourceMetadataUrl:e.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl}}s(ve,"flowOptions");async function D(e,t){if(e?.aborted)throw new g;try{return await t()}catch(r){throw e?.aborted?new g:r}}s(D,"cancellable");async function $t(e){let{settings:t}=e,r=ne(t),i=O((await e.store.load())?.clientInformation)[0],n=r.port??(i&&Number(new URL(i).port)||void 0),a=I(t,e.clientMetadataDocuments,r.url),o={host:r.host,redirectHost:r.redirectHost,path:r.path,extraPaths:a?[X(r.path,e.serverUrl)]:[],renderPage:e.renderPage},c;try{c=await _e.listen({...o,port:n??0})}catch(l){if(r.port!==void 0||n===void 0)throw l;c=await _e.listen(o)}return{callback:c,redirectUrl:r.fixedRedirectUrl??c.redirectUrl}}s($t,"listenForLoopbackSignIn");async function Dt(e){let{authorization:t}=e,r=new AbortController,i=e.signal?AbortSignal.any([r.signal,e.signal]):r.signal,n=e.callback.waitForCallback(t.state,new URL(t.redirectUrl).pathname),a=e.promptForRedirectUrl?e.promptForRedirectUrl(i).then(o=>{if(!o?.trim())throw new g;return Ht(o,t)}):new Promise((o,c)=>{i.addEventListener("abort",()=>c(new g),{once:!0})});try{return await D(e.signal,()=>Promise.race([n,a]))}finally{r.abort(),n.catch(()=>{}),a.catch(()=>{})}}s(Dt,"waitForLoopbackSignIn");function Ht(e,t){let r;try{r=new URL(e.trim())}catch{throw new Error("Expected the full redirect URL from the browser address bar")}let i=new URL(t.redirectUrl);if(r.origin!==i.origin||r.pathname!==i.pathname)throw new Error("The redirect URL does not match this sign-in's redirect URI");let n=r.searchParams.get("error");if(n)throw new Error(r.searchParams.get("error_description")??n);let a=r.searchParams.get("state");if(a!==t.state)throw new Error("The redirect URL belongs to a different sign-in");let o=r.searchParams.get("code");if(!o)throw new Error("The redirect URL does not contain an authorization code");let c=r.searchParams.get("iss");return{code:o,state:a,...c?{iss:c}:{}}}s(Ht,"responseFromRedirectUrl");import{createHash as Nt}from"node:crypto";import{mkdirSync as Ft}from"node:fs";import{join as ye}from"node:path";var Vt='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>';function A(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}s(A,"escapeHtml");function Ue(e){let t=A(e.title),r=A(e.heading),i=A(e.message),n=e.details?A(e.details):void 0;return`<!doctype html>
4
4
  <html lang="en">
@@ -0,0 +1,30 @@
1
+ var Te=Object.defineProperty;var d=(s,e)=>Te(s,"name",{value:e,configurable:!0});import{createRequire as Fe}from"node:module";const It=Fe(import.meta.url);import{fill as De}from"./chunk-G5AMLGXC.js";import{APP_NAME as Me,APP_TITLE as Ne,getAgentDir as $,getSessionsDir as Ae,normalizePath as b,pathsEqual as Re,resolvePath as S}from"./chunk-R47JBGS3.js";import{reportNewerDataFormat as Be,t as Oe,writeFileAtomicSync as Le}from"./chunk-QU2VEHMW.js";import{uuidv7 as $e}from"./chunk-IEBK4HQA.js";import{getCurrentSystemMessage as Pe}from"./chunk-5MF5GEDD.js";var je=`The conversation history before this point was compacted into the following summary:
2
+
3
+ <summary>
4
+ `,ke=`
5
+ </summary>`,Ue=`The following is a summary of a branch that this conversation came back from:
6
+
7
+ <summary>
8
+ `,He="</summary>";function Ve(s){let e=`Ran \`${s.command}\`
9
+ `;return s.output?e+=`\`\`\`
10
+ ${s.output}
11
+ \`\`\``:e+="(no output)",s.cancelled?e+=`
12
+
13
+ (command cancelled)`:s.exitCode!==null&&s.exitCode!==void 0&&s.exitCode!==0&&(e+=`
14
+
15
+ Command exited with code ${s.exitCode}`),s.truncated&&s.fullOutputPath&&(e+=`
16
+
17
+ [Output truncated. Full output: ${s.fullOutputPath}]`),e}d(Ve,"bashExecutionToText");function se(s,e,t){return{role:"branchSummary",summary:s,fromId:e,timestamp:new Date(t).getTime()}}d(se,"createBranchSummaryMessage");function ne(s,e,t){return{role:"compactionSummary",summary:s,tokensBefore:e,timestamp:new Date(t).getTime()}}d(ne,"createCompactionSummaryMessage");function re(s,e,t,i,n){return{role:"custom",customType:s,content:e,display:t,details:i,timestamp:new Date(n).getTime()}}d(re,"createCustomMessage");var Ye="compaction-summary",Ke="branch-summary",P="dal-context";function Xe(s){let e=s.replace(/[^A-Za-z0-9._:-]/g,"_")||"context";return`<${P} type="${e}">
18
+ `}d(Xe,"injectedContextOpen");var j=`
19
+ </${P}>`;function k(s,e){let t=Xe(s);if(typeof e=="string")return[{type:"text",text:t+e+j}];let i=e.findIndex(r=>r.type==="text");if(i===-1)return[{type:"text",text:t},...e,{type:"text",text:j}];let n=e.findLastIndex(r=>r.type==="text");return e.map((r,o)=>{if(r.type!=="text"||o!==i&&o!==n)return r;let a=(o===i?t:"")+r.text+(o===n?j:"");return{...r,text:a}})}d(k,"wrapInjectedContext");function We(s){return s.map(e=>{switch(e.role){case"bashExecution":return e.excludeFromContext?void 0:{role:"user",content:[{type:"text",text:Ve(e)}],timestamp:e.timestamp};case"custom":return{role:"user",content:k(e.customType,e.content),timestamp:e.timestamp};case"branchSummary":return{role:"user",content:k(Ke,Ue+e.summary+He),timestamp:e.timestamp};case"compactionSummary":return{role:"user",content:k(Ye,je+e.summary+ke),timestamp:e.timestamp};case"system":case"user":case"assistant":case"toolResult":return e;default:let t=e;return}}).filter(e=>e!==void 0)}d(We,"convertToLlm");import{randomUUID as oe}from"crypto";import{appendFileSync as ae,closeSync as A,createReadStream as ze,existsSync as _,mkdirSync as U,openSync as R,readdirSync as le,readSync as H,realpathSync as Je,statSync as V,writeFileSync as Y}from"fs";import{readdir as K,stat as de}from"fs/promises";import{basename as ue,join as v,resolve as pe}from"path";import{createInterface as Ze}from"readline";import{StringDecoder as fe}from"string_decoder";var T=3;function he(s){return typeof s?.version=="number"&&s.version>T}d(he,"isNewerSessionFormat");function X(){return $e()}d(X,"createSessionId");function W(s){if(!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(s))throw new Error("Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character")}d(W,"assertValidSessionId");function g(s){for(let e=0;e<100;e++){let t=oe().slice(0,8);if(!s.has(t))return t}return oe()}d(g,"generateId");function qe(s){let e=new Set,t=null;for(let i of s){if(i.type==="session"){i.version=2;continue}if(i.id=g(e),i.parentId=t,t=i.id,i.type==="compaction"){let n=i;if(typeof n.firstKeptEntryIndex=="number"){let r=s[n.firstKeptEntryIndex];r&&r.type!=="session"&&(n.firstKeptEntryId=r.id),delete n.firstKeptEntryIndex}}}}d(qe,"migrateV1ToV2");function Ge(s){for(let e of s){if(e.type==="session"){e.version=3;continue}if(e.type==="message"){let t=e;t.message&&t.message.role==="hookMessage"&&(t.message.role="custom")}}}d(Ge,"migrateV2ToV3");function me(s){let e=s.find(t=>t.type==="session")?.version??1;return e>=T?!1:(e<2&&qe(s),e<3&&Ge(s),!0)}d(me,"migrateToCurrentVersion");function Qe(s){me(s)}d(Qe,"migrateSessionEntries");function et(s){let e=[],t=s.trim().split(`
20
+ `);for(let i of t)if(i.trim())try{let n=JSON.parse(i);e.push(n)}catch{}return e}d(et,"parseSessionEntries");function tt(s){for(let e=s.length-1;e>=0;e--)if(s[e].type==="compaction")return s[e];return null}d(tt,"getLatestCompactionEntry");function it(s,e){if(e)return e;let t=new Map;for(let i of s)t.set(i.id,i);return t}d(it,"buildEntryIndex");function ce(s,e,t){let i=it(s,t),n;if(e===null)return[];if(e&&(n=i.get(e)),n??=s[s.length-1],!n)return[];let r=[],o=n;for(;o;)r.push(o),o=o.parentId?i.get(o.parentId):void 0;return r.reverse(),r}d(ce,"buildSessionPath");function st(s){let e="off",t=null;for(let i of s)i.type==="thinking_level_change"?e=i.thinkingLevel:i.type==="model_change"?t={provider:i.provider,modelId:i.modelId}:i.type==="message"&&i.message.role==="assistant"&&(t={provider:i.message.provider,modelId:i.message.model});return{thinkingLevel:e,model:t}}d(st,"getSessionContextSettings");function ye(s){if(s.type==="message"){let e=s.message;return e.role==="system"&&e.content==null?[{...e,content:""}]:(e.role==="user"||e.role==="assistant"||e.role==="toolResult")&&e.content==null?[{...e,content:[]}]:[e]}if(s.type==="custom_message")return[re(s.customType,s.content??[],s.display,s.details,s.timestamp)];if(s.type==="branch_summary"&&s.summary)return[se(s.summary,s.fromId,s.timestamp)];if(s.type==="compaction"){let e=ne(s.summary,s.tokensBefore,s.timestamp);return s.systemMessage?[s.systemMessage,e]:[e]}return[]}d(ye,"sessionEntryToContextMessages");function z(s,e,t){let i=ce(s,e,t),n=null;for(let u of i)u.type==="compaction"&&(n=u);if(!n)return i;let r=i.findIndex(u=>u.id===n.id);if(r<0)return i;let o=[n],a=!1;for(let u=0;u<r;u++){let l=i[u];l.id===n.firstKeptEntryId&&(a=!0),a&&!(l.type==="message"&&l.message.role==="system")&&o.push(l)}return o.push(...i.slice(r+1)),o}d(z,"buildContextEntries");function Ie(s,e){let t=ye(s);if(!e)return t;let i=e.replacement;return i===null?[]:t.map(n=>{if(n.role!=="user"&&n.role!=="assistant"&&n.role!=="toolResult"&&n.role!=="custom")return n;let r=(n.role==="assistant"||n.role==="toolResult")&&typeof i.content=="string"?[{type:"text",text:i.content}]:i.content;return{...n,content:r}})}d(Ie,"projectContextEntry");function J(s,e,t){let i=ce(s,e,t),{thinkingLevel:n,model:r}=st(i),o=z(s,e,t),a=new Map;for(let l of o)l.type==="context_edit"&&a.set(l.targetId,l);let u=o.map((l,p)=>({sourceEntry:l,messages:l.type==="compaction"&&p>0?[]:Ie(l,a.get(l.id))}));return{entries:u,messages:u.flatMap(l=>l.messages),thinkingLevel:n,model:r}}d(J,"buildSessionProjection");function nt(s,e,t){let{messages:i,thinkingLevel:n,model:r}=J(s,e,t);return{messages:i,thinkingLevel:n,model:r}}d(nt,"buildSessionContext");function ge(s,e){let t=`--${s.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`;return v(S(e),"sessions",t)}d(ge,"sessionDirFor");function rt(s){let e=S(s);try{return Je.native(e)}catch{return e}}d(rt,"realCwd");function Se(s,e=$()){return ge(rt(s),e)}d(Se,"getDefaultSessionDirPath");function D(s,e=$()){let t=Se(s,e),i=ge(S(s),e);return i!==t&&_(i)?[t,i]:[t]}d(D,"getDefaultSessionDirs");function F(s,e=$()){let t=Se(s,e);return _(t)||U(t,{recursive:!0}),t}d(F,"getDefaultSessionDir");var ot=1024*1024,at=4096,Z=1024*1024,we=class extends Error{static{d(this,"SessionHeaderScanLimitError")}constructor(s){super(`Session header exceeds ${Z}-byte scan limit: ${s}`),this.name="SessionHeaderScanLimitError"}};function B(s){if(!s.trim())return null;try{return JSON.parse(s)}catch{return null}}d(B,"parseSessionEntryLine");function q(s){let e=b(s);if(!_(e))return[];let t=[],i="",n=R(e,"r");try{let o=new fe("utf8"),a=Buffer.allocUnsafe(ot);for(;;){let l=H(n,a,0,a.length,null);if(l===0)break;i+=o.write(a.subarray(0,l));let p=0,m=i.indexOf(`
21
+ `,p);for(;m!==-1;){let c=B(i.slice(p,m));c&&t.push(c),p=m+1,m=i.indexOf(`
22
+ `,p)}i=i.slice(p)}i+=o.end();let u=B(i);u&&t.push(u)}finally{A(n)}if(t.length===0)return t;let r=t[0];return r.type!=="session"||typeof r.id!="string"?[]:(i&&ae(e,`
23
+ `),t)}d(q,"loadEntriesFromFile");function G(s){if(!s.trim())return;let e=B(s);if(e)return e.type!=="session"||typeof e.id!="string"?null:e}d(G,"parseSessionHeaderCandidate");function Ee(s){let e=R(s,"r");try{let t=new fe("utf8"),i=Buffer.allocUnsafe(at),n=[],r=0;for(;r<Z;){let a=Math.min(i.length,Z-r),u=H(e,i,0,a,null);if(u===0)return n.push(t.end()),G(n.join(""))??null;r+=u;let l=t.write(i.subarray(0,u)),p=0,m=l.indexOf(`
24
+ `,p);for(;m!==-1;){n.push(l.slice(p,m));let c=G(n.join(""));if(c!==void 0)return c;n.length=0,p=m+1,m=l.indexOf(`
25
+ `,p)}n.push(l.slice(p))}let o=Buffer.allocUnsafe(1);if(H(e,o,0,o.length,null)===0)return n.push(t.end()),G(n.join(""))??null;throw new we(s)}finally{A(e)}}d(Ee,"readSessionHeader");function be(s){try{return Ee(s)}catch{return null}}d(be,"readSessionHeaderForDiscovery");function Q(s){let e=s.cwd;return typeof e=="string"?e:void 0}d(Q,"getSessionHeaderCwd");function ee(s,e){return s!==void 0&&s!==""&&Re(S(s),e)}d(ee,"sessionCwdMatches");function _e(s,e){let t=b(s),i=e?S(e):void 0;try{let n=le(t).filter(r=>r.endsWith(".jsonl")).map(r=>v(t,r)).map(r=>({path:r,mtime:V(r).mtimeMs})).sort((r,o)=>o.mtime-r.mtime);for(let{path:r}of n){let o=be(r);if(o&&(!i||ee(Q(o),i)))return r}return null}catch{return null}}d(_e,"findMostRecentSession");function ve(s){return typeof s.role=="string"&&"content"in s}d(ve,"isMessageWithContent");function lt(s){let e=s.content;return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(" ")}d(lt,"extractTextContent");function dt(s){let e=s.message;if(!ve(e)||e.role!=="user"&&e.role!=="assistant")return;let t=e.timestamp;if(typeof t=="number")return t;let i=new Date(s.timestamp).getTime();return Number.isNaN(i)?void 0:i}d(dt,"getMessageActivityTime");async function ut(s,e,t){try{let i=t??await de(s),n=null,r=0,o="",a=[],u,l,p=Ze({input:ze(s,{encoding:"utf8",signal:e}),crlfDelay:1/0});for await(let w of p){let f=B(w);if(!f)continue;if(!n){if(f.type!=="session")return null;n=f;continue}if(f.type==="session_info"&&(u=f.name?.trim()||void 0),f.type!=="message")continue;r++;let h=dt(f);typeof h=="number"&&(l=Math.max(l??0,h));let y=f.message;if(!ve(y)||y.role!=="user"&&y.role!=="assistant")continue;let x=lt(y);x&&(a.push(x),!o&&y.role==="user"&&(o=x))}if(!n)return null;let m=typeof n.cwd=="string"?n.cwd:"",c=n.parentSession,I=typeof n.timestamp=="string"?new Date(n.timestamp).getTime():NaN,E=typeof l=="number"&&l>0?new Date(l):Number.isNaN(I)?i.mtime:new Date(I);return{path:s,id:n.id,cwd:m,name:u,parentSessionPath:c,created:new Date(n.timestamp),modified:E,messageCount:r,firstMessage:o||"(no messages)",allMessagesText:a.join(" ")}}catch{return e?.throwIfAborted(),null}}d(ut,"buildSessionInfo");var pt=10,Ce=64,ft=10,ht=100;async function te(s,e,t,i){let n=new Array(s.length),r=0,o=d(async()=>{for(;r<s.length;){i?.throwIfAborted();let a=r++;n[a]=await t(s[a],a)}},"worker");return await Promise.all(Array.from({length:Math.min(e,s.length)},()=>o())),n}d(te,"mapWithConcurrency");function M(s){return s.sort((e,t)=>t.modified.getTime()-e.modified.getTime())}d(M,"sortSessionInfos");function xe(s,e,t){return te(s,pt,async(i,n)=>{let r=await ut(i.path,t,i.stats);return e(r,n),r},t)}d(xe,"buildSessionInfosWithConcurrency");async function ie(s,e,t){if(t?.throwIfAborted(),!_(s))return[];try{let i=(await K(s)).filter(a=>a.endsWith(".jsonl")).sort((a,u)=>u.localeCompare(a)).map(a=>({path:v(s,a)})),n=i.length,r=[],o=0;return(await xe(i,a=>{o++,a&&r.push(a);let u=o===1||o%ft===0||o===i.length;e?.(o,n,u?M([...r]):void 0)},t)).filter(a=>a!==null)}catch{return t?.throwIfAborted(),[]}}d(ie,"listSessionsFromDir");var mt=class C{static{d(this,"_SessionManager")}sessionId="";sessionFile;sessionDir;cwd;persist;flushed=!1;newerFormat=!1;fileEntries=[];byId=new Map;labelsById=new Map;labelTimestampsById=new Map;leafId=null;constructor(e,t,i,n,r,o){this.cwd=S(e),this.sessionDir=b(t),this.persist=n,n&&this.sessionDir&&!_(this.sessionDir)&&U(this.sessionDir,{recursive:!0}),i?this._setSessionFile(i,o):o?.length?this._loadEntries(o,r):this.newSession(r)}setSessionFile(e){this._setSessionFile(e)}_setSessionFile(e,t){if(this.sessionFile=S(e),_(this.sessionFile)){let i=t??q(this.sessionFile);if(i.length===0){let n=this.sessionFile;if(V(n).size>0)throw new Error(`Session file is not a valid ${Me} session: ${n}`);this.newSession(),this.sessionFile=n,this._rewriteFile(),this.flushed=!0;return}this._loadEntries(i),this.flushed=!0}else{let i=this.sessionFile;this.newSession(),this.sessionFile=i}}newSession(e){e?.id!==void 0&&W(e.id),this.sessionId=e?.id??X();let t=new Date().toISOString(),i={type:"session",version:T,id:this.sessionId,timestamp:t,cwd:this.cwd,parentSession:e?.parentSession};if(this.fileEntries=[i],this.newerFormat=!1,this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.flushed=!1,this.persist){let n=t.replace(/[:.]/g,"-");this.sessionFile=v(this.getSessionDir(),`${n}_${this.sessionId}.jsonl`)}return this.sessionFile}_loadEntries(e,t){let i=e.find(n=>n.type==="session");i?(this.fileEntries=e,this.sessionId=i.id,this.newerFormat=he(i),this.newerFormat?Be(this.sessionFile??i.id):me(this.fileEntries)&&this._rewriteFile()):(this.newSession(t),this.fileEntries=this.fileEntries.concat(e)),this._buildIndex()}_buildIndex(){this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null;for(let e of this.fileEntries)e.type!=="session"&&(this.byId.set(e.id,e),this.leafId=e.id,e.type==="label"&&(e.label?(this.labelsById.set(e.targetId,e.label),this.labelTimestampsById.set(e.targetId,e.timestamp)):(this.labelsById.delete(e.targetId),this.labelTimestampsById.delete(e.targetId))))}_rewriteFile(){!this.persist||!this.sessionFile||this.newerFormat||Le(this.sessionFile,this.fileEntries.map(e=>`${JSON.stringify(e)}
26
+ `).join(""))}isPersisted(){return this.persist}isReadOnly(){return this.newerFormat}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}usesDefaultSessionDir(){return D(this.cwd).includes(this.sessionDir)}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}_hasConversation(){return this.fileEntries.some(e=>e.type==="message"&&(e.message.role==="user"||e.message.role==="assistant"))}_persist(e){if(!(!this.persist||!this.sessionFile||this.newerFormat))if(this.flushed)ae(this.sessionFile,`${JSON.stringify(e)}
27
+ `);else{if(!this._hasConversation())return;let t=R(this.sessionFile,"wx");try{for(let i of this.fileEntries)Y(t,`${JSON.stringify(i)}
28
+ `)}finally{A(t)}this.flushed=!0}}_appendEntry(e){let t=this.leafId;this.fileEntries.push(e),this.byId.set(e.id,e),this.leafId=e.id;try{this._persist(e)}catch(i){throw this.fileEntries.pop(),this.byId.delete(e.id),this.leafId=t,i}}appendMessage(e){let t={type:"message",id:g(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),message:e};return this._appendEntry(t),t.id}appendThinkingLevelChange(e){let t={type:"thinking_level_change",id:g(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),thinkingLevel:e};return this._appendEntry(t),t.id}appendModelChange(e,t){let i={type:"model_change",id:g(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),provider:e,modelId:t};return this._appendEntry(i),i.id}appendUsage(e,t,i,n,r){let o={type:"usage",id:g(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),kind:e,provider:t,model:i,usage:n,...r?{note:r}:{}};return this._appendEntry(o),o}appendCompaction(e,t,i,n,r,o){let a=new Date().toISOString(),u=Pe(this.buildSessionProjection().messages),l=g(this.byId),p={type:"compaction",id:l,parentId:this.leafId,timestamp:a,summary:e,firstKeptEntryId:t??l,tokensBefore:i,details:n,usage:o,fromHook:r,...u?{systemMessage:{...u,timestamp:new Date(a).getTime()}}:{}};return this._appendEntry(p),p.id}appendCustomEntry(e,t){let i={type:"custom",customType:e,data:t,id:g(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(i),i.id}appendSessionInfo(e){let t=e.replace(/[\r\n]+/g," ").trim(),i={type:"session_info",id:g(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),name:t};return this._appendEntry(i),i.id}getSessionName(){for(let e=this.fileEntries.length-1;e>=0;e--){let t=this.fileEntries[e];if(t.type==="session_info")return t.name?.trim()||void 0}}appendCustomMessageEntry(e,t,i,n){let r={type:"custom_message",customType:e,content:t,display:i,details:n,id:g(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(r),r.id}appendContextEdit(e,t){if(t!==null&&(typeof t!="object"||!("content"in t)||typeof t.content!="string"&&!Array.isArray(t.content)))throw new Error("Context edit replacement must be null or contain string/array content");let i=this.byId.get(e);if(!i)throw new Error(`Entry ${e} not found`);if(!this.getBranch().some(a=>a.id===e))throw new Error(`Entry ${e} is not on the active branch`);if(!(i.type==="custom_message"||i.type==="message"&&(i.message.role==="user"||i.message.role==="assistant"||i.message.role==="toolResult")))throw new Error(`Entry ${e} does not contribute editable model content`);let n=i.type==="message"?i.message.role:"custom",r=t!==null&&(n==="assistant"||n==="toolResult")&&typeof t.content=="string"?{content:[{type:"text",text:t.content}]}:t,o={type:"context_edit",id:g(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId:e,replacement:r};return this._appendEntry(o),o.id}getLeafId(){return this.leafId}getLeafEntry(){return this.leafId?this.byId.get(this.leafId):void 0}getEntry(e){return this.byId.get(e)}getChildren(e){let t=[];for(let i of this.byId.values())i.parentId===e&&t.push(i);return t}getLabel(e){return this.labelsById.get(e)}appendLabelChange(e,t){if(!this.byId.has(e))throw new Error(`Entry ${e} not found`);let i={type:"label",id:g(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId:e,label:t};return this._appendEntry(i),t?(this.labelsById.set(e,t),this.labelTimestampsById.set(e,i.timestamp)):(this.labelsById.delete(e),this.labelTimestampsById.delete(e)),i.id}getBranch(e){let t=[],i=e??this.leafId,n=i?this.byId.get(i):void 0;for(;n;)t.push(n),n=n.parentId?this.byId.get(n.parentId):void 0;return t.reverse(),t}buildContextEntries(){return z(this.getEntries(),this.leafId,this.byId)}buildSessionProjection(){return J(this.getEntries(),this.leafId,this.byId)}buildSessionContext(){let{messages:e,thinkingLevel:t,model:i}=this.buildSessionProjection();return{messages:e,thinkingLevel:t,model:i}}getHeader(){return this.fileEntries.find(t=>t.type==="session")||null}getEntryCount(){return this.byId.size}getEntries(){return this.fileEntries.filter(e=>e.type!=="session")}getTree(){let e=this.getEntries(),t=new Map,i=[];for(let r of e){let o=this.labelsById.get(r.id),a=this.labelTimestampsById.get(r.id);t.set(r.id,{entry:r,children:[],label:o,labelTimestamp:a})}for(let r of e){let o=t.get(r.id);if(r.parentId===null||r.parentId===r.id)i.push(o);else{let a=t.get(r.parentId);a?a.children.push(o):i.push(o)}}let n=[...i];for(;n.length>0;){let r=n.pop();r.children.sort((o,a)=>new Date(o.entry.timestamp).getTime()-new Date(a.entry.timestamp).getTime()),n.push(...r.children)}return i}branch(e){if(!this.byId.has(e))throw new Error(`Entry ${e} not found`);this.leafId=e}resetLeaf(){this.leafId=null}branchWithSummary(e,t,i,n,r){if(e!==null&&!this.byId.has(e))throw new Error(`Entry ${e} not found`);let o=this.leafId??"root";this.leafId=e;let a={type:"branch_summary",id:g(this.byId),parentId:e,timestamp:new Date().toISOString(),fromId:o,summary:t,details:i,usage:r,fromHook:n};return this._appendEntry(a),a.id}createBranchedSession(e){let t=this.sessionFile,i=this.getBranch(e);if(i.length===0)throw new Error(`Entry ${e} not found`);let n=[],r=new Map,o=[],a=null;for(let h of i){if(h.type==="label"){o.push(h.id);continue}for(let y of o)r.set(y,h.id);o.length=0,n.push(h.type==="compaction"?{...h,parentId:a,firstKeptEntryId:h.firstKeptEntryId===h.id?h.id:r.get(h.firstKeptEntryId)??h.firstKeptEntryId}:{...h,parentId:a}),a=h.id}let u=X(),l=new Date().toISOString(),p=l.replace(/[:.]/g,"-"),m=v(this.getSessionDir(),`${p}_${u}.jsonl`),c={type:"session",version:T,id:u,timestamp:l,cwd:this.cwd,parentSession:this.persist?t:void 0},I=new Set(n.map(h=>h.id)),E=[];for(let[h,y]of this.labelsById)I.has(h)&&E.push({targetId:h,label:y,timestamp:this.labelTimestampsById.get(h)});if(this.persist){let h=n[n.length-1]?.id||null,y=[];for(let{targetId:x,label:N,timestamp:O}of E){let L={type:"label",id:g(new Set(I)),parentId:h,timestamp:O,targetId:x,label:N};I.add(L.id),y.push(L),h=L.id}return this.fileEntries=[c,...n,...y],this.sessionId=u,this.sessionFile=m,this._buildIndex(),this._hasConversation()?(this._rewriteFile(),this.flushed=!0):this.flushed=!1,m}let w=[],f=n[n.length-1]?.id||null;for(let{targetId:h,label:y,timestamp:x}of E){let N={type:"label",id:g(new Set([...I,...w.map(O=>O.id)])),parentId:f,timestamp:x,targetId:h,label:y};w.push(N),f=N.id}this.fileEntries=[c,...n,...w],this.sessionId=u,this._buildIndex()}static create(e,t,i){let n=t?b(t):F(e);return new C(e,n,void 0,!0,i)}static open(e,t,i){let n=S(e),r=null,o;if(i===void 0&&_(n))try{r=Ee(n)}catch(l){if(!(l instanceof we))throw l;o=q(n);let p=o[0];r=p?.type==="session"?p:null}let a=i??(r?Q(r):void 0)??process.cwd(),u=t?b(t):pe(n,"..");return new C(a,u,n,!0,void 0,o)}static continueRecent(e,t){let i=t?b(t):F(e),n=D(e);if(n.includes(i)){let o=n.map(a=>_e(a)).filter(a=>a!==null).map(a=>({path:a,mtime:V(a).mtimeMs})).sort((a,u)=>u.mtime-a.mtime)[0];return o?new C(e,pe(o.path,".."),o.path,!0):new C(e,n[0],void 0,!0)}let r=_e(i,e);return r?new C(e,i,r,!0):new C(e,i,void 0,!0)}static inMemory(e=process.cwd(),t,i){return new C(e,"",void 0,!1,t,i)}static forkFrom(e,t,i,n){let r=S(e),o=S(t),a=q(r);if(a.length===0)throw new Error(`Cannot fork: source session file is empty or invalid: ${r}`);let u=a.find(f=>f.type==="session");if(!u)throw new Error(`Cannot fork: source session has no header: ${r}`);if(he(u))throw new Error(De(Oe("{path} \u7531\u66F4\u65B0\u7248\u672C\u7684 {app} \u5199\u5165\uFF0C\u5F53\u524D\u7248\u672C\u53EA\u8BFB\uFF0C\u4E0D\u4F1A\u6539\u52A8\u5B83\uFF1B\u8BF7\u5347\u7EA7 {app}\u3002"),{path:r,app:Ne}));let l=i?b(i):F(o);_(l)||U(l,{recursive:!0}),n?.id!==void 0&&W(n.id);let p=n?.id??X(),m=new Date().toISOString(),c=m.replace(/[:.]/g,"-"),I=v(l,`${c}_${p}.jsonl`),E={type:"session",version:T,id:p,timestamp:m,cwd:o,parentSession:r},w=R(I,"wx");try{Y(w,`${JSON.stringify(E)}
29
+ `);for(let f of a)f.type!=="session"&&Y(w,`${JSON.stringify(f)}
30
+ `)}finally{A(w)}return new C(o,l,I,!0)}static findById(e,t,i){let n=i?b(i):F(e),r=D(e),o=!r.includes(n),a=o?[n]:r,u=S(e);for(let l of a)try{for(let p of le(l)){if(!p.endsWith(".jsonl"))continue;let m=v(l,p),c=be(m);if(c?.id===t&&!(o&&!ee(Q(c),u)))return m}}catch{}}static async list(e,t,i,n){let r=D(e),o=t?b(t):F(e),a=!r.includes(o),u=S(e),l=d(m=>!a||ee(m.cwd,u),"includeSession"),p=(await ie(o,i?(m,c,I)=>i(m,c,I?.filter(l)):void 0,n)).filter(l);if(!a)for(let m of r.filter(c=>c!==o))p.push(...await ie(m,void 0,n));return M(p)}static async listAll(e,t,i){let n=typeof e=="string"?b(e):void 0,r=typeof e=="function"?e:typeof t=="function"?t:void 0,o=typeof e=="string"||typeof t=="function"?i:t??i;if(o?.throwIfAborted(),n)return M(await ie(n,r,o));let a=Ae();try{if(!_(a))return[];let u=(await K(a,{withFileTypes:!0})).filter(f=>f.isDirectory()||f.isSymbolicLink()).map(f=>v(a,f.name)),l=(await te(u,Ce,async f=>{try{return(await K(f)).filter(h=>h.endsWith(".jsonl")).map(h=>v(f,h))}catch{return[]}},o)).flat(),p=await te(l,Ce,async f=>{try{return{path:f,stats:await de(f)}}catch{return{path:f}}},o);p.sort((f,h)=>(h.stats?.mtimeMs??Number.NEGATIVE_INFINITY)-(f.stats?.mtimeMs??Number.NEGATIVE_INFINITY)||ue(h.path).localeCompare(ue(f.path)));let m=p.length,c=0,I=!1,E=[],w=await xe(p,(f,h)=>{c++,h===0&&(I=!0),f&&E.push(f);let y=I&&(h===0||c%ht===0||c===m);r?.(c,m,y?M([...E]):void 0)},o);return M(w.filter(f=>f!==null))}catch{return o?.throwIfAborted(),[]}}};export{T as CURRENT_SESSION_VERSION,P as INJECTED_CONTEXT_TAG,mt as SessionManager,W as assertValidSessionId,z as buildContextEntries,nt as buildSessionContext,J as buildSessionProjection,We as convertToLlm,se as createBranchSummaryMessage,ne as createCompactionSummaryMessage,re as createCustomMessage,F as getDefaultSessionDir,D as getDefaultSessionDirs,tt as getLatestCompactionEntry,Qe as migrateSessionEntries,et as parseSessionEntries,Ie as projectContextEntry,ye as sessionEntryToContextMessages};