flujo-ai 3.45.1 → 3.45.2

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 (192) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +37 -37
  3. package/.next/build-manifest.json +3 -3
  4. package/.next/react-loadable-manifest.json +2 -2
  5. package/.next/server/app/_global-error.html +1 -1
  6. package/.next/server/app/_global-error.rsc +1 -1
  7. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  8. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  9. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found.html +1 -1
  14. package/.next/server/app/_not-found.rsc +1 -1
  15. package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  16. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  17. package/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  18. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  19. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  20. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  21. package/.next/server/app/api/telemetry/daily-active/route.js +1 -1
  22. package/.next/server/app/automation/triggers.html +1 -1
  23. package/.next/server/app/automation/triggers.rsc +1 -1
  24. package/.next/server/app/automation/triggers.segments/_full.segment.rsc +1 -1
  25. package/.next/server/app/automation/triggers.segments/_head.segment.rsc +1 -1
  26. package/.next/server/app/automation/triggers.segments/_index.segment.rsc +1 -1
  27. package/.next/server/app/automation/triggers.segments/_tree.segment.rsc +1 -1
  28. package/.next/server/app/automation/triggers.segments/automation/triggers/__PAGE__.segment.rsc +1 -1
  29. package/.next/server/app/automation/triggers.segments/automation/triggers.segment.rsc +1 -1
  30. package/.next/server/app/automation/triggers.segments/automation.segment.rsc +1 -1
  31. package/.next/server/app/automation/waves.html +1 -1
  32. package/.next/server/app/automation/waves.rsc +1 -1
  33. package/.next/server/app/automation/waves.segments/_full.segment.rsc +1 -1
  34. package/.next/server/app/automation/waves.segments/_head.segment.rsc +1 -1
  35. package/.next/server/app/automation/waves.segments/_index.segment.rsc +1 -1
  36. package/.next/server/app/automation/waves.segments/_tree.segment.rsc +1 -1
  37. package/.next/server/app/automation/waves.segments/automation/waves/__PAGE__.segment.rsc +1 -1
  38. package/.next/server/app/automation/waves.segments/automation/waves.segment.rsc +1 -1
  39. package/.next/server/app/automation/waves.segments/automation.segment.rsc +1 -1
  40. package/.next/server/app/chain-chat.html +1 -1
  41. package/.next/server/app/chain-chat.rsc +1 -1
  42. package/.next/server/app/chain-chat.segments/_full.segment.rsc +1 -1
  43. package/.next/server/app/chain-chat.segments/_head.segment.rsc +1 -1
  44. package/.next/server/app/chain-chat.segments/_index.segment.rsc +1 -1
  45. package/.next/server/app/chain-chat.segments/_tree.segment.rsc +1 -1
  46. package/.next/server/app/chain-chat.segments/chain-chat/__PAGE__.segment.rsc +1 -1
  47. package/.next/server/app/chain-chat.segments/chain-chat.segment.rsc +1 -1
  48. package/.next/server/app/chat/page_client-reference-manifest.js +1 -1
  49. package/.next/server/app/chat.html +1 -1
  50. package/.next/server/app/chat.rsc +2 -2
  51. package/.next/server/app/chat.segments/_full.segment.rsc +2 -2
  52. package/.next/server/app/chat.segments/_head.segment.rsc +1 -1
  53. package/.next/server/app/chat.segments/_index.segment.rsc +1 -1
  54. package/.next/server/app/chat.segments/_tree.segment.rsc +1 -1
  55. package/.next/server/app/chat.segments/chat/__PAGE__.segment.rsc +2 -2
  56. package/.next/server/app/chat.segments/chat.segment.rsc +1 -1
  57. package/.next/server/app/docs.html +1 -1
  58. package/.next/server/app/docs.rsc +1 -1
  59. package/.next/server/app/docs.segments/_full.segment.rsc +1 -1
  60. package/.next/server/app/docs.segments/_head.segment.rsc +1 -1
  61. package/.next/server/app/docs.segments/_index.segment.rsc +1 -1
  62. package/.next/server/app/docs.segments/_tree.segment.rsc +1 -1
  63. package/.next/server/app/docs.segments/docs/__PAGE__.segment.rsc +1 -1
  64. package/.next/server/app/docs.segments/docs.segment.rsc +1 -1
  65. package/.next/server/app/executions.html +1 -1
  66. package/.next/server/app/executions.rsc +1 -1
  67. package/.next/server/app/executions.segments/_full.segment.rsc +1 -1
  68. package/.next/server/app/executions.segments/_head.segment.rsc +1 -1
  69. package/.next/server/app/executions.segments/_index.segment.rsc +1 -1
  70. package/.next/server/app/executions.segments/_tree.segment.rsc +1 -1
  71. package/.next/server/app/executions.segments/executions/__PAGE__.segment.rsc +1 -1
  72. package/.next/server/app/executions.segments/executions.segment.rsc +1 -1
  73. package/.next/server/app/flows/page_client-reference-manifest.js +1 -1
  74. package/.next/server/app/flows.html +1 -1
  75. package/.next/server/app/flows.rsc +2 -2
  76. package/.next/server/app/flows.segments/_full.segment.rsc +2 -2
  77. package/.next/server/app/flows.segments/_head.segment.rsc +1 -1
  78. package/.next/server/app/flows.segments/_index.segment.rsc +1 -1
  79. package/.next/server/app/flows.segments/_tree.segment.rsc +1 -1
  80. package/.next/server/app/flows.segments/flows/__PAGE__.segment.rsc +2 -2
  81. package/.next/server/app/flows.segments/flows.segment.rsc +1 -1
  82. package/.next/server/app/index.html +1 -1
  83. package/.next/server/app/index.rsc +1 -1
  84. package/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  85. package/.next/server/app/index.segments/_full.segment.rsc +1 -1
  86. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  87. package/.next/server/app/index.segments/_index.segment.rsc +1 -1
  88. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  89. package/.next/server/app/mcp/page_client-reference-manifest.js +1 -1
  90. package/.next/server/app/mcp-flows/route.js +1 -1
  91. package/.next/server/app/mcp-proxy/[server]/route.js +1 -1
  92. package/.next/server/app/mcp.html +1 -1
  93. package/.next/server/app/mcp.rsc +2 -2
  94. package/.next/server/app/mcp.segments/_full.segment.rsc +2 -2
  95. package/.next/server/app/mcp.segments/_head.segment.rsc +1 -1
  96. package/.next/server/app/mcp.segments/_index.segment.rsc +1 -1
  97. package/.next/server/app/mcp.segments/_tree.segment.rsc +1 -1
  98. package/.next/server/app/mcp.segments/mcp/__PAGE__.segment.rsc +2 -2
  99. package/.next/server/app/mcp.segments/mcp.segment.rsc +1 -1
  100. package/.next/server/app/meetings.html +1 -1
  101. package/.next/server/app/meetings.rsc +1 -1
  102. package/.next/server/app/meetings.segments/_full.segment.rsc +1 -1
  103. package/.next/server/app/meetings.segments/_head.segment.rsc +1 -1
  104. package/.next/server/app/meetings.segments/_index.segment.rsc +1 -1
  105. package/.next/server/app/meetings.segments/_tree.segment.rsc +1 -1
  106. package/.next/server/app/meetings.segments/meetings/__PAGE__.segment.rsc +1 -1
  107. package/.next/server/app/meetings.segments/meetings.segment.rsc +1 -1
  108. package/.next/server/app/packages.html +1 -1
  109. package/.next/server/app/packages.rsc +1 -1
  110. package/.next/server/app/packages.segments/_full.segment.rsc +1 -1
  111. package/.next/server/app/packages.segments/_head.segment.rsc +1 -1
  112. package/.next/server/app/packages.segments/_index.segment.rsc +1 -1
  113. package/.next/server/app/packages.segments/_tree.segment.rsc +1 -1
  114. package/.next/server/app/packages.segments/packages/__PAGE__.segment.rsc +1 -1
  115. package/.next/server/app/packages.segments/packages.segment.rsc +1 -1
  116. package/.next/server/app/personas.html +1 -1
  117. package/.next/server/app/personas.rsc +1 -1
  118. package/.next/server/app/personas.segments/_full.segment.rsc +1 -1
  119. package/.next/server/app/personas.segments/_head.segment.rsc +1 -1
  120. package/.next/server/app/personas.segments/_index.segment.rsc +1 -1
  121. package/.next/server/app/personas.segments/_tree.segment.rsc +1 -1
  122. package/.next/server/app/personas.segments/personas/__PAGE__.segment.rsc +1 -1
  123. package/.next/server/app/personas.segments/personas.segment.rsc +1 -1
  124. package/.next/server/app/roles/new.html +1 -1
  125. package/.next/server/app/roles/new.rsc +1 -1
  126. package/.next/server/app/roles/new.segments/_full.segment.rsc +1 -1
  127. package/.next/server/app/roles/new.segments/_head.segment.rsc +1 -1
  128. package/.next/server/app/roles/new.segments/_index.segment.rsc +1 -1
  129. package/.next/server/app/roles/new.segments/_tree.segment.rsc +1 -1
  130. package/.next/server/app/roles/new.segments/roles/new/__PAGE__.segment.rsc +1 -1
  131. package/.next/server/app/roles/new.segments/roles/new.segment.rsc +1 -1
  132. package/.next/server/app/roles/new.segments/roles.segment.rsc +1 -1
  133. package/.next/server/app/roles.html +1 -1
  134. package/.next/server/app/roles.rsc +1 -1
  135. package/.next/server/app/roles.segments/_full.segment.rsc +1 -1
  136. package/.next/server/app/roles.segments/_head.segment.rsc +1 -1
  137. package/.next/server/app/roles.segments/_index.segment.rsc +1 -1
  138. package/.next/server/app/roles.segments/_tree.segment.rsc +1 -1
  139. package/.next/server/app/roles.segments/roles/__PAGE__.segment.rsc +1 -1
  140. package/.next/server/app/roles.segments/roles.segment.rsc +1 -1
  141. package/.next/server/app/settings.html +1 -1
  142. package/.next/server/app/settings.rsc +1 -1
  143. package/.next/server/app/settings.segments/_full.segment.rsc +1 -1
  144. package/.next/server/app/settings.segments/_head.segment.rsc +1 -1
  145. package/.next/server/app/settings.segments/_index.segment.rsc +1 -1
  146. package/.next/server/app/settings.segments/_tree.segment.rsc +1 -1
  147. package/.next/server/app/settings.segments/settings/__PAGE__.segment.rsc +1 -1
  148. package/.next/server/app/settings.segments/settings.segment.rsc +1 -1
  149. package/.next/server/app/statistics.html +1 -1
  150. package/.next/server/app/statistics.rsc +1 -1
  151. package/.next/server/app/statistics.segments/_full.segment.rsc +1 -1
  152. package/.next/server/app/statistics.segments/_head.segment.rsc +1 -1
  153. package/.next/server/app/statistics.segments/_index.segment.rsc +1 -1
  154. package/.next/server/app/statistics.segments/_tree.segment.rsc +1 -1
  155. package/.next/server/app/statistics.segments/statistics/__PAGE__.segment.rsc +1 -1
  156. package/.next/server/app/statistics.segments/statistics.segment.rsc +1 -1
  157. package/.next/server/app/waves.html +1 -1
  158. package/.next/server/app/waves.rsc +1 -1
  159. package/.next/server/app/waves.segments/_full.segment.rsc +1 -1
  160. package/.next/server/app/waves.segments/_head.segment.rsc +1 -1
  161. package/.next/server/app/waves.segments/_index.segment.rsc +1 -1
  162. package/.next/server/app/waves.segments/_tree.segment.rsc +1 -1
  163. package/.next/server/app/waves.segments/waves/__PAGE__.segment.rsc +1 -1
  164. package/.next/server/app/waves.segments/waves.segment.rsc +1 -1
  165. package/.next/server/app-paths-manifest.json +37 -37
  166. package/.next/server/chunks/1475.js +1 -1
  167. package/.next/server/chunks/1914.js +1 -1
  168. package/.next/server/chunks/2887.js +1 -1
  169. package/.next/server/chunks/3686.js +1 -1
  170. package/.next/server/chunks/5189.js +1 -1
  171. package/.next/server/chunks/5399.js +1 -1
  172. package/.next/server/chunks/5560.js +2 -2
  173. package/.next/server/chunks/7570.js +1 -1
  174. package/.next/server/middleware-build-manifest.js +1 -1
  175. package/.next/server/middleware-react-loadable-manifest.js +1 -1
  176. package/.next/server/pages/404.html +1 -1
  177. package/.next/server/pages/500.html +1 -1
  178. package/.next/server/server-reference-manifest.js +1 -1
  179. package/.next/server/server-reference-manifest.json +1 -1
  180. package/.next/static/chunks/{7208-5af7190dbc0e142b.js → 7208-714230aba8f0df89.js} +1 -1
  181. package/.next/static/chunks/webpack-f1c3062d7039f0c7.js +1 -0
  182. package/.next/trace +118 -118
  183. package/.next/trace-build +1 -1
  184. package/README.md +1 -1
  185. package/mcp-servers/bash/package.json +1 -1
  186. package/mcp-servers/browser/package.json +1 -1
  187. package/mcp-servers/filesystem/package.json +1 -1
  188. package/mcp-servers/flujo/package.json +1 -1
  189. package/package.json +5 -5
  190. package/.next/static/chunks/webpack-489c70bebf5a4745.js +0 -1
  191. /package/.next/static/{PEARC3s6DHN81nwlN8qpZ → 21CjEbc0FIa9X6No7R5M-}/_buildManifest.js +0 -0
  192. /package/.next/static/{PEARC3s6DHN81nwlN8qpZ → 21CjEbc0FIa9X6No7R5M-}/_ssgManifest.js +0 -0
@@ -49,7 +49,7 @@ Stderr output:
49
49
  ${d}`:`MCP error ${a.code}: ${e}`}let f=jG(a);return d?`${f}
50
50
 
51
51
  Stderr output:
52
- ${d}`:f}let jI=["OAuth authentication required","UnauthorizedError","invalid_token","token_expired","HTTP 401","HTTP 403","Missing Authorization header","Authorization header is required"];function jJ(a){if(!(a instanceof Error))return!1;if(jK(a))return!0;let b=a.code;return 401===b||403===b||jI.some(b=>a.message.includes(b))}function jK(a){if(!(a instanceof Error))return!1;if("OAuthAuthenticationRequired"===a.name)return!0;let b=a.errorCode;return"string"==typeof b&&b.length>0||a.message.includes("OAuth authentication required")}var jL=c(98683),jM=c(30314);let jN=new Set(["npx","bunx","uvx","pipx","dlx"]),jO=new Set(["pnpm","yarn","bun","npm"]),jP=new Set(["dlx","exec","x"]);function jQ(a,b=[]){let c=((a||"").split(/[\\/]/).filter(Boolean).pop()||"").toLowerCase().replace(/\.(cmd|exe|bat|ps1)$/i,"");if(jN.has(c))return!0;if(jO.has(c)){let a=(b[0]||"").toLowerCase();return jP.has(a)}return!1}let jR=new Set(["node","npm","npx"]);var jS=c(84022),jT=c(68644),jU=c(14493),jV=c(30670),jW=c(70690);let jX=(0,o.h)("backend/services/mcp/sampling");function jY(a){return a.sampling}function jZ(a){let b=jY(a);return!!(b?.enabled&&b.modelId)}function j$(a){let b=[];return async c=>{let d=jY(a);if(!d?.enabled||!d.modelId)throw new J.Nh(J.O4.InvalidRequest,"Sampling is not enabled for this server");let e=d.maxCallsPerMinute??10,f=Date.now(),g=f-6e4;for(;b.length>0&&b[0]<g;)b.shift();if(b.length>=e)throw jX.warn(`Sampling rate limit (${e}/min) hit for ${a.name}`),new J.Nh(J.O4.InvalidRequest,`Sampling rate limit of ${e}/min exceeded`);b.push(f);let h=await jU.modelService.getModel(d.modelId);if(!h)throw new J.Nh(J.O4.InternalError,`Sampling model not found: ${d.modelId}`);let i=await jU.modelService.resolveAndDecryptApiKey(h.ApiKey);if(!i)throw new J.Nh(J.O4.InternalError,"Could not resolve the sampling model API key");let j=c.params,k=function(a){let b=[];for(let c of(a.systemPrompt&&b.push({role:"system",content:a.systemPrompt}),a.messages||[])){let a=c.content,d=a?.type==="text"&&"string"==typeof a.text?a.text:`[unsupported ${a?.type||"non-text"} content omitted]`;b.push({role:c.role,content:d})}return b}(j),l="number"==typeof j.temperature?j.temperature:.7;jX.info(`Sampling for ${a.name} via model ${h.name} (${k.length} messages)`);let m=(0,jV.getCompletionAdapter)(h),n=d.maxTokens??(0,jW.normalizeMaxTokens)(h.maxTokens),{completion:o}=await m.createCompletion({model:h,apiKey:i,messages:k,temperature:l,maxTokens:n}),p=o.choices?.[0]?.message?.content;return{role:"assistant",content:{type:"text",text:"string"==typeof p?p:""},model:h.name,stopReason:"endTurn"}}}var j_=c(21550),j0=c(94917);let j1=(0,o.h)("backend/services/mcp/elicitationRegistry"),j2=globalThis,j3=j2.__flujoElicitationRegistry??(j2.__flujoElicitationRegistry=new Map),j4="co.com.flujo/mcp-stdio-oauth",j5=`${j4}/status`,j6=`${j4}/start`,j7=Object.freeze({version:"0.1",urlElicitation:!0}),j8=Y.Yj().min(1),j9=Y.Ik({version:Y.eu("0.1"),urlElicitation:Y.eu(!0)}).loose(),ka=Y.Ik({id:j8,provider:Y.Yj().optional(),label:Y.Yj(),state:Y.Yj(),blocksUnattendedUse:Y.zM().default(!0),message:Y.Yj().optional()}).loose(),kb=Y.Ik({}).loose(),kc=Y.Ik({authorizations:Y.YO(ka)}).loose().superRefine((a,b)=>{let c=new Set;a.authorizations.forEach((a,d)=>{c.has(a.id)&&b.addIssue({code:"custom",message:`Duplicate authorization id: ${a.id}`,path:["authorizations",d,"id"]}),c.add(a.id)})}),kd=Y.Ik({authorizationId:j8}).loose(),ke=Y.Ik({authorizationId:j8,state:Y.Yj(),message:Y.Yj().optional()}).loose(),kf=Y.Ik({authorizationId:j8,state:Y.Yj(),message:Y.Yj().optional()}).loose();Y.Ik({[j4]:kf}).loose();let kg=Y.Ik({mode:Y.eu("url"),url:Y.Yj().min(1),message:Y.Yj()}).loose(),kh=Y.Ik({action:Y.k5(["accept","decline","cancel"])}).loose(),ki=Y.Ik({resultType:Y.eu("input_required"),inputRequests:Y.g1(Y.Yj(),Y.Ik({method:Y.eu("elicitation/create"),params:kg}).loose()),requestState:j8}).loose().superRefine((a,b)=>{1!==Object.keys(a.inputRequests).length&&b.addIssue({code:"custom",message:"mcp-stdio-oauth input_required requires exactly one URL input request.",path:["inputRequests"]})});function kj(a){return void 0!==function(a){if(!a||"object"!=typeof a)return;let b=a.extensions;if(!b||"object"!=typeof b)return;let c=j9.safeParse(b[j4]);return c.success?c.data:void 0}(a.getServerCapabilities?.())}async function kk(a,b,c){let d=kd.parse({authorizationId:b}),e=await a.request({method:j6,params:d},ke,c),f=ke.parse(e);if(f.authorizationId!==d.authorizationId)throw Error(`The server returned authorizationId ${f.authorizationId} for a request concerning ${d.authorizationId}.`);return f}async function kl(a,b){let c=kb.parse({}),d=await a.request({method:j5,params:c},kc,b);return kc.parse(d)}let km=new Set(["localhost","127.0.0.1","[::1]","::1"]);class kn extends Error{constructor(a){super(a),this.code="UNSAFE_ELICITATION_URL",this.name="UnsafeElicitationUrlError"}}function ko(a){let b;try{b=new URL(a)}catch{throw new kn("The elicitation URL is malformed.")}if(b.username||b.password)throw new kn("The elicitation URL must not contain embedded credentials.");let c=b.hostname.toLowerCase(),d=km.has(c),e="https:"===b.protocol,f="http:"===b.protocol&&d;if(!e&&!f)throw new kn("The elicitation URL must use HTTPS, except for HTTP loopback URLs.");return Object.freeze({url:b,href:b.href,origin:b.origin,hostname:c,isLoopback:d,hasPunycode:c.split(".").some(a=>a.startsWith("xn--"))})}class kp extends Error{constructor(){super("The MCP server does not advertise the mcp-stdio-oauth extension."),this.code="STDIO_OAUTH_UNSUPPORTED",this.name="StdioOAuthUnsupportedError"}}class kq extends Error{constructor(){super("The MCP client cannot advertise the mcp-stdio-oauth extension and URL elicitation capabilities."),this.code="STDIO_OAUTH_CLIENT_ADVERTISEMENT_REQUIRED",this.name="StdioOAuthClientAdvertisementRequiredError"}}class kr extends Error{constructor(a){super(a),this.code="STDIO_OAUTH_USER_ACTION_REQUIRED",this.name="StdioOAuthUserActionRequiredError"}}class ks extends Error{constructor(){super("MCP 2026-07-28 requires StdioOAuthClientTransport for the extension-defined start MRTR flow."),this.code="STDIO_OAUTH_MODERN_ADAPTER_REQUIRED",this.name="StdioOAuthModernAdapterRequiredError"}}function kt(a){return"id"in a&&("result"in a||"error"in a)}class ku{constructor(a){this.flows=new Map,this.maxRounds=a}beginUserInitiatedStart(a){if(this.activeAuthorizationId)throw Error("An OAuth start flow is already active on this transport.");this.activeAuthorizationId=a}endUserInitiatedStart(){this.activeAuthorizationId=void 0}setUrlElicitationHandler(a){this.urlHandler=a}clear(){this.flows.clear(),this.activeAuthorizationId=void 0}async send(a,b,c){let d;if("id"in a&&"method"in a&&function(a){if(a.method!==j6)return!1;let b=a.params?._meta;return!!b&&"object"==typeof b&&"2026-07-28"===b["io.modelcontextprotocol/protocolVersion"]}(a)){let c=a.params?.authorizationId;this.activeAuthorizationId&&c===this.activeAuthorizationId&&(d=a.id,this.flows.set(a.id,{originalId:a.id,request:a,rounds:0,...void 0===b?{}:{sendOptions:b}}))}try{await c(a,b)}catch(a){throw void 0!==d&&this.flows.delete(d),a}}async receive(a,b,c,d,e){try{await this.handleResponse(a,b,c,d)}catch(f){let d=f instanceof Error?f:Error(String(f));if(kt(a)){let d=this.flows.get(a.id);d&&(this.flows.delete(a.id),c?.({jsonrpc:"2.0",id:d.originalId,error:{code:-32603,message:"OAuth URL elicitation failed"}},b))}e?.(d)}}async handleResponse(a,b,c,d){if(!kt(a))return void c?.(a,b);let e=this.flows.get(a.id);if(!e)return void c?.(a,b);if("error"in a){this.flows.delete(a.id),c?.({...a,id:e.originalId},b);return}let f=ki.safeParse(a.result);if(!f.success){this.flows.delete(a.id),c?.({...a,id:e.originalId},b);return}if(e.rounds>=this.maxRounds)throw Error("OAuth start exceeded the maximum MRTR rounds.");if(!this.urlHandler||!this.activeAuthorizationId)throw Error("Received OAuth input_required without an active user-initiated start.");let g={};for(let[a,b]of Object.entries(f.data.inputRequests))g[a]=await this.urlHandler(b);let h=`mcp-stdio-oauth:${(0,jx.randomUUID)()}`,i={...e.request,id:h,params:{...e.request.params,inputResponses:g,requestState:f.data.requestState}};this.flows.set(h,{...e,rounds:e.rounds+1});try{await d(i,e.sendOptions)}catch(a){throw this.flows.delete(h),a}this.flows.delete(a.id)}}let kv=new WeakMap;class kw{attach(a,b=8){if(this.delegate){if(a!==this.attachedTransport)throw Error("This deferred OAuth MRTR controller is already attached to another transport.");return this.delegate}return this.attachedTransport=a,this.delegate=function(a,b=8){let c=kv.get(a);if(c)return c;let d=new ku(b),e=a.send.bind(a),f=a.onmessage,g=a.onclose,h=a.onerror,i=!1,j=(a,b)=>d.send(a,b,e),k=(a,b)=>{d.receive(a,b,f,e,h)},l=()=>{d.clear(),g?.()};a.send=j,a.onmessage=k,a.onclose=l;let m={beginUserInitiatedStart:a=>d.beginUserInitiatedStart(a),endUserInitiatedStart:()=>d.endUserInitiatedStart(),setUrlElicitationHandler:a=>d.setUrlElicitationHandler(a),dispose(){i||(i=!0,d.clear(),a.send===j&&(a.send=e),a.onmessage===k&&(a.onmessage=f),a.onclose===l&&(a.onclose=g),kv.delete(a))}};return kv.set(a,m),m}(a,b),this.delegate.setUrlElicitationHandler(this.handler),this.delegate}beginUserInitiatedStart(a){if(!this.delegate)throw Error("The deferred OAuth MRTR controller must be attached after MCP connect before start is used.");this.delegate.beginUserInitiatedStart(a)}endUserInitiatedStart(){this.delegate?.endUserInitiatedStart()}setUrlElicitationHandler(a){this.handler=a,this.delegate?.setUrlElicitationHandler(a)}dispose(){this.delegate?.dispose(),this.delegate=void 0,this.attachedTransport=void 0}}function kx(a){return null!==a&&"object"==typeof a?a:void 0}let ky=(0,o.h)("backend/services/mcp/externalAuthorization");({...j7});let kz=global.__mcp_external_authorization_status??(global.__mcp_external_authorization_status=new Map),kA=global.__mcp_external_authorization_sessions??(global.__mcp_external_authorization_sessions=new Map),kB=global.__mcp_stdio_oauth_clients??(global.__mcp_stdio_oauth_clients=new WeakMap);function kC(a){return(0,p.workspaceCacheKey)(a)}function kD(a,b){return`${a}\0${b}`}function kE(a){return kD((0,p.getCurrentWorkspace)(),a)}function kF(a,b,c){if(kB.has(a))return;let d=function(a){var b,c;let d,e,{mcpClient:f,onUrlElicitation:g}=a,h=!1,i=!!(b=f).registerCapabilities&&(b.registerCapabilities({...c={elicitation:{url:{}}},extensions:{...c.extensions,[j4]:{...j7}}}),!0),j=async a=>{var b;let c;if(!e||h)return{action:"cancel"};let d=a&&"object"==typeof a&&"params"in a?a.params:a,f=(b=kg.parse(d),Object.freeze({...c=kg.parse(b),target:ko(c.url)})),i=await g(f);return kh.parse(i)},k=!0===a.installElicitationHandler&&"function"==typeof f.setRequestHandler&&(f.setRequestHandler.call(f,"elicitation/create",j),!0);a.mrtrController?.setUrlElicitationHandler(j);let l=()=>{if(h)throw Error("The mcp-stdio-oauth client has been disposed.");if(!i)throw new kq;if(!kj(f))throw new kp};return{isSupported:()=>!h&&i&&kj(f),async getStatus(a){l();let b=await kl(f,a);return d=new Set(b.authorizations.map(a=>a.id)),b},async start(b,c){if(l(),f.getProtocolEra?.()==="modern"&&!a.mrtrController)throw new ks;let g=Y.Yj().min(1,"Expected a non-empty authorization ID").parse(b);if(!d?.has(g))throw new kr("Start requires an authorizationId from the latest successful status result.");if(e)throw new kr("Only one user-initiated authorization start may be active per client helper.");e=g,a.mrtrController?.beginUserInitiatedStart(g);try{return await kk(f,g,c)}finally{a.mrtrController?.endUserInitiatedStart(),e=void 0}},handleUrlElicitation:j,dispose(){!h&&k&&("function"!=typeof f.removeRequestHandler||f.removeRequestHandler.call(f,"elicitation/create")),a.mrtrController?.setUrlElicitationHandler(void 0),h=!0,e=void 0,d=void 0}}}({mcpClient:a,installElicitationHandler:!1,...c?{mrtrController:c}:{},onUrlElicitation:(0,p.bindToCurrentWorkspace)(async a=>await kN(b,{mode:a.mode,url:a.target.href,message:a.message})??{action:"cancel"})});kB.set(a,d),a.__flujoStdioOAuth=!0}function kG(a){let b=kB.get(a);if(!b)throw Error("This MCP client did not negotiate mcp-stdio-oauth.");return b}function kH(a){if(!a)return!1;let b=!0===a.__flujoStdioOAuth,c=kB.get(a);return b&&!!c?.isSupported()}async function kI(a,b,c={}){if(!kH(a))return{supported:!1,authorizations:[]};let d=kC(b),e=kz.get(d);if(!c.force&&e&&Date.now()-e.timestamp<2e3)return e.value;let f=(await kG(a).getStatus({timeout:8e3})).authorizations.map(a=>({id:a.id,...a.provider?{provider:a.provider}:{},label:a.label,state:a.state,blocksUnattendedUse:a.blocksUnattendedUse,...a.message?{message:a.message}:{}})),g={supported:!0,authorizations:f,blockingAuthorization:f.find(a=>a.blocksUnattendedUse&&"ready"!==a.state)};return kz.set(d,{value:g,timestamp:Date.now()}),g}function kJ(a){kz.delete(kC(a))}function kK(a){let b=(0,p.getCurrentWorkspace)();return Array.from(kA.values()).filter(c=>c.workspace===b&&c.serverName===a).sort((a,b)=>b.createdAt-a.createdAt)[0]}function kL(a){a.timer&&clearTimeout(a.timer),kA.delete(kD(a.workspace,a.sessionId))}function kM(a,b){let c=b?kA.get(kE(b)):kK(a);if(!c||c.serverName!==a)return!1;if(c.resolveElicitation){let a=c.resolveElicitation;c.resolveElicitation=void 0,c.elicitationResponded=!0,a({action:"cancel"})}else c.elicitationResponded,c.abortController.abort();return c.rejectPrompt(Error("Authorization was cancelled.")),!0}async function kN(a,b){if("url"!==b.mode)return;let c=kK(a);if("string"!=typeof b.url||0===b.url.length)return c&&(c.rejectPrompt(Error("The MCP server supplied a malformed authorization URL.")),c.abortController.abort()),{action:"cancel"};if(!c)return ky.warn(`Rejected unsolicited URL elicitation from ${a}`),{action:"cancel"};if(c.abortController.signal.aborted)return ky.warn(`Rejected URL elicitation from cancelled start on ${a}`),{action:"cancel"};if(c.resolveElicitation||c.elicitationResponded)return ky.warn(`Rejected duplicate URL elicitation from ${a}`),{action:"cancel"};try{!function(a,b,c){if(a.prompt)return a.prompt;let d=ko(b),e={sessionId:a.sessionId,authorizationId:a.authorizationId,url:d.href,origin:d.origin,hasPunycode:d.hasPunycode,...c?{message:c}:{}};a.prompt=e,a.resolvePrompt(e)}(c,b.url,b.message)}catch(a){return c.rejectPrompt(a instanceof Error?a:Error(String(a))),c.abortController.abort(),{action:"cancel"}}return new Promise(a=>{c.resolveElicitation=a})}async function kO(a,b,c,d={}){let e,f,g;if(d.signal?.throwIfAborted(),!kH(a))throw Error("This MCP server did not negotiate external authorization support.");let h=(await kI(a,b,{force:!0})).authorizations.find(a=>a.id===c);if(!h)throw Error("The OAuth authorization is no longer available. Refresh and try again.");if("ready"===h.state)return{sessionId:crypto.randomUUID(),authorizationId:c,url:"",origin:"",hasPunycode:!1,alreadyReady:!0};let i=kK(b);if(i&&(kM(b,i.sessionId),kA.has(kD(i.workspace,i.sessionId))))throw Error("The previous authorization request is still closing. Try again in a moment.");d.signal?.throwIfAborted();let j=new Promise((a,b)=>{e=a,f=b}),k={workspace:(0,p.getCurrentWorkspace)(),sessionId:crypto.randomUUID(),serverName:b,authorizationId:c,createdAt:Date.now(),resolvePrompt:e,rejectPrompt:f,promptPromise:j,abortController:new AbortController};k.timer=setTimeout((0,p.bindToCurrentWorkspace)(()=>{let a=k.resolveElicitation;k.resolveElicitation=void 0,k.elicitationResponded=!0,a?.({action:"cancel"}),k.abortController.abort(),k.rejectPrompt(Error("Authorization request timed out."))}),3e5),kA.set(kD(k.workspace,k.sessionId),k);let l=(0,p.bindToCurrentWorkspace)(()=>{kM(b,k.sessionId)});d.signal?.addEventListener("abort",l,{once:!0});let m=(0,p.bindToCurrentWorkspace)(async d=>{if(kJ(b),"ready"===d.state){k.resolvePrompt({sessionId:k.sessionId,authorizationId:c,url:"",origin:"",hasPunycode:!1,alreadyReady:!0}),kL(k);return}let e=(await kI(a,b,{force:!0})).authorizations.find(a=>a.id===c);if(e?.state==="ready"){k.resolvePrompt({sessionId:k.sessionId,authorizationId:c,url:"",origin:"",hasPunycode:!1,alreadyReady:!0}),kL(k);return}k.rejectPrompt(Error("The MCP server completed OAuth start without URL elicitation or ready status.")),kL(k)}),n=(0,p.bindToCurrentWorkspace)(a=>{k.rejectPrompt(a instanceof Error?a:Error(String(a)))}),o=(0,p.bindToCurrentWorkspace)(()=>kL(k));kG(a).start(c,{timeout:3e5,signal:k.abortController.signal}).then(m).catch(n).finally(o);try{return await Promise.race([j,new Promise((a,b)=>{g=setTimeout(()=>b(Error("The MCP server did not present an authorization URL in time.")),3e4)})])}catch(a){throw kM(b,k.sessionId),a}finally{g&&clearTimeout(g),d.signal?.removeEventListener("abort",l)}}let kP=(0,o.h)("backend/services/mcp/taskInputRegistry"),kQ=globalThis,kR=kQ.__flujoMcpTaskInputRegistry??(kQ.__flujoMcpTaskInputRegistry=new Map);function kS(a,b){return(0,p.workspaceCacheKey)(a,b)}let kT=(0,o.h)("backend/services/mcp/elicitation");function kU(a){return a.elicitation}function kV(a){let b=kU(a);return!!b?.enabled}function kW(a){return(0,p.bindToCurrentWorkspace)(async b=>{var c,d,e;let f,g,h,i,j,k=b.params,l=(0,L.PJ)(k?._meta),m=await kN(a.name,k??{});if(m)return m;if(!kV(a))throw new J.Nh(J.O4.MethodNotFound,"Elicitation is not enabled for this server");let n=(0,j0.lx)(a.name);if(!n&&l&&kT.warn(`Task ${l} on ${a.name} requested input outside an attended run; auto-cancelling`),!n)return kT.warn(`Elicitation request from ${a.name} outside an active run; auto-cancelling`),{action:"cancel"};if(n.getUnattended())return kT.warn(`Elicitation request from ${a.name} in unattended run ${n.conversationId}; auto-cancelling`),{action:"cancel"};let o=k?.message??"Additional information required",q=k?.requestedSchema??{type:"object",properties:{}},r=crypto.randomUUID();kT.info(`Suspending for elicitation ${r} from ${a.name} in conv ${n.conversationId}`),l&&(c=a.name,f=kS(c,l),g=Date.now(),(h=kR.get(f)??{outstanding:new Set,answered:new Set,firstRequestedAt:g,lastRequestedAt:g}).answered.has(r)||(h.outstanding.add(r),h.lastRequestedAt=g,kR.set(f,h),kP.info(`Task ${l} on ${c} requested input (elicitation ${r}); outstanding=${h.outstanding.size}`))),j_.$.emitterFor(n.conversationId)({type:"run:awaiting_elicitation",elicitationId:r,message:o,requestedSchema:q});let s=await function(a,b=3e5){let c=(0,p.getCurrentWorkspace)(),d=(0,p.workspaceCacheKey)(a);return new Promise(e=>{let f=setTimeout(()=>{j3.has(d)&&(j1.warn(`Elicitation ${a} timed out after ${b}ms; auto-cancelling`),j3.delete(d),e({action:"cancel"}))},b);j3.set(d,{workspace:c,resolve:e,timer:f})})}(r);return kT.info(`Elicitation ${r} resolved with action=${s.action}`),l&&(d=a.name,e=s.action,i=kS(d,l),!(j=kR.get(i))||!j.outstanding.delete(r)&&j.answered.has(r)||(j.answered.add(r),kR.set(i,j),kP.info(`Task ${l} on ${d} input ${r} resolved with action=${e}; outstanding=${j.outstanding.size}`))),s})}var kX=c(65935);let kY=["key","secret","token","password"],kZ=a=>kY.some(b=>a.toLowerCase().includes(b));function k$(a){return"string"==typeof a&&a.startsWith("${global:")}function k_(a,b){return a&&"object"==typeof a&&"value"in a?{value:a.value??"",isSecret:!!a.metadata?.isSecret}:{value:a??"",isSecret:kZ(b)||"authorization"===b.trim().toLowerCase()}}function k0(a){return a===kX.RJ||a===kX.gF}let k1="io.modelcontextprotocol/ui",k2="text/html;profile=mcp-app",k3=["model","app"];function k4(a,b){return(function(a){let b=a._meta;if(void 0===b)return k3;if(!b||"object"!=typeof b||Array.isArray(b))return[];if(!Object.prototype.hasOwnProperty.call(b,"ui"))return k3;let c=b.ui;if(!c||"object"!=typeof c||Array.isArray(c))return[];if(!Object.prototype.hasOwnProperty.call(c,"visibility"))return k3;let d=c.visibility;return Array.isArray(d)&&d.every(a=>"model"===a||"app"===a)?Array.from(new Set(d)):[]})(a).includes(b)}var k5=c(78591);function k6(a){let b,c;return[(b=jY(a),!b?.enabled?"":JSON.stringify({m:b.modelId,t:b.maxTokens,r:b.maxCallsPerMinute})),(c=kU(a),c?.enabled?"e:1":""),!0===a.enableMcpApps?"mcp-apps:on":"mcp-apps:off",!0===a.enableMcpSkills?"mcp-skills:on":"mcp-skills:off"].join("|")}let k7=(0,o.h)("backend/services/mcp/connection");async function k8(a){let b=a;if(a.env&&"object"==typeof a.env){let c={};for(let[b,d]of Object.entries(a.env)){if(!b)continue;let a=d&&"object"==typeof d&&"value"in d?d.value??"":d??"";if(!a||k0(a))continue;let e=await (0,K.G)(a);e&&(c[b]=e)}b={...b,env:c}}if("streamable"!==a.transport&&"sse"!==a.transport||!a.headers||"object"!=typeof a.headers)return b;let c={};for(let[b,d]of Object.entries(a.headers)){if(!b)continue;let{value:a}=k_(d,b);if(!a||k0(a))continue;let e=await (0,K.G)(a);e&&(c[b]=e)}return{...b,headers:c}}function k9(a){let b={};for(let[c,d]of Object.entries(a)){if(!c)continue;let{value:a}=k_(d,c);"string"==typeof a&&a.length>0&&(b[c]=a)}return b}function la(a){let b={};if(a)for(let[c,d]of Object.entries(a))d&&"object"==typeof d&&"value"in d?b[c]=d.value:b[c]=d;return b}let lb=new Set(["path","pathext","home","userprofile","homedrive","homepath","appdata","localappdata","programdata","xdg_config_home","xdg_cache_home","xdg_data_home","xdg_state_home","xdg_runtime_dir","tmp","temp","tmpdir","shell","comspec","systemroot","windir","systemdrive","programfiles","programfiles(x86)","gh_config_dir"]);function lc(a,b,c){for(let c of Object.keys(a))c.toLowerCase()===b.toLowerCase()&&delete a[c];void 0!==c&&(a[b]=c)}function ld(a,b=!1){return JSON.stringify({command:a.command,args:a.args??[],env:la(a.env),cwd:String(a.cwd??""),rootPath:a.rootPath??"",isolateRuntimeHome:b})}function le(a){return JSON.stringify({transport:a.transport,url:a.serverUrl??"",headers:a.headers??{},requestInit:a.requestInit??{},eventSourceInit:a.eventSourceInit??{},reconnectionOptions:a.reconnectionOptions??{},sessionId:a.sessionId??"",oauthClientId:a.oauthClientId??"",oauthClientInformation:a.oauthClientInformation??{},oauthClientSecret:a.oauthClientSecret??"",oauthTokens:a.oauthTokens??{}})}function lf(a){k7.debug("Entering createNewClient method");let b=jZ(a),c=kV(a),d=!0===a.enableMcpApps,e="stdio"===a.transport,f=new iv({name:`flujo-${a.name}-client`,version:"3.45.1"},{capabilities:{experimental:{},roots:{listChanged:!0},...b?{sampling:{}}:{},...e||c?{elicitation:{...e?{url:{}}:{},...c?{form:{}}:{}}}:{},extensions:{...e?{[j4]:j7}:{},...d?{[k1]:{mimeTypes:[k2]}}:{}}}});return(0,jT.FP)(f,a),b&&f.setRequestHandler(J.u9,j$(a)),(e||c)&&f.setRequestHandler(J.$9,kW(a)),f.__flujoCapKey=k6(a),f}function lg(a,b){if(k7.debug("Entering createTransport method"),"streamable"===a.transport){k7.info(`Creating streamable http transport for server ${a.name} with URL ${a.serverUrl}`);let b={};if(a.requestInit&&"object"==typeof a.requestInit&&(b.requestInit=a.requestInit),a.reconnectionOptions&&"object"==typeof a.reconnectionOptions&&(b.reconnectionOptions=a.reconnectionOptions),"string"==typeof a.sessionId&&a.sessionId.length>0&&(b.sessionId=a.sessionId),a.headers&&"object"==typeof a.headers){let c=k9(a.headers);Object.keys(c).length>0&&(b.requestInit={...b.requestInit||{},headers:{...b.requestInit?.headers||{},...c}},k7.info(`Applied ${Object.keys(c).length} custom header(s) for ${a.name}: ${Object.keys(c).join(", ")}`))}a.oauthClientId||a.oauthClientInformation?(k7.info(`Setting up OAuth authentication for ${a.name}`),b.authProvider=jA(a),a.oauthTokens?.access_token?(k7.debug(`OAuth provider configured for ${a.name} with existing tokens`),k7.debug(`Token expires in: ${a.oauthTokens.expires_in} seconds`)):k7.debug(`OAuth provider configured for ${a.name} - will initiate OAuth flow if needed`)):k7.debug(`No OAuth configuration found for ${a.name}`);let c=new jr(new URL(a.serverUrl),b);return c.__flujoHttpKey=le(a),c}if("sse"===a.transport){k7.info(`Creating legacy sse transport for server ${a.name} with URL ${a.serverUrl}`);let b={};if(a.requestInit&&"object"==typeof a.requestInit&&(b.requestInit=a.requestInit),a.eventSourceInit&&"object"==typeof a.eventSourceInit&&(b.eventSourceInit=a.eventSourceInit),a.headers&&"object"==typeof a.headers){let c=k9(a.headers);Object.keys(c).length>0&&(b.requestInit={...b.requestInit||{},headers:{...b.requestInit?.headers||{},...c}},k7.info(`Applied ${Object.keys(c).length} custom header(s) for ${a.name}: ${Object.keys(c).join(", ")}`))}let c=new jt(new URL(a.serverUrl),b);return c.__flujoHttpKey=le(a),c}return"websocket"===a.transport?(k7.info(`Creating WebSocket transport for server ${a.name} with URL ${a.websocketUrl}`),new iz(new URL(a.websocketUrl))):function(a,b){let c;if(k7.debug("Entering createStdioTransport method"),"stdio"!==a.transport)throw Error("Cannot create stdio transport for non-stdio config");let{command:d,args:e,env:f,cwd:g}=lh(a,b),h=b?.enableRuntimeBroker&&!0===a.enableMcpApps?(0,k5.D9)(a.name):void 0;k7.info(`Creating StdioClientTransport for ${a.name} with stderr: 'pipe'`);let i={command:d,args:e,env:h?{...f,...h.env}:f,cwd:g,stderr:"pipe"};try{c=new iy(i)}catch(a){throw(0,k5.tS)(h?.leaseId),a}return h&&(c.__flujoRuntimeBrokerLeaseId=h.leaseId),c.__flujoStdioKey=ld(a,b?.isolateRuntimeHome===!0),c.stderr?k7.info(`Stderr stream is available for ${a.name}`):k7.warn(`Stderr stream is NOT available for ${a.name}`),c}(a,b)}function lh(a,b){let c=(0,jS.AW)(a),d=!!c,e=c?.defaultName==="bash",f=a=>d?a:(0,p.remapLegacyDefaultWorkspaceReference)(a,"mcp-servers"),g=f(a.command),h=a.args?a.args.map(f):[],i=`${r.VL}/${a.name}`;k7.info(`Creating stdio transport for server ${a.name}`),k7.debug(`Original command: ${g}`),k7.debug(`Original args: ${JSON.stringify(h)}`),k7.debug(`Server directory: ${i}`);let j=!m.isAbsolute(g)&&(g.includes("/")||g.includes("\\")),k=!g.includes("/")&&!g.includes("\\");if(k7.debug(`Is relative path: ${j}`),k7.debug(`Is just filename: ${k}`),"win32"===jv.platform()&&g.toLowerCase().endsWith(".bat"))if(k7.debug(`Detected .bat file on Windows: ${g}`),k){let a=m.join((0,p.getWorkspaceDataDir)(),i,g);k7.debug(`Checking if file exists at: ${a}`);let b=ju.existsSync(a);k7.debug(`File exists: ${b}`),b?(k7.debug(`Using full path to .bat file: ${a}`),h=["/c",a,...h]):(k7.warn(`WARNING: .bat file not found at ${a}`),h=["/c",g,...h]),g="cmd.exe"}else k7.debug(`Using cmd.exe with path as provided: ${g}`),h=["/c",g,...h],g="cmd.exe";let l=function(a,b){if(!a||!(!a.includes("/")&&!a.includes("\\")))return a;let c=a.toLowerCase();if(!jR.has(c))return a;if("node"===c)return b.execPath||a;if(!b.execPath)return a;let d=b.dirname(b.execPath);for(let a of"win32"===b.platform?[`${c}.cmd`,`${c}.exe`,c]:[c]){let c=b.joinPath(d,a);if(b.fileExists(c))return c}return a}(g,{execPath:process.execPath,platform:jv.platform(),dirname:m.dirname,joinPath:m.join,fileExists:ju.existsSync});l!==g&&(k7.debug(`Resolved Node toolchain command "${g}" to absolute path: ${l}`),g=l),k7.debug(`Final command: ${g}`),k7.debug(`Final args: ${JSON.stringify(h)}`);let n=e||b?.isolateRuntimeHome!==!0?void 0:function(a){let b=(0,p.getWorkspaceDataDir)(),c=(0,jw.createHash)("sha256").update(a,"utf8").digest("hex").slice(0,24),d=(a,b)=>{try{let c=ju.lstatSync(a);if(!c.isDirectory()||c.isSymbolicLink())throw Error(`${b} must be a real directory: ${a}`)}catch(d){if("ENOENT"!==d.code)throw d;ju.mkdirSync(a,{mode:448});let c=ju.lstatSync(a);if(!c.isDirectory()||c.isSymbolicLink())throw Error(`${b} must be a real directory: ${a}`)}},e=ju.lstatSync(b);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`Workspace root must be a real directory: ${b}`);let f=b;for(let a of["userdata","mcp-runtime",c])d(f=m.join(f,a),"MCP runtime directory");let g=f,h=m.join(g,"home"),i=m.join(g,"cwd");d(h,"MCP runtime home"),d(i,"MCP runtime cwd");let j={appData:m.join(h,"AppData","Roaming"),localAppData:m.join(h,"AppData","Local"),config:m.join(h,".config"),cache:m.join(h,".cache"),data:m.join(h,".local","share"),state:m.join(h,".local","state"),runtime:m.join(h,".runtime"),temp:m.join(h,"tmp"),npm:m.join(h,".npm"),pip:m.join(h,".cache","pip"),uv:m.join(h,".cache","uv")};for(let a of Object.values(j)){let b=m.relative(h,a),c=h;for(let a of b.split(m.sep).filter(Boolean))d(c=m.join(c,a),"MCP runtime directory")}let k={HOME:h,USERPROFILE:h,APPDATA:j.appData,LOCALAPPDATA:j.localAppData,XDG_CONFIG_HOME:j.config,XDG_CACHE_HOME:j.cache,XDG_DATA_HOME:j.data,XDG_STATE_HOME:j.state,XDG_RUNTIME_DIR:j.runtime,TMPDIR:j.temp,TMP:j.temp,TEMP:j.temp,NPM_CONFIG_CACHE:j.npm,PIP_CACHE_DIR:j.pip,UV_CACHE_DIR:j.uv};if("win32"===process.platform){let a=m.parse(h);k.HOMEDRIVE=a.root.replace(/[\\/]$/,""),k.HOMEPATH=h.slice(a.root.length-1)}return{cwd:i,env:k}}(a.name),o=f(function({command:a,args:b=[],rootPath:c,cwd:d,serverName:e,defaultCwd:f,packageRunnerCwd:g}){let h=c||d||f;if(jQ(a,b)&&g)return g;if(e&&jQ(a,b)&&(h.split(/[\\/]/).filter(Boolean).pop()||"")===e){let a;return((a=h.match(/^(.*[\\/])[^\\/]+[\\/]*$/))?a[1].replace(/[\\/]+$/,""):"")||h}return h}({command:a.command,args:a.args,rootPath:a.rootPath,cwd:a.cwd,serverName:a.name,defaultCwd:`${r.VL}/${a.name}`,packageRunnerCwd:n?.cwd})),q=m.isAbsolute(o)?o:m.join((0,p.getWorkspaceDataDir)(),o);k7.debug(`cwd: ${q}`),k7.debug(`Environment variable names: ${JSON.stringify(Object.keys(a.env??{}))}`);let s=la(a.env),t=e?function(a){let b={...a},c=Object.entries(process.env).filter(a=>"string"==typeof a[1]);for(let[a,d]of c)lc(b,a,d);for(let a of lb)c.find(([b])=>b.toLowerCase()===a)||lc(b,a,void 0);return b}(s):s;if(!d)for(let[a,b]of Object.entries(t))t[a]=f(b);n&&Object.assign(t,n.env),function(a){if("win32"!==process.platform)return;let b=(a,b)=>Object.entries(a).find(([a,c])=>a.toLowerCase()===b.toLowerCase()&&""!==(c??"").trim())?.[1],c=b(process.env,"SystemRoot")??b(process.env,"windir")??"C:\\Windows";for(let[d,e]of Object.entries({SystemRoot:c,windir:c,ComSpec:b(process.env,"ComSpec")??m.join(c,"System32","cmd.exe"),PATHEXT:b(process.env,"PATHEXT")??".COM;.EXE;.BAT;.CMD"}))if(void 0===b(a,d)){for(let b of Object.keys(a))b.toLowerCase()===d.toLowerCase()&&delete a[b];a[d]=e}}(t);let u=(0,jM.ok)(),v=(0,p.getWorkspaceDataDir)();if(t.FLUJO_PARENT_DATA_DIR=u,t.FLUJO_DATA_DIR=v,t.FLUJO_WORKSPACE=(0,p.getCurrentWorkspace)(),c?.defaultName==="browser"){if(!t.PLAYWRIGHT_BROWSERS_PATH?.trim()){let a=(0,jS.AI)(process.env);a&&(t.PLAYWRIGHT_BROWSERS_PATH=a)}t.FLUJO_BROWSER_PROFILE_DIR=m.join(v,"browser-profile","trusted"),t.FLUJO_BROWSER_SCREENSHOT_DIR=m.join(v,"screenshots","browser"),t.FLUJO_BROWSER_RECORD_DIR=m.join(v,"recordings","browser")}return k7.verbose("Transformed environment variable names",JSON.stringify(Object.keys(t))),"1"===process.env.FLUJO_WORKER_MODE&&c?.defaultName==="flujo"&&(t.FLUJO_WORKER_MODE="1",process.env.FLUJO_SNAPSHOT_CONTROL_TOKEN&&(t.FLUJO_SNAPSHOT_CONTROL_TOKEN=process.env.FLUJO_SNAPSHOT_CONTROL_TOKEN)),{command:g,args:h,env:t,cwd:q}}async function li(a,b,c,d){k7.debug("Entering safelyCloseClient method");let e=Date.now(),f=d?.gracePeriodMs??15e3,g=d?.killEscalationMs??5e3,h=!0,i=!1,j=function(a){let b=a,c=new Set;for(;b&&"object"==typeof b&&!c.has(b);){c.add(b);let a=b.__flujoInnerTransport;if(!a)break;b=a}return b}(a.transport);try{let c=j?._process;if(c&&"function"==typeof c.kill&&null===c.exitCode&&null===c.signalCode){try{c.stdin&&!c.stdin.destroyed&&(c.stdin.end(),k7.debug(`Closed stdin for graceful shutdown for ${b}`))}catch(a){k7.warn(`Error closing stdin for ${b}:`,a)}if(h=await (null!==c.exitCode||null!==c.signalCode?Promise.resolve(!0):new Promise(a=>{let b=()=>{clearTimeout(d),a(!0)},d=setTimeout(()=>{c.removeListener("exit",b),a(!1)},f);d.unref?.(),c.once("exit",b)})))k7.info(`Process exited gracefully for ${b}`);else{k7.warn(`Process did not exit within ${f}ms after stdin close; escalating to a tree kill for ${b}`);let a=await (0,jL.U)(c,{graceMs:g,finalWaitMs:g});h=a.exited,i=a.forced,h?k7.warn(`Process tree for ${b} force-terminated after ${a.durationMs}ms`):k7.error(`Process tree for ${b} (pid ${a.pid??"unknown"}) did not exit after forced escalation`)}}await a.close(),k7.info(`Client closed successfully for ${b}`)}catch(a){k7.warn(`Error closing client for ${b}:`,a)}finally{(0,k5.tS)(j?.__flujoRuntimeBrokerLeaseId)}return{exited:h,forced:i,durationMs:Date.now()-e}}let lj=(0,o.h)("backend/services/mcp/betaClient");async function lk(){try{let a=await (0,io.loadItem)(ip.Zg.SPEECH_SETTINGS,void 0);return!!a?.experimental?.mcpBetaProtocol}catch(a){return lj.warn("Failed to read mcpBetaProtocol setting; defaulting to disabled",{err:a}),!1}}function ll(a){return!0===a.__flujoBeta}function lm(a){let b=jZ(a),c=kV(a),d=!0===a.enableMcpApps,e="stdio"===a.transport,f=new ia({name:`flujo-${a.name}-client`,version:"3.45.1"},{capabilities:{roots:{listChanged:!0},...b?{sampling:{}}:{},...e||c?{elicitation:{...e?{url:{}}:{},...c?{form:{}}:{}}}:{},extensions:{...e?{[j4]:j7}:{},...d?{[k1]:{mimeTypes:[k2]}}:{}}},versionNegotiation:{mode:"auto"}});if(f.setRequestHandler("roots/list",(0,jT.sG)(a)),b){let b=j$(a);f.setRequestHandler("sampling/createMessage",async a=>b(a))}if(e||c){let b=kW(a);f.setRequestHandler("elicitation/create",async a=>b(a))}return f.__flujoBeta=!0,f.__flujoCapKey=k6(a),lj.info(`Created v2-beta MCP client for ${a.name} (version negotiation: auto)`),f}function ln(a){let b=a.requestInit&&"object"==typeof a.requestInit?a.requestInit:void 0;if(a.headers&&"object"==typeof a.headers){let c=k9(a.headers);Object.keys(c).length>0&&(b={...b||{},headers:{...b?.headers||{},...c}})}return b}function lo(a,b){let c;if("websocket"===a.transport)throw Error("The v2-beta MCP SDK has no websocket transport; use the v1 path");if("streamable"===a.transport){let b={},c=ln(a);c&&(b.requestInit=c),a.reconnectionOptions&&"object"==typeof a.reconnectionOptions&&(b.reconnectionOptions=a.reconnectionOptions),"string"==typeof a.sessionId&&a.sessionId.length>0&&(b.sessionId=a.sessionId),(a.oauthClientId||a.oauthClientInformation)&&(b.authProvider=jA(a));let d=new ih(new URL(a.serverUrl),b);return d.__flujoHttpKey=le(a),d.__flujoKind="streamable",lj.info(`Created v2-beta streamable transport for ${a.name}`),d}if("sse"===a.transport){let b={},c=ln(a);c&&(b.requestInit=c),a.eventSourceInit&&"object"==typeof a.eventSourceInit&&(b.eventSourceInit=a.eventSourceInit);let d=new ic(new URL(a.serverUrl),b);return d.__flujoHttpKey=le(a),d.__flujoKind="sse",lj.info(`Created v2-beta SSE transport for ${a.name}`),d}let{command:d,args:e,env:f,cwd:g}=lh(a,b),h=b?.enableRuntimeBroker&&!0===a.enableMcpApps?(0,k5.D9)(a.name):void 0;try{c=new im({command:d,args:e,env:h?{...f,...h.env}:f,cwd:g,stderr:"pipe"})}catch(a){throw(0,k5.tS)(h?.leaseId),a}let i=c;return i.__flujoRuntimeBrokerLeaseId=h?.leaseId,i.__flujoStdioKey=ld(a,b?.isolateRuntimeHome===!0),i.__flujoKind="stdio",lp.set(c,new kw),lj.info(`Created v2-beta stdio transport for ${a.name}`),c}let lp=new WeakMap;function lq(a){lp.get(a)?.attach(a)}var lr=c(55334),ls=c(77214),lt=c(61359);let lu=(0,o.h)("backend/services/mcp/clientTasks");function lv(a,b,c){return"completed"===a.status?{success:!0,data:c,progressToken:a.taskId}:"failed"===a.status?{success:!1,error:a.statusMessage??`Task ${a.taskId} failed`,errorType:"task-failed",progressToken:a.taskId,toolName:b}:{success:!1,error:a.statusMessage??`Tool '${b}' task ${a.taskId} was cancelled by the server.`,errorType:"cancelled",progressToken:a.taskId,toolName:b}}async function lw(a){var b,c;let d,{client:e,serverName:f,serverIdentity:g,toolName:h,task:i,timeoutMs:j,signal:k,onProgress:l,ownership:m,persist:n}=a,o=await (0,lt.VX)(),p=Date.now(),q=(0,L.uY)(i.pollInterval,{minMs:o.minPollIntervalMs,maxMs:o.maxPollIntervalMs,defaultMs:o.defaultPollIntervalMs}),r=(0,L.on)(i,p,o.fallbackTtlMs);lu.info(`Tool ${h} on ${f} returned task ${i.taskId} (status=${i.status}, poll=${q}ms, expiresAt=${r??"none"})`),l?.({progress:0,message:`Task ${i.taskId} created (${i.status})`});let s=await (0,lt.Au)(f);if(!s)return lu.warn(`Refusing to poll task ${i.taskId}: poll concurrency limit reached for ${f}`),a.supportsCancel&&await (0,lr.O0)(e,i.taskId),{success:!1,error:`Too many concurrent MCP tasks are being polled; task ${i.taskId} was not started.`,errorType:"task-poll-limit",progressToken:i.taskId,toolName:h};let t=null;n&&(t=await (0,lt.ZN)({remoteTaskId:i.taskId,serverName:f,serverIdentity:g,toolName:h,args:a.args,ownership:m,status:i.status,statusMessage:i.statusMessage,pollIntervalMs:q,...void 0!==r?{expiresAt:r,ttlMs:r-p}:{}}));let u=async a=>{if(!t)return;let b=await (0,lt.Pi)(t.recordId,a);b&&(t=b)},v=b=>(d||(d=(async()=>(await u({cancelRequestedAt:Date.now(),...b?{diagnostic:b}:{}}),a.supportsCancel)?(0,lr.O0)(e,i.taskId):void lu.warn(`Server ${f} does not advertise tasks.cancel; skipping cancellation of ${i.taskId}`))()),d),w=()=>{v()};k?.addEventListener("abort",w,{once:!0});try{let a;if((0,L.gJ)(i.status))return await x(i);let c=i,d=0,g=q,m=0;for(;;){let i;if(k?.aborted)return await v(),await u({status:"cancelled"}),{success:!1,error:`Tool '${h}' task ${c.taskId} was cancelled.`,errorType:"cancelled",progressToken:c.taskId,toolName:h};let n=Date.now();if(void 0!==r&&n>=r)return await v("expired"),await u({status:"failed",diagnostic:"expired",errorMessage:"Remote MCP task expired before completing."}),{success:!1,error:`Task ${c.taskId} expired before completing.`,errorType:"task-expired",progressToken:c.taskId,toolName:h};if(n-p>=j){await v(),await u({status:"failed",errorMessage:"Caller timeout elapsed while polling the remote MCP task."});let a=Math.round(j/1e3);return{success:!1,error:`Tool execution timed out after ${a} seconds`,errorType:"timeout",timeout:a,statusCode:408,progressToken:c.taskId,toolName:h}}if(await (0,ls.y)(g),k?.aborted)continue;try{i=await (0,lr.k$)(e,c.taskId,{timeout:Math.min(4*g+1e4,j)}),d=0,g=q}catch(a){if(d++,await u({diagnostic:"transport-error",lastPolledAt:Date.now()}),d>=o.maxTransientPollFailures)return await v("transport-error"),await u({status:"failed",diagnostic:"transport-error",errorMessage:`tasks/get failed ${d} times: ${String(a)}`}),{success:!1,error:`Lost contact with '${f}' while polling task ${c.taskId}.`,errorType:"task-transport-error",progressToken:c.taskId,toolName:h};g=(0,L.uY)(2*g,{minMs:o.minPollIntervalMs,maxMs:o.maxPollIntervalMs,defaultMs:o.defaultPollIntervalMs}),lu.warn(`Transient tasks/get failure ${d}/${o.maxTransientPollFailures} for ${c.taskId}; backing off to ${g}ms`);continue}if(!i.ok)return await v("protocol-invalid"),await u({status:"failed",diagnostic:"protocol-invalid",errorMessage:`Invalid tasks/get result: ${i.reason}`}),{success:!1,error:`Server '${f}' returned an invalid task status: ${i.reason}`,errorType:"task-protocol-invalid",progressToken:c.taskId,toolName:h};c=i.task,m++;let s=Date.now()-p;if(await u({status:c.status,statusMessage:c.statusMessage,lastPolledAt:Date.now(),nextPollAt:Date.now()+g,pollCount:m,outstandingInputKeys:(b=c.taskId,[...kR.get(kS(f,b))?.outstanding??[]])}),l?.({progress:"completed"===c.status?100:Math.min(99,Math.round(s/1e3)),message:`Task ${c.taskId}: ${c.status}${c.statusMessage?` — ${c.statusMessage}`:""}`}),(0,L.gJ)(c.status))return await x(c);if("input_required"===c.status){a??=Date.now();let b=function(a,b,c,d,e=Date.now()){let f=(0,j0.lx)(a),g=kR.get(kS(a,b));return f?f.getUnattended()?{action:"abandon",error:`Task ${b} on '${a}' requires input, but the run is unattended.`,errorType:"task-input-required-unattended",diagnostic:"input-required-unattended"}:e-c>=d?{action:"abandon",error:`Task ${b} on '${a}' was waiting for input for longer than the configured window (${Math.round(d/1e3)}s)${g?`; ${g.outstanding.size} request(s) unanswered`:""}.`,errorType:"task-input-timeout",diagnostic:"input-required-unattended"}:{action:"wait"}:{action:"abandon",error:`Task ${b} on '${a}' requires input, but no attended run is available to answer it.`,errorType:"task-input-required-unattended",diagnostic:"input-required-unattended"}}(f,c.taskId,a,o.inputRequiredTimeoutMs);if("abandon"===b.action)return await v(b.diagnostic),await u({status:"failed",diagnostic:b.diagnostic,errorMessage:b.error}),{success:!1,error:b.error,errorType:b.errorType,progressToken:c.taskId,toolName:h}}else a=void 0}}finally{k?.removeEventListener("abort",w),s.release(),c=i.taskId,kR.delete(kS(f,c))}async function x(a){if("completed"!==a.status)return await u({status:a.status,statusMessage:a.statusMessage,..."failed"===a.status?{errorMessage:a.statusMessage??"Remote MCP task failed."}:{}}),lv(a,h);try{let b=await (0,lr.Yr)(e,a.taskId,{timeout:Math.min(6e4,j)});return await u({status:"completed",resultRetrieved:!0}),l?.({progress:100,message:`Task ${a.taskId}: completed`}),lv(a,h,b)}catch(b){return await u({status:"completed",resultRetrieved:!1,errorMessage:`tasks/result failed: ${String(b)}`}),{success:!1,error:`Task ${a.taskId} completed but its result could not be retrieved from '${f}'.`,errorType:"task-result-unavailable",progressToken:a.taskId,toolName:h}}}}var lx=c(3050);let ly=(0,o.h)("backend/services/mcp/tools"),lz=0x80000000-1;async function lA(a,b,c="model"){if(ly.debug("Entering listServerTools method"),!a)return ly.warn(`Server ${b} not connected`),{tools:[],error:"Server not connected"};try{var d;ly.info(`Listing tools for server ${b}`);let e=await a.listTools();ly.verbose("Raw response from MCP server:",e);let f=(d=(e.tools||[]).map(a=>({...a,description:a.description||"",inputSchema:a.inputSchema||{type:"object"}})),"all"===c?d:d.filter(a=>k4(a,c)));return ly.verbose(`Processed tools for ${c} audience:`,f),{tools:f}}catch(c){ly.warn(`Failed to list tools for server ${b}:`,c);let a=c instanceof Error?c.message:"Unknown error";return{tools:[],error:a.includes("Connection timeout")?a:`Failed to list tools: ${a}`}}}async function lB(a,b,c,d,e,f,g,h="host",i,j){if(ly.debug("Entering callTool method"),!a)return ly.warn(`Server ${b} not found`),{success:!1,error:`Server ${b} not found`,statusCode:404};let k=void 0!==e&&e>0?Math.min(1e3*e,lz):lz;try{if("app"===h||"model"===h){var l;let d,e=await lA(a,b,"all");if(e.error)return{success:!1,error:`Could not verify MCP App access to tool '${c}' on '${b}': ${e.error}`,errorType:"tool-authorization-list",statusCode:502};let f=(l=e.tools,(d=l.find(a=>a.name===c))?k4(d,h)?{allowed:!0}:{allowed:!1,error:`Tool '${c}' on MCP server '${b}' is not callable by ${"app"===h?"MCP Apps":"the model"}.`,statusCode:403}:{allowed:!1,error:`Tool '${c}' was not found on MCP server '${b}'.`,statusCode:404});if(!f.allowed)return ly.warn(`Rejected ${h} tool call: ${f.error}`),{success:!1,error:f.error,statusCode:f.statusCode}}ly.debug(`Original args for tool ${c}:`,d);let e=await (0,K.resolveGlobalVars)(d),m=function(a,b){if(!a)return{};let c={};for(let d in a){let e=a[d];null==e?(ly.debug(`Normalizing undefined/null value for parameter '${d}' in tool '${b}'`),d.includes("number")||d.endsWith("Count")||d.endsWith("Id")||d.endsWith("Limit")?(c[d]=0,ly.debug(`Using default value 0 for likely number parameter: ${d}`)):d.includes("bool")||d.startsWith("is")||d.startsWith("has")||d.startsWith("should")?(c[d]=!1,ly.debug(`Using default value false for likely boolean parameter: ${d}`)):d.includes("array")||d.endsWith("s")||d.endsWith("List")||d.endsWith("Items")?(c[d]=[],ly.debug(`Using empty array for likely array parameter: ${d}`)):d.includes("object")||d.endsWith("Options")||d.endsWith("Config")||d.endsWith("Settings")?(c[d]={},ly.debug(`Using empty object for likely object parameter: ${d}`)):(c[d]="",ly.debug(`Using empty string for parameter with unknown type: ${d}`))):c[d]=e}return c}("object"==typeof e&&null!==e?e:{},c);ly.debug(`Normalized args for tool ${c}:`,m),ly.debug(`Calling tool ${c} with SDK timeout ${k}ms`);let n={timeout:k,resetTimeoutOnProgress:!0,...g?{signal:g}:{},onprogress:a=>{ly.debug(`Progress for tool ${c}: ${a.progress}${void 0!==a.total?`/${a.total}`:""}${a.message?` — ${a.message}`:""}`),f?.(a)}},o=await (0,lr.u2)(a,c);o.request&&ly.info(`Requesting task-augmented execution of ${c} on ${b} (${o.reason})`);let p={name:c,arguments:m,...o.request?(0,lr.E4)(o.ttlMs):{},...i||j?{_meta:{flujo:{...i?{callerNodeId:i}:{},...j?{ownerScope:j}:{}}}}:{}},q=ll(a)?await a.callTool.call(a,p,n):await a.callTool(p,void 0,n),r=(0,L.Qh)(q,{taskRequested:o.request});if("protocol-invalid"===r.kind)return ly.warn(`Server ${b} returned an invalid task result for ${c}: ${r.reason}`),{success:!1,error:`Server '${b}' returned an invalid MCP task result: ${r.reason}`,errorType:"task-protocol-invalid",statusCode:502,toolName:c};if("task"===r.kind){let d=(0,lr.rf)(),e=d?await (0,lt.kI)(b):"unnegotiated",l=await lw({client:a,serverName:b,serverIdentity:e,toolName:c,args:m,task:r.task,timeoutMs:k,...g?{signal:g}:{},...f?{onProgress:f}:{},ownership:{...i?{nodeId:i}:{},...j?{ownerScope:j}:{},source:h},persist:d,supportsCancel:o.negotiation.supportsCancel||!o.negotiation.supported});return void 0===l.data?l:{...l,data:(0,lx.iL)(l.data,j)}}return{success:!0,data:(0,lx.iL)(q,j)}}catch(m){let d,e,f,h;ly.warn(`Failed to call tool ${c} on server ${b}:`,m);let i=m instanceof Error?m.message:"Unknown error",j=500;if(g?.aborted)return{success:!1,error:`Tool '${c}' call was cancelled.`,errorType:"cancelled",toolName:c};if(m instanceof J.Nh&&m.code===J.O4.RequestTimeout){let a=Math.round(k/1e3);return ly.warn(`Tool ${c} execution timed out after ${a} seconds`),{success:!1,error:`Tool execution timed out after ${a} seconds`,errorType:"timeout",toolName:c,timeout:a,statusCode:408}}let l=kH(a)?(d=kx(m),e=kx(d?.error)??d,f=kx(e?.data),(h=kf.safeParse(f?.[j4])).success?h.data:void 0):void 0;if(l){kJ(b);try{await kI(a,b,{force:!0})}catch(a){ly.warn(`Failed to refresh mcp-stdio-oauth status after revocation on ${b}:`,a)}return{success:!1,error:l.message?l.message:"External account authorization is required. Open the MCP page to authenticate.",errorType:"stdio-oauth-required",statusCode:428,requiresAuthentication:!0}}if(i.includes("401")||i.includes("Unauthorized")||i.includes("invalid_token")||i.includes("token_expired"))return ly.info(`OAuth authentication error detected for tool ${c} on server ${b}`),{success:!1,error:"OAuth authentication failed or tokens have expired. Please re-authenticate the server.",statusCode:401,requiresAuthentication:!0};return(i.includes("404")||i.includes("Not Found"))&&(ly.info(`404 error detected for tool ${c} on server ${b} - may indicate OAuth issues`),j=404,i="Tool endpoint not found (404). This may indicate OAuth authentication issues or the server may not be properly configured."),m instanceof J.Nh?(i=`Failed to call tool: ${i} (Code: ${m.code})`,-32601===m.code?j=404:-32602===m.code?j=400:-32603===m.code&&(j=500)):i=`Failed to call tool: ${i}`,{success:!1,error:i,statusCode:j}}}let lC=(0,o.h)("backend/services/mcp/resources");async function lD(a,b){if(lC.debug("Entering listServerResources method"),!a)return lC.warn(`Server ${b} not connected`),{resources:[],error:"Server not connected"};try{lC.info(`Listing resources for server ${b}`);let c=(await a.listResources()).resources||[];return lC.verbose("Processed resources:",c),{resources:c}}catch(c){if(c instanceof J.Nh&&-32601===c.code)return lC.debug(`Server ${b} does not support resources/list`),{resources:[]};lC.warn(`Failed to list resources for server ${b}:`,c);let a=c instanceof Error?c.message:"Unknown error";return{resources:[],error:a.includes("Connection timeout")?a:`Failed to list resources: ${a}`}}}async function lE(a,b){if(lC.debug("Entering listServerResourceTemplates method"),!a)return lC.warn(`Server ${b} not connected`),{resourceTemplates:[],error:"Server not connected"};try{return lC.info(`Listing resource templates for server ${b}`),{resourceTemplates:(await a.listResourceTemplates()).resourceTemplates||[]}}catch(c){if(c instanceof J.Nh&&-32601===c.code)return lC.debug(`Server ${b} does not support resources/templates/list`),{resourceTemplates:[]};lC.warn(`Failed to list resource templates for server ${b}:`,c);let a=c instanceof Error?c.message:"Unknown error";return{resourceTemplates:[],error:a.includes("Connection timeout")?a:`Failed to list resource templates: ${a}`}}}async function lF(a,b,c){if(lC.debug("Entering readResource method"),!a)return lC.warn(`Server ${b} not found`),{success:!1,error:`Server ${b} not found`,statusCode:404};try{let d=await (0,K.resolveGlobalVars)(c);lC.info(`Reading resource ${d} from server ${b}`);let e=await a.readResource({uri:d});return{success:!0,data:e}}catch(e){lC.warn(`Failed to read resource ${c} on server ${b}:`,e);let a=e instanceof Error?e.message:"Unknown error",d=500;return e instanceof J.Nh?(a=`Failed to read resource: ${a} (Code: ${e.code})`,-32601===e.code?d=404:-32602===e.code&&(d=400)):a=`Failed to read resource: ${a}`,{success:!1,error:a,statusCode:d}}}let lG=(0,o.h)("backend/services/mcp/prompts");async function lH(a,b){if(lG.debug("Entering listServerPrompts method"),!a)return lG.warn(`Server ${b} not connected`),{prompts:[],error:"Server not connected"};try{return lG.info(`Listing prompts for server ${b}`),{prompts:(await a.listPrompts()).prompts||[]}}catch(c){if(c instanceof J.Nh&&-32601===c.code)return lG.debug(`Server ${b} does not support prompts/list`),{prompts:[]};lG.warn(`Failed to list prompts for server ${b}:`,c);let a=c instanceof Error?c.message:"Unknown error";return{prompts:[],error:a.includes("Connection timeout")?a:`Failed to list prompts: ${a}`}}}async function lI(a,b,c,d){if(lG.debug("Entering getPrompt method"),!a)return lG.warn(`Server ${b} not found`),{success:!1,error:`Server ${b} not found`,statusCode:404};try{let e;if(d&&Object.keys(d).length>0){let a=await (0,K.resolveGlobalVars)(d);e="object"==typeof a&&null!==a?a:void 0}lG.info(`Getting prompt ${c} from server ${b}`);let f=await a.getPrompt({name:c,arguments:e});return{success:!0,data:f}}catch(e){lG.warn(`Failed to get prompt ${c} on server ${b}:`,e);let a=e instanceof Error?e.message:"Unknown error",d=500;return e instanceof J.Nh?(a=`Failed to get prompt: ${a} (Code: ${e.code})`,-32601===e.code?d=404:-32602===e.code&&(d=400)):a=`Failed to get prompt: ${a}`,{success:!1,error:a,statusCode:d}}}var lJ=c(57975),lK=c(9148);class lL extends Error{constructor(a){super(`MCP Skills are unavailable: ${a}`),this.name="McpSkillsUnsupportedError",this.reason=a}}function lM(a,b){if(!b||!a)return;let c=a.getServerCapabilities();return(0,r.zT)(c?.extensions?.[r.ET])}function lN(a,b){if(!b)throw new lL("disabled");if(!a)throw new lL("extension-not-negotiated");let c=lM(a,b);if(!c)throw new lL("extension-not-negotiated");return{client:a,capability:c}}async function lO(a){try{return await a()}catch(a){if(a instanceof J.Nh&&-32601===a.code)throw new lL("method-not-found");throw a}}async function lP(a,b,c){let d=lN(a,b);return lO(async()=>await d.client.request({method:"skills/list",params:void 0===c?{}:{cursor:c}},r.lX))}async function lQ(a,b,c){let d=lN(a,b),e=(0,r.Bw)(c).normalizedUri;return lO(async()=>{let a=await d.client.request({method:"skills/get",params:{uri:e}},r.Kg);if(a.skill.uri!==e)throw Error("skills/get returned a different skill URI");return a})}async function lR(a,b,c,d){let e=lN(a,b);if(!0!==e.capability.directoryRead)throw new lL("directory-read-not-negotiated");let f=(0,r.sm)(c);return lO(async()=>await e.client.request({method:"resources/directory/read",params:{uri:f,...void 0===d?{}:{cursor:d}}},r.Pd))}async function lS(a,b,c,d){let e=lN(a,b),f=function(a,b){if("dynamic"===a.resources)throw Error("Dynamic MCP Skills cannot be integrity-verified");let c=(0,r.sm)(b),d=a.resources.find(a=>a.uri===c);if(!d)throw Error("Resource is not declared by the held MCP Skill entry");return d}(c,d),g=(await e.client.readResource({uri:f.uri})).contents;if(!Array.isArray(g)||1!==g.length)throw Error("MCP Skill resource read must return exactly one content item");let h=g[0];if(null===h||"object"!=typeof h||Array.isArray(h))throw Error("MCP Skill resource content is malformed");if(void 0!==h.uri&&(0,r.sm)(h.uri)!==f.uri)throw Error("MCP Skill resource read returned a different URI");let i=function(a){let b="string"==typeof a.text;if(b===("string"==typeof a.blob))throw Error("MCP Skill resource must contain exactly one of text or blob");return b?{bytes:Buffer.from(a.text,"utf8"),text:a.text}:{bytes:function(a){if(a.length%4!=0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a))throw Error("MCP Skill resource contains invalid base64");return Buffer.from(a,"base64")}(a.blob),blob:a.blob}}(h);if(i.bytes.byteLength!==f.size)throw Error("MCP Skill resource size verification failed");if(`sha256:${(0,jx.createHash)("sha256").update(i.bytes).digest("hex")}`!==f.digest)throw Error("MCP Skill resource digest verification failed");return{uri:f.uri,digest:f.digest,size:f.size,..."string"==typeof h.mimeType?{mimeType:h.mimeType}:{},...i,verified:!0}}async function lT(a,b,c,d){if("dynamic"===d.resources)throw Error("Dynamic MCP Skills cannot be integrity-verified");let e=d.resources,f=Array(e.length),g=0,h=async()=>{for(;;){let c=g;if(g+=1,c>=e.length)return;f[c]=await lS(a,b,d,e[c].uri)}};await Promise.all(Array.from({length:Math.min(4,e.length)},()=>h()));let i=f.find(a=>a.uri===d.uri);if(!i||void 0===i.text)throw Error("MCP Skill SKILL.md must be textual content");return!function(a,b){let c,d=a.replace(/\r\n/g,"\n");if(!d.startsWith("---\n"))throw Error("MCP Skill SKILL.md must start with YAML frontmatter");let e=d.indexOf("\n---",4);if(e<0)throw Error("MCP Skill SKILL.md frontmatter is not terminated");let f=d.slice(4,e);try{c=(0,lK.parse)(f)}catch{throw Error("MCP Skill SKILL.md frontmatter is invalid YAML")}if(null===c||"object"!=typeof c||Array.isArray(c)||!(0,lJ.isDeepStrictEqual)(c,b.frontmatter))throw Error("MCP Skill SKILL.md frontmatter does not match its advertised entry")}(i.text,d),{identity:{serverName:c,skillUri:d.uri},protocolRevision:r.v$,entry:d,manifest:i,resources:f,verification:"sha256",trust:"untrusted-external-content"}}function lU(){return global.__mcp_skill_approvals??=new Map,global.__mcp_skill_approvals}let lV=(0,o.h)("backend/services/mcp/runtimeHomeIsolation");async function lW(a,b=process.env){if("stdio"!==a.transport)return!1;let c=function(a){let b=a?.trim().toLowerCase();if(b){if(["1","true","yes","on","isolated"].includes(b))return!0;if(["0","false","no","off","host"].includes(b))return!1}}(b.FLUJO_MCP_RUNTIME_HOME_ISOLATION);if(void 0!==c)return c;if("isolated"===a.runtimeHomeMode)return!0;if("host"===a.runtimeHomeMode)return!1;try{let a=await (0,io.loadItem)(ip.Zg.SPEECH_SETTINGS,void 0);return a?.experimental?.mcpRuntimeHomeIsolation===!0}catch(a){return lV.warn("Could not read the workspace MCP runtime-home preference; defaulting to host home",{error:a}),!1}}var lX=c(35247),lY=c(479);function lZ(a){return"stdio"===a.transport&&jQ(a.command,a.args??[])}let l$=(0,o.h)("utils/mcp/oauthProbe");function l_(a){try{let b=new URL(a);if("https:"!==b.protocol)return!1;let c=b.hostname.toLocaleLowerCase().replace(/^\[|\]$/g,"");if("localhost"===c||c.endsWith(".local")||c.endsWith(".internal")||"::1"===c||c.startsWith("fc")||c.startsWith("fd")||c.startsWith("fe80:"))return!1;let d=c.split(".").map(Number);if(4===d.length&&d.every(Number.isInteger)&&(10===d[0]||127===d[0]||0===d[0]||169===d[0]&&254===d[1]||192===d[0]&&168===d[1]||172===d[0]&&d[1]>=16&&d[1]<=31))return!1;return!0}catch{return!1}}async function l0(a){let b=await fetch(a,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{}}),signal:AbortSignal.timeout(5e3)}),c=b.headers.get("www-authenticate")||"",d=/\bbearer\b/i.test(c),e=c.match(/resource_metadata\s*=\s*"([^"]+)"/i);return{bearer:d,reachable:!0,unauthenticated:b.ok&&!d,resourceMetadataUrl:e?.[1]}}async function l1(a,b=!1){if(b&&!l_(a))return;let c=await fetch(a,{headers:{accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!c.ok)return;let d=await c.json(),e=Array.isArray(d.authorization_servers);if(e||"string"==typeof d.resource)return{authorizationServers:e?d.authorization_servers.filter(a=>"string"==typeof a):void 0}}async function l2(a,b=!1){for(let c of a)if(!b||l_(c))for(let a of function(a){try{let b=new URL(a),c=b.pathname.replace(/\/$/,"");return Array.from(new Set([new URL(`/.well-known/oauth-authorization-server${c}`,b.origin).toString(),new URL(`${c}/.well-known/oauth-authorization-server`,b.origin).toString(),new URL(`${c}/.well-known/openid-configuration`,b.origin).toString()]))}catch{return[]}}(c))try{let b=await fetch(a,{headers:{accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!b.ok)continue;let c=await b.json();if("string"==typeof c.registration_endpoint)return c.registration_endpoint}catch{}}async function l3(a,b={}){try{if(b.publicOnly&&!l_(a))return{oauthCapable:!1};let c=new URL(a).origin,d=await l0(a).catch(b=>(l$.debug(`readAuthChallenge failed for ${a}: ${b instanceof Error?b.message:String(b)}`),{bearer:!1,reachable:void 0,unauthenticated:!1,resourceMetadataUrl:void 0})),e=[];for(let f of(d.resourceMetadataUrl&&e.push(d.resourceMetadataUrl),e.push(new URL("/.well-known/oauth-protected-resource",c).toString()),e)){let e=await l1(f,b.publicOnly).catch(()=>void 0);if(e){let g=e.authorizationServers??[c],h=await l2(g,b.publicOnly);return l$.info(`OAuth capability confirmed for ${a} via ${f}`),{oauthCapable:!0,resourceMetadataUrl:f,authorizationServers:e.authorizationServers,reachable:d.reachable,...h?{dynamicClientRegistration:!0,registrationEndpoint:h}:{dynamicClientRegistration:!1}}}}if(d.bearer)return l$.info(`OAuth capability inferred for ${a} from a Bearer challenge (no resource metadata)`),{oauthCapable:!0,resourceMetadataUrl:d.resourceMetadataUrl,reachable:!0};return l$.debug(`No OAuth capability detected for ${a}`),{oauthCapable:!1,...d.reachable?{reachable:!0}:{},...d.unauthenticated?{unauthenticated:!0}:{}}}catch(b){return l$.debug(`probeOAuthSupport failed for ${a}: ${b instanceof Error?b.message:String(b)}`),{oauthCapable:!1}}}let l4=(0,o.h)("backend/services/mcp/resourceNotifications"),l5=/^[A-Za-z0-9_-]{1,64}$/;function l6(a,b,c,d){let e=d?.conversationId?.trim();if("model"===c&&"create_ticket_for_human"===b&&e&&l5.test(e)&&a?.transport==="stdio"&&(0,jS.AW)(a)?.packageId==="@mario.andreschak/mcp-flujo")return e}function l7(a,b){let c=(0,p.getCurrentWorkspace)();if(c===p.DEFAULT_WORKSPACE)return b;let d=global.__mcp_workspace_registries??=new Map,e=d.get(c);e||(e=new Map,d.set(c,e));let f=e.get(a);return f||(f=b instanceof Set?new Set:new Map,e.set(a,f)),f}function l8(a){return{success:!1,error:a.error,statusCode:a.statusCode,errorType:a.errorType}}void 0===global.__mcp_clients&&(global.__mcp_clients=new Map),void 0===global.__mcp_connecting&&(global.__mcp_connecting=new Set),void 0===global.__mcp_starting_up&&(global.__mcp_starting_up=!0),void 0===global.__mcp_active_transports&&(global.__mcp_active_transports=new Map),void 0===global.__mcp_client_generation&&(global.__mcp_client_generation=new Map),void 0===global.__mcp_tool_schema_hash&&(global.__mcp_tool_schema_hash=new Map);let l9=(0,o.h)("backend/services/mcp/index");function ma(a){let b=a,c=new Set;for(;b&&"object"==typeof b&&!c.has(b);){c.add(b);let a=b.__flujoInnerTransport;if(!a)break;b=a}return b}function mb(a){if("streamable"!==a.transport&&"sse"!==a.transport)return!1;let b=a.headers;return!!b&&Object.entries(b).some(([a,b])=>"authorization"===a.toLowerCase()&&k_(b,a).value.trim().length>0)}class mc{get stderrLogs(){return l7("stderrLogs",this.stderrLogsBase)}get lastConnectionError(){return l7("lastConnectionError",this.lastConnectionErrorBase)}get inFlightConnects(){return l7("inFlightConnects",this.inFlightConnectsBase)}get connectionRetryTimers(){return l7("connectionRetryTimers",this.connectionRetryTimersBase)}get connectionRetryAttempts(){return l7("connectionRetryAttempts",this.connectionRetryAttemptsBase)}get resourceListVersion(){return l7("resourceListVersion",this.resourceListVersionBase)}get pendingResourceUpdates(){return l7("pendingResourceUpdates",this.pendingResourceUpdatesBase)}async clearLegacyInferredOAuthScopesForHeaderAuth(a){try{let b=await this.loadServerConfigs();if(!Array.isArray(b))return;let c=b.findIndex(b=>b.name===a);if(-1===c||"streamable"!==b[c].transport)return;let d=b[c];if(!mb(d)||d.oauthScopes?.length!==1||"read"!==d.oauthScopes[0]||d.oauthClientId||d.oauthClientSecret||d.oauthClientMetadata||d.oauthClientInformation||d.oauthTokens||d.oauthCodeVerifier||d.oauthState||d.authorizationUrl)return;b[c]={...d,oauthScopes:void 0};let e=await (0,s.saveConfig)(new Map(b.map(a=>[a.name,a])));e.success?l9.info(`Removed stale inferred OAuth scopes from header-authenticated server ${a}`):l9.warn(`Failed to remove stale inferred OAuth scopes from ${a}: ${e.error}`)}catch(b){l9.warn(`Failed to clean inferred OAuth scopes for ${a}: ${b instanceof Error?b.message:String(b)}`)}}get clients(){return l7("clients",global.__mcp_clients)}get connectingServers(){return l7("connectingServers",global.__mcp_connecting)}get activeTransports(){return l7("activeTransports",global.__mcp_active_transports)}get clientGenerations(){return l7("clientGenerations",global.__mcp_client_generation)}get toolSchemaHashes(){return l7("toolSchemaHashes",global.__mcp_tool_schema_hash)}static{this.MAX_STDERR_LOG_ENTRIES=200}appendStderrLog(a,b){let c=this.stderrLogs.get(a)||[];c.push(b),c.length>mc.MAX_STDERR_LOG_ENTRIES&&c.splice(0,c.length-mc.MAX_STDERR_LOG_ENTRIES),this.stderrLogs.set(a,c)}deregisterClient(a){this.clients.delete(a),this.activeTransports.delete(a);kJ(a);let b=(0,p.getCurrentWorkspace)();for(let c of Array.from(kA.values()))c.workspace===b&&c.serverName===a&&(c.resolveElicitation?.({action:"cancel"}),c.abortController.abort(),c.rejectPrompt(Error("Authorization was cancelled because the MCP connection closed.")),kL(c));(0,k5.HW)(a)}onResourceListChanged(a){let b=this.resourceListVersion.get(a)??0;this.resourceListVersion.set(a,b+1),l9.debug(`onResourceListChanged: server=${a} version=${b+1}`)}onResourceUpdated(a,b){let c=this.pendingResourceUpdates.get(a)??new Set;c.add(b),this.pendingResourceUpdates.set(a,c),l9.debug(`onResourceUpdated: server=${a} uri=${b}`)}getResourceListVersion(a){return this.resourceListVersion.get(a)??0}async subscribeToResource(a,b){try{let c=this.getClient(a);if(!c)return;let d=c.getServerCapabilities?.();if(!d?.resources?.subscribe)return;await c.subscribeResource({uri:b}),l9.debug(`subscribeToResource: server=${a} uri=${b}`)}catch(c){l9.debug(`subscribeToResource: ignored error for ${a}/${b}:`,c)}}clearRetryTimer(a){let b=this.connectionRetryTimers.get(a);b&&(clearTimeout(b),this.connectionRetryTimers.delete(a),l9.debug(`Cleared retry timer for server ${a}`))}scheduleConnectionRetry(a,b){this.clearRetryTimer(a);let c=this.connectionRetryAttempts.get(a)||0;if(c>=5){l9.warn(`Maximum retry attempts (5) reached for server ${a}, stopping retries`),this.connectionRetryAttempts.delete(a);return}let d=Math.min(5e3*Math.pow(2,c),3e5);l9.info(`Scheduling connection retry for server ${a} in ${d}ms (attempt ${c+1}/5)`);let e=setTimeout((0,p.bindToCurrentWorkspace)(async()=>{l9.info(`Attempting to reconnect server ${a} (attempt ${c+1}/5)`);let b=await this.getServerConfig(a);if(!b){l9.info(`Server ${a} configuration not found, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}if(b.disabled){l9.info(`Server ${a} is now disabled, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}let d=this.getClient(a);if(d)try{await d.ping({timeout:5e3}),l9.info(`Server ${a} is already connected and responsive, cancelling retry`),this.connectionRetryAttempts.delete(a);return}catch(b){l9.warn(`Server ${a} has a registered client but ping failed (${b instanceof Error?b.message:String(b)}); reconnecting from scratch`)}this.connectionRetryAttempts.set(a,c+1);try{let e=d?await this.forceReconnect(a):await this.connectServer(b);if(e.success)l9.info(`Successfully reconnected server ${a} after ${c+1} attempts`),this.connectionRetryAttempts.delete(a);else{if(l9.warn(`Failed to reconnect server ${a}: ${e.error}`),e.requiresAuthentication){l9.info(`Server ${a} requires authentication, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}this.scheduleConnectionRetry(a,b)}}catch(c){l9.error(`Error during retry connection for server ${a}:`,c),this.scheduleConnectionRetry(a,b)}}),d);this.connectionRetryTimers.set(a,e)}isStartingUp(){let a=(0,p.getCurrentWorkspace)();return a===p.DEFAULT_WORKSPACE?!0===global.__mcp_starting_up:global.__mcp_starting_up_by_workspace?.get(a)===!0}setStartingUp(a){let b=(0,p.getCurrentWorkspace)();b===p.DEFAULT_WORKSPACE?global.__mcp_starting_up=a:(global.__mcp_starting_up_by_workspace??=new Map).set(b,a),l9.info(`Backend startup state set to: ${a?"starting":"complete"}`)}getClientGeneration(a){return this.clientGenerations.get(a)??0}setToolSchemaHash(a,b,c){this.toolSchemaHashes.set(`${a}\0${b}`,c)}getToolSchemaHash(a,b){return this.toolSchemaHashes.get(`${a}\0${b}`)}getClient(a){let b=this.clients.get(a);if(b&&jC(b)){l9.warn(`getClient: client for ${a} has a closed/aborted connection — evicting it`),this.clients.delete(a);return}return l9.debug(`getClient: Looking for client: ${a}`,b?"Found":"Not found"),b}async loadServerConfigs(){l9.debug("loadServerConfigs: Entering method");try{let a=await (0,s.loadServerConfigs)();if(!Array.isArray(a))return l9.warn("loadServerConfigs: Received non-array response",a),a;return l9.debug(`loadServerConfigs: Loaded ${a.length} server configs`),a}catch(a){return l9.warn("loadServerConfigs: Failed to load server configs:",a),{success:!1,error:`Failed to load server configs: ${a instanceof Error?a.message:"Unknown error"}`}}}async getServerConfig(a){l9.debug(`getServerConfig: Looking up config for server ${a}`);let b=await this.loadServerConfigs();if(!Array.isArray(b))return l9.warn(`getServerConfig: Failed to load configs for ${a}:`,b.error),null;let c=b.find(b=>b.name===a);return c||(l9.warn(`getServerConfig: Server ${a} not found in configs`),null)}async isServerDisabled(a){let b=await this.getServerConfig(a);return b?.disabled===!0}async connectServer(a){let b="string"==typeof a?a:a.name;return z(b,async()=>{let c=this.connectServerInternal(a).finally(()=>{this.inFlightConnects.delete(b)});this.inFlightConnects.set(b,c);let d=await c;if(d.success){var e;let c;e=this.configFingerprint(a),c=w(b),c.generation+=1,c.state="warm",c.configFingerprint=e,c.retryAttempts=0,c.lastError=void 0,c.warmSince=Date.now(),c.lastUsedAt=Date.now(),c.generation}else{let a=this.activeTransports.has(b)&&!this.clients.has(b);!function(a,b,c=!1){let d=w(a);d.state="error",d.lastError=b,d.connectFailures=Math.min(d.connectFailures+1,Number.MAX_SAFE_INTEGER),c&&(d.handshakeFailures+=1),d.retryAttempts+=1}(b,d.error??"unknown connection failure",a)}return d})}configFingerprint(a){if("string"!=typeof a)return[a.transport,a.command??"",(a.args??[]).join(" "),a.url??"",a.websocketUrl??"",a.rootPath??"",a.disabled?"disabled":"enabled"].join("\0")}async connectServerInternal(a){let b;if("string"==typeof a){l9.info(`connectServer: Looking up config for server ${a}`);let c=await this.getServerConfig(a);if(!c)return l9.warn(`connectServer: Server ${a} not found in configs`),{success:!1,error:`Server configuration for "${a}" not found. The server may have been deleted or not properly configured.`};b=c}else b=a;let c="string"==typeof a?b:await this.getServerConfig(b.name),d=c??b;if((c??b).disabled)return l9.info(`connectServer: Server ${b.name} is disabled — refusing to create a client/transport`),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),{success:!1,error:`Server '${b.name}' is disabled. Enable it on the MCP page to use it.`};let e=(0,j.A)();l9.info(`connectServer: Starting connection for server ${b.name} [RequestID: ${e}]`),this.connectingServers.add(b.name);try{this.stderrLogs.set(b.name,[]),b=await k8(b);let a=await lk()&&"websocket"!==b.transport,c=await lW(b),d={enableRuntimeBroker:!0,isolateRuntimeHome:c},e=this.clients.get(b.name);if(e){let{needsNewClient:c,reason:f}=function(a,b,c=!1,d){if(k7.debug("Entering shouldRecreateClient method"),jC(a))return{needsNewClient:!0,reason:"Existing connection is closed"};if((a.__flujoCapKey??"")!==k6(b))return{needsNewClient:!0,reason:"Client capabilities (sampling/elicitation/MCP Apps/Skills) changed"};let e=!0===a.__flujoBeta,f=c&&"websocket"!==b.transport;if(e!==f)return{needsNewClient:!0,reason:f?"Beta MCP protocol enabled":"Beta MCP protocol disabled"};if(e){let c=a.transport;if(!c||c.__flujoKind!==b.transport)return{needsNewClient:!0,reason:`Transport type changed to ${b.transport}`};if("stdio"===b.transport){if(c.__flujoStdioKey!==ld(b,d?.isolateRuntimeHome===!0))return{needsNewClient:!0,reason:"Connection parameters changed"}}else if(c.__flujoHttpKey!==le(b))return{needsNewClient:!0,reason:`${b.transport} auth/connection parameters changed`};return{needsNewClient:!1}}if("websocket"===b.transport){if(!(a.transport instanceof iz))return{needsNewClient:!0,reason:"Transport type changed to websocket"}}else if("streamable"===b.transport){if(!(a.transport instanceof jr))return{needsNewClient:!0,reason:"Transport type changed to streamable"};let c=a.transport,d=c._url?.toString();if(void 0!==d&&d!==new URL(b.serverUrl).toString())return{needsNewClient:!0,reason:"Streamable server URL changed"};let e=c.__flujoHttpKey;if(!e)return{needsNewClient:!0,reason:"Existing streamable transport has no config key"};if(e!==le(b))return{needsNewClient:!0,reason:"Streamable auth/connection parameters changed"}}else if("sse"===b.transport){if(!(a.transport instanceof jt))return{needsNewClient:!0,reason:"Transport type changed to sse"};let c=a.transport,d=c._url?.toString();if(void 0!==d&&d!==new URL(b.serverUrl).toString())return{needsNewClient:!0,reason:"SSE server URL changed"};let e=c.__flujoHttpKey;if(!e)return{needsNewClient:!0,reason:"Existing sse transport has no config key"};if(e!==le(b))return{needsNewClient:!0,reason:"SSE auth/connection parameters changed"}}else{if(!(a.transport instanceof iy))return{needsNewClient:!0,reason:"Transport type changed to stdio"};if("stdio"!==b.transport)return{needsNewClient:!0,reason:"Transport type changed from stdio"};let c=a.transport.__flujoStdioKey;if(!c)return{needsNewClient:!0,reason:"Existing stdio transport has no config key"};if(c!==ld(b,d?.isolateRuntimeHome===!0))return{needsNewClient:!0,reason:"Connection parameters changed"}}return{needsNewClient:!1}}(e,b,a,d);if(!c)return l9.info(`connectServer: Server ${b.name} is already connected`),this.lastConnectionError.delete(b.name),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),await this.clearLegacyInferredOAuthScopesForHeaderAuth(b.name),{success:!0};l9.info(`connectServer: Existing client for ${b.name} is stale (${f}), recreating`),this.deregisterClient(b.name);try{await li(e,b.name,b)}catch(a){l9.debug(`connectServer: error closing stale client for ${b.name}: ${a instanceof Error?a.message:String(a)}`)}e=void 0}e=a?lm(b):lf(b);let f=a?lo(b,d):lg(b,d);if("stdio"===b.transport&&kF(e,b.name,a?lp.get(f):void 0),a){let a=e.setNotificationHandler?.bind(e);a&&(a("notifications/resources/list_changed",(0,p.bindToCurrentWorkspace)(()=>{this.onResourceListChanged(b.name)})),a("notifications/resources/updated",(0,p.bindToCurrentWorkspace)(a=>{let c=a?.params?.uri;c&&this.onResourceUpdated(b.name,c)})))}else!function(a,b,c,d){try{a.setNotificationHandler(J.hh,a=>{l4.debug(`resourceListChanged notification received for ${b}`),c(b)})}catch(a){l4.warn(`registerResourceNotificationHandlers: failed to register list_changed for ${b}`,a)}if(d)try{a.setNotificationHandler(J.cL,a=>{let c=a.params?.uri;c&&(l4.debug(`resourceUpdated notification received for ${b} uri=${c}`),d(b,c))})}catch(a){l4.warn(`registerResourceNotificationHandlers: failed to register resource_updated for ${b}`,a)}}(e,b.name,(0,p.bindToCurrentWorkspace)(a=>this.onResourceListChanged(a)),(0,p.bindToCurrentWorkspace)((a,b)=>this.onResourceUpdated(a,b)));let g=ma(f).stderr;if(g&&"function"==typeof g.on){let a=b.name;g.on("data",(0,p.bindToCurrentWorkspace)(b=>{let c=b.toString();l9.warn(`stderr: [${a}]: ${c}`),this.appendStderrLog(a,c)}))}if(f.onclose=(0,p.bindToCurrentWorkspace)(()=>{this.activeTransports.get(b.name)!==f?l9.debug(`connectServer: ignoring close event from a stale/deregistered transport for ${b.name}`):(l9.warn(`connectServer: Connection closed for server ${b.name}`),this.deregisterClient(b.name),this.getServerConfig(b.name).then(a=>{!a||a.disabled?l9.info(`Server ${b.name} is now disabled, skipping reconnection logic`):(l9.info(`Connection closed for enabled server ${b.name}, scheduling reconnection`),this.scheduleConnectionRetry(b.name,a))}).catch(a=>{l9.warn(`Error checking server config for ${b.name} during onclose:`,a)}))}),f.onerror=(0,p.bindToCurrentWorkspace)(a=>{let c;if((c=a instanceof Error?a.message:String(a)).includes("SSE stream disconnected")||c.includes("Failed to reconnect SSE stream")||c.includes("Maximum reconnection attempts")||/\bterminated\b/i.test(c))return void l9.debug(`connectServer: transient SSE stream disconnect for ${b.name} (self-healing, ignored): ${a instanceof Error?a.message:String(a)}`);if(this.activeTransports.get(b.name)!==f)return void l9.debug(`connectServer: ignoring error event from a stale/deregistered transport for ${b.name}`);if(l9.error(`connectServer: Transport error for server ${b.name}:`),a instanceof Error){l9.error(`Error name: ${a.name}`),l9.error(`Error message: ${a.message}`),l9.error(`Error stack: ${a.stack}`);let b=a.code;void 0!==b&&l9.error(`Error code: ${b}`),l9.error(`Error chain: ${jG(a)}`)}else if(a&&"object"==typeof a){let b=Object.getPrototypeOf(a),c="string"==typeof b?.constructor?.name?b.constructor.name:"Unknown";l9.error(`Error type: ${typeof a}`),l9.error(`Error constructor: ${c}`);let d=Object.getOwnPropertyNames(a);d.length>0?(l9.error(`Error properties: ${d.join(", ")}`),d.forEach(b=>{try{let c=a[b];l9.error(` ${b}: ${"function"==typeof c?"[Function]":JSON.stringify(c)}`)}catch(a){l9.error(` ${b}: [Unable to serialize: ${a}]`)}})):l9.error("Error object has no enumerable properties");try{let b=JSON.stringify(a);l9.error(`JSON stringified error: ${b}`)}catch(a){l9.error(`Cannot JSON stringify error: ${a}`)}}else l9.error(`Error value: ${String(a)} (type: ${typeof a})`);this.appendStderrLog(b.name,`Transport error: ${jG(a)}`),this.deregisterClient(b.name),this.getServerConfig(b.name).then(a=>{!a||a.disabled?l9.info(`Server ${b.name} is now disabled, skipping reconnection after transport error`):(l9.info(`Transport error for enabled server ${b.name}, scheduling reconnection`),this.scheduleConnectionRetry(b.name,a))}).catch(a=>{l9.warn(`Error checking server config for ${b.name} during onerror:`,a)})}),await e.connect(f),"stdio"===b.transport&&a&&lq(f),this.clients.set(b.name,e),this.activeTransports.set(b.name,f),this.clientGenerations.set(b.name,this.getClientGeneration(b.name)+1),kH(e))try{await kI(e,b.name,{force:!0})}catch(a){l9.warn(`mcp-stdio-oauth readiness probe failed for ${b.name}:`,a)}this.lastConnectionError.delete(b.name),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),await this.clearLegacyInferredOAuthScopesForHeaderAuth(b.name);let h=function(a){if(ll(a))try{return a.getNegotiatedProtocolVersion()}catch{return}}(e);return l9.info(`connectServer: Successfully connected to ${b.name}`+(h?` (beta SDK, negotiated MCP protocol ${h})`:"")),{success:!0}}catch(j){let a;"stdio"===b.transport&&(0,k5.HW)(b.name),l9.error(`connectServer: Failed to connect to server ${b.name}:`,j);let c=j instanceof Error?j.message:String(j),e=jK(j),f=jJ(j),g=mb(d);if(f&&!g&&("streamable"===b.transport||"sse"===b.transport)){let c=b.serverUrl;c&&(a=(await l3(c)).oauthCapable)}if(e||a){if(l9.info(`OAuth authentication error detected for server ${b.name}: ${c}`),"streamable"===b.transport&&a){let a=b;if(!a.oauthScopes||0===a.oauthScopes.length){l9.info(`Dynamically enabling OAuth for server ${b.name} after capability confirmation`);try{let c={...a,oauthScopes:["read"]},d=await this.loadServerConfigs();if(Array.isArray(d)){let a=d.findIndex(a=>a.name===b.name);-1!==a&&(d[a]=c,await (0,s.saveConfig)(new Map(d.map(a=>[a.name,a]))),l9.info(`Updated config for ${b.name} to enable OAuth`))}}catch(a){l9.warn(`Failed to update config for ${b.name} to enable OAuth:`,a)}}}return{success:!1,error:"OAuth authentication failed or tokens have expired. Please re-authenticate.",requiresAuthentication:!0,oauthCapable:!0}}if(f)return{success:!1,error:c,requiresAuthentication:!0,oauthCapable:a};let h=this.stderrLogs.get(b.name)||[],i=jH(j,b,h);return this.lastConnectionError.set(b.name,i),{success:!1,error:i}}finally{this.connectingServers.delete(b.name)}}async testConnection(a,b,c){l9.info(`testConnection: Testing connection to ${a.name||"(unnamed)"} via ${a.transport} transport`);let d=a=>{try{b?.(a)}catch{}},e=[],f=null,g=null;try{var h;let b,i=a,j=c?.storedName||a.name;if(("streamable"===a.transport||"sse"===a.transport)&&j){let b=await this.loadServerConfigs(),c=Array.isArray(b)?b.find(a=>a.name===j):void 0,d=c?.headers,e=a.headers;i={...a,headers:function(a,b){if(!a)return a;let c={};for(let[d,e]of Object.entries(a)){if(!d)continue;let{value:a,isSecret:f}=k_(e,d);if(f&&k0(a)){let a=b?.[d];void 0!==a&&(c[d]=a);continue}c[d]=e}return c}(e,d)}}let k=await k8(i),l=await lk()&&"websocket"!==k.transport,m={isolateRuntimeHome:await lW(k)};f=l?lm(k):lf(k),g=l?lo(k,m):lg(k,m),"stdio"===k.transport&&kF(f,k.name,l?(h=g,lp.get(h)):void 0);let n=ma(g).stderr;n&&"function"==typeof n.on&&n.on("data",a=>{let b=a.toString();e.push(b),d({type:"stderr",data:b})}),g.onerror=a=>{let b=`Transport error: ${jG(a)}`;e.push(b),d({type:"stderr",data:b+"\n"})},d({type:"status",phase:"spawning",message:"Starting server / opening transport..."});let o=lZ(a)?9e4:15e3,p=lZ(a),q=new Promise((a,c)=>{b=setTimeout(()=>c(Error(`Connection timeout after ${o/1e3}s`+(p?" — the package may still be downloading via npx/uvx. Try running the Test again (the package is cached after the first download), or verify the command and network access.":""))),o)});d({type:"status",phase:"handshaking",message:"Performing MCP handshake..."});try{await Promise.race([f.connect(g),q])}finally{b&&clearTimeout(b)}"stdio"===k.transport&&l&&lq(g),d({type:"status",phase:"listing-tools",message:"Handshake OK — listing tools..."});let r=0;try{let a=await f.listTools();r=Array.isArray(a?.tools)?a.tools.length:0}catch(b){l9.debug(`testConnection: connected to ${a.name} but listTools failed: ${b instanceof Error?b.message:String(b)}`)}return l9.info(`testConnection: Successfully connected to ${a.name} (${r} tools)`),d({type:"result",success:!0,data:{toolCount:r}}),{success:!0,data:{toolCount:r}}}catch(g){let b;l9.warn(`testConnection: Failed to connect to ${a.name}:`,g);let c=jJ(g);if(c&&("streamable"===a.transport||"sse"===a.transport)){let c=a.serverUrl;c&&(b=(await l3(c)).oauthCapable)}let f=jH(g,a,e);return d({type:"result",success:!1,error:f,requiresAuthentication:c,oauthCapable:b}),{success:!1,error:f,requiresAuthentication:c,oauthCapable:b}}finally{if(f)try{await li(f,a.name,a,{gracePeriodMs:3e3,killEscalationMs:2e3})}catch(b){l9.debug(`testConnection: error closing test client for ${a.name}: ${b instanceof Error?b.message:String(b)}`)}}}setNodeRoots(a,b,c){for(let d of(0,jT.eS)(a,b,c))this.notifyRootsChanged(d)}notifyRootsChanged(a){let b=this.getClient(a);if(!b)return void l9.debug(`notifyRootsChanged: ${a} not connected, skipping notification`);try{b.sendRootsListChanged().catch(b=>{l9.warn(`notifyRootsChanged: failed to notify ${a}:`,b)}),l9.debug(`notifyRootsChanged: sent roots/list_changed to ${a}`)}catch(b){l9.warn(`notifyRootsChanged: failed to notify ${a}:`,b)}}notifyAllRootsChanged(){for(let a of this.clients.keys())this.notifyRootsChanged(a)}async disconnectServer(a){l9.debug(`disconnectServer: Entering method for server ${a}`),this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a);let b=this.getClient(a);if(!b)return l9.warn(`disconnectServer: Server ${a} not found in clients map`),this.deregisterClient(a),{success:!1,error:`Server ${a} not found`};this.deregisterClient(a);try{let c=await this.getServerConfig(a);return await function(a,b,c){let d=w(a);if(d.teardownPromise)return t.debug(`beginTeardown: folding onto in-flight teardown for ${a} (${b})`),d.teardownPromise;let e=Date.now();d.state="stopping",d.teardownReason=b;let f=(async()=>{d.connectPromise&&await d.connectPromise.catch(()=>void 0);try{let a=await c(d);a&&a.forced&&(d.forcedKills+=1)}catch(c){t.warn(`beginTeardown: close failed for ${a} (${b}): ${c instanceof Error?c.message:String(c)}`)}finally{d.lastTeardownMs=Date.now()-e,d.state="cold",d.warmSince=void 0,d.configFingerprint=void 0,d.teardownPromise=void 0}})();return d.teardownPromise=f,f}(a,"disconnect",async()=>({forced:(await li(b,a,c||void 0)).forced})),l9.info(`disconnectServer: Disconnected server ${a}`),{success:!0}}catch(b){return l9.warn(`disconnectServer: Failed to disconnect server ${a}:`,b),{success:!1,error:`Failed to disconnect server: ${b instanceof Error?b.message:"Unknown error"}`}}}async disconnectAll(a){let b=[],c=[],d=Array.from(new Set(Array.from(this.clients.keys())));for(let e of(l9.info(`disconnectAll: tearing down ${d.length} MCP server(s) (${a})`),d)){this.clearRetryTimer(e),this.connectionRetryAttempts.delete(e);try{(await this.disconnectServer(e)).success?b.push(e):c.push(e)}catch(a){l9.warn(`disconnectAll: teardown of ${e} threw: ${a instanceof Error?a.message:String(a)}`),c.push(e)}}for(let[a]of Array.from(this.connectionRetryTimers))this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a);return l9.info(`disconnectAll: closed=${b.length} failed=${c.length} (${a})`),{closed:b,failed:c}}getLifecycleReport(){let a;return{runtimes:function(a=!1){let b=Date.now();return(a?Array.from(u().values()):y()).map(a=>({server:a.serverName,workspace:a.workspace,state:a.state,generation:a.generation,leases:a.leases,pins:Array.from(a.pins),idleMs:Math.max(0,b-a.lastUsedAt),connectFailures:a.connectFailures,handshakeFailures:a.handshakeFailures,forcedKills:a.forcedKills,lastTeardownMs:a.lastTeardownMs,lastError:a.lastError}))}(),pool:(a=Date.now(),{...D(),idleTtlMs:B(),maxWarmServers:C(),servers:y().map(b=>({server:b.serverName,state:b.state,leases:b.leases,pins:Array.from(b.pins),idleMs:Math.max(0,a-b.lastUsedAt)}))}),liveClients:this.clients.size}}async sweepIdleMcpServers(){return[...await H(this),...await I(this)]}acquireServerLease(a){return F(this,a)}pinServer(a,b){G(a,b)}unpinServer(a,b){x(a)?.pins.delete(b)}async forceReconnect(a){l9.info(`forceReconnect: Forcing fresh connection for server ${a}`);let b=this.clients.get(a);if(b){this.deregisterClient(a);let c=await this.getServerConfig(a);try{await li(b,a,c||void 0)}catch(b){l9.debug(`forceReconnect: error closing stale client for ${a}: ${b instanceof Error?b.message:String(b)}`)}}return this.connectServer(a)}async listServerTools(a,b="model"){if(l9.debug(`listServerTools: Entering method for server ${a}, audience ${b}`),await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return l9.warn(`listServerTools: ${b}`),{tools:[],error:b}}let c=this.getClient(a);c||l9.warn(`listServerTools: Client not found for ${a}`);let d=await lA(c,a,b);if(d.error){l9.warn(`listServerTools: Listing tools for ${a} failed (${d.error}); forcing reconnect and retrying once`);let e=await this.forceReconnect(a);if(!e.success)return l9.warn(`listServerTools: Reconnect for ${a} failed: ${e.error}`),{tools:[],error:e.error||d.error};c=this.clients.get(a),(d=await lA(c,a,b)).error?l9.warn(`listServerTools: Retry after reconnect still failed for ${a}:`,d.error):l9.info(`listServerTools: Recovered after reconnect for ${a}; listed ${d.tools.length} tools`)}else l9.info(`listServerTools: Listed ${d.tools.length} tools for ${a}`);return d}async getExternalAuthorizationStatus(a,b=!1){return kI(this.getClient(a),a,{force:b})}async prepareExternalAuthorization(a,b,c={}){let d=this.getClient(a);if(!d){let b=await this.forceReconnect(a);if(!b.success)throw Error(b.error||`Could not connect to ${a}.`);d=this.getClient(a)}if(!d)throw Error(`MCP server '${a}' is not connected.`);return kO(d,a,b,c)}confirmExternalAuthorization(a,b){let c=kA.get(kE(b));if(!c||c.serverName!==a||!c.prompt)throw Error("The authorization request is no longer active. Start it again.");if(!c.resolveElicitation||c.elicitationResponded)throw Error("The authorization request is no longer awaiting consent. Start it again.");let d=c.resolveElicitation;return c.resolveElicitation=void 0,c.elicitationResponded=!0,d({action:"accept"}),kJ(a),c.prompt}declineExternalAuthorization(a,b){let c=kA.get(kE(b));if(!c||c.serverName!==a||!c.prompt||!c.resolveElicitation)return!1;let d=c.resolveElicitation;return c.resolveElicitation=void 0,c.elicitationResponded=!0,d({action:"decline"}),kJ(a),!0}cancelExternalAuthorization(a,b){return kM(a,b)}async callTool(a,b,d,e,f,g,h,i="host",j,k){if(l9.debug(`callTool: Entering method for server ${a}, tool ${b}, source ${i}`),await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return l9.warn(`callTool: ${b}`),{success:!1,error:b}}let l=this.getClient(a),m=await this.acquireServerLease(a),n=m.lease;n?l=n.client:l||l9.warn(`callTool: Lease acquisition for ${a} failed: ${m.error}`);try{let m;if(l&&kH(l))try{let c=await kI(l,a,{force:!0});if(c.blockingAuthorization){let d=c.blockingAuthorization,e=d.message||`${d.label} authorization is required. Open the MCP page to authenticate before running this flow.`;return l9.warn(`callTool: blocked ${a}/${b}: ${e}`),{success:!1,error:e,errorType:"stdio-oauth-required",statusCode:428,requiresAuthentication:!0}}}catch(c){let b=c instanceof Error?c.message:String(c);return l9.warn(`callTool: mcp-stdio-oauth readiness check failed for ${a}: ${b}`),{success:!1,error:`Could not verify account readiness for '${a}': ${b}`,errorType:"stdio-oauth-status",statusCode:503}}let n="model"===i&&"create_ticket_for_human"===b&&k?.conversationId?await this.getServerConfig(a):null,o=l6(n,b,i,k),p=o?(m=l6(n,b,i,k))?{...d,conversation_id:m}:d:d,q=await lB(l,a,b,p,e,f,h,i,g,j);if(q.success&&o){let a=function(a){if(!a||"object"!=typeof a)return;let b=a.content;if(Array.isArray(b))for(let a of b){if(!a||"object"!=typeof a||"text"!==a.type)continue;let b=a.text;if("string"==typeof b)try{let a=JSON.parse(b);if(!0===a.created&&"string"==typeof a.id&&l5.test(a.id))return a.id}catch{}}}(q.data);if(a)try{let{ticketService:b}=await Promise.resolve().then(c.bind(c,26884));await b.stampPersonaAttributionFromTrustedConversation(a,o)}catch(b){l9.error(`callTool: Failed to stamp trusted ticket attribution for ${a}`,b)}}return l9.info(`callTool: Called tool ${b} on ${a}`),q}finally{n?.release()}}async callToolFromApp(a,b,c,d,e,f){let g=await this.checkMcpAppAccess(a);if(g)return g;let h=await this.callTool(a,b,c,d,void 0,void 0,e,"app",f);if("tool-authorization-list"!==h.errorType)return h;l9.warn(`callToolFromApp: visibility lookup failed for ${a}/${b}; reconnecting and retrying once before dispatch`);let i=await this.forceReconnect(a);return i.success?h=await this.callTool(a,b,c,d,void 0,void 0,e,"app",f):{success:!1,error:i.error||h.error,statusCode:h.statusCode}}async isMcpAppAccessEnabled(a){let b=await this.getServerConfig(a);return b?.disabled!==!0&&b?.enableMcpApps===!0}async checkMcpAppAccess(a){if(await this.isMcpAppAccessEnabled(a))return null;let b=`MCP Apps are not enabled for server '${a}'. Enable them on the MCP page before opening or using this app.`;return l9.warn(`MCP App access denied: ${b}`),{success:!1,error:b,statusCode:403}}async readResourceFromApp(a,b){let c=await this.checkMcpAppAccess(a);return c||this.readResource(a,b)}async listWithReconnect(a,b,c){if(await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return l9.warn(`listWithReconnect: ${b}`),{...c,error:b}}let d=this.getClient(a);d||l9.warn(`listWithReconnect: Client not found for ${a}`);let e=await b(d,a);if(!e.error)return e;l9.warn(`listWithReconnect: Listing for ${a} failed (${e.error}); forcing reconnect and retrying once`);let f=await this.forceReconnect(a);return f.success?(d=this.clients.get(a),(e=await b(d,a)).error?l9.warn(`listWithReconnect: Retry after reconnect still failed for ${a}:`,e.error):l9.info(`listWithReconnect: Recovered after reconnect for ${a}`),e):(l9.warn(`listWithReconnect: Reconnect for ${a} failed: ${f.error}`),{...c,error:f.error||e.error})}async listServerResources(a){return l9.debug(`listServerResources: Entering method for server ${a}`),this.listWithReconnect(a,lD,{resources:[]})}async listServerResourceTemplates(a){return l9.debug(`listServerResourceTemplates: Entering method for server ${a}`),this.listWithReconnect(a,lE,{resourceTemplates:[]})}async readResource(a,b){l9.debug(`readResource: Entering method for server ${a}, uri ${b}`);let c=this.getClient(a);c||l9.warn(`readResource: Client not found for ${a}`);let d=await lF(c,a,b);return l9.info(`readResource: Read resource ${b} on ${a}`),d}async prepareMcpSkillsClient(a){let b=await this.getServerConfig(a);if(!b)return{success:!1,error:`MCP server '${a}' was not found.`,statusCode:404};if(b.disabled)return{success:!1,error:`Server '${a}' is disabled. Enable it on the MCP page to use it.`,statusCode:409,errorType:"disabled"};if(!0!==b.enableMcpSkills)return{success:!1,error:`MCP Skills are disabled for server '${a}'.`,statusCode:409,errorType:"skills_disabled"};let c=await this.connectServer(a);if(!c.success)return{success:!1,error:c.error||`Failed to connect to MCP server '${a}'.`,statusCode:c.statusCode||502};let d=this.getClient(a),e=lM(d,!0);return d&&e?{success:!0,data:{client:d,capability:e}}:{success:!1,error:`Server '${a}' does not advertise ${r.ET}.`,statusCode:404,errorType:"skills_unsupported"}}async getServerSkillsCapability(a){let b=await this.prepareMcpSkillsClient(a);return b.success?b.data?.capability:void 0}async listServerSkills(a,b){let c=await this.getServerConfig(a);if(!c||c.disabled||!0!==c.enableMcpSkills)return{resultType:"complete",skills:[],serverName:a,availability:"disabled",...!c?{error:`MCP server '${a}' was not found.`}:{}};let d=await this.prepareMcpSkillsClient(a);if(!d.success||!d.data)return{resultType:"complete",skills:[],serverName:a,availability:"skills_unsupported"===d.errorType?"unsupported":"available",..."skills_unsupported"===d.errorType?{}:{error:d.error}};let e=async a=>lP(a,!0,b);try{return{...await e(d.data.client),serverName:a,availability:"available",capability:d.data.capability}}catch(b){if(b instanceof lL)return{resultType:"complete",skills:[],serverName:a,availability:"unsupported"};if((await this.forceReconnect(a)).success){let c=this.getClient(a);try{let b=await e(c),d=lM(c,!0);return{...b,serverName:a,availability:"available",...d?{capability:d}:{}}}catch(a){b=a}}return{resultType:"complete",skills:[],serverName:a,availability:"available",error:b instanceof Error?b.message:"Failed to list MCP Skills."}}}async getServerSkill(a,b){let c=await this.prepareMcpSkillsClient(a);if(!c.success||!c.data)return l8(c);try{return{success:!0,data:await lQ(c.data.client,!0,b)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Failed to get MCP Skill.",statusCode:a instanceof lL?404:502}}}async readServerSkillDirectory(a,b,c){let d=await this.prepareMcpSkillsClient(a);if(!d.success||!d.data)return l8(d);try{return{success:!0,data:await lR(d.data.client,!0,b,c)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Failed to read MCP Skill directory.",statusCode:a instanceof lL?404:502}}}async readVerifiedSkillResource(a,b,c){let d=await this.prepareMcpSkillsClient(a);if(!d.success||!d.data)return l8(d);let e=await this.getServerSkill(a,b);if(!e.success||!e.data)return l8(e);try{return{success:!0,data:await lS(d.data.client,!0,e.data.skill,c)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Failed to verify MCP Skill resource.",statusCode:422}}}async loadVerifiedSkill(a,b,c){let d=await this.prepareMcpSkillsClient(a);if(!d.success||!d.data)return l8(d);let e=await this.getServerSkill(a,b);if(!e.success||!e.data)return l8(e);if("dynamic"===e.data.skill.resources)return{success:!1,error:"Dynamic MCP Skills cannot be integrity-verified.",statusCode:422};let f=(0,r.Bw)(e.data.skill.uri).normalizedUri,g=e.data.skill.resources.find(a=>a.uri===f);if(!g)return{success:!1,error:"MCP Skill manifest metadata is missing.",statusCode:422};if(!function(a,b=Date.now()){let c=function(a){let b=a.conversationId.trim(),c=a.serverName.trim();if(!b||b.length>512)throw Error("A valid conversation ID is required to approve an MCP Skill.");if(!c||c.length>512)throw Error("A valid MCP server name is required to approve a Skill.");return{conversationId:b,serverName:c,skillUri:(0,r.Bw)(a.skillUri).normalizedUri,manifestDigest:(0,r.cU)(a.manifestDigest)}}(a),d=(0,p.getCurrentWorkspace)(),e=JSON.stringify([d,c.conversationId,c.serverName,c.skillUri]),f=lU().get(e);if(!f)return;let g=(0,r.BC)(c.serverName,c.skillUri,c.manifestDigest),h=(0,r.BC)(f.serverName,f.skillUri,f.manifestDigest);return f.expiresAt<=b||f.workspace!==d||f.conversationId!==c.conversationId||h!==g?void lU().delete(e):f}({conversationId:c,serverName:a,skillUri:f,manifestDigest:g.digest}))return{success:!1,error:"This MCP Skill is not approved for the current conversation and manifest digest.",statusCode:403,errorType:"skills_approval_required"};try{return{success:!0,data:await lT(d.data.client,!0,a,e.data.skill)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Failed to load MCP Skill.",statusCode:422}}}async listServerPrompts(a){return l9.debug(`listServerPrompts: Entering method for server ${a}`),this.listWithReconnect(a,lH,{prompts:[]})}async getPrompt(a,b,c){l9.debug(`getPrompt: Entering method for server ${a}, prompt ${b}`);let d=this.getClient(a);d||l9.warn(`getPrompt: Client not found for ${a}`);let e=await lI(d,a,b,c);return l9.info(`getPrompt: Got prompt ${b} on ${a}`),e}async resolveOAuthSecretForSave(a,b){return(k0(a)&&(a=b??""),a)?a.startsWith("${global:")?a:this.encryptSecretForSave(a):""}async encryptSecretForSave(a){if(a.startsWith("encrypted_failed:"))throw Error("MCP credential encryption failed");if(a.startsWith("encrypted:")&&a.length>10)return a;let b=await (0,lX.Rs)(a);if(!b.startsWith("encrypted:")||b.length<=10)throw Error("MCP credential encryption failed");return b}async resolveEnvForSave(a,b){let c={};for(let[d,e]of Object.entries((0,lY.ds)(a))){let a="string"==typeof e?e:e.value,f=b?.[d],g="object"==typeof f&&f.metadata.isSecret;if(!("string"==typeof e?g||kZ(d):e.metadata.isSecret)){c[d]=e;continue}k0(a)&&(void 0===f||k0(a="string"==typeof f?f:f.value))||(c[d]={value:!a||k$(a)?a:await this.encryptSecretForSave(a),metadata:{isSecret:!0}})}return c}async resolveHeadersForSave(a,b){let c={};for(let[d,e]of Object.entries(a||{})){if(!d)continue;let{value:a}=k_(e,d),{isSecret:f}=k_(e,d);if(!f){""!==a&&(c[d]={value:a,metadata:{isSecret:!1}});continue}if(k0(a)){let c=b?.[d];if(void 0===c||k0(a=k_(c,d).value))continue}if(a){if(k$(a)){c[d]={value:a,metadata:{isSecret:!0}};continue}c[d]={value:await this.encryptSecretForSave(a),metadata:{isSecret:!0}}}}return c}async ensureManagedServerRootDir(a){try{let b=(a.rootPath||"").trim();if(!b)return;let c=["streamable","sse","websocket"].includes(a.transport),d="stdio"===a.transport&&(a.source?.type==="registry"||a.source?.type==="marketplace");if(!c&&!d)return;let e=n().resolve((0,p.getWorkspaceDataDir)(),b);if(n().dirname(e)===e)return;if(d){let a=n().join((0,p.getWorkspaceDataDir)(),"mcp-servers"),b=n().relative(a,e);if(!b||b.startsWith("..")||n().isAbsolute(b))return}await l().mkdir(e,{recursive:!0}),l9.debug(`ensureManagedServerRootDir: ensured ${e} for ${a.name}`)}catch(b){l9.warn(`ensureManagedServerRootDir: could not create root dir for ${a.name}:`,b)}}async updateServerConfig(a,b){l9.debug(`updateServerConfig: Entering method for server ${a}`);let d=await this.loadServerConfigs();if(!Array.isArray(d))return l9.warn("updateServerConfig: Failed to load configs:",d.error),d;let e=d.find(b=>b.name===a),f=!!e&&"string"==typeof b.name&&b.name!==a;if(f&&d.some(a=>a.name===b.name))return l9.warn(`updateServerConfig: Refusing to rename ${a} -> ${b.name}: name already in use`),{success:!1,error:`A server named "${b.name}" already exists`};if(!e&&b.name)l9.info(`updateServerConfig: Creating new server config for ${b.name}`),e={name:b.name,transport:"stdio",command:"",args:[],env:{},disabled:!1,_buildCommand:"",_installCommand:"",rootPath:""},d.push(e);else if(!e)return l9.warn(`updateServerConfig: Server ${a} not found`),{success:!1,error:`Server ${a} not found`};b={...b};try{void 0!==b.env&&(b.env=await this.resolveEnvForSave(b.env,e.env));let a=b.oauthClientSecret;if(void 0!==a){let c=e.oauthClientSecret;b.oauthClientSecret=await this.resolveOAuthSecretForSave(a,c)}let c=b.headers;if(void 0!==c){let a=e.headers;b.headers=await this.resolveHeadersForSave(c,a)}}catch{return{success:!1,error:"Failed to encrypt MCP credentials; configuration was not saved"}}let g={...e};g={...e,...b};let h=JSON.stringify(e.roots??[])!==JSON.stringify(g.roots??[])||(e.rootPath??"")!==(g.rootPath??""),i=d.findIndex(b=>b.name===a);-1!==i?d[i]=g:g.name&&d.push(g);let j=await (0,s.saveConfig)(new Map(d.map(a=>[a.name,a])));if(!j.success)return l9.warn(`updateServerConfig: Failed to save config for ${a}:`,j.error),j;if(await this.ensureManagedServerRootDir(g),f)try{let{flowService:b}=await Promise.resolve().then(c.bind(c,22605)),d=await b.migrateMcpServerReferences(a,g.name);d.success?d.migratedReferences>0&&l9.info(`updateServerConfig: Migrated ${d.migratedReferences} MCP reference(s) across ${d.migratedFlows} flow(s)`):l9.warn("updateServerConfig: Server rename succeeded, but some flow references could not be migrated",d)}catch(a){l9.warn("updateServerConfig: Server rename succeeded, but flow-reference migration failed",a)}return f?(this.clients.has(a)?await this.disconnectServer(a):(this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a)),this.stderrLogs.delete(a),this.lastConnectionError.delete(a),await this.handleConnectionStateChange(g.name,g)):await this.handleConnectionStateChange(a,g),h&&this.notifyRootsChanged(g.name),l9.info(`updateServerConfig: Successfully updated config for ${a}${f?` (renamed to ${g.name})`:""}`),g}async handleConnectionStateChange(a,b){l9.debug(`handleConnectionStateChange: Entering method for server ${a}`);let c=!!this.getClient(a),d=!b.disabled;if(c&&!d){l9.info(`handleConnectionStateChange: Disconnecting disabled server ${a}`);try{await this.disconnectServer(a)}catch(b){l9.warn(`handleConnectionStateChange: Failed to disconnect server ${a} during update:`,b)}}else!c&&d?(l9.info(`handleConnectionStateChange: Connecting previously disabled server ${a}`),await this.connectServer(b)):c&&d?(l9.info(`handleConnectionStateChange: Re-applying config to connected server ${a}`),await this.connectServer(b)):d||(l9.info(`handleConnectionStateChange: Clearing retry timers for disabled server ${a}`),this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a))}async clearRetryTimersForDisabledServers(){l9.debug("clearRetryTimersForDisabledServers: Checking for disabled servers with active retry timers");try{let a=await this.loadServerConfigs();if(!Array.isArray(a))return void l9.warn("clearRetryTimersForDisabledServers: Failed to load server configs");for(let b of a.filter(a=>a.disabled))this.connectionRetryTimers.has(b.name)&&(l9.info(`clearRetryTimersForDisabledServers: Clearing retry timer for disabled server ${b.name}`),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name))}catch(a){l9.error("clearRetryTimersForDisabledServers: Error clearing retry timers:",a)}}async deleteServerConfig(a){l9.debug(`deleteServerConfig: Entering method for server ${a}`),this.clients.has(a)&&(l9.info(`deleteServerConfig: Disconnecting server ${a} before deletion`),await this.disconnectServer(a));let b=await this.loadServerConfigs();if(!Array.isArray(b))return l9.warn("deleteServerConfig: Failed to load configs:",b.error),b;let c=b.findIndex(b=>b.name===a);if(-1===c)return l9.warn(`deleteServerConfig: Server ${a} not found in configs`),{success:!1,error:`Server ${a} not found`};b.splice(c,1),l9.debug(`deleteServerConfig: Saving updated configs after deleting ${a}`);let d=await (0,s.saveConfig)(new Map(b.map(a=>[a.name,a])));return d.success?l9.info(`deleteServerConfig: Successfully deleted server ${a}`):l9.warn(`deleteServerConfig: Error saving configs after deleting ${a}:`,d.error),d}async getServerStatus(a){let b,c=await this.getServerConfig(a);if(!c)return l9.warn(`getServerStatus: Server ${a} not found`),{status:"error",message:`Server ${a} configuration not found. The server may have been deleted or not properly configured.`};if(c.disabled)return l9.debug(`getServerStatus: Server ${a} is disabled`),{status:"disconnected"};let d=!!this.getClient(a);if("streamable"===c.transport&&!d&&c.oauthScopes&&c.oauthScopes.length>0){if(!c.oauthTokens||!c.oauthTokens.access_token)return l9.info(`getServerStatus: Server ${a} requires OAuth authentication but has no valid tokens`),{status:"requires_authentication",message:"OAuth authentication required. Click the authenticate button to complete the OAuth flow."};let b=c.oauthTokens.issued_at;if(!c.oauthTokens.refresh_token&&c.oauthTokens.expires_in&&b){let d=c.oauthTokens.expires_in;if(Math.floor(Date.now()/1e3)>=b+d)return l9.info(`getServerStatus: OAuth tokens for ${a} have expired and no refresh token is available`),{status:"requires_authentication",message:"OAuth tokens have expired. Please re-authenticate."}}}let e=(this.stderrLogs.get(a)||[]).join("\n").trim(),f=this.lastConnectionError.get(a);if(d){let c=this.getClient(a);if(kH(c))try{if((b=await kI(c,a)).blockingAuthorization){let a=b.blockingAuthorization;return{status:"requires_authentication",message:a.message||`${a.label} authorization is required before this server can be used by unattended flows.`,stderrOutput:e||void 0,stdioOAuth:b}}}catch(b){let a=b instanceof Error?b.message:String(b);return{status:"error",message:`Connected, but the mcp-stdio-oauth readiness check failed: ${a}`,stderrOutput:e||void 0}}}if(d||this.getClient(a))return l9.info(`getServerStatus: Server ${a} is connected`),{status:"connected",stderrOutput:e||void 0,...b?{stdioOAuth:b}:{}};{let b=this.isStartingUp()&&!this.lastConnectionError.has(a);if(this.connectingServers.has(a)||b)return l9.info(`getServerStatus: Server ${a} is still connecting`),{status:"connecting",message:"Server is starting up. This may take a few moments."};if(e&&(e.includes("OAuth authentication required")||e.includes("invalid_token")))return l9.info(`getServerStatus: OAuth authentication error detected for ${a}`),{status:"requires_authentication",message:"OAuth authentication required. Please complete the OAuth flow.",stderrOutput:e};let c=e||f;return c?(l9.info(`getServerStatus: Using ${e?"stderr output":"persisted connection error"} as error message for ${a}`),{status:"error",message:c,stderrOutput:e||void 0}):(l9.info(`getServerStatus: No specific error details available for ${a}`),{status:"error",message:`Server ${a} is configured but not connected. The server process may have crashed or been terminated.`,stderrOutput:void 0})}}async startEnabledServers(){l9.info("Starting all enabled servers"),this.setStartingUp(!0);try{await this.clearRetryTimersForDisabledServers();let a=await this.loadServerConfigs();if(!Array.isArray(a))return void l9.warn("Failed to load server configs, cannot start servers");let b=a.filter(a=>!a.disabled),c=/^(1|true|yes)$/i.test(process.env.FLUJO_MCP_LAZY_START??""),d=b.filter(a=>!0===a.alwaysOn);for(let a of d)G(a.name,"always-on");let e=c?d:b;c?l9.info(`Lazy MCP start: ${b.length} enabled server(s) discovered, warming only ${d.length} always-on server(s)`):(l9.info(`Found ${e.length} enabled servers to start`),l9.debug(`${e}`)),e.forEach(a=>this.connectingServers.add(a.name));let f=Math.max(1,Number(process.env.FLUJO_MCP_BOOT_CONCURRENCY)||2);l9.info(`Connecting ${e.length} enabled servers with boot concurrency ${f}`),await (0,q.P)(e,f,async a=>{l9.info(`Starting server: ${a.name}`),await this.connectServer(a).catch(b=>{l9.error(`Failed to start server ${a.name}:`,b)})})}finally{this.setStartingUp(!1)}}async getAvailableClients(){try{let a=await this.loadServerConfigs();if(!a||"error"in a)return l9.warn("getAvailableClients: Failed to load server configs:",a?.error),[];return(await Promise.all(a.map(async a=>{try{let b=await this.getServerStatus(a.name);return{name:a.name,status:"string"==typeof b?b:b.status,connected:"string"==typeof b?"connected"===b:"connected"===b.status}}catch(b){return l9.warn(`getAvailableClients: Error getting status for ${a.name}:`,b),{name:a.name,status:"error",connected:!1}}}))).map(a=>`${a.name} (${a.status})`)}catch(a){return l9.error("getAvailableClients: Error getting available clients:",a),[]}}constructor(){this.stderrLogsBase=new Map,this.lastConnectionErrorBase=new Map,this.inFlightConnectsBase=new Map,this.connectionRetryTimersBase=new Map,this.connectionRetryAttemptsBase=new Map,this.resourceListVersionBase=new Map,this.pendingResourceUpdatesBase=new Map}}let md=new mc},11554:(a,b,c)=>{"use strict";let d;c.r(b),c.d(b,{INTERRUPTED_TOOL_RESULT_CONTENT:()=>N,_setConversationLogDirForTests:()=>r,allocateSeq:()=>w,appendFromBus:()=>C,appendRawForState:()=>D,deleteConversationLog:()=>H,flushConversationLog:()=>E,hasConversationLog:()=>S,latestSequence:()=>x,projectMessages:()=>I,projectModelContextMessages:()=>J,readConversationLog:()=>G,reconcileConversationLog:()=>M,recoverConversationTranscript:()=>R,recoverMessagesFromLog:()=>P,repairDanglingToolCalls:()=>O,repairTruncatedConversationLog:()=>Q,replaceConversationTranscript:()=>F});var e=c(29021),f=c(33873),g=c.n(f),h=c(91065),i=c(62888),j=c(82964),k=c(28461),l=c(6727);let m=(0,j.h)("backend/execution/flow/conversationLog"),n=new Set(["run:start","run:done","recovery:checkpoint","recovery:transition","recovery:retry","node:enter","node:exit","node:snapshot","node:changed-files","model:dispatch","model:dispatch-result","handoff","message","message:removed","tool:call","tool:result","usage","subflow:start","subflow:done","resource:read","resource:write","error"]),o=/^[A-Za-z0-9_-]+$/,p=()=>d??g().join((0,k.getWorkspaceDataDir)(),"db","conversation-logs"),q=a=>(0,k.workspaceCacheKey)("conversation-log",a);function r(a){let b=d;return d=a,u.clear(),b??a}function s(a){return g().join(p(),`${a}.jsonl`)}let t=new Map,u=new Map;function v(a){if(u.has(q(a)))return;let b=-1;try{for(let c of(0,e.readFileSync)(s(a),"utf-8").split("\n"))if(0!==c.trim().length)try{let a=JSON.parse(c).seq;"number"==typeof a&&Number.isFinite(a)&&a>b&&(b=a)}catch{}}catch(b){"ENOENT"!==b.code&&m.warn(`Could not read conversation log ${a} to seed seq; starting at 0.`,{err:b})}u.set(q(a),b+1)}function w(a){v(a);let b=u.get(q(a));return u.set(q(a),b+1),b}async function x(a){return o.test(a)?(v(a),u.get(q(a))-1):-1}function y(a,b){return(0,l.NU)(async()=>{let c=q(a),d=(t.get(c)??Promise.resolve()).catch(()=>{}).then(async()=>{await e.promises.mkdir(p(),{recursive:!0}),await e.promises.appendFile(s(a),b)});return t.set(c,d),d.finally(()=>{t.get(c)===d&&t.delete(c)})})}function z(a,b){return(0,l.NU)(async()=>{let c=q(a),d=(t.get(c)??Promise.resolve()).catch(()=>{}).then(async()=>{await e.promises.mkdir(p(),{recursive:!0}),await e.promises.writeFile(s(a),b)});return t.set(c,d),d.finally(()=>{t.get(c)===d&&t.delete(c)})})}async function A(a,b){if(a.personaAttribution&&!a.executionAuthority)throw Error("Persona-attributed transcript persistence requires current execution authority.");return a.executionAuthority?a.executionAuthority?.commitWhileCurrent?a.executionAuthority.commitWhileCurrent(b):(await a.executionAuthority.assertCurrent(),b()):b()}function B(a){return`${JSON.stringify(a)}
52
+ ${d}`:f}let jI=["OAuth authentication required","UnauthorizedError","invalid_token","token_expired","HTTP 401","HTTP 403","Missing Authorization header","Authorization header is required"];function jJ(a){if(!(a instanceof Error))return!1;if(jK(a))return!0;let b=a.code;return 401===b||403===b||jI.some(b=>a.message.includes(b))}function jK(a){if(!(a instanceof Error))return!1;if("OAuthAuthenticationRequired"===a.name)return!0;let b=a.errorCode;return"string"==typeof b&&b.length>0||a.message.includes("OAuth authentication required")}var jL=c(98683),jM=c(30314);let jN=new Set(["npx","bunx","uvx","pipx","dlx"]),jO=new Set(["pnpm","yarn","bun","npm"]),jP=new Set(["dlx","exec","x"]);function jQ(a,b=[]){let c=((a||"").split(/[\\/]/).filter(Boolean).pop()||"").toLowerCase().replace(/\.(cmd|exe|bat|ps1)$/i,"");if(jN.has(c))return!0;if(jO.has(c)){let a=(b[0]||"").toLowerCase();return jP.has(a)}return!1}let jR=new Set(["node","npm","npx"]);var jS=c(84022),jT=c(68644),jU=c(14493),jV=c(30670),jW=c(70690);let jX=(0,o.h)("backend/services/mcp/sampling");function jY(a){return a.sampling}function jZ(a){let b=jY(a);return!!(b?.enabled&&b.modelId)}function j$(a){let b=[];return async c=>{let d=jY(a);if(!d?.enabled||!d.modelId)throw new J.Nh(J.O4.InvalidRequest,"Sampling is not enabled for this server");let e=d.maxCallsPerMinute??10,f=Date.now(),g=f-6e4;for(;b.length>0&&b[0]<g;)b.shift();if(b.length>=e)throw jX.warn(`Sampling rate limit (${e}/min) hit for ${a.name}`),new J.Nh(J.O4.InvalidRequest,`Sampling rate limit of ${e}/min exceeded`);b.push(f);let h=await jU.modelService.getModel(d.modelId);if(!h)throw new J.Nh(J.O4.InternalError,`Sampling model not found: ${d.modelId}`);let i=await jU.modelService.resolveAndDecryptApiKey(h.ApiKey);if(!i)throw new J.Nh(J.O4.InternalError,"Could not resolve the sampling model API key");let j=c.params,k=function(a){let b=[];for(let c of(a.systemPrompt&&b.push({role:"system",content:a.systemPrompt}),a.messages||[])){let a=c.content,d=a?.type==="text"&&"string"==typeof a.text?a.text:`[unsupported ${a?.type||"non-text"} content omitted]`;b.push({role:c.role,content:d})}return b}(j),l="number"==typeof j.temperature?j.temperature:.7;jX.info(`Sampling for ${a.name} via model ${h.name} (${k.length} messages)`);let m=(0,jV.getCompletionAdapter)(h),n=d.maxTokens??(0,jW.normalizeMaxTokens)(h.maxTokens),{completion:o}=await m.createCompletion({model:h,apiKey:i,messages:k,temperature:l,maxTokens:n}),p=o.choices?.[0]?.message?.content;return{role:"assistant",content:{type:"text",text:"string"==typeof p?p:""},model:h.name,stopReason:"endTurn"}}}var j_=c(21550),j0=c(94917);let j1=(0,o.h)("backend/services/mcp/elicitationRegistry"),j2=globalThis,j3=j2.__flujoElicitationRegistry??(j2.__flujoElicitationRegistry=new Map),j4="co.com.flujo/mcp-stdio-oauth",j5=`${j4}/status`,j6=`${j4}/start`,j7=Object.freeze({version:"0.1",urlElicitation:!0}),j8=Y.Yj().min(1),j9=Y.Ik({version:Y.eu("0.1"),urlElicitation:Y.eu(!0)}).loose(),ka=Y.Ik({id:j8,provider:Y.Yj().optional(),label:Y.Yj(),state:Y.Yj(),blocksUnattendedUse:Y.zM().default(!0),message:Y.Yj().optional()}).loose(),kb=Y.Ik({}).loose(),kc=Y.Ik({authorizations:Y.YO(ka)}).loose().superRefine((a,b)=>{let c=new Set;a.authorizations.forEach((a,d)=>{c.has(a.id)&&b.addIssue({code:"custom",message:`Duplicate authorization id: ${a.id}`,path:["authorizations",d,"id"]}),c.add(a.id)})}),kd=Y.Ik({authorizationId:j8}).loose(),ke=Y.Ik({authorizationId:j8,state:Y.Yj(),message:Y.Yj().optional()}).loose(),kf=Y.Ik({authorizationId:j8,state:Y.Yj(),message:Y.Yj().optional()}).loose();Y.Ik({[j4]:kf}).loose();let kg=Y.Ik({mode:Y.eu("url"),url:Y.Yj().min(1),message:Y.Yj()}).loose(),kh=Y.Ik({action:Y.k5(["accept","decline","cancel"])}).loose(),ki=Y.Ik({resultType:Y.eu("input_required"),inputRequests:Y.g1(Y.Yj(),Y.Ik({method:Y.eu("elicitation/create"),params:kg}).loose()),requestState:j8}).loose().superRefine((a,b)=>{1!==Object.keys(a.inputRequests).length&&b.addIssue({code:"custom",message:"mcp-stdio-oauth input_required requires exactly one URL input request.",path:["inputRequests"]})});function kj(a){return void 0!==function(a){if(!a||"object"!=typeof a)return;let b=a.extensions;if(!b||"object"!=typeof b)return;let c=j9.safeParse(b[j4]);return c.success?c.data:void 0}(a.getServerCapabilities?.())}async function kk(a,b,c){let d=kd.parse({authorizationId:b}),e=await a.request({method:j6,params:d},ke,c),f=ke.parse(e);if(f.authorizationId!==d.authorizationId)throw Error(`The server returned authorizationId ${f.authorizationId} for a request concerning ${d.authorizationId}.`);return f}async function kl(a,b){let c=kb.parse({}),d=await a.request({method:j5,params:c},kc,b);return kc.parse(d)}let km=new Set(["localhost","127.0.0.1","[::1]","::1"]);class kn extends Error{constructor(a){super(a),this.code="UNSAFE_ELICITATION_URL",this.name="UnsafeElicitationUrlError"}}function ko(a){let b;try{b=new URL(a)}catch{throw new kn("The elicitation URL is malformed.")}if(b.username||b.password)throw new kn("The elicitation URL must not contain embedded credentials.");let c=b.hostname.toLowerCase(),d=km.has(c),e="https:"===b.protocol,f="http:"===b.protocol&&d;if(!e&&!f)throw new kn("The elicitation URL must use HTTPS, except for HTTP loopback URLs.");return Object.freeze({url:b,href:b.href,origin:b.origin,hostname:c,isLoopback:d,hasPunycode:c.split(".").some(a=>a.startsWith("xn--"))})}class kp extends Error{constructor(){super("The MCP server does not advertise the mcp-stdio-oauth extension."),this.code="STDIO_OAUTH_UNSUPPORTED",this.name="StdioOAuthUnsupportedError"}}class kq extends Error{constructor(){super("The MCP client cannot advertise the mcp-stdio-oauth extension and URL elicitation capabilities."),this.code="STDIO_OAUTH_CLIENT_ADVERTISEMENT_REQUIRED",this.name="StdioOAuthClientAdvertisementRequiredError"}}class kr extends Error{constructor(a){super(a),this.code="STDIO_OAUTH_USER_ACTION_REQUIRED",this.name="StdioOAuthUserActionRequiredError"}}class ks extends Error{constructor(){super("MCP 2026-07-28 requires StdioOAuthClientTransport for the extension-defined start MRTR flow."),this.code="STDIO_OAUTH_MODERN_ADAPTER_REQUIRED",this.name="StdioOAuthModernAdapterRequiredError"}}function kt(a){return"id"in a&&("result"in a||"error"in a)}class ku{constructor(a){this.flows=new Map,this.maxRounds=a}beginUserInitiatedStart(a){if(this.activeAuthorizationId)throw Error("An OAuth start flow is already active on this transport.");this.activeAuthorizationId=a}endUserInitiatedStart(){this.activeAuthorizationId=void 0}setUrlElicitationHandler(a){this.urlHandler=a}clear(){this.flows.clear(),this.activeAuthorizationId=void 0}async send(a,b,c){let d;if("id"in a&&"method"in a&&function(a){if(a.method!==j6)return!1;let b=a.params?._meta;return!!b&&"object"==typeof b&&"2026-07-28"===b["io.modelcontextprotocol/protocolVersion"]}(a)){let c=a.params?.authorizationId;this.activeAuthorizationId&&c===this.activeAuthorizationId&&(d=a.id,this.flows.set(a.id,{originalId:a.id,request:a,rounds:0,...void 0===b?{}:{sendOptions:b}}))}try{await c(a,b)}catch(a){throw void 0!==d&&this.flows.delete(d),a}}async receive(a,b,c,d,e){try{await this.handleResponse(a,b,c,d)}catch(f){let d=f instanceof Error?f:Error(String(f));if(kt(a)){let d=this.flows.get(a.id);d&&(this.flows.delete(a.id),c?.({jsonrpc:"2.0",id:d.originalId,error:{code:-32603,message:"OAuth URL elicitation failed"}},b))}e?.(d)}}async handleResponse(a,b,c,d){if(!kt(a))return void c?.(a,b);let e=this.flows.get(a.id);if(!e)return void c?.(a,b);if("error"in a){this.flows.delete(a.id),c?.({...a,id:e.originalId},b);return}let f=ki.safeParse(a.result);if(!f.success){this.flows.delete(a.id),c?.({...a,id:e.originalId},b);return}if(e.rounds>=this.maxRounds)throw Error("OAuth start exceeded the maximum MRTR rounds.");if(!this.urlHandler||!this.activeAuthorizationId)throw Error("Received OAuth input_required without an active user-initiated start.");let g={};for(let[a,b]of Object.entries(f.data.inputRequests))g[a]=await this.urlHandler(b);let h=`mcp-stdio-oauth:${(0,jx.randomUUID)()}`,i={...e.request,id:h,params:{...e.request.params,inputResponses:g,requestState:f.data.requestState}};this.flows.set(h,{...e,rounds:e.rounds+1});try{await d(i,e.sendOptions)}catch(a){throw this.flows.delete(h),a}this.flows.delete(a.id)}}let kv=new WeakMap;class kw{attach(a,b=8){if(this.delegate){if(a!==this.attachedTransport)throw Error("This deferred OAuth MRTR controller is already attached to another transport.");return this.delegate}return this.attachedTransport=a,this.delegate=function(a,b=8){let c=kv.get(a);if(c)return c;let d=new ku(b),e=a.send.bind(a),f=a.onmessage,g=a.onclose,h=a.onerror,i=!1,j=(a,b)=>d.send(a,b,e),k=(a,b)=>{d.receive(a,b,f,e,h)},l=()=>{d.clear(),g?.()};a.send=j,a.onmessage=k,a.onclose=l;let m={beginUserInitiatedStart:a=>d.beginUserInitiatedStart(a),endUserInitiatedStart:()=>d.endUserInitiatedStart(),setUrlElicitationHandler:a=>d.setUrlElicitationHandler(a),dispose(){i||(i=!0,d.clear(),a.send===j&&(a.send=e),a.onmessage===k&&(a.onmessage=f),a.onclose===l&&(a.onclose=g),kv.delete(a))}};return kv.set(a,m),m}(a,b),this.delegate.setUrlElicitationHandler(this.handler),this.delegate}beginUserInitiatedStart(a){if(!this.delegate)throw Error("The deferred OAuth MRTR controller must be attached after MCP connect before start is used.");this.delegate.beginUserInitiatedStart(a)}endUserInitiatedStart(){this.delegate?.endUserInitiatedStart()}setUrlElicitationHandler(a){this.handler=a,this.delegate?.setUrlElicitationHandler(a)}dispose(){this.delegate?.dispose(),this.delegate=void 0,this.attachedTransport=void 0}}function kx(a){return null!==a&&"object"==typeof a?a:void 0}let ky=(0,o.h)("backend/services/mcp/externalAuthorization");({...j7});let kz=global.__mcp_external_authorization_status??(global.__mcp_external_authorization_status=new Map),kA=global.__mcp_external_authorization_sessions??(global.__mcp_external_authorization_sessions=new Map),kB=global.__mcp_stdio_oauth_clients??(global.__mcp_stdio_oauth_clients=new WeakMap);function kC(a){return(0,p.workspaceCacheKey)(a)}function kD(a,b){return`${a}\0${b}`}function kE(a){return kD((0,p.getCurrentWorkspace)(),a)}function kF(a,b,c){if(kB.has(a))return;let d=function(a){var b,c;let d,e,{mcpClient:f,onUrlElicitation:g}=a,h=!1,i=!!(b=f).registerCapabilities&&(b.registerCapabilities({...c={elicitation:{url:{}}},extensions:{...c.extensions,[j4]:{...j7}}}),!0),j=async a=>{var b;let c;if(!e||h)return{action:"cancel"};let d=a&&"object"==typeof a&&"params"in a?a.params:a,f=(b=kg.parse(d),Object.freeze({...c=kg.parse(b),target:ko(c.url)})),i=await g(f);return kh.parse(i)},k=!0===a.installElicitationHandler&&"function"==typeof f.setRequestHandler&&(f.setRequestHandler.call(f,"elicitation/create",j),!0);a.mrtrController?.setUrlElicitationHandler(j);let l=()=>{if(h)throw Error("The mcp-stdio-oauth client has been disposed.");if(!i)throw new kq;if(!kj(f))throw new kp};return{isSupported:()=>!h&&i&&kj(f),async getStatus(a){l();let b=await kl(f,a);return d=new Set(b.authorizations.map(a=>a.id)),b},async start(b,c){if(l(),f.getProtocolEra?.()==="modern"&&!a.mrtrController)throw new ks;let g=Y.Yj().min(1,"Expected a non-empty authorization ID").parse(b);if(!d?.has(g))throw new kr("Start requires an authorizationId from the latest successful status result.");if(e)throw new kr("Only one user-initiated authorization start may be active per client helper.");e=g,a.mrtrController?.beginUserInitiatedStart(g);try{return await kk(f,g,c)}finally{a.mrtrController?.endUserInitiatedStart(),e=void 0}},handleUrlElicitation:j,dispose(){!h&&k&&("function"!=typeof f.removeRequestHandler||f.removeRequestHandler.call(f,"elicitation/create")),a.mrtrController?.setUrlElicitationHandler(void 0),h=!0,e=void 0,d=void 0}}}({mcpClient:a,installElicitationHandler:!1,...c?{mrtrController:c}:{},onUrlElicitation:(0,p.bindToCurrentWorkspace)(async a=>await kN(b,{mode:a.mode,url:a.target.href,message:a.message})??{action:"cancel"})});kB.set(a,d),a.__flujoStdioOAuth=!0}function kG(a){let b=kB.get(a);if(!b)throw Error("This MCP client did not negotiate mcp-stdio-oauth.");return b}function kH(a){if(!a)return!1;let b=!0===a.__flujoStdioOAuth,c=kB.get(a);return b&&!!c?.isSupported()}async function kI(a,b,c={}){if(!kH(a))return{supported:!1,authorizations:[]};let d=kC(b),e=kz.get(d);if(!c.force&&e&&Date.now()-e.timestamp<2e3)return e.value;let f=(await kG(a).getStatus({timeout:8e3})).authorizations.map(a=>({id:a.id,...a.provider?{provider:a.provider}:{},label:a.label,state:a.state,blocksUnattendedUse:a.blocksUnattendedUse,...a.message?{message:a.message}:{}})),g={supported:!0,authorizations:f,blockingAuthorization:f.find(a=>a.blocksUnattendedUse&&"ready"!==a.state)};return kz.set(d,{value:g,timestamp:Date.now()}),g}function kJ(a){kz.delete(kC(a))}function kK(a){let b=(0,p.getCurrentWorkspace)();return Array.from(kA.values()).filter(c=>c.workspace===b&&c.serverName===a).sort((a,b)=>b.createdAt-a.createdAt)[0]}function kL(a){a.timer&&clearTimeout(a.timer),kA.delete(kD(a.workspace,a.sessionId))}function kM(a,b){let c=b?kA.get(kE(b)):kK(a);if(!c||c.serverName!==a)return!1;if(c.resolveElicitation){let a=c.resolveElicitation;c.resolveElicitation=void 0,c.elicitationResponded=!0,a({action:"cancel"})}else c.elicitationResponded,c.abortController.abort();return c.rejectPrompt(Error("Authorization was cancelled.")),!0}async function kN(a,b){if("url"!==b.mode)return;let c=kK(a);if("string"!=typeof b.url||0===b.url.length)return c&&(c.rejectPrompt(Error("The MCP server supplied a malformed authorization URL.")),c.abortController.abort()),{action:"cancel"};if(!c)return ky.warn(`Rejected unsolicited URL elicitation from ${a}`),{action:"cancel"};if(c.abortController.signal.aborted)return ky.warn(`Rejected URL elicitation from cancelled start on ${a}`),{action:"cancel"};if(c.resolveElicitation||c.elicitationResponded)return ky.warn(`Rejected duplicate URL elicitation from ${a}`),{action:"cancel"};try{!function(a,b,c){if(a.prompt)return a.prompt;let d=ko(b),e={sessionId:a.sessionId,authorizationId:a.authorizationId,url:d.href,origin:d.origin,hasPunycode:d.hasPunycode,...c?{message:c}:{}};a.prompt=e,a.resolvePrompt(e)}(c,b.url,b.message)}catch(a){return c.rejectPrompt(a instanceof Error?a:Error(String(a))),c.abortController.abort(),{action:"cancel"}}return new Promise(a=>{c.resolveElicitation=a})}async function kO(a,b,c,d={}){let e,f,g;if(d.signal?.throwIfAborted(),!kH(a))throw Error("This MCP server did not negotiate external authorization support.");let h=(await kI(a,b,{force:!0})).authorizations.find(a=>a.id===c);if(!h)throw Error("The OAuth authorization is no longer available. Refresh and try again.");if("ready"===h.state)return{sessionId:crypto.randomUUID(),authorizationId:c,url:"",origin:"",hasPunycode:!1,alreadyReady:!0};let i=kK(b);if(i&&(kM(b,i.sessionId),kA.has(kD(i.workspace,i.sessionId))))throw Error("The previous authorization request is still closing. Try again in a moment.");d.signal?.throwIfAborted();let j=new Promise((a,b)=>{e=a,f=b}),k={workspace:(0,p.getCurrentWorkspace)(),sessionId:crypto.randomUUID(),serverName:b,authorizationId:c,createdAt:Date.now(),resolvePrompt:e,rejectPrompt:f,promptPromise:j,abortController:new AbortController};k.timer=setTimeout((0,p.bindToCurrentWorkspace)(()=>{let a=k.resolveElicitation;k.resolveElicitation=void 0,k.elicitationResponded=!0,a?.({action:"cancel"}),k.abortController.abort(),k.rejectPrompt(Error("Authorization request timed out."))}),3e5),kA.set(kD(k.workspace,k.sessionId),k);let l=(0,p.bindToCurrentWorkspace)(()=>{kM(b,k.sessionId)});d.signal?.addEventListener("abort",l,{once:!0});let m=(0,p.bindToCurrentWorkspace)(async d=>{if(kJ(b),"ready"===d.state){k.resolvePrompt({sessionId:k.sessionId,authorizationId:c,url:"",origin:"",hasPunycode:!1,alreadyReady:!0}),kL(k);return}let e=(await kI(a,b,{force:!0})).authorizations.find(a=>a.id===c);if(e?.state==="ready"){k.resolvePrompt({sessionId:k.sessionId,authorizationId:c,url:"",origin:"",hasPunycode:!1,alreadyReady:!0}),kL(k);return}k.rejectPrompt(Error("The MCP server completed OAuth start without URL elicitation or ready status.")),kL(k)}),n=(0,p.bindToCurrentWorkspace)(a=>{k.rejectPrompt(a instanceof Error?a:Error(String(a)))}),o=(0,p.bindToCurrentWorkspace)(()=>kL(k));kG(a).start(c,{timeout:3e5,signal:k.abortController.signal}).then(m).catch(n).finally(o);try{return await Promise.race([j,new Promise((a,b)=>{g=setTimeout(()=>b(Error("The MCP server did not present an authorization URL in time.")),3e4)})])}catch(a){throw kM(b,k.sessionId),a}finally{g&&clearTimeout(g),d.signal?.removeEventListener("abort",l)}}let kP=(0,o.h)("backend/services/mcp/taskInputRegistry"),kQ=globalThis,kR=kQ.__flujoMcpTaskInputRegistry??(kQ.__flujoMcpTaskInputRegistry=new Map);function kS(a,b){return(0,p.workspaceCacheKey)(a,b)}let kT=(0,o.h)("backend/services/mcp/elicitation");function kU(a){return a.elicitation}function kV(a){let b=kU(a);return!!b?.enabled}function kW(a){return(0,p.bindToCurrentWorkspace)(async b=>{var c,d,e;let f,g,h,i,j,k=b.params,l=(0,L.PJ)(k?._meta),m=await kN(a.name,k??{});if(m)return m;if(!kV(a))throw new J.Nh(J.O4.MethodNotFound,"Elicitation is not enabled for this server");let n=(0,j0.lx)(a.name);if(!n&&l&&kT.warn(`Task ${l} on ${a.name} requested input outside an attended run; auto-cancelling`),!n)return kT.warn(`Elicitation request from ${a.name} outside an active run; auto-cancelling`),{action:"cancel"};if(n.getUnattended())return kT.warn(`Elicitation request from ${a.name} in unattended run ${n.conversationId}; auto-cancelling`),{action:"cancel"};let o=k?.message??"Additional information required",q=k?.requestedSchema??{type:"object",properties:{}},r=crypto.randomUUID();kT.info(`Suspending for elicitation ${r} from ${a.name} in conv ${n.conversationId}`),l&&(c=a.name,f=kS(c,l),g=Date.now(),(h=kR.get(f)??{outstanding:new Set,answered:new Set,firstRequestedAt:g,lastRequestedAt:g}).answered.has(r)||(h.outstanding.add(r),h.lastRequestedAt=g,kR.set(f,h),kP.info(`Task ${l} on ${c} requested input (elicitation ${r}); outstanding=${h.outstanding.size}`))),j_.$.emitterFor(n.conversationId)({type:"run:awaiting_elicitation",elicitationId:r,message:o,requestedSchema:q});let s=await function(a,b=3e5){let c=(0,p.getCurrentWorkspace)(),d=(0,p.workspaceCacheKey)(a);return new Promise(e=>{let f=setTimeout(()=>{j3.has(d)&&(j1.warn(`Elicitation ${a} timed out after ${b}ms; auto-cancelling`),j3.delete(d),e({action:"cancel"}))},b);j3.set(d,{workspace:c,resolve:e,timer:f})})}(r);return kT.info(`Elicitation ${r} resolved with action=${s.action}`),l&&(d=a.name,e=s.action,i=kS(d,l),!(j=kR.get(i))||!j.outstanding.delete(r)&&j.answered.has(r)||(j.answered.add(r),kR.set(i,j),kP.info(`Task ${l} on ${d} input ${r} resolved with action=${e}; outstanding=${j.outstanding.size}`))),s})}var kX=c(65935);let kY=["key","secret","token","password"],kZ=a=>kY.some(b=>a.toLowerCase().includes(b));function k$(a){return"string"==typeof a&&a.startsWith("${global:")}function k_(a,b){return a&&"object"==typeof a&&"value"in a?{value:a.value??"",isSecret:!!a.metadata?.isSecret}:{value:a??"",isSecret:kZ(b)||"authorization"===b.trim().toLowerCase()}}function k0(a){return a===kX.RJ||a===kX.gF}let k1="io.modelcontextprotocol/ui",k2="text/html;profile=mcp-app",k3=["model","app"];function k4(a,b){return(function(a){let b=a._meta;if(void 0===b)return k3;if(!b||"object"!=typeof b||Array.isArray(b))return[];if(!Object.prototype.hasOwnProperty.call(b,"ui"))return k3;let c=b.ui;if(!c||"object"!=typeof c||Array.isArray(c))return[];if(!Object.prototype.hasOwnProperty.call(c,"visibility"))return k3;let d=c.visibility;return Array.isArray(d)&&d.every(a=>"model"===a||"app"===a)?Array.from(new Set(d)):[]})(a).includes(b)}var k5=c(78591);function k6(a){let b,c;return[(b=jY(a),!b?.enabled?"":JSON.stringify({m:b.modelId,t:b.maxTokens,r:b.maxCallsPerMinute})),(c=kU(a),c?.enabled?"e:1":""),!0===a.enableMcpApps?"mcp-apps:on":"mcp-apps:off",!0===a.enableMcpSkills?"mcp-skills:on":"mcp-skills:off"].join("|")}let k7=(0,o.h)("backend/services/mcp/connection");async function k8(a){let b=a;if(a.env&&"object"==typeof a.env){let c={};for(let[b,d]of Object.entries(a.env)){if(!b)continue;let a=d&&"object"==typeof d&&"value"in d?d.value??"":d??"";if(!a||k0(a))continue;let e=await (0,K.G)(a);e&&(c[b]=e)}b={...b,env:c}}if("streamable"!==a.transport&&"sse"!==a.transport||!a.headers||"object"!=typeof a.headers)return b;let c={};for(let[b,d]of Object.entries(a.headers)){if(!b)continue;let{value:a}=k_(d,b);if(!a||k0(a))continue;let e=await (0,K.G)(a);e&&(c[b]=e)}return{...b,headers:c}}function k9(a){let b={};for(let[c,d]of Object.entries(a)){if(!c)continue;let{value:a}=k_(d,c);"string"==typeof a&&a.length>0&&(b[c]=a)}return b}function la(a){let b={};if(a)for(let[c,d]of Object.entries(a))d&&"object"==typeof d&&"value"in d?b[c]=d.value:b[c]=d;return b}let lb=new Set(["path","pathext","home","userprofile","homedrive","homepath","appdata","localappdata","programdata","xdg_config_home","xdg_cache_home","xdg_data_home","xdg_state_home","xdg_runtime_dir","tmp","temp","tmpdir","shell","comspec","systemroot","windir","systemdrive","programfiles","programfiles(x86)","gh_config_dir"]);function lc(a,b,c){for(let c of Object.keys(a))c.toLowerCase()===b.toLowerCase()&&delete a[c];void 0!==c&&(a[b]=c)}function ld(a,b=!1){return JSON.stringify({command:a.command,args:a.args??[],env:la(a.env),cwd:String(a.cwd??""),rootPath:a.rootPath??"",isolateRuntimeHome:b})}function le(a){return JSON.stringify({transport:a.transport,url:a.serverUrl??"",headers:a.headers??{},requestInit:a.requestInit??{},eventSourceInit:a.eventSourceInit??{},reconnectionOptions:a.reconnectionOptions??{},sessionId:a.sessionId??"",oauthClientId:a.oauthClientId??"",oauthClientInformation:a.oauthClientInformation??{},oauthClientSecret:a.oauthClientSecret??"",oauthTokens:a.oauthTokens??{}})}function lf(a){k7.debug("Entering createNewClient method");let b=jZ(a),c=kV(a),d=!0===a.enableMcpApps,e="stdio"===a.transport,f=new iv({name:`flujo-${a.name}-client`,version:"3.45.2"},{capabilities:{experimental:{},roots:{listChanged:!0},...b?{sampling:{}}:{},...e||c?{elicitation:{...e?{url:{}}:{},...c?{form:{}}:{}}}:{},extensions:{...e?{[j4]:j7}:{},...d?{[k1]:{mimeTypes:[k2]}}:{}}}});return(0,jT.FP)(f,a),b&&f.setRequestHandler(J.u9,j$(a)),(e||c)&&f.setRequestHandler(J.$9,kW(a)),f.__flujoCapKey=k6(a),f}function lg(a,b){if(k7.debug("Entering createTransport method"),"streamable"===a.transport){k7.info(`Creating streamable http transport for server ${a.name} with URL ${a.serverUrl}`);let b={};if(a.requestInit&&"object"==typeof a.requestInit&&(b.requestInit=a.requestInit),a.reconnectionOptions&&"object"==typeof a.reconnectionOptions&&(b.reconnectionOptions=a.reconnectionOptions),"string"==typeof a.sessionId&&a.sessionId.length>0&&(b.sessionId=a.sessionId),a.headers&&"object"==typeof a.headers){let c=k9(a.headers);Object.keys(c).length>0&&(b.requestInit={...b.requestInit||{},headers:{...b.requestInit?.headers||{},...c}},k7.info(`Applied ${Object.keys(c).length} custom header(s) for ${a.name}: ${Object.keys(c).join(", ")}`))}a.oauthClientId||a.oauthClientInformation?(k7.info(`Setting up OAuth authentication for ${a.name}`),b.authProvider=jA(a),a.oauthTokens?.access_token?(k7.debug(`OAuth provider configured for ${a.name} with existing tokens`),k7.debug(`Token expires in: ${a.oauthTokens.expires_in} seconds`)):k7.debug(`OAuth provider configured for ${a.name} - will initiate OAuth flow if needed`)):k7.debug(`No OAuth configuration found for ${a.name}`);let c=new jr(new URL(a.serverUrl),b);return c.__flujoHttpKey=le(a),c}if("sse"===a.transport){k7.info(`Creating legacy sse transport for server ${a.name} with URL ${a.serverUrl}`);let b={};if(a.requestInit&&"object"==typeof a.requestInit&&(b.requestInit=a.requestInit),a.eventSourceInit&&"object"==typeof a.eventSourceInit&&(b.eventSourceInit=a.eventSourceInit),a.headers&&"object"==typeof a.headers){let c=k9(a.headers);Object.keys(c).length>0&&(b.requestInit={...b.requestInit||{},headers:{...b.requestInit?.headers||{},...c}},k7.info(`Applied ${Object.keys(c).length} custom header(s) for ${a.name}: ${Object.keys(c).join(", ")}`))}let c=new jt(new URL(a.serverUrl),b);return c.__flujoHttpKey=le(a),c}return"websocket"===a.transport?(k7.info(`Creating WebSocket transport for server ${a.name} with URL ${a.websocketUrl}`),new iz(new URL(a.websocketUrl))):function(a,b){let c;if(k7.debug("Entering createStdioTransport method"),"stdio"!==a.transport)throw Error("Cannot create stdio transport for non-stdio config");let{command:d,args:e,env:f,cwd:g}=lh(a,b),h=b?.enableRuntimeBroker&&!0===a.enableMcpApps?(0,k5.D9)(a.name):void 0;k7.info(`Creating StdioClientTransport for ${a.name} with stderr: 'pipe'`);let i={command:d,args:e,env:h?{...f,...h.env}:f,cwd:g,stderr:"pipe"};try{c=new iy(i)}catch(a){throw(0,k5.tS)(h?.leaseId),a}return h&&(c.__flujoRuntimeBrokerLeaseId=h.leaseId),c.__flujoStdioKey=ld(a,b?.isolateRuntimeHome===!0),c.stderr?k7.info(`Stderr stream is available for ${a.name}`):k7.warn(`Stderr stream is NOT available for ${a.name}`),c}(a,b)}function lh(a,b){let c=(0,jS.AW)(a),d=!!c,e=c?.defaultName==="bash",f=a=>d?a:(0,p.remapLegacyDefaultWorkspaceReference)(a,"mcp-servers"),g=f(a.command),h=a.args?a.args.map(f):[],i=`${r.VL}/${a.name}`;k7.info(`Creating stdio transport for server ${a.name}`),k7.debug(`Original command: ${g}`),k7.debug(`Original args: ${JSON.stringify(h)}`),k7.debug(`Server directory: ${i}`);let j=!m.isAbsolute(g)&&(g.includes("/")||g.includes("\\")),k=!g.includes("/")&&!g.includes("\\");if(k7.debug(`Is relative path: ${j}`),k7.debug(`Is just filename: ${k}`),"win32"===jv.platform()&&g.toLowerCase().endsWith(".bat"))if(k7.debug(`Detected .bat file on Windows: ${g}`),k){let a=m.join((0,p.getWorkspaceDataDir)(),i,g);k7.debug(`Checking if file exists at: ${a}`);let b=ju.existsSync(a);k7.debug(`File exists: ${b}`),b?(k7.debug(`Using full path to .bat file: ${a}`),h=["/c",a,...h]):(k7.warn(`WARNING: .bat file not found at ${a}`),h=["/c",g,...h]),g="cmd.exe"}else k7.debug(`Using cmd.exe with path as provided: ${g}`),h=["/c",g,...h],g="cmd.exe";let l=function(a,b){if(!a||!(!a.includes("/")&&!a.includes("\\")))return a;let c=a.toLowerCase();if(!jR.has(c))return a;if("node"===c)return b.execPath||a;if(!b.execPath)return a;let d=b.dirname(b.execPath);for(let a of"win32"===b.platform?[`${c}.cmd`,`${c}.exe`,c]:[c]){let c=b.joinPath(d,a);if(b.fileExists(c))return c}return a}(g,{execPath:process.execPath,platform:jv.platform(),dirname:m.dirname,joinPath:m.join,fileExists:ju.existsSync});l!==g&&(k7.debug(`Resolved Node toolchain command "${g}" to absolute path: ${l}`),g=l),k7.debug(`Final command: ${g}`),k7.debug(`Final args: ${JSON.stringify(h)}`);let n=e||b?.isolateRuntimeHome!==!0?void 0:function(a){let b=(0,p.getWorkspaceDataDir)(),c=(0,jw.createHash)("sha256").update(a,"utf8").digest("hex").slice(0,24),d=(a,b)=>{try{let c=ju.lstatSync(a);if(!c.isDirectory()||c.isSymbolicLink())throw Error(`${b} must be a real directory: ${a}`)}catch(d){if("ENOENT"!==d.code)throw d;ju.mkdirSync(a,{mode:448});let c=ju.lstatSync(a);if(!c.isDirectory()||c.isSymbolicLink())throw Error(`${b} must be a real directory: ${a}`)}},e=ju.lstatSync(b);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`Workspace root must be a real directory: ${b}`);let f=b;for(let a of["userdata","mcp-runtime",c])d(f=m.join(f,a),"MCP runtime directory");let g=f,h=m.join(g,"home"),i=m.join(g,"cwd");d(h,"MCP runtime home"),d(i,"MCP runtime cwd");let j={appData:m.join(h,"AppData","Roaming"),localAppData:m.join(h,"AppData","Local"),config:m.join(h,".config"),cache:m.join(h,".cache"),data:m.join(h,".local","share"),state:m.join(h,".local","state"),runtime:m.join(h,".runtime"),temp:m.join(h,"tmp"),npm:m.join(h,".npm"),pip:m.join(h,".cache","pip"),uv:m.join(h,".cache","uv")};for(let a of Object.values(j)){let b=m.relative(h,a),c=h;for(let a of b.split(m.sep).filter(Boolean))d(c=m.join(c,a),"MCP runtime directory")}let k={HOME:h,USERPROFILE:h,APPDATA:j.appData,LOCALAPPDATA:j.localAppData,XDG_CONFIG_HOME:j.config,XDG_CACHE_HOME:j.cache,XDG_DATA_HOME:j.data,XDG_STATE_HOME:j.state,XDG_RUNTIME_DIR:j.runtime,TMPDIR:j.temp,TMP:j.temp,TEMP:j.temp,NPM_CONFIG_CACHE:j.npm,PIP_CACHE_DIR:j.pip,UV_CACHE_DIR:j.uv};if("win32"===process.platform){let a=m.parse(h);k.HOMEDRIVE=a.root.replace(/[\\/]$/,""),k.HOMEPATH=h.slice(a.root.length-1)}return{cwd:i,env:k}}(a.name),o=f(function({command:a,args:b=[],rootPath:c,cwd:d,serverName:e,defaultCwd:f,packageRunnerCwd:g}){let h=c||d||f;if(jQ(a,b)&&g)return g;if(e&&jQ(a,b)&&(h.split(/[\\/]/).filter(Boolean).pop()||"")===e){let a;return((a=h.match(/^(.*[\\/])[^\\/]+[\\/]*$/))?a[1].replace(/[\\/]+$/,""):"")||h}return h}({command:a.command,args:a.args,rootPath:a.rootPath,cwd:a.cwd,serverName:a.name,defaultCwd:`${r.VL}/${a.name}`,packageRunnerCwd:n?.cwd})),q=m.isAbsolute(o)?o:m.join((0,p.getWorkspaceDataDir)(),o);k7.debug(`cwd: ${q}`),k7.debug(`Environment variable names: ${JSON.stringify(Object.keys(a.env??{}))}`);let s=la(a.env),t=e?function(a){let b={...a},c=Object.entries(process.env).filter(a=>"string"==typeof a[1]);for(let[a,d]of c)lc(b,a,d);for(let a of lb)c.find(([b])=>b.toLowerCase()===a)||lc(b,a,void 0);return b}(s):s;if(!d)for(let[a,b]of Object.entries(t))t[a]=f(b);n&&Object.assign(t,n.env),function(a){if("win32"!==process.platform)return;let b=(a,b)=>Object.entries(a).find(([a,c])=>a.toLowerCase()===b.toLowerCase()&&""!==(c??"").trim())?.[1],c=b(process.env,"SystemRoot")??b(process.env,"windir")??"C:\\Windows";for(let[d,e]of Object.entries({SystemRoot:c,windir:c,ComSpec:b(process.env,"ComSpec")??m.join(c,"System32","cmd.exe"),PATHEXT:b(process.env,"PATHEXT")??".COM;.EXE;.BAT;.CMD"}))if(void 0===b(a,d)){for(let b of Object.keys(a))b.toLowerCase()===d.toLowerCase()&&delete a[b];a[d]=e}}(t);let u=(0,jM.ok)(),v=(0,p.getWorkspaceDataDir)();if(t.FLUJO_PARENT_DATA_DIR=u,t.FLUJO_DATA_DIR=v,t.FLUJO_WORKSPACE=(0,p.getCurrentWorkspace)(),c?.defaultName==="browser"){if(!t.PLAYWRIGHT_BROWSERS_PATH?.trim()){let a=(0,jS.AI)(process.env);a&&(t.PLAYWRIGHT_BROWSERS_PATH=a)}t.FLUJO_BROWSER_PROFILE_DIR=m.join(v,"browser-profile","trusted"),t.FLUJO_BROWSER_SCREENSHOT_DIR=m.join(v,"screenshots","browser"),t.FLUJO_BROWSER_RECORD_DIR=m.join(v,"recordings","browser")}return k7.verbose("Transformed environment variable names",JSON.stringify(Object.keys(t))),"1"===process.env.FLUJO_WORKER_MODE&&c?.defaultName==="flujo"&&(t.FLUJO_WORKER_MODE="1",process.env.FLUJO_SNAPSHOT_CONTROL_TOKEN&&(t.FLUJO_SNAPSHOT_CONTROL_TOKEN=process.env.FLUJO_SNAPSHOT_CONTROL_TOKEN)),{command:g,args:h,env:t,cwd:q}}async function li(a,b,c,d){k7.debug("Entering safelyCloseClient method");let e=Date.now(),f=d?.gracePeriodMs??15e3,g=d?.killEscalationMs??5e3,h=!0,i=!1,j=function(a){let b=a,c=new Set;for(;b&&"object"==typeof b&&!c.has(b);){c.add(b);let a=b.__flujoInnerTransport;if(!a)break;b=a}return b}(a.transport);try{let c=j?._process;if(c&&"function"==typeof c.kill&&null===c.exitCode&&null===c.signalCode){try{c.stdin&&!c.stdin.destroyed&&(c.stdin.end(),k7.debug(`Closed stdin for graceful shutdown for ${b}`))}catch(a){k7.warn(`Error closing stdin for ${b}:`,a)}if(h=await (null!==c.exitCode||null!==c.signalCode?Promise.resolve(!0):new Promise(a=>{let b=()=>{clearTimeout(d),a(!0)},d=setTimeout(()=>{c.removeListener("exit",b),a(!1)},f);d.unref?.(),c.once("exit",b)})))k7.info(`Process exited gracefully for ${b}`);else{k7.warn(`Process did not exit within ${f}ms after stdin close; escalating to a tree kill for ${b}`);let a=await (0,jL.U)(c,{graceMs:g,finalWaitMs:g});h=a.exited,i=a.forced,h?k7.warn(`Process tree for ${b} force-terminated after ${a.durationMs}ms`):k7.error(`Process tree for ${b} (pid ${a.pid??"unknown"}) did not exit after forced escalation`)}}await a.close(),k7.info(`Client closed successfully for ${b}`)}catch(a){k7.warn(`Error closing client for ${b}:`,a)}finally{(0,k5.tS)(j?.__flujoRuntimeBrokerLeaseId)}return{exited:h,forced:i,durationMs:Date.now()-e}}let lj=(0,o.h)("backend/services/mcp/betaClient");async function lk(){try{let a=await (0,io.loadItem)(ip.Zg.SPEECH_SETTINGS,void 0);return!!a?.experimental?.mcpBetaProtocol}catch(a){return lj.warn("Failed to read mcpBetaProtocol setting; defaulting to disabled",{err:a}),!1}}function ll(a){return!0===a.__flujoBeta}function lm(a){let b=jZ(a),c=kV(a),d=!0===a.enableMcpApps,e="stdio"===a.transport,f=new ia({name:`flujo-${a.name}-client`,version:"3.45.2"},{capabilities:{roots:{listChanged:!0},...b?{sampling:{}}:{},...e||c?{elicitation:{...e?{url:{}}:{},...c?{form:{}}:{}}}:{},extensions:{...e?{[j4]:j7}:{},...d?{[k1]:{mimeTypes:[k2]}}:{}}},versionNegotiation:{mode:"auto"}});if(f.setRequestHandler("roots/list",(0,jT.sG)(a)),b){let b=j$(a);f.setRequestHandler("sampling/createMessage",async a=>b(a))}if(e||c){let b=kW(a);f.setRequestHandler("elicitation/create",async a=>b(a))}return f.__flujoBeta=!0,f.__flujoCapKey=k6(a),lj.info(`Created v2-beta MCP client for ${a.name} (version negotiation: auto)`),f}function ln(a){let b=a.requestInit&&"object"==typeof a.requestInit?a.requestInit:void 0;if(a.headers&&"object"==typeof a.headers){let c=k9(a.headers);Object.keys(c).length>0&&(b={...b||{},headers:{...b?.headers||{},...c}})}return b}function lo(a,b){let c;if("websocket"===a.transport)throw Error("The v2-beta MCP SDK has no websocket transport; use the v1 path");if("streamable"===a.transport){let b={},c=ln(a);c&&(b.requestInit=c),a.reconnectionOptions&&"object"==typeof a.reconnectionOptions&&(b.reconnectionOptions=a.reconnectionOptions),"string"==typeof a.sessionId&&a.sessionId.length>0&&(b.sessionId=a.sessionId),(a.oauthClientId||a.oauthClientInformation)&&(b.authProvider=jA(a));let d=new ih(new URL(a.serverUrl),b);return d.__flujoHttpKey=le(a),d.__flujoKind="streamable",lj.info(`Created v2-beta streamable transport for ${a.name}`),d}if("sse"===a.transport){let b={},c=ln(a);c&&(b.requestInit=c),a.eventSourceInit&&"object"==typeof a.eventSourceInit&&(b.eventSourceInit=a.eventSourceInit);let d=new ic(new URL(a.serverUrl),b);return d.__flujoHttpKey=le(a),d.__flujoKind="sse",lj.info(`Created v2-beta SSE transport for ${a.name}`),d}let{command:d,args:e,env:f,cwd:g}=lh(a,b),h=b?.enableRuntimeBroker&&!0===a.enableMcpApps?(0,k5.D9)(a.name):void 0;try{c=new im({command:d,args:e,env:h?{...f,...h.env}:f,cwd:g,stderr:"pipe"})}catch(a){throw(0,k5.tS)(h?.leaseId),a}let i=c;return i.__flujoRuntimeBrokerLeaseId=h?.leaseId,i.__flujoStdioKey=ld(a,b?.isolateRuntimeHome===!0),i.__flujoKind="stdio",lp.set(c,new kw),lj.info(`Created v2-beta stdio transport for ${a.name}`),c}let lp=new WeakMap;function lq(a){lp.get(a)?.attach(a)}var lr=c(55334),ls=c(77214),lt=c(61359);let lu=(0,o.h)("backend/services/mcp/clientTasks");function lv(a,b,c){return"completed"===a.status?{success:!0,data:c,progressToken:a.taskId}:"failed"===a.status?{success:!1,error:a.statusMessage??`Task ${a.taskId} failed`,errorType:"task-failed",progressToken:a.taskId,toolName:b}:{success:!1,error:a.statusMessage??`Tool '${b}' task ${a.taskId} was cancelled by the server.`,errorType:"cancelled",progressToken:a.taskId,toolName:b}}async function lw(a){var b,c;let d,{client:e,serverName:f,serverIdentity:g,toolName:h,task:i,timeoutMs:j,signal:k,onProgress:l,ownership:m,persist:n}=a,o=await (0,lt.VX)(),p=Date.now(),q=(0,L.uY)(i.pollInterval,{minMs:o.minPollIntervalMs,maxMs:o.maxPollIntervalMs,defaultMs:o.defaultPollIntervalMs}),r=(0,L.on)(i,p,o.fallbackTtlMs);lu.info(`Tool ${h} on ${f} returned task ${i.taskId} (status=${i.status}, poll=${q}ms, expiresAt=${r??"none"})`),l?.({progress:0,message:`Task ${i.taskId} created (${i.status})`});let s=await (0,lt.Au)(f);if(!s)return lu.warn(`Refusing to poll task ${i.taskId}: poll concurrency limit reached for ${f}`),a.supportsCancel&&await (0,lr.O0)(e,i.taskId),{success:!1,error:`Too many concurrent MCP tasks are being polled; task ${i.taskId} was not started.`,errorType:"task-poll-limit",progressToken:i.taskId,toolName:h};let t=null;n&&(t=await (0,lt.ZN)({remoteTaskId:i.taskId,serverName:f,serverIdentity:g,toolName:h,args:a.args,ownership:m,status:i.status,statusMessage:i.statusMessage,pollIntervalMs:q,...void 0!==r?{expiresAt:r,ttlMs:r-p}:{}}));let u=async a=>{if(!t)return;let b=await (0,lt.Pi)(t.recordId,a);b&&(t=b)},v=b=>(d||(d=(async()=>(await u({cancelRequestedAt:Date.now(),...b?{diagnostic:b}:{}}),a.supportsCancel)?(0,lr.O0)(e,i.taskId):void lu.warn(`Server ${f} does not advertise tasks.cancel; skipping cancellation of ${i.taskId}`))()),d),w=()=>{v()};k?.addEventListener("abort",w,{once:!0});try{let a;if((0,L.gJ)(i.status))return await x(i);let c=i,d=0,g=q,m=0;for(;;){let i;if(k?.aborted)return await v(),await u({status:"cancelled"}),{success:!1,error:`Tool '${h}' task ${c.taskId} was cancelled.`,errorType:"cancelled",progressToken:c.taskId,toolName:h};let n=Date.now();if(void 0!==r&&n>=r)return await v("expired"),await u({status:"failed",diagnostic:"expired",errorMessage:"Remote MCP task expired before completing."}),{success:!1,error:`Task ${c.taskId} expired before completing.`,errorType:"task-expired",progressToken:c.taskId,toolName:h};if(n-p>=j){await v(),await u({status:"failed",errorMessage:"Caller timeout elapsed while polling the remote MCP task."});let a=Math.round(j/1e3);return{success:!1,error:`Tool execution timed out after ${a} seconds`,errorType:"timeout",timeout:a,statusCode:408,progressToken:c.taskId,toolName:h}}if(await (0,ls.y)(g),k?.aborted)continue;try{i=await (0,lr.k$)(e,c.taskId,{timeout:Math.min(4*g+1e4,j)}),d=0,g=q}catch(a){if(d++,await u({diagnostic:"transport-error",lastPolledAt:Date.now()}),d>=o.maxTransientPollFailures)return await v("transport-error"),await u({status:"failed",diagnostic:"transport-error",errorMessage:`tasks/get failed ${d} times: ${String(a)}`}),{success:!1,error:`Lost contact with '${f}' while polling task ${c.taskId}.`,errorType:"task-transport-error",progressToken:c.taskId,toolName:h};g=(0,L.uY)(2*g,{minMs:o.minPollIntervalMs,maxMs:o.maxPollIntervalMs,defaultMs:o.defaultPollIntervalMs}),lu.warn(`Transient tasks/get failure ${d}/${o.maxTransientPollFailures} for ${c.taskId}; backing off to ${g}ms`);continue}if(!i.ok)return await v("protocol-invalid"),await u({status:"failed",diagnostic:"protocol-invalid",errorMessage:`Invalid tasks/get result: ${i.reason}`}),{success:!1,error:`Server '${f}' returned an invalid task status: ${i.reason}`,errorType:"task-protocol-invalid",progressToken:c.taskId,toolName:h};c=i.task,m++;let s=Date.now()-p;if(await u({status:c.status,statusMessage:c.statusMessage,lastPolledAt:Date.now(),nextPollAt:Date.now()+g,pollCount:m,outstandingInputKeys:(b=c.taskId,[...kR.get(kS(f,b))?.outstanding??[]])}),l?.({progress:"completed"===c.status?100:Math.min(99,Math.round(s/1e3)),message:`Task ${c.taskId}: ${c.status}${c.statusMessage?` — ${c.statusMessage}`:""}`}),(0,L.gJ)(c.status))return await x(c);if("input_required"===c.status){a??=Date.now();let b=function(a,b,c,d,e=Date.now()){let f=(0,j0.lx)(a),g=kR.get(kS(a,b));return f?f.getUnattended()?{action:"abandon",error:`Task ${b} on '${a}' requires input, but the run is unattended.`,errorType:"task-input-required-unattended",diagnostic:"input-required-unattended"}:e-c>=d?{action:"abandon",error:`Task ${b} on '${a}' was waiting for input for longer than the configured window (${Math.round(d/1e3)}s)${g?`; ${g.outstanding.size} request(s) unanswered`:""}.`,errorType:"task-input-timeout",diagnostic:"input-required-unattended"}:{action:"wait"}:{action:"abandon",error:`Task ${b} on '${a}' requires input, but no attended run is available to answer it.`,errorType:"task-input-required-unattended",diagnostic:"input-required-unattended"}}(f,c.taskId,a,o.inputRequiredTimeoutMs);if("abandon"===b.action)return await v(b.diagnostic),await u({status:"failed",diagnostic:b.diagnostic,errorMessage:b.error}),{success:!1,error:b.error,errorType:b.errorType,progressToken:c.taskId,toolName:h}}else a=void 0}}finally{k?.removeEventListener("abort",w),s.release(),c=i.taskId,kR.delete(kS(f,c))}async function x(a){if("completed"!==a.status)return await u({status:a.status,statusMessage:a.statusMessage,..."failed"===a.status?{errorMessage:a.statusMessage??"Remote MCP task failed."}:{}}),lv(a,h);try{let b=await (0,lr.Yr)(e,a.taskId,{timeout:Math.min(6e4,j)});return await u({status:"completed",resultRetrieved:!0}),l?.({progress:100,message:`Task ${a.taskId}: completed`}),lv(a,h,b)}catch(b){return await u({status:"completed",resultRetrieved:!1,errorMessage:`tasks/result failed: ${String(b)}`}),{success:!1,error:`Task ${a.taskId} completed but its result could not be retrieved from '${f}'.`,errorType:"task-result-unavailable",progressToken:a.taskId,toolName:h}}}}var lx=c(3050);let ly=(0,o.h)("backend/services/mcp/tools"),lz=0x80000000-1;async function lA(a,b,c="model"){if(ly.debug("Entering listServerTools method"),!a)return ly.warn(`Server ${b} not connected`),{tools:[],error:"Server not connected"};try{var d;ly.info(`Listing tools for server ${b}`);let e=await a.listTools();ly.verbose("Raw response from MCP server:",e);let f=(d=(e.tools||[]).map(a=>({...a,description:a.description||"",inputSchema:a.inputSchema||{type:"object"}})),"all"===c?d:d.filter(a=>k4(a,c)));return ly.verbose(`Processed tools for ${c} audience:`,f),{tools:f}}catch(c){ly.warn(`Failed to list tools for server ${b}:`,c);let a=c instanceof Error?c.message:"Unknown error";return{tools:[],error:a.includes("Connection timeout")?a:`Failed to list tools: ${a}`}}}async function lB(a,b,c,d,e,f,g,h="host",i,j){if(ly.debug("Entering callTool method"),!a)return ly.warn(`Server ${b} not found`),{success:!1,error:`Server ${b} not found`,statusCode:404};let k=void 0!==e&&e>0?Math.min(1e3*e,lz):lz;try{if("app"===h||"model"===h){var l;let d,e=await lA(a,b,"all");if(e.error)return{success:!1,error:`Could not verify MCP App access to tool '${c}' on '${b}': ${e.error}`,errorType:"tool-authorization-list",statusCode:502};let f=(l=e.tools,(d=l.find(a=>a.name===c))?k4(d,h)?{allowed:!0}:{allowed:!1,error:`Tool '${c}' on MCP server '${b}' is not callable by ${"app"===h?"MCP Apps":"the model"}.`,statusCode:403}:{allowed:!1,error:`Tool '${c}' was not found on MCP server '${b}'.`,statusCode:404});if(!f.allowed)return ly.warn(`Rejected ${h} tool call: ${f.error}`),{success:!1,error:f.error,statusCode:f.statusCode}}ly.debug(`Original args for tool ${c}:`,d);let e=await (0,K.resolveGlobalVars)(d),m=function(a,b){if(!a)return{};let c={};for(let d in a){let e=a[d];null==e?(ly.debug(`Normalizing undefined/null value for parameter '${d}' in tool '${b}'`),d.includes("number")||d.endsWith("Count")||d.endsWith("Id")||d.endsWith("Limit")?(c[d]=0,ly.debug(`Using default value 0 for likely number parameter: ${d}`)):d.includes("bool")||d.startsWith("is")||d.startsWith("has")||d.startsWith("should")?(c[d]=!1,ly.debug(`Using default value false for likely boolean parameter: ${d}`)):d.includes("array")||d.endsWith("s")||d.endsWith("List")||d.endsWith("Items")?(c[d]=[],ly.debug(`Using empty array for likely array parameter: ${d}`)):d.includes("object")||d.endsWith("Options")||d.endsWith("Config")||d.endsWith("Settings")?(c[d]={},ly.debug(`Using empty object for likely object parameter: ${d}`)):(c[d]="",ly.debug(`Using empty string for parameter with unknown type: ${d}`))):c[d]=e}return c}("object"==typeof e&&null!==e?e:{},c);ly.debug(`Normalized args for tool ${c}:`,m),ly.debug(`Calling tool ${c} with SDK timeout ${k}ms`);let n={timeout:k,resetTimeoutOnProgress:!0,...g?{signal:g}:{},onprogress:a=>{ly.debug(`Progress for tool ${c}: ${a.progress}${void 0!==a.total?`/${a.total}`:""}${a.message?` — ${a.message}`:""}`),f?.(a)}},o=await (0,lr.u2)(a,c);o.request&&ly.info(`Requesting task-augmented execution of ${c} on ${b} (${o.reason})`);let p={name:c,arguments:m,...o.request?(0,lr.E4)(o.ttlMs):{},...i||j?{_meta:{flujo:{...i?{callerNodeId:i}:{},...j?{ownerScope:j}:{}}}}:{}},q=ll(a)?await a.callTool.call(a,p,n):await a.callTool(p,void 0,n),r=(0,L.Qh)(q,{taskRequested:o.request});if("protocol-invalid"===r.kind)return ly.warn(`Server ${b} returned an invalid task result for ${c}: ${r.reason}`),{success:!1,error:`Server '${b}' returned an invalid MCP task result: ${r.reason}`,errorType:"task-protocol-invalid",statusCode:502,toolName:c};if("task"===r.kind){let d=(0,lr.rf)(),e=d?await (0,lt.kI)(b):"unnegotiated",l=await lw({client:a,serverName:b,serverIdentity:e,toolName:c,args:m,task:r.task,timeoutMs:k,...g?{signal:g}:{},...f?{onProgress:f}:{},ownership:{...i?{nodeId:i}:{},...j?{ownerScope:j}:{},source:h},persist:d,supportsCancel:o.negotiation.supportsCancel||!o.negotiation.supported});return void 0===l.data?l:{...l,data:(0,lx.iL)(l.data,j)}}return{success:!0,data:(0,lx.iL)(q,j)}}catch(m){let d,e,f,h;ly.warn(`Failed to call tool ${c} on server ${b}:`,m);let i=m instanceof Error?m.message:"Unknown error",j=500;if(g?.aborted)return{success:!1,error:`Tool '${c}' call was cancelled.`,errorType:"cancelled",toolName:c};if(m instanceof J.Nh&&m.code===J.O4.RequestTimeout){let a=Math.round(k/1e3);return ly.warn(`Tool ${c} execution timed out after ${a} seconds`),{success:!1,error:`Tool execution timed out after ${a} seconds`,errorType:"timeout",toolName:c,timeout:a,statusCode:408}}let l=kH(a)?(d=kx(m),e=kx(d?.error)??d,f=kx(e?.data),(h=kf.safeParse(f?.[j4])).success?h.data:void 0):void 0;if(l){kJ(b);try{await kI(a,b,{force:!0})}catch(a){ly.warn(`Failed to refresh mcp-stdio-oauth status after revocation on ${b}:`,a)}return{success:!1,error:l.message?l.message:"External account authorization is required. Open the MCP page to authenticate.",errorType:"stdio-oauth-required",statusCode:428,requiresAuthentication:!0}}if(i.includes("401")||i.includes("Unauthorized")||i.includes("invalid_token")||i.includes("token_expired"))return ly.info(`OAuth authentication error detected for tool ${c} on server ${b}`),{success:!1,error:"OAuth authentication failed or tokens have expired. Please re-authenticate the server.",statusCode:401,requiresAuthentication:!0};return(i.includes("404")||i.includes("Not Found"))&&(ly.info(`404 error detected for tool ${c} on server ${b} - may indicate OAuth issues`),j=404,i="Tool endpoint not found (404). This may indicate OAuth authentication issues or the server may not be properly configured."),m instanceof J.Nh?(i=`Failed to call tool: ${i} (Code: ${m.code})`,-32601===m.code?j=404:-32602===m.code?j=400:-32603===m.code&&(j=500)):i=`Failed to call tool: ${i}`,{success:!1,error:i,statusCode:j}}}let lC=(0,o.h)("backend/services/mcp/resources");async function lD(a,b){if(lC.debug("Entering listServerResources method"),!a)return lC.warn(`Server ${b} not connected`),{resources:[],error:"Server not connected"};try{lC.info(`Listing resources for server ${b}`);let c=(await a.listResources()).resources||[];return lC.verbose("Processed resources:",c),{resources:c}}catch(c){if(c instanceof J.Nh&&-32601===c.code)return lC.debug(`Server ${b} does not support resources/list`),{resources:[]};lC.warn(`Failed to list resources for server ${b}:`,c);let a=c instanceof Error?c.message:"Unknown error";return{resources:[],error:a.includes("Connection timeout")?a:`Failed to list resources: ${a}`}}}async function lE(a,b){if(lC.debug("Entering listServerResourceTemplates method"),!a)return lC.warn(`Server ${b} not connected`),{resourceTemplates:[],error:"Server not connected"};try{return lC.info(`Listing resource templates for server ${b}`),{resourceTemplates:(await a.listResourceTemplates()).resourceTemplates||[]}}catch(c){if(c instanceof J.Nh&&-32601===c.code)return lC.debug(`Server ${b} does not support resources/templates/list`),{resourceTemplates:[]};lC.warn(`Failed to list resource templates for server ${b}:`,c);let a=c instanceof Error?c.message:"Unknown error";return{resourceTemplates:[],error:a.includes("Connection timeout")?a:`Failed to list resource templates: ${a}`}}}async function lF(a,b,c){if(lC.debug("Entering readResource method"),!a)return lC.warn(`Server ${b} not found`),{success:!1,error:`Server ${b} not found`,statusCode:404};try{let d=await (0,K.resolveGlobalVars)(c);lC.info(`Reading resource ${d} from server ${b}`);let e=await a.readResource({uri:d});return{success:!0,data:e}}catch(e){lC.warn(`Failed to read resource ${c} on server ${b}:`,e);let a=e instanceof Error?e.message:"Unknown error",d=500;return e instanceof J.Nh?(a=`Failed to read resource: ${a} (Code: ${e.code})`,-32601===e.code?d=404:-32602===e.code&&(d=400)):a=`Failed to read resource: ${a}`,{success:!1,error:a,statusCode:d}}}let lG=(0,o.h)("backend/services/mcp/prompts");async function lH(a,b){if(lG.debug("Entering listServerPrompts method"),!a)return lG.warn(`Server ${b} not connected`),{prompts:[],error:"Server not connected"};try{return lG.info(`Listing prompts for server ${b}`),{prompts:(await a.listPrompts()).prompts||[]}}catch(c){if(c instanceof J.Nh&&-32601===c.code)return lG.debug(`Server ${b} does not support prompts/list`),{prompts:[]};lG.warn(`Failed to list prompts for server ${b}:`,c);let a=c instanceof Error?c.message:"Unknown error";return{prompts:[],error:a.includes("Connection timeout")?a:`Failed to list prompts: ${a}`}}}async function lI(a,b,c,d){if(lG.debug("Entering getPrompt method"),!a)return lG.warn(`Server ${b} not found`),{success:!1,error:`Server ${b} not found`,statusCode:404};try{let e;if(d&&Object.keys(d).length>0){let a=await (0,K.resolveGlobalVars)(d);e="object"==typeof a&&null!==a?a:void 0}lG.info(`Getting prompt ${c} from server ${b}`);let f=await a.getPrompt({name:c,arguments:e});return{success:!0,data:f}}catch(e){lG.warn(`Failed to get prompt ${c} on server ${b}:`,e);let a=e instanceof Error?e.message:"Unknown error",d=500;return e instanceof J.Nh?(a=`Failed to get prompt: ${a} (Code: ${e.code})`,-32601===e.code?d=404:-32602===e.code&&(d=400)):a=`Failed to get prompt: ${a}`,{success:!1,error:a,statusCode:d}}}var lJ=c(57975),lK=c(9148);class lL extends Error{constructor(a){super(`MCP Skills are unavailable: ${a}`),this.name="McpSkillsUnsupportedError",this.reason=a}}function lM(a,b){if(!b||!a)return;let c=a.getServerCapabilities();return(0,r.zT)(c?.extensions?.[r.ET])}function lN(a,b){if(!b)throw new lL("disabled");if(!a)throw new lL("extension-not-negotiated");let c=lM(a,b);if(!c)throw new lL("extension-not-negotiated");return{client:a,capability:c}}async function lO(a){try{return await a()}catch(a){if(a instanceof J.Nh&&-32601===a.code)throw new lL("method-not-found");throw a}}async function lP(a,b,c){let d=lN(a,b);return lO(async()=>await d.client.request({method:"skills/list",params:void 0===c?{}:{cursor:c}},r.lX))}async function lQ(a,b,c){let d=lN(a,b),e=(0,r.Bw)(c).normalizedUri;return lO(async()=>{let a=await d.client.request({method:"skills/get",params:{uri:e}},r.Kg);if(a.skill.uri!==e)throw Error("skills/get returned a different skill URI");return a})}async function lR(a,b,c,d){let e=lN(a,b);if(!0!==e.capability.directoryRead)throw new lL("directory-read-not-negotiated");let f=(0,r.sm)(c);return lO(async()=>await e.client.request({method:"resources/directory/read",params:{uri:f,...void 0===d?{}:{cursor:d}}},r.Pd))}async function lS(a,b,c,d){let e=lN(a,b),f=function(a,b){if("dynamic"===a.resources)throw Error("Dynamic MCP Skills cannot be integrity-verified");let c=(0,r.sm)(b),d=a.resources.find(a=>a.uri===c);if(!d)throw Error("Resource is not declared by the held MCP Skill entry");return d}(c,d),g=(await e.client.readResource({uri:f.uri})).contents;if(!Array.isArray(g)||1!==g.length)throw Error("MCP Skill resource read must return exactly one content item");let h=g[0];if(null===h||"object"!=typeof h||Array.isArray(h))throw Error("MCP Skill resource content is malformed");if(void 0!==h.uri&&(0,r.sm)(h.uri)!==f.uri)throw Error("MCP Skill resource read returned a different URI");let i=function(a){let b="string"==typeof a.text;if(b===("string"==typeof a.blob))throw Error("MCP Skill resource must contain exactly one of text or blob");return b?{bytes:Buffer.from(a.text,"utf8"),text:a.text}:{bytes:function(a){if(a.length%4!=0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a))throw Error("MCP Skill resource contains invalid base64");return Buffer.from(a,"base64")}(a.blob),blob:a.blob}}(h);if(i.bytes.byteLength!==f.size)throw Error("MCP Skill resource size verification failed");if(`sha256:${(0,jx.createHash)("sha256").update(i.bytes).digest("hex")}`!==f.digest)throw Error("MCP Skill resource digest verification failed");return{uri:f.uri,digest:f.digest,size:f.size,..."string"==typeof h.mimeType?{mimeType:h.mimeType}:{},...i,verified:!0}}async function lT(a,b,c,d){if("dynamic"===d.resources)throw Error("Dynamic MCP Skills cannot be integrity-verified");let e=d.resources,f=Array(e.length),g=0,h=async()=>{for(;;){let c=g;if(g+=1,c>=e.length)return;f[c]=await lS(a,b,d,e[c].uri)}};await Promise.all(Array.from({length:Math.min(4,e.length)},()=>h()));let i=f.find(a=>a.uri===d.uri);if(!i||void 0===i.text)throw Error("MCP Skill SKILL.md must be textual content");return!function(a,b){let c,d=a.replace(/\r\n/g,"\n");if(!d.startsWith("---\n"))throw Error("MCP Skill SKILL.md must start with YAML frontmatter");let e=d.indexOf("\n---",4);if(e<0)throw Error("MCP Skill SKILL.md frontmatter is not terminated");let f=d.slice(4,e);try{c=(0,lK.parse)(f)}catch{throw Error("MCP Skill SKILL.md frontmatter is invalid YAML")}if(null===c||"object"!=typeof c||Array.isArray(c)||!(0,lJ.isDeepStrictEqual)(c,b.frontmatter))throw Error("MCP Skill SKILL.md frontmatter does not match its advertised entry")}(i.text,d),{identity:{serverName:c,skillUri:d.uri},protocolRevision:r.v$,entry:d,manifest:i,resources:f,verification:"sha256",trust:"untrusted-external-content"}}function lU(){return global.__mcp_skill_approvals??=new Map,global.__mcp_skill_approvals}let lV=(0,o.h)("backend/services/mcp/runtimeHomeIsolation");async function lW(a,b=process.env){if("stdio"!==a.transport)return!1;let c=function(a){let b=a?.trim().toLowerCase();if(b){if(["1","true","yes","on","isolated"].includes(b))return!0;if(["0","false","no","off","host"].includes(b))return!1}}(b.FLUJO_MCP_RUNTIME_HOME_ISOLATION);if(void 0!==c)return c;if("isolated"===a.runtimeHomeMode)return!0;if("host"===a.runtimeHomeMode)return!1;try{let a=await (0,io.loadItem)(ip.Zg.SPEECH_SETTINGS,void 0);return a?.experimental?.mcpRuntimeHomeIsolation===!0}catch(a){return lV.warn("Could not read the workspace MCP runtime-home preference; defaulting to host home",{error:a}),!1}}var lX=c(35247),lY=c(479);function lZ(a){return"stdio"===a.transport&&jQ(a.command,a.args??[])}let l$=(0,o.h)("utils/mcp/oauthProbe");function l_(a){try{let b=new URL(a);if("https:"!==b.protocol)return!1;let c=b.hostname.toLocaleLowerCase().replace(/^\[|\]$/g,"");if("localhost"===c||c.endsWith(".local")||c.endsWith(".internal")||"::1"===c||c.startsWith("fc")||c.startsWith("fd")||c.startsWith("fe80:"))return!1;let d=c.split(".").map(Number);if(4===d.length&&d.every(Number.isInteger)&&(10===d[0]||127===d[0]||0===d[0]||169===d[0]&&254===d[1]||192===d[0]&&168===d[1]||172===d[0]&&d[1]>=16&&d[1]<=31))return!1;return!0}catch{return!1}}async function l0(a){let b=await fetch(a,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{}}),signal:AbortSignal.timeout(5e3)}),c=b.headers.get("www-authenticate")||"",d=/\bbearer\b/i.test(c),e=c.match(/resource_metadata\s*=\s*"([^"]+)"/i);return{bearer:d,reachable:!0,unauthenticated:b.ok&&!d,resourceMetadataUrl:e?.[1]}}async function l1(a,b=!1){if(b&&!l_(a))return;let c=await fetch(a,{headers:{accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!c.ok)return;let d=await c.json(),e=Array.isArray(d.authorization_servers);if(e||"string"==typeof d.resource)return{authorizationServers:e?d.authorization_servers.filter(a=>"string"==typeof a):void 0}}async function l2(a,b=!1){for(let c of a)if(!b||l_(c))for(let a of function(a){try{let b=new URL(a),c=b.pathname.replace(/\/$/,"");return Array.from(new Set([new URL(`/.well-known/oauth-authorization-server${c}`,b.origin).toString(),new URL(`${c}/.well-known/oauth-authorization-server`,b.origin).toString(),new URL(`${c}/.well-known/openid-configuration`,b.origin).toString()]))}catch{return[]}}(c))try{let b=await fetch(a,{headers:{accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!b.ok)continue;let c=await b.json();if("string"==typeof c.registration_endpoint)return c.registration_endpoint}catch{}}async function l3(a,b={}){try{if(b.publicOnly&&!l_(a))return{oauthCapable:!1};let c=new URL(a).origin,d=await l0(a).catch(b=>(l$.debug(`readAuthChallenge failed for ${a}: ${b instanceof Error?b.message:String(b)}`),{bearer:!1,reachable:void 0,unauthenticated:!1,resourceMetadataUrl:void 0})),e=[];for(let f of(d.resourceMetadataUrl&&e.push(d.resourceMetadataUrl),e.push(new URL("/.well-known/oauth-protected-resource",c).toString()),e)){let e=await l1(f,b.publicOnly).catch(()=>void 0);if(e){let g=e.authorizationServers??[c],h=await l2(g,b.publicOnly);return l$.info(`OAuth capability confirmed for ${a} via ${f}`),{oauthCapable:!0,resourceMetadataUrl:f,authorizationServers:e.authorizationServers,reachable:d.reachable,...h?{dynamicClientRegistration:!0,registrationEndpoint:h}:{dynamicClientRegistration:!1}}}}if(d.bearer)return l$.info(`OAuth capability inferred for ${a} from a Bearer challenge (no resource metadata)`),{oauthCapable:!0,resourceMetadataUrl:d.resourceMetadataUrl,reachable:!0};return l$.debug(`No OAuth capability detected for ${a}`),{oauthCapable:!1,...d.reachable?{reachable:!0}:{},...d.unauthenticated?{unauthenticated:!0}:{}}}catch(b){return l$.debug(`probeOAuthSupport failed for ${a}: ${b instanceof Error?b.message:String(b)}`),{oauthCapable:!1}}}let l4=(0,o.h)("backend/services/mcp/resourceNotifications"),l5=/^[A-Za-z0-9_-]{1,64}$/;function l6(a,b,c,d){let e=d?.conversationId?.trim();if("model"===c&&"create_ticket_for_human"===b&&e&&l5.test(e)&&a?.transport==="stdio"&&(0,jS.AW)(a)?.packageId==="@mario.andreschak/mcp-flujo")return e}function l7(a,b){let c=(0,p.getCurrentWorkspace)();if(c===p.DEFAULT_WORKSPACE)return b;let d=global.__mcp_workspace_registries??=new Map,e=d.get(c);e||(e=new Map,d.set(c,e));let f=e.get(a);return f||(f=b instanceof Set?new Set:new Map,e.set(a,f)),f}function l8(a){return{success:!1,error:a.error,statusCode:a.statusCode,errorType:a.errorType}}void 0===global.__mcp_clients&&(global.__mcp_clients=new Map),void 0===global.__mcp_connecting&&(global.__mcp_connecting=new Set),void 0===global.__mcp_starting_up&&(global.__mcp_starting_up=!0),void 0===global.__mcp_active_transports&&(global.__mcp_active_transports=new Map),void 0===global.__mcp_client_generation&&(global.__mcp_client_generation=new Map),void 0===global.__mcp_tool_schema_hash&&(global.__mcp_tool_schema_hash=new Map);let l9=(0,o.h)("backend/services/mcp/index");function ma(a){let b=a,c=new Set;for(;b&&"object"==typeof b&&!c.has(b);){c.add(b);let a=b.__flujoInnerTransport;if(!a)break;b=a}return b}function mb(a){if("streamable"!==a.transport&&"sse"!==a.transport)return!1;let b=a.headers;return!!b&&Object.entries(b).some(([a,b])=>"authorization"===a.toLowerCase()&&k_(b,a).value.trim().length>0)}class mc{get stderrLogs(){return l7("stderrLogs",this.stderrLogsBase)}get lastConnectionError(){return l7("lastConnectionError",this.lastConnectionErrorBase)}get inFlightConnects(){return l7("inFlightConnects",this.inFlightConnectsBase)}get connectionRetryTimers(){return l7("connectionRetryTimers",this.connectionRetryTimersBase)}get connectionRetryAttempts(){return l7("connectionRetryAttempts",this.connectionRetryAttemptsBase)}get resourceListVersion(){return l7("resourceListVersion",this.resourceListVersionBase)}get pendingResourceUpdates(){return l7("pendingResourceUpdates",this.pendingResourceUpdatesBase)}async clearLegacyInferredOAuthScopesForHeaderAuth(a){try{let b=await this.loadServerConfigs();if(!Array.isArray(b))return;let c=b.findIndex(b=>b.name===a);if(-1===c||"streamable"!==b[c].transport)return;let d=b[c];if(!mb(d)||d.oauthScopes?.length!==1||"read"!==d.oauthScopes[0]||d.oauthClientId||d.oauthClientSecret||d.oauthClientMetadata||d.oauthClientInformation||d.oauthTokens||d.oauthCodeVerifier||d.oauthState||d.authorizationUrl)return;b[c]={...d,oauthScopes:void 0};let e=await (0,s.saveConfig)(new Map(b.map(a=>[a.name,a])));e.success?l9.info(`Removed stale inferred OAuth scopes from header-authenticated server ${a}`):l9.warn(`Failed to remove stale inferred OAuth scopes from ${a}: ${e.error}`)}catch(b){l9.warn(`Failed to clean inferred OAuth scopes for ${a}: ${b instanceof Error?b.message:String(b)}`)}}get clients(){return l7("clients",global.__mcp_clients)}get connectingServers(){return l7("connectingServers",global.__mcp_connecting)}get activeTransports(){return l7("activeTransports",global.__mcp_active_transports)}get clientGenerations(){return l7("clientGenerations",global.__mcp_client_generation)}get toolSchemaHashes(){return l7("toolSchemaHashes",global.__mcp_tool_schema_hash)}static{this.MAX_STDERR_LOG_ENTRIES=200}appendStderrLog(a,b){let c=this.stderrLogs.get(a)||[];c.push(b),c.length>mc.MAX_STDERR_LOG_ENTRIES&&c.splice(0,c.length-mc.MAX_STDERR_LOG_ENTRIES),this.stderrLogs.set(a,c)}deregisterClient(a){this.clients.delete(a),this.activeTransports.delete(a);kJ(a);let b=(0,p.getCurrentWorkspace)();for(let c of Array.from(kA.values()))c.workspace===b&&c.serverName===a&&(c.resolveElicitation?.({action:"cancel"}),c.abortController.abort(),c.rejectPrompt(Error("Authorization was cancelled because the MCP connection closed.")),kL(c));(0,k5.HW)(a)}onResourceListChanged(a){let b=this.resourceListVersion.get(a)??0;this.resourceListVersion.set(a,b+1),l9.debug(`onResourceListChanged: server=${a} version=${b+1}`)}onResourceUpdated(a,b){let c=this.pendingResourceUpdates.get(a)??new Set;c.add(b),this.pendingResourceUpdates.set(a,c),l9.debug(`onResourceUpdated: server=${a} uri=${b}`)}getResourceListVersion(a){return this.resourceListVersion.get(a)??0}async subscribeToResource(a,b){try{let c=this.getClient(a);if(!c)return;let d=c.getServerCapabilities?.();if(!d?.resources?.subscribe)return;await c.subscribeResource({uri:b}),l9.debug(`subscribeToResource: server=${a} uri=${b}`)}catch(c){l9.debug(`subscribeToResource: ignored error for ${a}/${b}:`,c)}}clearRetryTimer(a){let b=this.connectionRetryTimers.get(a);b&&(clearTimeout(b),this.connectionRetryTimers.delete(a),l9.debug(`Cleared retry timer for server ${a}`))}scheduleConnectionRetry(a,b){this.clearRetryTimer(a);let c=this.connectionRetryAttempts.get(a)||0;if(c>=5){l9.warn(`Maximum retry attempts (5) reached for server ${a}, stopping retries`),this.connectionRetryAttempts.delete(a);return}let d=Math.min(5e3*Math.pow(2,c),3e5);l9.info(`Scheduling connection retry for server ${a} in ${d}ms (attempt ${c+1}/5)`);let e=setTimeout((0,p.bindToCurrentWorkspace)(async()=>{l9.info(`Attempting to reconnect server ${a} (attempt ${c+1}/5)`);let b=await this.getServerConfig(a);if(!b){l9.info(`Server ${a} configuration not found, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}if(b.disabled){l9.info(`Server ${a} is now disabled, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}let d=this.getClient(a);if(d)try{await d.ping({timeout:5e3}),l9.info(`Server ${a} is already connected and responsive, cancelling retry`),this.connectionRetryAttempts.delete(a);return}catch(b){l9.warn(`Server ${a} has a registered client but ping failed (${b instanceof Error?b.message:String(b)}); reconnecting from scratch`)}this.connectionRetryAttempts.set(a,c+1);try{let e=d?await this.forceReconnect(a):await this.connectServer(b);if(e.success)l9.info(`Successfully reconnected server ${a} after ${c+1} attempts`),this.connectionRetryAttempts.delete(a);else{if(l9.warn(`Failed to reconnect server ${a}: ${e.error}`),e.requiresAuthentication){l9.info(`Server ${a} requires authentication, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}this.scheduleConnectionRetry(a,b)}}catch(c){l9.error(`Error during retry connection for server ${a}:`,c),this.scheduleConnectionRetry(a,b)}}),d);this.connectionRetryTimers.set(a,e)}isStartingUp(){let a=(0,p.getCurrentWorkspace)();return a===p.DEFAULT_WORKSPACE?!0===global.__mcp_starting_up:global.__mcp_starting_up_by_workspace?.get(a)===!0}setStartingUp(a){let b=(0,p.getCurrentWorkspace)();b===p.DEFAULT_WORKSPACE?global.__mcp_starting_up=a:(global.__mcp_starting_up_by_workspace??=new Map).set(b,a),l9.info(`Backend startup state set to: ${a?"starting":"complete"}`)}getClientGeneration(a){return this.clientGenerations.get(a)??0}setToolSchemaHash(a,b,c){this.toolSchemaHashes.set(`${a}\0${b}`,c)}getToolSchemaHash(a,b){return this.toolSchemaHashes.get(`${a}\0${b}`)}getClient(a){let b=this.clients.get(a);if(b&&jC(b)){l9.warn(`getClient: client for ${a} has a closed/aborted connection — evicting it`),this.clients.delete(a);return}return l9.debug(`getClient: Looking for client: ${a}`,b?"Found":"Not found"),b}async loadServerConfigs(){l9.debug("loadServerConfigs: Entering method");try{let a=await (0,s.loadServerConfigs)();if(!Array.isArray(a))return l9.warn("loadServerConfigs: Received non-array response",a),a;return l9.debug(`loadServerConfigs: Loaded ${a.length} server configs`),a}catch(a){return l9.warn("loadServerConfigs: Failed to load server configs:",a),{success:!1,error:`Failed to load server configs: ${a instanceof Error?a.message:"Unknown error"}`}}}async getServerConfig(a){l9.debug(`getServerConfig: Looking up config for server ${a}`);let b=await this.loadServerConfigs();if(!Array.isArray(b))return l9.warn(`getServerConfig: Failed to load configs for ${a}:`,b.error),null;let c=b.find(b=>b.name===a);return c||(l9.warn(`getServerConfig: Server ${a} not found in configs`),null)}async isServerDisabled(a){let b=await this.getServerConfig(a);return b?.disabled===!0}async connectServer(a){let b="string"==typeof a?a:a.name;return z(b,async()=>{let c=this.connectServerInternal(a).finally(()=>{this.inFlightConnects.delete(b)});this.inFlightConnects.set(b,c);let d=await c;if(d.success){var e;let c;e=this.configFingerprint(a),c=w(b),c.generation+=1,c.state="warm",c.configFingerprint=e,c.retryAttempts=0,c.lastError=void 0,c.warmSince=Date.now(),c.lastUsedAt=Date.now(),c.generation}else{let a=this.activeTransports.has(b)&&!this.clients.has(b);!function(a,b,c=!1){let d=w(a);d.state="error",d.lastError=b,d.connectFailures=Math.min(d.connectFailures+1,Number.MAX_SAFE_INTEGER),c&&(d.handshakeFailures+=1),d.retryAttempts+=1}(b,d.error??"unknown connection failure",a)}return d})}configFingerprint(a){if("string"!=typeof a)return[a.transport,a.command??"",(a.args??[]).join(" "),a.url??"",a.websocketUrl??"",a.rootPath??"",a.disabled?"disabled":"enabled"].join("\0")}async connectServerInternal(a){let b;if("string"==typeof a){l9.info(`connectServer: Looking up config for server ${a}`);let c=await this.getServerConfig(a);if(!c)return l9.warn(`connectServer: Server ${a} not found in configs`),{success:!1,error:`Server configuration for "${a}" not found. The server may have been deleted or not properly configured.`};b=c}else b=a;let c="string"==typeof a?b:await this.getServerConfig(b.name),d=c??b;if((c??b).disabled)return l9.info(`connectServer: Server ${b.name} is disabled — refusing to create a client/transport`),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),{success:!1,error:`Server '${b.name}' is disabled. Enable it on the MCP page to use it.`};let e=(0,j.A)();l9.info(`connectServer: Starting connection for server ${b.name} [RequestID: ${e}]`),this.connectingServers.add(b.name);try{this.stderrLogs.set(b.name,[]),b=await k8(b);let a=await lk()&&"websocket"!==b.transport,c=await lW(b),d={enableRuntimeBroker:!0,isolateRuntimeHome:c},e=this.clients.get(b.name);if(e){let{needsNewClient:c,reason:f}=function(a,b,c=!1,d){if(k7.debug("Entering shouldRecreateClient method"),jC(a))return{needsNewClient:!0,reason:"Existing connection is closed"};if((a.__flujoCapKey??"")!==k6(b))return{needsNewClient:!0,reason:"Client capabilities (sampling/elicitation/MCP Apps/Skills) changed"};let e=!0===a.__flujoBeta,f=c&&"websocket"!==b.transport;if(e!==f)return{needsNewClient:!0,reason:f?"Beta MCP protocol enabled":"Beta MCP protocol disabled"};if(e){let c=a.transport;if(!c||c.__flujoKind!==b.transport)return{needsNewClient:!0,reason:`Transport type changed to ${b.transport}`};if("stdio"===b.transport){if(c.__flujoStdioKey!==ld(b,d?.isolateRuntimeHome===!0))return{needsNewClient:!0,reason:"Connection parameters changed"}}else if(c.__flujoHttpKey!==le(b))return{needsNewClient:!0,reason:`${b.transport} auth/connection parameters changed`};return{needsNewClient:!1}}if("websocket"===b.transport){if(!(a.transport instanceof iz))return{needsNewClient:!0,reason:"Transport type changed to websocket"}}else if("streamable"===b.transport){if(!(a.transport instanceof jr))return{needsNewClient:!0,reason:"Transport type changed to streamable"};let c=a.transport,d=c._url?.toString();if(void 0!==d&&d!==new URL(b.serverUrl).toString())return{needsNewClient:!0,reason:"Streamable server URL changed"};let e=c.__flujoHttpKey;if(!e)return{needsNewClient:!0,reason:"Existing streamable transport has no config key"};if(e!==le(b))return{needsNewClient:!0,reason:"Streamable auth/connection parameters changed"}}else if("sse"===b.transport){if(!(a.transport instanceof jt))return{needsNewClient:!0,reason:"Transport type changed to sse"};let c=a.transport,d=c._url?.toString();if(void 0!==d&&d!==new URL(b.serverUrl).toString())return{needsNewClient:!0,reason:"SSE server URL changed"};let e=c.__flujoHttpKey;if(!e)return{needsNewClient:!0,reason:"Existing sse transport has no config key"};if(e!==le(b))return{needsNewClient:!0,reason:"SSE auth/connection parameters changed"}}else{if(!(a.transport instanceof iy))return{needsNewClient:!0,reason:"Transport type changed to stdio"};if("stdio"!==b.transport)return{needsNewClient:!0,reason:"Transport type changed from stdio"};let c=a.transport.__flujoStdioKey;if(!c)return{needsNewClient:!0,reason:"Existing stdio transport has no config key"};if(c!==ld(b,d?.isolateRuntimeHome===!0))return{needsNewClient:!0,reason:"Connection parameters changed"}}return{needsNewClient:!1}}(e,b,a,d);if(!c)return l9.info(`connectServer: Server ${b.name} is already connected`),this.lastConnectionError.delete(b.name),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),await this.clearLegacyInferredOAuthScopesForHeaderAuth(b.name),{success:!0};l9.info(`connectServer: Existing client for ${b.name} is stale (${f}), recreating`),this.deregisterClient(b.name);try{await li(e,b.name,b)}catch(a){l9.debug(`connectServer: error closing stale client for ${b.name}: ${a instanceof Error?a.message:String(a)}`)}e=void 0}e=a?lm(b):lf(b);let f=a?lo(b,d):lg(b,d);if("stdio"===b.transport&&kF(e,b.name,a?lp.get(f):void 0),a){let a=e.setNotificationHandler?.bind(e);a&&(a("notifications/resources/list_changed",(0,p.bindToCurrentWorkspace)(()=>{this.onResourceListChanged(b.name)})),a("notifications/resources/updated",(0,p.bindToCurrentWorkspace)(a=>{let c=a?.params?.uri;c&&this.onResourceUpdated(b.name,c)})))}else!function(a,b,c,d){try{a.setNotificationHandler(J.hh,a=>{l4.debug(`resourceListChanged notification received for ${b}`),c(b)})}catch(a){l4.warn(`registerResourceNotificationHandlers: failed to register list_changed for ${b}`,a)}if(d)try{a.setNotificationHandler(J.cL,a=>{let c=a.params?.uri;c&&(l4.debug(`resourceUpdated notification received for ${b} uri=${c}`),d(b,c))})}catch(a){l4.warn(`registerResourceNotificationHandlers: failed to register resource_updated for ${b}`,a)}}(e,b.name,(0,p.bindToCurrentWorkspace)(a=>this.onResourceListChanged(a)),(0,p.bindToCurrentWorkspace)((a,b)=>this.onResourceUpdated(a,b)));let g=ma(f).stderr;if(g&&"function"==typeof g.on){let a=b.name;g.on("data",(0,p.bindToCurrentWorkspace)(b=>{let c=b.toString();l9.warn(`stderr: [${a}]: ${c}`),this.appendStderrLog(a,c)}))}if(f.onclose=(0,p.bindToCurrentWorkspace)(()=>{this.activeTransports.get(b.name)!==f?l9.debug(`connectServer: ignoring close event from a stale/deregistered transport for ${b.name}`):(l9.warn(`connectServer: Connection closed for server ${b.name}`),this.deregisterClient(b.name),this.getServerConfig(b.name).then(a=>{!a||a.disabled?l9.info(`Server ${b.name} is now disabled, skipping reconnection logic`):(l9.info(`Connection closed for enabled server ${b.name}, scheduling reconnection`),this.scheduleConnectionRetry(b.name,a))}).catch(a=>{l9.warn(`Error checking server config for ${b.name} during onclose:`,a)}))}),f.onerror=(0,p.bindToCurrentWorkspace)(a=>{let c;if((c=a instanceof Error?a.message:String(a)).includes("SSE stream disconnected")||c.includes("Failed to reconnect SSE stream")||c.includes("Maximum reconnection attempts")||/\bterminated\b/i.test(c))return void l9.debug(`connectServer: transient SSE stream disconnect for ${b.name} (self-healing, ignored): ${a instanceof Error?a.message:String(a)}`);if(this.activeTransports.get(b.name)!==f)return void l9.debug(`connectServer: ignoring error event from a stale/deregistered transport for ${b.name}`);if(l9.error(`connectServer: Transport error for server ${b.name}:`),a instanceof Error){l9.error(`Error name: ${a.name}`),l9.error(`Error message: ${a.message}`),l9.error(`Error stack: ${a.stack}`);let b=a.code;void 0!==b&&l9.error(`Error code: ${b}`),l9.error(`Error chain: ${jG(a)}`)}else if(a&&"object"==typeof a){let b=Object.getPrototypeOf(a),c="string"==typeof b?.constructor?.name?b.constructor.name:"Unknown";l9.error(`Error type: ${typeof a}`),l9.error(`Error constructor: ${c}`);let d=Object.getOwnPropertyNames(a);d.length>0?(l9.error(`Error properties: ${d.join(", ")}`),d.forEach(b=>{try{let c=a[b];l9.error(` ${b}: ${"function"==typeof c?"[Function]":JSON.stringify(c)}`)}catch(a){l9.error(` ${b}: [Unable to serialize: ${a}]`)}})):l9.error("Error object has no enumerable properties");try{let b=JSON.stringify(a);l9.error(`JSON stringified error: ${b}`)}catch(a){l9.error(`Cannot JSON stringify error: ${a}`)}}else l9.error(`Error value: ${String(a)} (type: ${typeof a})`);this.appendStderrLog(b.name,`Transport error: ${jG(a)}`),this.deregisterClient(b.name),this.getServerConfig(b.name).then(a=>{!a||a.disabled?l9.info(`Server ${b.name} is now disabled, skipping reconnection after transport error`):(l9.info(`Transport error for enabled server ${b.name}, scheduling reconnection`),this.scheduleConnectionRetry(b.name,a))}).catch(a=>{l9.warn(`Error checking server config for ${b.name} during onerror:`,a)})}),await e.connect(f),"stdio"===b.transport&&a&&lq(f),this.clients.set(b.name,e),this.activeTransports.set(b.name,f),this.clientGenerations.set(b.name,this.getClientGeneration(b.name)+1),kH(e))try{await kI(e,b.name,{force:!0})}catch(a){l9.warn(`mcp-stdio-oauth readiness probe failed for ${b.name}:`,a)}this.lastConnectionError.delete(b.name),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),await this.clearLegacyInferredOAuthScopesForHeaderAuth(b.name);let h=function(a){if(ll(a))try{return a.getNegotiatedProtocolVersion()}catch{return}}(e);return l9.info(`connectServer: Successfully connected to ${b.name}`+(h?` (beta SDK, negotiated MCP protocol ${h})`:"")),{success:!0}}catch(j){let a;"stdio"===b.transport&&(0,k5.HW)(b.name),l9.error(`connectServer: Failed to connect to server ${b.name}:`,j);let c=j instanceof Error?j.message:String(j),e=jK(j),f=jJ(j),g=mb(d);if(f&&!g&&("streamable"===b.transport||"sse"===b.transport)){let c=b.serverUrl;c&&(a=(await l3(c)).oauthCapable)}if(e||a){if(l9.info(`OAuth authentication error detected for server ${b.name}: ${c}`),"streamable"===b.transport&&a){let a=b;if(!a.oauthScopes||0===a.oauthScopes.length){l9.info(`Dynamically enabling OAuth for server ${b.name} after capability confirmation`);try{let c={...a,oauthScopes:["read"]},d=await this.loadServerConfigs();if(Array.isArray(d)){let a=d.findIndex(a=>a.name===b.name);-1!==a&&(d[a]=c,await (0,s.saveConfig)(new Map(d.map(a=>[a.name,a]))),l9.info(`Updated config for ${b.name} to enable OAuth`))}}catch(a){l9.warn(`Failed to update config for ${b.name} to enable OAuth:`,a)}}}return{success:!1,error:"OAuth authentication failed or tokens have expired. Please re-authenticate.",requiresAuthentication:!0,oauthCapable:!0}}if(f)return{success:!1,error:c,requiresAuthentication:!0,oauthCapable:a};let h=this.stderrLogs.get(b.name)||[],i=jH(j,b,h);return this.lastConnectionError.set(b.name,i),{success:!1,error:i}}finally{this.connectingServers.delete(b.name)}}async testConnection(a,b,c){l9.info(`testConnection: Testing connection to ${a.name||"(unnamed)"} via ${a.transport} transport`);let d=a=>{try{b?.(a)}catch{}},e=[],f=null,g=null;try{var h;let b,i=a,j=c?.storedName||a.name;if(("streamable"===a.transport||"sse"===a.transport)&&j){let b=await this.loadServerConfigs(),c=Array.isArray(b)?b.find(a=>a.name===j):void 0,d=c?.headers,e=a.headers;i={...a,headers:function(a,b){if(!a)return a;let c={};for(let[d,e]of Object.entries(a)){if(!d)continue;let{value:a,isSecret:f}=k_(e,d);if(f&&k0(a)){let a=b?.[d];void 0!==a&&(c[d]=a);continue}c[d]=e}return c}(e,d)}}let k=await k8(i),l=await lk()&&"websocket"!==k.transport,m={isolateRuntimeHome:await lW(k)};f=l?lm(k):lf(k),g=l?lo(k,m):lg(k,m),"stdio"===k.transport&&kF(f,k.name,l?(h=g,lp.get(h)):void 0);let n=ma(g).stderr;n&&"function"==typeof n.on&&n.on("data",a=>{let b=a.toString();e.push(b),d({type:"stderr",data:b})}),g.onerror=a=>{let b=`Transport error: ${jG(a)}`;e.push(b),d({type:"stderr",data:b+"\n"})},d({type:"status",phase:"spawning",message:"Starting server / opening transport..."});let o=lZ(a)?9e4:15e3,p=lZ(a),q=new Promise((a,c)=>{b=setTimeout(()=>c(Error(`Connection timeout after ${o/1e3}s`+(p?" — the package may still be downloading via npx/uvx. Try running the Test again (the package is cached after the first download), or verify the command and network access.":""))),o)});d({type:"status",phase:"handshaking",message:"Performing MCP handshake..."});try{await Promise.race([f.connect(g),q])}finally{b&&clearTimeout(b)}"stdio"===k.transport&&l&&lq(g),d({type:"status",phase:"listing-tools",message:"Handshake OK — listing tools..."});let r=0;try{let a=await f.listTools();r=Array.isArray(a?.tools)?a.tools.length:0}catch(b){l9.debug(`testConnection: connected to ${a.name} but listTools failed: ${b instanceof Error?b.message:String(b)}`)}return l9.info(`testConnection: Successfully connected to ${a.name} (${r} tools)`),d({type:"result",success:!0,data:{toolCount:r}}),{success:!0,data:{toolCount:r}}}catch(g){let b;l9.warn(`testConnection: Failed to connect to ${a.name}:`,g);let c=jJ(g);if(c&&("streamable"===a.transport||"sse"===a.transport)){let c=a.serverUrl;c&&(b=(await l3(c)).oauthCapable)}let f=jH(g,a,e);return d({type:"result",success:!1,error:f,requiresAuthentication:c,oauthCapable:b}),{success:!1,error:f,requiresAuthentication:c,oauthCapable:b}}finally{if(f)try{await li(f,a.name,a,{gracePeriodMs:3e3,killEscalationMs:2e3})}catch(b){l9.debug(`testConnection: error closing test client for ${a.name}: ${b instanceof Error?b.message:String(b)}`)}}}setNodeRoots(a,b,c){for(let d of(0,jT.eS)(a,b,c))this.notifyRootsChanged(d)}notifyRootsChanged(a){let b=this.getClient(a);if(!b)return void l9.debug(`notifyRootsChanged: ${a} not connected, skipping notification`);try{b.sendRootsListChanged().catch(b=>{l9.warn(`notifyRootsChanged: failed to notify ${a}:`,b)}),l9.debug(`notifyRootsChanged: sent roots/list_changed to ${a}`)}catch(b){l9.warn(`notifyRootsChanged: failed to notify ${a}:`,b)}}notifyAllRootsChanged(){for(let a of this.clients.keys())this.notifyRootsChanged(a)}async disconnectServer(a){l9.debug(`disconnectServer: Entering method for server ${a}`),this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a);let b=this.getClient(a);if(!b)return l9.warn(`disconnectServer: Server ${a} not found in clients map`),this.deregisterClient(a),{success:!1,error:`Server ${a} not found`};this.deregisterClient(a);try{let c=await this.getServerConfig(a);return await function(a,b,c){let d=w(a);if(d.teardownPromise)return t.debug(`beginTeardown: folding onto in-flight teardown for ${a} (${b})`),d.teardownPromise;let e=Date.now();d.state="stopping",d.teardownReason=b;let f=(async()=>{d.connectPromise&&await d.connectPromise.catch(()=>void 0);try{let a=await c(d);a&&a.forced&&(d.forcedKills+=1)}catch(c){t.warn(`beginTeardown: close failed for ${a} (${b}): ${c instanceof Error?c.message:String(c)}`)}finally{d.lastTeardownMs=Date.now()-e,d.state="cold",d.warmSince=void 0,d.configFingerprint=void 0,d.teardownPromise=void 0}})();return d.teardownPromise=f,f}(a,"disconnect",async()=>({forced:(await li(b,a,c||void 0)).forced})),l9.info(`disconnectServer: Disconnected server ${a}`),{success:!0}}catch(b){return l9.warn(`disconnectServer: Failed to disconnect server ${a}:`,b),{success:!1,error:`Failed to disconnect server: ${b instanceof Error?b.message:"Unknown error"}`}}}async disconnectAll(a){let b=[],c=[],d=Array.from(new Set(Array.from(this.clients.keys())));for(let e of(l9.info(`disconnectAll: tearing down ${d.length} MCP server(s) (${a})`),d)){this.clearRetryTimer(e),this.connectionRetryAttempts.delete(e);try{(await this.disconnectServer(e)).success?b.push(e):c.push(e)}catch(a){l9.warn(`disconnectAll: teardown of ${e} threw: ${a instanceof Error?a.message:String(a)}`),c.push(e)}}for(let[a]of Array.from(this.connectionRetryTimers))this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a);return l9.info(`disconnectAll: closed=${b.length} failed=${c.length} (${a})`),{closed:b,failed:c}}getLifecycleReport(){let a;return{runtimes:function(a=!1){let b=Date.now();return(a?Array.from(u().values()):y()).map(a=>({server:a.serverName,workspace:a.workspace,state:a.state,generation:a.generation,leases:a.leases,pins:Array.from(a.pins),idleMs:Math.max(0,b-a.lastUsedAt),connectFailures:a.connectFailures,handshakeFailures:a.handshakeFailures,forcedKills:a.forcedKills,lastTeardownMs:a.lastTeardownMs,lastError:a.lastError}))}(),pool:(a=Date.now(),{...D(),idleTtlMs:B(),maxWarmServers:C(),servers:y().map(b=>({server:b.serverName,state:b.state,leases:b.leases,pins:Array.from(b.pins),idleMs:Math.max(0,a-b.lastUsedAt)}))}),liveClients:this.clients.size}}async sweepIdleMcpServers(){return[...await H(this),...await I(this)]}acquireServerLease(a){return F(this,a)}pinServer(a,b){G(a,b)}unpinServer(a,b){x(a)?.pins.delete(b)}async forceReconnect(a){l9.info(`forceReconnect: Forcing fresh connection for server ${a}`);let b=this.clients.get(a);if(b){this.deregisterClient(a);let c=await this.getServerConfig(a);try{await li(b,a,c||void 0)}catch(b){l9.debug(`forceReconnect: error closing stale client for ${a}: ${b instanceof Error?b.message:String(b)}`)}}return this.connectServer(a)}async listServerTools(a,b="model"){if(l9.debug(`listServerTools: Entering method for server ${a}, audience ${b}`),await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return l9.warn(`listServerTools: ${b}`),{tools:[],error:b}}let c=this.getClient(a);c||l9.warn(`listServerTools: Client not found for ${a}`);let d=await lA(c,a,b);if(d.error){l9.warn(`listServerTools: Listing tools for ${a} failed (${d.error}); forcing reconnect and retrying once`);let e=await this.forceReconnect(a);if(!e.success)return l9.warn(`listServerTools: Reconnect for ${a} failed: ${e.error}`),{tools:[],error:e.error||d.error};c=this.clients.get(a),(d=await lA(c,a,b)).error?l9.warn(`listServerTools: Retry after reconnect still failed for ${a}:`,d.error):l9.info(`listServerTools: Recovered after reconnect for ${a}; listed ${d.tools.length} tools`)}else l9.info(`listServerTools: Listed ${d.tools.length} tools for ${a}`);return d}async getExternalAuthorizationStatus(a,b=!1){return kI(this.getClient(a),a,{force:b})}async prepareExternalAuthorization(a,b,c={}){let d=this.getClient(a);if(!d){let b=await this.forceReconnect(a);if(!b.success)throw Error(b.error||`Could not connect to ${a}.`);d=this.getClient(a)}if(!d)throw Error(`MCP server '${a}' is not connected.`);return kO(d,a,b,c)}confirmExternalAuthorization(a,b){let c=kA.get(kE(b));if(!c||c.serverName!==a||!c.prompt)throw Error("The authorization request is no longer active. Start it again.");if(!c.resolveElicitation||c.elicitationResponded)throw Error("The authorization request is no longer awaiting consent. Start it again.");let d=c.resolveElicitation;return c.resolveElicitation=void 0,c.elicitationResponded=!0,d({action:"accept"}),kJ(a),c.prompt}declineExternalAuthorization(a,b){let c=kA.get(kE(b));if(!c||c.serverName!==a||!c.prompt||!c.resolveElicitation)return!1;let d=c.resolveElicitation;return c.resolveElicitation=void 0,c.elicitationResponded=!0,d({action:"decline"}),kJ(a),!0}cancelExternalAuthorization(a,b){return kM(a,b)}async callTool(a,b,d,e,f,g,h,i="host",j,k){if(l9.debug(`callTool: Entering method for server ${a}, tool ${b}, source ${i}`),await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return l9.warn(`callTool: ${b}`),{success:!1,error:b}}let l=this.getClient(a),m=await this.acquireServerLease(a),n=m.lease;n?l=n.client:l||l9.warn(`callTool: Lease acquisition for ${a} failed: ${m.error}`);try{let m;if(l&&kH(l))try{let c=await kI(l,a,{force:!0});if(c.blockingAuthorization){let d=c.blockingAuthorization,e=d.message||`${d.label} authorization is required. Open the MCP page to authenticate before running this flow.`;return l9.warn(`callTool: blocked ${a}/${b}: ${e}`),{success:!1,error:e,errorType:"stdio-oauth-required",statusCode:428,requiresAuthentication:!0}}}catch(c){let b=c instanceof Error?c.message:String(c);return l9.warn(`callTool: mcp-stdio-oauth readiness check failed for ${a}: ${b}`),{success:!1,error:`Could not verify account readiness for '${a}': ${b}`,errorType:"stdio-oauth-status",statusCode:503}}let n="model"===i&&"create_ticket_for_human"===b&&k?.conversationId?await this.getServerConfig(a):null,o=l6(n,b,i,k),p=o?(m=l6(n,b,i,k))?{...d,conversation_id:m}:d:d,q=await lB(l,a,b,p,e,f,h,i,g,j);if(q.success&&o){let a=function(a){if(!a||"object"!=typeof a)return;let b=a.content;if(Array.isArray(b))for(let a of b){if(!a||"object"!=typeof a||"text"!==a.type)continue;let b=a.text;if("string"==typeof b)try{let a=JSON.parse(b);if(!0===a.created&&"string"==typeof a.id&&l5.test(a.id))return a.id}catch{}}}(q.data);if(a)try{let{ticketService:b}=await Promise.resolve().then(c.bind(c,26884));await b.stampPersonaAttributionFromTrustedConversation(a,o)}catch(b){l9.error(`callTool: Failed to stamp trusted ticket attribution for ${a}`,b)}}return l9.info(`callTool: Called tool ${b} on ${a}`),q}finally{n?.release()}}async callToolFromApp(a,b,c,d,e,f){let g=await this.checkMcpAppAccess(a);if(g)return g;let h=await this.callTool(a,b,c,d,void 0,void 0,e,"app",f);if("tool-authorization-list"!==h.errorType)return h;l9.warn(`callToolFromApp: visibility lookup failed for ${a}/${b}; reconnecting and retrying once before dispatch`);let i=await this.forceReconnect(a);return i.success?h=await this.callTool(a,b,c,d,void 0,void 0,e,"app",f):{success:!1,error:i.error||h.error,statusCode:h.statusCode}}async isMcpAppAccessEnabled(a){let b=await this.getServerConfig(a);return b?.disabled!==!0&&b?.enableMcpApps===!0}async checkMcpAppAccess(a){if(await this.isMcpAppAccessEnabled(a))return null;let b=`MCP Apps are not enabled for server '${a}'. Enable them on the MCP page before opening or using this app.`;return l9.warn(`MCP App access denied: ${b}`),{success:!1,error:b,statusCode:403}}async readResourceFromApp(a,b){let c=await this.checkMcpAppAccess(a);return c||this.readResource(a,b)}async listWithReconnect(a,b,c){if(await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return l9.warn(`listWithReconnect: ${b}`),{...c,error:b}}let d=this.getClient(a);d||l9.warn(`listWithReconnect: Client not found for ${a}`);let e=await b(d,a);if(!e.error)return e;l9.warn(`listWithReconnect: Listing for ${a} failed (${e.error}); forcing reconnect and retrying once`);let f=await this.forceReconnect(a);return f.success?(d=this.clients.get(a),(e=await b(d,a)).error?l9.warn(`listWithReconnect: Retry after reconnect still failed for ${a}:`,e.error):l9.info(`listWithReconnect: Recovered after reconnect for ${a}`),e):(l9.warn(`listWithReconnect: Reconnect for ${a} failed: ${f.error}`),{...c,error:f.error||e.error})}async listServerResources(a){return l9.debug(`listServerResources: Entering method for server ${a}`),this.listWithReconnect(a,lD,{resources:[]})}async listServerResourceTemplates(a){return l9.debug(`listServerResourceTemplates: Entering method for server ${a}`),this.listWithReconnect(a,lE,{resourceTemplates:[]})}async readResource(a,b){l9.debug(`readResource: Entering method for server ${a}, uri ${b}`);let c=this.getClient(a);c||l9.warn(`readResource: Client not found for ${a}`);let d=await lF(c,a,b);return l9.info(`readResource: Read resource ${b} on ${a}`),d}async prepareMcpSkillsClient(a){let b=await this.getServerConfig(a);if(!b)return{success:!1,error:`MCP server '${a}' was not found.`,statusCode:404};if(b.disabled)return{success:!1,error:`Server '${a}' is disabled. Enable it on the MCP page to use it.`,statusCode:409,errorType:"disabled"};if(!0!==b.enableMcpSkills)return{success:!1,error:`MCP Skills are disabled for server '${a}'.`,statusCode:409,errorType:"skills_disabled"};let c=await this.connectServer(a);if(!c.success)return{success:!1,error:c.error||`Failed to connect to MCP server '${a}'.`,statusCode:c.statusCode||502};let d=this.getClient(a),e=lM(d,!0);return d&&e?{success:!0,data:{client:d,capability:e}}:{success:!1,error:`Server '${a}' does not advertise ${r.ET}.`,statusCode:404,errorType:"skills_unsupported"}}async getServerSkillsCapability(a){let b=await this.prepareMcpSkillsClient(a);return b.success?b.data?.capability:void 0}async listServerSkills(a,b){let c=await this.getServerConfig(a);if(!c||c.disabled||!0!==c.enableMcpSkills)return{resultType:"complete",skills:[],serverName:a,availability:"disabled",...!c?{error:`MCP server '${a}' was not found.`}:{}};let d=await this.prepareMcpSkillsClient(a);if(!d.success||!d.data)return{resultType:"complete",skills:[],serverName:a,availability:"skills_unsupported"===d.errorType?"unsupported":"available",..."skills_unsupported"===d.errorType?{}:{error:d.error}};let e=async a=>lP(a,!0,b);try{return{...await e(d.data.client),serverName:a,availability:"available",capability:d.data.capability}}catch(b){if(b instanceof lL)return{resultType:"complete",skills:[],serverName:a,availability:"unsupported"};if((await this.forceReconnect(a)).success){let c=this.getClient(a);try{let b=await e(c),d=lM(c,!0);return{...b,serverName:a,availability:"available",...d?{capability:d}:{}}}catch(a){b=a}}return{resultType:"complete",skills:[],serverName:a,availability:"available",error:b instanceof Error?b.message:"Failed to list MCP Skills."}}}async getServerSkill(a,b){let c=await this.prepareMcpSkillsClient(a);if(!c.success||!c.data)return l8(c);try{return{success:!0,data:await lQ(c.data.client,!0,b)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Failed to get MCP Skill.",statusCode:a instanceof lL?404:502}}}async readServerSkillDirectory(a,b,c){let d=await this.prepareMcpSkillsClient(a);if(!d.success||!d.data)return l8(d);try{return{success:!0,data:await lR(d.data.client,!0,b,c)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Failed to read MCP Skill directory.",statusCode:a instanceof lL?404:502}}}async readVerifiedSkillResource(a,b,c){let d=await this.prepareMcpSkillsClient(a);if(!d.success||!d.data)return l8(d);let e=await this.getServerSkill(a,b);if(!e.success||!e.data)return l8(e);try{return{success:!0,data:await lS(d.data.client,!0,e.data.skill,c)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Failed to verify MCP Skill resource.",statusCode:422}}}async loadVerifiedSkill(a,b,c){let d=await this.prepareMcpSkillsClient(a);if(!d.success||!d.data)return l8(d);let e=await this.getServerSkill(a,b);if(!e.success||!e.data)return l8(e);if("dynamic"===e.data.skill.resources)return{success:!1,error:"Dynamic MCP Skills cannot be integrity-verified.",statusCode:422};let f=(0,r.Bw)(e.data.skill.uri).normalizedUri,g=e.data.skill.resources.find(a=>a.uri===f);if(!g)return{success:!1,error:"MCP Skill manifest metadata is missing.",statusCode:422};if(!function(a,b=Date.now()){let c=function(a){let b=a.conversationId.trim(),c=a.serverName.trim();if(!b||b.length>512)throw Error("A valid conversation ID is required to approve an MCP Skill.");if(!c||c.length>512)throw Error("A valid MCP server name is required to approve a Skill.");return{conversationId:b,serverName:c,skillUri:(0,r.Bw)(a.skillUri).normalizedUri,manifestDigest:(0,r.cU)(a.manifestDigest)}}(a),d=(0,p.getCurrentWorkspace)(),e=JSON.stringify([d,c.conversationId,c.serverName,c.skillUri]),f=lU().get(e);if(!f)return;let g=(0,r.BC)(c.serverName,c.skillUri,c.manifestDigest),h=(0,r.BC)(f.serverName,f.skillUri,f.manifestDigest);return f.expiresAt<=b||f.workspace!==d||f.conversationId!==c.conversationId||h!==g?void lU().delete(e):f}({conversationId:c,serverName:a,skillUri:f,manifestDigest:g.digest}))return{success:!1,error:"This MCP Skill is not approved for the current conversation and manifest digest.",statusCode:403,errorType:"skills_approval_required"};try{return{success:!0,data:await lT(d.data.client,!0,a,e.data.skill)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Failed to load MCP Skill.",statusCode:422}}}async listServerPrompts(a){return l9.debug(`listServerPrompts: Entering method for server ${a}`),this.listWithReconnect(a,lH,{prompts:[]})}async getPrompt(a,b,c){l9.debug(`getPrompt: Entering method for server ${a}, prompt ${b}`);let d=this.getClient(a);d||l9.warn(`getPrompt: Client not found for ${a}`);let e=await lI(d,a,b,c);return l9.info(`getPrompt: Got prompt ${b} on ${a}`),e}async resolveOAuthSecretForSave(a,b){return(k0(a)&&(a=b??""),a)?a.startsWith("${global:")?a:this.encryptSecretForSave(a):""}async encryptSecretForSave(a){if(a.startsWith("encrypted_failed:"))throw Error("MCP credential encryption failed");if(a.startsWith("encrypted:")&&a.length>10)return a;let b=await (0,lX.Rs)(a);if(!b.startsWith("encrypted:")||b.length<=10)throw Error("MCP credential encryption failed");return b}async resolveEnvForSave(a,b){let c={};for(let[d,e]of Object.entries((0,lY.ds)(a))){let a="string"==typeof e?e:e.value,f=b?.[d],g="object"==typeof f&&f.metadata.isSecret;if(!("string"==typeof e?g||kZ(d):e.metadata.isSecret)){c[d]=e;continue}k0(a)&&(void 0===f||k0(a="string"==typeof f?f:f.value))||(c[d]={value:!a||k$(a)?a:await this.encryptSecretForSave(a),metadata:{isSecret:!0}})}return c}async resolveHeadersForSave(a,b){let c={};for(let[d,e]of Object.entries(a||{})){if(!d)continue;let{value:a}=k_(e,d),{isSecret:f}=k_(e,d);if(!f){""!==a&&(c[d]={value:a,metadata:{isSecret:!1}});continue}if(k0(a)){let c=b?.[d];if(void 0===c||k0(a=k_(c,d).value))continue}if(a){if(k$(a)){c[d]={value:a,metadata:{isSecret:!0}};continue}c[d]={value:await this.encryptSecretForSave(a),metadata:{isSecret:!0}}}}return c}async ensureManagedServerRootDir(a){try{let b=(a.rootPath||"").trim();if(!b)return;let c=["streamable","sse","websocket"].includes(a.transport),d="stdio"===a.transport&&(a.source?.type==="registry"||a.source?.type==="marketplace");if(!c&&!d)return;let e=n().resolve((0,p.getWorkspaceDataDir)(),b);if(n().dirname(e)===e)return;if(d){let a=n().join((0,p.getWorkspaceDataDir)(),"mcp-servers"),b=n().relative(a,e);if(!b||b.startsWith("..")||n().isAbsolute(b))return}await l().mkdir(e,{recursive:!0}),l9.debug(`ensureManagedServerRootDir: ensured ${e} for ${a.name}`)}catch(b){l9.warn(`ensureManagedServerRootDir: could not create root dir for ${a.name}:`,b)}}async updateServerConfig(a,b){l9.debug(`updateServerConfig: Entering method for server ${a}`);let d=await this.loadServerConfigs();if(!Array.isArray(d))return l9.warn("updateServerConfig: Failed to load configs:",d.error),d;let e=d.find(b=>b.name===a),f=!!e&&"string"==typeof b.name&&b.name!==a;if(f&&d.some(a=>a.name===b.name))return l9.warn(`updateServerConfig: Refusing to rename ${a} -> ${b.name}: name already in use`),{success:!1,error:`A server named "${b.name}" already exists`};if(!e&&b.name)l9.info(`updateServerConfig: Creating new server config for ${b.name}`),e={name:b.name,transport:"stdio",command:"",args:[],env:{},disabled:!1,_buildCommand:"",_installCommand:"",rootPath:""},d.push(e);else if(!e)return l9.warn(`updateServerConfig: Server ${a} not found`),{success:!1,error:`Server ${a} not found`};b={...b};try{void 0!==b.env&&(b.env=await this.resolveEnvForSave(b.env,e.env));let a=b.oauthClientSecret;if(void 0!==a){let c=e.oauthClientSecret;b.oauthClientSecret=await this.resolveOAuthSecretForSave(a,c)}let c=b.headers;if(void 0!==c){let a=e.headers;b.headers=await this.resolveHeadersForSave(c,a)}}catch{return{success:!1,error:"Failed to encrypt MCP credentials; configuration was not saved"}}let g={...e};g={...e,...b};let h=JSON.stringify(e.roots??[])!==JSON.stringify(g.roots??[])||(e.rootPath??"")!==(g.rootPath??""),i=d.findIndex(b=>b.name===a);-1!==i?d[i]=g:g.name&&d.push(g);let j=await (0,s.saveConfig)(new Map(d.map(a=>[a.name,a])));if(!j.success)return l9.warn(`updateServerConfig: Failed to save config for ${a}:`,j.error),j;if(await this.ensureManagedServerRootDir(g),f)try{let{flowService:b}=await Promise.resolve().then(c.bind(c,22605)),d=await b.migrateMcpServerReferences(a,g.name);d.success?d.migratedReferences>0&&l9.info(`updateServerConfig: Migrated ${d.migratedReferences} MCP reference(s) across ${d.migratedFlows} flow(s)`):l9.warn("updateServerConfig: Server rename succeeded, but some flow references could not be migrated",d)}catch(a){l9.warn("updateServerConfig: Server rename succeeded, but flow-reference migration failed",a)}return f?(this.clients.has(a)?await this.disconnectServer(a):(this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a)),this.stderrLogs.delete(a),this.lastConnectionError.delete(a),await this.handleConnectionStateChange(g.name,g)):await this.handleConnectionStateChange(a,g),h&&this.notifyRootsChanged(g.name),l9.info(`updateServerConfig: Successfully updated config for ${a}${f?` (renamed to ${g.name})`:""}`),g}async handleConnectionStateChange(a,b){l9.debug(`handleConnectionStateChange: Entering method for server ${a}`);let c=!!this.getClient(a),d=!b.disabled;if(c&&!d){l9.info(`handleConnectionStateChange: Disconnecting disabled server ${a}`);try{await this.disconnectServer(a)}catch(b){l9.warn(`handleConnectionStateChange: Failed to disconnect server ${a} during update:`,b)}}else!c&&d?(l9.info(`handleConnectionStateChange: Connecting previously disabled server ${a}`),await this.connectServer(b)):c&&d?(l9.info(`handleConnectionStateChange: Re-applying config to connected server ${a}`),await this.connectServer(b)):d||(l9.info(`handleConnectionStateChange: Clearing retry timers for disabled server ${a}`),this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a))}async clearRetryTimersForDisabledServers(){l9.debug("clearRetryTimersForDisabledServers: Checking for disabled servers with active retry timers");try{let a=await this.loadServerConfigs();if(!Array.isArray(a))return void l9.warn("clearRetryTimersForDisabledServers: Failed to load server configs");for(let b of a.filter(a=>a.disabled))this.connectionRetryTimers.has(b.name)&&(l9.info(`clearRetryTimersForDisabledServers: Clearing retry timer for disabled server ${b.name}`),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name))}catch(a){l9.error("clearRetryTimersForDisabledServers: Error clearing retry timers:",a)}}async deleteServerConfig(a){l9.debug(`deleteServerConfig: Entering method for server ${a}`),this.clients.has(a)&&(l9.info(`deleteServerConfig: Disconnecting server ${a} before deletion`),await this.disconnectServer(a));let b=await this.loadServerConfigs();if(!Array.isArray(b))return l9.warn("deleteServerConfig: Failed to load configs:",b.error),b;let c=b.findIndex(b=>b.name===a);if(-1===c)return l9.warn(`deleteServerConfig: Server ${a} not found in configs`),{success:!1,error:`Server ${a} not found`};b.splice(c,1),l9.debug(`deleteServerConfig: Saving updated configs after deleting ${a}`);let d=await (0,s.saveConfig)(new Map(b.map(a=>[a.name,a])));return d.success?l9.info(`deleteServerConfig: Successfully deleted server ${a}`):l9.warn(`deleteServerConfig: Error saving configs after deleting ${a}:`,d.error),d}async getServerStatus(a){let b,c=await this.getServerConfig(a);if(!c)return l9.warn(`getServerStatus: Server ${a} not found`),{status:"error",message:`Server ${a} configuration not found. The server may have been deleted or not properly configured.`};if(c.disabled)return l9.debug(`getServerStatus: Server ${a} is disabled`),{status:"disconnected"};let d=!!this.getClient(a);if("streamable"===c.transport&&!d&&c.oauthScopes&&c.oauthScopes.length>0){if(!c.oauthTokens||!c.oauthTokens.access_token)return l9.info(`getServerStatus: Server ${a} requires OAuth authentication but has no valid tokens`),{status:"requires_authentication",message:"OAuth authentication required. Click the authenticate button to complete the OAuth flow."};let b=c.oauthTokens.issued_at;if(!c.oauthTokens.refresh_token&&c.oauthTokens.expires_in&&b){let d=c.oauthTokens.expires_in;if(Math.floor(Date.now()/1e3)>=b+d)return l9.info(`getServerStatus: OAuth tokens for ${a} have expired and no refresh token is available`),{status:"requires_authentication",message:"OAuth tokens have expired. Please re-authenticate."}}}let e=(this.stderrLogs.get(a)||[]).join("\n").trim(),f=this.lastConnectionError.get(a);if(d){let c=this.getClient(a);if(kH(c))try{if((b=await kI(c,a)).blockingAuthorization){let a=b.blockingAuthorization;return{status:"requires_authentication",message:a.message||`${a.label} authorization is required before this server can be used by unattended flows.`,stderrOutput:e||void 0,stdioOAuth:b}}}catch(b){let a=b instanceof Error?b.message:String(b);return{status:"error",message:`Connected, but the mcp-stdio-oauth readiness check failed: ${a}`,stderrOutput:e||void 0}}}if(d||this.getClient(a))return l9.info(`getServerStatus: Server ${a} is connected`),{status:"connected",stderrOutput:e||void 0,...b?{stdioOAuth:b}:{}};{let b=this.isStartingUp()&&!this.lastConnectionError.has(a);if(this.connectingServers.has(a)||b)return l9.info(`getServerStatus: Server ${a} is still connecting`),{status:"connecting",message:"Server is starting up. This may take a few moments."};if(e&&(e.includes("OAuth authentication required")||e.includes("invalid_token")))return l9.info(`getServerStatus: OAuth authentication error detected for ${a}`),{status:"requires_authentication",message:"OAuth authentication required. Please complete the OAuth flow.",stderrOutput:e};let c=e||f;return c?(l9.info(`getServerStatus: Using ${e?"stderr output":"persisted connection error"} as error message for ${a}`),{status:"error",message:c,stderrOutput:e||void 0}):(l9.info(`getServerStatus: No specific error details available for ${a}`),{status:"error",message:`Server ${a} is configured but not connected. The server process may have crashed or been terminated.`,stderrOutput:void 0})}}async startEnabledServers(){l9.info("Starting all enabled servers"),this.setStartingUp(!0);try{await this.clearRetryTimersForDisabledServers();let a=await this.loadServerConfigs();if(!Array.isArray(a))return void l9.warn("Failed to load server configs, cannot start servers");let b=a.filter(a=>!a.disabled),c=/^(1|true|yes)$/i.test(process.env.FLUJO_MCP_LAZY_START??""),d=b.filter(a=>!0===a.alwaysOn);for(let a of d)G(a.name,"always-on");let e=c?d:b;c?l9.info(`Lazy MCP start: ${b.length} enabled server(s) discovered, warming only ${d.length} always-on server(s)`):(l9.info(`Found ${e.length} enabled servers to start`),l9.debug(`${e}`)),e.forEach(a=>this.connectingServers.add(a.name));let f=Math.max(1,Number(process.env.FLUJO_MCP_BOOT_CONCURRENCY)||2);l9.info(`Connecting ${e.length} enabled servers with boot concurrency ${f}`),await (0,q.P)(e,f,async a=>{l9.info(`Starting server: ${a.name}`),await this.connectServer(a).catch(b=>{l9.error(`Failed to start server ${a.name}:`,b)})})}finally{this.setStartingUp(!1)}}async getAvailableClients(){try{let a=await this.loadServerConfigs();if(!a||"error"in a)return l9.warn("getAvailableClients: Failed to load server configs:",a?.error),[];return(await Promise.all(a.map(async a=>{try{let b=await this.getServerStatus(a.name);return{name:a.name,status:"string"==typeof b?b:b.status,connected:"string"==typeof b?"connected"===b:"connected"===b.status}}catch(b){return l9.warn(`getAvailableClients: Error getting status for ${a.name}:`,b),{name:a.name,status:"error",connected:!1}}}))).map(a=>`${a.name} (${a.status})`)}catch(a){return l9.error("getAvailableClients: Error getting available clients:",a),[]}}constructor(){this.stderrLogsBase=new Map,this.lastConnectionErrorBase=new Map,this.inFlightConnectsBase=new Map,this.connectionRetryTimersBase=new Map,this.connectionRetryAttemptsBase=new Map,this.resourceListVersionBase=new Map,this.pendingResourceUpdatesBase=new Map}}let md=new mc},11554:(a,b,c)=>{"use strict";let d;c.r(b),c.d(b,{INTERRUPTED_TOOL_RESULT_CONTENT:()=>N,_setConversationLogDirForTests:()=>r,allocateSeq:()=>w,appendFromBus:()=>C,appendRawForState:()=>D,deleteConversationLog:()=>H,flushConversationLog:()=>E,hasConversationLog:()=>S,latestSequence:()=>x,projectMessages:()=>I,projectModelContextMessages:()=>J,readConversationLog:()=>G,reconcileConversationLog:()=>M,recoverConversationTranscript:()=>R,recoverMessagesFromLog:()=>P,repairDanglingToolCalls:()=>O,repairTruncatedConversationLog:()=>Q,replaceConversationTranscript:()=>F});var e=c(29021),f=c(33873),g=c.n(f),h=c(91065),i=c(62888),j=c(82964),k=c(28461),l=c(6727);let m=(0,j.h)("backend/execution/flow/conversationLog"),n=new Set(["run:start","run:done","recovery:checkpoint","recovery:transition","recovery:retry","node:enter","node:exit","node:snapshot","node:changed-files","model:dispatch","model:dispatch-result","handoff","message","message:removed","tool:call","tool:result","usage","subflow:start","subflow:done","resource:read","resource:write","error"]),o=/^[A-Za-z0-9_-]+$/,p=()=>d??g().join((0,k.getWorkspaceDataDir)(),"db","conversation-logs"),q=a=>(0,k.workspaceCacheKey)("conversation-log",a);function r(a){let b=d;return d=a,u.clear(),b??a}function s(a){return g().join(p(),`${a}.jsonl`)}let t=new Map,u=new Map;function v(a){if(u.has(q(a)))return;let b=-1;try{for(let c of(0,e.readFileSync)(s(a),"utf-8").split("\n"))if(0!==c.trim().length)try{let a=JSON.parse(c).seq;"number"==typeof a&&Number.isFinite(a)&&a>b&&(b=a)}catch{}}catch(b){"ENOENT"!==b.code&&m.warn(`Could not read conversation log ${a} to seed seq; starting at 0.`,{err:b})}u.set(q(a),b+1)}function w(a){v(a);let b=u.get(q(a));return u.set(q(a),b+1),b}async function x(a){return o.test(a)?(v(a),u.get(q(a))-1):-1}function y(a,b){return(0,l.NU)(async()=>{let c=q(a),d=(t.get(c)??Promise.resolve()).catch(()=>{}).then(async()=>{await e.promises.mkdir(p(),{recursive:!0}),await e.promises.appendFile(s(a),b)});return t.set(c,d),d.finally(()=>{t.get(c)===d&&t.delete(c)})})}function z(a,b){return(0,l.NU)(async()=>{let c=q(a),d=(t.get(c)??Promise.resolve()).catch(()=>{}).then(async()=>{await e.promises.mkdir(p(),{recursive:!0}),await e.promises.writeFile(s(a),b)});return t.set(c,d),d.finally(()=>{t.get(c)===d&&t.delete(c)})})}async function A(a,b){if(a.personaAttribution&&!a.executionAuthority)throw Error("Persona-attributed transcript persistence requires current execution authority.");return a.executionAuthority?a.executionAuthority?.commitWhileCurrent?a.executionAuthority.commitWhileCurrent(b):(await a.executionAuthority.assertCurrent(),b()):b()}function B(a){return`${JSON.stringify(a)}
53
53
  `}function C(a){if(!n.has(a.type))return;if(!o.test(a.conversationId))return void m.warn("Refusing to log event for unsafe conversation id",{conversationId:a.conversationId});let b=function(a){try{if((0,i.isConversationDeleted)(a))return;let{FlowExecutor:b}=c(14727),d=b.conversationStates.get(a);if(!d||d.ephemeral)return;return d}catch(b){m.warn(`Could not resolve persistence policy for ${a}; not persisting.`,{err:b});return}}(a.conversationId);b&&A(b,()=>y(a.conversationId,B(a))).catch(b=>m.warn(`Failed to append event to conversation log ${a.conversationId}`,{err:b}))}async function D(a,b){if(0===b.length||a.ephemeral)return;let c=a.conversationId;if(!c||!o.test(c)||(0,i.isConversationDeleted)(c))return;let d=b.map(a=>B({...a,conversationId:c,seq:w(c),timestamp:Date.now()})).join("");try{await A(a,()=>y(c,d))}catch(d){if(m.warn(`Failed to append ${b.length} event(s) to conversation log ${c}`,{err:d}),a.executionAuthority||a.personaAttribution)throw d}}function E(a){let b=t.get(q(a));return b?b.then(()=>void 0,()=>void 0):Promise.resolve()}async function F(a,b){if(a.ephemeral)throw Error("Cannot rewrite an ephemeral conversation transcript.");let c=a.conversationId;if(!c||!o.test(c))throw Error("Cannot rewrite a transcript without a safe conversation id.");await E(c);let d=s(c),f="";try{f=await e.promises.readFile(d,"utf-8")}catch(a){if("ENOENT"!==a.code)throw a}let g=a.messages,i=J(f.split("\n").filter(a=>a.trim().length>0).flatMap(a=>{try{return[JSON.parse(a)]}catch{return[]}})),j=[...(i.length>0?i:g.filter(a=>"system"!==a.role)).map(a=>({type:"message:removed",messageId:a.id})),...b.filter(a=>"system"!==a.role).map(a=>({type:"message",message:a}))].map(a=>B({...a,conversationId:c,seq:w(c),timestamp:Date.now()})).join("");await A(a,()=>z(c,f+j)),a.messages=structuredClone(b);try{await (0,h.persistConversationState)(`conversations/${c}`,a)}catch(b){a.messages=g;try{await A(a,()=>z(c,f))}catch(a){m.error("Failed to roll back conversation log after transcript rewrite failure",{conversationId:c,rollbackError:a})}throw b}}async function G(a){let b;if(!o.test(a))return;try{b=await e.promises.readFile(s(a),"utf-8")}catch(b){if("ENOENT"===b.code)return;m.error(`Error reading conversation log ${a}:`,b);return}let c=[],d=0;for(let a of b.split("\n"))if(0!==a.trim().length)try{c.push(JSON.parse(a))}catch{d++}return d>0&&m.warn(`Skipped ${d} unparseable line(s) in conversation log ${a} (truncated append?)`),c}async function H(a){o.test(a)&&await (0,l.NU)(async()=>{let b=q(a),c=(t.get(b)??Promise.resolve()).catch(()=>{}).then(()=>e.promises.unlink(s(a)));t.set(b,c);try{await c}catch(b){"ENOENT"!==b.code&&m.warn(`Error deleting conversation log ${a}:`,b)}finally{t.get(b)===c&&t.delete(b)}})}function I(a){return K(a,!1)}function J(a){return K(a,!0)}function K(a,b){let c=[],d=new Map,e=new Map;for(let f of a)if("message"===f.type){let a=f.message;if(!a||!a.id||"system"===a.role)continue;let b=f.depth??0,g=a.id,h=d.get(g);if(void 0!==h&&/^stream_codex_item_/.test(g)){let a=(e.get(g)??1)+1;e.set(g,a),g=`${g}_legacy_${a}`,h=void 0}else e.has(g)||e.set(g,1);let i=g===a.id?a:{...a,id:g},j=b>0?{...i,depth:b}:{...i};void 0!==h?c[h]=j:(d.set(g,c.length),c.push(j))}else if("node:changed-files"===f.type){let a=f.node?.nodeId;if(!a||0===f.changedFiles.length)continue;for(let b=c.length-1;b>=0;b--)if(c[b].processNodeId===a){c[b]={...c[b],changedFiles:f.changedFiles.map(({path:a,status:b})=>({path:a,status:b}))};break}}else if(b&&"message:removed"===f.type){let a=d.get(f.messageId);if(void 0===a)continue;for(let[b,e]of(c.splice(a,1),d.delete(f.messageId),d))e>a&&d.set(b,e-1)}return c}function L(a){return JSON.stringify([a.role,a.content,a.tool_calls??null,a.disabled??!1,a.processNodeId??null])}async function M(a,b){if(a.ephemeral)return;let c=a.conversationId;if(!c||!o.test(c))return;let d=(a.messages??[]).filter(a=>"system"!==a.role&&!!a.id),e=await S(c)?b.filter(a=>"system"!==a.role&&!!a.id):[],f=new Map(e.map(a=>[a.id,a])),g=new Set(d.map(a=>a.id)),h=[];for(let a of d){let b=f.get(a.id);b&&L(b)===L(a)||h.push({type:"message",message:a})}for(let a of e)g.has(a.id)||h.push({type:"message:removed",messageId:a.id});await D(a,h)}let N="Tool execution interrupted (FLUJO restarted before this tool finished)";function O(a,b=N){if("paused_debug"===a.status&&(a.debugPendingAction||a.debugPendingToolCalls?.length)||"awaiting_tool_approval"===a.status&&a.pendingToolCalls?.length||a.handoffRequested)return[];let c=a.messages??[];if(0===c.length)return[];let d=new Set;for(let a of c)if("tool"===a.role){let b=a.tool_call_id;b&&d.add(b)}let e=[],f=[];for(let a=0;a<c.length;a++){let g=c[a];f.push(g);let h=g.tool_calls;if("assistant"!==g.role||!Array.isArray(h)||0===h.length)continue;let i=h.filter(a=>!!a.id&&!d.has(a.id));if(0===i.length)continue;let j=a+1;for(;j<c.length&&"tool"===c[j].role;)f.push(c[j]),j++;for(let a of i){let c={id:crypto.randomUUID(),role:"tool",tool_call_id:a.id,content:b,timestamp:Date.now(),...void 0!==g.processNodeId?{processNodeId:g.processNodeId}:{},...void 0!==g.depth?{depth:g.depth}:{}};f.push(c),e.push(c),d.add(a.id)}a=j-1}return 0===e.length?[]:(a.messages=f,e)}async function P(a){if(a.ephemeral)return!1;let b=a.conversationId;if(!b||!o.test(b))return!1;let c=await G(b);if(!c)return!1;let d=J(c).filter(a=>!((a.depth??0)>0)),e=(a.messages??[]).filter(a=>"system"!==a.role&&!!a.id).map(a=>a.id);if(d.length<=e.length)return!1;let f=new Set(d.map(a=>a.id));return!!e.every(a=>f.has(a))&&(m.info(`Recovered ${d.length-e.length} message(s) from the conversation log for ${b} (snapshot was behind).`),a.messages=d,!0)}async function Q(a){if(a.ephemeral||a.personaAttribution&&!a.executionAuthority)return;let b=a.conversationId;if(!b||!o.test(b))return;let c=await G(b);if(!c)return;let d=J(c).filter(a=>!((a.depth??0)>0)),e=(a.messages??[]).filter(a=>"system"!==a.role&&!!a.id);if(d.length>=e.length)return;let f=new Set(e.map(a=>a.id));if(!d.every(a=>f.has(a.id)))return;let g=new Set(d.map(a=>a.id)),h=e.filter(a=>!g.has(a.id));try{await D(a,h.map(a=>({type:"message",message:a}))),m.info(`Repaired truncated conversation log for ${b} from snapshot (${d.length} → ${e.length} active message(s), ${h.length} append(s)); issue #49 self-heal.`)}catch(a){m.warn(`Failed to repair truncated conversation log ${b}`,{err:a})}return e}async function R(a){let b=(a.messages??[]).filter(a=>"system"!==a.role).map(a=>({...a,id:a.id||crypto.randomUUID()}));if(a.ephemeral)return{messages:b,source:"snapshot"};let c=a.conversationId;if(!c||!o.test(c))return{messages:b,source:"snapshot"};await E(c),await Q(a);let d=await G(c),e=d?I(d):[];if(0===e.length)return{messages:b,source:"snapshot"};let f=new Set(e.map(a=>a.id));return{messages:[...e,...b.filter(a=>!f.has(a.id))],source:"durable-log"}}async function S(a){if(!o.test(a))return!1;try{return await e.promises.access(s(a)),!0}catch{return!1}}},11836:function(a,b,c){var d;d=c(61345),c(92256),c(17212),c(1296),c(90751),function(){var a=d.lib.StreamCipher,b=d.algo,c=[],e=[],f=[],g=b.RabbitLegacy=a.extend({_doReset:function(){var a=this._key.words,b=this.cfg.iv,c=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],d=this._C=[a[2]<<16|a[2]>>>16,0xffff0000&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,0xffff0000&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,0xffff0000&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,0xffff0000&a[3]|65535&a[0]];this._b=0;for(var e=0;e<4;e++)h.call(this);for(var e=0;e<8;e++)d[e]^=c[e+4&7];if(b){var f=b.words,g=f[0],i=f[1],j=(g<<8|g>>>24)&0xff00ff|(g<<24|g>>>8)&0xff00ff00,k=(i<<8|i>>>24)&0xff00ff|(i<<24|i>>>8)&0xff00ff00,l=j>>>16|0xffff0000&k,m=k<<16|65535&j;d[0]^=j,d[1]^=l,d[2]^=k,d[3]^=m,d[4]^=j,d[5]^=l,d[6]^=k,d[7]^=m;for(var e=0;e<4;e++)h.call(this)}},_doProcessBlock:function(a,b){var d=this._X;h.call(this),c[0]=d[0]^d[5]>>>16^d[3]<<16,c[1]=d[2]^d[7]>>>16^d[5]<<16,c[2]=d[4]^d[1]>>>16^d[7]<<16,c[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;e<4;e++)c[e]=(c[e]<<8|c[e]>>>24)&0xff00ff|(c[e]<<24|c[e]>>>8)&0xff00ff00,a[b+e]^=c[e]},blockSize:4,ivSize:2});function h(){for(var a=this._X,b=this._C,c=0;c<8;c++)e[c]=b[c];b[0]=b[0]+0x4d34d34d+this._b|0,b[1]=b[1]+0xd34d34d3+ +(b[0]>>>0<e[0]>>>0)|0,b[2]=b[2]+0x34d34d34+ +(b[1]>>>0<e[1]>>>0)|0,b[3]=b[3]+0x4d34d34d+ +(b[2]>>>0<e[2]>>>0)|0,b[4]=b[4]+0xd34d34d3+ +(b[3]>>>0<e[3]>>>0)|0,b[5]=b[5]+0x34d34d34+ +(b[4]>>>0<e[4]>>>0)|0,b[6]=b[6]+0x4d34d34d+ +(b[5]>>>0<e[5]>>>0)|0,b[7]=b[7]+0xd34d34d3+ +(b[6]>>>0<e[6]>>>0)|0,this._b=+(b[7]>>>0<e[7]>>>0);for(var c=0;c<8;c++){var d=a[c]+b[c],g=65535&d,h=d>>>16,i=((g*g>>>17)+g*h>>>15)+h*h,j=((0xffff0000&d)*d|0)+((65535&d)*d|0);f[c]=i^j}a[0]=f[0]+(f[7]<<16|f[7]>>>16)+(f[6]<<16|f[6]>>>16)|0,a[1]=f[1]+(f[0]<<8|f[0]>>>24)+f[7]|0,a[2]=f[2]+(f[1]<<16|f[1]>>>16)+(f[0]<<16|f[0]>>>16)|0,a[3]=f[3]+(f[2]<<8|f[2]>>>24)+f[1]|0,a[4]=f[4]+(f[3]<<16|f[3]>>>16)+(f[2]<<16|f[2]>>>16)|0,a[5]=f[5]+(f[4]<<8|f[4]>>>24)+f[3]|0,a[6]=f[6]+(f[5]<<16|f[5]>>>16)+(f[4]<<16|f[4]>>>16)|0,a[7]=f[7]+(f[6]<<8|f[6]>>>24)+f[5]|0}d.RabbitLegacy=a._createHelper(g)}(),a.exports=d.RabbitLegacy},12600:(a,b,c)=>{"use strict";let d,{extractBody:e,mixinBody:f,cloneBody:g,bodyUnusable:h}=c(35381),{Headers:i,fill:j,HeadersList:k,setHeadersGuard:l,getHeadersGuard:m,setHeadersList:n,getHeadersList:o}=c(28665),p=c(84285),q=c(57975),{isValidHTTPToken:r,sameOrigin:s,environmentSettingsObject:t}=c(42425),{forbiddenMethodsSet:u,corsSafeListedMethodsSet:v,referrerPolicy:w,requestRedirect:x,requestMode:y,requestCredentials:z,requestCache:A,requestDuplex:B}=c(19608),{kEnumerableProperty:C,normalizedMethodRecordsBase:D,normalizedMethodRecords:E}=p,{webidl:F}=c(32984),{URLSerializer:G}=c(16537),{kConstruct:H}=c(49176),I=c(34589),{getMaxListeners:J,setMaxListeners:K,defaultMaxListeners:L}=c(78474),M=Symbol("abortController"),N=new FinalizationRegistry(({signal:a,abort:b})=>{a.removeEventListener("abort",b)}),O=new WeakMap;try{d=J(new AbortController().signal)>0}catch{d=!1}function P(a){return function b(){let c=a.deref();if(void 0!==c){N.unregister(b),this.removeEventListener("abort",b),c.abort(this.reason);let a=O.get(c.signal);if(void 0!==a){if(0!==a.size){for(let b of a){let a=b.deref();void 0!==a&&a.abort(this.reason)}a.clear()}O.delete(c.signal)}}}}let Q=!1;class R{#e;#f;#g;#a;constructor(a,b){let c;if(F.util.markAsUncloneable(this),a===H)return;F.argumentLengthCheck(arguments,1,"Request constructor"),a=F.converters.RequestInfo(a),b=F.converters.RequestInit(b);let f=null,g=null;const m=t.settingsObject.baseUrl;let q=null;if("string"==typeof a){let c;this.#f=b.dispatcher;try{c=new URL(a,m)}catch(b){throw TypeError("Failed to parse URL from "+a,{cause:b})}if(c.username||c.password)throw TypeError("Request cannot be constructed from a URL that includes credentials: "+a);f=Y({urlList:[c]}),g="cors"}else I(F.is.Request(a)),f=a.#a,q=a.#e,this.#f=b.dispatcher||a.#f;const w=t.settingsObject.origin;let x="client";if(f.window?.constructor?.name==="EnvironmentSettingsObject"&&s(f.window,w)&&(x=f.window),null!=b.window)throw TypeError(`'window' option '${x}' must be null`);"window"in b&&(x="no-window"),f=Y({method:f.method,headersList:f.headersList,unsafeRequest:f.unsafeRequest,client:t.settingsObject,window:x,priority:f.priority,origin:f.origin,referrer:f.referrer,referrerPolicy:f.referrerPolicy,mode:f.mode,credentials:f.credentials,cache:f.cache,redirect:f.redirect,integrity:f.integrity,keepalive:f.keepalive,reloadNavigation:f.reloadNavigation,historyNavigation:f.historyNavigation,urlList:[...f.urlList]});const y=0!==Object.keys(b).length;if(y&&("navigate"===f.mode&&(f.mode="same-origin"),f.reloadNavigation=!1,f.historyNavigation=!1,f.origin="client",f.referrer="client",f.referrerPolicy="",f.url=f.urlList[f.urlList.length-1],f.urlList=[f.url]),void 0!==b.referrer){const a=b.referrer;if(""===a)f.referrer="no-referrer";else{let b;try{b=new URL(a,m)}catch(b){throw TypeError(`Referrer "${a}" is not a valid URL.`,{cause:b})}"about:"===b.protocol&&"client"===b.hostname||w&&!s(b,t.settingsObject.baseUrl)?f.referrer="client":f.referrer=b}}if(void 0!==b.referrerPolicy&&(f.referrerPolicy=b.referrerPolicy),"navigate"===(c=void 0!==b.mode?b.mode:g))throw F.errors.exception({header:"Request constructor",message:"invalid request mode navigate."});if(null!=c&&(f.mode=c),void 0!==b.credentials&&(f.credentials=b.credentials),void 0!==b.cache&&(f.cache=b.cache),"only-if-cached"===f.cache&&"same-origin"!==f.mode)throw TypeError("'only-if-cached' can be set only with 'same-origin' mode");if(void 0!==b.redirect&&(f.redirect=b.redirect),null!=b.integrity&&(f.integrity=String(b.integrity)),void 0!==b.keepalive&&(f.keepalive=!!b.keepalive),void 0!==b.method){let a=b.method;const c=E[a];if(void 0!==c)f.method=c;else{if(!r(a))throw TypeError(`'${a}' is not a valid HTTP method.`);const b=a.toUpperCase();if(u.has(b))throw TypeError(`'${a}' HTTP method is unsupported.`);a=D[b]??a,f.method=a}Q||"patch"!==f.method||(process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.",{code:"UNDICI-FETCH-patch"}),Q=!0)}void 0!==b.signal&&(q=b.signal),this.#a=f;const z=new AbortController;if(this.#e=z.signal,null!=q)if(q.aborted)z.abort(q.reason);else{this[M]=z;const a=P(new WeakRef(z));d&&J(q)===L&&K(1500,q),p.addAbortListener(q,a),N.register(z,{signal:q,abort:a},a)}if(this.#g=new i(H),n(this.#g,f.headersList),l(this.#g,"request"),"no-cors"===c){if(!v.has(f.method))throw TypeError(`'${f.method} is unsupported in no-cors mode.`);l(this.#g,"request-no-cors")}if(y){const a=o(this.#g),c=void 0!==b.headers?b.headers:new k(a);if(a.clear(),c instanceof k){for(const{name:b,value:d}of c.rawValues())a.append(b,d,!1);a.cookies=c.cookies}else j(this.#g,c)}const A=F.is.Request(a)?a.#a.body:null;if((null!=b.body||null!=A)&&("GET"===f.method||"HEAD"===f.method))throw TypeError("Request with GET/HEAD method cannot have body.");let B=null;if(null!=b.body){const[a,c]=e(b.body,f.keepalive);B=a,c&&!o(this.#g).contains("content-type",!0)&&this.#g.append("content-type",c,!0)}const C=B??A;if(null!=C&&null==C.source){if(null!=B&&null==b.duplex)throw TypeError("RequestInit: duplex option is required when sending a body.");if("same-origin"!==f.mode&&"cors"!==f.mode)throw TypeError('If request is made from ReadableStream, mode should be "same-origin" or "cors"');f.useCORSPreflightFlag=!0}let G=C;if(null==B&&null!=A){if(h(a.#a))throw TypeError("Cannot construct a Request with a Request object that has already been used.");const b=new TransformStream;A.stream.pipeThrough(b),G={source:A.source,length:A.length,stream:b.readable}}this.#a.body=G}get method(){return F.brandCheck(this,R),this.#a.method}get url(){return F.brandCheck(this,R),G(this.#a.url)}get headers(){return F.brandCheck(this,R),this.#g}get destination(){return F.brandCheck(this,R),this.#a.destination}get referrer(){return(F.brandCheck(this,R),"no-referrer"===this.#a.referrer)?"":"client"===this.#a.referrer?"about:client":this.#a.referrer.toString()}get referrerPolicy(){return F.brandCheck(this,R),this.#a.referrerPolicy}get mode(){return F.brandCheck(this,R),this.#a.mode}get credentials(){return F.brandCheck(this,R),this.#a.credentials}get cache(){return F.brandCheck(this,R),this.#a.cache}get redirect(){return F.brandCheck(this,R),this.#a.redirect}get integrity(){return F.brandCheck(this,R),this.#a.integrity}get keepalive(){return F.brandCheck(this,R),this.#a.keepalive}get isReloadNavigation(){return F.brandCheck(this,R),this.#a.reloadNavigation}get isHistoryNavigation(){return F.brandCheck(this,R),this.#a.historyNavigation}get signal(){return F.brandCheck(this,R),this.#e}get body(){return F.brandCheck(this,R),this.#a.body?this.#a.body.stream:null}get bodyUsed(){return F.brandCheck(this,R),!!this.#a.body&&p.isDisturbed(this.#a.body.stream)}get duplex(){return F.brandCheck(this,R),"half"}clone(){if(F.brandCheck(this,R),h(this.#a))throw TypeError("unusable");let a=Z(this.#a),b=new AbortController;if(this.signal.aborted)b.abort(this.signal.reason);else{let a=O.get(this.signal);void 0===a&&(a=new Set,O.set(this.signal,a));let c=new WeakRef(b);a.add(c),p.addAbortListener(b.signal,P(c))}return $(a,this.#f,b.signal,m(this.#g))}[q.inspect.custom](a,b){null===b.depth&&(b.depth=2),b.colors??=!0;let c={method:this.method,url:this.url,headers:this.headers,destination:this.destination,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,isReloadNavigation:this.isReloadNavigation,isHistoryNavigation:this.isHistoryNavigation,signal:this.signal};return`Request ${q.formatWithOptions(b,c)}`}static setRequestSignal(a,b){return a.#e=b,a}static getRequestDispatcher(a){return a.#f}static setRequestDispatcher(a,b){a.#f=b}static setRequestHeaders(a,b){a.#g=b}static getRequestState(a){return a.#a}static setRequestState(a,b){a.#a=b}}let{setRequestSignal:S,getRequestDispatcher:T,setRequestDispatcher:U,setRequestHeaders:V,getRequestState:W,setRequestState:X}=R;function Y(a){return{method:a.method??"GET",localURLsOnly:a.localURLsOnly??!1,unsafeRequest:a.unsafeRequest??!1,body:a.body??null,client:a.client??null,reservedClient:a.reservedClient??null,replacesClientId:a.replacesClientId??"",window:a.window??"client",keepalive:a.keepalive??!1,serviceWorkers:a.serviceWorkers??"all",initiator:a.initiator??"",destination:a.destination??"",priority:a.priority??null,origin:a.origin??"client",policyContainer:a.policyContainer??"client",referrer:a.referrer??"client",referrerPolicy:a.referrerPolicy??"",mode:a.mode??"no-cors",useCORSPreflightFlag:a.useCORSPreflightFlag??!1,credentials:a.credentials??"same-origin",useCredentials:a.useCredentials??!1,cache:a.cache??"default",redirect:a.redirect??"follow",integrity:a.integrity??"",cryptoGraphicsNonceMetadata:a.cryptoGraphicsNonceMetadata??"",parserMetadata:a.parserMetadata??"",reloadNavigation:a.reloadNavigation??!1,historyNavigation:a.historyNavigation??!1,userActivation:a.userActivation??!1,taintedOrigin:a.taintedOrigin??!1,redirectCount:a.redirectCount??0,responseTainting:a.responseTainting??"basic",preventNoCacheCacheControlHeaderModification:a.preventNoCacheCacheControlHeaderModification??!1,done:a.done??!1,timingAllowFailed:a.timingAllowFailed??!1,useURLCredentials:a.useURLCredentials??void 0,traversableForUserPrompts:a.traversableForUserPrompts??"client",urlList:a.urlList,url:a.urlList[0],headersList:a.headersList?new k(a.headersList):new k}}function Z(a){let b=Y({...a,body:null});return null!=a.body&&(b.body=g(a.body)),b}function $(a,b,c,d){let e=new R(H);X(e,a),U(e,b),S(e,c);let f=new i(H);return V(e,f),n(f,a.headersList),l(f,d),e}Reflect.deleteProperty(R,"setRequestSignal"),Reflect.deleteProperty(R,"getRequestDispatcher"),Reflect.deleteProperty(R,"setRequestDispatcher"),Reflect.deleteProperty(R,"setRequestHeaders"),Reflect.deleteProperty(R,"getRequestState"),Reflect.deleteProperty(R,"setRequestState"),f(R,W),Object.defineProperties(R.prototype,{method:C,url:C,headers:C,redirect:C,clone:C,signal:C,duplex:C,destination:C,body:C,bodyUsed:C,isHistoryNavigation:C,isReloadNavigation:C,keepalive:C,integrity:C,cache:C,credentials:C,attribute:C,referrerPolicy:C,referrer:C,mode:C,[Symbol.toStringTag]:{value:"Request",configurable:!0}}),F.is.Request=F.util.MakeTypeAssertion(R),F.converters.RequestInfo=function(a){return"string"==typeof a?F.converters.USVString(a):F.is.Request(a)?a:F.converters.USVString(a)},F.converters.RequestInit=F.dictionaryConverter([{key:"method",converter:F.converters.ByteString},{key:"headers",converter:F.converters.HeadersInit},{key:"body",converter:F.nullableConverter(F.converters.BodyInit)},{key:"referrer",converter:F.converters.USVString},{key:"referrerPolicy",converter:F.converters.DOMString,allowedValues:w},{key:"mode",converter:F.converters.DOMString,allowedValues:y},{key:"credentials",converter:F.converters.DOMString,allowedValues:z},{key:"cache",converter:F.converters.DOMString,allowedValues:A},{key:"redirect",converter:F.converters.DOMString,allowedValues:x},{key:"integrity",converter:F.converters.DOMString},{key:"keepalive",converter:F.converters.boolean},{key:"signal",converter:F.nullableConverter(a=>F.converters.AbortSignal(a,"RequestInit","signal"))},{key:"window",converter:F.converters.any},{key:"duplex",converter:F.converters.DOMString,allowedValues:B},{key:"dispatcher",converter:F.converters.any},{key:"priority",converter:F.converters.DOMString,allowedValues:["high","low","auto"],defaultValue:()=>"auto"}]),a.exports={Request:R,makeRequest:Y,fromInnerRequest:$,cloneRequest:Z,getRequestDispatcher:T,getRequestState:W}},13007:(a,b,c)=>{"use strict";var d,e=c(87692),f=c(94505),g=c(52193),h=c(49014),i=c(55706),j=c(23590),k=c(32659),l=c(76259),m=c(47306),n=c(15816),o=c(86952),p=c(17254),q=c(73472),r=c(18498),s=c(15701),t=Function,u=function(a){try{return t('"use strict"; return ('+a+").constructor;")()}catch(a){}},v=c(77783),w=c(42099),x=function(){throw new k},y=v?function(){try{return arguments.callee,x}catch(a){try{return v(arguments,"callee").get}catch(a){return x}}}():x,z=c(24977)(),A=c(59944),B=c(37992),C=c(16102),D=c(58362),E=c(93065),F={},G="u">typeof Uint8Array&&A?A(Uint8Array):d,H={__proto__:null,"%AggregateError%":"u"<typeof AggregateError?d:AggregateError,"%Array%":Array,"%ArrayBuffer%":"u"<typeof ArrayBuffer?d:ArrayBuffer,"%ArrayIteratorPrototype%":z&&A?A([][Symbol.iterator]()):d,"%AsyncFromSyncIteratorPrototype%":d,"%AsyncFunction%":F,"%AsyncGenerator%":F,"%AsyncGeneratorFunction%":F,"%AsyncIteratorPrototype%":F,"%Atomics%":"u"<typeof Atomics?d:Atomics,"%BigInt%":"u"<typeof BigInt?d:BigInt,"%BigInt64Array%":"u"<typeof BigInt64Array?d:BigInt64Array,"%BigUint64Array%":"u"<typeof BigUint64Array?d:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"u"<typeof DataView?d:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":f,"%eval%":eval,"%EvalError%":g,"%Float16Array%":"u"<typeof Float16Array?d:Float16Array,"%Float32Array%":"u"<typeof Float32Array?d:Float32Array,"%Float64Array%":"u"<typeof Float64Array?d:Float64Array,"%FinalizationRegistry%":"u"<typeof FinalizationRegistry?d:FinalizationRegistry,"%Function%":t,"%GeneratorFunction%":F,"%Int8Array%":"u"<typeof Int8Array?d:Int8Array,"%Int16Array%":"u"<typeof Int16Array?d:Int16Array,"%Int32Array%":"u"<typeof Int32Array?d:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":z&&A?A(A([][Symbol.iterator]())):d,"%JSON%":"object"==typeof JSON?JSON:d,"%Map%":"u"<typeof Map?d:Map,"%MapIteratorPrototype%":"u">typeof Map&&z&&A?A(new Map()[Symbol.iterator]()):d,"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":v,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"u"<typeof Promise?d:Promise,"%Proxy%":"u"<typeof Proxy?d:Proxy,"%RangeError%":h,"%ReferenceError%":i,"%Reflect%":"u"<typeof Reflect?d:Reflect,"%RegExp%":RegExp,"%Set%":"u"<typeof Set?d:Set,"%SetIteratorPrototype%":"u">typeof Set&&z&&A?A(new Set()[Symbol.iterator]()):d,"%SharedArrayBuffer%":"u"<typeof SharedArrayBuffer?d:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":z&&A?A(""[Symbol.iterator]()):d,"%Symbol%":z?Symbol:d,"%SyntaxError%":j,"%ThrowTypeError%":y,"%TypedArray%":G,"%TypeError%":k,"%Uint8Array%":"u"<typeof Uint8Array?d:Uint8Array,"%Uint8ClampedArray%":"u"<typeof Uint8ClampedArray?d:Uint8ClampedArray,"%Uint16Array%":"u"<typeof Uint16Array?d:Uint16Array,"%Uint32Array%":"u"<typeof Uint32Array?d:Uint32Array,"%URIError%":l,"%WeakMap%":"u"<typeof WeakMap?d:WeakMap,"%WeakRef%":"u"<typeof WeakRef?d:WeakRef,"%WeakSet%":"u"<typeof WeakSet?d:WeakSet,"%Function.prototype.call%":E,"%Function.prototype.apply%":D,"%Object.defineProperty%":w,"%Object.getPrototypeOf%":B,"%Math.abs%":m,"%Math.floor%":n,"%Math.max%":o,"%Math.min%":p,"%Math.pow%":q,"%Math.round%":r,"%Math.sign%":s,"%Reflect.getPrototypeOf%":C};if(A)try{null.error}catch(a){var I=A(A(a));H["%Error.prototype%"]=I}var J=function a(b){var c;if("%AsyncFunction%"===b)c=u("async function () {}");else if("%GeneratorFunction%"===b)c=u("function* () {}");else if("%AsyncGeneratorFunction%"===b)c=u("async function* () {}");else if("%AsyncGenerator%"===b){var d=a("%AsyncGeneratorFunction%");d&&(c=d.prototype)}else if("%AsyncIteratorPrototype%"===b){var e=a("%AsyncGenerator%");e&&A&&(c=A(e.prototype))}return H[b]=c,c},K={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},L=c(14165),M=c(46813),N=L.call(E,Array.prototype.concat),O=L.call(D,Array.prototype.splice),P=L.call(E,String.prototype.replace),Q=L.call(E,String.prototype.slice),R=L.call(E,RegExp.prototype.exec),S=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,T=/\\(\\)?/g,U=function(a){var b=Q(a,0,1),c=Q(a,-1);if("%"===b&&"%"!==c)throw new j("invalid intrinsic syntax, expected closing `%`");if("%"===c&&"%"!==b)throw new j("invalid intrinsic syntax, expected opening `%`");var d=[];return P(a,S,function(a,b,c,e){d[d.length]=c?P(e,T,"$1"):b||a}),d},V=function(a,b){var c,d=a;if(M(K,d)&&(d="%"+(c=K[d])[0]+"%"),M(H,d)){var e=H[d];if(e===F&&(e=J(d)),void 0===e&&!b)throw new k("intrinsic "+a+" exists, but is not available. Please file an issue!");return{alias:c,name:d,value:e}}throw new j("intrinsic "+a+" does not exist!")};a.exports=function(a,b){if("string"!=typeof a||0===a.length)throw new k("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof b)throw new k('"allowMissing" argument must be a boolean');if(null===R(/^%?[^%]*%?$/,a))throw new j("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var c=U(a),d=c.length>0?c[0]:"",e=V("%"+d+"%",b),f=e.name,g=e.value,h=!1,i=e.alias;i&&(d=i[0],O(c,N([0,1],i)));for(var l=1,m=!0;l<c.length;l+=1){var n=c[l],o=Q(n,0,1),p=Q(n,-1);if(('"'===o||"'"===o||"`"===o||'"'===p||"'"===p||"`"===p)&&o!==p)throw new j("property names with quotes must have matching quotes");if("constructor"!==n&&m||(h=!0),d+="."+n,M(H,f="%"+d+"%"))g=H[f];else if(null!=g){if(!(n in g)){if(!b)throw new k("base intrinsic for "+a+" exists, but the property is not available.");return}if(v&&l+1>=c.length){var q=v(g,n);g=(m=!!q)&&"get"in q&&!("originalValue"in q.get)?q.get:g[n]}else m=M(g,n),g=g[n];m&&!h&&(H[f]=g)}}return g}},13192:a=>{a.exports=function(a){var b=this.has(a)&&delete this.__data__[a];return this.size-=!!b,b}},13376:(a,b,c)=>{var d=c(24280);a.exports=function(){this.__data__=d?d(null):{},this.size=0}},13862:(a,b,c)=>{var d,e,f,g=c(1932),h=g.URL,i=c(81630),j=c(55591),k=c(27910).Writable,l=c(12412),m=c(86867);d="u">typeof process,e="u">typeof window&&"u">typeof document,f=I(Error.captureStackTrace),d||!e&&f||console.warn("The follow-redirects package should be excluded from browser builds.");var n=!1;try{l(new h(""))}catch(a){n="ERR_INVALID_URL"===a.code}var o=["Authorization","Proxy-Authorization","Cookie"],p=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],q=["abort","aborted","connect","error","socket","timeout"],r=Object.create(null);q.forEach(function(a){r[a]=function(b,c,d){this._redirectable.emit(a,b,c,d)}});var s=F("ERR_INVALID_URL","Invalid URL",TypeError),t=F("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),u=F("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",t),v=F("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),w=F("ERR_STREAM_WRITE_AFTER_END","write after end"),x=k.prototype.destroy||A;function y(a,b){k.call(this),this._sanitizeOptions(a),this._options=a,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],b&&this.on("response",b);var c=this;this._onNativeResponse=function(a){try{c._processResponse(a)}catch(a){c.emit("error",a instanceof t?a:new t({cause:a}))}},this._headerFilter=RegExp("^(?:"+o.concat(a.sensitiveHeaders).map(J).join("|")+")$","i"),this._performRequest()}function z(a){var b={maxRedirects:21,maxBodyLength:0xa00000},c={};return Object.keys(a).forEach(function(d){var e=d+":",f=c[e]=a[d],g=b[d]=Object.create(f);Object.defineProperties(g,{request:{value:function(a,d,f){var g;return(g=a,h&&g instanceof h)?a=D(a):H(a)?a=D(B(a)):(f=d,d=C(a),a={protocol:e}),I(d)&&(f=d,d=null),(d=Object.assign({maxRedirects:b.maxRedirects,maxBodyLength:b.maxBodyLength},a,d)).nativeProtocols=c,H(d.host)||H(d.hostname)||(d.hostname="::1"),l.equal(d.protocol,e,"protocol mismatch"),m("options",d),new y(d,f)},configurable:!0,enumerable:!0,writable:!0},get:{value:function(a,b,c){var d=g.request(a,b,c);return d.end(),d},configurable:!0,enumerable:!0,writable:!0}})}),b}function A(){}function B(a){var b;if(n)b=new h(a);else if(!H((b=C(g.parse(a))).protocol))throw new s({input:a});return b}function C(a){if(/^\[/.test(a.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(a.hostname)||/^\[/.test(a.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(a.host))throw new s({input:a.href||a});return a}function D(a,b){var c=b||{};for(var d of p)c[d]=a[d];return c.hostname.startsWith("[")&&(c.hostname=c.hostname.slice(1,-1)),""!==c.port&&(c.port=Number(c.port)),c.path=c.search?c.pathname+c.search:c.pathname,c}function E(a,b){var c;for(var d in b)a.test(d)&&(c=b[d],delete b[d]);return null==c?void 0:String(c).trim()}function F(a,b,c){function d(c){I(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,c||{}),this.code=a,this.message=this.cause?b+": "+this.cause.message:b}return d.prototype=new(c||Error),Object.defineProperties(d.prototype,{constructor:{value:d,enumerable:!1},name:{value:"Error ["+a+"]",enumerable:!1}}),d}function G(a,b){for(var c of q)a.removeListener(c,r[c]);a.on("error",A),a.destroy(b)}function H(a){return"string"==typeof a||a instanceof String}function I(a){return"function"==typeof a}function J(a){return a.replace(/[\]\\/()*+?.$]/g,"\\$&")}y.prototype=Object.create(k.prototype),y.prototype.abort=function(){G(this._currentRequest),this._currentRequest.abort(),this.emit("abort")},y.prototype.destroy=function(a){return G(this._currentRequest,a),x.call(this,a),this},y.prototype.write=function(a,b,c){var d;if(this._ending)throw new w;if(!H(a)&&!("object"==typeof(d=a)&&"length"in d))throw TypeError("data should be a string, Buffer or Uint8Array");if(I(b)&&(c=b,b=null),0===a.length){c&&c();return}this._requestBodyLength+a.length<=this._options.maxBodyLength?(this._requestBodyLength+=a.length,this._requestBodyBuffers.push({data:a,encoding:b}),this._currentRequest.write(a,b,c)):(this.emit("error",new v),this.abort())},y.prototype.end=function(a,b,c){if(I(a)?(c=a,a=b=null):I(b)&&(c=b,b=null),a){var d=this,e=this._currentRequest;this.write(a,b,function(){d._ended=!0,e.end(null,null,c)}),this._ending=!0}else this._ended=this._ending=!0,this._currentRequest.end(null,null,c)},y.prototype.setHeader=function(a,b){this._options.headers[a]=b,this._currentRequest.setHeader(a,b)},y.prototype.removeHeader=function(a){delete this._options.headers[a],this._currentRequest.removeHeader(a)},y.prototype.setTimeout=function(a,b){var c=this;function d(b){b.setTimeout(a),b.removeListener("timeout",b.destroy),b.addListener("timeout",b.destroy)}function e(b){c._timeout&&clearTimeout(c._timeout),c._timeout=setTimeout(function(){c.emit("timeout"),f()},a),d(b)}function f(){c._timeout&&(clearTimeout(c._timeout),c._timeout=null),c.removeListener("abort",f),c.removeListener("error",f),c.removeListener("response",f),c.removeListener("close",f),b&&c.removeListener("timeout",b),c.socket||c._currentRequest.removeListener("socket",e)}return b&&this.on("timeout",b),this.socket?e(this.socket):this._currentRequest.once("socket",e),this.on("socket",d),this.on("abort",f),this.on("error",f),this.on("response",f),this.on("close",f),this},["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(a){y.prototype[a]=function(b,c){return this._currentRequest[a](b,c)}}),["aborted","connection","socket"].forEach(function(a){Object.defineProperty(y.prototype,a,{get:function(){return this._currentRequest[a]}})}),y.prototype._sanitizeOptions=function(a){if(a.headers||(a.headers={}),a.sensitiveHeaders instanceof Array||(a.sensitiveHeaders=[]),a.host&&(a.hostname||(a.hostname=a.host),delete a.host),!a.pathname&&a.path){var b=a.path.indexOf("?");b<0?a.pathname=a.path:(a.pathname=a.path.substring(0,b),a.search=a.path.substring(b))}},y.prototype._performRequest=function(){var a=this._options.protocol,b=this._options.nativeProtocols[a];if(!b)throw TypeError("Unsupported protocol "+a);if(this._options.agents){var c=a.slice(0,-1);this._options.agent=this._options.agents[c]}var d=this._currentRequest=b.request(this._options,this._onNativeResponse);for(var e of(d._redirectable=this,q))d.on(e,r[e]);if(this._currentUrl=/^\//.test(this._options.path)?g.format(this._options):this._options.path,this._isRedirect){var f=0,h=this,i=this._requestBodyBuffers;!function a(b){if(d===h._currentRequest)if(b)h.emit("error",b);else if(f<i.length){var c=i[f++];d.finished||d.write(c.data,c.encoding,a)}else h._ended&&d.end()}()}},y.prototype._processResponse=function(a){var b,c,d,e,f,i,j=a.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:a.headers,statusCode:j});var k=a.headers.location;if(!k||!1===this._options.followRedirects||j<300||j>=400){a.responseUrl=this._currentUrl,a.redirects=this._redirects,this.emit("response",a),this._requestBodyBuffers=[];return}if(G(this._currentRequest),a.destroy(),++this._redirectCount>this._options.maxRedirects)throw new u;var o=this._options.beforeRedirect;o&&(i=Object.assign({Host:a.req.getHeader("host")},this._options.headers));var p=this._options.method;(301!==j&&302!==j||"POST"!==this._options.method)&&(303!==j||/^(?:GET|HEAD)$/.test(this._options.method))||(this._options.method="GET",this._requestBodyBuffers=[],E(/^content-/i,this._options.headers));var q=E(/^host$/i,this._options.headers),r=B(this._currentUrl),s=q||r.host,t=/^\w+:/.test(k)?this._currentUrl:g.format(Object.assign(r,{host:s})),v=(b=k,c=t,n?new h(b,c):B(g.resolve(c,b)));if(m("redirecting to",v.href),this._isRedirect=!0,D(v,this._options),(v.protocol===r.protocol||"https:"===v.protocol)&&(v.host===s||(d=v.host,e=s,l(H(d)&&H(e)),(f=d.length-e.length-1)>0&&"."===d[f]&&d.endsWith(e)))||E(this._headerFilter,this._options.headers),I(o)){var w={headers:a.headers,statusCode:j},x={url:t,method:p,headers:i};o(this._options,w,x),this._sanitizeOptions(this._options)}this._performRequest()},a.exports=z({http:i,https:j}),a.exports.wrap=z},14030:(a,b,c)=>{var d=c(58130),e=c(29773),f=Object.prototype.propertyIsEnumerable,g=Object.getOwnPropertySymbols;a.exports=g?function(a){return null==a?[]:d(g(a=Object(a)),function(b){return f.call(a,b)})}:e},14040:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});let d=c(66840),e=c(43380),f=c(44510),g=c(70900),h=c(47551);b.default=[d.default,e.default,(0,f.default)(),g.default,h.metadataVocabulary,h.contentVocabulary]},14165:(a,b,c)=>{"use strict";var d=c(43565);a.exports=Function.prototype.bind||d},14340:function(a,b,c){a.exports=function(a){if("function"==typeof ArrayBuffer){var b=a.lib.WordArray,c=b.init;(b.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"u">typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,d=[],e=0;e<b;e++)d[e>>>2]|=a[e]<<24-e%4*8;c.call(this,d,b)}else c.apply(this,arguments)}).prototype=b}return a.lib.WordArray}(c(61345))},14400:(a,b,c)=>{a.exports=c(39409)(Object.keys,Object)},14493:(a,b,c)=>{"use strict";let d,e,f,g;c.r(b),c.d(b,{modelService:()=>de});var h,i,j,k,l={};c.r(l),c.d(l,{hasBrowserEnv:()=>a7,hasStandardBrowserEnv:()=>a9,hasStandardBrowserWebWorkerEnv:()=>ba,navigator:()=>a8,origin:()=>bb});var m=c(77598),n=c(77665),o=c(70690),p=c(46024),q=c(21030),r=c(82964),s=c(89449),t=c(65935),u=c(35247),v=c(97291);let w=(0,r.h)("backend/services/model/provider"),x=/(?:^|-)(?:embedding|image|audio|tts|live|transcribe|robotics|computer-use|deep-research|omni)(?:-|$)/i;function y(a){return null!==a&&"object"==typeof a&&"id"in a&&"string"==typeof a.id}function z(a){let b=Array.isArray(a.supported_parameters)?a.supported_parameters.filter(a=>"string"==typeof a):void 0,c="number"==typeof a.context_length&&Number.isFinite(a.context_length)?a.context_length:void 0,d="number"==typeof a.top_provider?.max_completion_tokens&&Number.isFinite(a.top_provider.max_completion_tokens)?a.top_provider.max_completion_tokens:"number"==typeof a.max_completion_tokens&&Number.isFinite(a.max_completion_tokens)?a.max_completion_tokens:void 0,e=Array.isArray(a.architecture?.input_modalities)?a.architecture.input_modalities.filter(a=>"string"==typeof a):void 0,f=Array.isArray(a.architecture?.output_modalities)?a.architecture.output_modalities.filter(a=>"string"==typeof a):void 0;return{...void 0!==c?{contextWindow:c}:{},...void 0!==d?{maxTokens:d}:{},...void 0!==b?{supportedParameters:b,supportsTools:b.includes("tools")}:{},...void 0!==e?{inputModalities:e,visionInputCapability:e.some(a=>/^(?:image|vision)$/i.test(a))?"supported":"unsupported"}:{visionInputCapability:"unknown"},...void 0!==f?{outputModalities:f}:{}}}async function A(a){if(!a)return[];let b=new v.M4({apiKey:a}),c=await b.models.list({config:{pageSize:1e3}}),d=new Map;for await(let a of c){let b=function(a){if(!a||"object"!=typeof a||"string"!=typeof a.name)return null;let b=a.name.trim().replace(/^models\//i,"");if(!/^gemini-/i.test(b)||x.test(b)||!(Array.isArray(a.supportedActions)?a.supportedActions:Array.isArray(a.supportedGenerationMethods)?a.supportedGenerationMethods:[]).filter(a=>"string"==typeof a).some(a=>"generatecontent"===a.toLowerCase()))return null;let c="string"==typeof a.displayName&&a.displayName.trim()?a.displayName.trim():b,d="string"==typeof a.description&&a.description.trim()?a.description.trim():void 0,e="number"==typeof a.inputTokenLimit&&Number.isFinite(a.inputTokenLimit)?a.inputTokenLimit:void 0,f="number"==typeof a.outputTokenLimit&&Number.isFinite(a.outputTokenLimit)?a.outputTokenLimit:void 0;return{id:b,name:c,...d?{description:d}:{},...void 0!==e?{contextWindow:e}:{},...void 0!==f?{maxTokens:f}:{},visionInputCapability:"unknown"}}(a);b&&!d.has(b.id)&&d.set(b.id,b)}return[...d.values()].sort((a,b)=>a.id.localeCompare(b.id))}async function B(){w.debug("fetchOpenRouterModels: Entering method");let a=await fetch("https://openrouter.ai/api/v1/models?output_modalities=all",{headers:{"Content-Type":"application/json",Accept:"application/json"}});if(!a.ok)throw Error(`OpenRouter API error: ${a.status} ${a.statusText}`);let b=await a.json();return b.data&&Array.isArray(b.data)?b.data.filter(y).map(a=>({id:a.id,name:a.name||a.id,description:a.description,...z(a)})):[]}async function C(a,b){w.debug("fetchOpenAIModels: Entering method");let c=b;c=c.endsWith("/")?`${c}models`:`${c}/models`,w.debug(`Fetching models from: ${c}`);let d={"Content-Type":"application/json"};a&&(b.includes("anthropic")?(d["x-api-key"]=`${a}`,d["anthropic-version"]="2023-06-01"):d.Authorization=`Bearer ${a}`);try{let a={...d};a.Authorization&&(a.Authorization="Bearer ********"),a["x-api-key"]&&(a["x-api-key"]="********"),w.verbose(`fetching models @${c} with ${JSON.stringify(a)}`);let e=await fetch(c,{headers:d});if(!e.ok)throw w.verbose("model list response",e),Error(`API error: ${e.status} ${e.statusText}`);let f=await e.json();if(f.data&&Array.isArray(f.data)){if(w.debug("Successfully parsed response in standard OpenAI format"),b.includes("api.openai.com"))return f.data.filter(y).filter(a=>a.id.includes("gpt")).map(a=>({id:a.id,name:a.id,description:`OpenAI ${a.id}`}));return f.data.filter(y).map(a=>({id:a.id,name:a.name||a.id,description:a.description||`Model ${a.id}`,...z(a)}))}if("list"===f.object&&Array.isArray(f.data))return w.debug("Parsing response in Ollama format"),f.data.filter(y).map(a=>({id:a.id,name:a.id,description:`${a.owned_by?`${a.owned_by}: `:""}${a.id}`}));return w.warn("Could not parse API response in any known format",{data:f}),[]}catch(a){throw w.error("OpenAI-compatible model catalogue request failed",{modelsUrl:c,message:a instanceof Error?a.message:"Unknown provider error"}),a}}async function D(a,b,c,d="openai"){w.debug(`fetchModelsFromProvider: Fetching models for provider: ${a}`);try{if("azure"===a)return[];if("gemini"===a&&"gemini"===d)return await A(c);if("openrouter"===a)return await B();return await C(c,b)}catch{return w.warn("Provider model catalogue request failed",{provider:a,adapter:d}),[]}}var E=c(28461);let F=(0,r.h)("backend/services/model/cache");class G{currentCache(){let a=(0,E.getCurrentWorkspace)(),b=this.caches.get(a);return b||(b=new Map,this.caches.set(a,b)),b}normalizeTarget(a){return"string"==typeof a?{baseUrl:a}:a}getCacheKey(a){let b=this.normalizeTarget(a),c=b.baseUrl.trim().toLowerCase().replace(/\/$/,"");return JSON.stringify([b.profileId??"",b.provider??"",b.adapter??"",c,b.credentialFingerprint??""])}logIdentity(a){let b=this.normalizeTarget(a);return{baseUrl:b.baseUrl,...b.provider?{provider:b.provider}:{},...b.adapter?{adapter:b.adapter}:{},...b.profileId?{profileId:b.profileId}:{}}}isValid(a){return Date.now()-a.timestamp<a.ttl}get(a){let b=this.getCacheKey(a),c=this.currentCache(),d=c.get(b),e=this.logIdentity(a);return d?this.isValid(d)?(F.debug("Cache hit",{...e,modelCount:d.models.length}),d.models):(F.debug("Cache miss - entry expired",{...e,age:Date.now()-d.timestamp}),c.delete(b),null):(F.debug("Cache miss - no entry found",e),null)}set(a,b,c){let d=this.getCacheKey(a),e={models:b,timestamp:Date.now(),ttl:c||this.DEFAULT_TTL};this.currentCache().set(d,e),F.debug("Models cached",{...this.logIdentity(a),modelCount:b.length,ttl:e.ttl})}clear(a){let b=this.getCacheKey(a),c=this.currentCache().delete(b);F.debug("Cache cleared",{...this.logIdentity(a),deleted:c})}clearAll(){let a=this.currentCache(),b=a.size;a.clear(),F.debug("All cache cleared",{entriesCleared:b})}getStats(){let a=this.currentCache(),b=a.size,c=0,d=0;for(let b of a.values())this.isValid(b)?c++:d++;return{totalEntries:b,validEntries:c,expiredEntries:d}}cleanup(){let a=this.currentCache(),b=[];for(let[c,d]of a.entries())this.isValid(d)||b.push(c);b.forEach(b=>a.delete(b)),b.length>0&&F.debug("Cache cleanup completed",{expiredEntriesRemoved:b.length})}constructor(){this.caches=new Map,this.DEFAULT_TTL=3e5}}let H=new G;function I(a,b){return function(){return a.apply(b,arguments)}}let{toString:J}=Object.prototype,{getPrototypeOf:K}=Object,{iterator:L,toStringTag:M}=Symbol,N=(({hasOwnProperty:a})=>(b,c)=>a.call(b,c))(Object.prototype),O=(a,b)=>{let c=a,d=[];for(;null!=c&&c!==Object.prototype&&-1===d.indexOf(c);){if(d.push(c),N(c,b))return!0;c=K(c)}return!1},P=(d=Object.create(null),a=>{let b=J.call(a);return d[b]||(d[b]=b.slice(8,-1).toLowerCase())}),Q=a=>(a=a.toLowerCase(),b=>P(b)===a),R=a=>b=>typeof b===a,{isArray:S}=Array,T=R("undefined");function U(a){return null!==a&&!T(a)&&null!==a.constructor&&!T(a.constructor)&&X(a.constructor.isBuffer)&&a.constructor.isBuffer(a)}let V=Q("ArrayBuffer"),W=R("string"),X=R("function"),Y=R("number"),Z=a=>null!==a&&"object"==typeof a,$=a=>{if(!Z(a))return!1;let b=K(a);return(null===b||b===Object.prototype||null===K(b))&&!O(a,M)&&!O(a,L)},_=Q("Date"),aa=Q("File"),ab=Q("Blob"),ac=Q("FileList"),ad=Q("Set"),ae="u">typeof globalThis?globalThis:"u">typeof self?self:"u">typeof window?window:"u">typeof global?global:{},af=void 0!==ae.FormData?ae.FormData:void 0,ag=Q("URLSearchParams"),[ah,ai,aj,ak]=["ReadableStream","Request","Response","Headers"].map(Q);function al(a,b,{allOwnKeys:c=!1}={}){let d,e;if(null!=a)if("object"!=typeof a&&(a=[a]),S(a))for(d=0,e=a.length;d<e;d++)b.call(null,a[d],d,a);else{let e;if(U(a))return;let f=c?Object.getOwnPropertyNames(a):Object.keys(a),g=f.length;for(d=0;d<g;d++)e=f[d],b.call(null,a[e],e,a)}}function am(a,b){let c;if(U(a))return null;b=b.toLowerCase();let d=Object.keys(a),e=d.length;for(;e-- >0;)if(b===(c=d[e]).toLowerCase())return c;return null}let an="u">typeof globalThis?globalThis:"u">typeof self?self:"u">typeof window?window:global,ao=a=>!T(a)&&a!==an,ap=(e="u">typeof Uint8Array&&K(Uint8Array),a=>e&&a instanceof e),aq=Q("HTMLFormElement"),{propertyIsEnumerable:ar}=Object.prototype,as=Q("RegExp"),at=(a,b)=>{let c=Object.getOwnPropertyDescriptors(a),d={};al(c,(c,e)=>{let f;!1!==(f=b(c,e,a))&&(d[e]=f||c)}),Object.defineProperties(a,d)},au=Q("AsyncFunction"),av=(h="function"==typeof setImmediate,i=X(an.postMessage),h?setImmediate:i?(j=`axios@${Math.random()}`,k=[],an.addEventListener("message",({source:a,data:b})=>{a===an&&b===j&&k.length&&k.shift()()},!1),a=>{k.push(a),an.postMessage(j,"*")}):a=>setTimeout(a)),aw="u">typeof queueMicrotask?queueMicrotask.bind(an):"u">typeof process&&process.nextTick||av,ax=a=>null!=a&&X(a[L]),ay={isArray:S,isArrayBuffer:V,isBuffer:U,isFormData:a=>{if(!a)return!1;if(af&&a instanceof af)return!0;let b=K(a);if(!b||b===Object.prototype||!X(a.append))return!1;let c=P(a);return"formdata"===c||"object"===c&&X(a.toString)&&"[object FormData]"===a.toString()},isArrayBufferView:function(a){return"u">typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(a):a&&a.buffer&&V(a.buffer)},isString:W,isNumber:Y,isBoolean:a=>!0===a||!1===a,isObject:Z,isPlainObject:$,isEmptyObject:a=>{if(!Z(a)||U(a))return!1;try{return 0===Object.keys(a).length&&Object.getPrototypeOf(a)===Object.prototype}catch(a){return!1}},isReadableStream:ah,isRequest:ai,isResponse:aj,isHeaders:ak,isUndefined:T,isDate:_,isFile:aa,isReactNativeBlob:a=>!!(a&&void 0!==a.uri),isReactNative:a=>a&&void 0!==a.getParts,isBlob:ab,isRegExp:as,isFunction:X,isStream:a=>Z(a)&&X(a.pipe),isURLSearchParams:ag,isTypedArray:ap,isFileList:ac,forEach:al,merge:function a(...b){let{caseless:c,skipUndefined:d}=ao(this)&&this||{},e={},f=(b,f)=>{if("__proto__"===f||"constructor"===f||"prototype"===f)return;let g=c&&"string"==typeof f&&am(e,f)||f,h=N(e,g)?e[g]:void 0;$(h)&&$(b)?e[g]=a(h,b):$(b)?e[g]=a({},b):S(b)?e[g]=b.slice():d&&T(b)||(e[g]=b)};for(let a=0,c=b.length;a<c;a++){let c=b[a];if(!c||U(c)||(al(c,f),"object"!=typeof c||S(c)))continue;let d=Object.getOwnPropertySymbols(c);for(let a=0;a<d.length;a++){let b=d[a];ar.call(c,b)&&f(c[b],b)}}return e},extend:(a,b,c,{allOwnKeys:d}={})=>(al(b,(b,d)=>{c&&X(b)?Object.defineProperty(a,d,{__proto__:null,value:I(b,c),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(a,d,{__proto__:null,value:b,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:d}),a),trim:a=>a.trim?a.trim():a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:a=>(65279===a.charCodeAt(0)&&(a=a.slice(1)),a),inherits:(a,b,c,d)=>{a.prototype=Object.create(b.prototype,d),Object.defineProperty(a.prototype,"constructor",{__proto__:null,value:a,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(a,"super",{__proto__:null,value:b.prototype}),c&&Object.assign(a.prototype,c)},toFlatObject:(a,b,c,d)=>{let e,f,g,h={};if(b=b||{},null==a)return b;do{for(f=(e=Object.getOwnPropertyNames(a)).length;f-- >0;)g=e[f],(!d||d(g,a,b))&&!h[g]&&(b[g]=a[g],h[g]=!0);a=!1!==c&&K(a)}while(a&&(!c||c(a,b))&&a!==Object.prototype);return b},kindOf:P,kindOfTest:Q,endsWith:(a,b,c)=>{a=String(a),(void 0===c||c>a.length)&&(c=a.length),c-=b.length;let d=a.indexOf(b,c);return -1!==d&&d===c},toArray:a=>{if(!a)return null;if(S(a))return a;let b=a.length;if(!Y(b))return null;let c=Array(b);for(;b-- >0;)c[b]=a[b];return c},forEachEntry:(a,b)=>{let c,d=(a&&a[L]).call(a);for(;(c=d.next())&&!c.done;){let d=c.value;b.call(a,d[0],d[1])}},matchAll:(a,b)=>{let c,d=[];for(;null!==(c=a.exec(b));)d.push(c);return d},isHTMLForm:aq,hasOwnProperty:N,hasOwnProp:N,hasOwnInPrototypeChain:O,getSafeProp:(a,b)=>null!=a&&O(a,b)?a[b]:void 0,reduceDescriptors:at,freezeMethods:a=>{at(a,(b,c)=>{if(X(a)&&["arguments","caller","callee"].includes(c))return!1;if(X(a[c])){if(b.enumerable=!1,"writable"in b){b.writable=!1;return}b.set||(b.set=()=>{throw Error("Can not rewrite read-only method '"+c+"'")})}})},toObjectSet:(a,b)=>{let c={};return(S(a)?a:String(a).split(b)).forEach(a=>{c[a]=!0}),c},toCamelCase:a=>a.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(a,b,c){return b.toUpperCase()+c}),noop:()=>{},toFiniteNumber:(a,b)=>null!=a&&Number.isFinite(a*=1)?a:b,findKey:am,global:an,isContextDefined:ao,isSpecCompliantForm:function(a){return!!(a&&X(a.append)&&"FormData"===a[M]&&a[L])},toJSONObject:a=>{let b=new WeakSet,c=a=>{if(Z(a)){if(b.has(a))return;if(U(a))return a;if(!("toJSON"in a)){let d;if(b.add(a),ad(a))for(let b of(d=[],a)){let a=c(b);T(a)||d.push(a)}else d=S(a)?[]:{},al(a,(a,b)=>{let e=c(a);T(e)||(d[b]=e)});return b.delete(a),d}}return a};return c(a)},isAsyncFn:au,isThenable:a=>a&&(Z(a)||X(a))&&X(a.then)&&X(a.catch),setImmediate:av,asap:aw,isIterable:ax,isSafeIterable:a=>null!=a&&O(a,L)&&ax(a)},az=ay.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),aA=RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),aB=RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function aC(a,b){return ay.isArray(a)?a.map(a=>aC(a,b)):function(a){let b=0,c=a.length;for(;b<c;){let c=a.charCodeAt(b);if(9!==c&&32!==c)break;b+=1}for(;c>b;){let b=a.charCodeAt(c-1);if(9!==b&&32!==b)break;c-=1}return 0===b&&c===a.length?a:a.slice(b,c)}(String(a).replace(b,""))}function aD(a){let b=Object.create(null);return ay.forEach(a.toJSON(),(a,c)=>{b[c]=aC(a,aB)}),b}let aE=Symbol("internals");function aF(a){return a&&String(a).trim().toLowerCase()}function aG(a){return!1===a||null==a?a:ay.isArray(a)?a.map(aG):aC(String(a),aA)}let aH=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function aI(a){let b=0,c=a.length;for(;b<c;){let c=a.charCodeAt(b);if(9!==c&&32!==c)break;b+=1}for(;c>b;){let b=a.charCodeAt(c-1);if(9!==b&&32!==b)break;c-=1}return 0===b&&c===a.length?a:a.slice(b,c)}function aJ(a,b,c,d,e){if(ay.isFunction(d))return d.call(this,b,c);if(e&&(b=c),ay.isString(b)){if(ay.isString(d))return -1!==b.indexOf(d);if(ay.isRegExp(d))return d.test(b)}}class aK{constructor(a){a&&this.set(a)}set(a,b,c){let d=this;function e(a,b,c){let e=aF(b);if(!e)return;let f=ay.findKey(d,e);f&&void 0!==d[f]&&!0!==c&&(void 0!==c||!1===d[f])||(d[f||b]=aG(a))}let f=(a,b)=>ay.forEach(a,(a,c)=>e(a,c,b));if(ay.isPlainObject(a)||a instanceof this.constructor)f(a,b);else{let d;if(ay.isString(a)&&(a=a.trim())&&(d=a,!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(d.trim()))){var g;let c,d,e,h;f((h={},(g=a)&&g.split("\n").forEach(function(a){e=a.indexOf(":"),c=a.substring(0,e).trim().toLowerCase(),d=a.substring(e+1).trim();let b=ay.hasOwnProp(h,c);!c||b&&ay.hasOwnProp(az,c)||("set-cookie"===c?b?h[c].push(d):h[c]=[d]:h[c]=b?h[c]+", "+d:d)}),h),b)}else if(ay.isObject(a)&&ay.isSafeIterable(a)){let c=Object.create(null),d,e;for(let b of a){if(!ay.isArray(b))throw TypeError("Object iterator must return a key-value pair");e=b[0],ay.hasOwnProp(c,e)?(d=c[e],c[e]=ay.isArray(d)?[...d,b[1]]:[d,b[1]]):c[e]=b[1]}f(c,b)}else null!=a&&e(b,a,c)}return this}get(a,b){if(a=aF(a)){let c=ay.findKey(this,a);if(c){let a=this[c];if(!b)return a;if(!0===b){let b,c=Object.create(null),d=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;for(;b=d.exec(a);)c[b[1]]=b[2];return c}if(ay.isFunction(b))return b.call(this,a,c);if(ay.isRegExp(b))return b.exec(a);throw TypeError("parser must be boolean|regexp|function")}}}has(a,b){if(a=aF(a)){let c=ay.findKey(this,a);return!!(c&&void 0!==this[c]&&(!b||aJ(this,this[c],c,b)))}return!1}delete(a,b){let c=this,d=!1;function e(a){if(a=aF(a)){let e=ay.findKey(c,a);e&&(!b||aJ(c,c[e],e,b))&&(delete c[e],d=!0)}}return ay.isArray(a)?a.forEach(e):e(a),d}clear(a){let b=Object.keys(this),c=b.length,d=!1;for(;c--;){let e=b[c];(!a||aJ(this,this[e],e,a,!0))&&(delete this[e],d=!0)}return d}normalize(a){let b=this,c={};return ay.forEach(this,(d,e)=>{let f=ay.findKey(c,e);if(f){b[f]=aG(d),delete b[e];return}let g=a?e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(a,b,c)=>b.toUpperCase()+c):String(e).trim();g!==e&&delete b[e],b[g]=aG(d),c[g]=!0}),this}concat(...a){return this.constructor.concat(this,...a)}toJSON(a){let b=Object.create(null);return ay.forEach(this,(c,d)=>{null!=c&&!1!==c&&(b[d]=a&&ay.isArray(c)?c.join(", "):c)}),b}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([a,b])=>a+": "+b).join("\n")}getSetCookie(){let a=this.get("set-cookie");return ay.isArray(a)?a:null==a||!1===a?[]:[a]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(a){return a instanceof this?a:new this(a)}static parseParameters(a){return function(a){let b=Object.create(null),c=String(a),d=0,e=!1,f=!1;function g(a){let e=aI(c.slice(d,a)),f=e.indexOf("=");if(f<1)return;let g=aI(e.slice(0,f));if(!aH.test(g))return;let h=g.toLowerCase();if("__proto__"===h||"constructor"===h||"prototype"===h)return;let i=aI(e.slice(f+1));b[h]=function(a){let b=a.length-1;if(b<1||34!==a.charCodeAt(0)||34!==a.charCodeAt(b))return a;let c="";for(let d=1;d<b;d++){let e=a.charCodeAt(d);if(34===e||92===e&&(d+=1)>=b)return a;c+=a[d]}return c}(i)}for(let a=0;a<c.length;a++){let b=c.charCodeAt(a);e?f?f=!1:92===b?f=!0:34===b&&(e=!1):34===b?e=!0:(44===b||59===b)&&(g(a),d=a+1)}return g(c.length),b}(a)}static concat(a,...b){let c=new this(a);return b.forEach(a=>c.set(a)),c}static accessor(a){let b=(this[aE]=this[aE]={accessors:{}}).accessors,c=this.prototype;function d(a){let d=aF(a);if(!b[d]){let e;e=ay.toCamelCase(" "+a),["get","set","has"].forEach(b=>{Object.defineProperty(c,b+e,{__proto__:null,value:function(c,d,e){return this[b].call(this,a,c,d,e)},configurable:!0})}),b[d]=!0}}return ay.isArray(a)?a.forEach(d):d(a),this}}aK.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ay.reduceDescriptors(aK.prototype,({value:a},b)=>{let c=b[0].toUpperCase()+b.slice(1);return{get:()=>a,set(a){this[c]=a}}}),ay.freezeMethods(aK);let aL="[REDACTED ****]";function aM(a){try{return String(a)}catch(a){return""}}class aN extends Error{static from(a,b,c,d,e,f){let g=a.message;!g&&ay.isArray(a.errors)&&a.errors.length&&(g=a.errors.map(a=>{try{return a&&a.message?aM(a.message):aM(a)}catch(a){return""}}).filter(Boolean).join("; ")||a.name||"AggregateError");let h=new aN(g,b||a.code,c,d,e);return Object.defineProperty(h,"cause",{__proto__:null,value:a,writable:!0,enumerable:!1,configurable:!0}),h.name=a.name,null!=a.status&&null==h.status&&(h.status=a.status),f&&Object.assign(h,f),h}constructor(a,b,c,d,e){super(a),Object.defineProperty(this,"message",{__proto__:null,value:a,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,b&&(this.code=b),c&&(this.config=c),d&&(this.request=d),e&&(this.response=e,this.status=e.status)}toJSON(){let a,b,c,d=this.config,e=d&&ay.hasOwnProp(d,"redact")?d.redact:void 0,f=ay.isArray(e)&&e.length>0?(a=new Set(e.map(a=>String(a).toLowerCase())),b=[],(c=d=>{let e;if(null===d||"object"!=typeof d||ay.isBuffer(d))return d;if(-1===b.indexOf(d)){if(d instanceof aK&&(d=d.toJSON()),b.push(d),ay.isArray(d))e=[],d.forEach((a,b)=>{let d=c(a);ay.isUndefined(d)||(e[b]=d)});else{if(!ay.isPlainObject(d)&&function(a){if(ay.hasOwnProp(a,"toJSON"))return!0;let b=Object.getPrototypeOf(a);for(;b&&b!==Object.prototype;){if(ay.hasOwnProp(b,"toJSON"))return!0;b=Object.getPrototypeOf(b)}return!1}(d))return b.pop(),d;for(let[b,f]of(e=Object.create(null),Object.entries(d))){let d=a.has(b.toLowerCase())?aL:c(f);ay.isUndefined(d)||(e[b]=d)}}return b.pop(),e}})(d)):ay.toJSONObject(d);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:f,code:this.code,status:this.status}}}aN.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",aN.ERR_BAD_OPTION="ERR_BAD_OPTION",aN.ECONNABORTED="ECONNABORTED",aN.ETIMEDOUT="ETIMEDOUT",aN.ECONNREFUSED="ECONNREFUSED",aN.ERR_NETWORK="ERR_NETWORK",aN.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",aN.ERR_DEPRECATED="ERR_DEPRECATED",aN.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",aN.ERR_BAD_REQUEST="ERR_BAD_REQUEST",aN.ERR_CANCELED="ERR_CANCELED",aN.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",aN.ERR_INVALID_URL="ERR_INVALID_URL",aN.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";let aO=aN;var aP=c(39879);let aQ={isBufferAvailable:()=>"u">typeof Buffer,from:a=>Buffer.from(a)};function aR(a){return ay.isPlainObject(a)||ay.isArray(a)}function aS(a){return ay.endsWith(a,"[]")?a.slice(0,-2):a}function aT(a,b,c){return a?a.concat(b).map(function(a,b){return a=aS(a),!c&&b?"["+a+"]":a}).join(c?".":""):b}let aU=ay.toFlatObject(ay,{},null,function(a){return/^is[A-Z]/.test(a)}),aV=function(a,b,c){if(!ay.isObject(a))throw TypeError("target must be an object");b=b||new(aP||FormData);let d=(c=ay.toFlatObject(c,{metaTokens:!0,dots:!1,indexes:!1},!1,function(a,b){return!ay.isUndefined(b[a])})).metaTokens,e=c.visitor||n,f=c.dots,g=c.indexes,h=c.Blob||"u">typeof Blob&&Blob,i=void 0===c.maxDepth?100:c.maxDepth,j=h&&ay.isSpecCompliantForm(b),k=[];if(!ay.isFunction(e))throw TypeError("visitor must be a function");function l(a){if(null===a)return"";if(ay.isDate(a))return a.toISOString();if(ay.isBoolean(a))return a.toString();if(!j&&ay.isBlob(a))throw new aO("Blob is not supported. Use a Buffer instead.");if(ay.isArrayBuffer(a)||ay.isTypedArray(a)){if(j&&"function"==typeof h)return new h([a]);if(aQ&&aQ.isBufferAvailable())return aQ.from(a);throw new aO("Blob is not supported. Use a Buffer instead.",aO.ERR_NOT_SUPPORT)}return a}function m(a){if(a>i)throw new aO("Object is too deeply nested ("+a+" levels). Max depth: "+i,aO.ERR_FORM_DATA_DEPTH_EXCEEDED)}function n(a,c,e){let h=a;if(ay.isReactNative(b)&&ay.isReactNativeBlob(a))return b.append(aT(e,c,f),l(a)),!1;if(a&&!e&&"object"==typeof a)if(ay.endsWith(c,"{}"))c=d?c:c.slice(0,-2),a=function(a){if(i===1/0)return JSON.stringify(a);let b=[];return JSON.stringify(a,function(a,c){if(!ay.isObject(c))return c;for(;b.length&&b[b.length-1]!==this;)b.pop();return b.push(c),m(1+b.length-1),c})}(a);else{var j;if(ay.isArray(a)&&(j=a,ay.isArray(j)&&!j.some(aR))||(ay.isFileList(a)||ay.endsWith(c,"[]"))&&(h=ay.toArray(a)))return c=aS(c),h.forEach(function(a,d){ay.isUndefined(a)||null===a||b.append(!0===g?aT([c],d,f):null===g?c:c+"[]",l(a))}),!1}return!!aR(a)||(b.append(aT(e,c,f),l(a)),!1)}let o=Object.assign(aU,{defaultVisitor:n,convertValue:l,isVisitable:aR});if(!ay.isObject(a))throw TypeError("data must be an object");return!function a(c,d,f=0){if(!ay.isUndefined(c)){if(m(f),-1!==k.indexOf(c))throw Error("Circular reference detected in "+d.join("."));k.push(c),ay.forEach(c,function(c,g){!0===(!(ay.isUndefined(c)||null===c)&&e.call(b,c,ay.isString(g)?g.trim():g,d,o))&&a(c,d?d.concat(g):[g],f+1)}),k.pop()}}(a),b};function aW(a){let b={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(a).replace(/[!'()~]|%20/g,function(a){return b[a]})}function aX(a,b){this._pairs=[],a&&aV(a,this,b)}let aY=aX.prototype;function aZ(a){return encodeURIComponent(a).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function a$(a,b,c){let d;if(!b)return a;a=a||"";let e=ay.isFunction(c)?{serialize:c}:c,f=ay.getSafeProp(e,"encode")||aZ,g=ay.getSafeProp(e,"serialize");if(d=g?g(b,e):ay.isURLSearchParams(b)?b.toString():new aX(b,e).toString(f)){let b=a.indexOf("#");-1!==b&&(a=a.slice(0,b)),a+=(-1===a.indexOf("?")?"?":"&")+d}return a}aY.append=function(a,b){this._pairs.push([a,b])},aY.toString=function(a){let b=a?b=>a.call(this,b,aW):aW;return this._pairs.map(function(a){return b(a[0])+"="+b(a[1])},"").join("&")};class a_{constructor(){this.handlers=[]}use(a,b,c){return this.handlers.push({fulfilled:a,rejected:b,synchronous:!!c&&c.synchronous,runWhen:c?c.runWhen:null}),this.handlers.length-1}eject(a){this.handlers[a]&&(this.handlers[a]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(a){ay.forEach(this.handlers,function(b){null!==b&&a(b)})}}let a0={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0};var a1=c(55511);let a2=c(1932).URLSearchParams,a3="abcdefghijklmnopqrstuvwxyz",a4="0123456789",a5={DIGIT:a4,ALPHA:a3,ALPHA_DIGIT:a3+a3.toUpperCase()+a4},a6={isNode:!0,classes:{URLSearchParams:a2,FormData:aP,Blob:"u">typeof Blob&&Blob||null},ALPHABET:a5,generateString:(a=16,b=a5.ALPHA_DIGIT)=>{let c="",{length:d}=b,e=new Uint32Array(a);a1.randomFillSync(e);for(let f=0;f<a;f++)c+=b[e[f]%d];return c},protocols:["http","https","file","data"]},a7="u">typeof window&&"u">typeof document,a8="object"==typeof navigator&&navigator||void 0,a9=a7&&(!a8||0>["ReactNative","NativeScript","NS"].indexOf(a8.product)),ba="u">typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,bb=a7&&window.location.href||"http://localhost",bc={...l,...a6};function bd(a){if(a>100)throw new aO("FormData field is too deeply nested ("+a+" levels). Max depth: 100",aO.ERR_FORM_DATA_DEPTH_EXCEEDED)}let be=function(a){if(ay.isFormData(a)&&ay.isFunction(a.entries)){let b={};return ay.forEachEntry(a,(a,c)=>{!function a(b,c,d,e){bd(e);let f=b[e++];if("__proto__"===f)return!0;let g=Number.isFinite(+f),h=e>=b.length;return(f=!f&&ay.isArray(d)?d.length:f,h)?ay.hasOwnProp(d,f)?d[f]=ay.isArray(d[f])?d[f].concat(c):[d[f],c]:d[f]=c:(ay.hasOwnProp(d,f)&&ay.isObject(d[f])||(d[f]=[]),a(b,c,d[f],e)&&ay.isArray(d[f])&&(d[f]=function(a){let b,c,d={},e=Object.keys(a),f=e.length;for(b=0;b<f;b++)d[c=e[b]]=a[c];return d}(d[f]))),!g}(function(a){let b,c=[],d=/[^.[\]]+|\[([^.[\]]*)]/g;for(;null!==(b=d.exec(a));)bd(c.length),c.push("[]"===b[0]?"":b[1]||b[0]);return c}(a),c,b,0)}),b}return null},bf=(a,b)=>null!=a&&ay.hasOwnProp(a,b)?a[b]:void 0,bg={transitional:a0,adapter:["xhr","http","fetch"],transformRequest:[function(a,b){let c,d=b.getContentType()||"",e=d.indexOf("application/json")>-1,f=ay.isObject(a);if(f&&ay.isHTMLForm(a)&&(a=new FormData(a)),ay.isFormData(a))return e?JSON.stringify(be(a)):a;if(ay.isArrayBuffer(a)||ay.isBuffer(a)||ay.isStream(a)||ay.isFile(a)||ay.isBlob(a)||ay.isReadableStream(a))return a;if(ay.isArrayBufferView(a))return a.buffer;if(ay.isURLSearchParams(a))return b.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),a.toString();if(f){let b=bf(this,"formSerializer");if(d.indexOf("application/x-www-form-urlencoded")>-1)return aV(a,new bc.classes.URLSearchParams,{visitor:function(a,b,c,d){return bc.isNode&&ay.isBuffer(a)?(this.append(b,a.toString("base64")),!1):d.defaultVisitor.apply(this,arguments)},...b}).toString();if((c=ay.isFileList(a))||d.indexOf("multipart/form-data")>-1){let d=bf(this,"env"),e=d&&d.FormData;return aV(c?{"files[]":a}:a,e&&new e,b)}}if(f||e){b.setContentType("application/json",!1);var g=a;if(ay.isString(g))try{return(0,JSON.parse)(g),ay.trim(g)}catch(a){if("SyntaxError"!==a.name)throw a}return(0,JSON.stringify)(g)}return a}],transformResponse:[function(a){let b=bf(this,"transitional")||bg.transitional,c=b&&b.forcedJSONParsing,d=bf(this,"responseType"),e="json"===d;if(ay.isResponse(a)||ay.isReadableStream(a))return a;if(a&&ay.isString(a)&&(c&&!d||e)){let c=b&&b.silentJSONParsing;try{return JSON.parse(a,bf(this,"parseReviver"))}catch(a){if(!c&&e){if("SyntaxError"===a.name)throw aO.from(a,aO.ERR_BAD_RESPONSE,this,null,bf(this,"response"));throw a}}}return a}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:bc.classes.FormData,Blob:bc.classes.Blob},validateStatus:function(a){return a>=200&&a<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};function bh(a,b){let c=this||bg,d=b||c,e=aK.from(d.headers),f=d.data;return ay.forEach(a,function(a){f=a.call(c,f,e.normalize(),b?b.status:void 0)}),e.normalize(),f}function bi(a){return!!(a&&a.__CANCEL__)}ay.forEach(["delete","get","head","post","put","patch","query"],a=>{bg.headers[a]={}});class bj extends aO{constructor(a,b,c){super(null==a?"canceled":a,aO.ERR_CANCELED,b,c),this.name="CanceledError",this.__CANCEL__=!0}}function bk(a,b,c){let d=c.config.validateStatus;!c.status||!d||d(c.status)?a(c):b(new aO("Request failed with status code "+c.status,c.status>=400&&c.status<500?aO.ERR_BAD_REQUEST:aO.ERR_BAD_RESPONSE,c.config,c.request,c))}let bl=/^https?:(?!\/\/)/i,bm=/[\t\n\r]/g;function bn(a,b){if("string"==typeof a){let d=(function(a){let b=0;for(;b<a.length&&32>=a.charCodeAt(b);)b++;return a.slice(b)})(a).replace(bm,"");if(bl.test(d)){var c;let a,e,f;throw new aO(`Invalid URL ${JSON.stringify((f=(-1===(e=(a=d.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${aL}@`)).indexOf("#"))?a:a.slice(0,e)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${aL}`),-1===e?f:`${f}#${!(c=a.slice(e+1))?c:c.replace(/(^|&)([^=&]*=)?[^&]+/g,(a,b,c="")=>`${b}${c}${aL}`)}`))}: missing "//" after protocol`,aO.ERR_INVALID_URL,b)}}}function bo(a,b,c,d){bn(b,d);let e=!("string"==typeof b&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(b));if(a&&(e||!1===c)){bn(a,d);if(!b)return a;let c=a.length;for(;c>0&&47===a.charCodeAt(c-1);)c--;return a.slice(0,c)+"/"+b.replace(/^\/+/,"")}return b}var bp={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function bq(a){return process.env[a.toLowerCase()]||process.env[a.toUpperCase()]||""}var br=c(95314),bs=c(81630),bt=c(55591),bu=c(73496),bv=c(28354),bw=c(33873),bx=c(13862),by=c(74075);let bz="1.19.0";function bA(a){let b=/^([-+\w]{1,25}):(?:\/\/)?/.exec(a);return b&&b[1]||""}let bB=/^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;var bC=c(27910);let bD=["content-type","content-length"];function bE(a,b,c){"content-only"!==c?a.set(b):Object.entries(b||{}).forEach(([b,c])=>{bD.includes(b.toLowerCase())&&a.set(b,c)})}let bF=Symbol("internals");class bG extends bC.Transform{constructor(a){super({readableHighWaterMark:(a=ay.toFlatObject(a,{maxRate:0,chunkSize:65536,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(a,b)=>!ay.isUndefined(b[a]))).chunkSize});const b=this[bF]={timeWindow:a.timeWindow,chunkSize:a.chunkSize,maxRate:a.maxRate,minChunkSize:a.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",a=>{"progress"!==a||b.isCaptured||(b.isCaptured=!0)})}_read(a){let b=this[bF];return b.onReadCallback&&b.onReadCallback(),super._read(a)}_transform(a,b,c){let d=this[bF],e=d.maxRate,f=this.readableHighWaterMark,g=d.timeWindow,h=e/(1e3/g),i=!1!==d.minChunkSize?Math.max(d.minChunkSize,.01*h):0,j=(a,b)=>{let c=Buffer.byteLength(a);d.bytesSeen+=c,d.bytes+=c,d.isCaptured&&this.emit("progress",d.bytesSeen),this.push(a)?process.nextTick(b):d.onReadCallback=()=>{d.onReadCallback=null,process.nextTick(b)}},k=(a,b)=>{let c,k=Buffer.byteLength(a),l=null,m=f,n=0;if(e){let a=Date.now();(!d.ts||(n=a-d.ts)>=g)&&(d.ts=a,c=h-d.bytes,d.bytes=c<0?-c:0,n=0),c=h-d.bytes}if(e){if(c<=0)return setTimeout(()=>{b(null,a)},g-n);c<m&&(m=c)}m&&k>m&&k-m>i&&(l=a.subarray(m),a=a.subarray(0,m)),j(a,l?()=>{process.nextTick(b,null,l)}:b)};k(a,function a(b,d){if(b)return c(b);d?k(d,a):c(null)})}}var bH=c(94735);let{asyncIterator:bI}=Symbol,bJ=async function*(a){a.stream?yield*a.stream():a.arrayBuffer?yield await a.arrayBuffer():a[bI]?yield*a[bI]():yield a},bK=bc.ALPHABET.ALPHA_DIGIT+"-_",bL="function"==typeof TextEncoder?new TextEncoder:new bv.TextEncoder,bM=bL.encode("\r\n");class bN{constructor(a,b){const{escapeName:c}=this.constructor,d=ay.isString(b);let e=`Content-Disposition: form-data; name="${c(a)}"${!d&&b.name?`; filename="${c(b.name)}"`:""}\r
54
54
  `;if(d)b=bL.encode(String(b).replace(/\r?\n|\r\n?/g,"\r\n"));else{const a=String(b.type||"application/octet-stream").replace(/[\r\n]/g,"");e+=`Content-Type: ${a}\r
55
55
  `}this.headers=bL.encode(e+"\r\n"),this.contentLength=d?b.byteLength:b.size,this.size=this.headers.byteLength+this.contentLength+2,this.name=a,this.value=b}async *encode(){yield this.headers;let{value:a}=this;ay.isTypedArray(a)?yield a:yield*bJ(a),yield bM}static escapeName(a){return String(a).replace(/[\r\n"]/g,a=>({"\r":"%0D","\n":"%0A",'"':"%22"})[a])}}class bO extends bC.Transform{__transform(a,b,c){this.push(a),c()}_transform(a,b,c){if(0!==a.length&&(this._transform=this.__transform,120!==a[0])){let a=Buffer.alloc(2);a[0]=120,a[1]=156,this.push(a,b)}this.__transform(a,b,c)}}class bP{constructor(){this.sessions=Object.create(null)}getSession(a,b){let c,d;b=Object.assign({sessionTimeout:1e3},b);let e=this.sessions[a];if(e){let a=e.length;for(let c=0;c<a;c++){let[a,d]=e[c];if(!a.destroyed&&!a.closed&&bv.isDeepStrictEqual(d,b))return a}}let f=bu.connect(a,b),g=()=>{if(c)return;c=!0,d&&(clearTimeout(d),d=null);let b=e,g=b.length,h=g;for(;h--;)if(b[h][0]===f){1===g?delete this.sessions[a]:b.splice(h,1),f.closed||f.close();return}},h=f.request,{sessionTimeout:i}=b;if(null!=i){let a=0;f.request=function(){let b=h.apply(this,arguments);return a++,d&&(clearTimeout(d),d=null),b.once("close",()=>{--a||(d=setTimeout(()=>{d=null,g()},i))}),b}}f.once("close",g);let j=[f,b];return e?e.push(j):e=this.sessions[a]=[j],f}}let bQ=new Set(["localhost","0.0.0.0"]),bR=a=>{let b=a.split(".");return 4===b.length&&"127"===b[0]&&b.every(a=>/^\d+$/.test(a)&&Number(a)>=0&&255>=Number(a))},bS=a=>{if(/^0[xX][0-9a-fA-F]+$/.test(a)){let b=parseInt(a.slice(2),16);return Number.isFinite(b)?b:null}if(a.length>1&&/^0[0-7]+$/.test(a)){let b=parseInt(a,8);return Number.isFinite(b)?b:null}if(a.length>1&&/^0[0-9]+$/.test(a))return null;if(/^[0-9]+$/.test(a)){let b=parseInt(a,10);return Number.isFinite(b)?b:null}return null},bT=a=>/^0{1,4}$/.test(a),bU=a=>!!a&&(!!(bQ.has(a)||bR(a)||(a=>{if("::"===a)return!0;let b=a.indexOf("::");if(-1!==b){if(b!==a.lastIndexOf("::"))return!1;let c=a.slice(0,b),d=a.slice(b+2),e=c?c.split(":"):[],f=d?d.split(":"):[];return e.length+f.length<8&&e.every(bT)&&f.every(bT)}let c=a.split(":");return 8===c.length&&c.every(bT)})(a))||(a=>{if("::1"===a)return!0;let b=a.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(b)return bR(b[1]);let c=a.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(c){let a=parseInt(c[1],16);return a>=32512&&a<=32767}let d=a.split(":");if(8===d.length){for(let a=0;a<7;a++)if(!/^0+$/.test(d[a]))return!1;return/^0*1$/.test(d[7])}return!1})(a)),bV={http:80,https:443,ws:80,wss:443,ftp:21},bW=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i,bX=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i,bY=a=>{if(!a)return a;"["===a.charAt(0)&&"]"===a.charAt(a.length-1)&&(a=a.slice(1,-1));let b=a.replace(/\.+$/,""),c=(a=>{if("string"!=typeof a||!a||-1!==a.indexOf(":"))return a;let b=a;if("["===b.charAt(0)&&"]"===b.charAt(b.length-1)&&(b=b.slice(1,-1)),b=b.replace(/\.+$/,""),!/^[0-9.xXa-fA-F]+$/.test(b))return a;let c=b.split(".");if(c.some(a=>""===a))return a;if(4===c.length){let b=c.map(bS);return b.some(a=>null===a||a<0||a>255)?a:b.join(".")}if(c.length>4||1===c.length)return a;let d=c.slice(0,-1),e=c[c.length-1],f=4-d.length,g=bS(e);if(null===g)return a;let h=(1<<8*f)-1;if(g<0||g>h)return a;let i=Array(f).fill(0);for(let a=f-1,b=g;a>=0;a--,b>>=8)i[a]=255&b;let j=d.map(bS);return j.some(a=>null===a||a<0||a>255)?a:[...j,...i].join(".")})(b);if(c!==b)return c;if("string"!=typeof b||-1===b.indexOf(":"))return b;let d=b.match(bW);if(d)return d[1];let e=b.match(bX);if(e){let a=parseInt(e[1],16),b=parseInt(e[2],16);return`${a>>8}.${255&a}.${b>>8}.${255&b}`}return b},bZ=function(a,b){let c,d=Array(a=a||10),e=Array(a),f=0,g=0;return b=void 0!==b?b:1e3,function(h){let i=Date.now(),j=e[g];c||(c=i),d[f]=h,e[f]=i;let k=g,l=0;for(;k!==f;)l+=d[k++],k%=a;if((f=(f+1)%a)===g&&(g=(g+1)%a),i-c<b)return;let m=j&&i-j;return m?Math.round(1e3*l/m):void 0}},b$=function(a,b){let c,d,e=0,f=1e3/b,g=(b,f=Date.now())=>{e=f,c=null,d&&(clearTimeout(d),d=null),a(...b)};return[(...a)=>{let b=Date.now(),h=b-e;h>=f?g(a,b):(c=a,d||(d=setTimeout(()=>{d=null,g(c)},f-h)))},()=>c&&g(c)]},b_=(a,b,c=3)=>{let d=0,e=bZ(50,250);return b$(c=>{if(!c||"number"!=typeof c.loaded)return;let f=c.loaded,g=c.lengthComputable?c.total:void 0,h=Math.max(0,null!=g?Math.min(f,g):f),i=Math.max(0,h-d),j=e(i);d=Math.max(d,h),a({loaded:h,total:g,progress:g?h/g:void 0,bytes:i,rate:j||void 0,estimated:j&&g?(g-h)/j:void 0,event:c,lengthComputable:null!=g,[b?"download":"upload"]:!0})},c)},b0=(a,b)=>{let c=null!=a;return[d=>b[0]({lengthComputable:c,total:a,loaded:d}),b[1]]},b1=(a,b=ay.asap)=>(...c)=>b(()=>a(...c)),b2=a=>a>=48&&a<=57||a>=65&&a<=70||a>=97&&a<=102,b3=(a,b,c)=>b+2<c&&b2(a.charCodeAt(b+1))&&b2(a.charCodeAt(b+2)),b4=a=>a<=57?a-48:(223&a)-55,b5=a=>a>=65&&a<=90||a>=97&&a<=122||a>=48&&a<=57||43===a||47===a||45===a||95===a,b6=a=>9===a||10===a||12===a||13===a||32===a,b7=a=>{let b=a.length,c=0;return b>0&&61===a.charCodeAt(b-1)&&(c++,b>1&&61===a.charCodeAt(b-2)&&c++),Math.floor((b-c)*3/4)},b8=a=>{var b;let c,d,e=a.length,f=0,g=0,h=!1;for(let b=0;b<e;b++){let c=a.charCodeAt(b);if(37===c&&b3(a,b,e)&&(c=16*b4(a.charCodeAt(b+1))+b4(a.charCodeAt(b+2)),b+=2),!b6(c)){if(61===c){g++;continue}if(!b5(c)||g>0){h=!0;continue}f++}}return h||g>2||g>0&&(f+g)%4!=0||f%4==1?b7(a):(c=Math.floor((b=f)/4),3*c+(2==(d=b%4)?1:2*(3===d)))},b9=(a,b)=>{if(!a||"string"!=typeof a||!a.startsWith("data:"))return 0;let c=a.indexOf(",");if(c<0)return 0;let d=a.slice(5,c),e=a.slice(c+1);if(/;base64/i.test(d))return b(e);let f=0;for(let a=0,b=e.length;a<b;a++){let c=e.charCodeAt(a);if(37===c&&b3(e,a,b))f+=1,a+=2;else if(c<128)f+=1;else if(c<2048)f+=2;else if(c>=55296&&c<=56319&&a+1<b){let b=e.charCodeAt(a+1);b>=56320&&b<=57343?(f+=4,a++):f+=3}else f+=3}return f},ca={flush:by.constants.Z_SYNC_FLUSH,finishFlush:by.constants.Z_SYNC_FLUSH},cb={flush:by.constants.BROTLI_OPERATION_FLUSH,finishFlush:by.constants.BROTLI_OPERATION_FLUSH},cc={flush:by.constants.ZSTD_e_flush,finishFlush:by.constants.ZSTD_e_flush},cd=ay.isFunction(by.createBrotliDecompress),ce=ay.isFunction(by.createZstdDecompress),cf="gzip, compress, deflate"+(cd?", br":""),cg=cf+(ce?", zstd":""),ch="u">typeof process&&process.nextTick?process.nextTick.bind(process):ay.asap,{http:ci,https:cj}=bx,ck=/https:?/,cl=Symbol("axios.http.socketListener"),cm=Symbol("axios.http.currentReq"),cn=Symbol("axios.http.installedTunnel"),co=new Map,cp=new WeakMap,cq={22:21,24:5},cr=bc.protocols.map(a=>a+":"),cs=a=>{if(!ay.isString(a))return a;try{return decodeURIComponent(a)}catch(b){return a}},ct=(a,[b,c])=>(a.on("end",c).on("error",c),b),cu=new bP;function cv(a,b,c){a.beforeRedirects.proxy&&a.beforeRedirects.proxy(a),a.beforeRedirects.auth&&a.beforeRedirects.auth(a),a.beforeRedirects.sensitiveHeaders&&a.beforeRedirects.sensitiveHeaders(a,c),a.beforeRedirects.config&&a.beforeRedirects.config(a,b,c)}let cw="u">typeof process&&"process"===ay.kindOf(process),cx=(a,b)=>(({address:a,family:b})=>{if(!ay.isString(a))throw TypeError("address must be a string");return{address:a,family:b||(0>a.indexOf(".")?6:4)}})(ay.isObject(a)?a:{address:a,family:b}),cy={request(a,b){let c=a.protocol+"//"+a.hostname+":"+(a.port||("https:"===a.protocol?443:80)),{http2Options:d,headers:e}=a,f=cu.getSession(c,d),{HTTP2_HEADER_SCHEME:g,HTTP2_HEADER_METHOD:h,HTTP2_HEADER_PATH:i,HTTP2_HEADER_STATUS:j}=bu.constants,k={[g]:a.protocol.replace(":",""),[h]:a.method,[i]:a.path};ay.forEach(e,(a,b)=>{":"!==b.charAt(0)&&(k[b]=a)});let l=f.request(k);return l.once("response",a=>{let c=(a=Object.assign({},a))[j];delete a[j],l.headers=a,l.statusCode=+c,b(l)}),l}},cz=cw&&function(a){let b;return b=async function(b,c,d){let e,f,g,h,i,j,k,l,m=ay.getSafeProp(a,"transitional")||a0,n=ay.getSafeProp(a,"data"),o=ay.getSafeProp(a,"lookup"),p=ay.getSafeProp(a,"family"),q=ay.getSafeProp(a,"httpVersion");void 0===q&&(q=1);let r=ay.getSafeProp(a,"http2Options"),s=ay.getSafeProp(a,"httpAgent"),t=ay.getSafeProp(a,"httpsAgent"),u=ay.getSafeProp(a,"proxy"),v=ay.getSafeProp(a,"responseType"),w=ay.getSafeProp(a,"responseEncoding"),x=ay.getSafeProp(a,"socketPath"),y=ay.getSafeProp(a,"method").toUpperCase(),z=ay.getSafeProp(a,"maxRedirects"),A=ay.getSafeProp(a,"maxBodyLength"),B=ay.getSafeProp(a,"maxContentLength"),C=ay.getSafeProp(a,"decompress"),D=!1;if(Number.isNaN(q*=1))throw TypeError(`Invalid protocol version: '${a.httpVersion}' is not a number`);if(1!==q&&2!==q)throw TypeError(`Unsupported protocol version '${q}'`);let E=2===q;if(o){let a,b,c=(a=o,b=a=>ay.isArray(a)?a:[a],ay.isAsyncFn(a)?function(...c){let d=c.pop();a.apply(this,c).then(a=>{try{b?d(null,...b(a)):d(null,a)}catch(a){d(a)}},d)}:a);o=(a,b,d)=>{c(a,b,(a,c,e)=>{if(a)return d(a);let f=ay.isArray(c)?c.map(a=>cx(a)):[cx(c,e)];b.all?d(a,f):d(a,f[0].address,f[0].family)})}}let F=new bH.EventEmitter;function G(b){try{F.emit("abort",!b||b.type?new bj(null,a,f):b)}catch(a){}}function H(){g&&(clearTimeout(g),g=null)}F.once("abort",c);let I=()=>{H(),a.cancelToken&&a.cancelToken.unsubscribe(G),a.signal&&a.signal.removeEventListener("abort",G),F.removeAllListeners()};(a.cancelToken||a.signal)&&(a.cancelToken&&a.cancelToken.subscribe(G),a.signal&&(a.signal.aborted?G():a.signal.addEventListener("abort",G))),d((a,b)=>{if(e=!0,H(),b){D=!0,I();return}let{data:c}=a;if(c instanceof bC.Readable||c instanceof bC.Duplex){let a=bC.finished(c,()=>{a(),I()})}else I()});let J=bo(ay.getSafeProp(a,"baseURL"),ay.getSafeProp(a,"url"),ay.getSafeProp(a,"allowAbsoluteUrls"),a),K=new URL(J,x?"http://localhost":bc.hasBrowserEnv?bc.origin:void 0),L=K.protocol||cr[0];if("data:"===L){let d;if(B>-1&&b9(String(ay.getSafeProp(a,"url")||J||""),b7)>B)return c(new aO("maxContentLength size of "+B+" exceeded",aO.ERR_BAD_RESPONSE,a));if("GET"!==y)return bk(b,c,{status:405,statusText:"method not allowed",headers:{},config:a});try{d=function(a,b,c){let d=c&&c.Blob||bc.classes.Blob,e=bA(a);if(void 0===b&&d&&(b=!0),"data"===e){a=e.length?a.slice(e.length+1):a;let c=bB.exec(a);if(!c)throw new aO("Invalid URL",aO.ERR_INVALID_URL);let f=c[1],g=c[2],h=c[3]?"base64":"utf8",i=c[4],j="";f?j=g?f+g:f:g&&(j="text/plain"+g);let k="base64"===h?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),h);if(b){if(!d)throw new aO("Blob is not supported",aO.ERR_NOT_SUPPORT);return new d([k],{type:j})}return k}throw new aO("Unsupported protocol "+e,aO.ERR_NOT_SUPPORT)}(ay.getSafeProp(a,"url"),"blob"===v,{Blob:a.env&&a.env.Blob})}catch(b){throw aO.from(b,aO.ERR_BAD_REQUEST,a)}return"text"===v?(d=d.toString(w),w&&"utf8"!==w||(d=ay.stripBOM(d))):"stream"===v&&(d=bC.Readable.from(d)),bk(b,c,{data:d,status:200,statusText:"OK",headers:new aK,config:a})}if(-1===cr.indexOf(L))return c(new aO("Unsupported protocol "+L,aO.ERR_BAD_REQUEST,a));let M=aK.from(a.headers).normalize();M.set("User-Agent","axios/"+bz,!1);let{onUploadProgress:N,onDownloadProgress:O}=a,P=a.maxRate;if(ay.isSpecCompliantForm(n)){let a=M.getContentType(/boundary=([-_\w\d]{10,70})/i);n=((a,b,c)=>{let{tag:d="form-data-boundary",size:e=25,boundary:f=d+"-"+bc.generateString(e,bK)}=c||{};if(!ay.isFormData(a))throw TypeError("FormData instance required");if(f.length<1||f.length>70)throw Error("boundary must be 1-70 characters long");let g=bL.encode("--"+f+"\r\n"),h=bL.encode("--"+f+"--\r\n"),i=h.byteLength,j=Array.from(a.entries()).map(([a,b])=>{let c=new bN(a,b);return i+=c.size,c});i+=g.byteLength*j.length;let k={"Content-Type":`multipart/form-data; boundary=${f}`};return Number.isFinite(i=ay.toFiniteNumber(i))&&(k["Content-Length"]=i),b&&b(k),bC.Readable.from(async function*(){for(let a of j)yield g,yield*a.encode();yield h}())})(n,a=>{M.set(a)},{tag:`axios-${bz}-boundary`,boundary:a&&a[1]||void 0})}else if(ay.isFormData(n)&&ay.isFunction(n.getHeaders)&&n.getHeaders!==Object.prototype.getHeaders){if(bE(M,n.getHeaders(),ay.getSafeProp(a,"formDataHeaderPolicy")),!M.hasContentLength())try{let a=await bv.promisify(n.getLength).call(n);Number.isFinite(a)&&a>=0&&M.setContentLength(a)}catch(a){}}else if(ay.isBlob(n)||ay.isFile(n))n.size&&M.setContentType(n.type||"application/octet-stream"),M.setContentLength(n.size||0),n=bC.Readable.from(bJ(n));else if(n&&!ay.isStream(n)){if(Buffer.isBuffer(n));else if(ay.isArrayBuffer(n))n=Buffer.from(new Uint8Array(n));else{if(!ay.isString(n))return c(new aO("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",aO.ERR_BAD_REQUEST,a));n=Buffer.from(n,"utf-8")}if(M.setContentLength(n.length,!1),A>-1&&n.length>A)return c(new aO("Request body larger than maxBodyLength limit",aO.ERR_BAD_REQUEST,a))}let Q=ay.toFiniteNumber(M.getContentLength());ay.isArray(P)?(j=P[0],k=P[1]):j=k=P,n&&(N||j)&&(ay.isStream(n)||(n=bC.Readable.from(n,{objectMode:!1})),n=bC.pipeline([n,new bG({maxRate:ay.toFiniteNumber(j)})],ay.noop),N&&n.on("progress",ct(n,b0(Q,b_(b1(N,ch),!1,3)))));let R=ay.getSafeProp(a,"auth");R&&(l=(ay.getSafeProp(R,"username")||"")+":"+(ay.getSafeProp(R,"password")||"")),!l&&(K.username||K.password)&&(l=cs(K.username)+":"+cs(K.password)),l&&M.delete("authorization");try{h=a$(K.pathname+K.search,ay.getSafeProp(a,"params"),ay.getSafeProp(a,"paramsSerializer")).replace(/^\?/,"")}catch(b){return c(aO.from(b,aO.ERR_BAD_REQUEST,a,null,null,{url:ay.getSafeProp(a,"url"),exists:!0}))}M.set("Accept-Encoding",ay.hasOwnProp(m,"advertiseZstdAcceptEncoding")&&!0===m.advertiseZstdAcceptEncoding?cg:cf,!1);let S=Object.assign(Object.create(null),{path:h,method:y,headers:aD(M),agents:{http:s,https:t},auth:l,protocol:L,family:p,beforeRedirect:cv,beforeRedirects:Object.create(null),http2Options:r});if(ay.isUndefined(o)||(S.lookup=o),x){if("string"!=typeof x)return c(new aO("socketPath must be a string",aO.ERR_BAD_OPTION_VALUE,a));let b=ay.getSafeProp(a,"allowedSocketPaths");if(null!=b){let d=Array.isArray(b)?b:[b],e=(0,bw.resolve)(x);if(!d.some(a=>"string"==typeof a&&(0,bw.resolve)(a)===e))return c(new aO(`socketPath "${x}" is not permitted by allowedSocketPaths`,aO.ERR_BAD_OPTION_VALUE,a))}S.socketPath=x}else S.hostname=K.hostname.startsWith("[")?K.hostname.slice(1,-1):K.hostname,S.port=K.port,function a(b,c,d,e,f,g){let h=c,i=ck.test(b.protocol)?f||bt.globalAgent:g||bs.globalAgent;if(!h&&!1!==h&&!function(a,b=process.versions&&process.versions.node){if(!function(a=process.versions&&process.versions.node){if(!a)return!1;let[b,c]=a.split(".").map(a=>Number(a));return!!Number.isInteger(b)&&!!Number.isInteger(c)&&(b>24||null!=cq[b]&&c>=cq[b])}(b))return!1;let c=a&&a.options;return!!(c&&ay.hasOwnProp(c,"proxyEnv")&&null!=c.proxyEnv)}(i)){let a=function(a){var b,c,d,e=("string"==typeof a?function(a){try{return new URL(a)}catch{return null}}(a):a)||{},f=e.protocol,g=e.host,h=e.port;if("string"!=typeof g||!g||"string"!=typeof f||(f=f.split(":",1)[0],b=g=g.replace(/:\d*$/,""),c=h=parseInt(h)||bp[f]||0,!(!(d=bq("no_proxy").toLowerCase())||"*"!==d&&d.split(/[,\s]/).every(function(a){if(!a)return!0;var d=a.match(/^(.+):(\d+)$/),e=d?d[1]:a,f=d?parseInt(d[2]):0;return!!f&&f!==c||(/^[.*]/.test(e)?("*"===e.charAt(0)&&(e=e.slice(1)),!b.endsWith(e)):b!==e)}))))return"";var i=bq(f+"_proxy")||bq("all_proxy");return i&&-1===i.indexOf("://")&&(i=f+"://"+i),i}(d);a&&!function(a){let b;try{b=new URL(a)}catch(a){return!1}let c=(process.env.no_proxy||process.env.NO_PROXY||"").toLowerCase();if(!c)return!1;if("*"===c)return!0;let d=Number.parseInt(b.port,10)||bV[b.protocol.split(":",1)[0]]||0,e=bY(b.hostname.toLowerCase());return c.split(/[\s,]+/).some(a=>{if(!a)return!1;if("*"===a)return!0;let[b,c]=(a=>{let b=a,c=0;if("["===b.charAt(0)){let a=b.indexOf("]");if(-1!==a){let d=b.slice(1,a),e=b.slice(a+1);return":"===e.charAt(0)&&/^\d+$/.test(e.slice(1))&&(c=Number.parseInt(e.slice(1),10)),[d,c]}}let d=b.indexOf(":"),e=b.lastIndexOf(":");return -1!==d&&d===e&&/^\d+$/.test(b.slice(e+1))&&(c=Number.parseInt(b.slice(e+1),10),b=b.slice(0,e)),[b,c]})(a);return!!(b=bY(b))&&(!c||c===d)&&(("*"===b.charAt(0)&&(b=b.slice(1)),"."===b.charAt(0))?e.endsWith(b):e===b||bU(e)&&bU(b))})}(d)&&(h=new URL(a))}if(e&&b.headers)for(let a of Object.keys(b.headers))"proxy-authorization"===a.toLowerCase()&&delete b.headers[a];if(e&&b.agent&&b.agent[cn]&&(b.agent=void 0),h){let a=h instanceof URL,c=b=>a||ay.hasOwnProp(h,b)?h[b]:void 0,e=c("username"),g=c("password"),i=ay.hasOwnProp(h,"auth")?h.auth:void 0;if(e&&(i=(e||"")+":"+(g||"")),i){let a="object"==typeof i,b=a&&ay.hasOwnProp(i,"username")?i.username:void 0,c=a&&ay.hasOwnProp(i,"password")?i.password:void 0;if(b||c)i=(b||"")+":"+(c||"");else if(a)throw new aO("Invalid proxy authorization",aO.ERR_BAD_OPTION,{proxy:h})}if(ck.test(b.protocol)){if(!(f instanceof br)){let a=c("hostname")||c("host"),d=c("port"),e=c("protocol"),g=e?e.includes(":")?e:`${e}:`:"http:",h=a&&a.includes(":")&&!a.startsWith("[")?`[${a}]`:a,j=new URL(`${g}//${h}${d?":"+d:""}`),k={protocol:j.protocol,hostname:j.hostname.replace(/^\[|\]$/g,""),port:j.port,auth:i&&"string"==typeof i?i:void 0};"https:"===j.protocol&&(k.ALPNProtocols=["http/1.1"]);let l=function(a,b){let c=a.protocol+"//"+a.hostname+":"+(a.port||"")+"#"+(a.auth||""),d=b?cp.get(b)||cp.set(b,new Map).get(b):co,e=d.get(c);if(e)return e;if(e=new br(b&&b.options?{...b.options,...a}:a),b&&b.options){let a={...b.options},c=e.callback;e.callback=function(b,d){return c.call(this,b,{...a,...d})}}return e[cn]=!0,d.set(c,e),e}(k,f);b.agent=l,b.agents&&(b.agents.https=l)}}else{if(i){let a=Buffer.from(i,"utf8").toString("base64");b.headers["Proxy-Authorization"]="Basic "+a}let a=!1;for(let c of Object.keys(b.headers))if("host"===c.toLowerCase()){a=!0;break}a||(b.headers.host=b.hostname+(b.port?":"+b.port:""));let e=c("hostname")||c("host");b.hostname=e,b.host=e,b.port=c("port"),b.path=d;let f=c("protocol");f&&(b.protocol=f.includes(":")?f:`${f}:`)}}b.beforeRedirects.proxy=function(b){a(b,c,b.href,!0,f,g)}}(S,u,L+"//"+K.hostname+(K.port?":"+K.port:"")+S.path,!1,t,s);let T=!1,U=!1,V=ck.test(S.protocol);if(null==S.agent&&(S.agent=V?t:s),E)i=cy;else{let b=ay.getSafeProp(a,"transport");if(b)i=b;else if(0===z)i=V?bt:bs,T=!0;else{U=!0,S.sensitiveHeaders=[],z&&(S.maxRedirects=z);let b=ay.getSafeProp(a,"beforeRedirect");if(b&&(S.beforeRedirects.config=b),l){let a=K.origin,b=l;S.beforeRedirects.auth=function(c){try{new URL(c.href).origin===a&&(c.auth=b)}catch(a){}}}let d=ay.getSafeProp(a,"sensitiveHeaders");if(null!=d){if(!ay.isArray(d))return c(new aO("sensitiveHeaders must be an array of strings",aO.ERR_BAD_OPTION_VALUE,a));let b=new Set;for(let e of d){if(!ay.isString(e))return c(new aO("sensitiveHeaders must be an array of strings",aO.ERR_BAD_OPTION_VALUE,a));b.add(e.toLowerCase())}b.size&&(S.sensitiveHeaders=Array.from(b),S.beforeRedirects.sensitiveHeaders=function(a,c){var d;!function(a,b){if(!b)return!1;try{return new URL(b.url).origin===new URL(a.href).origin}catch(a){return!1}}(a,c)&&(d=a.headers,d&&Object.keys(d).forEach(a=>{b.has(a.toLowerCase())&&delete d[a]}))})}i=V?cj:ci}}A>-1?S.maxBodyLength=A:S.maxBodyLength=1/0,S.insecureHTTPParser=!!ay.getSafeProp(a,"insecureHTTPParser"),f=i.request(S,function(d){if(H(),f.destroyed)return;let e=[d],g=ay.toFiniteNumber(d.headers["content-length"]);if(O||k){let a=new bG({maxRate:ay.toFiniteNumber(k)});O&&a.on("progress",ct(a,b0(g,b_(b1(O,ch),!0,3)))),e.push(a)}let h=d,i=d.req||f;if(!1!==C&&d.headers["content-encoding"])switch(("HEAD"===y||204===d.statusCode)&&delete d.headers["content-encoding"],(d.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":e.push(by.createUnzip(ca)),delete d.headers["content-encoding"];break;case"deflate":e.push(new bO),e.push(by.createUnzip(ca)),delete d.headers["content-encoding"];break;case"br":cd&&(e.push(by.createBrotliDecompress(cb)),delete d.headers["content-encoding"]);break;case"zstd":ce&&(e.push(by.createZstdDecompress(cc)),delete d.headers["content-encoding"])}h=e.length>1?bC.pipeline(e,ay.noop):e[0];let j={status:d.statusCode,statusText:d.statusMessage,headers:new aK(d.headers),config:a,request:i};if("stream"===v){if(B>-1){let b=h;async function*l(){let c=0;for await(let d of b){if((c+=d.length)>B)throw new aO("maxContentLength size of "+B+" exceeded",aO.ERR_BAD_RESPONSE,a,i);yield d}}h=bC.Readable.from(l(),{objectMode:!1})}j.data=h,bk(b,c,j)}else{let d=[],e=0;h.on("data",function(b){d.push(b),e+=b.length,B>-1&&e>B&&(D=!0,h.destroy(),G(new aO("maxContentLength size of "+B+" exceeded",aO.ERR_BAD_RESPONSE,a,i)))}),h.on("aborted",function(){if(D)return;let b=new aO("stream has been aborted",aO.ERR_BAD_RESPONSE,a,i,j);h.destroy(b),c(b)}),h.on("error",function(b){D||c(aO.from(b,null,a,i,j))}),h.on("end",function(){try{let a=1===d.length?d[0]:Buffer.concat(d);"arraybuffer"!==v&&(a=a.toString(w),w&&"utf8"!==w||(a=ay.stripBOM(a))),j.data=a}catch(b){return c(aO.from(b,null,a,j.request,j))}bk(b,c,j)})}F.once("abort",a=>{h.destroyed||(h.emit("error",a),h.destroy())})}),F.once("abort",a=>{f.close?f.close():f.destroy(a)}),f.on("error",function(b){c(aO.from(b,null,a,f))});let W=new Set;if(f.on("socket",function(a){"function"==typeof a.setKeepAlive&&a.setKeepAlive(!0,6e4),a[cl]||(a.on("error",function(b){let c=a[cm];c&&!c.destroyed&&c.destroy(b)}),a[cl]=!0),a[cm]=f,W.add(a)}),f.once("close",function(){for(let a of(H(),W))a[cm]===f&&(a[cm]=null);W.clear()}),ay.getSafeProp(a,"timeout")){let b=parseInt(ay.getSafeProp(a,"timeout"),10);if(Number.isNaN(b))return void G(new aO("error trying to parse `config.timeout` to int",aO.ERR_BAD_OPTION_VALUE,a,f));let c=function(){if(!e){let b,c,d;G((c=(b=ay.getSafeProp(a,"timeout"))?"timeout of "+b+"ms exceeded":"timeout exceeded",(d=ay.getSafeProp(a,"timeoutErrorMessage"))&&(c=d),new aO(c,m.clarifyTimeoutError?aO.ETIMEDOUT:aO.ECONNABORTED,a,f)))}};T&&b>0&&(g=setTimeout(c,b)),f.setTimeout(b,c)}else f.setTimeout(0);if(ay.isStream(n)){let b=!1,c=!1;n.on("end",()=>{b=!0}),n.once("error",a=>{c=!0,f.destroy(a)}),n.on("close",()=>{b||c||G(new bj("Request stream has been aborted",a,f))});let d=n;if(A>-1&&!U){let b=0;(d=bC.pipeline([n,new bC.Transform({transform(c,d,e){if((b+=c.length)>A)return e(new aO("Request body larger than maxBodyLength limit",aO.ERR_BAD_REQUEST,a,f));e(null,c)}})],ay.noop)).on("error",a=>{f.destroyed||f.destroy(a)})}d.pipe(f)}else n&&f.write(n),f.end()},new Promise((a,c)=>{let d,e,f=(a,b)=>{!e&&(e=!0,d&&d(a,b))},g=a=>{f(a,!0),c(a)};b(b=>{f(b),a(b)},g,a=>d=a).catch(g)})},cA=bc.hasStandardBrowserEnv?(f=new URL(bc.origin),g=bc.navigator&&/(msie|trident)/i.test(bc.navigator.userAgent),a=>(a=new URL(a,bc.origin),f.protocol===a.protocol&&f.host===a.host&&(g||f.port===a.port))):()=>!0,cB=bc.hasStandardBrowserEnv?{write(a,b,c,d,e,f,g){if("u"<typeof document)return;let h=[`${a}=${encodeURIComponent(b)}`];ay.isNumber(c)&&h.push(`expires=${new Date(c).toUTCString()}`),ay.isString(d)&&h.push(`path=${d}`),ay.isString(e)&&h.push(`domain=${e}`),!0===f&&h.push("secure"),ay.isString(g)&&h.push(`SameSite=${g}`),document.cookie=h.join("; ")},read(a){if("u"<typeof document)return null;let b=document.cookie.split(";");for(let c=0;c<b.length;c++){let d=b[c].replace(/^\s+/,""),e=d.indexOf("=");if(-1!==e&&d.slice(0,e)===a)try{return decodeURIComponent(d.slice(e+1))}catch(a){return d.slice(e+1)}}return null},remove(a){this.write(a,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}},cC=a=>a instanceof aK?{...a}:a;function cD(a,b){var c;a=a||{},b=b||{};let d=Object.create(null);function e(a,b,c,d){return ay.isPlainObject(a)&&ay.isPlainObject(b)?ay.merge.call({caseless:d},a,b):ay.isPlainObject(b)?ay.merge({},b):ay.isArray(b)?b.slice():b}function f(a,b,c,d){return ay.isUndefined(b)?ay.isUndefined(a)?void 0:e(void 0,a,c,d):e(a,b,c,d)}function g(a,b){if(!ay.isUndefined(b))return e(void 0,b)}function h(a,b){return ay.isUndefined(b)?ay.isUndefined(a)?void 0:e(void 0,a):e(void 0,b)}function i(c,d,f){return ay.hasOwnProp(b,f)?e(c,d):ay.hasOwnProp(a,f)?e(void 0,c):void 0}Object.defineProperty(d,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});let j={url:g,method:g,data:g,baseURL:h,transformRequest:h,transformResponse:h,paramsSerializer:h,timeout:h,timeoutMessage:h,withCredentials:h,withXSRFToken:h,adapter:h,responseType:h,xsrfCookieName:h,xsrfHeaderName:h,onUploadProgress:h,onDownloadProgress:h,decompress:h,maxContentLength:h,maxBodyLength:h,beforeRedirect:h,transport:h,httpAgent:h,httpsAgent:h,cancelToken:h,socketPath:h,allowedSocketPaths:h,responseEncoding:h,validateStatus:i,headers:(a,b,c)=>f(cC(a),cC(b),c,!0)};return ay.forEach((c={...a,...b},Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(c).concat(Object.getOwnPropertySymbols(c).filter(a=>Object.getOwnPropertyDescriptor(c,a).enumerable)):Object.keys(c)),function(c){if("__proto__"===c||"constructor"===c||"prototype"===c)return;let e=ay.hasOwnProp(j,c)?j[c]:f,g=e(ay.hasOwnProp(a,c)?a[c]:void 0,ay.hasOwnProp(b,c)?b[c]:void 0,c);ay.isUndefined(g)&&e!==i||(d[c]=g)}),ay.hasOwnProp(b,"validateStatus")&&ay.isUndefined(b.validateStatus)&&!1===function(c){let d=ay.hasOwnProp(b,"transitional")?b.transitional:void 0;if(!ay.isUndefined(d)){if(!ay.isPlainObject(d))return;else if(ay.hasOwnProp(d,c))return d[c]}let e=ay.hasOwnProp(a,"transitional")?a.transitional:void 0;if(ay.isPlainObject(e)&&ay.hasOwnProp(e,c))return e[c]}("validateStatusUndefinedResolves")&&(ay.hasOwnProp(a,"validateStatus")?d.validateStatus=e(void 0,a.validateStatus):delete d.validateStatus),d}let cE=function(a){let b=cD({},a),c=a=>ay.hasOwnProp(b,a)?b[a]:void 0,d=c("data"),e=c("withXSRFToken"),f=c("xsrfHeaderName"),g=c("xsrfCookieName"),h=c("headers"),i=c("auth"),j=c("baseURL"),k=c("allowAbsoluteUrls"),l=c("url");if(b.headers=h=aK.from(h),b.url=a$(bo(j,l,k,b),c("params"),c("paramsSerializer")),i){let b=ay.getSafeProp(i,"username")||"",c=ay.getSafeProp(i,"password")||"";try{h.set("Authorization","Basic "+btoa(b+":"+(c?encodeURIComponent(c).replace(/%([0-9A-F]{2})/gi,(a,b)=>String.fromCharCode(parseInt(b,16))):"")))}catch(b){throw aO.from(b,aO.ERR_BAD_OPTION_VALUE,a)}}if(ay.isFormData(d)&&(bc.hasStandardBrowserEnv||bc.hasStandardBrowserWebWorkerEnv||ay.isReactNative(d)?h.setContentType(void 0):ay.isFunction(d.getHeaders)&&bE(h,d.getHeaders(),c("formDataHeaderPolicy"))),bc.hasStandardBrowserEnv&&(ay.isFunction(e)&&(e=e(b)),!0===e||null==e&&cA(b.url))){let a=f&&g&&cB.read(g);a&&h.set(f,a)}return b},cF="u">typeof XMLHttpRequest&&function(a){return new Promise(function(b,c){let d,e,f,g,h,i=cE(a),j=i.data,k=aK.from(i.headers).normalize(),{responseType:l,onUploadProgress:m,onDownloadProgress:n}=i;function o(){g&&g(),h&&h(),i.cancelToken&&i.cancelToken.unsubscribe(d),i.signal&&i.signal.removeEventListener("abort",d)}let p=new XMLHttpRequest;function q(){if(!p)return;let d=aK.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders());bk(function(a){b(a),o()},function(a){c(a),o()},{data:l&&"text"!==l&&"json"!==l?p.response:p.responseText,status:p.status,statusText:p.statusText,headers:d,config:a,request:p}),p=null}p.open(i.method.toUpperCase(),i.url,!0),p.timeout=i.timeout,"onloadend"in p?p.onloadend=q:p.onreadystatechange=function(){!p||4!==p.readyState||(0!==p.status||p.responseURL&&p.responseURL.startsWith("file:"))&&setTimeout(q)},p.onabort=function(){p&&(c(new aO("Request aborted",aO.ECONNABORTED,a,p)),o(),p=null)},p.onerror=function(b){let d=new aO(b&&b.message?b.message:"Network Error",aO.ERR_NETWORK,a,p);d.event=b||null,c(d),o(),p=null},p.ontimeout=function(){let b=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",d=i.transitional||a0;i.timeoutErrorMessage&&(b=i.timeoutErrorMessage),c(new aO(b,d.clarifyTimeoutError?aO.ETIMEDOUT:aO.ECONNABORTED,a,p)),o(),p=null},void 0===j&&k.setContentType(null),"setRequestHeader"in p&&ay.forEach(aD(k),function(a,b){p.setRequestHeader(b,a)}),ay.isUndefined(i.withCredentials)||(p.withCredentials=!!i.withCredentials),l&&"json"!==l&&(p.responseType=i.responseType),n&&([f,h]=b_(n,!0),p.addEventListener("progress",f)),m&&p.upload&&([e,g]=b_(m),p.upload.addEventListener("progress",e),p.upload.addEventListener("loadend",g)),(i.cancelToken||i.signal)&&(d=b=>{p&&(c(!b||b.type?new bj(null,a,p):b),p.abort(),o(),p=null)},i.cancelToken&&i.cancelToken.subscribe(d),i.signal&&(i.signal.aborted?d():i.signal.addEventListener("abort",d)));let r=bA(i.url);if(r&&!bc.protocols.includes(r)){c(new aO("Unsupported protocol "+r+":",aO.ERR_BAD_REQUEST,a)),o();return}p.send(j||null)})},cG=function*(a,b){let c,d=a.byteLength;if(!b||d<b)return void(yield a);let e=0;for(;e<d;)c=e+b,yield a.slice(e,c),e=c},cH=async function*(a,b){for await(let c of cI(a))yield*cG(c,b)},cI=async function*(a){if(a[Symbol.asyncIterator])return void(yield*a);let b=a.getReader();try{for(;;){let{done:a,value:c}=await b.read();if(a)break;yield c}}finally{await b.cancel()}},cJ=(a,b,c,d)=>{let e,f=cH(a,b),g=0,h=a=>{!e&&(e=!0,d&&d(a))};return new ReadableStream({async pull(a){try{let{done:b,value:d}=await f.next();if(b){h(),a.close();return}let e=d.byteLength;if(c){let a=g+=e;c(a)}a.enqueue(new Uint8Array(d))}catch(a){throw h(a),a}},cancel:a=>(h(a),f.return())},{highWaterMark:2})},{isFunction:cK}=ay,cL=a=>{if(!ay.isString(a))return a;try{return decodeURIComponent(a)}catch(b){return a}},cM=(a,...b)=>{try{return!!a(...b)}catch(a){return!1}},cN=a=>{let b,c=void 0!==ay.global&&null!==ay.global?ay.global:globalThis,{ReadableStream:d,TextEncoder:e}=c,{fetch:f,Request:g,Response:h}=a=ay.merge.call({skipUndefined:!0},{Request:c.Request,Response:c.Response},a),i=f?cK(f):"function"==typeof fetch,j=cK(g),k=cK(h);if(!i)return!1;let l=i&&cK(d),m=i&&("function"==typeof e?(b=new e,a=>b.encode(a)):async a=>new Uint8Array(await new g(a).arrayBuffer())),n=j&&l&&cM(()=>{let a=!1,b=new g(bc.origin,{body:new d,method:"POST",get duplex(){return a=!0,"half"}}),c=b.headers.has("Content-Type");return null!=b.body&&b.body.cancel(),a&&!c}),o=k&&l&&cM(()=>ay.isReadableStream(new h("").body)),p={stream:o&&(a=>a.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(a=>{p[a]||(p[a]=(b,c)=>{let d=b&&b[a];if(d)return d.call(b);throw new aO(`Response type '${a}' is not supported`,aO.ERR_NOT_SUPPORT,c)})});let q=async a=>{if(null==a)return 0;if(ay.isBlob(a))return a.size;if(ay.isSpecCompliantForm(a)){let b=new g(bc.origin,{method:"POST",body:a});return(await b.arrayBuffer()).byteLength}return ay.isArrayBufferView(a)||ay.isArrayBuffer(a)?a.byteLength:(ay.isURLSearchParams(a)&&(a+=""),ay.isString(a))?(await m(a)).byteLength:void 0},r=async(a,b)=>{let c=ay.toFiniteNumber(a.getContentLength());return null==c?q(b):c};return async a=>{let b,{url:c,method:d,data:i,signal:k,cancelToken:m,timeout:s,onDownloadProgress:t,onUploadProgress:u,responseType:v,headers:w,withCredentials:x="same-origin",fetchOptions:y,maxContentLength:z,maxBodyLength:A}=cE(a),B=ay.isNumber(z)&&z>-1,C=ay.isNumber(A)&&A>-1,D=f||fetch;v=v?(v+"").toLowerCase():"text";let E=((a,b)=>{if(a=a?a.filter(Boolean):[],!b&&!a.length)return;let c=new AbortController,d=!1,e=function(a){if(!d){d=!0,g();let b=a instanceof Error?a:this.reason;c.abort(b instanceof aO?b:new bj(b instanceof Error?b.message:b))}},f=b&&setTimeout(()=>{f=null,e(new aO(`timeout of ${b}ms exceeded`,aO.ETIMEDOUT))},b),g=()=>{a&&(f&&clearTimeout(f),f=null,a.forEach(a=>{a.unsubscribe?a.unsubscribe(e):a.removeEventListener("abort",e)}),a=null)};a.forEach(a=>{if(!d){if(a.aborted)return void e.call(a);a.addEventListener("abort",e,{once:!0})}});let{signal:h}=c;return h.unsubscribe=()=>ay.asap(g),h})([k,m&&m.toAbortSignal()],s),F=null,G=E&&E.unsubscribe&&(()=>{E.unsubscribe()}),H=null,I=()=>new aO("Request body larger than maxBodyLength limit",aO.ERR_BAD_REQUEST,a,F);try{var J,K;let f,k,m,s,L=(k="auth",ay.hasOwnProp(a,k)?a[k]:void 0);if(L){let a=ay.getSafeProp(L,"username")||"",b=ay.getSafeProp(L,"password")||"";f={username:a,password:b}}if(m=(J=c).indexOf("://"),s=J,-1!==m&&(s=s.slice(m+3)),s.includes("@")||s.includes(":")){let a=new URL(c,bc.origin);if(!f&&(a.username||a.password)){let b=cL(a.username),c=cL(a.password);f={username:b,password:c}}(a.username||a.password)&&(a.username="",a.password="",c=a.href)}if(f){let a;w.delete("authorization"),w.set("Authorization","Basic "+btoa((a=(f.username||"")+":"+(f.password||""),encodeURIComponent(a).replace(/%([0-9A-F]{2})/gi,(a,b)=>String.fromCharCode(parseInt(b,16))))))}if(B&&"string"==typeof c&&c.startsWith("data:")){let b;if(K=c,b="string"==typeof K?K.indexOf("#"):-1,b9(-1===b?K:K.slice(0,b),b8)>z)throw new aO("maxContentLength size of "+z+" exceeded",aO.ERR_BAD_RESPONSE,a,F)}if(C&&"get"!==d&&"head"!==d){let a=await q(i);if("number"==typeof a&&isFinite(a)&&(b=a,a>A))throw I()}let M=C&&(ay.isReadableStream(i)||ay.isStream(i)),N=(a,b,c)=>cJ(a,65536,a=>{if(C&&a>A)throw H=I();b&&b(a)},c);if(n&&"get"!==d&&"head"!==d&&(u||M)){if(b=null==b?await r(w,i):b,0!==b||M){let a,d=new g(c,{method:"POST",body:i,duplex:"half"});if(ay.isFormData(i)&&(a=d.headers.get("content-type"))&&w.setContentType(a),d.body){let[a,c]=u&&b0(b,b_(b1(u)))||[];i=N(d.body,a,c)}}}else if(M&&!j&&l&&"get"!==d&&"head"!==d)i=N(i);else if(M&&j&&!n&&"get"!==d&&"head"!==d)throw new aO("Stream request bodies are not supported by the current fetch implementation",aO.ERR_NOT_SUPPORT,a,F);ay.isString(x)||(x=x?"include":"omit");let O=j&&"credentials"in g.prototype;if(ay.isFormData(i)){let a=w.getContentType();a&&/^multipart\/form-data/i.test(a)&&!/boundary=/i.test(a)&&w.delete("content-type")}w.set("User-Agent","axios/"+bz,!1);let P={...y,signal:E,method:d.toUpperCase(),headers:aD(w.normalize()),body:i,duplex:"half",credentials:O?x:void 0};F=j&&new g(c,P);let Q=await (j?D(F,y):D(c,P)),R=aK.from(Q.headers);if(B){let b=ay.toFiniteNumber(R.getContentLength());if(null!=b&&b>z)throw new aO("maxContentLength size of "+z+" exceeded",aO.ERR_BAD_RESPONSE,a,F)}let S=o&&("stream"===v||"response"===v);if(o&&Q.body&&(t||B||S&&G)){let b={};["status","statusText","headers"].forEach(a=>{b[a]=Q[a]});let c=ay.toFiniteNumber(R.getContentLength()),[d,e]=t&&b0(c,b_(b1(t),!0))||[];Q=new h(cJ(Q.body,65536,b=>{if(B&&b>z)throw new aO("maxContentLength size of "+z+" exceeded",aO.ERR_BAD_RESPONSE,a,F);d&&d(b)},()=>{e&&e(),G&&G()}),b)}v=v||"text";let T=await p[ay.findKey(p,v)||"text"](Q,a);if(B&&!o&&!S){let b;if(null!=T&&("number"==typeof T.byteLength?b=T.byteLength:"number"==typeof T.size?b=T.size:"string"==typeof T&&(b="function"==typeof e?new e().encode(T).byteLength:T.length)),"number"==typeof b&&b>z)throw new aO("maxContentLength size of "+z+" exceeded",aO.ERR_BAD_RESPONSE,a,F)}return!S&&G&&G(),await new Promise((b,c)=>{bk(b,c,{data:T,headers:aK.from(Q.headers),status:Q.status,statusText:Q.statusText,config:a,request:F})})}catch(b){if(G&&G(),E&&E.aborted&&E.reason instanceof aO){let c=E.reason;throw c.config=a,F&&(c.request=F),b!==c&&Object.defineProperty(c,"cause",{__proto__:null,value:b,writable:!0,enumerable:!1,configurable:!0}),c}if(H)throw F&&!H.request&&(H.request=F),H;if(b instanceof aO)throw F&&!b.request&&(b.request=F),b;if(b&&"TypeError"===b.name&&/Load failed|fetch/i.test(b.message)){let c=new aO("Network Error",aO.ERR_NETWORK,a,F,b&&b.response);throw Object.defineProperty(c,"cause",{__proto__:null,value:b.cause||b,writable:!0,enumerable:!1,configurable:!0}),c}throw aO.from(b,b&&b.code,a,F,b&&b.response)}}},cO=new Map,cP=a=>{let b=a&&a.env||{},{fetch:c,Request:d,Response:e}=b,f=[d,e,c],g=f.length,h,i,j=cO;for(;g--;)h=f[g],void 0===(i=j.get(h))&&j.set(h,i=g?new Map:cN(b)),j=i;return i};cP();let cQ={http:cz,xhr:cF,fetch:{get:cP}};ay.forEach(cQ,(a,b)=>{if(a){try{Object.defineProperty(a,"name",{__proto__:null,value:b})}catch(a){}Object.defineProperty(a,"adapterName",{__proto__:null,value:b})}});let cR=a=>`- ${a}`,cS=a=>ay.isFunction(a)||null===a||!1===a,cT=function(a,b){let c,d,{length:e}=a=ay.isArray(a)?a:[a],f={};for(let g=0;g<e;g++){let e;if(d=c=a[g],!cS(c)&&void 0===(d=cQ[(e=String(c)).toLowerCase()]))throw new aO(`Unknown adapter '${e}'`);if(d&&(ay.isFunction(d)||(d=d.get(b))))break;f[e||"#"+g]=d}if(!d){let a=Object.entries(f).map(([a,b])=>`adapter ${a} `+(!1===b?"is not supported by the environment":"is not available in the build"));throw new aO("There is no suitable adapter to dispatch the request "+(e?a.length>1?"since :\n"+a.map(cR).join("\n"):" "+cR(a[0]):"as no adapter specified"),aO.ERR_NOT_SUPPORT)}return d};function cU(a){if(a.cancelToken&&a.cancelToken.throwIfRequested(),a.signal&&a.signal.aborted)throw new bj(null,a)}function cV(a){return cU(a),a.headers=aK.from(a.headers),a.data=bh.call(a,a.transformRequest),-1!==["post","put","patch"].indexOf(a.method)&&a.headers.setContentType("application/x-www-form-urlencoded",!1),cT(a.adapter||bg.adapter,a)(a).then(function(b){cU(a),a.response=b;try{b.data=bh.call(a,a.transformResponse,b)}finally{delete a.response}return b.headers=aK.from(b.headers),b},function(b){if(!bi(b)&&(cU(a),b&&b.response)){a.response=b.response;try{b.response.data=bh.call(a,a.transformResponse,b.response)}finally{delete a.response}b.response.headers=aK.from(b.response.headers)}return Promise.reject(b)})}let cW={};["object","boolean","number","function","string","symbol"].forEach((a,b)=>{cW[a]=function(c){return typeof c===a||"a"+(b<1?"n ":" ")+a}});let cX={};cW.transitional=function(a,b,c){function d(a,b){return"[Axios v"+bz+"] Transitional option '"+a+"'"+b+(c?". "+c:"")}return(c,e,f)=>{if(!1===a)throw new aO(d(e," has been removed"+(b?" in "+b:"")),aO.ERR_DEPRECATED);return b&&!cX[e]&&(cX[e]=!0,console.warn(d(e," has been deprecated since v"+b+" and will be removed in the near future"))),!a||a(c,e,f)}},cW.spelling=function(a){return(b,c)=>(console.warn(`${c} is likely a misspelling of ${a}`),!0)};let cY=function(a,b,c){if("object"!=typeof a||null===a)throw new aO("options must be an object",aO.ERR_BAD_OPTION_VALUE);let d=Object.keys(a),e=d.length;for(;e-- >0;){let f=d[e],g=Object.prototype.hasOwnProperty.call(b,f)?b[f]:void 0;if(g){let b=a[f],c=void 0===b||g(b,f,a);if(!0!==c)throw new aO("option "+f+" must be "+c,aO.ERR_BAD_OPTION_VALUE);continue}if(!0!==c)throw new aO("Unknown option "+f,aO.ERR_BAD_OPTION)}};class cZ{constructor(a){this.defaults=a||{},this.interceptors={request:new a_,response:new a_}}async request(a,b){try{return await this._request(a,b)}catch(a){if(a instanceof Error){let b={};Error.captureStackTrace?Error.captureStackTrace(b):b=Error();let c=(()=>{if(!b.stack)return"";let a=b.stack.indexOf("\n");return -1===a?"":b.stack.slice(a+1)})();try{if(a.stack){if(c){let b=c.indexOf("\n"),d=-1===b?-1:c.indexOf("\n",b+1),e=-1===d?"":c.slice(d+1);String(a.stack).endsWith(e)||(a.stack+="\n"+c)}}else a.stack=c}catch(a){}}throw a}}_request(a,b){let c,d;"string"==typeof a?(b=b||{}).url=a:b=a||{};let{transitional:e,paramsSerializer:f,headers:g}=b=cD(this.defaults,b);void 0!==e&&cY(e,{silentJSONParsing:cW.transitional(cW.boolean),forcedJSONParsing:cW.transitional(cW.boolean),clarifyTimeoutError:cW.transitional(cW.boolean),legacyInterceptorReqResOrdering:cW.transitional(cW.boolean),advertiseZstdAcceptEncoding:cW.transitional(cW.boolean),validateStatusUndefinedResolves:cW.transitional(cW.boolean)},!1),null!=f&&(ay.isFunction(f)?b.paramsSerializer={serialize:f}:cY(f,{encode:cW.function,serialize:cW.function},!0)),void 0!==b.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?b.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:b.allowAbsoluteUrls=!0),cY(b,{baseUrl:cW.spelling("baseURL"),withXsrfToken:cW.spelling("withXSRFToken")},!0),b.method=(b.method||this.defaults.method||"get").toLowerCase();let h=g&&ay.merge(g.common,g[b.method]);g&&ay.forEach(["delete","get","head","post","put","patch","query","common"],a=>{delete g[a]}),b.headers=aK.concat(h,g);let i=[],j=!0;this.interceptors.request.forEach(function(a){if("function"==typeof a.runWhen&&!1===a.runWhen(b))return;j=j&&a.synchronous;let c=b.transitional||a0;c&&c.legacyInterceptorReqResOrdering?i.unshift(a.fulfilled,a.rejected):i.push(a.fulfilled,a.rejected)});let k=[];this.interceptors.response.forEach(function(a){k.push(a.fulfilled,a.rejected)});let l=0;if(!j){let a=[cV.bind(this),void 0];for(a.unshift(...i),a.push(...k),d=a.length,c=Promise.resolve(b);l<d;)c=c.then(a[l++],a[l++]);return c}d=i.length;let m=b;for(;l<d;){let a=i[l++],b=i[l++];try{m=a?a(m):m}catch(a){if(!b){c=Promise.reject(a);break}try{let d=b.call(this,a);ay.isThenable(d)&&(c=Promise.resolve(d).then(()=>cV.call(this,m)))}catch(a){c=Promise.reject(a)}break}}if(!c)try{c=cV.call(this,m)}catch(a){c=Promise.reject(a)}for(l=0,d=k.length;l<d;)c=c.then(k[l++],k[l++]);return c}getUri(a){return a$(bo((a=cD(this.defaults,a)).baseURL,a.url,a.allowAbsoluteUrls,a),a.params,a.paramsSerializer)}}ay.forEach(["delete","get","head","options"],function(a){cZ.prototype[a]=function(b,c){return this.request(cD(c||{},{method:a,url:b,data:c&&ay.hasOwnProp(c,"data")?c.data:void 0}))}}),ay.forEach(["post","put","patch","query"],function(a){function b(b){return function(c,d,e){return this.request(cD(e||{},{method:a,headers:b?{"Content-Type":"multipart/form-data"}:{},url:c,data:d}))}}cZ.prototype[a]=b(),"query"!==a&&(cZ.prototype[a+"Form"]=b(!0))});class c${constructor(a){let b;if("function"!=typeof a)throw TypeError("executor must be a function.");this.promise=new Promise(function(a){b=a});const c=this;this.promise.then(a=>{if(!c._listeners)return;let b=c._listeners.length;for(;b-- >0;)c._listeners[b](a);c._listeners=null}),this.promise.then=a=>{let b,d=new Promise(a=>{c.subscribe(a),b=a}).then(a);return d.cancel=function(){c.unsubscribe(b)},d},a(function(a,d,e){c.reason||(c.reason=new bj(a,d,e),b(c.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(a){this.reason?a(this.reason):this._listeners?this._listeners.push(a):this._listeners=[a]}unsubscribe(a){if(!this._listeners)return;let b=this._listeners.indexOf(a);-1!==b&&this._listeners.splice(b,1)}toAbortSignal(){let a=new AbortController,b=b=>{a.abort(b)};return this.subscribe(b),a.signal.unsubscribe=()=>this.unsubscribe(b),a.signal}static source(){let a;return{token:new c$(function(b){a=b}),cancel:a}}}let c_={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(c_).forEach(([a,b])=>{c_[b]=a});let c0=function a(b){let c=new cZ(b),d=I(cZ.prototype.request,c);return ay.extend(d,cZ.prototype,c,{allOwnKeys:!0}),ay.extend(d,c,null,{allOwnKeys:!0}),d.create=function(c){return a(cD(b,c))},d}(bg);c0.Axios=cZ,c0.CanceledError=bj,c0.CancelToken=c$,c0.isCancel=bi,c0.VERSION=bz,c0.toFormData=aV,c0.AxiosError=aO,c0.Cancel=c0.CanceledError,c0.all=function(a){return Promise.all(a)},c0.spread=function(a){return function(b){return a.apply(null,b)}},c0.isAxiosError=function(a){return ay.isObject(a)&&!0===a.isAxiosError},c0.mergeConfig=cD,c0.AxiosHeaders=aK,c0.formToJSON=a=>be(ay.isHTMLForm(a)?new FormData(a):a),c0.getAdapter=cT,c0.HttpStatusCode=c_,c0.default=c0;var c1=c(5907),c2=c(30670);let c3=(0,r.h)("backend/services/model/testConnection"),c4=[{role:"user",content:"Reply with the single word: pong"}],c5=["premature close","econnreset","socket hang up","epipe","und_err","terminated","network","fetch failed"];function c6(a){if(!a)return;let b=["retry-after","x-ratelimit-reset","x-ratelimit-remaining","x-ratelimit-limit"],c={};for(let d of Object.keys(a))b.includes(d.toLowerCase())&&(c[d.toLowerCase()]=String(a[d]));return Object.keys(c).length>0?c:void 0}async function c7(a,b,c,d){let e=Date.now();try{let f=(0,c1.sJ)({apiKey:c,baseURL:b,maxRetries:0,defaultHeaders:(0,c1.lj)(d)}),g=await f.chat.completions.create({model:a,messages:c4}),h=Date.now()-e,i="error"in g&&g.error&&"object"==typeof g.error?g.error:void 0;if(i)return{ok:!1,durationMs:h,error:{message:"string"==typeof i.message?i.message:"Provider returned an error in the response body",code:void 0!==i.code?String(i.code):void 0,type:"string"==typeof i.type?i.type:void 0,body:i}};return{ok:!0,status:200,durationMs:h,content:g.choices?.[0]?.message?.content?.slice(0,500)??"",usage:g.usage}}catch(c){let a=Date.now()-e;if(c instanceof n.Ay.APIError){let b="error"in c?c.error:void 0,d=c6(c.headers);return{ok:!1,status:c.status,durationMs:a,error:{name:c.name,message:c.message,status:c.status,code:c.code??void 0,type:c.type??void 0,param:c.param??void 0,retryAfter:d?.["retry-after"],headers:d,body:b,stack:c.stack}}}let b=c instanceof Error?c.message:String(c);return{ok:!1,durationMs:a,error:{name:c instanceof Error?c.name:void 0,message:b,code:c&&"object"==typeof c&&"code"in c&&void 0!==c.code?String(c.code):void 0,stack:c instanceof Error?c.stack:void 0}}}}async function c8(a,b,c,d){let e=Date.now(),f=(b||"https://api.openai.com/v1").replace(/\/+$/,""),g=`${f}/chat/completions`;try{let b=await c0.post(g,{model:a,messages:c4},{headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",...(0,c1.lj)(d)??{}},timeout:6e5,validateStatus:()=>!0}),f=Date.now()-e,h=b.data;if(b.status<200||b.status>=300||h?.error){let a=h?.error??h;return{ok:!1,status:b.status,durationMs:f,error:{message:a?.message||`HTTP ${b.status}`,status:b.status,code:a?.code!==void 0?String(a.code):void 0,type:a?.type,headers:c6(b.headers),body:a}}}return{ok:!0,status:b.status,durationMs:f,content:h?.choices?.[0]?.message?.content?.slice(0,500)??"",usage:h?.usage}}catch(b){let a=Date.now()-e;return{ok:!1,status:b.response?.status,durationMs:a,error:{name:b.name,message:b.message,status:b.response?.status,code:b.code,body:b.response?.data,stack:b.stack}}}}async function c9(a,b){let c=Date.now();try{let d=(0,c2.getCompletionAdapter)(a),{completion:e}=await d.createCompletion({model:a,apiKey:b,messages:[...c4],temperature:0,maxTokens:(0,o.normalizeMaxTokens)(a.maxTokens)}),f=Date.now()-c,g=e?.error;if(g)return{ok:!1,durationMs:f,error:{message:g.message||"Provider returned an error"}};return{ok:!0,status:200,durationMs:f,content:e.choices?.[0]?.message?.content?.slice(0,500)??"",usage:e.usage}}catch(a){return{ok:!1,durationMs:Date.now()-c,error:{name:a instanceof Error?a.name:void 0,message:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0}}}}async function da(a,b,c){let d=Date.now(),e=(a.baseUrl||"https://openrouter.ai/api/v1").replace(/\/+$/,""),f={Authorization:`Bearer ${b}`,...(0,c1.lj)("openrouter")??{}};try{let b=await c0.get(`${e}/key`,{headers:f,timeout:6e4,validateStatus:()=>!0});if(b.status<200||b.status>=300){let a=b.data?.error??b.data;return{ok:!1,status:b.status,durationMs:Date.now()-d,error:{message:a?.message||`HTTP ${b.status}`,status:b.status,code:a?.code!==void 0?String(a.code):void 0,type:a?.type,headers:c6(b.headers),body:a}}}let g=await c0.get(`${e}/${c}/models`,{headers:f,timeout:6e4,validateStatus:()=>!0});if(g.status<200||g.status>=300){let a=g.data?.error??g.data;return{ok:!1,status:g.status,durationMs:Date.now()-d,error:{message:a?.message||`HTTP ${g.status}`,status:g.status,code:a?.code!==void 0?String(a.code):void 0,type:a?.type,headers:c6(g.headers),body:a}}}if(!(Array.isArray(g.data?.data)&&g.data.data.some(b=>b?.id===a.name)))return{ok:!1,status:404,durationMs:Date.now()-d,error:{message:`${a.name} is not listed by OpenRouter's ${c} API.`,status:404,code:"media_model_not_found"}};return{ok:!0,status:200,durationMs:Date.now()-d,content:`API key is valid and ${a.name} is available through /${c}.`}}catch(a){return{ok:!1,status:a.response?.status,durationMs:Date.now()-d,error:{name:a.name,message:a.message,status:a.response?.status,code:a.code,body:a.response?.data,stack:a.stack}}}}async function db(a){let{modelName:b,baseUrl:c,apiKey:d,provider:e,adapter:f,model:g}=a;c3.info("Testing model connection",{modelName:b,baseUrl:c,provider:e,adapter:f,hasApiKey:!!d});let h=g?(0,c2.Pi)(g):{useMediaRoute:!1},i=g?(0,c2.Ro)(g):void 0;if(h.useMediaRoute&&g){let a=h.kind??"images",f=await da(g,d,a),j={ok:f.ok,durationMs:0,content:"n/a — dedicated OpenRouter media APIs are validated without starting a billable generation."},k="videos"===a?"video":"image",l=f.ok?`Connected successfully. The API key is valid and the model is listed by OpenRouter's dedicated ${k} API. No billable generation was started.`:`OpenRouter ${k} API validation failed: ${f.error?.message??"unknown error"}.`;return{ok:f.ok,model:b,baseUrl:c,provider:e,sdk:f,axios:j,diagnosis:l,adapterRoute:i,adapter:f}}if(f&&"openai"!==f&&g){let a=await c9(g,d),h="openai-responses"!==f,j={ok:a.ok,durationMs:0,content:h?"n/a — native SDK adapter; the axios cross-check applies only to OpenAI-compatible endpoints.":"n/a — the axios cross-check targets the Chat Completions endpoint only."},k=a.ok?`Connected successfully via the ${f} adapter${h?" (native SDK)":""}. The model and credentials are working.`:`The ${f} adapter failed: ${a.error?.message??"unknown error"}. Check the model name and the ${"claude-cli"===f?"OAuth token (claude setup-token) and that the `claude` CLI is installed":"codex-cli"===f?"OpenAI API key (or run `codex login` for a ChatGPT plan and leave the key empty)":"API key"}.`;return{ok:a.ok,model:b,baseUrl:c,provider:e,sdk:a,axios:j,diagnosis:k,adapterRoute:i,adapter:a}}let[j,k]=await Promise.all([c7(b,c,d,e),c8(b,c,d,e)]),l=function(a,b){if(a.ok&&b.ok)return"Both the SDK and axios reached the provider successfully. The model, key, and base URL are working.";if(a.ok&&!b.ok)return`The SDK succeeded but the axios cross-check failed. This is unusual; the model is usable via flows. axios error: ${b.error?.message??"unknown"}.`;if(!a.ok&&b.ok)return!function(a){if(!a)return!1;let b=a.toLowerCase();return c5.some(a=>b.includes(a))}(a.error?.message)?`The SDK failed but axios succeeded. Likely an SDK/transport issue rather than the provider or key. SDK error: ${a.error?.message??"unknown"}.`:'The SDK failed with a transport error ("'+(a.error?.message??"")+'") while axios succeeded against the same endpoint and key. This is the keep-alive / "Premature close" connection-reuse bug, not a provider or key problem. The flow engine now disables keep-alive to avoid it.';let c=a.error?.status??b.error?.status;if(401===c||403===c)return"Both attempts failed with an auth error. The API key is missing, invalid, or lacks access to this model.";if(429===c){let b=a.error?.retryAfter??a.error?.headers?.["retry-after"];return"Both attempts were rate-limited (429) by the provider"+(b?` (retry after ${b}s)`:"")+'. For OpenRouter ":free" models this is a hard daily/throughput limit — try a paid model or wait.'}return 404===c?"Both attempts returned 404. The model name is probably wrong for this provider/base URL.":`Both the SDK and axios failed to reach the provider. SDK error: ${a.error?.message??"unknown"}; axios error: ${b.error?.message??"unknown"}. Check the base URL and network connectivity.`}(j,k);if(i?.adapterId==="openai"&&"openrouter"===e&&g){let a=(0,c2.AY)(g);(a.includes("image")||a.includes("video"))&&a.includes("text")&&(l+=" This model also outputs image/video alongside text, so it is served by /chat/completions rather than the dedicated OpenRouter media route.")}let m={ok:j.ok,model:b,baseUrl:c,provider:e,sdk:j,axios:k,diagnosis:l,adapterRoute:i,adapter:i?{...j,content:j.ok?j.content?j.content:"Same round-trip as the OpenAI SDK attempt above.":j.content}:void 0};return c3.info("Model connection test complete",{modelName:b,sdkOk:j.ok,axiosOk:k.ok}),m}let dc=(0,r.h)("backend/services/model/index");class dd{async loadModels(){dc.debug("loadModels: Entering method");try{return await (0,p.loadItem)(q.Zg.MODELS,[])}catch(a){return dc.warn("loadModels: Failed to load models:",a),[]}}async getModel(a){dc.debug(`getModel: Looking for model with ID: ${a}`);try{let b=(await this.loadModels()).find(b=>b.id===a)||null;if(b)return dc.debug(`getModel: Model ${a} found`),b;return dc.debug(`getModel: Model ${a} not found`),null}catch(b){return dc.error(`getModel: Error finding model ${a}:`,b),null}}async addModel(a){dc.debug("addModel: Entering method");try{let b=(0,s.u3)(a);if(b)return{success:!1,error:b};let c=await this.loadModels();if(a.displayName&&a.displayName.trim()){let b=a.displayName.trim();if(c.find(a=>a.displayName?.toLowerCase()===b.toLowerCase()))return{success:!1,error:`A model with the display name "${b}" already exists`};a.displayName=b}let d={...a,ApiKey:await this.resolveApiKeyForSave(a.ApiKey,void 0)},e=[...c,d];return await (0,p.VH)(q.Zg.MODELS,e),{success:!0,model:d}}catch(a){return dc.warn("addModel: Failed to add model:",a),{success:!1,error:a instanceof Error?a.message:"Failed to add model"}}}async resolveApiKeyForSave(a,b){let c=a??"";return c===t.RJ?b??"":c.startsWith("${global:")||c.startsWith("encrypted:")||c.startsWith("encrypted_failed:")?c:""===c.trim()?"":await (0,u.Rs)(c)}async updateModel(a){dc.debug("updateModel: Entering method");try{if(dc.debug("updateModel: validating model metadata",{modelId:a.id,provider:a.provider,adapter:a.adapter,credentialConfigured:!!a.ApiKey?.trim()}),!a.id)return dc.warn("updateModel: Missing model ID"),{success:!1,error:"Model ID is required"};let b=await this.loadModels(),c=b.find(b=>b.id===a.id);if(!c)return dc.warn("updateModel: Model not found",{modelId:a.id}),{success:!1,error:"Model not found"};if(!a.provider)return dc.warn("updateModel: Missing provider",{modelId:a.id}),{success:!1,error:"Provider is required"};let d=(0,s.u3)(a);if(d)return{success:!1,error:d};if(a.displayName&&a.displayName.trim()){let c=a.displayName.trim(),d=b.find(b=>b.displayName?.toLowerCase()===c.toLowerCase()&&b.id!==a.id);if(d){let b=`A model with the display name "${c}" already exists (ID: ${d.id})`;return dc.warn("updateModel: Duplicate display name",{modelId:a.id,displayName:c,duplicateId:d.id,duplicateDisplayName:d.displayName}),{success:!1,error:b}}a.displayName=c}let e={...c,...a};e.ApiKey=await this.resolveApiKeyForSave(a.ApiKey,c.ApiKey);let f=b.map(b=>b.id===a.id?e:b);return dc.verbose("updateModel: Updating models",JSON.stringify(e)),await (0,p.VH)(q.Zg.MODELS,f),dc.debug("updateModel: Model updated successfully",{modelId:a.id,displayName:e.displayName}),{success:!0,model:e}}catch(b){return dc.error("updateModel: Failed to update model",{modelId:a.id,displayName:a.displayName,error:b instanceof Error?b.message:b}),{success:!1,error:b instanceof Error?b.message:"An unexpected error occurred while updating the model"}}}async deleteModel(a){dc.debug("deleteModel: Entering method");try{if(!a)return dc.warn("deleteModel: Missing model ID"),{success:!1,error:"Model ID is required"};let b=await this.loadModels(),c=b.find(b=>b.id===a);if(!c)return dc.warn("deleteModel: Model not found",{modelId:a}),{success:!1,error:"Model not found"};dc.debug("deleteModel: Attempting to delete model",{modelId:a,displayName:c.displayName});let d=b.filter(b=>b.id!==a);return await (0,p.VH)(q.Zg.MODELS,d),dc.debug("deleteModel: Model deleted successfully",{modelId:a,displayName:c.displayName}),{success:!0}}catch(b){return dc.error("deleteModel: Failed to delete model",{modelId:a,error:b instanceof Error?b.message:b}),{success:!1,error:b instanceof Error?b.message:"An unexpected error occurred while deleting the model"}}}async listModels(){dc.debug("listModels: Entering method");try{let a=await this.loadModels();return dc.debug("listModels: Models loaded successfully",{count:a.length}),{success:!0,models:a}}catch(a){return dc.error("listModels: Failed to list models",{error:a instanceof Error?a.message:a}),{success:!1,error:a instanceof Error?a.message:"An unexpected error occurred while listing models"}}}async fetchProviderModels(a,b,c,d,e){dc.debug("fetchProviderModels: Fetching provider catalogue",{baseUrl:a,modelId:b,profileId:e,hasApiKey:!!d,searchTerm:c?`"${c}"`:"none"});try{let f,g=e?(0,s.vI)(e):void 0;if(e&&!g)throw Error("Unsupported provider discovery profile");if(g?.supportsModelDiscovery===!1)return[];b&&(f=(await this.loadModels()).find(a=>a.id===b));let h=g?.provider??f?.provider??function(a){if(/\.openai\.azure\.(?:com|us)(?:[/:]|$)|\.cognitiveservices\.azure\.(?:com|us)(?:[/:]|$)/i.test(a))return"azure";if(a.includes("openrouter.ai"))return"openrouter";if(a.includes("requesty.ai"))return"requesty";if(a.includes("api.x.ai"))return"xai";if(a.includes("generativelanguage.googleapis.com"))return"gemini";else if(a.includes("api.anthropic.com"))return"anthropic";else if(a.includes("api.mistral.ai"))return"mistral";else if(a.includes("api.openai.com"))return"openai";else if(function(a){try{let b=new URL(a);if("4000"===b.port||b.pathname.toLowerCase().includes("/litellm"))return!0}catch{if(a.includes(":4000")||a.toLowerCase().includes("/litellm"))return!0}return!1}(a))return"litellm";else return"ollama"}(a),i=g?.adapter??f?.adapter??"openai",j="gemini"===h&&"gemini"===i;if(!a.trim()&&!j)return dc.warn("Provider catalogue discovery requires a base URL",{provider:h,adapter:i,profileId:e}),[];let k=null;d&&d!==t.RJ?(k=await (0,u.GN)(d),dc.debug("Using directly supplied API key for provider fetch")):f?(k=await (0,u.GN)(f.ApiKey),dc.debug("Resolved stored API key for provider fetch")):b?dc.warn(`Model with ID ${b} not found for API key resolution`):dc.warn("Provider fetch will be unauthenticated");let l=(0,m.createHash)("sha256").update(k??"").digest("hex"),n={baseUrl:a,provider:h,adapter:i,profileId:g?.id??`${h}:${i}`,credentialFingerprint:l},o=H.get(n);if(o?dc.debug("Using cached models",{count:o.length,provider:h,adapter:i}):(dc.debug("Cache miss - fetching from provider",{provider:h,adapter:i}),o=await D(h,a,k,i),dc.debug("Provider catalogue fetch completed",{provider:h,adapter:i,count:o.length}),o.length>0&&H.set(n,o)),c&&c.trim()){let a=function(a,b){if(!b||0===b.trim().length)return a;let c=b.toLowerCase().trim();return a.filter(a=>{let b=a.id.toLowerCase(),d=a.name.toLowerCase();if(b.includes(c)||d.includes(c))return!0;let e=a=>{let b=0,d=0;for(;b<a.length&&d<c.length;)a[b]===c[d]&&d++,b++;return d===c.length};return e(b)||e(d)}).sort((a,b)=>{let d=a.id.toLowerCase(),e=b.id.toLowerCase(),f=a.name.toLowerCase(),g=b.name.toLowerCase(),h=d.includes(c)||f.includes(c),i=e.includes(c)||g.includes(c);return h&&!i?-1:!h&&i?1:a.id.length-b.id.length})}(o,c);return dc.debug("Search filtering applied",{searchTerm:`"${c}"`,originalCount:o.length,filteredCount:a.length}),a}return o}catch(c){throw dc.error("fetchProviderModels: Provider catalogue fetch failed",{baseUrl:a,modelId:b,profileId:e,message:c instanceof Error?c.message:"Unknown provider error"}),c}}async testModel(a){let{modelId:b,apiKey:c}=a,d=a.name,e=a.baseUrl,f=a.provider,g=a.adapter,h=null,i=null;if(c&&c!==t.RJ&&(i=await (0,u.GN)(c)),b&&(h=await this.getModel(b))&&(d=d||h.name,e=e||h.baseUrl,f=f||h.provider,g=g||h.adapter,i||(i=await (0,u.GN)(h.ApiKey))),!d)throw Error("Model name is required to run a test");if(!i)if("codex-cli"===g)i="";else throw Error("Could not resolve an API key for this model");let j=h?{...h,name:d,baseUrl:e??h.baseUrl,provider:f??h.provider,adapter:g??h.adapter}:void 0;return db({modelName:d,baseUrl:e,apiKey:i,provider:f,adapter:g,model:j})}async generateChatCompletion(a){let{modelIdentifier:b,messages:c,tools:d}=a;dc.debug("generateChatCompletion: Entering method",{modelIdentifier:b,messageCount:c?.length||0,hasTools:!!(d&&d.length>0)});try{let e=await this.loadModels(),f=b.trim().toLowerCase(),g=e.filter(a=>(a.displayName?.trim().toLowerCase()||"")===f);if(0===g.length&&(g=e.filter(a=>(a.name||"").trim().toLowerCase()===f)),0===g.length)return{success:!1,error:{message:`Model not found: model-${b}`,type:"invalid_request_error",code:"model_not_found",param:"model"},statusCode:404};if(g.length>1)return{success:!1,error:{message:`The identifier "${b}" matches more than one configured model. Address the model by its unique display name instead.`,type:"invalid_request_error",code:"model_ambiguous",param:"model"},statusCode:400};let h=g[0];if((0,s.vt)(h.adapter)&&d&&d.length>0)return{success:!1,error:{message:"Tool definitions are not supported for this model via the direct completion endpoint.",type:"invalid_request_error",code:"tools_not_supported_for_this_model",param:"tools"},statusCode:400};let i=await (0,u.GN)(h.ApiKey)||("codex-cli"!==h.adapter||h.ApiKey?.trim()?null:"");if(null===i)return{success:!1,error:{message:"Failed to resolve the API key for this model.",type:"api_error",code:"api_key_error",param:null},statusCode:500};let j="number"==typeof a.temperature&&Number.isFinite(a.temperature)?a.temperature:(0,s.VQ)(h.temperature,h.provider,h.adapter,h.name)??(void 0===h.temperature||""===h.temperature?0:void 0),k=(0,o.normalizeMaxTokens)(a.maxTokens)??(0,o.normalizeMaxTokens)(h.maxTokens),l=(0,c2.getCompletionAdapter)(h);dc.debug("generateChatCompletion: calling completion adapter",{adapter:h.adapter||"openai",model:h.name,temperature:j,maxTokens:k});let{completion:m,media:n}=await l.createCompletion({model:h,apiKey:i,messages:c,tools:d&&d.length>0?d:void 0,temperature:j,maxTokens:k,maxTurns:1});if(m&&"object"==typeof m&&"error"in m&&m.error){let a=m.error;return dc.warn("generateChatCompletion: provider returned an in-band error object",{code:a?.code,type:a?.type}),{success:!1,error:dd.sanitizeProviderError(a),statusCode:502}}if(!m?.choices?.[0])return{success:!1,error:{message:"Invalid response structure from provider: missing choices.",type:"api_error",code:"invalid_provider_response",param:null},statusCode:502};return{success:!0,completion:{...m,model:`model-${b}`},...n?.length?{media:n}:{}}}catch(a){if(dc.error("generateChatCompletion: provider call failed",{modelIdentifier:b,error:a instanceof Error?a.message:String(a)}),a instanceof n.Ay.APIError){let b=a.error,c=dd.sanitizeProviderError(b,a.message);return{success:!1,error:{message:c.message,type:"api_error"!==c.type?c.type:"string"==typeof a.type?a.type:"api_error",code:"provider_error"!==c.code?c.code:"string"==typeof a.code?a.code:"provider_error",param:c.param??("string"==typeof a.param?a.param:null)},statusCode:"number"==typeof a.status?a.status:500}}return{success:!1,error:{message:a instanceof Error?a.message:"Failed to generate completion",type:"api_error",code:"internal_error",param:null},statusCode:500}}}static sanitizeProviderError(a,b){let c=b||("string"==typeof a?.message?a.message:"")||"Provider returned an unspecified error.";b&&"string"==typeof a?.message&&a.message&&a.message!==b&&(c=`${b} - ${a.message}`);let d=a?.metadata;if(d){let a;if("string"==typeof d.raw)try{let b=JSON.parse(d.raw);a=b?.error?.message||b?.message||d.raw}catch{a=d.raw}else if(d.raw&&"object"==typeof d.raw){let b=d.raw;a=b.error?.message||b.message}let b=[];d.provider_name&&b.push(String(d.provider_name)),a&&b.push(a),b.length>0&&(c=`${c} (upstream: ${b.join(": ")})`)}return{message:c,type:"string"==typeof a?.type?a.type:"api_error",code:"string"==typeof a?.code?a.code:"provider_error",param:"string"==typeof a?.param?a.param:null}}constructor(){this.encryptApiKey=u.Rs,this.decryptApiKey=u.Tt,this.resolveAndDecryptApiKey=u.GN,this.isEncryptionConfigured=u.yg,this.isUserEncryptionEnabled=u.eS,this.setEncryptionKey=u.nB,this.initializeDefaultEncryption=u.hO}}let de=new dd},14597:(a,b,c)=>{a=c.nmd(a);var d=c(21170),e=b&&!b.nodeType&&b,f=e&&a&&!a.nodeType&&a,g=f&&f.exports===e&&d.process,h=function(){try{var a=f&&f.require&&f.require("util").types;if(a)return a;return g&&g.binding&&g.binding("util")}catch(a){}}();a.exports=h},14727:(a,b,c)=>{"use strict";c.r(b),c.d(b,{FlowExecutor:()=>a7});var d=c(82964),e=c(97328),f=c(70035),g=c.n(f),h=c(68680),i=c(55511),j=c.n(i),k=c(22605),l=c(87951);let m=(0,d.h)("execution/nodes/StartNode.ts");class n extends l.Yp{async prep(a,b){m.info("prep() started");let c=b?.properties?.promptTemplate||"";m.info("Extracted promptTemplate",{promptTemplateLength:c.length,promptTemplatePreview:c.length>100?c.substring(0,100)+"...":c});let d={nodeId:b?.id||"",nodeType:"start",systemPrompt:c};return m.info("prep() completed"),d}async execCore(a,b){m.info("execCore() started"),m.verbose("execCore() prepResult",JSON.stringify(a));let c={success:!0};return m.verbose("execCore() execResult",JSON.stringify(c)),m.info("execCore() completed"),c}async post(a,b,c,d){if(m.info("post() started"),m.verbose("post() inputs",JSON.stringify({prepResult:a,execResult:b,nodeParams:d})),h.Gv.ENABLE_EXECUTION_TRACKER&&Array.isArray(c.trackingInfo.nodeExecutionTracker)&&(c.trackingInfo.nodeExecutionTracker.push({nodeType:"StartNode",nodeId:d?.id||"unknown",nodeName:d?.properties?.name||"Start Node",timestamp:new Date().toISOString()}),m.info("Added StartNode tracking information")),a.systemPrompt){let b={role:"system",content:a.systemPrompt,id:crypto.randomUUID(),timestamp:Date.now()};c.messages.some(a=>"system"===a.role)||(c.messages.push(b),m.debug("Added system message",{contentLength:"string"==typeof b.content?b.content.length:"non-string content",contentPreview:"string"==typeof b.content&&b.content.length>50?b.content.substring(0,50)+"...":b.content}))}m.info("Successors object:",{hasSuccessors:!!this.successors,isMap:this.successors instanceof Map,type:typeof this.successors});let e=this.successors instanceof Map?Array.from(this.successors.keys()):Object.keys(this.successors||{});if(m.info("Actions:",{actionsCount:e.length,actions:e}),e.length>0){let a=e[0];return m.info(`post() completed, returning action: ${a}`),a}return m.info("post() completed, returning default action"),"default"}_clone(){return new n}}var o=c(14493),p=c(11540),q=c(46691),r=c(18836);let s=(0,d.h)("backend/utils/PromptRenderer");class t{async resolveChatMessageReferences(a,b,c){let d=(0,q.A$)(a),e=a;if(d.length>0){let f="",g=0;for(let e of d){if(f+=a.slice(g,e.index),g=e.index+e.fullMatch.length,"tool"===e.kind){f+=e.fullMatch;continue}f+=b.some(a=>{if(a.properties.boundServer!==e.server)return!1;let b=a.properties.enabledResources;return void 0===b||"all"===b||b.includes(e.name)})?await this.renderResourceBinding(e.server,e.name,c,e.fullMatch):e.fullMatch}f+=a.slice(g),e=f}return await (0,r.V)(e)}async renderPrompt(a,b,c){let d=c?.renderMode||"rendered",e=c?.includeConversationHistory||!1;s.info(`Rendering prompt for node ${b} in flow ${a}`,{renderMode:d,includeConversationHistory:e});let{prompt:f,excludeModelPrompt:g,excludeStartNodePrompt:h,excludeSystemPrompt:i}=await this.findNodePrompt(b,a,c?.flowSnapshot),j=c?.excludeModelPrompt!==void 0?c?.excludeModelPrompt:g,k=c?.excludeStartNodePrompt!==void 0?c?.excludeStartNodePrompt:h,l=c?.excludeSystemPrompt!==void 0?c?.excludeSystemPrompt:i;s.debug("Exclusion settings",{excludeModelPrompt:j,excludeStartNodePrompt:k,excludeSystemPrompt:l,fromOptions:{excludeModelPrompt:c?.excludeModelPrompt!==void 0,excludeStartNodePrompt:c?.excludeStartNodePrompt!==void 0,excludeSystemPrompt:c?.excludeSystemPrompt!==void 0}});let m="",n=null;if(!k){let b=await this.findStartNodePrompt(a,c?.flowSnapshot);b&&(s.debug("Adding start node prompt",{length:b.length}),m+=b+"\n\n")}if(!j){let d=await this.findModelPrompt(b,a,c?.flowSnapshot);d.prompt&&(s.debug("Adding model prompt",{modelId:d.modelId,length:d.prompt.length}),m+=d.prompt+"\n\n"),n=d.functionCallingSchema,d.reasoningSchema&&(m+=`Please use the following pattern to mark your reasoning: ${d.reasoningSchema}
@@ -439,7 +439,7 @@ _(Earlier turns compacted; full pre-summary history preserved at ${l}.)_`:"",u={
439
439
  ${j}${t}`,timestamp:n(),...void 0!==b.nodeId?{processNodeId:b.nodeId}:{}},v=[...p.leadingSystem,u,...p.preservedSubflow,...p.toKeep],w={artifactId:s,conversationId:b.conversationId,nodeId:b.nodeId,sourceStartId:p.toSummarize[0]?.id,sourceEndId:p.toSummarize.at(-1)?.id,sourceMessageCount:p.toSummarize.length,sourceDigest:b.sourceDigest,projectionDigest:b.projectionDigest,summaryText:String(u.content??""),summaryResourceUri:l,policyVersion:b.policyVersion,modelId:b.modelId,schemaVersion:1,createdAt:n()};return f.info("compactHistory: built wire summary artifact",{summarized:p.toSummarize.length,kept:p.toKeep.length,updatedPrevious:!!p.previousSummary,anchorUri:l??null}),{wireMessages:v,artifact:w,summarizedMessageIds:p.toSummarize.map(a=>a.id).filter(a=>!!a)}}},94505:a=>{"use strict";a.exports=Error},94917:(a,b,c)=>{"use strict";c.d(b,{F7:()=>g,lx:()=>i,mR:()=>h});var d=c(28461);let e=globalThis,f=e.__flujoElicitationContexts??(e.__flujoElicitationContexts=new Map);function g(a,b){f.set((0,d.workspaceCacheKey)(a),b)}function h(a){f.delete((0,d.workspaceCacheKey)(a))}function i(a){return f.get((0,d.workspaceCacheKey)(a))}},94941:(a,b)=>{"use strict";var c=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,d=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,e=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,f=/\\([\u000b\u0020-\u00ff])/g,g=/([\\"])/g,h=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function i(a){this.parameters=Object.create(null),this.type=a}b.format=function(a){if(!a||"object"!=typeof a)throw TypeError("argument obj is required");var b=a.parameters,c=a.type;if(!c||!h.test(c))throw TypeError("invalid type");var f=c;if(b&&"object"==typeof b)for(var i,j=Object.keys(b).sort(),k=0;k<j.length;k++){if(i=j[k],!e.test(i))throw TypeError("invalid parameter name");f+="; "+i+"="+function(a){var b=String(a);if(e.test(b))return b;if(b.length>0&&!d.test(b))throw TypeError("invalid parameter value");return'"'+b.replace(g,"\\$1")+'"'}(b[i])}return f},b.parse=function(a){if(!a)throw TypeError("argument string is required");var b,d,e,g="object"==typeof a?function(a){var b;if("function"==typeof a.getHeader?b=a.getHeader("content-type"):"object"==typeof a.headers&&(b=a.headers&&a.headers["content-type"]),"string"!=typeof b)throw TypeError("content-type header is missing from object");return b}(a):a;if("string"!=typeof g)throw TypeError("argument string is required to be a string");var j=g.indexOf(";"),k=-1!==j?g.slice(0,j).trim():g.trim();if(!h.test(k))throw TypeError("invalid media type");var l=new i(k.toLowerCase());if(-1!==j){for(c.lastIndex=j;d=c.exec(g);){if(d.index!==j)throw TypeError("invalid parameter format");j+=d[0].length,b=d[1].toLowerCase(),34===(e=d[2]).charCodeAt(0)&&-1!==(e=e.slice(1,-1)).indexOf("\\")&&(e=e.replace(f,"$1")),l.parameters[b]=e}if(j!==g.length)throw TypeError("invalid parameter format")}return l}},94984:(a,b,c)=>{"use strict";var d,e;Object.defineProperty(b,"__esModule",{value:!0}),b.reportTypeError=b.checkDataTypes=b.checkDataType=b.coerceAndCheckDataType=b.getJSONTypes=b.getSchemaTypes=b.DataType=void 0;let f=c(31812),g=c(32207),h=c(90682),i=c(97151),j=c(77595);function k(a){let b=Array.isArray(a)?a:a?[a]:[];if(b.every(f.isJSONType))return b;throw Error("type must be JSONType or JSONType[]: "+b.join(","))}(e=d||(b.DataType=d={}))[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong",b.getSchemaTypes=function(a){let b=k(a.type);if(b.includes("null")){if(!1===a.nullable)throw Error("type: null contradicts nullable: false")}else{if(!b.length&&void 0!==a.nullable)throw Error('"nullable" cannot be used without "type"');!0===a.nullable&&b.push("null")}return b},b.getJSONTypes=k,b.coerceAndCheckDataType=function(a,b){var c,e;let{gen:f,data:h,opts:j}=a,k=(c=b,(e=j.coerceTypes)?c.filter(a=>l.has(a)||"array"===e&&"array"===a):[]),m=b.length>0&&!(0===k.length&&1===b.length&&(0,g.schemaHasRulesForType)(a,b[0]));if(m){let c=n(b,h,j.strictNumbers,d.Wrong);f.if(c,()=>{k.length?function(a,b,c){let{gen:d,data:e,opts:f}=a,g=d.let("dataType",(0,i._)`typeof ${e}`),h=d.let("coerced",(0,i._)`undefined`);for(let a of("array"===f.coerceTypes&&d.if((0,i._)`${g} == 'object' && Array.isArray(${e}) && ${e}.length == 1`,()=>d.assign(e,(0,i._)`${e}[0]`).assign(g,(0,i._)`typeof ${e}`).if(n(b,e,f.strictNumbers),()=>d.assign(h,e))),d.if((0,i._)`${h} !== undefined`),c))(l.has(a)||"array"===a&&"array"===f.coerceTypes)&&function(a){switch(a){case"string":d.elseIf((0,i._)`${g} == "number" || ${g} == "boolean"`).assign(h,(0,i._)`"" + ${e}`).elseIf((0,i._)`${e} === null`).assign(h,(0,i._)`""`);return;case"number":d.elseIf((0,i._)`${g} == "boolean" || ${e} === null
440
440
  || (${g} == "string" && ${e} && ${e} == +${e})`).assign(h,(0,i._)`+${e}`);return;case"integer":d.elseIf((0,i._)`${g} === "boolean" || ${e} === null
441
441
  || (${g} === "string" && ${e} && ${e} == +${e} && !(${e} % 1))`).assign(h,(0,i._)`+${e}`);return;case"boolean":d.elseIf((0,i._)`${e} === "false" || ${e} === 0 || ${e} === null`).assign(h,!1).elseIf((0,i._)`${e} === "true" || ${e} === 1`).assign(h,!0);return;case"null":d.elseIf((0,i._)`${e} === "" || ${e} === 0 || ${e} === false`),d.assign(h,null);return;case"array":d.elseIf((0,i._)`${g} === "string" || ${g} === "number"
442
- || ${g} === "boolean" || ${e} === null`).assign(h,(0,i._)`[${e}]`)}}(a);d.else(),p(a),d.endIf(),d.if((0,i._)`${h} !== undefined`,()=>{d.assign(e,h),function({gen:a,parentData:b,parentDataProperty:c},d){a.if((0,i._)`${b} !== undefined`,()=>a.assign((0,i._)`${b}[${c}]`,d))}(a,h)})}(a,b,k):p(a)})}return m};let l=new Set(["string","number","integer","boolean","null"]);function m(a,b,c,e=d.Correct){let f,g=e===d.Correct?i.operators.EQ:i.operators.NEQ;switch(a){case"null":return(0,i._)`${b} ${g} null`;case"array":f=(0,i._)`Array.isArray(${b})`;break;case"object":f=(0,i._)`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":f=h((0,i._)`!(${b} % 1) && !isNaN(${b})`);break;case"number":f=h();break;default:return(0,i._)`typeof ${b} ${g} ${a}`}return e===d.Correct?f:(0,i.not)(f);function h(a=i.nil){return(0,i.and)((0,i._)`typeof ${b} == "number"`,a,c?(0,i._)`isFinite(${b})`:i.nil)}}function n(a,b,c,d){let e;if(1===a.length)return m(a[0],b,c,d);let f=(0,j.toHash)(a);if(f.array&&f.object){let a=(0,i._)`typeof ${b} != "object"`;e=f.null?a:(0,i._)`!${b} || ${a}`,delete f.null,delete f.array,delete f.object}else e=i.nil;for(let a in f.number&&delete f.integer,f)e=(0,i.and)(e,m(a,b,c,d));return e}b.checkDataType=m,b.checkDataTypes=n;let o={message:({schema:a})=>`must be ${a}`,params:({schema:a,schemaValue:b})=>"string"==typeof a?(0,i._)`{type: ${a}}`:(0,i._)`{type: ${b}}`};function p(a){let b=function(a){let{gen:b,data:c,schema:d}=a,e=(0,j.schemaRefOrVal)(a,d,"type");return{gen:b,keyword:"type",data:c,schema:d.type,schemaCode:e,schemaValue:e,parentSchema:d,params:{},it:a}}(a);(0,h.reportError)(b,o)}b.reportTypeError=p},95055:(a,b,c)=>{"use strict";c.d(b,{DB:()=>O,oW:()=>W,hz:()=>X,vu:()=>$,SR:()=>R,dQ:()=>Y,od:()=>V,qV:()=>Q,Re:()=>Z});var d=c(45146),e=c(68680),f=c(8012),g=c(82964),h=c(28461),i=c(23715),j=c(36200),k=c(4669),l=c(63455),m=c(42370);let n=new Map,o=new Map;function p(a){let b=`fallback:${a}`;n.set(b,(n.get(b)??0)+1)}function q(a,b){Number.isFinite(b)&&!(b<0)&&(n.set(`stage:${a}`,(n.get(`stage:${a}`)??0)+1),o.set(a,(o.get(a)??0)+b))}class r{constructor(a={}){this.entries=new Map,this.inFlight=new Map,this.generation=0,this.hits=0,this.misses=0,this.coalesced=0,this.evictions=0,this.maxEntries=Math.max(1,Math.floor(a.maxEntries??256)),this.ttlMilliseconds=Math.max(1,Math.floor(a.ttlMilliseconds??3e5)),this.now=a.now??Date.now}cacheKey(a){return JSON.stringify([a.workspaceId,a.provider,a.modelId,a.dimensions??null,a.query.normalize("NFKC").trim().replace(/\s+/gu," ").toLowerCase()])}get(a){let b=this.cacheKey(a),c=this.entries.get(b);if(c)return c.expiresAt<=this.now()?void this.entries.delete(b):(this.entries.delete(b),this.entries.set(b,c),c.vector)}set(a,b){let c=this.cacheKey(a);for(this.entries.delete(c),this.entries.set(c,{vector:[...b],expiresAt:this.now()+this.ttlMilliseconds});this.entries.size>this.maxEntries;){let a=this.entries.keys().next().value;if(void 0===a)break;this.entries.delete(a),this.evictions+=1}}async getOrCreate(a,b){let c=this.get(a);if(c)return this.hits+=1,c;let d=this.cacheKey(a),e=this.inFlight.get(d);if(e)return this.coalesced+=1,e;this.misses+=1;let f=this.generation,g=b().then(b=>(f===this.generation&&this.set(a,b),b)).finally(()=>{this.inFlight.get(d)===g&&this.inFlight.delete(d)});return this.inFlight.set(d,g),g}clear(){this.entries.clear(),this.inFlight.clear(),this.generation+=1,this.resetStats()}resetStats(){this.hits=0,this.misses=0,this.coalesced=0,this.evictions=0}stats(){return{hits:this.hits,misses:this.misses,coalesced:this.coalesced,evictions:this.evictions,size:this.entries.size,inFlight:this.inFlight.size}}}let s=new r;var t=c(64486),u=c(51030);let v=new Set(["no","not","never","none","neither","without","isn't","aren't","wasn't","weren't","doesn't","don't","didn't","cannot","can't","won't"]),w=[["allow","deny"],["allowed","denied"],["enable","disable"],["enabled","disabled"],["increase","decrease"],["increased","decreased"],["open","closed"],["present","absent"],["required","optional"],["true","false"],["yes","no"]],x=new Map(w.flatMap(([a,b])=>[[a,b],[b,a]])),y=new Set(w.flat());function z(a){return a.normalize("NFKC").toLocaleLowerCase().match(/[\p{L}\p{N}]+(?:['’][\p{L}]+)?/gu)??[]}function A(a,b){if(0===a.size&&0===b.size)return 1;let c=[...a].filter(a=>b.has(a)).length;return c/(a.size+b.size-c)}function B(a){return a.normalize("NFKC").toLocaleLowerCase().match(/\b(?:\d{4}-\d{1,2}-\d{1,2}|\d+(?:[.,]\d+)?)\b/g)??[]}function C(a){return a.filter(a=>!v.has(a)&&!y.has(a)&&!/^\d/.test(a))}let D={score(a,b,c){let d,e,f=z(a),g=z(b),h=new Set(f),i=new Set(g),j=A(h,i),k=(d=new Set(f.slice(0,-1).map((a,b)=>`${a}\u0000${f[b+1]}`)),e=new Set(g.slice(0,-1).map((a,b)=>`${a}\u0000${g[b+1]}`)),0===d.size&&0===e.size?+(f.length===g.length&&f[0]===g[0]):2*[...d].filter(a=>e.has(a)).length/(d.size+e.size)),l=Math.max(j,k,A(new Set(C(f)),new Set(C(g)))),m={similarity:l,tokenJaccard:j,bigramDice:k,detectorVersion:"lexical-v1"};if(l<Math.min(1,Math.max(0,c)))return{...m,relation:"unrelated",reason:"low_overlap"};let n=B(a),o=B(b);return n.length>0&&o.length>0&&JSON.stringify(n)!==JSON.stringify(o)?{...m,relation:"contradict",reason:"value_mismatch"}:f.some(a=>v.has(a))!==g.some(a=>v.has(a))?{...m,relation:"contradict",reason:"polarity_mismatch"}:[...h].some(a=>{let b=x.get(a);return void 0!==b&&i.has(b)})?{...m,relation:"contradict",reason:"antonym_mismatch"}:{...m,relation:"agree",reason:"high_overlap"}}};function E(a,b){let c=Math.max(0,b-a.createdAt)/864e5;return Math.min(1,Math.max(0,a.confidence))*2**(-c/30)}var F=c(18172),G=c(66720);let H=(0,g.h)("backend/services/enduringAgents/memoryKernel"),I=d.Ik({query:d.Yj().trim().max(2e3).optional(),kinds:d.YO(d.k5(i.g_)).optional(),scopes:d.YO(d.k5(i.su)).optional(),statuses:d.YO(d.k5(i.f5)).optional(),trust:d.YO(d.k5(i.bo)).optional(),coreOnly:d.zM().optional(),mode:d.k5(["lexical","hybrid"]).optional(),order:d.k5(["review"]).optional(),asOf:d.ai().int().nonnegative().optional(),limit:d.ai().int().min(1).max(200).optional()}).strict(),J=d.Ik({content:d.Yj().trim().min(1).max(1e5),confidence:d.ai().min(0).max(1).optional(),importance:d.ai().min(0).max(1).optional(),sourceRefs:d.YO(i.Pk).min(1).max(100),validFrom:d.ai().int().nonnegative().optional(),validUntil:d.ai().int().nonnegative().optional(),expectedUpdatedAt:d.ai().int().nonnegative().optional()}).strict();function K(a,b){if(b.executionAuthority&&"locked"===a.autonomyLevel)throw new j.TP("Automatic memory changes are turned off for this Persona.","PERSONA_LEARNING_DISABLED",{reason:"learning_disabled"})}function L(a){return JSON.stringify(a.sourceRefs.map(({observedAt:a,...b})=>b))}async function M(a,b,c,d){return(0,u.NK)(await (0,G.eD)(a),{kind:b,scope:c,content:d},u.jg)}function N(a,b,c){if(!a||a.personaId!==b)throw new j.SZ("MemoryItem",c);return a}function O(a,b,c,d){if("active"===b){if("external_untrusted"===a)throw new j.TP("Untrusted external content cannot be activated.");if("model_inference"===a&&!c.reviewed)throw new j.TP("Model-inferred memory requires explicit review before activation.");if("explicit_user"===a&&!d.includes("user_statement"))throw new j.TP("Explicit-user memory requires user-statement provenance.");if("verified_tool"===a&&!d.includes("tool_result"))throw new j.TP("Verified-tool memory requires tool-result provenance.")}}async function P(a,b,c){let d,f=Date.now(),g=await (0,t.pm)(),h=!!b.executionAuthority,m=h?"model_inference":a.trust,n=h?"candidate":a.status??"candidate",o=[...a.sourceRefs];"candidate"===n&&g.candidateExpiryDays>0&&(d=f+24*g.candidateExpiryDays*36e5),c&&!o.some(a=>"activity"===a.kind&&a.id===c)&&o.push({kind:"activity",id:c,observedAt:f}),O(m,n,b,o.map(a=>a.kind));let p=i.OZ.parse({schemaVersion:i.cq,id:a.id??(0,k.WK)("memory"),personaId:a.personaId,kind:a.kind,scope:a.scope,status:n,content:a.content,confidence:a.confidence,importance:a.importance,sourceRefs:(0,F.c)(o,{now:f,producer:h?"persona-flow-proposal":void 0,digestMaterial:a.content}),trust:m,...void 0!==a.validFrom?{validFrom:a.validFrom}:{},...void 0!==a.validUntil?{validUntil:a.validUntil}:{},...a.supersedes?.length?{supersedes:a.supersedes}:{},...a.conflictsWith?.length?{conflictsWith:[...new Set(a.conflictsWith)].sort()}:{},...void 0!==d?{expiresAt:d}:{},createdAt:f,updatedAt:f}),q=[...new Set(p.conflictsWith??[])].filter(a=>a!==p.id).sort(),r=q.length>0?await (0,G.eD)(p.personaId,{ids:q}):[];if(r.length!==q.length||r.some(a=>a.personaId!==p.personaId))throw new j.TP("conflictsWith must reference existing memories owned by this Persona.");let s=e.Gv.ENABLE_MEMORY_CONFLICT_SURFACING&&g.conflictDetectionEnabled?await (0,G.eD)(p.personaId,{statuses:["active"],kinds:[p.kind],scopes:[p.scope],limit:200,order:"updated_at"}):[],v=new Set(p.supersedes??[]),w=new Map([...r,...s.filter(a=>a.id!==p.id&&!v.has(a.id)&&"contradict"===D.score(a.content,p.content,g.conflictSimilarityThreshold).relation)].map(a=>[a.id,a])),x=[...w.keys()].sort(),y=x.length>0?{...p,conflictsWith:x}:(()=>{let{conflictsWith:a,...b}=p;return b})(),z=await (0,G.Xc)(p.personaId,p.id);if(z){if(z.personaId!==p.personaId||z.kind!==p.kind||z.scope!==p.scope||z.status!==p.status||z.content!==p.content||z.confidence!==p.confidence||z.importance!==p.importance||z.trust!==p.trust||L(z)!==L(p)||JSON.stringify(z.supersedes??[])!==JSON.stringify(p.supersedes??[]))throw new j.TP(`MemoryItem ${JSON.stringify(p.id)} already exists.`);if(0===x.length)return z}if(!z&&0===x.length&&u.jg.enabled&&!b.skipNearDuplicateMerge&&!p.supersedes?.length){let a=await M(p.personaId,p.kind,p.scope,p.content);if(a){let{candidate:c,similarity:d}=a,e=await (0,G.AN)((0,l._q)(c,{now:f,incomingTrust:p.trust,incomingSourceRefs:p.sourceRefs,canUpgradeTrust:a=>{try{return O(a,c.status,b,p.sourceRefs.map(a=>a.kind)),!0}catch{return!1}}}));return H.debug("Dedup merged near-duplicate",{survivorId:c.id,similarity:d.toFixed(3),kind:p.kind,scope:p.scope}),e}}let A=z??await (0,G.AN)((()=>{let{conflictsWith:a,...b}=y;return b})());for(let a of w.values()){let b=[...new Set([...a.conflictsWith??[],p.id])].sort();JSON.stringify(b)!==JSON.stringify(a.conflictsWith??[])&&await (0,G.AN)({...a,conflictsWith:b,updatedAt:Math.max(Date.now(),a.updatedAt+1)})}if(x.length>0){let a=[...new Set([...A.conflictsWith??[],...x])].sort();A=await (0,G.AN)({...A,conflictsWith:a,updatedAt:Math.max(Date.now(),A.updatedAt+1)})}return A}async function Q(a,b={}){let c=i.Q$.parse(a);return(0,j.g7)(c.personaId,b,({persona:a,activity:d})=>(K(a,b),P(c,b,d?.id)))}async function R(a,b){return i.Qy.parse(a),i.Qy.parse(b),N(await (0,G.Xc)(a,b),a,b)}function S(a=u.ks){return{scores:new Map,floor:a,lexicalWeight:1,semanticWeight:0}}function T(a,b=u.ks){return p(a),H.debug("Semantic recall unavailable; using lexical fallback.",{reason:a}),S(b)}async function U(a,b,d){if(!b?.trim())return T("empty_query");let e=await (0,t.pm)();if(!e.semanticRecallEnabled)return T("disabled",e.semanticFloor);if(!e.semanticEmbeddingModelId)return T("missing_model",e.semanticFloor);let[{modelService:g},{getEmbeddingProvider:i}]=await Promise.all([Promise.resolve().then(c.bind(c,14493)),Promise.resolve().then(c.bind(c,49062))]),j=await g.getModel(e.semanticEmbeddingModelId);if(!j)return T("model_not_found",e.semanticFloor);if(!(0,f.VP)(j.adapter))return T("unsupported_adapter",e.semanticFloor);try{let c=performance.now(),f=await s.getOrCreate({workspaceId:(0,h.getCurrentWorkspace)(),provider:j.adapter,modelId:j.name,dimensions:e.semanticEmbeddingDimensions,query:b},async()=>{let a=await i().embed(j,{modelId:j.name,text:b,dimensions:e.semanticEmbeddingDimensions});if(0===a.vector.length||a.vector.length!==a.dimensions||!a.vector.every(Number.isFinite))throw Error("Embedding provider returned an invalid query vector.");return a.vector});q("query_embedding",performance.now()-c);let g=performance.now(),k=await (0,m.rn)(a);q("sidecar_load",performance.now()-g),0===k.length&&p("missing_sidecar");let l=performance.now(),n=(0,m.NH)(a,d,k,f,j.name);return q("cosine_scoring",performance.now()-l),{scores:n,floor:e.semanticFloor,lexicalWeight:e.lexicalWeight,semanticWeight:e.semanticWeight}}catch{return T("embedding_failure",e.semanticFloor)}}async function V(a,b={}){var c,d,f;let g;i.Qy.parse(a);let h=I.parse(b),k=await (0,G.getPersona)(a);if(!k)throw new j.SZ("Persona",a);let l=new Set(k.coreMemoryItemIds??[]),m=(c=h.query,[...new Set(c?.toLocaleLowerCase().match(/[\p{L}\p{N}_-]{2,}/gu)??[])]),o=h.asOf??Date.now(),p="review"===h.order,r=h.limit??(p?20:50),s=performance.now(),t=await (0,G.eD)(a,{statuses:p?["candidate"]:h.statuses??["active"],kinds:h.kinds?.length?h.kinds:void 0,scopes:h.scopes?.length?h.scopes:void 0,trust:h.trust?.length?h.trust:void 0,validAt:o,ids:h.coreOnly?[...l]:void 0,...!p&&0===m.length?{limit:r,order:"memory_relevance",coreIds:[...l]}:{}});q("item_load",performance.now()-s);let v=performance.now();if(p)g=t.filter(a=>"candidate"===a.status&&void 0===a.reviewedAt&&(void 0===a.expiresAt||a.expiresAt>o)&&(0===m.length||m.some(b=>a.content.toLocaleLowerCase().includes(b)))).sort((a,b)=>E(b,o)-E(a,o)||b.createdAt-a.createdAt||a.id.localeCompare(b.id)).slice(0,r).map(a=>({item:a,core:l.has(a.id),score:E(a,o)}));else{let b="lexical"===h.mode?S():await U(a,h.query,t),c=t.map(a=>{let c=m.some(b=>a.content.toLocaleLowerCase().includes(b));return{item:a,core:l.has(a.id),lexicalHit:c,semantic:b.scores.get(a.id)}}),e=c.filter(({lexicalHit:a,semantic:c})=>0===m.length||(0,u.pV)(a,c,b.floor));d=c.length,f=e.length,Number.isFinite(d)&&Number.isFinite(f)&&(n.set("candidates:before",(n.get("candidates:before")??0)+d),n.set("candidates:after",(n.get("candidates:after")??0)+f));let i={...u.nj,lexicalWeight:b.lexicalWeight,semanticWeight:b.semanticWeight},j=e.map(({item:a,core:b,semantic:c})=>({item:a,core:b,score:(0,u.Fv)({item:a,terms:m,core:b,asOf:o,semantic:c,weights:i})}));g=0===m.length?j:j.sort((a,b)=>b.score-a.score||b.item.updatedAt-a.item.updatedAt||a.item.id.localeCompare(b.item.id)).slice(0,r)}if(q("filter_rank",performance.now()-v),!e.Gv.ENABLE_MEMORY_CONFLICT_SURFACING)return g;let w=[...new Set(g.flatMap(a=>a.item.conflictsWith??[]))];if(0===w.length)return g;let x=new Map((await (0,G.eD)(a,{ids:w})).map(a=>[a.id,a]));return g.map(b=>{let c=(b.item.conflictsWith??[]).filter(a=>a!==b.item.id).map(a=>x.get(a)).filter(b=>b?.personaId===a).sort((a,b)=>Number("active"===b.status)-Number("active"===a.status)||b.updatedAt-a.updatedAt||a.id.localeCompare(b.id)).slice(0,5).map(a=>({id:a.id,content:a.content,kind:a.kind,scope:a.scope,status:a.status,trust:a.trust,confidence:a.confidence,importance:a.importance,updatedAt:a.updatedAt}));return c.length>0?{...b,conflicts:c}:b})}async function W(a,b,c,d={}){i.Qy.parse(a),i.Qy.parse(b);let e=J.parse(c);return(0,j.g7)(a,d,async({persona:c,activity:f,updatePersona:g})=>{K(c,d);let h=N(await (0,G.Xc)(a,b),a,b);if("forgotten"===h.status)throw new j.TP("Forgotten memory cannot be corrected in place.");if(void 0!==e.expectedUpdatedAt&&e.expectedUpdatedAt!==h.updatedAt)throw new j.TP("Memory changed since it was inspected.","memory_changed",{currentUpdatedAt:h.updatedAt});let i=!!d.executionAuthority,k=await P({personaId:a,kind:h.kind,scope:h.scope,status:i?"candidate":"active",content:e.content,confidence:e.confidence??h.confidence,importance:e.importance??h.importance,sourceRefs:e.sourceRefs,trust:i?"model_inference":"explicit_user",...void 0!==e.validFrom?{validFrom:e.validFrom}:{},...void 0!==e.validUntil?{validUntil:e.validUntil}:{},supersedes:[h.id]},d,f?.id);return"active"!==k.status||(c.coreMemoryItemIds?.includes(h.id)&&await g({...c,coreMemoryItemIds:(c.coreMemoryItemIds??[]).map(a=>a===h.id?k.id:a),updatedAt:Math.max(Date.now(),c.updatedAt+1)}),await (0,G.AN)({...h,status:"superseded",updatedAt:Math.max(Date.now(),h.updatedAt+1)})),k})}async function X(a,b,c={}){return(0,j.g7)(a,c,async({persona:d,updatePersona:e})=>{K(d,c);let f=N(await (0,G.Xc)(a,b),a,b);return"forgotten"===f.status?f:(d.coreMemoryItemIds?.includes(f.id)&&await e({...d,coreMemoryItemIds:d.coreMemoryItemIds.filter(a=>a!==f.id),updatedAt:Math.max(Date.now(),d.updatedAt+1)}),(0,G.AN)({...f,status:"forgotten",updatedAt:Math.max(Date.now(),f.updatedAt+1)}))})}async function Y(a,b,c={}){return(0,j.g7)(a,c,async({persona:d,updatePersona:e})=>{K(d,c);let f=N(await (0,G.Xc)(a,b),a,b);if("active"!==f.status||"explicit_user"!==f.trust&&"verified_tool"!==f.trust)throw new j.TP("Core memory requires active explicit-user or verified-tool trust.");let g=[...new Set([...d.coreMemoryItemIds??[],f.id])],h=await (0,G.lc)(d.roleVersionId),i=h?.defaults?.memory?.coreMemoryMaxItems??32;if(g.length>i)throw new j.TP(`Core memory is limited to ${i} items.`,"core_memory_capacity",{maxCoreItems:i,currentCoreItems:d.coreMemoryItemIds?.length??0});g.length!==(d.coreMemoryItemIds??[]).length&&await e({...d,coreMemoryItemIds:g,updatedAt:Math.max(Date.now(),d.updatedAt+1)});let k=new Map((await (0,G.eD)(a,{ids:g})).map(a=>[a.id,a]));return g.map(a=>k.get(a)).filter(a=>!!a)})}async function Z(a,b,c={}){return(0,j.g7)(a,c,async({persona:d,updatePersona:e})=>{K(d,c),N(await (0,G.Xc)(a,b),a,b);let f=(d.coreMemoryItemIds??[]).filter(a=>a!==b);f.length!==(d.coreMemoryItemIds??[]).length&&await e({...d,coreMemoryItemIds:f,updatedAt:Math.max(Date.now(),d.updatedAt+1)});let g=new Map((await (0,G.eD)(a,{ids:f})).map(a=>[a.id,a]));return f.map(a=>g.get(a)).filter(a=>!!a)})}async function $(a){let b=await (0,G.getPersona)(a);if(!b)throw new j.SZ("Persona",a);let c=b.coreMemoryItemIds??[];if(0===c.length)return[];let d=new Map((await (0,G.eD)(a,{ids:c})).map(a=>[a.id,a]));return c.map(a=>d.get(a)).filter(a=>!!a)}},95095:(a,b,c)=>{"use strict";let d=c(7344),e=c(31825);class f extends d{#cb=null;#cc=null;constructor(a,b={}){super(b),this.#cb=a,this.#cc=b}dispatch(a,b){let c=new e({...a,retryOptions:this.#cc},{dispatch:this.#cb.dispatch.bind(this.#cb),handler:b});return this.#cb.dispatch(a,c)}close(){return this.#cb.close()}destroy(){return this.#cb.destroy()}}a.exports=f},95195:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),b.GoogleAuth=b.GoogleAuthExceptionMessages=void 0;let d=c(79646),e=c(29021),f=c(32184),g=c(95699),h=c(21820),i=c(33873),j=c(57784),k=c(73926),l=c(24587),m=c(78072),n=c(29114),o=c(18536),p=c(70973),q=c(76808),r=c(9419),s=c(84687),t=c(22961),u=c(98953),v=c(96451);b.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:"Unable to detect a Project Id in the current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_CREDENTIALS_FOUND:"Unable to find credentials in current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:"Unable to detect a Universe Domain in the current environment.\nTo learn more about Universe Domain retrieval, visit: \nhttps://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"};class w{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#cd=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(a={}){if(this._cachedProjectId=a.projectId||null,this.cachedCredential=a.authClient||null,this.keyFilename=a.keyFilename||a.keyFile,this.scopes=a.scopes,this.clientOptions=a.clientOptions||{},this.jsonContent=a.credentials||null,this.apiKey=a.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw RangeError(b.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);a.universeDomain&&(this.clientOptions.universeDomain=a.universeDomain)}setGapicJWTValues(a){a.defaultServicePath=this.defaultServicePath,a.useJWTAccessWithScope=this.useJWTAccessWithScope,a.defaultScopes=this.defaultScopes}getProjectId(a){if(!a)return this.getProjectIdAsync();this.getProjectIdAsync().then(b=>a(null,b),a)}async getProjectIdOptional(){try{return await this.getProjectId()}catch(a){if(a instanceof Error&&a.message===b.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw a}}async findAndCacheProjectId(){let a=null;if(a||=await this.getProductionProjectId(),a||=await this.getFileProjectId(),a||=await this.getDefaultServiceProjectId(),a||=await this.getGCEProjectId(),a||=await this.getExternalAccountClientProjectId())return this._cachedProjectId=a,a;throw Error(b.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let a;try{a=await g.universe("universe-domain"),a||=s.DEFAULT_UNIVERSE}catch(b){if(b&&b?.response?.status===404)a=s.DEFAULT_UNIVERSE;else throw b}return a}async getUniverseDomain(){let a=(0,v.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{a??=(await this.getClient()).universeDomain}catch{a??=s.DEFAULT_UNIVERSE}return a}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(a={},b){let c;if("function"==typeof a?b=a:c=a,!b)return this.getApplicationDefaultAsync(c);this.getApplicationDefaultAsync(c).then(a=>b(null,a.credential,a.projectId),b)}async getApplicationDefaultAsync(a={}){let c;if(this.cachedCredential)return await this.#ce(this.cachedCredential,null);if((c=await this._tryGetApplicationCredentialsFromEnvironmentVariable(a))||(c=await this._tryGetApplicationCredentialsFromWellKnownFile(a)))return c instanceof n.JWT?c.scopes=this.scopes:c instanceof r.BaseExternalAccountClient&&(c.scopes=this.getAnyScopes()),await this.#ce(c);if(await this._checkIsGCE())return a.scopes=this.getAnyScopes(),await this.#ce(new k.Compute(a));throw Error(b.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async #ce(a,b=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let c=await this.getProjectIdOptional();return b&&(a.quotaProjectId=b),this.cachedCredential=a,{credential:a,projectId:c}}async _checkIsGCE(){return void 0===this.checkIsGCE&&(this.checkIsGCE=g.getGCPResidency()||await g.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(a){let b=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!b||0===b.length)return null;try{return await this._getApplicationCredentialsFromFilePath(b,a)}catch(a){throw a instanceof Error&&(a.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${a.message}`),a}}async _tryGetApplicationCredentialsFromWellKnownFile(a){let b=process.env.CLOUDSDK_CONFIG;if(!b)if(this._isWindows())process.env.APPDATA&&(b=i.join(process.env.APPDATA,"gcloud"));else{let a=process.env.HOME;a&&(b=i.join(a,".config","gcloud"))}if(!b)return null;let c=i.join(b,"application_default_credentials.json");return e.existsSync(c)?await this._getApplicationCredentialsFromFilePath(c,a):null}async _getApplicationCredentialsFromFilePath(a,b={}){if(!a||0===a.length)throw Error("The file path is invalid.");try{if(a=e.realpathSync(a),!e.lstatSync(a).isFile())throw Error()}catch(b){throw b instanceof Error&&(b.message=`The file at ${a} does not exist, or it is not a file. ${b.message}`),b}let c=e.createReadStream(a);return this.fromStream(c,b)}fromImpersonatedJSON(a){if(!a)throw Error("Must pass in a JSON object containing an impersonated refresh token");if(a.type!==p.IMPERSONATED_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${p.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!a.source_credentials)throw Error("The incoming JSON object does not contain a source_credentials field");if(!a.service_account_impersonation_url)throw Error("The incoming JSON object does not contain a service_account_impersonation_url field");let b=this.fromJSON(a.source_credentials);if(a.service_account_impersonation_url?.length>256)throw RangeError(`Target principal is too long: ${a.service_account_impersonation_url}`);let c=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(a.service_account_impersonation_url)?.groups?.target;if(!c)throw RangeError(`Cannot extract target principal from ${a.service_account_impersonation_url}`);let d=(this.scopes||a.scopes||this.defaultScopes)??[];return new p.Impersonated({...a,sourceClient:b,targetPrincipal:c,targetScopes:Array.isArray(d)?d:[d]})}fromJSON(a,b={}){let c,d=(0,v.originalOrCamelOptions)(b).get("universe_domain");return a.type===o.USER_REFRESH_ACCOUNT_TYPE?(c=new o.UserRefreshClient(b)).fromJSON(a):a.type===p.IMPERSONATED_ACCOUNT_TYPE?c=this.fromImpersonatedJSON(a):a.type===r.EXTERNAL_ACCOUNT_TYPE?(c=q.ExternalAccountClient.fromJSON({...a,...b})).scopes=this.getAnyScopes():a.type===t.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?c=new t.ExternalAccountAuthorizedUserClient({...a,...b}):a.type===u.GDCH_SERVICE_ACCOUNT_TYPE?(c=new u.GdchClient(b)).fromJSON(a):(b.scopes=this.scopes,c=new n.JWT(b),this.setGapicJWTValues(c),c.fromJSON(a)),d&&(c.universeDomain=d),c}_cacheClientFromJSON(a,b){let c=this.fromJSON(a,b);return this.jsonContent=a,this.cachedCredential=c,c}fromStream(a,b={},c){let d={};if("function"==typeof b?c=b:d=b,!c)return this.fromStreamAsync(a,d);this.fromStreamAsync(a,d).then(a=>c(null,a),c)}fromStreamAsync(a,b){return new Promise((c,d)=>{if(!a)throw Error("Must pass in a stream containing the Google auth settings.");let e=[];a.setEncoding("utf8").on("error",d).on("data",a=>e.push(a)).on("end",()=>{try{try{let a=JSON.parse(e.join("")),d=this._cacheClientFromJSON(a,b);return c(d)}catch(b){if(!this.keyFilename)throw b;let a=new n.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=a,this.setGapicJWTValues(a),c(a)}}catch(a){return d(a)}})})}fromAPIKey(a,b={}){return new n.JWT({...b,apiKey:a})}_isWindows(){let a=h.platform();return!!a&&!!(a.length>=3)&&"win"===a.substring(0,3).toLowerCase()}async getDefaultServiceProjectId(){return new Promise(a=>{(0,d.exec)("gcloud config config-helper --format json",(b,c)=>{if(!b&&c)try{let b=JSON.parse(c).configuration.properties.core.project;a(b);return}catch(a){}a(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let a=await this.getClient();if(a&&a.projectId)return a.projectId}let a=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return a?a.projectId:null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==r.EXTERNAL_ACCOUNT_TYPE)return null;let a=await this.getClient();return await a.getProjectId()}async getGCEProjectId(){try{return await g.project("project-id")}catch(a){return null}}getCredentials(a){if(!a)return this.getCredentialsAsync();this.getCredentialsAsync().then(b=>a(null,b),a)}async getCredentialsAsync(){let a=await this.getClient();if(a instanceof p.Impersonated)return{client_email:a.getTargetPrincipal()};if(a instanceof r.BaseExternalAccountClient){let b=a.getServiceAccountEmail();if(b)return{client_email:b,universe_domain:a.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[a,b]=await Promise.all([g.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:a,universe_domain:b}}throw Error(b.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#cd=this.#cd||this.#cf();try{let a=await this.#cd;if(a instanceof u.GdchClient&&!a.apiAudience){let b=this.clientOptions,c=b.apiEndpoint||b.servicePath;if(c){let b=c.startsWith("http")?"":"https://",d=`${b}${c}`.replace(/\/+$/,""),e=a.createWithGdchAudience(d);return this.cachedCredential=e,e}}return a}finally{this.#cd=null}}async #cf(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let a=i.resolve(this.keyFilename),b=e.createReadStream(a);return await this.fromStreamAsync(b,this.clientOptions)}if(this.apiKey){let a=await this.fromAPIKey(this.apiKey,this.clientOptions);a.scopes=this.scopes;let{credential:b}=await this.#ce(a);return b}{let{credential:a}=await this.getApplicationDefaultAsync(this.clientOptions);return a}}async getIdTokenClient(a){let b=await this.getClient();if(!("fetchIdToken"in b))throw Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new l.IdTokenClient({targetAudience:a,idTokenProvider:b})}async getAccessToken(){let a=await this.getClient();return(await a.getAccessToken()).token}async getRequestHeaders(a){return(await this.getClient()).getRequestHeaders(a)}async authorizeRequest(a={}){let b=a.url,c=await this.getClient(),d=await c.getRequestHeaders(b);return a.headers=f.Gaxios.mergeHeaders(a.headers,d),a}async fetch(...a){return(await this.getClient()).fetch(...a)}async request(a){return(await this.getClient()).request(a)}getEnv(){return(0,m.getEnv)()}async sign(a,b){let c=await this.getClient(),d=await this.getUniverseDomain();if(b=b||`https://iamcredentials.${d}/v1/projects/-/serviceAccounts/`,c instanceof p.Impersonated)return(await c.sign(a)).signedBlob;let e=(0,j.createCrypto)();if(c instanceof n.JWT&&c.key)return await e.sign(c.key,a);let f=await this.getCredentials();if(!f.client_email)throw Error("Cannot sign data without `client_email`.");return this.signBlob(e,f.client_email,a,b)}async signBlob(a,b,c,d){let e=new URL(d+`${b}:signBlob`);return(await this.request({method:"POST",url:e.href,data:{payload:a.encodeBase64StringUtf8(c)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}b.GoogleAuth=w},95296:a=>{a.exports=function(){this.__data__=[],this.size=0}},95314:function(a,b,c){"use strict";var d;let e=(this&&this.__importDefault||function(a){return a&&a.__esModule?a:{default:a}})(c(30073));function f(a){return new e.default(a)}(d=f||(f={})).HttpsProxyAgent=e.default,d.prototype=e.default.prototype,a.exports=f},95570:(a,b,c)=>{"use strict";let d,{Duplex:e}=c(27910),{randomFillSync:f}=c(55511),{types:{isUint8Array:g}}=c(28354),h=c(24869),{EMPTY_BUFFER:i,kWebSocket:j,NOOP:k}=c(52712),{isBlob:l,isValidStatusCode:m}=c(32464),{mask:n,toBuffer:o}=c(15596),p=Symbol("kByteLength"),q=Buffer.alloc(4),r=8192;class s{constructor(a,b,c){this._extensions=b||{},c&&(this._generateMask=c,this._maskBuffer=Buffer.alloc(4)),this._socket=a,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=k,this[j]=void 0}static frame(a,b){let c,e,g=!1,h=2,i=!1;b.mask&&(c=b.maskBuffer||q,b.generateMask?b.generateMask(c):(8192===r&&(void 0===d&&(d=Buffer.alloc(8192)),f(d,0,8192),r=0),c[0]=d[r++],c[1]=d[r++],c[2]=d[r++],c[3]=d[r++]),i=(c[0]|c[1]|c[2]|c[3])==0,h=6),"string"==typeof a?e=(!b.mask||i)&&void 0!==b[p]?b[p]:(a=Buffer.from(a)).length:(e=a.length,g=b.mask&&b.readOnly&&!i);let j=e;e>=65536?(h+=8,j=127):e>125&&(h+=2,j=126);let k=Buffer.allocUnsafe(g?e+h:h);return(k[0]=b.fin?128|b.opcode:b.opcode,b.rsv1&&(k[0]|=64),k[1]=j,126===j?k.writeUInt16BE(e,2):127===j&&(k[2]=k[3]=0,k.writeUIntBE(e,4,6)),b.mask)?(k[1]|=128,k[h-4]=c[0],k[h-3]=c[1],k[h-2]=c[2],k[h-1]=c[3],i)?[k,a]:g?(n(a,c,k,h,e),[k]):(n(a,c,a,0,e),[k,a]):[k,a]}close(a,b,c,d){let e;if(void 0===a)e=i;else if("number"==typeof a&&m(a))if(void 0!==b&&b.length){let c=Buffer.byteLength(b);if(c>123)throw RangeError("The message must not be greater than 123 bytes");if((e=Buffer.allocUnsafe(2+c)).writeUInt16BE(a,0),"string"==typeof b)e.write(b,2);else if(g(b))e.set(b,2);else throw TypeError("Second argument must be a string or a Uint8Array")}else(e=Buffer.allocUnsafe(2)).writeUInt16BE(a,0);else throw TypeError("First argument must be a valid error code number");let f={[p]:e.length,fin:!0,generateMask:this._generateMask,mask:c,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,e,!1,f,d]):this.sendFrame(s.frame(e,f),d)}ping(a,b,c){let d,e;if("string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),d>125)throw RangeError("The data size must not be greater than 125 bytes");let f={[p]:d,fin:!0,generateMask:this._generateMask,mask:b,maskBuffer:this._maskBuffer,opcode:9,readOnly:e,rsv1:!1};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,!1,f,c]):this.getBlobData(a,!1,f,c):0!==this._state?this.enqueue([this.dispatch,a,!1,f,c]):this.sendFrame(s.frame(a,f),c)}pong(a,b,c){let d,e;if("string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),d>125)throw RangeError("The data size must not be greater than 125 bytes");let f={[p]:d,fin:!0,generateMask:this._generateMask,mask:b,maskBuffer:this._maskBuffer,opcode:10,readOnly:e,rsv1:!1};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,!1,f,c]):this.getBlobData(a,!1,f,c):0!==this._state?this.enqueue([this.dispatch,a,!1,f,c]):this.sendFrame(s.frame(a,f),c)}send(a,b,c){let d,e,f=this._extensions[h.extensionName],g=b.binary?2:1,i=b.compress;"string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),this._firstFragment?(this._firstFragment=!1,i&&f&&f.params[f._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=d>=f._threshold),this._compress=i):(i=!1,g=0),b.fin&&(this._firstFragment=!0);let j={[p]:d,fin:b.fin,generateMask:this._generateMask,mask:b.mask,maskBuffer:this._maskBuffer,opcode:g,readOnly:e,rsv1:i};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,this._compress,j,c]):this.getBlobData(a,this._compress,j,c):0!==this._state?this.enqueue([this.dispatch,a,this._compress,j,c]):this.dispatch(a,this._compress,j,c)}getBlobData(a,b,c,d){this._bufferedBytes+=c[p],this._state=2,a.arrayBuffer().then(a=>{if(this._socket.destroyed){let a=Error("The socket was closed while the blob was being read");process.nextTick(t,this,a,d);return}this._bufferedBytes-=c[p];let e=o(a);b?this.dispatch(e,b,c,d):(this._state=0,this.sendFrame(s.frame(e,c),d),this.dequeue())}).catch(a=>{process.nextTick(u,this,a,d)})}dispatch(a,b,c,d){if(!b)return void this.sendFrame(s.frame(a,c),d);let e=this._extensions[h.extensionName];this._bufferedBytes+=c[p],this._state=1,e.compress(a,c.fin,(a,b)=>{this._socket.destroyed?t(this,Error("The socket was closed while data was being compressed"),d):(this._bufferedBytes-=c[p],this._state=0,c.readOnly=!1,this.sendFrame(s.frame(b,c),d),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){let a=this._queue.shift();this._bufferedBytes-=a[3][p],Reflect.apply(a[0],this,a.slice(1))}}enqueue(a){this._bufferedBytes+=a[3][p],this._queue.push(a)}sendFrame(a,b){2===a.length?(this._socket.cork(),this._socket.write(a[0]),this._socket.write(a[1],b),this._socket.uncork()):this._socket.write(a[0],b)}}function t(a,b,c){"function"==typeof c&&c(b);for(let c=0;c<a._queue.length;c++){let d=a._queue[c],e=d[d.length-1];"function"==typeof e&&e(b)}}function u(a,b,c){t(a,b,c),a.onerror(b)}a.exports=s},95685:(a,b,c)=>{var d=c(38534),e=c(27934),f=c(47702),g={};g["[object Float32Array]"]=g["[object Float64Array]"]=g["[object Int8Array]"]=g["[object Int16Array]"]=g["[object Int32Array]"]=g["[object Uint8Array]"]=g["[object Uint8ClampedArray]"]=g["[object Uint16Array]"]=g["[object Uint32Array]"]=!0,g["[object Arguments]"]=g["[object Array]"]=g["[object ArrayBuffer]"]=g["[object Boolean]"]=g["[object DataView]"]=g["[object Date]"]=g["[object Error]"]=g["[object Function]"]=g["[object Map]"]=g["[object Number]"]=g["[object Object]"]=g["[object RegExp]"]=g["[object Set]"]=g["[object String]"]=g["[object WeakMap]"]=!1,a.exports=function(a){return f(a)&&e(a.length)&&!!g[d(a)]}},95699:function(a,b,c){"use strict";let d;var e,f=this&&this.__createBinding||(Object.create?function(a,b,c,d){void 0===d&&(d=c);var e=Object.getOwnPropertyDescriptor(b,c);(!e||("get"in e?!b.__esModule:e.writable||e.configurable))&&(e={enumerable:!0,get:function(){return b[c]}}),Object.defineProperty(a,d,e)}:function(a,b,c,d){void 0===d&&(d=c),a[d]=b[c]}),g=this&&this.__setModuleDefault||(Object.create?function(a,b){Object.defineProperty(a,"default",{enumerable:!0,value:b})}:function(a,b){a.default=b}),h=this&&this.__importStar||(e=function(a){return(e=Object.getOwnPropertyNames||function(a){var b=[];for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[b.length]=c);return b})(a)},function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c=e(a),d=0;d<c.length;d++)"default"!==c[d]&&f(b,a,c[d]);return g(b,a),b}),i=this&&this.__exportStar||function(a,b){for(var c in a)"default"===c||Object.prototype.hasOwnProperty.call(b,c)||f(b,a,c)};Object.defineProperty(b,"__esModule",{value:!0}),b.gcpResidencyCache=b.METADATA_SERVER_DETECTION=b.HEADERS=b.HEADER_VALUE=b.HEADER_NAME=b.SECONDARY_HOST_ADDRESS=b.HOST_ADDRESS=b.BASE_PATH=void 0,b.instance=function(a){return p("instance",a)},b.project=function(a){return p("project",a)},b.universe=function(a){return p("universe",a)},b.bulk=r,b.isAvailable=s,b.resetIsAvailableCache=function(){d=void 0},b.getGCPResidency=t,b.setGCPResidency=u,b.requestTimeout=v;let j=c(32184),k=c(72831),l=c(29314),m=h(c(25850));b.BASE_PATH="/computeMetadata/v1",b.HOST_ADDRESS="http://169.254.169.254",b.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.",b.HEADER_NAME="Metadata-Flavor",b.HEADER_VALUE="Google",b.HEADERS=Object.freeze({[b.HEADER_NAME]:b.HEADER_VALUE});let n=m.log("gcp-metadata");function o(a){return a||(a=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||b.HOST_ADDRESS),/^https?:\/\//.test(a)||(a=`http://${a}`),new URL(b.BASE_PATH,a).href}async function p(a,c={},d=3,e=!1){let f=new Headers(b.HEADERS),g="",h={};("object"==typeof a?(new Headers(a.headers).forEach((a,b)=>f.set(b,a)),g=a.metadataKey,h=a.params||h,d=a.noResponseRetries||d,e=a.fastFail||e):g=a,"string"==typeof c)?g+=`/${c}`:(Object.keys(c).forEach(a=>{switch(a){case"params":case"property":case"headers":break;case"qs":throw Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw Error(`'${a}' is not a valid configuration option.`)}}),c.property&&(g+=`/${c.property}`),new Headers(c.headers).forEach((a,b)=>f.set(b,a)),h=c.params||h);let i=e?q:j.request,l={url:`${o()}/${g}`,headers:f,retryConfig:{noResponseRetries:d},params:h,responseType:"text",timeout:v()};n.info("instance request %j",l);let m=await i(l);n.info("instance metadata is %s",m.data);let r=m.headers.get(b.HEADER_NAME);if(r!==b.HEADER_VALUE)throw RangeError(`Invalid response from metadata service: incorrect ${b.HEADER_NAME} header. Expected '${b.HEADER_VALUE}', got ${r?`'${r}'`:"no header"}`);if("string"==typeof m.data)try{return k.parse(m.data)}catch{}return m.data}async function q(a){let c={...a,url:a.url?.toString().replace(o(),o(b.SECONDARY_HOST_ADDRESS))};return Promise.any([(0,j.request)(a),(0,j.request)(c)])}async function r(a){let b={};return await Promise.all(a.map(a=>(async()=>{let c=await p(a);b[a.metadataKey]=c})())),b}async function s(){if(process.env.METADATA_SERVER_DETECTION){let a=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(a in b.METADATA_SERVER_DETECTION))throw RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${a}\`, but it should be \`${Object.keys(b.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(a){case"assume-present":return!0;case"none":return!1;case"bios-only":return t()}}try{return void 0===d&&(d=p("instance",void 0,process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0,!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await d,!0}catch(a){if(process.env.DEBUG_AUTH&&console.info(a),"request-timeout"===a.type||a.response&&404===a.response.status)return!1;if(!(a.response&&404===a.response.status)&&(!a.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(a.code.toString()))){let b="UNKNOWN";a.code&&(b=a.code.toString()),process.emitWarning(`received unexpected error = ${a.message} code = ${b}`,"MetadataLookupWarning")}return!1}}function t(){return null===b.gcpResidencyCache&&u(),b.gcpResidencyCache}function u(a=null){b.gcpResidencyCache=null!==a?a:(0,l.detectGCPResidency)()}function v(){return 3e3*!t()}b.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"}),b.gcpResidencyCache=null,i(c(29314),b)},95979:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});let d=c(87204),e=c(78276),f=c(65042),g=c(94134);b.default={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,e._)`{additionalProperty: ${a.additionalProperty}}`},code(a){let{gen:b,schema:c,parentSchema:h,data:i,errsCount:j,it:k}=a;if(!j)throw Error("ajv implementation error");let{allErrors:l,opts:m}=k;if(k.props=!0,"all"!==m.removeAdditional&&(0,g.alwaysValidSchema)(k,c))return;let n=(0,d.allSchemaProperties)(h.properties),o=(0,d.allSchemaProperties)(h.patternProperties);function p(a){b.code((0,e._)`delete ${i}[${a}]`)}function q(d){if("all"===m.removeAdditional||m.removeAdditional&&!1===c)return void p(d);if(!1===c){a.setParams({additionalProperty:d}),a.error(),l||b.break();return}if("object"==typeof c&&!(0,g.alwaysValidSchema)(k,c)){let c=b.name("valid");"failing"===m.removeAdditional?(r(d,c,!1),b.if((0,e.not)(c),()=>{a.reset(),p(d)})):(r(d,c),l||b.if((0,e.not)(c),()=>b.break()))}}function r(b,c,d){let e={keyword:"additionalProperties",dataProp:b,dataPropType:g.Type.Str};!1===d&&Object.assign(e,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(e,c)}b.forIn("key",i,c=>{n.length||o.length?b.if(function(c){let f;if(n.length>8){let a=(0,g.schemaRefOrVal)(k,h.properties,"properties");f=(0,d.isOwnProperty)(b,a,c)}else f=n.length?(0,e.or)(...n.map(a=>(0,e._)`${c} === ${a}`)):e.nil;return o.length&&(f=(0,e.or)(f,...o.map(b=>(0,e._)`${(0,d.usePattern)(a,b)}.test(${c})`))),(0,e.not)(f)}(c),()=>q(c)):q(c)}),a.ok((0,e._)`${j} === ${f.default.errors}`)}}},96001:(a,b,c)=>{var d=c(34314),e=c(43677),f=c(76148),g=c(26959),h=c(93137),i=c(38534),j=c(70757),k="[object Map]",l="[object Promise]",m="[object Set]",n="[object WeakMap]",o="[object DataView]",p=j(d),q=j(e),r=j(f),s=j(g),t=j(h),u=i;(d&&u(new d(new ArrayBuffer(1)))!=o||e&&u(new e)!=k||f&&u(f.resolve())!=l||g&&u(new g)!=m||h&&u(new h)!=n)&&(u=function(a){var b=i(a),c="[object Object]"==b?a.constructor:void 0,d=c?j(c):"";if(d)switch(d){case p:return o;case q:return k;case r:return l;case s:return m;case t:return n}return b}),a.exports=u},96233:function(a,b,c){"use strict";let d;var e,f,g,h=this&&this.__createBinding||(Object.create?function(a,b,c,d){void 0===d&&(d=c);var e=Object.getOwnPropertyDescriptor(b,c);(!e||("get"in e?!b.__esModule:e.writable||e.configurable))&&(e={enumerable:!0,get:function(){return b[c]}}),Object.defineProperty(a,d,e)}:function(a,b,c,d){void 0===d&&(d=c),a[d]=b[c]}),i=this&&this.__setModuleDefault||(Object.create?function(a,b){Object.defineProperty(a,"default",{enumerable:!0,value:b})}:function(a,b){a.default=b}),j=this&&this.__importStar||(e=function(a){return(e=Object.getOwnPropertyNames||function(a){var b=[];for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[b.length]=c);return b})(a)},function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c=e(a),d=0;d<c.length;d++)"default"!==c[d]&&h(b,a,c[d]);return i(b,a),b});Object.defineProperty(b,"__esModule",{value:!0}),b.env=b.DebugLogBackendBase=b.placeholder=b.AdhocDebugLogger=b.LogSeverity=void 0,b.getNodeBackend=r,b.getDebugBackend=function(a){return new s(a)},b.getStructuredBackend=function(a){return new t(a)},b.setBackend=function(a){d=a,u.clear()},b.log=v;let k=c(94735),l=j(c(19771)),m=j(c(28354)),n=c(24709);(f=g||(b.LogSeverity=g={})).DEFAULT="DEFAULT",f.DEBUG="DEBUG",f.INFO="INFO",f.WARNING="WARNING",f.ERROR="ERROR";class o extends k.EventEmitter{constructor(a,b){super(),this.namespace=a,this.upstream=b,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(a,b)=>this.on(a,b)}),this.func.debug=(...a)=>this.invokeSeverity(g.DEBUG,...a),this.func.info=(...a)=>this.invokeSeverity(g.INFO,...a),this.func.warn=(...a)=>this.invokeSeverity(g.WARNING,...a),this.func.error=(...a)=>this.invokeSeverity(g.ERROR,...a),this.func.sublog=a=>v(a,this.func)}invoke(a,...b){if(this.upstream)try{this.upstream(a,...b)}catch(a){}try{this.emit("log",a,b)}catch(a){}}invokeSeverity(a,...b){this.invoke({severity:a},...b)}}b.AdhocDebugLogger=o,b.placeholder=new o("",()=>{}).func;class p{constructor(){var a;this.cached=new Map,this.filters=[],this.filtersSet=!1;let c=null!=(a=l.env[b.env.nodeEnables])?a:"*";"all"===c&&(c="*"),this.filters=c.split(",")}log(a,b,...c){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let d=this.cached.get(a);d||(d=this.makeLogger(a),this.cached.set(a,d)),d(b,...c)}catch(a){console.error(a)}}}b.DebugLogBackendBase=p;class q extends p{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(a){return this.enabledRegexp.test(a)}makeLogger(a){return this.enabledRegexp.test(a)?(b,...c)=>{var d;let e,f=`${n.Colours.green}${a}${n.Colours.reset}`,h=`${n.Colours.yellow}${l.pid}${n.Colours.reset}`;switch(b.severity){case g.ERROR:e=`${n.Colours.red}${b.severity}${n.Colours.reset}`;break;case g.INFO:e=`${n.Colours.magenta}${b.severity}${n.Colours.reset}`;break;case g.WARNING:e=`${n.Colours.yellow}${b.severity}${n.Colours.reset}`;break;default:e=null!=(d=b.severity)?d:g.DEFAULT}let i=m.formatWithOptions({colors:n.Colours.enabled},...c),j=Object.assign({},b);delete j.severity;let k=Object.getOwnPropertyNames(j).length?JSON.stringify(j):"",o=k?`${n.Colours.grey}${k}${n.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",h,f,e,i,k?` ${o}`:"")}:()=>{}}setFilters(){let a=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=RegExp(`^${a}$`,"i")}}function r(){return new q}class s extends p{constructor(a){super(),this.debugPkg=a}makeLogger(a){let b=this.debugPkg(a);return(a,...c)=>{b(c[0],...c.slice(1))}}setFilters(){var a;let b=null!=(a=l.env.NODE_DEBUG)?a:"";l.env.NODE_DEBUG=`${b}${b?",":""}${this.filters.join(",")}`}}class t extends p{constructor(a){super(),this.upstream=null!=a?a:void 0}makeLogger(a){var b;let c=null==(b=this.upstream)?void 0:b.makeLogger(a);return(a,...b)=>{var d;let e=JSON.stringify(Object.assign({severity:null!=(d=a.severity)?d:g.INFO,message:m.format(...b)},a));c?c(a,e):console.log("%s",e)}}setFilters(){var a;null==(a=this.upstream)||a.setFilters()}}b.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};let u=new Map;function v(a,c){let e;if(!d&&!l.env[b.env.nodeEnables]||!a)return b.placeholder;c&&(a=`${c.instance.namespace}:${a}`);let f=u.get(a);if(f)return f.func;if(null===d)return b.placeholder;void 0===d&&(d=r());let g=new o(a,(b,...c)=>{if(e!==d){if(null===d)return;void 0===d&&(d=r()),e=d}null==d||d.log(a,b,...c)});return u.set(a,g),g.func}},96363:(a,b,c)=>{var d=c(81598);a.exports=function(){try{var a=d(Object,"defineProperty");return a({},"",{}),a}catch(a){}}()},96436:(a,b,c)=>{"use strict";function d(a,b,c,d,e){if("m"===d)throw TypeError("Private method is not writable");if("a"===d&&!e)throw TypeError("Private accessor was defined without a setter");if("function"==typeof b?a!==b||!e:!b.has(a))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===d?e.call(a,c):e?e.value=c:b.set(a,c),c}function e(a,b,c,d){if("a"===c&&!d)throw TypeError("Private accessor was defined without a getter");if("function"==typeof b?a!==b||!d:!b.has(a))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===c?d:"a"===c?d.call(a):d?d.value:b.get(a)}c.d(b,{G:()=>d,g:()=>e})},96450:(a,b,c)=>{"use strict";c.d(b,{_T:()=>ac,qU:()=>y,vd:()=>ad});var d=c(55511),e=c(79646),f=c(29021),g=c(33873),h=c.n(g),i=c(28354),j=c(46024);c(4669);var k=c(62471),l=c(28461);let m=(0,k.H)(),n=[".runtime-locks","enduring-agents"],o=["darwin","linux","win32"].includes(process.platform),p=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,q=(0,i.promisify)(e.execFile),r=async(a,b,c)=>{let{stdout:d}=await q(a,b,c);return{stdout:String(d)}},s=global.__flujo_enduring_agent_process_instance_id??=(0,d.randomUUID)(),t=global.__flujo_enduring_agent_active_lock_owners??=new Set,u=global.__flujo_enduring_agent_issued_runtime_lock_scopes_v2??=new WeakMap,v=global.__flujo_enduring_agent_deferred_lock_cleanups??=new Set,w=new Map,x=new Map;async function y(a,b,c){let d=function(a,b){let c=u.get(a);if(!c||c.personaId!==b||c.workspace!==(0,l.getCurrentWorkspace)())throw Error("Persona runtime lock capability was not issued by this runtime.");return c}(a,b);if(d.closing)throw Error("Persona runtime lock capability is closing.");d.activeOperations+=1;try{return await a.assertOwned(),await c()}finally{if(d.activeOperations-=1,0===d.activeOperations){for(let a of d.idleWaiters)a();d.idleWaiters.clear()}}}async function z(a){let b=u.get(a);b&&(b.closing=!0,b.activeOperations>0&&await new Promise(a=>b.idleWaiters.add(a)))}class A extends Error{constructor(a){super(`Timed out acquiring the runtime lock for Persona ${JSON.stringify(a)}.`),this.personaId=a,this.code="PERSONA_RUNTIME_LOCK_TIMEOUT",this.name="PersonaRuntimeLockTimeoutError"}}class B extends Error{constructor(a){super(`Lost the runtime lock for Persona ${JSON.stringify(a)}.`),this.personaId=a,this.code="PERSONA_RUNTIME_LOCK_LOST",this.name="PersonaRuntimeLockLostError"}}function C(a){return m.sleep(a)}async function D(){await (0,l.ensureWorkspaceDirs)((0,l.getCurrentWorkspace)());let a=h().resolve((0,l.getWorkspaceDbDir)()),b=h().join(a,...n);await f.promises.mkdir(b,{recursive:!0});let[c,d]=await Promise.all([f.promises.realpath(a),f.promises.realpath(b)]),e=h().relative(c,d);if(""===e||e.startsWith("..")||h().isAbsolute(e))throw Error(`Persona runtime lock root escapes the workspace database: ${b}`);return d}async function E(a){try{let b=JSON.parse(await f.promises.readFile(a,"utf8"));if(!b||"object"!=typeof b||Array.isArray(b))throw Error(`Persona runtime lock ${JSON.stringify(a)} is malformed.`);return b}catch(a){if("ENOENT"===a.code)return null;throw a}}function F(a,b){if("string"!=typeof b.ownerId||!p.test(b.ownerId)||"string"!=typeof b.processInstanceId||"number"!=typeof b.pid||!Number.isInteger(b.pid)||b.pid<=0||void 0!==b.processBirthMarker&&"string"!=typeof b.processBirthMarker||void 0!==b.processBirthMarkerV2&&"string"!=typeof b.processBirthMarkerV2||"string"!=typeof b.workspace||"number"!=typeof b.acquiredAt)throw Error(`Persona runtime lock ${JSON.stringify(a)} is malformed.`);return b}async function G(a){let b=await E(a);return b?F(a,b):null}async function H(a){let b=await E(a);if(!b)return null;let c=F(a,b);if("string"!=typeof b.targetOwnerId||!p.test(b.targetOwnerId)||"string"!=typeof b.targetProcessInstanceId||"number"!=typeof b.targetPid||!Number.isInteger(b.targetPid)||b.targetPid<=0)throw Error(`Persona runtime recovery lock ${JSON.stringify(a)} is malformed.`);return{...c,...b}}async function I(a,b){let c=`${h().basename(b)}.recovery.`,d=(await f.promises.readdir(a)).filter(a=>a.startsWith(c)&&p.test(a.slice(c.length)));return(await Promise.all(d.map(async b=>{let c=h().join(a,b),d=await H(c);return d?{path:c,owner:d}:null}))).filter(a=>null!==a)}function J(a,b){if(!p.test(b))throw Error(`Persona runtime lock owner id ${JSON.stringify(b)} is malformed.`);let c=h().dirname(a),d=h().join(c,`${h().basename(a)}.abandoned.${b}`);if(h().dirname(d)!==c)throw Error("Persona runtime abandonment marker escapes its lock directory.");return d}async function K(a,b){let c=`${h().basename(b)}.abandoned.`;return new Set((await f.promises.readdir(a)).filter(a=>a.startsWith(c)&&p.test(a.slice(c.length))).map(a=>a.slice(c.length)))}async function L(a,b,c){let d=J(b,c.ownerId);return await Y(a,d,c),d}async function M(a){try{await W(a)}catch{}}async function N(){let a=global.__flujo_enduring_agent_linux_boot_id??=f.promises.readFile("/proc/sys/kernel/random/boot_id","utf8").then(a=>a.trim()||null).catch(()=>null),b=await a;return b||global.__flujo_enduring_agent_linux_boot_id!==a||(global.__flujo_enduring_agent_linux_boot_id=void 0),b}async function O(a){let b=process.env.SystemRoot??process.env.WINDIR;if(!b||!h().win32.isAbsolute(b))return null;let c=h().win32.normalize(b);if(!/^[a-z]:\\/i.test(c))return null;let d=h().win32.join(c,"System32","WindowsPowerShell","v1.0","powershell.exe"),{stdout:e}=await r(d,["-NoProfile","-NonInteractive","-Command",`$p=Get-Process -Id ${a} -ErrorAction Stop; $p.StartTime.ToUniversalTime().Ticks`],{encoding:"utf8",timeout:900,windowsHide:!0}),f=e.trim();return f?`win32-v2:${f}`:null}async function P(a){try{if("linux"===process.platform){let[b,c]=await Promise.all([f.promises.readFile(`/proc/${a}/stat`,"utf8"),N()]);if(!c)return null;let d=b.lastIndexOf(")");if(d<0)return null;let e=b.slice(d+1).trim().split(/\s+/);if("Z"===e[0])return"dead:linux-zombie";let g=e[19];return g?`linux-v2:${c}:${g}`:null}if("win32"===process.platform)return await O(a);if("darwin"===process.platform){let{stdout:b}=await r("/bin/ps",["-o","state=","-o","lstart=","-p",String(a)],{encoding:"utf8",timeout:3e3,env:{...process.env,LANG:"C",LC_ALL:"C",TZ:"UTC"}}),c=b.trim(),d=/^(\S+)\s+(.+)$/.exec(c);if(!d)return null;if(d[1].includes("Z"))return"dead:darwin-zombie";return`darwin-v2:${d[2].trim()}`}}catch{}return null}async function Q(a){try{return await P(a)}catch{return null}}async function R(){let a=global.__flujo_enduring_agent_process_birth_marker_v2??=Q(process.pid),b=await a;if(b||global.__flujo_enduring_agent_process_birth_marker_v2!==a||(global.__flujo_enduring_agent_process_birth_marker_v2=void 0),!b&&o)throw Error("Unable to establish this process birth identity for Persona locking.");return b}async function S(a){if(a===process.pid)return R();let b=w.get(a);if(b&&m.monotonicNow()-b.checkedAt<1e3)return b.marker;let c=x.get(a);if(c)return c;let d=Q(a).then(b=>(w.set(a,{checkedAt:m.monotonicNow(),marker:b}),b)).finally(()=>{x.get(a)===d&&x.delete(a)});return x.set(a,d),d}function T(a){return/^linux-v2:[0-9a-f-]{36}:\d+$/i.test(a)?"linux-v2":/^darwin-v2:[A-Z][a-z]{2} [A-Z][a-z]{2}\s+\d{1,2} \d{2}:\d{2}:\d{2} \d{4}$/.test(a)?"darwin-v2":/^win32-v2:\d+$/.test(a)?"win32-v2":null}function U(a,b){if(b.startsWith("dead:"))return!0;let c=T(a);return!!(c&&c===T(b)&&a!==b)}async function V(a,b){if(b.has(a.ownerId))return!1;if(a.pid===process.pid){let b=await R();return!(a.processBirthMarkerV2&&b&&U(a.processBirthMarkerV2,b))&&(a.processInstanceId===s?t.has(a.ownerId):!a.processBirthMarkerV2||!b||!U(a.processBirthMarkerV2,b))}if(!function(a){try{return process.kill(a,0),!0}catch(a){if("ESRCH"===a.code)return!1;return!0}}(a.pid))return!1;if(!a.processBirthMarkerV2){let b=await S(a.pid);return b?.startsWith("dead:")&&(b=await Q(a.pid),w.set(a.pid,{checkedAt:m.monotonicNow(),marker:b})),!b?.startsWith("dead:")}let c=await S(a.pid);return c&&U(a.processBirthMarkerV2,c)&&(c=await Q(a.pid),w.set(a.pid,{checkedAt:m.monotonicNow(),marker:c})),!c||!U(a.processBirthMarkerV2,c)}async function W(a){for(let b=0;b<20;b+=1)try{await f.promises.unlink(a);return}catch(c){let a=c.code;if("ENOENT"===a)return;if(!["EACCES","EBUSY","EPERM"].includes(a??"")||19===b)throw c;await C(25)}}async function X(a,b,c){let e=h().join(a,`${h().basename(b)}.candidate.${(0,d.randomUUID)()}`);try{await f.promises.writeFile(e,JSON.stringify(c),{encoding:"utf8",flag:"wx"});try{return await f.promises.link(e,b),!0}catch(a){if("EEXIST"===a.code)return!1;throw a}}finally{try{await f.promises.unlink(e)}catch{}}}async function Y(a,b,c){let d=m.monotonicNow();for(;;)try{return await X(a,b,c)}catch(a){if(!["EACCES","EBUSY","EPERM"].includes(a.code??"")||m.monotonicNow()-d>=15e3)throw a;await C(25)}}function Z(a){return new Promise(b=>{m.setTimer(b,a).unref()})}async function $(a,b,c,e){let f=await R(),g={ownerId:(0,d.randomUUID)(),processInstanceId:s,pid:process.pid,...f?{processBirthMarkerV2:f}:{},workspace:(0,l.getCurrentWorkspace)(),acquiredAt:m.now(),targetOwnerId:c.ownerId,targetProcessInstanceId:c.processInstanceId,targetPid:c.pid},h=`${b}.recovery.${g.ownerId}`;t.add(g.ownerId);let i=!1;try{if(!(i=await Y(a,h,g)))throw Error(`Recovery intent ${JSON.stringify(g.ownerId)} already exists.`);return await e(g)}finally{if(i){let c=null;try{c=await L(a,b,g)}catch{}t.delete(g.ownerId);try{await W(h),c&&await M(c)}catch{let c;c=`intent:${h}`,v.has(c)||(v.add(c),(async()=>{for(;;){let c=null;try{c=await L(a,b,g)}catch{}t.delete(g.ownerId);try{await W(h),c&&await M(c);return}catch{await Z(1e3)}}})().finally(()=>{v.delete(c)}))}}else t.delete(g.ownerId)}}async function _(a,b,c){await $(a,b,c,async()=>{let d=null;try{d=await L(a,b,c)}finally{t.delete(c.ownerId)}let e=!1;try{let a=await G(b);a?.ownerId===c.ownerId&&a.processInstanceId===c.processInstanceId&&a.pid===c.pid&&await W(b),e=!0}finally{e&&d&&await M(d)}})}function aa(a,b,c){let d=`canonical:${b}:${c.ownerId}`;v.has(d)||(v.add(d),(async()=>{for(;;)try{await _(a,b,c);return}catch{try{let a=await G(b);if(!a||a.ownerId!==c.ownerId||a.processInstanceId!==c.processInstanceId||a.pid!==c.pid)return}catch{}await Z(1e3)}})().finally(()=>{v.delete(d)}))}async function ab(a){let b=await D(),c=h().join(b,`${a}.lock`),e=await R(),f={ownerId:(0,d.randomUUID)(),processInstanceId:s,pid:process.pid,...e?{processBirthMarkerV2:e}:{},workspace:(0,l.getCurrentWorkspace)(),acquiredAt:m.now()};t.add(f.ownerId);let g=m.monotonicNow(),i=!1;try{for(;;){let[d,e]=await Promise.all([I(b,c),K(b,c)]),h=await Promise.all(d.map(async a=>({...a,alive:await V(a.owner,e)}))),j=h.filter(a=>a.alive);if(await Promise.all(h.filter(a=>!a.alive).map(async({path:a,owner:b})=>{await W(a),await M(J(c,b.ownerId))})),j.length>0){if(m.monotonicNow()-g>=15e3)throw new A(a);await C(25);continue}if(i){let a=await G(c);if(a?.ownerId===f.ownerId&&a.processInstanceId===f.processInstanceId&&a.pid===f.pid)break;i=!1}if(await Y(b,c,f)){i=!0;let[a,d]=await Promise.all([I(b,c),K(b,c)]);if((await Promise.all(a.map(({owner:a})=>V(a,d)))).some(Boolean)){await C(25);continue}let e=await G(c);if(e?.ownerId===f.ownerId&&e.processInstanceId===f.processInstanceId&&e.pid===f.pid)break;i=!1;continue}let k=await G(c);if(k){if(!await V(k,e)){await $(b,c,k,async a=>{let d=await G(c),e=await K(b,c);d&&d.ownerId===a.targetOwnerId&&d.processInstanceId===a.targetProcessInstanceId&&d.pid===a.targetPid&&!await V(d,e)&&(await W(c),await M(J(c,d.ownerId)))});continue}if(m.monotonicNow()-g>=15e3)throw new A(a);await C(25)}}}catch(a){try{if(i)try{await _(b,c,f)}catch(a){throw aa(b,c,f),a}}finally{t.delete(f.ownerId)}throw a}let j=async()=>{let b=await G(c);if(b?.ownerId!==f.ownerId||b.processInstanceId!==f.processInstanceId||b.pid!==f.pid||b.workspace!==f.workspace)throw new B(a)},k={assertOwned:j};return u.set(k,{personaId:a,workspace:f.workspace,closing:!1,activeOperations:0,idleWaiters:new Set}),{lock:k,release:async()=>{let a;await z(k);try{await j()}catch(b){a=b}try{try{await _(b,c,f)}catch(a){throw aa(b,c,f),a}}finally{t.delete(f.ownerId),u.delete(k)}if(a)throw a}}}function ac(a,b){return(0,j.ln)(a),(0,j.l_)(`enduring-agent-runtime/${a}`,async()=>{let c=await ab(a);try{return await b(c.lock)}finally{await c.release()}})}function ad(a,b){(0,j.ln)(a);let c=`.${a}`;return(0,j.l_)(`workspace-runtime/${a}`,async()=>{let a=await ab(c);try{return await b(a.lock)}finally{await a.release()}})}},96451:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),b.LRUCache=void 0,b.snakeToCamel=h,b.originalOrCamelOptions=function(a){return{get:function(b){let c=a||{};return c[b]??c[h(b)]}}},b.removeUndefinedValuesInObject=function(a){return Object.entries(a).forEach(([b,c])=>{(void 0===c||"undefined"===c)&&delete a[b]}),a},b.isValidFile=j,b.getWellKnownCertificateConfigFileLocation=function(){let a=process.env.CLOUDSDK_CONFIG||(e.platform().startsWith("win")?f.join(process.env.APPDATA||"",g):f.join(process.env.HOME||"",".config",g));return f.join(a,"certificate_config.json")};let d=c(29021),e=c(21820),f=c(33873),g="gcloud";function h(a){return a.replace(/([_][^_])/g,a=>a.slice(1).toUpperCase())}class i{capacity;#cg=new Map;maxAge;constructor(a){this.capacity=a.capacity,this.maxAge=a.maxAge}#ch(a,b){this.#cg.delete(a),this.#cg.set(a,{value:b,lastAccessed:Date.now()})}set(a,b){this.#ch(a,b),this.#ci()}get(a){let b=this.#cg.get(a);if(b)return this.#ch(a,b.value),this.#ci(),b.value}#ci(){let a=this.maxAge?Date.now()-this.maxAge:0,b=this.#cg.entries().next();for(;!b.done&&(this.#cg.size>this.capacity||b.value[1].lastAccessed<a);)this.#cg.delete(b.value[0]),b=this.#cg.entries().next()}}async function j(a){try{return(await d.promises.lstat(a)).isFile()}catch(a){return!1}}b.LRUCache=i},96650:(a,b,c)=>{"use strict";function d(a,b,c){if(!a)throw Error(`${c} does not support task creation (required for ${b})`);if("tools/call"===b&&!a.tools?.call)throw Error(`${c} does not support task creation for tools/call (required for ${b})`)}function e(a,b,c){if(!a)throw Error(`${c} does not support task creation (required for ${b})`);switch(b){case"sampling/createMessage":if(!a.sampling?.createMessage)throw Error(`${c} does not support task creation for sampling/createMessage (required for ${b})`);break;case"elicitation/create":if(!a.elicitation?.create)throw Error(`${c} does not support task creation for elicitation/create (required for ${b})`)}}c.d(b,{s:()=>e,z:()=>d})},96694:a=>{"use strict";let b="win32"===process.platform;function c(a,b){return Object.assign(Error(`${b} ${a.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${b} ${a.command}`,path:a.command,spawnargs:a.args})}function d(a,d){return b&&1===a&&!d.file?c(d.original,"spawn"):null}a.exports={hookChildProcess:function(a,c){if(!b)return;let e=a.emit;a.emit=function(b,f){if("exit"===b){let b=d(f,c);if(b)return e.call(a,"error",b)}return e.apply(a,arguments)}},verifyENOENT:d,verifyENOENTSync:function(a,d){return b&&1===a&&!d.file?c(d.original,"spawnSync"):null},notFoundError:c}},96809:(a,b,c)=>{"use strict";c.d(b,{e:()=>i,h:()=>j});var d=c(46024),e=c(28461),f=c(53348),g=c(87512);function h(a,b,c){let d=g.jc.parse(b);if(d.id!==a||d.workspaceId!==c)throw Error(`PersonaFlowDispatchRecord ${JSON.stringify(a)} has mismatched storage identity or workspace.`);return d}async function i(a){(0,d.ln)(a);let b=(0,e.getCurrentWorkspace)();return(await (0,d.$G)(f.p.flowDispatches)).map(({id:a,item:c})=>h(a,c,b)).filter(b=>b.personaId===a).sort((a,b)=>a.createdAt-b.createdAt||a.id.localeCompare(b.id))}function j(a){let b=g.jc.parse(a),c=(0,e.getCurrentWorkspace)();if(b.workspaceId!==c)throw Error(`PersonaFlowDispatchRecord ${JSON.stringify(b.id)} belongs to another workspace.`);return(0,d.ln)(b.id),(0,d.l_)(`enduring-agent:${f.p.flowDispatches}/${b.id}`,async()=>{let a=await (0,d.EI)(f.p.flowDispatches,b.id,null);if(null===a)throw Error(`Cannot compact missing PersonaFlowDispatchRecord ${JSON.stringify(b.id)}.`);let e=h(b.id,a,c);if(e.personaId!==b.personaId||e.createdAt!==b.createdAt||e.updatedAt!==b.updatedAt||e.state!==b.state)throw Error("PersonaFlowDispatchRecord changed during retention compaction.");return await (0,d.Vt)(f.p.flowDispatches,b.id,b),b})}},97151:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),b.or=b.and=b.not=b.CodeGen=b.operators=b.varKinds=b.ValueScopeName=b.ValueScope=b.Scope=b.Name=b.regexpCode=b.stringify=b.getProperty=b.nil=b.strConcat=b.str=b._=void 0;let d=c(89670),e=c(61591);var f=c(89670);Object.defineProperty(b,"_",{enumerable:!0,get:function(){return f._}}),Object.defineProperty(b,"str",{enumerable:!0,get:function(){return f.str}}),Object.defineProperty(b,"strConcat",{enumerable:!0,get:function(){return f.strConcat}}),Object.defineProperty(b,"nil",{enumerable:!0,get:function(){return f.nil}}),Object.defineProperty(b,"getProperty",{enumerable:!0,get:function(){return f.getProperty}}),Object.defineProperty(b,"stringify",{enumerable:!0,get:function(){return f.stringify}}),Object.defineProperty(b,"regexpCode",{enumerable:!0,get:function(){return f.regexpCode}}),Object.defineProperty(b,"Name",{enumerable:!0,get:function(){return f.Name}});var g=c(61591);Object.defineProperty(b,"Scope",{enumerable:!0,get:function(){return g.Scope}}),Object.defineProperty(b,"ValueScope",{enumerable:!0,get:function(){return g.ValueScope}}),Object.defineProperty(b,"ValueScopeName",{enumerable:!0,get:function(){return g.ValueScopeName}}),Object.defineProperty(b,"varKinds",{enumerable:!0,get:function(){return g.varKinds}}),b.operators={GT:new d._Code(">"),GTE:new d._Code(">="),LT:new d._Code("<"),LTE:new d._Code("<="),EQ:new d._Code("==="),NEQ:new d._Code("!=="),NOT:new d._Code("!"),OR:new d._Code("||"),AND:new d._Code("&&"),ADD:new d._Code("+")};class h{optimizeNodes(){return this}optimizeNames(a,b){return this}}class i extends h{constructor(a,b,c){super(),this.varKind=a,this.name=b,this.rhs=c}render({es5:a,_n:b}){let c=a?e.varKinds.var:this.varKind,d=void 0===this.rhs?"":` = ${this.rhs}`;return`${c} ${this.name}${d};`+b}optimizeNames(a,b){if(a[this.name.str])return this.rhs&&(this.rhs=G(this.rhs,a,b)),this}get names(){return this.rhs instanceof d._CodeOrName?this.rhs.names:{}}}class j extends h{constructor(a,b,c){super(),this.lhs=a,this.rhs=b,this.sideEffects=c}render({_n:a}){return`${this.lhs} = ${this.rhs};`+a}optimizeNames(a,b){if(!(this.lhs instanceof d.Name)||a[this.lhs.str]||this.sideEffects)return this.rhs=G(this.rhs,a,b),this}get names(){return F(this.lhs instanceof d.Name?{}:{...this.lhs.names},this.rhs)}}class k extends j{constructor(a,b,c,d){super(a,c,d),this.op=b}render({_n:a}){return`${this.lhs} ${this.op}= ${this.rhs};`+a}}class l extends h{constructor(a){super(),this.label=a,this.names={}}render({_n:a}){return`${this.label}:`+a}}class m extends h{constructor(a){super(),this.label=a,this.names={}}render({_n:a}){let b=this.label?` ${this.label}`:"";return`break${b};`+a}}class n extends h{constructor(a){super(),this.error=a}render({_n:a}){return`throw ${this.error};`+a}get names(){return this.error.names}}class o extends h{constructor(a){super(),this.code=a}render({_n:a}){return`${this.code};`+a}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(a,b){return this.code=G(this.code,a,b),this}get names(){return this.code instanceof d._CodeOrName?this.code.names:{}}}class p extends h{constructor(a=[]){super(),this.nodes=a}render(a){return this.nodes.reduce((b,c)=>b+c.render(a),"")}optimizeNodes(){let{nodes:a}=this,b=a.length;for(;b--;){let c=a[b].optimizeNodes();Array.isArray(c)?a.splice(b,1,...c):c?a[b]=c:a.splice(b,1)}return a.length>0?this:void 0}optimizeNames(a,b){let{nodes:c}=this,d=c.length;for(;d--;){let e=c[d];e.optimizeNames(a,b)||(function(a,b){for(let c in b)a[c]=(a[c]||0)-(b[c]||0)}(a,e.names),c.splice(d,1))}return c.length>0?this:void 0}get names(){return this.nodes.reduce((a,b)=>E(a,b.names),{})}}class q extends p{render(a){return"{"+a._n+super.render(a)+"}"+a._n}}class r extends p{}class s extends q{}s.kind="else";class t extends q{constructor(a,b){super(b),this.condition=a}render(a){let b=`if(${this.condition})`+super.render(a);return this.else&&(b+="else "+this.else.render(a)),b}optimizeNodes(){super.optimizeNodes();let a=this.condition;if(!0===a)return this.nodes;let b=this.else;if(b){let a=b.optimizeNodes();b=this.else=Array.isArray(a)?new s(a):a}return b?!1===a?b instanceof t?b:b.nodes:this.nodes.length?this:new t(H(a),b instanceof t?[b]:b.nodes):!1!==a&&this.nodes.length?this:void 0}optimizeNames(a,b){var c;if(this.else=null==(c=this.else)?void 0:c.optimizeNames(a,b),super.optimizeNames(a,b)||this.else)return this.condition=G(this.condition,a,b),this}get names(){let a=super.names;return F(a,this.condition),this.else&&E(a,this.else.names),a}}t.kind="if";class u extends q{}u.kind="for";class v extends u{constructor(a){super(),this.iteration=a}render(a){return`for(${this.iteration})`+super.render(a)}optimizeNames(a,b){if(super.optimizeNames(a,b))return this.iteration=G(this.iteration,a,b),this}get names(){return E(super.names,this.iteration.names)}}class w extends u{constructor(a,b,c,d){super(),this.varKind=a,this.name=b,this.from=c,this.to=d}render(a){let b=a.es5?e.varKinds.var:this.varKind,{name:c,from:d,to:f}=this;return`for(${b} ${c}=${d}; ${c}<${f}; ${c}++)`+super.render(a)}get names(){let a=F(super.names,this.from);return F(a,this.to)}}class x extends u{constructor(a,b,c,d){super(),this.loop=a,this.varKind=b,this.name=c,this.iterable=d}render(a){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(a)}optimizeNames(a,b){if(super.optimizeNames(a,b))return this.iterable=G(this.iterable,a,b),this}get names(){return E(super.names,this.iterable.names)}}class y extends q{constructor(a,b,c){super(),this.name=a,this.args=b,this.async=c}render(a){let b=this.async?"async ":"";return`${b}function ${this.name}(${this.args})`+super.render(a)}}y.kind="func";class z extends p{render(a){return"return "+super.render(a)}}z.kind="return";class A extends q{render(a){let b="try"+super.render(a);return this.catch&&(b+=this.catch.render(a)),this.finally&&(b+=this.finally.render(a)),b}optimizeNodes(){var a,b;return super.optimizeNodes(),null==(a=this.catch)||a.optimizeNodes(),null==(b=this.finally)||b.optimizeNodes(),this}optimizeNames(a,b){var c,d;return super.optimizeNames(a,b),null==(c=this.catch)||c.optimizeNames(a,b),null==(d=this.finally)||d.optimizeNames(a,b),this}get names(){let a=super.names;return this.catch&&E(a,this.catch.names),this.finally&&E(a,this.finally.names),a}}class B extends q{constructor(a){super(),this.error=a}render(a){return`catch(${this.error})`+super.render(a)}}B.kind="catch";class C extends q{render(a){return"finally"+super.render(a)}}C.kind="finally";class D{constructor(a,b={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...b,_n:b.lines?"\n":""},this._extScope=a,this._scope=new e.Scope({parent:a}),this._nodes=[new r]}toString(){return this._root.render(this.opts)}name(a){return this._scope.name(a)}scopeName(a){return this._extScope.name(a)}scopeValue(a,b){let c=this._extScope.value(a,b);return(this._values[c.prefix]||(this._values[c.prefix]=new Set)).add(c),c}getScopeValue(a,b){return this._extScope.getValue(a,b)}scopeRefs(a){return this._extScope.scopeRefs(a,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(a,b,c,d){let e=this._scope.toName(b);return void 0!==c&&d&&(this._constants[e.str]=c),this._leafNode(new i(a,e,c)),e}const(a,b,c){return this._def(e.varKinds.const,a,b,c)}let(a,b,c){return this._def(e.varKinds.let,a,b,c)}var(a,b,c){return this._def(e.varKinds.var,a,b,c)}assign(a,b,c){return this._leafNode(new j(a,b,c))}add(a,c){return this._leafNode(new k(a,b.operators.ADD,c))}code(a){return"function"==typeof a?a():a!==d.nil&&this._leafNode(new o(a)),this}object(...a){let b=["{"];for(let[c,e]of a)b.length>1&&b.push(","),b.push(c),(c!==e||this.opts.es5)&&(b.push(":"),(0,d.addCodeArg)(b,e));return b.push("}"),new d._Code(b)}if(a,b,c){if(this._blockNode(new t(a)),b&&c)this.code(b).else().code(c).endIf();else if(b)this.code(b).endIf();else if(c)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(a){return this._elseNode(new t(a))}else(){return this._elseNode(new s)}endIf(){return this._endBlockNode(t,s)}_for(a,b){return this._blockNode(a),b&&this.code(b).endFor(),this}for(a,b){return this._for(new v(a),b)}forRange(a,b,c,d,f=this.opts.es5?e.varKinds.var:e.varKinds.let){let g=this._scope.toName(a);return this._for(new w(f,g,b,c),()=>d(g))}forOf(a,b,c,f=e.varKinds.const){let g=this._scope.toName(a);if(this.opts.es5){let a=b instanceof d.Name?b:this.var("_arr",b);return this.forRange("_i",0,(0,d._)`${a}.length`,b=>{this.var(g,(0,d._)`${a}[${b}]`),c(g)})}return this._for(new x("of",f,g,b),()=>c(g))}forIn(a,b,c,f=this.opts.es5?e.varKinds.var:e.varKinds.const){if(this.opts.ownProperties)return this.forOf(a,(0,d._)`Object.keys(${b})`,c);let g=this._scope.toName(a);return this._for(new x("in",f,g,b),()=>c(g))}endFor(){return this._endBlockNode(u)}label(a){return this._leafNode(new l(a))}break(a){return this._leafNode(new m(a))}return(a){let b=new z;if(this._blockNode(b),this.code(a),1!==b.nodes.length)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(z)}try(a,b,c){if(!b&&!c)throw Error('CodeGen: "try" without "catch" and "finally"');let d=new A;if(this._blockNode(d),this.code(a),b){let a=this.name("e");this._currNode=d.catch=new B(a),b(a)}return c&&(this._currNode=d.finally=new C,this.code(c)),this._endBlockNode(B,C)}throw(a){return this._leafNode(new n(a))}block(a,b){return this._blockStarts.push(this._nodes.length),a&&this.code(a).endBlock(b),this}endBlock(a){let b=this._blockStarts.pop();if(void 0===b)throw Error("CodeGen: not in self-balancing block");let c=this._nodes.length-b;if(c<0||void 0!==a&&c!==a)throw Error(`CodeGen: wrong number of nodes: ${c} vs ${a} expected`);return this._nodes.length=b,this}func(a,b=d.nil,c,e){return this._blockNode(new y(a,b,c)),e&&this.code(e).endFunc(),this}endFunc(){return this._endBlockNode(y)}optimize(a=1){for(;a-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(a){return this._currNode.nodes.push(a),this}_blockNode(a){this._currNode.nodes.push(a),this._nodes.push(a)}_endBlockNode(a,b){let c=this._currNode;if(c instanceof a||b&&c instanceof b)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${b?`${a.kind}/${b.kind}`:a.kind}"`)}_elseNode(a){let b=this._currNode;if(!(b instanceof t))throw Error('CodeGen: "else" without "if"');return this._currNode=b.else=a,this}get _root(){return this._nodes[0]}get _currNode(){let a=this._nodes;return a[a.length-1]}set _currNode(a){let b=this._nodes;b[b.length-1]=a}}function E(a,b){for(let c in b)a[c]=(a[c]||0)+(b[c]||0);return a}function F(a,b){return b instanceof d._CodeOrName?E(a,b.names):a}function G(a,b,c){var e;if(a instanceof d.Name)return f(a);if(!((e=a)instanceof d._Code&&e._items.some(a=>a instanceof d.Name&&1===b[a.str]&&void 0!==c[a.str])))return a;return new d._Code(a._items.reduce((a,b)=>(b instanceof d.Name&&(b=f(b)),b instanceof d._Code?a.push(...b._items):a.push(b),a),[]));function f(a){let d=c[a.str];return void 0===d||1!==b[a.str]?a:(delete b[a.str],d)}}function H(a){return"boolean"==typeof a||"number"==typeof a||null===a?!a:(0,d._)`!${L(a)}`}b.CodeGen=D,b.not=H;let I=K(b.operators.AND);b.and=function(...a){return a.reduce(I)};let J=K(b.operators.OR);function K(a){return(b,c)=>b===d.nil?c:c===d.nil?b:(0,d._)`${L(b)} ${a} ${L(c)}`}function L(a){return a instanceof d.Name?a:(0,d._)`(${a})`}b.or=function(...a){return a.reduce(J)}},97210:(a,b,c)=>{"use strict";let{createInflateRaw:d,Z_DEFAULT_WINDOWBITS:e}=c(38522),{isValidClientWindowBits:f}=c(94050),{MessageSizeExceededError:g}=c(61448),h=Buffer.from([0,0,255,255]),i=Symbol("kBuffer"),j=Symbol("kLength");class k{#cj;#cc={};#bH=0;constructor(a,b){this.#cc.serverNoContextTakeover=a.has("server_no_context_takeover"),this.#cc.serverMaxWindowBits=a.get("server_max_window_bits"),this.#bH=b.maxPayloadSize}decompress(a,b,c){if(!this.#cj){let a=e;if(this.#cc.serverMaxWindowBits){if(!f(this.#cc.serverMaxWindowBits))return void c(Error("Invalid server_max_window_bits"));a=Number.parseInt(this.#cc.serverMaxWindowBits)}try{this.#cj=d({windowBits:a})}catch(a){c(a);return}this.#cj[i]=[],this.#cj[j]=0,this.#cj.on("data",a=>{if(this.#cj[j]+=a.length,this.#bH>0&&this.#cj[j]>this.#bH){c(new g),this.#cj.removeAllListeners(),this.#cj=null;return}this.#cj[i].push(a)}),this.#cj.on("error",a=>{this.#cj=null,c(a)})}this.#cj.write(a),b&&this.#cj.write(h),this.#cj.flush(()=>{if(!this.#cj)return;let a=Buffer.concat(this.#cj[i],this.#cj[j]);this.#cj[i].length=0,this.#cj[j]=0,c(null,a)})}}a.exports={PerMessageDeflate:k}},97218:(a,b,c)=>{"use strict";c.d(b,{dM:()=>s});var d=c(10220),e=c(46691),f=c(53857),g=c(38626);function h(a,b,c,d){return"number"!=typeof a||Number.isNaN(a)?d:Math.max(b,Math.min(c,Math.floor(a)))}let i={type:"arrowclosed",width:20,height:20,color:"#1976d2"},j={stroke:"#1976d2",strokeWidth:2},k={type:"arrowclosed",width:20,height:20,color:"#009688"},l={stroke:"#009688",strokeWidth:2},m=new Set(["full-history","latest-message","isolated"]),n=new Set(["steps","final-only"]),o=new Set(["full-conversation","latest-message"]);function p(a,b={}){let{keepPills:c=!1,wiredServers:d=new Set,validHandoffNames:f=new Set}=b,g=(0,e.A$)(a);if(0===g.length)return{text:a,stripped:!1,unresolved:[]};let h="",i=0,j=!1,k=[];for(let b of g){h+=a.slice(i,b.index),i=b.index+b.fullMatch.length;let e=!1;c&&(e="handoff"===b.server?f.has(b.name):d.has(b.server)),e?h+=b.fullMatch:(h+=b.name,j=!0,c&&k.push(b.fullMatch))}return{text:h+=a.slice(i),stripped:j,unresolved:k}}function q(a,b,c){let d=b.filter(b=>b.from===a).map(a=>c.get(a.to)).filter(Boolean).map(a=>({id:a.key??"",label:a.label,type:a.type}));return new Set((0,g.E9)(d).values())}function r(a,b){if(b.some(b=>b.id===a))return a;let c=a.toLowerCase(),d=b.find(a=>a.name.toLowerCase()===c);return d?d.id:null}function s(a,b={},c={}){var e,g,t;let u,v=[],w=(a,b,c)=>v.push({severity:"error",code:a,message:b,nodeKey:c}),x=(a,b,c)=>v.push({severity:"warning",code:a,message:b,nodeKey:c}),y=b.models??[],z=new Set((b.servers??[]).map(a=>a.name)),A=b.serverTools??{},B=h(c.maxDepth,0,3,3),C=h(c.maxFlows,1,8,8),D=[],E=[...(b.flows??[]).map(a=>a.name)],F=[],G=0;return e=function a(e,g,s){let t=Array.isArray(e?.nodes)?e.nodes:[],u=Array.isArray(e?.edges)?e.edges:[],v=function(a,b){let c=(a??"").trim().replace(/[^\w-]+/g,"_").replace(/^_+|_+$/g,"");c||(c="generated_flow");let d=new Set(b.map(a=>a.toLowerCase()));if(!d.has(c.toLowerCase()))return c;for(let a=2;;a++){let b=`${c}_${a}`;if(!d.has(b.toLowerCase()))return b}}(e?.name,E);E.push(v),G++;let I=(0,d.A)(),J=[...s,v],K=new Map,L=[],M=[],N=new Map(t.filter(a=>a?.key&&"string"==typeof a.key).map(a=>[a.key,a]));for(let e of t){let f=e?.key;if(!f||"string"!=typeof f){w("node-missing-key",'A node is missing its "key" — every node needs a unique key.');continue}if(K.has(f)){w("node-duplicate-key",`Duplicate node key "${f}" — keys must be unique; the later node was dropped.`,f);continue}let i=e.type;if("mcp"===i){w("mcp-node-not-allowed",`Node "${f}": do not emit "mcp" nodes — attach servers to a process node via its "servers" list instead.`,f);continue}if("start"!==i&&"process"!==i&&"finish"!==i&&"subflow"!==i&&"resource"!==i&&"signal"!==i&&"static"!==i){w("unknown-node-type",`Node "${f}" has unknown type "${String(i)}".`,f);continue}let j={},k="string"==typeof e.prompt?e.prompt:void 0;if("start"===i){let{text:a,stripped:b,unresolved:d}=p(k??"",c.keepPills?{keepPills:!0,wiredServers:new Set((e.servers??[]).map(a=>a.name)),validHandoffNames:q(f,u,N)}:{});for(let a of(b&&!c.keepPills&&x("pill-stripped",`Node "${f}": binding pills are not supported in generated prompts and were replaced with plain names.`,f),d))x("pill-unresolved",`Node "${f}": pill "${a}" not resolved against wired servers — stripped.`,f);j.promptTemplate=a}else if("process"===i){let{text:a,stripped:b,unresolved:d}=p(k??"",c.keepPills?{keepPills:!0,wiredServers:new Set((e.servers??[]).map(a=>a.name)),validHandoffNames:q(f,u,N)}:{});for(let a of(b&&!c.keepPills&&x("pill-stripped",`Node "${f}": binding pills are not supported in generated prompts and were replaced with plain names.`,f),d))x("pill-unresolved",`Node "${f}": pill "${a}" not resolved against wired servers — stripped.`,f);if(j.promptTemplate=a,e.model){let a=function(a,b){if(b.some(b=>b.id===a))return a;let c=a.toLowerCase(),d=b.find(a=>a.displayName?.toLowerCase()===c);if(d)return d.id;let e=b.find(a=>a.name?.toLowerCase()===c);return e?e.id:null}(e.model,y);a?j.boundModel=a:(j.boundModel=e.model,x("model-unresolved",`Node "${f}": model "${e.model}" does not match any configured model (by id, display name, or name).`,f))}void 0!==e.inputMode&&(m.has(e.inputMode)?(j.inputMode=e.inputMode,"isolated"===e.inputMode&&"string"==typeof e.isolatedPrompt&&(j.isolatedPrompt=e.isolatedPrompt)):x("invalid-input-mode",`Node "${f}": inputMode "${String(e.inputMode)}" is not valid (full-history | latest-message | isolated); omitted.`,f)),"boolean"==typeof e.allowCallerPrompt&&(j.allowCallerPrompt=e.allowCallerPrompt),void 0!==e.outputMode&&(o.has(e.outputMode)?j.outputMode=e.outputMode:x("invalid-output-mode",`Node "${f}": outputMode "${String(e.outputMode)}" is not valid on a process node (full-conversation | latest-message); omitted.`,f)),void 0!==e.maxTurns&&("number"!=typeof e.maxTurns||Number.isNaN(e.maxTurns)?x("invalid-max-turns",`Node "${f}": maxTurns "${String(e.maxTurns)}" is not a number; omitted.`,f):j.maxTurns=h(e.maxTurns,1,1e3,1)),"boolean"==typeof e.excludeModelPrompt&&(j.excludeModelPrompt=e.excludeModelPrompt),"boolean"==typeof e.excludeStartNodePrompt&&(j.excludeStartNodePrompt=e.excludeStartNodePrompt),"boolean"==typeof e.excludeSystemPrompt&&(j.excludeSystemPrompt=e.excludeSystemPrompt),Array.isArray(e.allowedTools)&&(j.allowedTools=e.allowedTools.filter(a=>"string"==typeof a&&a)),"string"==typeof e.captureVariable&&e.captureVariable.trim()&&(j.captureVariable=e.captureVariable.trim()),"string"==typeof e.captureResource&&e.captureResource.trim()&&x("process-capture-resource-unsupported",`Node "${f}": process captureResource is not supported; connect the process to a Resource node so it can call write_resource.`,f),"string"==typeof e.captureKv&&e.captureKv.trim()&&(j.captureKv=e.captureKv.trim())}else if("subflow"===i){if(function(c,d,e,f,g){let h=Array.isArray(c.parallelFlows)&&c.parallelFlows.length>0,i=Array.isArray(c.parallelSubflowSpecs)&&c.parallelSubflowSpecs.length>0,j="string"==typeof c.parallelFlowsVariable?c.parallelFlowsVariable.trim():"";if([void 0!==c.flow&&null!==c.flow?"flow":null,void 0!==c.subflowSpec&&null!==c.subflowSpec?"subflowSpec":null,h?"parallelFlows":null,i?"parallelSubflowSpecs":null,void 0!==c.generateSubflow&&null!==c.generateSubflow?"generateSubflow":null].filter(Boolean).length>1&&x("subflow-multiple-sources",`Node "${d}": a subflow node should have only one target source ("flow", "subflowSpec", "parallelFlows", "parallelSubflowSpecs", or "generateSubflow"); applying precedence flow > subflowSpec > parallelFlows > parallelSubflowSpecs > generateSubflow.`,d),!0===c.mapOverList){let a=void 0!==c.flow&&null!==c.flow||void 0!==c.subflowSpec&&null!==c.subflowSpec;(h||i)&&w("subflow-map-and-parallel",`Node "${d}": "mapOverList" runs a SINGLE child once per item and cannot be combined with "parallelFlows"/"parallelSubflowSpecs".`,d),a?(g.mapOverList=!0,void 0!==c.itemSplit&&("json-array"===c.itemSplit||"lines"===c.itemSplit?g.itemSplit=c.itemSplit:x("invalid-item-split",`Node "${d}": itemSplit "${String(c.itemSplit)}" is not valid (json-array | lines); using json-array.`,d)),!0===c.sequential&&(g.sequential=!0),H(c,g)):w("subflow-map-no-child",`Node "${d}": "mapOverList" needs a single child ("flow" or "subflowSpec") to run once per item.`,d)}let k=Array.isArray(c.spawnBriefs)?c.spawnBriefs.filter(a=>"string"==typeof a&&""!==a.trim()):[];if(k.length>0){let a=void 0!==c.flow&&null!==c.flow||void 0!==c.subflowSpec&&null!==c.subflowSpec;h||i?w("subflow-spawn-and-parallel",`Node "${d}": "spawnBriefs" runs a SINGLE child once per brief and cannot be combined with "parallelFlows"/"parallelSubflowSpecs".`,d):!0===c.mapOverList?w("subflow-spawn-and-map",`Node "${d}": "spawnBriefs" cannot be combined with "mapOverList"; use one lane source or the other.`,d):a?(g.spawnBriefs=k,H(c,g)):w("subflow-spawn-no-child",`Node "${d}": "spawnBriefs" needs a single child ("flow" or "subflowSpec") to spawn once per brief.`,d)}if(j&&(!0===c.mapOverList?w("subflow-map-and-parallel-var",`Node "${d}": "parallelFlowsVariable" (dynamic fan-out) cannot be combined with "mapOverList".`,d):g.parallelSubflowIdsVar=j),c.flow){if(f.some(a=>a.toLowerCase()===c.flow.toLowerCase()))return w("subflow-cycle",`Node "${d}": flow "${c.flow}" refers to an ancestor flow, which would create a cycle.`,d);let a=r(c.flow,[...b.flows??[],...F]);return a?g.subflowId=a:w("subflow-unresolved",`Node "${d}": flow "${c.flow}" does not match any existing flow (by id or name).`,d)}if(c.subflowSpec){if(e+1>B)return w("subflow-too-deep",`Node "${d}": nested subflows may not go deeper than ${B} level(s); this inline subflow was not compiled.`,d);if(G>=C)return w("subflow-too-many",`Node "${d}": compiling this inline subflow would exceed the maximum of ${C} flows in one bundle; it was not compiled.`,d);let b=a(c.subflowSpec,e+1,f);return b?g.subflowId=b.id:w("subflow-child-empty",`Node "${d}": the inline "subflowSpec" produced no usable flow.`,d)}if(h){let a=[];for(let e of c.parallelFlows){if("string"!=typeof e||!e){w("parallel-flow-invalid",`Node "${d}": a "parallelFlows" entry is missing or not a string.`,d);continue}if(f.some(a=>a.toLowerCase()===e.toLowerCase())){w("subflow-cycle",`Node "${d}": parallel flow "${e}" refers to an ancestor flow, which would create a cycle.`,d);continue}let c=r(e,[...b.flows??[],...F]);c?a.includes(c)||a.push(c):w("parallel-flow-unresolved",`Node "${d}": parallel flow "${e}" does not match any existing flow (by id or name).`,d)}a.length>0?(g.parallelSubflowIds=a,H(c,g)):w("parallel-empty",`Node "${d}": "parallelFlows" resolved to no runnable lanes.`,d);return}if(i){let b=[];for(let g of c.parallelSubflowSpecs){if(!g||"object"!=typeof g){w("parallel-spec-invalid",`Node "${d}": a "parallelSubflowSpecs" entry is not a FlowSpec object.`,d);continue}if(e+1>B){w("subflow-too-deep",`Node "${d}": nested subflows may not go deeper than ${B} level(s); a parallel inline subflow was not compiled.`,d);continue}if(G>=C){w("subflow-too-many",`Node "${d}": compiling a parallel inline subflow would exceed the maximum of ${C} flows in one bundle; it was not compiled.`,d);continue}let c=a(g,e+1,f);c?b.push(c.id):w("subflow-child-empty",`Node "${d}": a "parallelSubflowSpecs" entry produced no usable flow.`,d)}b.length>0?(g.parallelSubflowIds=b,H(c,g)):w("parallel-empty",`Node "${d}": "parallelSubflowSpecs" produced no runnable lanes.`,d);return}j&&g.parallelSubflowIdsVar?H(c,g):void 0!==c.generateSubflow&&null!==c.generateSubflow?w("subflow-generate-unsupported",`Node "${d}": "generateSubflow" is only available through the AI flow generator. Use "subflowSpec" for deterministic nested authoring, or "flow" to reference an existing flow.`,d):w("subflow-missing-flow",`Node "${d}": subflow nodes need a "flow" (existing flow), a "subflowSpec" (inline child), "parallelFlows"/"parallelSubflowSpecs" (concurrent children), or "generateSubflow".`,d)}(e,f,g,J,j),void 0!==e.inputMode&&(m.has(e.inputMode)?j.inputMode=e.inputMode:x("invalid-input-mode",`Node "${f}": inputMode "${String(e.inputMode)}" is not valid (full-history | latest-message | isolated); omitted.`,f)),void 0!==e.outputMode&&(n.has(e.outputMode)?j.outputMode=e.outputMode:x("invalid-output-mode",`Node "${f}": outputMode "${String(e.outputMode)}" is not valid (steps | final-only); omitted.`,f)),void 0!==k){let{text:a,stripped:b,unresolved:d}=p(k,c.keepPills?{keepPills:!0}:{});for(let a of(b&&!c.keepPills&&x("pill-stripped",`Node "${f}": binding pills are not supported in generated prompts and were replaced with plain names.`,f),d))x("pill-unresolved",`Node "${f}": pill "${a}" not resolved against wired servers — stripped.`,f);j.promptTemplate=a}"boolean"==typeof e.allowCallerPrompt&&(j.allowCallerPrompt=e.allowCallerPrompt),"boolean"==typeof e.allowCallerFanout&&(j.allowCallerFanout=e.allowCallerFanout);let d=e.sessionScope??(c.newSubflowDefaults?"per-key":void 0);"per-visit"===d||"per-run"===d||"per-key"===d?"per-visit"!==d&&(j.sessionScope=d):void 0!==e.sessionScope&&x("invalid-session-scope",`Node "${f}": sessionScope "${String(e.sessionScope)}" is not valid (per-visit | per-run | per-key); omitted.`,f),"string"==typeof e.sessionKey&&e.sessionKey.trim()&&(j.sessionKey=e.sessionKey.trim()),"separate"===(e.resultPresentation??"separate")&&(j.resultPresentation="separate"),"string"==typeof e.captureVariable&&e.captureVariable.trim()&&(j.captureVariable=e.captureVariable.trim()),"string"==typeof e.captureResource&&e.captureResource.trim()&&(j.captureResource=e.captureResource.trim()),"string"==typeof e.captureKv&&e.captureKv.trim()&&(j.captureKv=e.captureKv.trim())}else if("resource"===i){let a="string"==typeof e.runName?e.runName.trim():"",b="string"==typeof e.server?e.server.trim():"",c="string"==typeof e.uri?e.uri.trim():"";a?(j.scope="run",j.runName=a,(b||c)&&x("resource-both-bindings",`Node "${f}": a resource node is EITHER a run artifact ("runName") or a static MCP resource ("server"+"uri"); kept the run artifact.`,f)):(j.scope="mcp",b&&(j.boundServer=b),c&&(j.uri=c),b&&c?z.has(b)||x("server-unknown",`Node "${f}": MCP server "${b}" is not configured in FLUJO.`,f):x("resource-missing-binding",`Node "${f}": a static resource node needs both "server" and "uri" (or a "runName" for a run artifact).`,f))}else if("signal"===i){let a="string"==typeof e.topic?e.topic.trim():"";a?j.topic=a:x("signal-missing-topic",`Node "${f}": a signal node needs a "topic" to emit.`,f),"string"==typeof e.payloadTemplate&&e.payloadTemplate?j.payloadTemplate=e.payloadTemplate:void 0!==k&&(j.payloadTemplate=k)}else if("static"===i){let a=Array.isArray(e.entries)?e.entries:[],b=[];for(let c=0;c<a.length&&b.length<200;c++){let d=a[c];if(!d||"object"!=typeof d){x("static-invalid-entry",`Node "${f}": entry #${c+1} is not an object; dropped.`,f);continue}if("message"===d.kind){let a=d.role,e=d.content;if(("system"===a||"user"===a||"assistant"===a)&&"string"==typeof e){let c=Array.isArray(d.attachments)?d.attachments.flatMap(a=>a&&"object"==typeof a?"document"!==a.type&&"audio"!==a.type&&"image"!==a.type&&"video"!==a.type||"string"!=typeof a.content?[]:[{type:a.type,content:a.content,..."string"==typeof a.id?{id:a.id}:{},..."string"==typeof a.originalName?{originalName:a.originalName}:{},..."string"==typeof a.mimeType?{mimeType:a.mimeType}:{},..."string"==typeof a.transcript?{transcript:a.transcript}:{}}]:[]):[];b.push({kind:"message",role:a,content:e,...c.length>0?{attachments:c}:{}})}else x("static-invalid-entry",`Node "${f}": message entry #${c+1} has an invalid role/content; dropped.`,f)}else if("toolCall"===d.kind){let a=d.toolName,e=d.argumentsJson,g=d.result;if("string"==typeof a&&a.trim()&&"string"==typeof e&&"string"==typeof g){let h="real"===d.executionMode?"real":"mock",i="string"==typeof d.serverName?d.serverName.trim():"";if("real"!==h||i?b.push({kind:"toolCall",toolName:a,argumentsJson:e,result:g,..."real"===d.executionMode||"mock"===d.executionMode?{executionMode:h}:{},...i?{serverName:i}:{}}):(x("static-real-toolcall-missing-server",`Node "${f}": real tool-call entry #${c+1} needs a serverName; kept as a mock.`,f),b.push({kind:"toolCall",toolName:a,argumentsJson:e,result:g,executionMode:"mock"})),e.trim())try{JSON.parse(e)}catch{x("static-toolcall-invalid-json",`Node "${f}": tool-call entry #${c+1} has invalid JSON arguments.`,f)}}else x("static-invalid-entry",`Node "${f}": tool-call entry #${c+1} is missing toolName/argumentsJson/result; dropped.`,f)}else x("static-invalid-entry",`Node "${f}": entry #${c+1} has unknown kind "${String(d.kind)}"; dropped.`,f)}a.length>200&&x("static-too-many-entries",`Node "${f}": only the first 200 entries were kept.`,f),b.length>0?j.entries=b:x("static-no-entries",`Node "${f}": a static node has no entries; it injects nothing.`,f),!0===e.injectOnce?j.injectOnce=!0:void 0!==e.injectOnce&&"boolean"!=typeof e.injectOnce&&x("static-invalid-injectonce",`Node "${f}": injectOnce must be a boolean; value ignored.`,f)}let l={id:(0,d.A)(),type:i,position:{x:0,y:0},data:{label:"finish"===i?"Finish Node":e.label||`${i.charAt(0).toUpperCase()}${i.slice(1)} Node`,type:i,...e.description?{description:e.description}:{},properties:j}};K.set(f,l),L.push(l);let s=Array.isArray(e.servers)?e.servers.map(a=>({...a,...Array.isArray(a.tools)?{tools:[...a.tools]}:{}})):[];if("static"===i)for(let a of j.entries??[]){if("toolCall"!==a.kind||"real"!==a.executionMode||!a.serverName)continue;let b=s.find(b=>b.name===a.serverName);b?Array.isArray(b.tools)?b.tools.includes(a.toolName)||b.tools.push(a.toolName):b.tools=[a.toolName]:s.push({name:a.serverName,tools:[a.toolName]})}if(("process"===i||"static"===i)&&s.length>0){let a=new Set;for(let b of s){let c,e=b?.name;if(!e||"string"!=typeof e){x("server-missing-name",`Node "${f}": a server reference is missing its "name"; skipped.`,f);continue}if(a.has(e))continue;a.add(e),z.has(e)||x("server-unknown",`Node "${f}": MCP server "${e}" is not configured in FLUJO.`,f);let g=A[e];if(Array.isArray(b.tools)){if(c=b.tools.filter(a=>"string"==typeof a&&a),g){let a=c.filter(a=>!g.includes(a));a.length>0&&x("tool-unknown",`Node "${f}": server "${e}" does not report tool(s): ${a.join(", ")}.`,f)}}else c=g?[...g]:[];let h={id:(0,d.A)(),type:"mcp",position:{x:0,y:0},data:{label:e,type:"mcp",properties:{boundServer:e,enabledTools:c}}};L.push(h),M.push({consumerKey:f,mcpNode:h})}}else"process"!==i&&"static"!==i&&s.length>0&&x("servers-on-unsupported-node",`Node "${f}": only process and static nodes can have "servers"; ignored.`,f)}if(0===K.size)return w("no-usable-nodes","No usable nodes — the spec must contain at least a start node and one step."),null;let O=[],P=new Set;for(let a of u){let b,c=a?.from,d=a?.to,e=c?K.get(c):void 0,g=d?K.get(d):void 0;if(!e||!g){w("edge-unknown-node",`Edge "${String(c)}" -> "${String(d)}" references a node key that does not exist (or was dropped).`);continue}if(e===g){w("edge-self-loop",`Edge "${c}" -> "${d}": a node cannot connect to itself.`);continue}if("resource"===e.type||"resource"===g.type){if(("resource"!==e.type||"process"!==g.type)&&("process"!==e.type||"resource"!==g.type)){w("resource-edge-invalid",`Edge "${c}" -> "${d}": resource nodes connect only to process nodes.`);continue}a.condition&&x("resource-edge-condition",`Edge "${c}" -> "${d}": conditions do not apply to resource wiring; dropped.`),!0===a.bidirectional&&x("resource-edge-bidirectional",`Edge "${c}" -> "${d}": resource wiring is directional (read vs write); "bidirectional" was ignored — add the opposite edge explicitly if the step both reads and writes.`);let b=`${c}->${d}`;if(P.has(b)){x("edge-duplicate",`Edge "${c}" -> "${d}" appears more than once; kept the first.`);continue}P.add(b),O.push(function(a,b){let c="resource"===a.type?"resource-out":"process-right-resource",d="resource"===b.type?"resource-in":"process-left-resource";return{id:`${a.id}:${c}->${b.id}:${d}`,source:a.id,sourceHandle:c,target:b.id,targetHandle:d,type:"resourceEdge",data:{edgeType:"resource"},animated:!1,markerEnd:{...k},style:{...l}}}(e,g));continue}if("start"===g.type){w("edge-into-start",`Edge "${c}" -> "${d}": nothing may connect INTO a start node.`);continue}if("finish"===e.type){w("edge-out-of-finish",`Edge "${c}" -> "${d}": nothing may connect OUT OF a finish node.`);continue}let h=`${c}->${d}`;if(P.has(h)){x("edge-duplicate",`Edge "${c}" -> "${d}" appears more than once; kept the first.`);continue}P.add(h);let i=!0===a.bidirectional;i&&("start"===e.type||"finish"===g.type)&&(x("bidirectional-illegal",`Edge "${c}" -> "${d}" cannot be bidirectional; downgraded to one-way.`),i=!1);let j=a.condition;j&&"object"==typeof j&&("process"!==e.type?x("edge-condition-non-process",`Edge "${c}" -> "${d}" has a condition but leaves a ${e.type} node; conditions only route from process nodes and were dropped.`):(0,f.C)(j.kind)?"always"===j.kind?b={kind:"always",..."last-message"===j.target?{target:"last-message"}:{},...!0===j.negate?{negate:!0}:{}}:"string"!=typeof j.value||0===j.value.length?x("edge-condition-value",`Edge "${c}" -> "${d}" has a condition with no "value"; the condition was dropped.`):("regex"!==j.kind||(0,f.wM)(j.value)||x("edge-condition-regex",`Edge "${c}" -> "${d}" has a regex condition that does not compile; it is kept but will never match at runtime.`),b={kind:j.kind,value:j.value,..."last-message"===j.target?{target:"last-message"}:{},...!0===j.ignoreCase?{ignoreCase:!0}:{},...!0===j.negate?{negate:!0}:{}}):x("edge-condition-kind",`Edge "${c}" -> "${d}" has an unknown condition kind "${String(j.kind)}"; the condition was dropped.`)),O.push(function(a,b,c,d){let e=`${a.type}-bottom`,f=`${b.type}-top`;return{id:`${a.id}:${e}->${b.id}:${f}`,source:a.id,sourceHandle:e,target:b.id,targetHandle:f,type:"custom",data:{edgeType:"standard",...c?{bidirectional:!0}:{},...d?{condition:d}:{}},animated:!0}}(e,g,i,b))}for(let{consumerKey:a,mcpNode:b}of M){let c=K.get(a);O.push(function(a,b){let c="static"===a.type?"static-right-mcp":"process-right-mcp",d="mcp-left";return{id:`${a.id}:${c}->${b.id}:${d}`,source:a.id,sourceHandle:c,target:b.id,targetHandle:d,type:"mcpEdge",data:{edgeType:"mcp"},animated:!1,markerEnd:{...i},markerStart:{...i},style:{...j}}}(c,b))}!function(a,b,c,d){let e=new Map;for(let a of b){let b=a.data?.edgeType;"mcp"!==b&&"resource"!==b&&(e.has(a.source)||e.set(a.source,[]),e.get(a.source).push(a.target))}let f=[...a.values()],g=f.filter(a=>"resource"===a.type),h=f.filter(a=>"resource"!==a.type),i=h.filter(a=>"start"===a.type),j=i.length>0?i:h.slice(0,1),k=new Map,l=j.map(a=>({id:a.id,depth:0}));for(let a of l)k.set(a.id,0);for(;l.length;){let{id:a,depth:b}=l.shift();for(let c of e.get(a)??[])k.has(c)||(k.set(c,b+1),l.push({id:c,depth:b+1}))}let m=0;for(let a of k.values())m=Math.max(m,a);for(let a of h)k.has(a.id)||k.set(a.id,m+1);let n=new Map;for(let[b,c]of a)n.set(c.id,b);let o=new Map;for(let a of h){let b=n.get(a.id),c=d&&b?d[b]:void 0;if(c&&"number"==typeof c.x&&"number"==typeof c.y){a.position={x:c.x,y:c.y};continue}let e=k.get(a.id),f=o.get(e)??0;o.set(e,f+1),a.position={x:250+280*f,y:150+170*e}}let p=new Map;for(let{consumerKey:b,mcpNode:d}of c){let c=a.get(b),e=p.get(b)??0;p.set(b,e+1),d.position={x:c.position.x+320,y:c.position.y+150*e}}let q=new Map(f.map(a=>[a.id,a])),r=new Map,s=0;for(let a of g){let c=n.get(a.id),e=d&&c?d[c]:void 0;if(e&&"number"==typeof e.x&&"number"==typeof e.y){a.position={x:e.x,y:e.y};continue}let f=b.find(b=>b.data?.edgeType==="resource"&&(b.source===a.id||b.target===a.id)),g=f?f.source===a.id?f.target:f.source:void 0,i=g?q.get(g):void 0;if(i){let b=r.get(i.id)??0;r.set(i.id,b+1),a.position={x:i.position.x-320,y:i.position.y+150*b}}else{let b=0;for(let a of h)b=Math.max(b,a.position.y);a.position={x:250+280*s,y:b+170},s++}}}(K,O,M,0===g?c.positions:void 0);let Q={id:I,name:v,...e?.description?{description:e.description}:{},nodes:L,edges:O};return D.push(Q),F.push({id:Q.id,name:Q.name}),Q}(a,0,[]),g=D,u=(t=v).filter(a=>"error"===a.severity).length,{flow:e,flows:g,issues:t,errorCount:u,warningCount:t.length-u};function H(a,b){void 0!==a.concurrencyLimit&&("number"!=typeof a.concurrencyLimit||Number.isNaN(a.concurrencyLimit)?x("invalid-concurrency-limit",`Node "${a.key}": concurrencyLimit "${String(a.concurrencyLimit)}" is not a number; using the runtime default.`,a.key):b.concurrencyLimit=Math.max(1,Math.floor(a.concurrencyLimit))),"string"==typeof a.joinSeparator&&(b.joinSeparator=a.joinSeparator),void 0!==a.errorStrategy&&("fail-fast"===a.errorStrategy||"collect-all"===a.errorStrategy?b.errorStrategy=a.errorStrategy:x("invalid-error-strategy",`Node "${a.key}": errorStrategy "${String(a.errorStrategy)}" is not valid (fail-fast | collect-all); using collect-all.`,a.key))}}},97291:(a,b,c)=>{"use strict";let d,e,f;c.d(b,{M4:()=>gD});var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,aa,ab,ac,ad,ae,af,ag,ah,ai,aj,ak,al,am,an,ao,ap,aq,ar,as,at,au,av,aw,ax,ay,az,aA,aB,aC,aD,aE,aF,aG,aH,aI,aJ,aK,aL,aM,aN,aO,aP,aQ,aR,aS,aT,aU,aV,aW,aX,aY,aZ,a$,a_,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,ba,bb,bc,bd,be,bf,bg,bh,bi,bj,bk,bl,bm,bn,bo,bp,bq,br,bs,bt,bu,bv,bw,bx,by,bz,bA,bB,bC,bD,bE,bF,bG,bH,bI,bJ,bK,bL,bM,bN,bO=c(62928),bP=c(28325),bQ=c(29021),bR=c(79748),bS=c(57075),bT=c(46466);c(75397),c(20704),c(24869),c(7310),c(95570),c(1093);var bU=c(28942);c(43082);var bV=c(33873);class bW{}function bX(a,b){return a.replace(/\{([^}]+)\}/g,(a,c)=>{if(Object.prototype.hasOwnProperty.call(b,c)){let a=b[c];return null!=a?String(a):""}throw Error(`Key '${c}' not found in valueMap.`)})}function bY(a,b,c){for(let d=0;d<b.length-1;d++){let e=b[d];if(e.endsWith("[]")){let f=e.slice(0,-2);if(!(f in a))if(Array.isArray(c))a[f]=Array.from({length:c.length},()=>({}));else throw Error(`Value must be a list given an array path ${e}`);if(Array.isArray(a[f])){let e=a[f];if(Array.isArray(c))for(let a=0;a<e.length;a++)bY(e[a],b.slice(d+1),c[a]);else for(let a of e)bY(a,b.slice(d+1),c)}return}if(e.endsWith("[0]")){let f=e.slice(0,-3);f in a||(a[f]=[{}]),bY(a[f][0],b.slice(d+1),c);return}a[e]&&"object"==typeof a[e]||(a[e]={}),a=a[e]}let d=b[b.length-1],e=a[d];if(void 0!==e){if(!c||"object"==typeof c&&0===Object.keys(c).length||c===e)return;if("object"==typeof e&&"object"==typeof c&&null!==e&&null!==c)Object.assign(e,c);else throw Error(`Cannot set value for an existing key. Key: ${d}`)}else"_self"!==d||"object"!=typeof c||null===c||Array.isArray(c)?a[d]=c:Object.assign(a,c)}function bZ(a,b,c){try{if(1===b.length&&"_self"===b[0])return a;for(let d=0;d<b.length;d++){if("object"!=typeof a||null===a)return c;let e=b[d];if(e.endsWith("[]")){let f=e.slice(0,-2);if(!(f in a))return c;{let e=a[f];if(!Array.isArray(e))return c;return e.map(a=>bZ(a,b.slice(d+1),c))}}a=a[e]}return a}catch(a){if(a instanceof TypeError)return c;throw a}}function b$(a){if("string"!=typeof a)throw Error("fromImageBytes must be a string");return a}function b_(a){var b;let c,d,e,f,g={},h=bZ(a,["name"]);null!=h&&bY(g,["name"],h);let i=bZ(a,["metadata"]);null!=i&&bY(g,["metadata"],i);let j=bZ(a,["done"]);null!=j&&bY(g,["done"],j);let k=bZ(a,["error"]);null!=k&&bY(g,["error"],k);let l=bZ(a,["response"]);return null!=l&&bY(g,["response"],(c={},null!=(d=bZ(b=l,["sdkHttpResponse"]))&&bY(c,["sdkHttpResponse"],d),null!=(e=bZ(b,["parent"]))&&bY(c,["parent"],e),null!=(f=bZ(b,["documentName"]))&&bY(c,["documentName"],f),c)),g}(g=aB||(aB={})).OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",g.OUTCOME_OK="OUTCOME_OK",g.OUTCOME_FAILED="OUTCOME_FAILED",g.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED",(h=aC||(aC={})).LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",h.PYTHON="PYTHON",(i=aD||(aD={})).SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",i.SILENT="SILENT",i.WHEN_IDLE="WHEN_IDLE",i.INTERRUPT="INTERRUPT",(j=aE||(aE={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",j.STRING="STRING",j.NUMBER="NUMBER",j.INTEGER="INTEGER",j.BOOLEAN="BOOLEAN",j.ARRAY="ARRAY",j.OBJECT="OBJECT",j.NULL="NULL",(k=aF||(aF={})).AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",k.NO_AUTH="NO_AUTH",k.API_KEY_AUTH="API_KEY_AUTH",k.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",k.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",k.OAUTH="OAUTH",k.OIDC_AUTH="OIDC_AUTH",(l=aG||(aG={})).HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",l.HTTP_IN_QUERY="HTTP_IN_QUERY",l.HTTP_IN_HEADER="HTTP_IN_HEADER",l.HTTP_IN_PATH="HTTP_IN_PATH",l.HTTP_IN_BODY="HTTP_IN_BODY",l.HTTP_IN_COOKIE="HTTP_IN_COOKIE",(m=aH||(aH={})).API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",m.SIMPLE_SEARCH="SIMPLE_SEARCH",m.ELASTIC_SEARCH="ELASTIC_SEARCH",(n=aI||(aI={})).ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",n.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",n.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",n.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP",(o=aJ||(aJ={})).SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",o.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",o.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",o.COMMUNICATION_TOOL="COMMUNICATION_TOOL",o.ACCOUNT_CREATION="ACCOUNT_CREATION",o.DATA_MODIFICATION="DATA_MODIFICATION",o.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",o.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS",(p=aK||(aK={})).PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",p.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",p.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",p.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",p.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",p.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",p.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH",(q=aL||(aL={})).UNSPECIFIED="UNSPECIFIED",q.BLOCKING="BLOCKING",q.NON_BLOCKING="NON_BLOCKING",(r=aM||(aM={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",r.MODE_DYNAMIC="MODE_DYNAMIC",(s=aN||(aN={})).THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",s.MINIMAL="MINIMAL",s.LOW="LOW",s.MEDIUM="MEDIUM",s.HIGH="HIGH",(t=aO||(aO={})).DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL",(u=aP||(aP={})).PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",u.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",u.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE",(v=aQ||(aQ={})).HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",v.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",v.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",v.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",v.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",v.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",v.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",v.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",v.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",v.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",v.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",(w=aR||(aR={})).HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",w.SEVERITY="SEVERITY",w.PROBABILITY="PROBABILITY",(x=aS||(aS={})).HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",x.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",x.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",x.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",x.BLOCK_NONE="BLOCK_NONE",x.OFF="OFF",(y=aT||(aT={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",y.AUTO="AUTO",y.ANY="ANY",y.NONE="NONE",y.VALIDATED="VALIDATED",(z=aU||(aU={})).FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",z.STOP="STOP",z.MAX_TOKENS="MAX_TOKENS",z.SAFETY="SAFETY",z.RECITATION="RECITATION",z.LANGUAGE="LANGUAGE",z.OTHER="OTHER",z.BLOCKLIST="BLOCKLIST",z.PROHIBITED_CONTENT="PROHIBITED_CONTENT",z.SPII="SPII",z.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",z.IMAGE_SAFETY="IMAGE_SAFETY",z.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",z.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",z.NO_IMAGE="NO_IMAGE",z.IMAGE_RECITATION="IMAGE_RECITATION",z.IMAGE_OTHER="IMAGE_OTHER",(A=aV||(aV={})).HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",A.NEGLIGIBLE="NEGLIGIBLE",A.LOW="LOW",A.MEDIUM="MEDIUM",A.HIGH="HIGH",(B=aW||(aW={})).HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",B.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",B.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",B.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",B.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH",(C=aX||(aX={})).URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",C.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",C.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",C.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",C.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE",(D=aY||(aY={})).BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",D.SAFETY="SAFETY",D.OTHER="OTHER",D.BLOCKLIST="BLOCKLIST",D.PROHIBITED_CONTENT="PROHIBITED_CONTENT",D.IMAGE_SAFETY="IMAGE_SAFETY",D.MODEL_ARMOR="MODEL_ARMOR",D.JAILBREAK="JAILBREAK",(E=aZ||(aZ={})).TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",E.ON_DEMAND="ON_DEMAND",E.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",E.ON_DEMAND_FLEX="ON_DEMAND_FLEX",E.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT",(F=a$||(a$={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",F.TEXT="TEXT",F.IMAGE="IMAGE",F.VIDEO="VIDEO",F.AUDIO="AUDIO",F.DOCUMENT="DOCUMENT",(G=a_||(a_={})).MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",G.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",G.EXPERIMENTAL="EXPERIMENTAL",G.PREVIEW="PREVIEW",G.STABLE="STABLE",G.LEGACY="LEGACY",G.DEPRECATED="DEPRECATED",G.RETIRED="RETIRED",(H=a0||(a0={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",H.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",H.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",H.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",(I=a1||(a1={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",I.TEXT="TEXT",I.IMAGE="IMAGE",I.AUDIO="AUDIO",I.VIDEO="VIDEO",(J=a2||(a2={})).DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",J.INLINE="INLINE",J.URI="URI",(K=a3||(a3={})).ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",K.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",K.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",K.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",K.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",K.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",K.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",K.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",K.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",K.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",K.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",K.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",K.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",K.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",K.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE",(L=a4||(a4={})).IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",L.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",L.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",L.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",L.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K",(M=a5||(a5={})).TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",M.TUNING_MODE_FULL="TUNING_MODE_FULL",M.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER",(N=a6||(a6={})).ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",N.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",N.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",N.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",N.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",N.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",N.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO",(O=a7||(a7={})).RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",O.IDENTITY="IDENTITY",O.REGEX_EXTRACT="REGEX_EXTRACT",(P=a8||(a8={})).MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",P.REGEX_CONTAINS="REGEX_CONTAINS",P.PARTIAL_MATCH="PARTIAL_MATCH",P.EXACT_MATCH="EXACT_MATCH",(Q=a9||(a9={})).REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",Q.MINIMAL="MINIMAL",Q.HIGH="HIGH",(R=ba||(ba={})).JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",R.JOB_STATE_QUEUED="JOB_STATE_QUEUED",R.JOB_STATE_PENDING="JOB_STATE_PENDING",R.JOB_STATE_RUNNING="JOB_STATE_RUNNING",R.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",R.JOB_STATE_FAILED="JOB_STATE_FAILED",R.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",R.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",R.JOB_STATE_PAUSED="JOB_STATE_PAUSED",R.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",R.JOB_STATE_UPDATING="JOB_STATE_UPDATING",R.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED",(S=bb||(bb={})).TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",S.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",S.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",S.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",S.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",S.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING",(T=bc||(bc={})).AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",T.AVERAGE="AVERAGE",T.MODE="MODE",T.STANDARD_DEVIATION="STANDARD_DEVIATION",T.VARIANCE="VARIANCE",T.MINIMUM="MINIMUM",T.MAXIMUM="MAXIMUM",T.MEDIAN="MEDIAN",T.PERCENTILE_P90="PERCENTILE_P90",T.PERCENTILE_P95="PERCENTILE_P95",T.PERCENTILE_P99="PERCENTILE_P99",(U=bd||(bd={})).PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",U.BASELINE="BASELINE",U.CANDIDATE="CANDIDATE",U.TIE="TIE",(V=be||(be={})).VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",V.LANDSCAPE="LANDSCAPE",V.PORTRAIT="PORTRAIT",(W=bf||(bf={})).TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",W.REGULAR="REGULAR",W.FAST="FAST",(X=bg||(bg={})).TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",X.TUNING_TASK_I2V="TUNING_TASK_I2V",X.TUNING_TASK_T2V="TUNING_TASK_T2V",X.TUNING_TASK_R2V="TUNING_TASK_R2V",(Y=bh||(bh={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",Y.STATE_PENDING="STATE_PENDING",Y.STATE_ACTIVE="STATE_ACTIVE",Y.STATE_FAILED="STATE_FAILED",(Z=bi||(bi={})).UNSPECIFIED="unspecified",Z.FLEX="flex",Z.STANDARD="standard",Z.PRIORITY="priority",($=bj||(bj={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",$.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",$.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",$.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",$.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH",(_=bk||(bk={})).TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",_.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",_.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",_.URL_CONTEXT="URL_CONTEXT",_.GOOGLE_MAPS="GOOGLE_MAPS",_.FILE_SEARCH="FILE_SEARCH",(bl||(bl={})).COLLECTION="COLLECTION",(aa=bm||(bm={})).FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",aa.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",aa.BALANCED="BALANCED",aa.PRIORITIZE_COST="PRIORITIZE_COST",(ab=bn||(bn={})).PREDICT="PREDICT",ab.EMBED_CONTENT="EMBED_CONTENT",(ac=bo||(bo={})).BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",ac.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",ac.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",ac.BLOCK_NONE="BLOCK_NONE",(ad=bp||(bp={})).auto="auto",ad.en="en",ad.ja="ja",ad.ko="ko",ad.hi="hi",ad.zh="zh",ad.pt="pt",ad.es="es",(ae=bq||(bq={})).MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",ae.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",ae.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",ae.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",ae.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC",(af=br||(br={})).CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",af.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",af.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",af.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH",(ag=bs||(bs={})).SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",ag.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",ag.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",ag.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT",(ah=bt||(bt={})).EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",ah.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",ah.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",ah.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",ah.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",ah.EDIT_MODE_STYLE="EDIT_MODE_STYLE",ah.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",ah.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE",(ai=bu||(bu={})).FOREGROUND="FOREGROUND",ai.BACKGROUND="BACKGROUND",ai.PROMPT="PROMPT",ai.SEMANTIC="SEMANTIC",ai.INTERACTIVE="INTERACTIVE",(aj=bv||(bv={})).ASSET="ASSET",aj.STYLE="STYLE",(ak=bw||(bw={})).INSERT="INSERT",ak.REMOVE="REMOVE",ak.REMOVE_STATIC="REMOVE_STATIC",ak.OUTPAINT="OUTPAINT",(al=bx||(bx={})).OPTIMIZED="OPTIMIZED",al.LOSSLESS="LOSSLESS",(am=by||(by={})).CROP="CROP",am.PAD="PAD",(an=bz||(bz={})).SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",an.PREFERENCE_TUNING="PREFERENCE_TUNING",an.DISTILLATION="DISTILLATION",an.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING",(ao=bA||(bA={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",ao.PROCESSING="PROCESSING",ao.ACTIVE="ACTIVE",ao.FAILED="FAILED",(ap=bB||(bB={})).SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",ap.UPLOADED="UPLOADED",ap.GENERATED="GENERATED",ap.REGISTERED="REGISTERED",(aq=bC||(bC={})).TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",aq.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",aq.RESPONSE_REJECTED="RESPONSE_REJECTED",aq.NEED_MORE_INPUT="NEED_MORE_INPUT",aq.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",aq.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",aq.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",aq.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",aq.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",aq.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",aq.INPUT_OTHER="INPUT_OTHER",aq.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",aq.BLOCKLIST="BLOCKLIST",aq.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",aq.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",aq.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",aq.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",aq.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",aq.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",aq.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",aq.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",aq.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",aq.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",aq.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",aq.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",aq.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",aq.GENERATED_OTHER="GENERATED_OTHER",aq.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED",(ar=bD||(bD={})).VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",ar.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",ar.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS",(as=bE||(bE={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",as.ACTIVITY_START="ACTIVITY_START",as.ACTIVITY_END="ACTIVITY_END",(at=bF||(bF={})).START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",at.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",at.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW",(au=bG||(bG={})).END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",au.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",au.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW",(av=bH||(bH={})).ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",av.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",av.NO_INTERRUPTION="NO_INTERRUPTION",(aw=bI||(bI={})).TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",aw.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",aw.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",aw.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO",(ax=bJ||(bJ={})).SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",ax.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",ax.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",ax.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",ax.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",ax.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",ax.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",ax.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",ax.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",ax.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",ax.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",ax.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",ax.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR",(ay=bK||(bK={})).MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",ay.QUALITY="QUALITY",ay.DIVERSITY="DIVERSITY",ay.VOCALIZATION="VOCALIZATION",(az=bL||(bL={})).PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",az.PLAY="PLAY",az.PAUSE="PAUSE",az.STOP="STOP",az.RESET_CONTEXT="RESET_CONTEXT";class b0{constructor(a){const b={};for(const c of a.headers.entries())b[c[0]]=c[1];this.headers=b,this.responseInternal=a}json(){return this.responseInternal.json()}}class b1{get text(){var a,b,c,d,e,f,g,h;if((null==(d=null==(c=null==(b=null==(a=this.candidates)?void 0:a[0])?void 0:b.content)?void 0:c.parts)?void 0:d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let i="",j=!1,k=[];for(let a of null!=(h=null==(g=null==(f=null==(e=this.candidates)?void 0:e[0])?void 0:f.content)?void 0:g.parts)?h:[]){for(let[b,c]of Object.entries(a))"text"!==b&&"thought"!==b&&"thoughtSignature"!==b&&(null!==c||void 0!==c)&&k.push(b);if("string"==typeof a.text){if("boolean"==typeof a.thought&&a.thought)continue;j=!0,i+=a.text}}return k.length>0&&console.warn(`there are non-text parts ${k} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),j?i:void 0}get data(){var a,b,c,d,e,f,g,h;if((null==(d=null==(c=null==(b=null==(a=this.candidates)?void 0:a[0])?void 0:b.content)?void 0:c.parts)?void 0:d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let i="",j=[];for(let a of null!=(h=null==(g=null==(f=null==(e=this.candidates)?void 0:e[0])?void 0:f.content)?void 0:g.parts)?h:[]){for(let[b,c]of Object.entries(a))"inlineData"!==b&&(null!==c||void 0!==c)&&j.push(b);a.inlineData&&"string"==typeof a.inlineData.data&&(i+=atob(a.inlineData.data))}return j.length>0&&console.warn(`there are non-data parts ${j} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),i.length>0?btoa(i):void 0}get functionCalls(){var a,b,c,d,e,f,g,h;if((null==(d=null==(c=null==(b=null==(a=this.candidates)?void 0:a[0])?void 0:b.content)?void 0:c.parts)?void 0:d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let i=null==(h=null==(g=null==(f=null==(e=this.candidates)?void 0:e[0])?void 0:f.content)?void 0:g.parts)?void 0:h.filter(a=>a.functionCall).map(a=>a.functionCall).filter(a=>void 0!==a);if((null==i?void 0:i.length)!==0)return i}get executableCode(){var a,b,c,d,e,f,g,h,i;if((null==(d=null==(c=null==(b=null==(a=this.candidates)?void 0:a[0])?void 0:b.content)?void 0:c.parts)?void 0:d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let j=null==(h=null==(g=null==(f=null==(e=this.candidates)?void 0:e[0])?void 0:f.content)?void 0:g.parts)?void 0:h.filter(a=>a.executableCode).map(a=>a.executableCode).filter(a=>void 0!==a);if((null==j?void 0:j.length)!==0)return null==(i=null==j?void 0:j[0])?void 0:i.code}get codeExecutionResult(){var a,b,c,d,e,f,g,h,i;if((null==(d=null==(c=null==(b=null==(a=this.candidates)?void 0:a[0])?void 0:b.content)?void 0:c.parts)?void 0:d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let j=null==(h=null==(g=null==(f=null==(e=this.candidates)?void 0:e[0])?void 0:f.content)?void 0:g.parts)?void 0:h.filter(a=>a.codeExecutionResult).map(a=>a.codeExecutionResult).filter(a=>void 0!==a);if((null==j?void 0:j.length)!==0)return null==(i=null==j?void 0:j[0])?void 0:i.output}}class b2{}class b3{}class b4{}class b5{}class b6{}class b7{}class b8{}class b9{}class ca{}class cb{}class cc{_fromAPIResponse({apiResponse:a,_isVertexAI:b}){let c,d=new cc;if(b){let b,d,e,f,g,h;b={},null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["metadata"]))&&bY(b,["metadata"],e),null!=(f=bZ(a,["done"]))&&bY(b,["done"],f),null!=(g=bZ(a,["error"]))&&bY(b,["error"],g),null!=(h=bZ(a,["response"]))&&bY(b,["response"],function(a){let b={},c=bZ(a,["videos"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h;return c={},null!=(d=bZ(a,["_self"]))&&bY(c,["video"],(e={},null!=(f=bZ(b=d,["gcsUri"]))&&bY(e,["uri"],f),null!=(g=bZ(b,["bytesBase64Encoded"]))&&bY(e,["videoBytes"],b$(g)),null!=(h=bZ(b,["mimeType"]))&&bY(e,["mimeType"],h),e)),c})),bY(b,["generatedVideos"],a)}let d=bZ(a,["raiMediaFilteredCount"]);null!=d&&bY(b,["raiMediaFilteredCount"],d);let e=bZ(a,["raiMediaFilteredReasons"]);return null!=e&&bY(b,["raiMediaFilteredReasons"],e),b}(h)),c=b}else{let b,d,e,f,g,h;b={},null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["metadata"]))&&bY(b,["metadata"],e),null!=(f=bZ(a,["done"]))&&bY(b,["done"],f),null!=(g=bZ(a,["error"]))&&bY(b,["error"],g),null!=(h=bZ(a,["response","generateVideoResponse"]))&&bY(b,["response"],function(a){let b={},c=bZ(a,["generatedSamples"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h;return c={},null!=(d=bZ(a,["video"]))&&bY(c,["video"],(e={},null!=(f=bZ(b=d,["uri"]))&&bY(e,["uri"],f),null!=(g=bZ(b,["encodedVideo"]))&&bY(e,["videoBytes"],b$(g)),null!=(h=bZ(b,["encoding"]))&&bY(e,["mimeType"],h),e)),c})),bY(b,["generatedVideos"],a)}let d=bZ(a,["raiMediaFilteredCount"]);null!=d&&bY(b,["raiMediaFilteredCount"],d);let e=bZ(a,["raiMediaFilteredReasons"]);return null!=e&&bY(b,["raiMediaFilteredReasons"],e),b}(h)),c=b}return Object.assign(d,c),d}}class cd{}class ce{}class cf{}class cg{}class ch{}class ci{}class cj{}class ck{}class cl{_fromAPIResponse({apiResponse:a,_isVertexAI:b}){var c;let d,e,f,g,h,i,j,k,l,m,n=new cl;return Object.assign(n,(h={},null!=(i=bZ(a,["name"]))&&bY(h,["name"],i),null!=(j=bZ(a,["metadata"]))&&bY(h,["metadata"],j),null!=(k=bZ(a,["done"]))&&bY(h,["done"],k),null!=(l=bZ(a,["error"]))&&bY(h,["error"],l),null!=(m=bZ(a,["response"]))&&bY(h,["response"],(d={},null!=(e=bZ(c=m,["sdkHttpResponse"]))&&bY(d,["sdkHttpResponse"],e),null!=(f=bZ(c,["parent"]))&&bY(d,["parent"],f),null!=(g=bZ(c,["documentName"]))&&bY(d,["documentName"],g),d)),h)),n}}class cm{}class cn{}class co{}class cp{}class cq{}class cr{get text(){var a,b,c;let d="",e=!1,f=[];for(let g of null!=(c=null==(b=null==(a=this.serverContent)?void 0:a.modelTurn)?void 0:b.parts)?c:[]){for(let[a,b]of Object.entries(g))"text"!==a&&"thought"!==a&&null!==b&&f.push(a);if("string"==typeof g.text){if("boolean"==typeof g.thought&&g.thought)continue;e=!0,d+=g.text}}return f.length>0&&console.warn(`there are non-text parts ${f} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),e?d:void 0}get data(){var a,b,c;let d="",e=[];for(let f of null!=(c=null==(b=null==(a=this.serverContent)?void 0:a.modelTurn)?void 0:b.parts)?c:[]){for(let[a,b]of Object.entries(f))"inlineData"!==a&&null!==b&&e.push(a);f.inlineData&&"string"==typeof f.inlineData.data&&(d+=atob(f.inlineData.data))}return e.length>0&&console.warn(`there are non-data parts ${e} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),d.length>0?btoa(d):void 0}}class cs{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class ct{_fromAPIResponse({apiResponse:a,_isVertexAI:b}){let c=new ct;return Object.assign(c,b_(a)),c}}function cu(a,b){if(!b||"string"!=typeof b)throw Error("model is required and must be a string");if(b.includes("..")||b.includes("?")||b.includes("&"))throw Error("invalid model parameter");if(a.isVertexAI())if(b.startsWith("publishers/")||b.startsWith("projects/")||b.startsWith("models/"))return b;else{if(!(b.indexOf("/")>=0))return`publishers/google/models/${b}`;let a=b.split("/",2);return`publishers/${a[0]}/models/${a[1]}`}return b.startsWith("models/")||b.startsWith("tunedModels/")?b:`models/${b}`}function cv(a,b){let c=cu(a,b);return c?c.startsWith("publishers/")&&a.isVertexAI()?`projects/${a.getProject()}/locations/${a.getLocation()}/${c}`:c.startsWith("models/")&&a.isVertexAI()?`projects/${a.getProject()}/locations/${a.getLocation()}/publishers/google/${c}`:c:""}function cw(a){return Array.isArray(a)?a.map(a=>cx(a)):[cx(a)]}function cx(a){if("object"==typeof a&&null!==a)return a;throw Error(`Could not parse input as Blob. Unsupported blob type: ${typeof a}`)}function cy(a){let b=cx(a);if(b.mimeType&&b.mimeType.startsWith("image/"))return b;throw Error(`Unsupported mime type: ${b.mimeType}`)}function cz(a){let b=cx(a);if(b.mimeType&&b.mimeType.startsWith("audio/"))return b;throw Error(`Unsupported mime type: ${b.mimeType}`)}function cA(a){if(null==a)throw Error("PartUnion is required");if("object"==typeof a)return a;if("string"==typeof a)return{text:a};throw Error(`Unsupported part type: ${typeof a}`)}function cB(a){if(null==a||Array.isArray(a)&&0===a.length)throw Error("PartListUnion is required");return Array.isArray(a)?a.map(a=>cA(a)):[cA(a)]}function cC(a){return null!=a&&"object"==typeof a&&"parts"in a&&Array.isArray(a.parts)}function cD(a){return null!=a&&"object"==typeof a&&"functionCall"in a}function cE(a){return null!=a&&"object"==typeof a&&"functionResponse"in a}function cF(a){if(null==a)throw Error("ContentUnion is required");return cC(a)?a:{role:"user",parts:cB(a)}}function cG(a,b){if(!b)return[];if(a.isVertexAI()&&Array.isArray(b))return b.flatMap(a=>{let b=cF(a);return b.parts&&b.parts.length>0&&void 0!==b.parts[0].text?[b.parts[0].text]:[]});if(a.isVertexAI()){let a=cF(b);return a.parts&&a.parts.length>0&&void 0!==a.parts[0].text?[a.parts[0].text]:[]}return Array.isArray(b)?b.map(a=>cF(a)):[cF(b)]}function cH(a){if(null==a||Array.isArray(a)&&0===a.length)throw Error("contents are required");if(!Array.isArray(a)){if(cD(a)||cE(a))throw Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[cF(a)]}let b=[],c=[],d=cC(a[0]);for(let e of a){let a=cC(e);if(a!=d)throw Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(a)b.push(e);else if(cD(e)||cE(e))throw Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");else c.push(e)}return d||b.push({role:"user",parts:cB(c)}),b}function cI(a){let b={},c=["items"],d=["anyOf"],e=["properties"];if(a.type&&a.anyOf)throw Error("type and anyOf cannot be both populated.");let f=a.anyOf;for(let[g,h]of(null!=f&&2==f.length&&("null"===f[0].type?(b.nullable=!0,a=f[1]):"null"===f[1].type&&(b.nullable=!0,a=f[0])),a.type instanceof Array&&function(a,b){a.includes("null")&&(b.nullable=!0);let c=a.filter(a=>"null"!==a);if(1===c.length)b.type=Object.values(aE).includes(c[0].toUpperCase())?c[0].toUpperCase():aE.TYPE_UNSPECIFIED;else for(let a of(b.anyOf=[],c))b.anyOf.push({type:Object.values(aE).includes(a.toUpperCase())?a.toUpperCase():aE.TYPE_UNSPECIFIED})}(a.type,b),Object.entries(a)))if(null!=h)if("type"==g){if("null"===h)throw Error("type: null can not be the only possible type for the field.");if(h instanceof Array)continue;b.type=Object.values(aE).includes(h.toUpperCase())?h.toUpperCase():aE.TYPE_UNSPECIFIED}else if(c.includes(g))b[g]=cI(h);else if(d.includes(g)){let a=[];for(let c of h){if("null"==c.type){b.nullable=!0;continue}a.push(cI(c))}b[g]=a}else if(e.includes(g)){let a={};for(let[b,c]of Object.entries(h))a[b]=cI(c);b[g]=a}else{if("additionalProperties"===g)continue;b[g]=h}return b}function cJ(a){if("object"==typeof a)return a;if("string"==typeof a)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:a}}};throw Error(`Unsupported speechConfig type: ${typeof a}`)}function cK(a){if("multiSpeakerVoiceConfig"in a)throw Error("multiSpeakerVoiceConfig is not supported in the live API.");return a}function cL(a){if(a.functionDeclarations)for(let b of a.functionDeclarations)b.parameters&&(Object.keys(b.parameters).includes("$schema")?b.parametersJsonSchema||(b.parametersJsonSchema=b.parameters,delete b.parameters):b.parameters=cI(b.parameters)),b.response&&(Object.keys(b.response).includes("$schema")?b.responseJsonSchema||(b.responseJsonSchema=b.response,delete b.response):b.response=cI(b.response));return a}function cM(a){if(null==a)throw Error("tools is required");if(!Array.isArray(a))throw Error("tools is required and must be an array of Tools");let b=[];for(let c of a)b.push(c);return b}function cN(a,b){if("string"!=typeof b)throw Error("name must be a string");return function(a,b,c,d=1){let e=!b.startsWith(`${c}/`)&&b.split("/").length===d;if(a.isVertexAI())if(b.startsWith("projects/"))return b;else if(b.startsWith("locations/"))return`projects/${a.getProject()}/${b}`;else if(b.startsWith(`${c}/`))return`projects/${a.getProject()}/locations/${a.getLocation()}/${b}`;else if(e)return`projects/${a.getProject()}/locations/${a.getLocation()}/${c}/${b}`;else return b;return e?`${c}/${b}`:b}(a,b,"cachedContents")}function cO(a){switch(a){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return a}}function cP(a){return null!=a&&"object"==typeof a&&"video"in a}function cQ(a){return null!=a&&"object"==typeof a&&"uri"in a}function cR(a){var b;let c;if(null!=a&&"object"==typeof a&&"name"in a&&(c=a.name),!cQ(a)||void 0!==(c=a.uri)){if(!cP(a)||void 0!==(c=null==(b=a.video)?void 0:b.uri)){if("string"==typeof a&&(c=a),void 0===c)throw Error("Could not extract file name from the provided input.");if(c.startsWith("https://")){let a=c.split("files/")[1].match(/[a-z0-9]+/);if(null===a)throw Error(`Could not extract file name from URI ${c}`);c=a[0]}else c.startsWith("files/")&&(c=c.split("files/")[1]);return c}}}function cS(a,b){return a.isVertexAI()?b?"publishers/google/models":"models":b?"models":"tunedModels"}function cT(a){for(let d of["models","tunedModels","publisherModels"]){var b,c;if(b=a,c=d,null!==b&&"object"==typeof b&&c in b)return a[d]}return[]}function cU(a,b){let c;if("string"==typeof b)if(a.isVertexAI())if(b.startsWith("gs://"))c={format:"jsonl",gcsUri:[b]};else if(b.startsWith("bq://"))c={format:"bigquery",bigqueryUri:b};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(b))c={format:"vertex-dataset",vertexDatasetName:b};else throw Error(`Unsupported string source for Vertex AI: ${b}`);else if(b.startsWith("files/"))c={fileName:b};else throw Error(`Unsupported string source for Gemini API: ${b}`);else if(Array.isArray(b)){if(a.isVertexAI())throw Error("InlinedRequest[] is not supported in Vertex AI.");c={inlinedRequests:b}}else c=b;let d=[c.gcsUri,c.bigqueryUri,c.vertexDatasetName].filter(Boolean).length,e=[c.inlinedRequests,c.fileName].filter(Boolean).length;if(a.isVertexAI()){if(e>0||1!==d)throw Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(d>0||1!==e)throw Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return c}function cV(a){if("object"!=typeof a||null===a)return{};let b=a.inlinedResponses;if("object"!=typeof b||null===b)return a;let c=b.inlinedResponses;if(!Array.isArray(c)||0===c.length)return a;let d=!1;for(let a of c){if("object"!=typeof a||null===a)continue;let b=a.response;if("object"==typeof b&&null!==b&&void 0!==b.embedding){d=!0;break}}return d&&(a.inlinedEmbedContentResponses=a.inlinedResponses,delete a.inlinedResponses),a}function cW(a,b){if(!a.isVertexAI()){if(/batches\/[^/]+$/.test(b))return b.split("/").pop();throw Error(`Invalid batch job name: ${b}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(b))return b.split("/").pop();if(/^\d+$/.test(b))return b;throw Error(`Invalid batch job name: ${b}.`)}function cX(a){if("BATCH_STATE_UNSPECIFIED"===a)return"JOB_STATE_UNSPECIFIED";if("BATCH_STATE_PENDING"===a)return"JOB_STATE_PENDING";if("BATCH_STATE_RUNNING"===a)return"JOB_STATE_RUNNING";if("BATCH_STATE_SUCCEEDED"===a)return"JOB_STATE_SUCCEEDED";if("BATCH_STATE_FAILED"===a)return"JOB_STATE_FAILED";else if("BATCH_STATE_CANCELLED"===a)return"JOB_STATE_CANCELLED";else if("BATCH_STATE_EXPIRED"===a)return"JOB_STATE_EXPIRED";else return a}function cY(a){let b={},c=bZ(a,["name"]);null!=c&&bY(b,["name"],c);let d=bZ(a,["metadata","displayName"]);null!=d&&bY(b,["displayName"],d);let e=bZ(a,["metadata","state"]);null!=e&&bY(b,["state"],cX(e));let f=bZ(a,["metadata","createTime"]);null!=f&&bY(b,["createTime"],f);let g=bZ(a,["metadata","endTime"]);null!=g&&bY(b,["endTime"],g);let h=bZ(a,["metadata","updateTime"]);null!=h&&bY(b,["updateTime"],h);let i=bZ(a,["metadata","model"]);null!=i&&bY(b,["model"],i);let j=bZ(a,["metadata","output"]);return null!=j&&bY(b,["dest"],function(a){let b={},c=bZ(a,["responsesFile"]);null!=c&&bY(b,["fileName"],c);let d=bZ(a,["inlinedResponses","inlinedResponses"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f;return c={},null!=(d=bZ(b=a,["response"]))&&bY(c,["response"],function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["candidates"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["content"]);null!=c&&bY(b,["content"],c);let d=bZ(a,["citationMetadata"]);null!=d&&bY(b,["citationMetadata"],function(a){let b={},c=bZ(a,["citationSources"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["citations"],a)}return b}(d));let e=bZ(a,["tokenCount"]);null!=e&&bY(b,["tokenCount"],e);let f=bZ(a,["finishReason"]);null!=f&&bY(b,["finishReason"],f);let g=bZ(a,["groundingMetadata"]);null!=g&&bY(b,["groundingMetadata"],g);let h=bZ(a,["avgLogprobs"]);null!=h&&bY(b,["avgLogprobs"],h);let i=bZ(a,["index"]);null!=i&&bY(b,["index"],i);let j=bZ(a,["logprobsResult"]);null!=j&&bY(b,["logprobsResult"],j);let k=bZ(a,["safetyRatings"]);if(null!=k){let a=k;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["safetyRatings"],a)}let l=bZ(a,["urlContextMetadata"]);return null!=l&&bY(b,["urlContextMetadata"],l),b})(a))),bY(b,["candidates"],a)}let e=bZ(a,["modelVersion"]);null!=e&&bY(b,["modelVersion"],e);let f=bZ(a,["promptFeedback"]);null!=f&&bY(b,["promptFeedback"],f);let g=bZ(a,["responseId"]);null!=g&&bY(b,["responseId"],g);let h=bZ(a,["usageMetadata"]);null!=h&&bY(b,["usageMetadata"],h);let i=bZ(a,["modelStatus"]);return null!=i&&bY(b,["modelStatus"],i),b}(d)),null!=(e=bZ(b,["metadata"]))&&bY(c,["metadata"],e),null!=(f=bZ(b,["error"]))&&bY(c,["error"],f),c})),bY(b,["inlinedResponses"],a)}let e=bZ(a,["inlinedEmbedContentResponses","inlinedResponses"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["inlinedEmbedContentResponses"],a)}return b}(cV(j))),b}function cZ(a){var b,c,d;let e,f,g,h,i,j,k,l,m,n,o,p,q,r={},s=bZ(a,["name"]);null!=s&&bY(r,["name"],s);let t=bZ(a,["displayName"]);null!=t&&bY(r,["displayName"],t);let u=bZ(a,["state"]);null!=u&&bY(r,["state"],cX(u));let v=bZ(a,["error"]);null!=v&&bY(r,["error"],v);let w=bZ(a,["createTime"]);null!=w&&bY(r,["createTime"],w);let x=bZ(a,["startTime"]);null!=x&&bY(r,["startTime"],x);let y=bZ(a,["endTime"]);null!=y&&bY(r,["endTime"],y);let z=bZ(a,["updateTime"]);null!=z&&bY(r,["updateTime"],z);let A=bZ(a,["model"]);null!=A&&bY(r,["model"],A);let B=bZ(a,["inputConfig"]);null!=B&&bY(r,["src"],(e={},null!=(f=bZ(c=B,["instancesFormat"]))&&bY(e,["format"],f),null!=(g=bZ(c,["gcsSource","uris"]))&&bY(e,["gcsUri"],g),null!=(h=bZ(c,["bigquerySource","inputUri"]))&&bY(e,["bigqueryUri"],h),null!=(i=bZ(c,["vertexMultimodalDatasetSource","datasetName"]))&&bY(e,["vertexDatasetName"],i),e));let C=bZ(a,["outputConfig"]);null!=C&&bY(r,["dest"],(b=cV(C),m={},null!=(n=bZ(b,["predictionsFormat"]))&&bY(m,["format"],n),null!=(o=bZ(b,["gcsDestination","outputUriPrefix"]))&&bY(m,["gcsUri"],o),null!=(p=bZ(b,["bigqueryDestination","outputUri"]))&&bY(m,["bigqueryUri"],p),null!=(q=bZ(b,["vertexMultimodalDatasetDestination"]))&&bY(m,["vertexDataset"],(j={},null!=(k=bZ(d=q,["bigqueryDestination","outputUri"]))&&bY(j,["bigqueryDestination"],k),null!=(l=bZ(d,["displayName"]))&&bY(j,["displayName"],l),j)),m));let D=bZ(a,["outputInfo"]);null!=D&&bY(r,["outputInfo"],D);let E=bZ(a,["completionStats"]);return null!=E&&bY(r,["completionStats"],E),r}function c$(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return c={},null!=(d=bZ(b=a,["mediaResolution"]))&&bY(c,["mediaResolution"],d),null!=(e=bZ(b,["toolCall"]))&&bY(c,["toolCall"],e),null!=(f=bZ(b,["toolResponse"]))&&bY(c,["toolResponse"],f),null!=(g=bZ(b,["audioTranscription"]))&&bY(c,["audioTranscription"],g),null!=(h=bZ(b,["codeExecutionResult"]))&&bY(c,["codeExecutionResult"],h),null!=(i=bZ(b,["executableCode"]))&&bY(c,["executableCode"],i),null!=(j=bZ(b,["fileData"]))&&bY(c,["fileData"],function(a){let b={};if(void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["fileUri"]);null!=c&&bY(b,["fileUri"],c);let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(j)),null!=(k=bZ(b,["functionCall"]))&&bY(c,["functionCall"],function(a){let b={},c=bZ(a,["args"]);null!=c&&bY(b,["args"],c);let d=bZ(a,["id"]);null!=d&&bY(b,["id"],d);let e=bZ(a,["name"]);if(null!=e&&bY(b,["name"],e),void 0!==bZ(a,["partialArgs"]))throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["willContinue"]))throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(k)),null!=(l=bZ(b,["functionResponse"]))&&bY(c,["functionResponse"],l),null!=(m=bZ(b,["inlineData"]))&&bY(c,["inlineData"],function(a){let b={},c=bZ(a,["data"]);if(null!=c&&bY(b,["data"],c),void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(m)),null!=(n=bZ(b,["text"]))&&bY(c,["text"],n),null!=(o=bZ(b,["thought"]))&&bY(c,["thought"],o),null!=(p=bZ(b,["thoughtSignature"]))&&bY(c,["thoughtSignature"],p),null!=(q=bZ(b,["videoMetadata"]))&&bY(c,["videoMetadata"],q),null!=(r=bZ(b,["partMetadata"]))&&bY(c,["partMetadata"],r),c})),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}function c_(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["_url","model"],cu(a,d));let e=bZ(b,["src"]);null!=e&&bY(c,["batch","inputConfig"],function(a,b){let c={};if(void 0!==bZ(b,["format"]))throw Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(b,["gcsUri"]))throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(b,["bigqueryUri"]))throw Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(b,["vertexDatasetName"]))throw Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(b,["fileName"]);null!=d&&bY(c,["fileName"],d);let e=bZ(b,["inlinedRequests"]);if(null!=e){let b=e;Array.isArray(b)&&(b=b.map(b=>(function(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["request","model"],cu(a,d));let e=bZ(b,["contents"]);if(null!=e){let a=cH(e);Array.isArray(a)&&(a=a.map(a=>c$(a))),bY(c,["request","contents"],a)}let f=bZ(b,["metadata"]);null!=f&&bY(c,["metadata"],f);let g=bZ(b,["config"]);return null!=g&&bY(c,["request","generationConfig"],function(a,b,c){var d;let e,f,g,h,i={},j=bZ(b,["serviceTier"]);void 0!==c&&null!=j&&bY(c,["serviceTier"],j);let k=bZ(b,["systemInstruction"]);void 0!==c&&null!=k&&bY(c,["systemInstruction"],c$(cF(k)));let l=bZ(b,["temperature"]);null!=l&&bY(i,["temperature"],l);let m=bZ(b,["topP"]);null!=m&&bY(i,["topP"],m);let n=bZ(b,["topK"]);null!=n&&bY(i,["topK"],n);let o=bZ(b,["candidateCount"]);null!=o&&bY(i,["candidateCount"],o);let p=bZ(b,["maxOutputTokens"]);null!=p&&bY(i,["maxOutputTokens"],p);let q=bZ(b,["stopSequences"]);null!=q&&bY(i,["stopSequences"],q);let r=bZ(b,["responseLogprobs"]);null!=r&&bY(i,["responseLogprobs"],r);let s=bZ(b,["logprobs"]);null!=s&&bY(i,["logprobs"],s);let t=bZ(b,["presencePenalty"]);null!=t&&bY(i,["presencePenalty"],t);let u=bZ(b,["frequencyPenalty"]);null!=u&&bY(i,["frequencyPenalty"],u);let v=bZ(b,["seed"]);null!=v&&bY(i,["seed"],v);let w=bZ(b,["responseMimeType"]);null!=w&&bY(i,["responseMimeType"],w);let x=bZ(b,["responseSchema"]);null!=x&&bY(i,["responseSchema"],cI(x));let y=bZ(b,["responseJsonSchema"]);if(null!=y&&bY(i,["responseJsonSchema"],y),void 0!==bZ(b,["routingConfig"]))throw Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(b,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let z=bZ(b,["safetySettings"]);if(void 0!==c&&null!=z){let a=z;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["category"]);if(null!=c&&bY(b,["category"],c),void 0!==bZ(a,["method"]))throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["threshold"]);return null!=d&&bY(b,["threshold"],d),b})(a))),bY(c,["safetySettings"],a)}let A=bZ(b,["tools"]);if(void 0!==c&&null!=A){let a=cM(A);Array.isArray(a)&&(a=a.map(a=>(function(a){let b={};if(void 0!==bZ(a,["retrieval"]))throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["googleMaps"]);null!=c&&bY(b,["googleMaps"],function(a){let b={},c=bZ(a,["authConfig"]);null!=c&&bY(b,["authConfig"],function(a){let b={},c=bZ(a,["apiKey"]);if(null!=c&&bY(b,["apiKey"],c),void 0!==bZ(a,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["authType"]))throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oauthConfig"]))throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oidcConfig"]))throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["enableWidget"]);if(null!=d&&bY(b,["enableWidget"],d),void 0!==bZ(a,["groundingTypes"]))throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["mcpServers"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mcpServers"],a)}let e=bZ(a,["codeExecution"]);null!=e&&bY(b,["codeExecution"],e);let f=bZ(a,["computerUse"]);if(null!=f&&bY(b,["computerUse"],f),void 0!==bZ(a,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["exaAiSearch"]))throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=bZ(a,["functionDeclarations"]);if(null!=g){let a=g;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let h=bZ(a,["googleSearch"]);null!=h&&bY(b,["googleSearch"],function(a){let b={};if(void 0!==bZ(a,["blockingConfidence"]))throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["excludeDomains"]))throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["searchTypes"]);null!=c&&bY(b,["searchTypes"],c);let d=bZ(a,["timeRangeFilter"]);return null!=d&&bY(b,["timeRangeFilter"],d),b}(h));let i=bZ(a,["googleSearchRetrieval"]);if(null!=i&&bY(b,["googleSearchRetrieval"],i),void 0!==bZ(a,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["urlContext"]);null!=j&&bY(b,["urlContext"],j);let k=bZ(a,["fileSearch"]);return null!=k&&bY(b,["fileSearch"],k),b})(cL(a)))),bY(c,["tools"],a)}let B=bZ(b,["toolConfig"]);if(void 0!==c&&null!=B&&bY(c,["toolConfig"],(e={},null!=(f=bZ(d=B,["functionCallingConfig"]))&&bY(e,["functionCallingConfig"],function(a){let b={},c=bZ(a,["allowedFunctionNames"]);null!=c&&bY(b,["allowedFunctionNames"],c);let d=bZ(a,["mode"]);if(null!=d&&bY(b,["mode"],d),void 0!==bZ(a,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(f)),null!=(g=bZ(d,["retrievalConfig"]))&&bY(e,["retrievalConfig"],g),null!=(h=bZ(d,["includeServerSideToolInvocations"]))&&bY(e,["includeServerSideToolInvocations"],h),e)),void 0!==bZ(b,["labels"]))throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let C=bZ(b,["cachedContent"]);void 0!==c&&null!=C&&bY(c,["cachedContent"],cN(a,C));let D=bZ(b,["responseModalities"]);null!=D&&bY(i,["responseModalities"],D);let E=bZ(b,["mediaResolution"]);null!=E&&bY(i,["mediaResolution"],E);let F=bZ(b,["speechConfig"]);if(null!=F&&bY(i,["speechConfig"],cJ(F)),void 0!==bZ(b,["audioTimestamp"]))throw Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let G=bZ(b,["thinkingConfig"]);null!=G&&bY(i,["thinkingConfig"],G);let H=bZ(b,["audioTranscriptionConfig"]);null!=H&&bY(i,["audioTranscriptionConfig"],H);let I=bZ(b,["imageConfig"]);null!=I&&bY(i,["imageConfig"],function(a){let b={},c=bZ(a,["aspectRatio"]);null!=c&&bY(b,["aspectRatio"],c);let d=bZ(a,["imageSize"]);if(null!=d&&bY(b,["imageSize"],d),void 0!==bZ(a,["personGeneration"]))throw Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["outputMimeType"]))throw Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["imageOutputOptions"]))throw Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["prominentPeople"]))throw Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(I));let J=bZ(b,["enableEnhancedCivicAnswers"]);if(null!=J&&bY(i,["enableEnhancedCivicAnswers"],J),void 0!==bZ(b,["modelArmorConfig"]))throw Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}(a,g,bZ(c,["request"],{}))),c})(a,b))),bY(c,["requests","requests"],b)}return c}(a,cU(a,e)));let f=bZ(b,["config"]);return null!=f&&function(a,b){let c=bZ(a,["displayName"]);if(void 0!==b&&null!=c&&bY(b,["batch","displayName"],c),void 0!==bZ(a,["dest"]))throw Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["webhookConfig"]);void 0!==b&&null!=d&&bY(b,["batch","webhookConfig"],d)}(f,c),c}(aA=bM||(bM={})).PAGED_ITEM_BATCH_JOBS="batchJobs",aA.PAGED_ITEM_MODELS="models",aA.PAGED_ITEM_TUNING_JOBS="tuningJobs",aA.PAGED_ITEM_FILES="files",aA.PAGED_ITEM_CACHED_CONTENTS="cachedContents",aA.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",aA.PAGED_ITEM_DOCUMENTS="documents",aA.PAGED_ITEM_SKILLS="skills";class c0{constructor(a,b,c,d){this.pageInternal=[],this.paramsInternal={},this.requestInternal=b,this.init(a,c,d)}init(a,b,c){var d,e;this.nameInternal=a,this.pageInternal=b[this.nameInternal]||[],this.sdkHttpResponseInternal=null==b?void 0:b.sdkHttpResponse,this.idxInternal=0;let f={config:{}};(f=c&&0!==Object.keys(c).length?"object"==typeof c?Object.assign({},c):c:{config:{}}).config&&(f.config.pageToken=b.nextPageToken),this.paramsInternal=f,this.pageInternalSize=null!=(e=null==(d=f.config)?void 0:d.pageSize)?e:this.pageInternal.length}initNextPage(a){this.init(this.nameInternal,a,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(a){return this.pageInternal[a]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(!this.hasNextPage())return{value:void 0,done:!0};else await this.nextPage();let a=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:a,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw Error("No more pages to fetch.");let a=await this.requestInternal(this.params);return this.initNextPage(a),this.page}hasNextPage(){var a;return(null==(a=this.params.config)?void 0:a.pageToken)!==void 0}}class c1 extends bW{constructor(a){super(),this.apiClient=a,this.list=async(a={})=>new c0(bM.PAGED_ITEM_BATCH_JOBS,a=>this.listInternal(a),await this.listInternal(a),a),this.create=async a=>(this.apiClient.isVertexAI()&&(a.config=this.formatDestination(a.src,a.config)),this.createInternal(a)),this.createEmbeddings=async a=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(a)}}createInlinedGenerateContentRequest(a){let b=c_(this.apiClient,a),c=bX("{model}:batchGenerateContent",b._url),d=b.batch.inputConfig.requests,e=d.requests,f=[];for(let a of e){let b=Object.assign({},a);if(b.systemInstruction){let a=b.systemInstruction;delete b.systemInstruction;let c=b.request;c.systemInstruction=a,b.request=c}f.push(b)}return d.requests=f,delete b.config,delete b._url,delete b._query,{path:c,body:b}}getGcsUri(a){return"string"==typeof a?a.startsWith("gs://")?a:void 0:!Array.isArray(a)&&a.gcsUri&&a.gcsUri.length>0?a.gcsUri[0]:void 0}getBigqueryUri(a){return"string"==typeof a?a.startsWith("bq://")?a:void 0:Array.isArray(a)?void 0:a.bigqueryUri}formatDestination(a,b){let c=b?Object.assign({},b):{},d=Date.now().toString();if(c.displayName||(c.displayName=`genaiBatchJob_${d}`),void 0===c.dest){let b=this.getGcsUri(a),e=this.getBigqueryUri(a);if(b)b.endsWith(".jsonl")?c.dest=`${b.slice(0,-6)}/dest`:c.dest=`${b}_dest_${d}`;else if(e)c.dest=`${e}_dest_${d}`;else throw Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return c}async createInternal(a){var b,c,d,e,f;let g="",h={};if(this.apiClient.isVertexAI()){let d,e,i,j,k=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["model"],cu(f,e)),null!=(i=bZ(a,["src"]))&&bY(d,["inputConfig"],function(a){let b={},c=bZ(a,["format"]);null!=c&&bY(b,["instancesFormat"],c);let d=bZ(a,["gcsUri"]);null!=d&&bY(b,["gcsSource","uris"],d);let e=bZ(a,["bigqueryUri"]);null!=e&&bY(b,["bigquerySource","inputUri"],e);let f=bZ(a,["vertexDatasetName"]);if(null!=f&&bY(b,["vertexMultimodalDatasetSource","datasetName"],f),void 0!==bZ(a,["fileName"]))throw Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["inlinedRequests"]))throw Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(cU(f,i))),null!=(j=bZ(a,["config"]))&&function(a,b){let c=bZ(a,["displayName"]);void 0!==b&&null!=c&&bY(b,["displayName"],c);let d=bZ(a,["dest"]);if(void 0!==b&&null!=d&&bY(b,["outputConfig"],function(a){var b;let c,d,e,f={},g=bZ(a,["format"]);null!=g&&bY(f,["predictionsFormat"],g);let h=bZ(a,["gcsUri"]);null!=h&&bY(f,["gcsDestination","outputUriPrefix"],h);let i=bZ(a,["bigqueryUri"]);null!=i&&bY(f,["bigqueryDestination","outputUri"],i);let j=bZ(a,["vertexDataset"]);if(null!=j&&bY(f,["vertexMultimodalDatasetDestination"],(c={},null!=(d=bZ(b=j,["bigqueryDestination"]))&&bY(c,["bigqueryDestination","outputUri"],d),null!=(e=bZ(b,["displayName"]))&&bY(c,["displayName"],e),c)),void 0!==bZ(a,["fileName"]))throw Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["inlinedResponses"]))throw Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["inlinedEmbedContentResponses"]))throw Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return f}(function(a){if("string"!=typeof a)return a;if(a.startsWith("gs://"))return{format:"jsonl",gcsUri:a};if(a.startsWith("bq://"))return{format:"bigquery",bigqueryUri:a};throw Error(`Unsupported destination: ${a}`)}(d))),void 0!==bZ(a,["webhookConfig"]))throw Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.")}(j,d),d);return g=bX("batchPredictionJobs",k._url),h=k._query,delete k._url,delete k._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(k),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>cZ(a))}{let b=c_(this.apiClient,a);return g=bX("{model}:batchGenerateContent",b._url),h=b._query,delete b._url,delete b._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>cY(a))}}async createEmbeddingsInternal(a){var b,c,d,e,f;let g="",h={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let i,j,k,l,m,n,o,p,q=(d=this.apiClient,l={},null!=(m=bZ(a,["model"]))&&bY(l,["_url","model"],cu(d,m)),null!=(n=bZ(a,["src"]))&&bY(l,["batch","inputConfig"],(e=d,i={},null!=(j=bZ(f=n,["fileName"]))&&bY(i,["file_name"],j),null!=(k=bZ(f,["inlinedRequests"]))&&bY(i,["requests"],function(a,b){let c={},d=bZ(b,["contents"]);if(null!=d){let b=cG(a,d);Array.isArray(b)&&(b=b.map(a=>a)),bY(c,["requests[]","request","content"],b)}let e=bZ(b,["config"]);return null!=e&&(bY(c,["_self"],function(a,b){let c=bZ(a,["taskType"]);void 0!==b&&null!=c&&bY(b,["requests[]","taskType"],c);let d=bZ(a,["title"]);void 0!==b&&null!=d&&bY(b,["requests[]","title"],d);let e=bZ(a,["outputDimensionality"]);if(void 0!==b&&null!=e&&bY(b,["requests[]","outputDimensionality"],e),void 0!==bZ(a,["mimeType"]))throw Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["autoTruncate"]))throw Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["documentOcr"]))throw Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["audioTrackExtraction"]))throw Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return{}}(e,c)),!function(a,b){for(let[c,d]of Object.entries(b)){let b=c.split("."),e=d.split("."),f=new Set,g=-1;for(let a=0;a<b.length;a++)if("*"===b[a]){g=a;break}if(-1!==g&&e.length>g)for(let a=g;a<e.length;a++){let b=e[a];"*"===b||b.endsWith("[]")||b.endsWith("[0]")||f.add(b)}!function a(b,c,d,e,f){if(e>=c.length||"object"!=typeof b||null===b)return;let g=c[e];if(g.endsWith("[]")){let h=g.slice(0,-2);if(h in b&&Array.isArray(b[h]))for(let g of b[h])a(g,c,d,e+1,f)}else if("*"===g){if("object"==typeof b&&null!==b&&!Array.isArray(b)){let a=Object.keys(b).filter(a=>!a.startsWith("_")&&!f.has(a)),c={};for(let d of a)c[d]=b[d];for(let[a,f]of Object.entries(c)){let c=[];for(let b of d.slice(e))"*"===b?c.push(a):c.push(b);bY(b,c,f)}for(let c of a)delete b[c]}}else g in b&&a(b[g],c,d,e+1,f)}(a,b,e,0,f)}}(c,{"requests[].*":"requests[].request.*"})),c}(e,k)),i)),null!=(o=bZ(a,["config"]))&&(p=bZ(o,["displayName"]),void 0!==l&&null!=p&&bY(l,["batch","displayName"],p)),l);return g=bX("{model}:asyncBatchEmbedContent",q._url),h=q._query,delete q._url,delete q._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(q),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>cY(a))}}async get(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cW(f,e)),d);return h=bX("batchPredictionJobs/{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>cZ(a))}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cW(g,c)),b);return h=bX("batches/{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>cY(a))}}async cancel(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cW(f,e)),d);h=bX("batchPredictionJobs/{name}:cancel",g._url),i=g._query,delete g._url,delete g._query,await this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal})}else{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cW(g,c)),b);h=bX("batches/{name}:cancel",f._url),i=f._query,delete f._url,delete f._query,await this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal})}}async listInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d,e,h,i,j,k=(d={},null!=(e=bZ(a,["config"]))&&(h=bZ(e,["pageSize"]),void 0!==d&&null!=h&&bY(d,["_query","pageSize"],h),i=bZ(e,["pageToken"]),void 0!==d&&null!=i&&bY(d,["_query","pageToken"],i),j=bZ(e,["filter"]),void 0!==d&&null!=j&&bY(d,["_query","filter"],j)),d);return f=bX("batchPredictionJobs",k._url),g=k._query,delete k._url,delete k._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(k),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["batchPredictionJobs"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>cZ(a))),bY(b,["batchJobs"],a)}return b}(a),c=new cq;return Object.assign(c,b),c})}{let b,c,h=(b={},null!=(c=bZ(a,["config"]))&&function(a,b){let c=bZ(a,["pageSize"]);void 0!==b&&null!=c&&bY(b,["_query","pageSize"],c);let d=bZ(a,["pageToken"]);if(void 0!==b&&null!=d&&bY(b,["_query","pageToken"],d),void 0!==bZ(a,["filter"]))throw Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(c,b),b);return f=bX("batches",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["operations"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>cY(a))),bY(b,["batchJobs"],a)}return b}(a),c=new cq;return Object.assign(c,b),c})}}async delete(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cW(f,e)),d);return h=bX("batchPredictionJobs/{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f;return b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["done"]))&&bY(b,["done"],e),null!=(f=bZ(a,["error"]))&&bY(b,["error"],f),b})}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cW(g,c)),b);return h=bX("batches/{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f;return b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["done"]))&&bY(b,["done"],e),null!=(f=bZ(a,["error"]))&&bY(b,["error"],f),b})}}}function c2(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return c={},null!=(d=bZ(b=a,["mediaResolution"]))&&bY(c,["mediaResolution"],d),null!=(e=bZ(b,["toolCall"]))&&bY(c,["toolCall"],e),null!=(f=bZ(b,["toolResponse"]))&&bY(c,["toolResponse"],f),null!=(g=bZ(b,["audioTranscription"]))&&bY(c,["audioTranscription"],g),null!=(h=bZ(b,["codeExecutionResult"]))&&bY(c,["codeExecutionResult"],h),null!=(i=bZ(b,["executableCode"]))&&bY(c,["executableCode"],i),null!=(j=bZ(b,["fileData"]))&&bY(c,["fileData"],function(a){let b={};if(void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["fileUri"]);null!=c&&bY(b,["fileUri"],c);let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(j)),null!=(k=bZ(b,["functionCall"]))&&bY(c,["functionCall"],function(a){let b={},c=bZ(a,["args"]);null!=c&&bY(b,["args"],c);let d=bZ(a,["id"]);null!=d&&bY(b,["id"],d);let e=bZ(a,["name"]);if(null!=e&&bY(b,["name"],e),void 0!==bZ(a,["partialArgs"]))throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["willContinue"]))throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(k)),null!=(l=bZ(b,["functionResponse"]))&&bY(c,["functionResponse"],l),null!=(m=bZ(b,["inlineData"]))&&bY(c,["inlineData"],function(a){let b={},c=bZ(a,["data"]);if(null!=c&&bY(b,["data"],c),void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(m)),null!=(n=bZ(b,["text"]))&&bY(c,["text"],n),null!=(o=bZ(b,["thought"]))&&bY(c,["thought"],o),null!=(p=bZ(b,["thoughtSignature"]))&&bY(c,["thoughtSignature"],p),null!=(q=bZ(b,["videoMetadata"]))&&bY(c,["videoMetadata"],q),null!=(r=bZ(b,["partMetadata"]))&&bY(c,["partMetadata"],r),c})),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}function c3(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["mediaResolution"]);if(null!=c&&bY(b,["mediaResolution"],c),void 0!==bZ(a,["toolCall"]))throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["toolResponse"]))throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let d=bZ(a,["audioTranscription"]);null!=d&&bY(b,["audioTranscription"],d);let e=bZ(a,["codeExecutionResult"]);null!=e&&bY(b,["codeExecutionResult"],function(a){let b={},c=bZ(a,["outcome"]);null!=c&&bY(b,["outcome"],c);let d=bZ(a,["output"]);if(null!=d&&bY(b,["output"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(e));let f=bZ(a,["executableCode"]);null!=f&&bY(b,["executableCode"],function(a){let b={},c=bZ(a,["code"]);null!=c&&bY(b,["code"],c);let d=bZ(a,["language"]);if(null!=d&&bY(b,["language"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(f));let g=bZ(a,["fileData"]);null!=g&&bY(b,["fileData"],g);let h=bZ(a,["functionCall"]);null!=h&&bY(b,["functionCall"],h);let i=bZ(a,["functionResponse"]);null!=i&&bY(b,["functionResponse"],i);let j=bZ(a,["inlineData"]);null!=j&&bY(b,["inlineData"],j);let k=bZ(a,["text"]);null!=k&&bY(b,["text"],k);let l=bZ(a,["thought"]);null!=l&&bY(b,["thought"],l);let m=bZ(a,["thoughtSignature"]);null!=m&&bY(b,["thoughtSignature"],m);let n=bZ(a,["videoMetadata"]);if(null!=n&&bY(b,["videoMetadata"],n),void 0!==bZ(a,["partMetadata"]))throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(a))),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}class c4 extends bW{constructor(a){super(),this.apiClient=a,this.list=async(a={})=>new c0(bM.PAGED_ITEM_CACHED_CONTENTS,a=>this.listInternal(a),await this.listInternal(a),a)}async create(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g,j=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["model"],cv(f,e)),null!=(g=bZ(a,["config"]))&&function(a,b){let c=bZ(a,["ttl"]);void 0!==b&&null!=c&&bY(b,["ttl"],c);let d=bZ(a,["expireTime"]);void 0!==b&&null!=d&&bY(b,["expireTime"],d);let e=bZ(a,["displayName"]);void 0!==b&&null!=e&&bY(b,["displayName"],e);let f=bZ(a,["contents"]);if(void 0!==b&&null!=f){let a=cH(f);Array.isArray(a)&&(a=a.map(a=>c3(a))),bY(b,["contents"],a)}let g=bZ(a,["systemInstruction"]);void 0!==b&&null!=g&&bY(b,["systemInstruction"],c3(cF(g)));let h=bZ(a,["tools"]);if(void 0!==b&&null!=h){let a=h;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["retrieval"]);null!=c&&bY(b,["retrieval"],c);let d=bZ(a,["googleMaps"]);null!=d&&bY(b,["googleMaps"],d);let e=bZ(a,["mcpServers"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>(function(a){if(void 0!==bZ(a,["name"]))throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["streamableHttpTransport"]))throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}})(a))),bY(b,["mcpServers"],a)}let f=bZ(a,["codeExecution"]);null!=f&&bY(b,["codeExecution"],f);let g=bZ(a,["computerUse"]);null!=g&&bY(b,["computerUse"],function(a){let b={},c=bZ(a,["enablePromptInjectionDetection"]);null!=c&&bY(b,["enablePromptInjectionDetection"],c);let d=bZ(a,["environment"]);null!=d&&bY(b,["environment"],d);let e=bZ(a,["excludedPredefinedFunctions"]);if(null!=e&&bY(b,["excludedPredefinedFunctions"],e),void 0!==bZ(a,["disabledSafetyPolicies"]))throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(g));let h=bZ(a,["enterpriseWebSearch"]);null!=h&&bY(b,["enterpriseWebSearch"],h);let i=bZ(a,["exaAiSearch"]);null!=i&&bY(b,["exaAiSearch"],i);let j=bZ(a,["functionDeclarations"]);if(null!=j){let a=j;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let k=bZ(a,["googleSearch"]);null!=k&&bY(b,["googleSearch"],k);let l=bZ(a,["googleSearchRetrieval"]);null!=l&&bY(b,["googleSearchRetrieval"],l);let m=bZ(a,["parallelAiSearch"]);null!=m&&bY(b,["parallelAiSearch"],m);let n=bZ(a,["urlContext"]);if(null!=n&&bY(b,["urlContext"],n),void 0!==bZ(a,["fileSearch"]))throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(a))),bY(b,["tools"],a)}let i=bZ(a,["toolConfig"]);void 0!==b&&null!=i&&bY(b,["toolConfig"],function(a){let b={},c=bZ(a,["functionCallingConfig"]);null!=c&&bY(b,["functionCallingConfig"],c);let d=bZ(a,["retrievalConfig"]);if(null!=d&&bY(b,["retrievalConfig"],d),void 0!==bZ(a,["includeServerSideToolInvocations"]))throw Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(i));let j=bZ(a,["kmsKeyName"]);void 0!==b&&null!=j&&bY(b,["encryption_spec","kmsKeyName"],j)}(g,d),d);return h=bX("cachedContents",j._url),i=j._query,delete j._url,delete j._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(j),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}{let b,c,f,j=(g=this.apiClient,b={},null!=(c=bZ(a,["model"]))&&bY(b,["model"],cv(g,c)),null!=(f=bZ(a,["config"]))&&function(a,b){var c;let d,e,f,g,h=bZ(a,["ttl"]);void 0!==b&&null!=h&&bY(b,["ttl"],h);let i=bZ(a,["expireTime"]);void 0!==b&&null!=i&&bY(b,["expireTime"],i);let j=bZ(a,["displayName"]);void 0!==b&&null!=j&&bY(b,["displayName"],j);let k=bZ(a,["contents"]);if(void 0!==b&&null!=k){let a=cH(k);Array.isArray(a)&&(a=a.map(a=>c2(a))),bY(b,["contents"],a)}let l=bZ(a,["systemInstruction"]);void 0!==b&&null!=l&&bY(b,["systemInstruction"],c2(cF(l)));let m=bZ(a,["tools"]);if(void 0!==b&&null!=m){let a=m;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={};if(void 0!==bZ(a,["retrieval"]))throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["googleMaps"]);null!=c&&bY(b,["googleMaps"],function(a){let b={},c=bZ(a,["authConfig"]);null!=c&&bY(b,["authConfig"],function(a){let b={},c=bZ(a,["apiKey"]);if(null!=c&&bY(b,["apiKey"],c),void 0!==bZ(a,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["authType"]))throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oauthConfig"]))throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oidcConfig"]))throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["enableWidget"]);if(null!=d&&bY(b,["enableWidget"],d),void 0!==bZ(a,["groundingTypes"]))throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["mcpServers"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mcpServers"],a)}let e=bZ(a,["codeExecution"]);null!=e&&bY(b,["codeExecution"],e);let f=bZ(a,["computerUse"]);if(null!=f&&bY(b,["computerUse"],f),void 0!==bZ(a,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["exaAiSearch"]))throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=bZ(a,["functionDeclarations"]);if(null!=g){let a=g;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let h=bZ(a,["googleSearch"]);null!=h&&bY(b,["googleSearch"],function(a){let b={};if(void 0!==bZ(a,["blockingConfidence"]))throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["excludeDomains"]))throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["searchTypes"]);null!=c&&bY(b,["searchTypes"],c);let d=bZ(a,["timeRangeFilter"]);return null!=d&&bY(b,["timeRangeFilter"],d),b}(h));let i=bZ(a,["googleSearchRetrieval"]);if(null!=i&&bY(b,["googleSearchRetrieval"],i),void 0!==bZ(a,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["urlContext"]);null!=j&&bY(b,["urlContext"],j);let k=bZ(a,["fileSearch"]);return null!=k&&bY(b,["fileSearch"],k),b})(a))),bY(b,["tools"],a)}let n=bZ(a,["toolConfig"]);if(void 0!==b&&null!=n&&bY(b,["toolConfig"],(d={},null!=(e=bZ(c=n,["functionCallingConfig"]))&&bY(d,["functionCallingConfig"],function(a){let b={},c=bZ(a,["allowedFunctionNames"]);null!=c&&bY(b,["allowedFunctionNames"],c);let d=bZ(a,["mode"]);if(null!=d&&bY(b,["mode"],d),void 0!==bZ(a,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(e)),null!=(f=bZ(c,["retrievalConfig"]))&&bY(d,["retrievalConfig"],f),null!=(g=bZ(c,["includeServerSideToolInvocations"]))&&bY(d,["includeServerSideToolInvocations"],g),d)),void 0!==bZ(a,["kmsKeyName"]))throw Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(f,b),b);return h=bX("cachedContents",j._url),i=j._query,delete j._url,delete j._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(j),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>a)}}async get(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cN(f,e)),d);return h=bX("{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cN(g,c)),b);return h=bX("{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>a)}}async delete(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cN(f,e)),d);return h=bX("{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new cg;return Object.assign(e,d),e})}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cN(g,c)),b);return h=bX("{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new cg;return Object.assign(e,d),e})}}async update(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g,j,k,l=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cN(f,e)),null!=(g=bZ(a,["config"]))&&(j=bZ(g,["ttl"]),void 0!==d&&null!=j&&bY(d,["ttl"],j),k=bZ(g,["expireTime"]),void 0!==d&&null!=k&&bY(d,["expireTime"],k)),d);return h=bX("{name}",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(l),httpMethod:"PATCH",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}{let b,c,f,j,k,l=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cN(g,c)),null!=(f=bZ(a,["config"]))&&(j=bZ(f,["ttl"]),void 0!==b&&null!=j&&bY(b,["ttl"],j),k=bZ(f,["expireTime"]),void 0!==b&&null!=k&&bY(b,["expireTime"],k)),b);return h=bX("{name}",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(l),httpMethod:"PATCH",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>a)}}async listInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d,e,h,i,j=(d={},null!=(e=bZ(a,["config"]))&&(h=bZ(e,["pageSize"]),void 0!==d&&null!=h&&bY(d,["_query","pageSize"],h),i=bZ(e,["pageToken"]),void 0!==d&&null!=i&&bY(d,["_query","pageToken"],i)),d);return f=bX("cachedContents",j._url),g=j._query,delete j._url,delete j._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(j),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["cachedContents"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["cachedContents"],a)}return b}(a),c=new ch;return Object.assign(c,b),c})}{let b,c,h,i,j=(b={},null!=(c=bZ(a,["config"]))&&(h=bZ(c,["pageSize"]),void 0!==b&&null!=h&&bY(b,["_query","pageSize"],h),i=bZ(c,["pageToken"]),void 0!==b&&null!=i&&bY(b,["_query","pageToken"],i)),b);return f=bX("cachedContents",j._url),g=j._query,delete j._url,delete j._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(j),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["cachedContents"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["cachedContents"],a)}return b}(a),c=new ch;return Object.assign(c,b),c})}}}function c5(a,b){var c={};for(var d in a)Object.prototype.hasOwnProperty.call(a,d)&&0>b.indexOf(d)&&(c[d]=a[d]);if(null!=a&&"function"==typeof Object.getOwnPropertySymbols)for(var e=0,d=Object.getOwnPropertySymbols(a);e<d.length;e++)0>b.indexOf(d[e])&&Object.prototype.propertyIsEnumerable.call(a,d[e])&&(c[d[e]]=a[d[e]]);return c}function c6(a){return this instanceof c6?(this.v=a,this):new c6(a)}function c7(a,b,c){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var d,e=c.apply(a,b||[]),f=[];return d=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),g("next"),g("throw"),g("return",function(a){return function(b){return Promise.resolve(b).then(a,j)}}),d[Symbol.asyncIterator]=function(){return this},d;function g(a,b){e[a]&&(d[a]=function(b){return new Promise(function(c,d){f.push([a,b,c,d])>1||h(a,b)})},b&&(d[a]=b(d[a])))}function h(a,b){try{var c;(c=e[a](b)).value instanceof c6?Promise.resolve(c.value.v).then(i,j):k(f[0][2],c)}catch(a){k(f[0][3],a)}}function i(a){h("next",a)}function j(a){h("throw",a)}function k(a,b){a(b),f.shift(),f.length&&h(f[0][0],f[0][1])}}function c8(a){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var b,c=a[Symbol.asyncIterator];return c?c.call(a):(a=function(a){var b="function"==typeof Symbol&&Symbol.iterator,c=b&&a[b],d=0;if(c)return c.call(a);if(a&&"number"==typeof a.length)return{next:function(){return a&&d>=a.length&&(a=void 0),{value:a&&a[d++],done:!a}}};throw TypeError(b?"Object is not iterable.":"Symbol.iterator is not defined.")}(a),b={},d("next"),d("throw"),d("return"),b[Symbol.asyncIterator]=function(){return this},b);function d(c){b[c]=a[c]&&function(b){return new Promise(function(d,e){var f,g,h;f=d,g=e,h=(b=a[c](b)).done,Promise.resolve(b.value).then(function(a){f({value:a,done:h})},g)})}}}function c9(a){if(void 0===a.parts||0===a.parts.length)return!1;for(let b of a.parts)if(void 0===b||0===Object.keys(b).length)return!1;return!0}function da(a){if(void 0===a||0===a.length)return[];let b=[],c=a.length,d=0;for(;d<c;)if("user"===a[d].role)b.push(a[d]),d++;else{let e=[],f=!0;for(;d<c&&"model"===a[d].role;)e.push(a[d]),f&&!c9(a[d])&&(f=!1),d++;f?b.push(...e):b.pop()}return b}"function"==typeof SuppressedError&&SuppressedError;class db{constructor(a,b){this.modelsModule=a,this.apiClient=b}create(a){return new dc(this.apiClient,this.modelsModule,a.model,a.config,structuredClone(a.history))}}class dc{constructor(a,b,c,d={},e=[]){this.apiClient=a,this.modelsModule=b,this.model=c,this.config=d,this.history=e,this.sendPromise=Promise.resolve(),function(a){if(0!==a.length){for(let b of a)if("user"!==b.role&&"model"!==b.role)throw Error(`Role must be user or model, but got ${b.role}.`)}}(e)}async sendMessage(a){var b;await this.sendPromise;let c=cF(a.message),d=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(c),config:null!=(b=a.config)?b:this.config});return this.sendPromise=(async()=>{var a,b,e;let f=await d,g=null==(b=null==(a=f.candidates)?void 0:a[0])?void 0:b.content,h=f.automaticFunctionCallingHistory,i=this.getHistory(!0).length,j=[];null!=h&&(j=null!=(e=h.slice(i))?e:[]),this.recordHistory(c,g?[g]:[],j)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),d}async sendMessageStream(a){var b;await this.sendPromise;let c=cF(a.message),d=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(c),config:null!=(b=a.config)?b:this.config});this.sendPromise=d.then(()=>void 0).catch(()=>void 0);let e=await d;return this.processStreamResponse(e,c)}getHistory(a=!1){return structuredClone(a?da(this.history):this.history)}processStreamResponse(a,b){return c7(this,arguments,function*(){let c=[];try{for(var d,e,f,g,h,i,j,k=!0,l=c8(a);!(d=(j=yield c6(l.next())).done);k=!0){if(g=j.value,k=!1,function(a){var b;if(void 0==a.candidates||0===a.candidates.length)return!1;let c=null==(b=a.candidates[0])?void 0:b.content;return void 0!==c&&c9(c)}(g)){let a=null==(i=null==(h=g.candidates)?void 0:h[0])?void 0:i.content;void 0!==a&&c.push(a)}yield yield c6(g)}}catch(a){e={error:a}}finally{try{!k&&!d&&(f=l.return)&&(yield c6(f.call(l)))}finally{if(e)throw e.error}}this.recordHistory(b,c)})}recordHistory(a,b,c){let d=[];b.length>0&&b.every(a=>void 0!==a.role)?d=b:d.push({role:"model",parts:[]}),c&&c.length>0?this.history.push(...da(c)):this.history.push(a),this.history.push(...d)}}class dd extends Error{constructor(a){super(a.message),this.name="ApiError",this.status=a.status,Object.setPrototypeOf(this,dd.prototype)}}class de extends bW{constructor(a){super(),this.apiClient=a,this.list=async(a={})=>new c0(bM.PAGED_ITEM_FILES,a=>this.listInternal(a),await this.listInternal(a),a)}async upload(a){if(this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(a.file,a.config).then(a=>a)}async download(a){await this.apiClient.downloadFile(a)}async registerFiles(a){throw Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(a){return this.registerFilesInternal(a)}async listInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j=(f={},null!=(g=bZ(a,["config"]))&&(h=bZ(g,["pageSize"]),void 0!==f&&null!=h&&bY(f,["_query","pageSize"],h),i=bZ(g,["pageToken"]),void 0!==f&&null!=i&&bY(f,["_query","pageToken"],i)),f);return d=bX("files",j._url),e=j._query,delete j._url,delete j._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(j),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["files"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["files"],a)}return b}(a),c=new cm;return Object.assign(c,b),c})}}async createInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["file"]))&&bY(f,["file"],g),f);return d=bX("upload/v1beta/files",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new cn;return Object.assign(e,d),e})}}async get(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","file"],cR(g)),f);return d=bX("files/{file}",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}}async delete(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","file"],cR(g)),f);return d=bX("files/{file}",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new co;return Object.assign(e,d),e})}}async registerFilesInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["uris"]))&&bY(f,["uris"],g),f);return d=bX("files:register",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["files"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["files"],a)}return b}(a),c=new cp;return Object.assign(c,b),c})}}}function df(a){let b={},c=bZ(a,["data"]);if(null!=c&&bY(b,["data"],c),void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}function dg(a){let b={},c=bZ(a,["voiceConfig"]);null!=c&&bY(b,["voiceConfig"],dh(c));let d=bZ(a,["languageCode"]);null!=d&&bY(b,["languageCode"],d);let e=bZ(a,["multiSpeakerVoiceConfig"]);return null!=e&&bY(b,["multiSpeakerVoiceConfig"],function(a){let b={},c=bZ(a,["speakerVoiceConfigs"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e;return c={},null!=(d=bZ(b=a,["speaker"]))&&bY(c,["speaker"],d),null!=(e=bZ(b,["voiceConfig"]))&&bY(c,["voiceConfig"],dh(e)),c})),bY(b,["speakerVoiceConfigs"],a)}return b}(e)),b}function dh(a){let b={},c=bZ(a,["replicatedVoiceConfig"]);null!=c&&bY(b,["replicatedVoiceConfig"],function(a){let b={},c=bZ(a,["mimeType"]);null!=c&&bY(b,["mimeType"],c);let d=bZ(a,["voiceSampleAudio"]);if(null!=d&&bY(b,["voiceSampleAudio"],d),void 0!==bZ(a,["consentAudio"]))throw Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["voiceConsentSignature"]))throw Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(c));let d=bZ(a,["prebuiltVoiceConfig"]);return null!=d&&bY(b,["prebuiltVoiceConfig"],d),b}function di(a,b){let c={},d=bZ(a,["parts"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return c={},null!=(d=bZ(b=a,["mediaResolution"]))&&bY(c,["mediaResolution"],d),null!=(e=bZ(b,["toolCall"]))&&bY(c,["toolCall"],e),null!=(f=bZ(b,["toolResponse"]))&&bY(c,["toolResponse"],f),null!=(g=bZ(b,["audioTranscription"]))&&bY(c,["audioTranscription"],g),null!=(h=bZ(b,["codeExecutionResult"]))&&bY(c,["codeExecutionResult"],h),null!=(i=bZ(b,["executableCode"]))&&bY(c,["executableCode"],i),null!=(j=bZ(b,["fileData"]))&&bY(c,["fileData"],function(a){let b={};if(void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["fileUri"]);null!=c&&bY(b,["fileUri"],c);let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(j)),null!=(k=bZ(b,["functionCall"]))&&bY(c,["functionCall"],function(a){let b={},c=bZ(a,["args"]);null!=c&&bY(b,["args"],c);let d=bZ(a,["id"]);null!=d&&bY(b,["id"],d);let e=bZ(a,["name"]);if(null!=e&&bY(b,["name"],e),void 0!==bZ(a,["partialArgs"]))throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["willContinue"]))throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(k)),null!=(l=bZ(b,["functionResponse"]))&&bY(c,["functionResponse"],l),null!=(m=bZ(b,["inlineData"]))&&bY(c,["inlineData"],function(a){let b={},c=bZ(a,["data"]);if(null!=c&&bY(b,["data"],c),void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(m)),null!=(n=bZ(b,["text"]))&&bY(c,["text"],n),null!=(o=bZ(b,["thought"]))&&bY(c,["thought"],o),null!=(p=bZ(b,["thoughtSignature"]))&&bY(c,["thoughtSignature"],p),null!=(q=bZ(b,["videoMetadata"]))&&bY(c,["videoMetadata"],q),null!=(r=bZ(b,["partMetadata"]))&&bY(c,["partMetadata"],r),c})),bY(c,["parts"],a)}let e=bZ(a,["role"]);return null!=e&&bY(c,["role"],e),c}function dj(a,b){let c={},d=bZ(a,["parts"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["mediaResolution"]);if(null!=c&&bY(b,["mediaResolution"],c),void 0!==bZ(a,["toolCall"]))throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["toolResponse"]))throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let d=bZ(a,["audioTranscription"]);null!=d&&bY(b,["audioTranscription"],d);let e=bZ(a,["codeExecutionResult"]);null!=e&&bY(b,["codeExecutionResult"],function(a){let b={},c=bZ(a,["outcome"]);null!=c&&bY(b,["outcome"],c);let d=bZ(a,["output"]);if(null!=d&&bY(b,["output"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(e));let f=bZ(a,["executableCode"]);null!=f&&bY(b,["executableCode"],function(a){let b={},c=bZ(a,["code"]);null!=c&&bY(b,["code"],c);let d=bZ(a,["language"]);if(null!=d&&bY(b,["language"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(f));let g=bZ(a,["fileData"]);null!=g&&bY(b,["fileData"],g);let h=bZ(a,["functionCall"]);null!=h&&bY(b,["functionCall"],h);let i=bZ(a,["functionResponse"]);null!=i&&bY(b,["functionResponse"],i);let j=bZ(a,["inlineData"]);null!=j&&bY(b,["inlineData"],j);let k=bZ(a,["text"]);null!=k&&bY(b,["text"],k);let l=bZ(a,["thought"]);null!=l&&bY(b,["thought"],l);let m=bZ(a,["thoughtSignature"]);null!=m&&bY(b,["thoughtSignature"],m);let n=bZ(a,["videoMetadata"]);if(null!=n&&bY(b,["videoMetadata"],n),void 0!==bZ(a,["partMetadata"]))throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(a))),bY(c,["parts"],a)}let e=bZ(a,["role"]);return null!=e&&bY(c,["role"],e),c}function dk(a,b,c){let d={},e=bZ(b,["model"]);null!=e&&bY(d,["_url","model"],cu(a,e));let f=bZ(b,["contents"]);if(null!=f){let a=cH(f);Array.isArray(a)&&(a=a.map(a=>di(a))),bY(d,["contents"],a)}let g=bZ(b,["config"]);return null!=g&&bY(d,["generationConfig"],function(a,b,c){var d;let e,f,g,h,i={},j=bZ(b,["serviceTier"]);void 0!==c&&null!=j&&bY(c,["serviceTier"],j);let k=bZ(b,["systemInstruction"]);void 0!==c&&null!=k&&bY(c,["systemInstruction"],di(cF(k)));let l=bZ(b,["temperature"]);null!=l&&bY(i,["temperature"],l);let m=bZ(b,["topP"]);null!=m&&bY(i,["topP"],m);let n=bZ(b,["topK"]);null!=n&&bY(i,["topK"],n);let o=bZ(b,["candidateCount"]);null!=o&&bY(i,["candidateCount"],o);let p=bZ(b,["maxOutputTokens"]);null!=p&&bY(i,["maxOutputTokens"],p);let q=bZ(b,["stopSequences"]);null!=q&&bY(i,["stopSequences"],q);let r=bZ(b,["responseLogprobs"]);null!=r&&bY(i,["responseLogprobs"],r);let s=bZ(b,["logprobs"]);null!=s&&bY(i,["logprobs"],s);let t=bZ(b,["presencePenalty"]);null!=t&&bY(i,["presencePenalty"],t);let u=bZ(b,["frequencyPenalty"]);null!=u&&bY(i,["frequencyPenalty"],u);let v=bZ(b,["seed"]);null!=v&&bY(i,["seed"],v);let w=bZ(b,["responseMimeType"]);null!=w&&bY(i,["responseMimeType"],w);let x=bZ(b,["responseSchema"]);null!=x&&bY(i,["responseSchema"],cI(x));let y=bZ(b,["responseJsonSchema"]);if(null!=y&&bY(i,["responseJsonSchema"],y),void 0!==bZ(b,["routingConfig"]))throw Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(b,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let z=bZ(b,["safetySettings"]);if(void 0!==c&&null!=z){let a=z;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["category"]);if(null!=c&&bY(b,["category"],c),void 0!==bZ(a,["method"]))throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["threshold"]);return null!=d&&bY(b,["threshold"],d),b})(a))),bY(c,["safetySettings"],a)}let A=bZ(b,["tools"]);if(void 0!==c&&null!=A){let a=cM(A);Array.isArray(a)&&(a=a.map(a=>(function(a){let b={};if(void 0!==bZ(a,["retrieval"]))throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["googleMaps"]);null!=c&&bY(b,["googleMaps"],function(a){let b={},c=bZ(a,["authConfig"]);null!=c&&bY(b,["authConfig"],function(a){let b={},c=bZ(a,["apiKey"]);if(null!=c&&bY(b,["apiKey"],c),void 0!==bZ(a,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["authType"]))throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oauthConfig"]))throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oidcConfig"]))throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["enableWidget"]);if(null!=d&&bY(b,["enableWidget"],d),void 0!==bZ(a,["groundingTypes"]))throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["mcpServers"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mcpServers"],a)}let e=bZ(a,["codeExecution"]);null!=e&&bY(b,["codeExecution"],e);let f=bZ(a,["computerUse"]);if(null!=f&&bY(b,["computerUse"],f),void 0!==bZ(a,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["exaAiSearch"]))throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=bZ(a,["functionDeclarations"]);if(null!=g){let a=g;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let h=bZ(a,["googleSearch"]);null!=h&&bY(b,["googleSearch"],function(a){let b={};if(void 0!==bZ(a,["blockingConfidence"]))throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["excludeDomains"]))throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["searchTypes"]);null!=c&&bY(b,["searchTypes"],c);let d=bZ(a,["timeRangeFilter"]);return null!=d&&bY(b,["timeRangeFilter"],d),b}(h));let i=bZ(a,["googleSearchRetrieval"]);if(null!=i&&bY(b,["googleSearchRetrieval"],i),void 0!==bZ(a,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["urlContext"]);null!=j&&bY(b,["urlContext"],j);let k=bZ(a,["fileSearch"]);return null!=k&&bY(b,["fileSearch"],k),b})(cL(a)))),bY(c,["tools"],a)}let B=bZ(b,["toolConfig"]);if(void 0!==c&&null!=B&&bY(c,["toolConfig"],(e={},null!=(f=bZ(d=B,["functionCallingConfig"]))&&bY(e,["functionCallingConfig"],function(a){let b={},c=bZ(a,["allowedFunctionNames"]);null!=c&&bY(b,["allowedFunctionNames"],c);let d=bZ(a,["mode"]);if(null!=d&&bY(b,["mode"],d),void 0!==bZ(a,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(f)),null!=(g=bZ(d,["retrievalConfig"]))&&bY(e,["retrievalConfig"],g),null!=(h=bZ(d,["includeServerSideToolInvocations"]))&&bY(e,["includeServerSideToolInvocations"],h),e)),void 0!==bZ(b,["labels"]))throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let C=bZ(b,["cachedContent"]);void 0!==c&&null!=C&&bY(c,["cachedContent"],cN(a,C));let D=bZ(b,["responseModalities"]);null!=D&&bY(i,["responseModalities"],D);let E=bZ(b,["mediaResolution"]);null!=E&&bY(i,["mediaResolution"],E);let F=bZ(b,["speechConfig"]);if(null!=F&&bY(i,["speechConfig"],cJ(F)),void 0!==bZ(b,["audioTimestamp"]))throw Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let G=bZ(b,["thinkingConfig"]);null!=G&&bY(i,["thinkingConfig"],G);let H=bZ(b,["audioTranscriptionConfig"]);null!=H&&bY(i,["audioTranscriptionConfig"],H);let I=bZ(b,["imageConfig"]);null!=I&&bY(i,["imageConfig"],function(a){let b={},c=bZ(a,["aspectRatio"]);null!=c&&bY(b,["aspectRatio"],c);let d=bZ(a,["imageSize"]);if(null!=d&&bY(b,["imageSize"],d),void 0!==bZ(a,["personGeneration"]))throw Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["outputMimeType"]))throw Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["imageOutputOptions"]))throw Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["prominentPeople"]))throw Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(I));let J=bZ(b,["enableEnhancedCivicAnswers"]);if(null!=J&&bY(i,["enableEnhancedCivicAnswers"],J),void 0!==bZ(b,["modelArmorConfig"]))throw Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}(a,g,d)),d}function dl(a,b,c){let d={},e=bZ(b,["model"]);null!=e&&bY(d,["_url","model"],cu(a,e));let f=bZ(b,["contents"]);if(null!=f){let a=cH(f);Array.isArray(a)&&(a=a.map(a=>dj(a))),bY(d,["contents"],a)}let g=bZ(b,["config"]);return null!=g&&bY(d,["generationConfig"],function(a,b,c){var d;let e,f,g,h,i,j,k,l,m={},n=bZ(b,["serviceTier"]);void 0!==c&&null!=n&&bY(c,["serviceTier"],n);let o=bZ(b,["systemInstruction"]);void 0!==c&&null!=o&&bY(c,["systemInstruction"],dj(cF(o)));let p=bZ(b,["temperature"]);null!=p&&bY(m,["temperature"],p);let q=bZ(b,["topP"]);null!=q&&bY(m,["topP"],q);let r=bZ(b,["topK"]);null!=r&&bY(m,["topK"],r);let s=bZ(b,["candidateCount"]);null!=s&&bY(m,["candidateCount"],s);let t=bZ(b,["maxOutputTokens"]);null!=t&&bY(m,["maxOutputTokens"],t);let u=bZ(b,["stopSequences"]);null!=u&&bY(m,["stopSequences"],u);let v=bZ(b,["responseLogprobs"]);null!=v&&bY(m,["responseLogprobs"],v);let w=bZ(b,["logprobs"]);null!=w&&bY(m,["logprobs"],w);let x=bZ(b,["presencePenalty"]);null!=x&&bY(m,["presencePenalty"],x);let y=bZ(b,["frequencyPenalty"]);null!=y&&bY(m,["frequencyPenalty"],y);let z=bZ(b,["seed"]);null!=z&&bY(m,["seed"],z);let A=bZ(b,["responseMimeType"]);null!=A&&bY(m,["responseMimeType"],A);let B=bZ(b,["responseSchema"]);null!=B&&bY(m,["responseSchema"],cI(B));let C=bZ(b,["responseJsonSchema"]);null!=C&&bY(m,["responseJsonSchema"],C);let D=bZ(b,["routingConfig"]);null!=D&&bY(m,["routingConfig"],D);let E=bZ(b,["modelSelectionConfig"]);null!=E&&bY(m,["modelConfig"],E);let F=bZ(b,["safetySettings"]);if(void 0!==c&&null!=F){let a=F;Array.isArray(a)&&(a=a.map(a=>a)),bY(c,["safetySettings"],a)}let G=bZ(b,["tools"]);if(void 0!==c&&null!=G){let a=cM(G);Array.isArray(a)&&(a=a.map(a=>dy(cL(a)))),bY(c,["tools"],a)}let H=bZ(b,["toolConfig"]);void 0!==c&&null!=H&&bY(c,["toolConfig"],function(a){let b={},c=bZ(a,["functionCallingConfig"]);null!=c&&bY(b,["functionCallingConfig"],c);let d=bZ(a,["retrievalConfig"]);if(null!=d&&bY(b,["retrievalConfig"],d),void 0!==bZ(a,["includeServerSideToolInvocations"]))throw Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(H));let I=bZ(b,["labels"]);void 0!==c&&null!=I&&bY(c,["labels"],I);let J=bZ(b,["cachedContent"]);void 0!==c&&null!=J&&bY(c,["cachedContent"],cN(a,J));let K=bZ(b,["responseModalities"]);null!=K&&bY(m,["responseModalities"],K);let L=bZ(b,["mediaResolution"]);null!=L&&bY(m,["mediaResolution"],L);let M=bZ(b,["speechConfig"]);null!=M&&bY(m,["speechConfig"],dx(cJ(M)));let N=bZ(b,["audioTimestamp"]);null!=N&&bY(m,["audioTimestamp"],N);let O=bZ(b,["thinkingConfig"]);null!=O&&bY(m,["thinkingConfig"],O);let P=bZ(b,["audioTranscriptionConfig"]);null!=P&&bY(m,["audioTranscriptionConfig"],P);let Q=bZ(b,["imageConfig"]);if(null!=Q&&bY(m,["imageConfig"],(e={},null!=(f=bZ(d=Q,["aspectRatio"]))&&bY(e,["aspectRatio"],f),null!=(g=bZ(d,["imageSize"]))&&bY(e,["imageSize"],g),null!=(h=bZ(d,["personGeneration"]))&&bY(e,["personGeneration"],h),null!=(i=bZ(d,["outputMimeType"]))&&bY(e,["imageOutputOptions","mimeType"],i),null!=(j=bZ(d,["outputCompressionQuality"]))&&bY(e,["imageOutputOptions","compressionQuality"],j),null!=(k=bZ(d,["imageOutputOptions"]))&&bY(e,["imageOutputOptions"],k),null!=(l=bZ(d,["prominentPeople"]))&&bY(e,["prominentPeople"],l),e)),void 0!==bZ(b,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let R=bZ(b,["modelArmorConfig"]);return void 0!==c&&null!=R&&bY(c,["modelArmorConfig"],R),m}(a,g,d)),d}function dm(a,b){let c={},d=bZ(a,["sdkHttpResponse"]);null!=d&&bY(c,["sdkHttpResponse"],d);let e=bZ(a,["candidates"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["content"]);null!=c&&bY(b,["content"],c);let d=bZ(a,["citationMetadata"]);null!=d&&bY(b,["citationMetadata"],function(a){let b={},c=bZ(a,["citationSources"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["citations"],a)}return b}(d));let e=bZ(a,["tokenCount"]);null!=e&&bY(b,["tokenCount"],e);let f=bZ(a,["finishReason"]);null!=f&&bY(b,["finishReason"],f);let g=bZ(a,["groundingMetadata"]);null!=g&&bY(b,["groundingMetadata"],g);let h=bZ(a,["avgLogprobs"]);null!=h&&bY(b,["avgLogprobs"],h);let i=bZ(a,["index"]);null!=i&&bY(b,["index"],i);let j=bZ(a,["logprobsResult"]);null!=j&&bY(b,["logprobsResult"],j);let k=bZ(a,["safetyRatings"]);if(null!=k){let a=k;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["safetyRatings"],a)}let l=bZ(a,["urlContextMetadata"]);return null!=l&&bY(b,["urlContextMetadata"],l),b})(a))),bY(c,["candidates"],a)}let f=bZ(a,["modelVersion"]);null!=f&&bY(c,["modelVersion"],f);let g=bZ(a,["promptFeedback"]);null!=g&&bY(c,["promptFeedback"],g);let h=bZ(a,["responseId"]);null!=h&&bY(c,["responseId"],h);let i=bZ(a,["usageMetadata"]);null!=i&&bY(c,["usageMetadata"],i);let j=bZ(a,["modelStatus"]);return null!=j&&bY(c,["modelStatus"],j),c}function dn(a,b){let c={},d=bZ(a,["sdkHttpResponse"]);null!=d&&bY(c,["sdkHttpResponse"],d);let e=bZ(a,["candidates"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(c,["candidates"],a)}let f=bZ(a,["createTime"]);null!=f&&bY(c,["createTime"],f);let g=bZ(a,["modelVersion"]);null!=g&&bY(c,["modelVersion"],g);let h=bZ(a,["promptFeedback"]);null!=h&&bY(c,["promptFeedback"],h);let i=bZ(a,["responseId"]);null!=i&&bY(c,["responseId"],i);let j=bZ(a,["usageMetadata"]);return null!=j&&bY(c,["usageMetadata"],j),c}function dp(a,b){let c={},d=bZ(a,["_self"]);null!=d&&bY(c,["image"],dq(d));let e=bZ(a,["raiFilteredReason"]);null!=e&&bY(c,["raiFilteredReason"],e);let f=bZ(a,["_self"]);null!=f&&bY(c,["safetyAttributes"],dw(f));let g=bZ(a,["prompt"]);return null!=g&&bY(c,["enhancedPrompt"],g),c}function dq(a,b){let c={},d=bZ(a,["gcsUri"]);null!=d&&bY(c,["gcsUri"],d);let e=bZ(a,["bytesBase64Encoded"]);null!=e&&bY(c,["imageBytes"],b$(e));let f=bZ(a,["mimeType"]);return null!=f&&bY(c,["mimeType"],f),c}function dr(a,b){let c={};if(void 0!==bZ(a,["gcsUri"]))throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["imageBytes"]);null!=d&&bY(c,["bytesBase64Encoded"],b$(d));let e=bZ(a,["mimeType"]);return null!=e&&bY(c,["mimeType"],e),c}function ds(a,b){let c={},d=bZ(a,["gcsUri"]);null!=d&&bY(c,["gcsUri"],d);let e=bZ(a,["imageBytes"]);null!=e&&bY(c,["bytesBase64Encoded"],b$(e));let f=bZ(a,["mimeType"]);return null!=f&&bY(c,["mimeType"],f),c}function dt(a,b){var c;let d,e,f,g,h={},i=bZ(a,["name"]);null!=i&&bY(h,["name"],i);let j=bZ(a,["displayName"]);null!=j&&bY(h,["displayName"],j);let k=bZ(a,["description"]);null!=k&&bY(h,["description"],k);let l=bZ(a,["version"]);null!=l&&bY(h,["version"],l);let m=bZ(a,["_self"]);null!=m&&bY(h,["tunedModelInfo"],(d={},null!=(e=bZ(c=m,["baseModel"]))&&bY(d,["baseModel"],e),null!=(f=bZ(c,["createTime"]))&&bY(d,["createTime"],f),null!=(g=bZ(c,["updateTime"]))&&bY(d,["updateTime"],g),d));let n=bZ(a,["inputTokenLimit"]);null!=n&&bY(h,["inputTokenLimit"],n);let o=bZ(a,["outputTokenLimit"]);null!=o&&bY(h,["outputTokenLimit"],o);let p=bZ(a,["supportedGenerationMethods"]);null!=p&&bY(h,["supportedActions"],p);let q=bZ(a,["temperature"]);null!=q&&bY(h,["temperature"],q);let r=bZ(a,["maxTemperature"]);null!=r&&bY(h,["maxTemperature"],r);let s=bZ(a,["topP"]);null!=s&&bY(h,["topP"],s);let t=bZ(a,["topK"]);null!=t&&bY(h,["topK"],t);let u=bZ(a,["thinking"]);return null!=u&&bY(h,["thinking"],u),h}function du(a,b){var c;let d,e,f,g,h={},i=bZ(a,["name"]);null!=i&&bY(h,["name"],i);let j=bZ(a,["displayName"]);null!=j&&bY(h,["displayName"],j);let k=bZ(a,["description"]);null!=k&&bY(h,["description"],k);let l=bZ(a,["versionId"]);null!=l&&bY(h,["version"],l);let m=bZ(a,["deployedModels"]);if(null!=m){let a=m;Array.isArray(a)&&(a=a.map(a=>{let b,c,d;return b={},null!=(c=bZ(a,["endpoint"]))&&bY(b,["name"],c),null!=(d=bZ(a,["deployedModelId"]))&&bY(b,["deployedModelId"],d),b})),bY(h,["endpoints"],a)}let n=bZ(a,["labels"]);null!=n&&bY(h,["labels"],n);let o=bZ(a,["_self"]);null!=o&&bY(h,["tunedModelInfo"],(d={},null!=(e=bZ(c=o,["labels","google-vertex-llm-tuning-base-model-id"]))&&bY(d,["baseModel"],e),null!=(f=bZ(c,["createTime"]))&&bY(d,["createTime"],f),null!=(g=bZ(c,["updateTime"]))&&bY(d,["updateTime"],g),d));let p=bZ(a,["defaultCheckpointId"]);null!=p&&bY(h,["defaultCheckpointId"],p);let q=bZ(a,["checkpoints"]);if(null!=q){let a=q;Array.isArray(a)&&(a=a.map(a=>a)),bY(h,["checkpoints"],a)}return h}function dv(a,b){let c={},d=bZ(a,["safetyAttributes","categories"]);null!=d&&bY(c,["categories"],d);let e=bZ(a,["safetyAttributes","scores"]);null!=e&&bY(c,["scores"],e);let f=bZ(a,["contentType"]);return null!=f&&bY(c,["contentType"],f),c}function dw(a,b){let c={},d=bZ(a,["safetyAttributes","categories"]);null!=d&&bY(c,["categories"],d);let e=bZ(a,["safetyAttributes","scores"]);null!=e&&bY(c,["scores"],e);let f=bZ(a,["contentType"]);return null!=f&&bY(c,["contentType"],f),c}function dx(a,b){let c={},d=bZ(a,["voiceConfig"]);null!=d&&bY(c,["voiceConfig"],dB(d));let e=bZ(a,["languageCode"]);null!=e&&bY(c,["languageCode"],e);let f=bZ(a,["multiSpeakerVoiceConfig"]);return null!=f&&bY(c,["multiSpeakerVoiceConfig"],function(a){let b={},c=bZ(a,["speakerVoiceConfigs"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e;return c={},null!=(d=bZ(b=a,["speaker"]))&&bY(c,["speaker"],d),null!=(e=bZ(b,["voiceConfig"]))&&bY(c,["voiceConfig"],dB(e)),c})),bY(b,["speakerVoiceConfigs"],a)}return b}(f)),c}function dy(a,b){let c={},d=bZ(a,["retrieval"]);null!=d&&bY(c,["retrieval"],d);let e=bZ(a,["googleMaps"]);null!=e&&bY(c,["googleMaps"],e);let f=bZ(a,["mcpServers"]);if(null!=f){let a=f;Array.isArray(a)&&(a=a.map(a=>(function(a){if(void 0!==bZ(a,["name"]))throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["streamableHttpTransport"]))throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}})(a))),bY(c,["mcpServers"],a)}let g=bZ(a,["codeExecution"]);null!=g&&bY(c,["codeExecution"],g);let h=bZ(a,["computerUse"]);null!=h&&bY(c,["computerUse"],function(a){let b={},c=bZ(a,["enablePromptInjectionDetection"]);null!=c&&bY(b,["enablePromptInjectionDetection"],c);let d=bZ(a,["environment"]);null!=d&&bY(b,["environment"],d);let e=bZ(a,["excludedPredefinedFunctions"]);if(null!=e&&bY(b,["excludedPredefinedFunctions"],e),void 0!==bZ(a,["disabledSafetyPolicies"]))throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(h));let i=bZ(a,["enterpriseWebSearch"]);null!=i&&bY(c,["enterpriseWebSearch"],i);let j=bZ(a,["exaAiSearch"]);null!=j&&bY(c,["exaAiSearch"],j);let k=bZ(a,["functionDeclarations"]);if(null!=k){let a=k;Array.isArray(a)&&(a=a.map(a=>a)),bY(c,["functionDeclarations"],a)}let l=bZ(a,["googleSearch"]);null!=l&&bY(c,["googleSearch"],l);let m=bZ(a,["googleSearchRetrieval"]);null!=m&&bY(c,["googleSearchRetrieval"],m);let n=bZ(a,["parallelAiSearch"]);null!=n&&bY(c,["parallelAiSearch"],n);let o=bZ(a,["urlContext"]);if(null!=o&&bY(c,["urlContext"],o),void 0!==bZ(a,["fileSearch"]))throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return c}function dz(a,b){let c={},d=bZ(a,["uri"]);null!=d&&bY(c,["uri"],d);let e=bZ(a,["videoBytes"]);null!=e&&bY(c,["encodedVideo"],b$(e));let f=bZ(a,["mimeType"]);return null!=f&&bY(c,["encoding"],f),c}function dA(a,b){let c={},d=bZ(a,["uri"]);null!=d&&bY(c,["gcsUri"],d);let e=bZ(a,["videoBytes"]);null!=e&&bY(c,["bytesBase64Encoded"],b$(e));let f=bZ(a,["mimeType"]);return null!=f&&bY(c,["mimeType"],f),c}function dB(a,b){let c={},d=bZ(a,["replicatedVoiceConfig"]);null!=d&&bY(c,["replicatedVoiceConfig"],function(a){let b={},c=bZ(a,["mimeType"]);null!=c&&bY(b,["mimeType"],c);let d=bZ(a,["voiceSampleAudio"]);if(null!=d&&bY(b,["voiceSampleAudio"],d),void 0!==bZ(a,["consentAudio"]))throw Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["voiceConsentSignature"]))throw Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(d));let e=bZ(a,["prebuiltVoiceConfig"]);return null!=e&&bY(c,["prebuiltVoiceConfig"],e),c}function dC(a,b){let c=bZ(a,["mimeType"]);void 0!==b&&null!=c&&bY(b,["mimeType"],c);let d=bZ(a,["displayName"]);void 0!==b&&null!=d&&bY(b,["displayName"],d);let e=bZ(a,["customMetadata"]);if(void 0!==b&&null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["customMetadata"],a)}let f=bZ(a,["chunkingConfig"]);return void 0!==b&&null!=f&&bY(b,["chunkingConfig"],f),{}}let dD="x-goog-api-client",dE=new Set(["us","eu"]),dF=[408,429,500,502,503,504];class dG{constructor(a){var b,c,d;this.clientOptions=Object.assign({},a),this.customBaseUrl=null==(b=a.httpOptions)?void 0:b.baseUrl;const e={};if(this.clientOptions.vertexai){if(this.clientOptions.location||this.clientOptions.apiKey||this.customBaseUrl||(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");const b=a.project&&a.location||!!a.apiKey;this.customBaseUrl&&!b?(e.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||"global"===this.clientOptions.location?e.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&dE.has(this.clientOptions.location)?e.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(e.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),e.apiVersion=null!=(c=this.clientOptions.apiVersion)?c:"v1beta1"}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),e.apiVersion=null!=(d=this.clientOptions.apiVersion)?d:"v1beta",e.baseUrl="https://generativelanguage.googleapis.com/";e.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=e,a.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(e,a.httpOptions))}isVertexAI(){var a;return null!=(a=this.clientOptions.vertexai)&&a}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let a=new Headers;return await this.clientOptions.auth.addAuthHeaders(a),a}getApiVersion(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.apiVersion)return this.clientOptions.httpOptions.apiVersion;throw Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.baseUrl)return this.clientOptions.httpOptions.baseUrl;throw Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.headers)return this.clientOptions.httpOptions.headers;throw Error("Headers are not set.")}getRequestUrlInternal(a){if(!a||void 0===a.baseUrl||void 0===a.apiVersion)throw Error("HTTP options are not correctly set.");let b=[a.baseUrl.endsWith("/")?a.baseUrl.slice(0,-1):a.baseUrl];return a.apiVersion&&""!==a.apiVersion&&b.push(a.apiVersion),b.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let a=new URL(this.getBaseUrl());return a.protocol="http:"==a.protocol?"ws":"wss",a.toString()}setBaseUrl(a){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=a;else throw Error("HTTP options are not correctly set.")}constructUrl(a,b,c){let d=[this.getRequestUrlInternal(b)];return c&&d.push(this.getBaseResourcePath()),""!==a&&d.push(a),new URL(`${d.join("/")}`)}shouldPrependVertexProjectPath(a,b){return!(b.baseUrl&&b.baseUrlResourceScope===bl.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||a.path.startsWith("projects/")||"GET"===a.httpMethod&&a.path.startsWith("publishers/google/models"))}async request(a){let b=this.clientOptions.httpOptions;a.httpOptions&&(b=this.patchHttpOptions(this.clientOptions.httpOptions,a.httpOptions));let c=this.shouldPrependVertexProjectPath(a,b),d=this.constructUrl(a.path,b,c);if(a.queryParams)for(let[b,c]of Object.entries(a.queryParams))d.searchParams.append(b,String(c));let e={};if("GET"===a.httpMethod){if(a.body&&"{}"!==a.body)throw Error("Request body should be empty for GET request, but got non empty request body")}else e.body=a.body;return e=await this.includeExtraHttpOptionsToRequestInit(e,b,d.toString(),a.abortSignal),this.unaryApiCall(d,e,a.httpMethod,b.retryOptions)}patchHttpOptions(a,b){let c=JSON.parse(JSON.stringify(a));for(let[a,d]of Object.entries(b))"object"==typeof d?c[a]=Object.assign(Object.assign({},c[a]),d):void 0!==d&&(c[a]=d);return c}async requestStream(a){let b=this.clientOptions.httpOptions;a.httpOptions&&(b=this.patchHttpOptions(this.clientOptions.httpOptions,a.httpOptions));let c=this.shouldPrependVertexProjectPath(a,b),d=this.constructUrl(a.path,b,c);d.searchParams.has("alt")&&"sse"===d.searchParams.get("alt")||d.searchParams.set("alt","sse");let e={};return e.body=a.body,e=await this.includeExtraHttpOptionsToRequestInit(e,b,d.toString(),a.abortSignal),this.streamApiCall(d,e,a.httpMethod,b.retryOptions)}async includeExtraHttpOptionsToRequestInit(a,b,c,d){if(b&&b.timeout||d){let c=new AbortController,e=c.signal;if(b.timeout&&(null==b?void 0:b.timeout)>0){let a=Symbol.for("undici.globalDispatcher.1"),d=globalThis[a];if(d)for(let a of Object.getOwnPropertySymbols(d)){let c=a.description;if((null==c?void 0:c.includes("headers timeout"))||(null==c?void 0:c.includes("body timeout"))){let c=d[a];"number"==typeof c&&(d[a]=Math.max(c,b.timeout))}}let e=setTimeout(()=>c.abort(),b.timeout);e&&"function"==typeof e.unref&&e.unref()}d&&d.addEventListener("abort",()=>{c.abort()}),a.signal=e}return b&&null!==b.extraBody&&function(a,b){if(!b||0===Object.keys(b).length)return;if(a.body instanceof Blob)return console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");let c={};if("string"==typeof a.body&&a.body.length>0)try{let b=JSON.parse(a.body);if("object"!=typeof b||null===b||Array.isArray(b))return void console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");c=b}catch(a){console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}a.body=JSON.stringify(function a(b,c){let d=Object.assign({},b);for(let b in c)if(Object.prototype.hasOwnProperty.call(c,b)){let e=c[b],f=d[b];e&&"object"==typeof e&&!Array.isArray(e)&&f&&"object"==typeof f&&!Array.isArray(f)?d[b]=a(f,e):(f&&e&&typeof f!=typeof e&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${b}". Original type: ${typeof f}, New type: ${typeof e}. Overwriting.`),d[b]=e)}return d}(c,b))}(a,b.extraBody),a.headers=await this.getHeadersInternal(b,c),a}async unaryApiCall(a,b,c,d){return this.apiCall(a.toString(),Object.assign(Object.assign({},b),{method:c}),d).then(async a=>(await dH(a),new b0(a))).catch(a=>{if(a instanceof Error)throw a;throw Error(`exception ${a} sending request`,{cause:a})})}async streamApiCall(a,b,c,d){return this.apiCall(a.toString(),Object.assign(Object.assign({},b),{method:c}),d).then(async a=>(await dH(a),this.processStreamResponse(a))).catch(a=>{if(a instanceof Error)throw a;throw Error(`exception ${a} sending request`,{cause:a})})}processStreamResponse(a){return c7(this,arguments,function*(){var b;let c=null==(b=null==a?void 0:a.body)?void 0:b.getReader(),d=new TextDecoder("utf-8");if(!c)throw Error("Response body is empty");try{let b="",e="data:",f=["\n\n","\r\r","\r\n\r\n"];for(;;){let{done:g,value:h}=yield c6(c.read());if(g){if(b.trim().length>0)throw Error("Incomplete JSON segment at the end");break}let i=d.decode(h,{stream:!0});try{let a=JSON.parse(i);if("error"in a){let b=JSON.parse(JSON.stringify(a.error)),c=b.status,d=b.code,e=`got status: ${c}. ${JSON.stringify(a)}`;if(d>=400&&d<600)throw new dd({message:e,status:d})}}catch(a){if("ApiError"===a.name)throw a}b+=i;let j=-1,k=0;for(;;){for(let a of(j=-1,k=0,f)){let c=b.indexOf(a);-1!==c&&(-1===j||c<j)&&(j=c,k=a.length)}if(-1===j)break;let c=b.substring(0,j);b=b.substring(j+k);let d=c.trim();if(d.startsWith(e)){let b=d.substring(e.length).trim();try{let c=new Response(b,{headers:null==a?void 0:a.headers,status:null==a?void 0:a.status,statusText:null==a?void 0:a.statusText});yield yield c6(new b0(c))}catch(a){throw Error(`exception parsing stream chunk ${b}. ${a}`)}}}}}finally{c.releaseLock()}})}async apiCall(a,b,c){var d,e,f,g,h,i;if(!c)return fetch(a,b);let j=null!=(d=c.httpStatusCodes)?d:dF,k=async()=>{let c=await fetch(a,b);return c.ok||!j.includes(c.status)||await dH(c),c},l=Math.max(1,null!=(e=c.attempts)?e:5),m=Math.round((null!=(f=c.initialDelay)?f:1)*1e3),n=Math.max(m,Math.round((null!=(g=c.maxDelay)?g:60)*1e3));return bO(k,{retries:l-1,factor:null!=(h=c.expBase)?h:2,minTimeout:m,maxTimeout:n,randomize:(null!=(i=c.jitter)?i:1)>0})}getDefaultHeaders(){let a={},b="google-genai-sdk/2.15.0 "+this.clientOptions.userAgentExtra;return a["User-Agent"]=b,a[dD]=b,a["Content-Type"]="application/json",a}async getHeadersInternal(a,b){let c=new Headers;if(a&&a.headers)for(let[b,d]of Object.entries(a.headers))c.append(b,d);return(null==a?void 0:a.timeout)&&a.timeout>0&&c.append("X-Server-Timeout",String(Math.ceil(a.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(c,b),c}getFileName(a){var b;let c="";return"string"==typeof a&&(c=null!=(b=(c=a.replace(/[/\\]+$/,"")).split(/[/\\]/).pop())?b:""),c}async uploadFile(a,b){var c;let d={};null!=b&&(d.mimeType=b.mimeType,d.name=b.name,d.displayName=b.displayName),d.name&&!d.name.startsWith("files/")&&(d.name=`files/${d.name}`);let e=this.clientOptions.uploader,f=await e.stat(a);d.sizeBytes=String(f.size);let g=null!=(c=null==b?void 0:b.mimeType)?c:f.type;if(void 0===g||""===g)throw Error("Can not determine mimeType. Please provide mimeType in the config.");d.mimeType=g;let h={file:d},i=this.getFileName(a),j=bX("upload/v1beta/files",h._url),k=await this.fetchUploadUrl(j,d.sizeBytes,d.mimeType,i,h,null==b?void 0:b.httpOptions);return e.upload(a,k,this)}async uploadFileToFileSearchStore(a,b,c){var d;let e=this.clientOptions.uploader,f=await e.stat(b),g=String(f.size),h=null!=(d=null==c?void 0:c.mimeType)?d:f.type;if(void 0===h||""===h)throw Error("Can not determine mimeType. Please provide mimeType in the config.");let i=`upload/v1beta/${a}:uploadToFileSearchStore`,j=this.getFileName(b),k={};null!=c&&dC(c,k);let l=await this.fetchUploadUrl(i,g,h,j,k,null==c?void 0:c.httpOptions);return e.uploadToFileSearchStore(b,l,this)}async downloadFile(a){let b=this.clientOptions.downloader;await b.download(a,this)}async fetchUploadUrl(a,b,c,d,e,f){var g;let h={};h=f||{apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${b}`,"X-Goog-Upload-Header-Content-Type":`${c}`},d?{"X-Goog-Upload-File-Name":d}:{})};let i=await this.request({path:a,body:JSON.stringify(e),httpMethod:"POST",httpOptions:h});if(!i||!(null==i?void 0:i.headers))throw Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let j=null==(g=null==i?void 0:i.headers)?void 0:g["x-goog-upload-url"];if(void 0===j)throw Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return j}}async function dH(a){var b;if(void 0===a)throw Error("response is undefined");if(!a.ok){let c=a.status,d=JSON.stringify((null==(b=a.headers.get("content-type"))?void 0:b.includes("application/json"))?await a.json():{error:{message:await a.text(),code:a.status,status:a.statusText}});if(c>=400&&c<600)throw new dd({message:d,status:c});throw Error(d)}}function dI(a){for(let c of a){var b;if(null!==(b=c)&&"object"==typeof b&&b instanceof dK||"object"==typeof c&&"inputSchema"in c)return!0}return!1}function dJ(a){var b;let c=null!=(b=a[dD])?b:"";a[dD]=(c+" mcp_used/unknown").trimStart()}class dK{constructor(a=[],b){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=a,this.config=b}static create(a,b){return new dK(a,b)}async initialize(){var a,b,c,d;if(this.mcpTools.length>0)return;let e={},f=[];for(let j of this.mcpClients)try{for(var g,h=!0,i=(b=void 0,c8(function(a){return c7(this,arguments,function*(a,b=100){let c,d=0;for(;d<b;){let b=yield c6(a.listTools({cursor:c}));for(let a of b.tools)yield yield c6(a),d++;if(!b.nextCursor)break;c=b.nextCursor}})}(j)));!(a=(g=await i.next()).done);h=!0){d=g.value,h=!1,f.push(d);let a=d.name;if(e[a])throw Error(`Duplicate function name ${a} found in MCP tools. Please ensure function names are unique.`);e[a]=j}}catch(a){b={error:a}}finally{try{!h&&!a&&(c=i.return)&&await c.call(i)}finally{if(b)throw b.error}}this.mcpTools=f,this.functionNameToMcpClient=e}async tool(){return await this.initialize(),function(a,b={}){let c=[],d=new Set;for(let e of a){let a=e.name;if(d.has(a))throw Error(`Duplicate function name ${a} found in MCP tools. Please ensure function names are unique.`);d.add(a);let f=function(a,b={}){let c={name:a.name,description:a.description,parametersJsonSchema:a.inputSchema};return a.outputSchema&&(c.responseJsonSchema=a.outputSchema),b.behavior&&(c.behavior=b.behavior),{functionDeclarations:[c]}}(e,b);f.functionDeclarations&&c.push(...f.functionDeclarations)}return{functionDeclarations:c}}(this.mcpTools,this.config)}async callTool(a){await this.initialize();let b=[];for(let c of a)if(c.name in this.functionNameToMcpClient){let a,d=this.functionNameToMcpClient[c.name];this.config.timeout&&(a={timeout:this.config.timeout});let e=await d.callTool({name:c.name,arguments:c.args},void 0,a);b.push({functionResponse:{name:c.name,response:e.isError?{error:e}:e}})}return b}}async function dL(a,b,c){let d=new cs;Object.assign(d,c.data instanceof Blob?JSON.parse(await c.data.text()):JSON.parse(c.data)),b(d)}class dM{constructor(a,b,c){this.apiClient=a,this.auth=b,this.webSocketFactory=c}async connect(a){var b,c;let d;if(this.apiClient.isVertexAI())throw Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let e=this.apiClient.getWebsocketBaseUrl(),f=this.apiClient.getApiVersion(),g=function(a){let b=new Headers;for(let[c,d]of Object.entries(a))b.append(c,d);return b}(this.apiClient.getDefaultHeaders()),h=this.apiClient.getApiKey(),i=`${e}/ws/google.ai.generativelanguage.${f}.GenerativeService.BidiGenerateMusic?key=${h}`,j=()=>{},k=new Promise(a=>{j=a}),l=a.callbacks,m=this.apiClient,n={onopen:function(){j({})},onmessage:a=>{dL(m,l.onmessage,a)},onerror:null!=(b=null==l?void 0:l.onerror)?b:function(a){},onclose:null!=(c=null==l?void 0:l.onclose)?c:function(a){}},o=this.webSocketFactory.create(i,(d={},g.forEach((a,b)=>{d[b]=a}),d),n);o.connect(),await k;let p=cu(this.apiClient,a.model);return o.send(JSON.stringify({setup:{model:p}})),new dN(o,this.apiClient)}}class dN{constructor(a,b){this.conn=a,this.apiClient=b}async setWeightedPrompts(a){if(!a.weightedPrompts||0===Object.keys(a.weightedPrompts).length)throw Error("Weighted prompts must be set and contain at least one entry.");let b=function(a){let b={},c=bZ(a,["weightedPrompts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["weightedPrompts"],a)}return b}(a);this.conn.send(JSON.stringify({clientContent:b}))}async setMusicGenerationConfig(a){let b,c;a.musicGenerationConfig||(a.musicGenerationConfig={});let d=(b={},null!=(c=bZ(a,["musicGenerationConfig"]))&&bY(b,["musicGenerationConfig"],c),b);this.conn.send(JSON.stringify(d))}sendPlaybackControl(a){this.conn.send(JSON.stringify({playbackControl:a}))}play(){this.sendPlaybackControl(bL.PLAY)}pause(){this.sendPlaybackControl(bL.PAUSE)}stop(){this.sendPlaybackControl(bL.STOP)}resetContext(){this.sendPlaybackControl(bL.RESET_CONTEXT)}close(){this.conn.close()}}async function dO(a,b,c){let d=new cr,e=JSON.parse(c.data instanceof Blob?await c.data.text():c.data instanceof ArrayBuffer?new TextDecoder().decode(c.data):c.data);if(a.isVertexAI()){var f;let a,b,c,g,h,i,j,k,l,m,n,o,p;Object.assign(d,(a={},null!=(b=bZ(e,["setupComplete"]))&&bY(a,["setupComplete"],b),null!=(c=bZ(e,["serverContent"]))&&bY(a,["serverContent"],c),null!=(g=bZ(e,["toolCall"]))&&bY(a,["toolCall"],g),null!=(h=bZ(e,["toolCallCancellation"]))&&bY(a,["toolCallCancellation"],h),null!=(i=bZ(e,["usageMetadata"]))&&bY(a,["usageMetadata"],function(a){let b={},c=bZ(a,["candidatesTokenCount"]);null!=c&&bY(b,["responseTokenCount"],c);let d=bZ(a,["candidatesTokensDetails"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["responseTokensDetails"],a)}let e=bZ(a,["cacheTokensDetails"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["cacheTokensDetails"],a)}let f=bZ(a,["cachedContentTokenCount"]);null!=f&&bY(b,["cachedContentTokenCount"],f);let g=bZ(a,["promptTokenCount"]);null!=g&&bY(b,["promptTokenCount"],g);let h=bZ(a,["promptTokensDetails"]);if(null!=h){let a=h;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["promptTokensDetails"],a)}let i=bZ(a,["thoughtsTokenCount"]);null!=i&&bY(b,["thoughtsTokenCount"],i);let j=bZ(a,["toolUsePromptTokenCount"]);null!=j&&bY(b,["toolUsePromptTokenCount"],j);let k=bZ(a,["toolUsePromptTokensDetails"]);if(null!=k){let a=k;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["toolUsePromptTokensDetails"],a)}let l=bZ(a,["totalTokenCount"]);null!=l&&bY(b,["totalTokenCount"],l);let m=bZ(a,["trafficType"]);return null!=m&&bY(b,["trafficType"],m),b}(i)),null!=(j=bZ(e,["goAway"]))&&bY(a,["goAway"],j),null!=(k=bZ(e,["sessionResumptionUpdate"]))&&bY(a,["sessionResumptionUpdate"],k),null!=(l=bZ(e,["voiceActivityDetectionSignal"]))&&bY(a,["voiceActivityDetectionSignal"],l),null!=(m=bZ(e,["voiceActivity"]))&&bY(a,["voiceActivity"],(n={},null!=(o=bZ(f=m,["type"]))&&bY(n,["voiceActivityType"],o),null!=(p=bZ(f,["audioOffset"]))&&bY(n,["audioOffset"],p),n)),a))}else Object.assign(d,e);b(d)}class dP{constructor(a,b,c){this.apiClient=a,this.auth=b,this.webSocketFactory=c,this.music=new dM(this.apiClient,this.auth,this.webSocketFactory)}async connect(a){var b,c,d,e,f,g,h,i;let j,k;if(a.config&&a.config.httpOptions)throw Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let l=this.apiClient.getWebsocketBaseUrl(),m=this.apiClient.getApiVersion(),n=this.apiClient.getHeaders();a.config&&a.config.tools&&dI(a.config.tools)&&dJ(n);let o=function(a){let b=new Headers;for(let[c,d]of Object.entries(a))b.append(c,d);return b}(n);if(this.apiClient.isVertexAI()){let a=this.apiClient.getProject(),b=this.apiClient.getLocation(),c=this.apiClient.getApiKey();this.apiClient.getCustomBaseUrl()&&!(a&&b||c)?j=l:(j=`${l}/ws/google.cloud.aiplatform.${m}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(o,j))}else{let a=this.apiClient.getApiKey(),b="BidiGenerateContent",c="key";(null==a?void 0:a.startsWith("auth_tokens/"))&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),"v1alpha"!==m&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),b="BidiGenerateContentConstrained",c="access_token"),j=`${l}/ws/google.ai.generativelanguage.${m}.GenerativeService.${b}?${c}=${a}`}let p=()=>{},q=new Promise(a=>{p=a}),r=a.callbacks,s=this.apiClient,t=!1,u=[],v=()=>{},w=new Promise(a=>{v=a}),x={onopen:function(){var a;null==(a=null==r?void 0:r.onopen)||a.call(r),p({})},onmessage:a=>{dO(s,a=>{a.setupComplete&&!E.setupComplete&&(E.setupComplete=a.setupComplete,v({})),t?r.onmessage(a):u.push(a)},a)},onerror:null!=(b=null==r?void 0:r.onerror)?b:function(a){},onclose:null!=(c=null==r?void 0:r.onclose)?c:function(a){}},y=this.webSocketFactory.create(j,(k={},o.forEach((a,b)=>{k[b]=a}),k),x);y.connect(),await q;let z=cu(this.apiClient,a.model);if(this.apiClient.isVertexAI()&&z.startsWith("publishers/")){let a=this.apiClient.getProject(),b=this.apiClient.getLocation();a&&b&&(z=`projects/${a}/locations/${b}/`+z)}let A={};this.apiClient.isVertexAI()&&(null==(d=a.config)?void 0:d.responseModalities)===void 0&&(void 0===a.config?a.config={responseModalities:[a1.AUDIO]}:a.config.responseModalities=[a1.AUDIO]),(null==(e=a.config)?void 0:e.generationConfig)&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let B=null!=(g=null==(f=a.config)?void 0:f.tools)?g:[],C=[];for(let a of B)this.isCallableTool(a)?C.push(await a.tool()):C.push(a);C.length>0&&(a.config.tools=C);let D={model:z,config:a.config,callbacks:a.callbacks};if(this.apiClient.isVertexAI()){let a,b,c;h=this.apiClient,a={},null!=(b=bZ(D,["model"]))&&bY(a,["setup","model"],cu(h,b)),null!=(c=bZ(D,["config"]))&&bY(a,["config"],function(a,b){let c=bZ(a,["generationConfig"]);void 0!==b&&null!=c&&bY(b,["setup","generationConfig"],function(a){let b={},c=bZ(a,["modelSelectionConfig"]);null!=c&&bY(b,["modelConfig"],c);let d=bZ(a,["responseJsonSchema"]);null!=d&&bY(b,["responseJsonSchema"],d);let e=bZ(a,["audioTranscriptionConfig"]);null!=e&&bY(b,["audioTranscriptionConfig"],e);let f=bZ(a,["audioTimestamp"]);null!=f&&bY(b,["audioTimestamp"],f);let g=bZ(a,["candidateCount"]);null!=g&&bY(b,["candidateCount"],g);let h=bZ(a,["enableAffectiveDialog"]);null!=h&&bY(b,["enableAffectiveDialog"],h);let i=bZ(a,["frequencyPenalty"]);null!=i&&bY(b,["frequencyPenalty"],i);let j=bZ(a,["logprobs"]);null!=j&&bY(b,["logprobs"],j);let k=bZ(a,["maxOutputTokens"]);null!=k&&bY(b,["maxOutputTokens"],k);let l=bZ(a,["mediaResolution"]);null!=l&&bY(b,["mediaResolution"],l);let m=bZ(a,["presencePenalty"]);null!=m&&bY(b,["presencePenalty"],m);let n=bZ(a,["responseFormat"]);if(null!=n){let a=n;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["responseFormat"],a)}let o=bZ(a,["responseLogprobs"]);null!=o&&bY(b,["responseLogprobs"],o);let p=bZ(a,["responseMimeType"]);null!=p&&bY(b,["responseMimeType"],p);let q=bZ(a,["responseModalities"]);null!=q&&bY(b,["responseModalities"],q);let r=bZ(a,["responseSchema"]);null!=r&&bY(b,["responseSchema"],r);let s=bZ(a,["routingConfig"]);null!=s&&bY(b,["routingConfig"],s);let t=bZ(a,["seed"]);null!=t&&bY(b,["seed"],t);let u=bZ(a,["speechConfig"]);null!=u&&bY(b,["speechConfig"],dg(u));let v=bZ(a,["stopSequences"]);null!=v&&bY(b,["stopSequences"],v);let w=bZ(a,["temperature"]);null!=w&&bY(b,["temperature"],w);let x=bZ(a,["thinkingConfig"]);null!=x&&bY(b,["thinkingConfig"],x);let y=bZ(a,["topK"]);null!=y&&bY(b,["topK"],y);let z=bZ(a,["topP"]);if(null!=z&&bY(b,["topP"],z),void 0!==bZ(a,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["translationConfig"]))throw Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(c));let d=bZ(a,["responseModalities"]);void 0!==b&&null!=d&&bY(b,["setup","generationConfig","responseModalities"],d);let e=bZ(a,["temperature"]);void 0!==b&&null!=e&&bY(b,["setup","generationConfig","temperature"],e);let f=bZ(a,["topP"]);void 0!==b&&null!=f&&bY(b,["setup","generationConfig","topP"],f);let g=bZ(a,["topK"]);void 0!==b&&null!=g&&bY(b,["setup","generationConfig","topK"],g);let h=bZ(a,["maxOutputTokens"]);void 0!==b&&null!=h&&bY(b,["setup","generationConfig","maxOutputTokens"],h);let i=bZ(a,["mediaResolution"]);void 0!==b&&null!=i&&bY(b,["setup","generationConfig","mediaResolution"],i);let j=bZ(a,["seed"]);void 0!==b&&null!=j&&bY(b,["setup","generationConfig","seed"],j);let k=bZ(a,["speechConfig"]);void 0!==b&&null!=k&&bY(b,["setup","generationConfig","speechConfig"],dg(cK(k)));let l=bZ(a,["thinkingConfig"]);void 0!==b&&null!=l&&bY(b,["setup","generationConfig","thinkingConfig"],l);let m=bZ(a,["enableAffectiveDialog"]);void 0!==b&&null!=m&&bY(b,["setup","generationConfig","enableAffectiveDialog"],m);let n=bZ(a,["systemInstruction"]);void 0!==b&&null!=n&&bY(b,["setup","systemInstruction"],function(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["mediaResolution"]);if(null!=c&&bY(b,["mediaResolution"],c),void 0!==bZ(a,["toolCall"]))throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["toolResponse"]))throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let d=bZ(a,["audioTranscription"]);null!=d&&bY(b,["audioTranscription"],d);let e=bZ(a,["codeExecutionResult"]);null!=e&&bY(b,["codeExecutionResult"],function(a){let b={},c=bZ(a,["outcome"]);null!=c&&bY(b,["outcome"],c);let d=bZ(a,["output"]);if(null!=d&&bY(b,["output"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(e));let f=bZ(a,["executableCode"]);null!=f&&bY(b,["executableCode"],function(a){let b={},c=bZ(a,["code"]);null!=c&&bY(b,["code"],c);let d=bZ(a,["language"]);if(null!=d&&bY(b,["language"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(f));let g=bZ(a,["fileData"]);null!=g&&bY(b,["fileData"],g);let h=bZ(a,["functionCall"]);null!=h&&bY(b,["functionCall"],h);let i=bZ(a,["functionResponse"]);null!=i&&bY(b,["functionResponse"],i);let j=bZ(a,["inlineData"]);null!=j&&bY(b,["inlineData"],j);let k=bZ(a,["text"]);null!=k&&bY(b,["text"],k);let l=bZ(a,["thought"]);null!=l&&bY(b,["thought"],l);let m=bZ(a,["thoughtSignature"]);null!=m&&bY(b,["thoughtSignature"],m);let n=bZ(a,["videoMetadata"]);if(null!=n&&bY(b,["videoMetadata"],n),void 0!==bZ(a,["partMetadata"]))throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(a))),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}(cF(n)));let o=bZ(a,["tools"]);if(void 0!==b&&null!=o){let a=cM(o);Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["retrieval"]);null!=c&&bY(b,["retrieval"],c);let d=bZ(a,["googleMaps"]);null!=d&&bY(b,["googleMaps"],d);let e=bZ(a,["mcpServers"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>(function(a){if(void 0!==bZ(a,["name"]))throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["streamableHttpTransport"]))throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}})(a))),bY(b,["mcpServers"],a)}let f=bZ(a,["codeExecution"]);null!=f&&bY(b,["codeExecution"],f);let g=bZ(a,["computerUse"]);null!=g&&bY(b,["computerUse"],function(a){let b={},c=bZ(a,["enablePromptInjectionDetection"]);null!=c&&bY(b,["enablePromptInjectionDetection"],c);let d=bZ(a,["environment"]);null!=d&&bY(b,["environment"],d);let e=bZ(a,["excludedPredefinedFunctions"]);if(null!=e&&bY(b,["excludedPredefinedFunctions"],e),void 0!==bZ(a,["disabledSafetyPolicies"]))throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(g));let h=bZ(a,["enterpriseWebSearch"]);null!=h&&bY(b,["enterpriseWebSearch"],h);let i=bZ(a,["exaAiSearch"]);null!=i&&bY(b,["exaAiSearch"],i);let j=bZ(a,["functionDeclarations"]);if(null!=j){let a=j;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let k=bZ(a,["googleSearch"]);null!=k&&bY(b,["googleSearch"],k);let l=bZ(a,["googleSearchRetrieval"]);null!=l&&bY(b,["googleSearchRetrieval"],l);let m=bZ(a,["parallelAiSearch"]);null!=m&&bY(b,["parallelAiSearch"],m);let n=bZ(a,["urlContext"]);if(null!=n&&bY(b,["urlContext"],n),void 0!==bZ(a,["fileSearch"]))throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(cL(a)))),bY(b,["setup","tools"],a)}let p=bZ(a,["sessionResumption"]);void 0!==b&&null!=p&&bY(b,["setup","sessionResumption"],p);let q=bZ(a,["inputAudioTranscription"]);void 0!==b&&null!=q&&bY(b,["setup","inputAudioTranscription"],q);let r=bZ(a,["outputAudioTranscription"]);void 0!==b&&null!=r&&bY(b,["setup","outputAudioTranscription"],r);let s=bZ(a,["realtimeInputConfig"]);void 0!==b&&null!=s&&bY(b,["setup","realtimeInputConfig"],s);let t=bZ(a,["contextWindowCompression"]);void 0!==b&&null!=t&&bY(b,["setup","contextWindowCompression"],t);let u=bZ(a,["proactivity"]);void 0!==b&&null!=u&&bY(b,["setup","proactivity"],u);let v=bZ(a,["explicitVadSignal"]);void 0!==b&&null!=v&&bY(b,["setup","explicitVadSignal"],v);let w=bZ(a,["avatarConfig"]);void 0!==b&&null!=w&&bY(b,["setup","avatarConfig"],w);let x=bZ(a,["safetySettings"]);if(void 0!==b&&null!=x){let a=x;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["setup","safetySettings"],a)}if(void 0!==bZ(a,["translationConfig"]))throw Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}(c,a)),A=a}else{let a,b,c;i=this.apiClient,a={},null!=(b=bZ(D,["model"]))&&bY(a,["setup","model"],cu(i,b)),null!=(c=bZ(D,["config"]))&&bY(a,["config"],function(a,b){let c=bZ(a,["generationConfig"]);void 0!==b&&null!=c&&bY(b,["setup","generationConfig"],c);let d=bZ(a,["responseModalities"]);void 0!==b&&null!=d&&bY(b,["setup","generationConfig","responseModalities"],d);let e=bZ(a,["temperature"]);void 0!==b&&null!=e&&bY(b,["setup","generationConfig","temperature"],e);let f=bZ(a,["topP"]);void 0!==b&&null!=f&&bY(b,["setup","generationConfig","topP"],f);let g=bZ(a,["topK"]);void 0!==b&&null!=g&&bY(b,["setup","generationConfig","topK"],g);let h=bZ(a,["maxOutputTokens"]);void 0!==b&&null!=h&&bY(b,["setup","generationConfig","maxOutputTokens"],h);let i=bZ(a,["mediaResolution"]);void 0!==b&&null!=i&&bY(b,["setup","generationConfig","mediaResolution"],i);let j=bZ(a,["seed"]);void 0!==b&&null!=j&&bY(b,["setup","generationConfig","seed"],j);let k=bZ(a,["speechConfig"]);void 0!==b&&null!=k&&bY(b,["setup","generationConfig","speechConfig"],cK(k));let l=bZ(a,["thinkingConfig"]);void 0!==b&&null!=l&&bY(b,["setup","generationConfig","thinkingConfig"],l);let m=bZ(a,["enableAffectiveDialog"]);void 0!==b&&null!=m&&bY(b,["setup","generationConfig","enableAffectiveDialog"],m);let n=bZ(a,["systemInstruction"]);void 0!==b&&null!=n&&bY(b,["setup","systemInstruction"],function(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return c={},null!=(d=bZ(b=a,["mediaResolution"]))&&bY(c,["mediaResolution"],d),null!=(e=bZ(b,["toolCall"]))&&bY(c,["toolCall"],e),null!=(f=bZ(b,["toolResponse"]))&&bY(c,["toolResponse"],f),null!=(g=bZ(b,["audioTranscription"]))&&bY(c,["audioTranscription"],g),null!=(h=bZ(b,["codeExecutionResult"]))&&bY(c,["codeExecutionResult"],h),null!=(i=bZ(b,["executableCode"]))&&bY(c,["executableCode"],i),null!=(j=bZ(b,["fileData"]))&&bY(c,["fileData"],function(a){let b={};if(void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["fileUri"]);null!=c&&bY(b,["fileUri"],c);let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(j)),null!=(k=bZ(b,["functionCall"]))&&bY(c,["functionCall"],function(a){let b={},c=bZ(a,["args"]);null!=c&&bY(b,["args"],c);let d=bZ(a,["id"]);null!=d&&bY(b,["id"],d);let e=bZ(a,["name"]);if(null!=e&&bY(b,["name"],e),void 0!==bZ(a,["partialArgs"]))throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["willContinue"]))throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(k)),null!=(l=bZ(b,["functionResponse"]))&&bY(c,["functionResponse"],l),null!=(m=bZ(b,["inlineData"]))&&bY(c,["inlineData"],df(m)),null!=(n=bZ(b,["text"]))&&bY(c,["text"],n),null!=(o=bZ(b,["thought"]))&&bY(c,["thought"],o),null!=(p=bZ(b,["thoughtSignature"]))&&bY(c,["thoughtSignature"],p),null!=(q=bZ(b,["videoMetadata"]))&&bY(c,["videoMetadata"],q),null!=(r=bZ(b,["partMetadata"]))&&bY(c,["partMetadata"],r),c})),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}(cF(n)));let o=bZ(a,["tools"]);if(void 0!==b&&null!=o){let a=cM(o);Array.isArray(a)&&(a=a.map(a=>(function(a){let b={};if(void 0!==bZ(a,["retrieval"]))throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["googleMaps"]);null!=c&&bY(b,["googleMaps"],function(a){let b={},c=bZ(a,["authConfig"]);null!=c&&bY(b,["authConfig"],function(a){let b={},c=bZ(a,["apiKey"]);if(null!=c&&bY(b,["apiKey"],c),void 0!==bZ(a,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["authType"]))throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oauthConfig"]))throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oidcConfig"]))throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["enableWidget"]);if(null!=d&&bY(b,["enableWidget"],d),void 0!==bZ(a,["groundingTypes"]))throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["mcpServers"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mcpServers"],a)}let e=bZ(a,["codeExecution"]);null!=e&&bY(b,["codeExecution"],e);let f=bZ(a,["computerUse"]);if(null!=f&&bY(b,["computerUse"],f),void 0!==bZ(a,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["exaAiSearch"]))throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=bZ(a,["functionDeclarations"]);if(null!=g){let a=g;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let h=bZ(a,["googleSearch"]);null!=h&&bY(b,["googleSearch"],function(a){let b={};if(void 0!==bZ(a,["blockingConfidence"]))throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["excludeDomains"]))throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["searchTypes"]);null!=c&&bY(b,["searchTypes"],c);let d=bZ(a,["timeRangeFilter"]);return null!=d&&bY(b,["timeRangeFilter"],d),b}(h));let i=bZ(a,["googleSearchRetrieval"]);if(null!=i&&bY(b,["googleSearchRetrieval"],i),void 0!==bZ(a,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["urlContext"]);null!=j&&bY(b,["urlContext"],j);let k=bZ(a,["fileSearch"]);return null!=k&&bY(b,["fileSearch"],k),b})(cL(a)))),bY(b,["setup","tools"],a)}let p=bZ(a,["sessionResumption"]);void 0!==b&&null!=p&&bY(b,["setup","sessionResumption"],function(a){let b={},c=bZ(a,["handle"]);if(null!=c&&bY(b,["handle"],c),void 0!==bZ(a,["transparent"]))throw Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(p));let q=bZ(a,["inputAudioTranscription"]);void 0!==b&&null!=q&&bY(b,["setup","inputAudioTranscription"],q);let r=bZ(a,["outputAudioTranscription"]);void 0!==b&&null!=r&&bY(b,["setup","outputAudioTranscription"],r);let s=bZ(a,["realtimeInputConfig"]);void 0!==b&&null!=s&&bY(b,["setup","realtimeInputConfig"],s);let t=bZ(a,["contextWindowCompression"]);void 0!==b&&null!=t&&bY(b,["setup","contextWindowCompression"],t);let u=bZ(a,["proactivity"]);if(void 0!==b&&null!=u&&bY(b,["setup","proactivity"],u),void 0!==bZ(a,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let v=bZ(a,["avatarConfig"]);void 0!==b&&null!=v&&bY(b,["setup","avatarConfig"],v);let w=bZ(a,["safetySettings"]);if(void 0!==b&&null!=w){let a=w;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["category"]);if(null!=c&&bY(b,["category"],c),void 0!==bZ(a,["method"]))throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["threshold"]);return null!=d&&bY(b,["threshold"],d),b})(a))),bY(b,["setup","safetySettings"],a)}let x=bZ(a,["translationConfig"]);return void 0!==b&&null!=x&&bY(b,["setup","generationConfig","translationConfig"],x),{}}(c,a)),A=a}delete A.config;let E=new dR(y,this.apiClient);for(let a of(y.send(JSON.stringify(A)),await w,t=!0,u))r.onmessage(a);return E}isCallableTool(a){return"callTool"in a&&"function"==typeof a.callTool}}let dQ={turnComplete:!0};class dR{constructor(a,b){this.conn=a,this.apiClient=b}tLiveClientContent(a,b){if(null!==b.turns&&void 0!==b.turns){let c=[];try{c=cH(b.turns),a.isVertexAI()||(c=c.map(a=>di(a)))}catch(a){throw Error(`Failed to parse client content "turns", type: '${typeof b.turns}'`)}return{clientContent:{turns:c,turnComplete:b.turnComplete}}}return{clientContent:{turnComplete:b.turnComplete}}}tLiveClienttToolResponse(a,b){let c=[];if(null==b.functionResponses||0===(c=Array.isArray(b.functionResponses)?b.functionResponses:[b.functionResponses]).length)throw Error("functionResponses is required.");for(let b of c){if("object"!=typeof b||null===b||!("name"in b)||!("response"in b))throw Error(`Could not parse function response, type '${typeof b}'.`);if(!a.isVertexAI()&&!("id"in b))throw Error("FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.")}return{toolResponse:{functionResponses:c}}}sendClientContent(a){a=Object.assign(Object.assign({},dQ),a);let b=this.tLiveClientContent(this.apiClient,a);this.conn.send(JSON.stringify(b))}sendRealtimeInput(a){let b={};b=this.apiClient.isVertexAI()?{realtimeInput:function(a){let b={},c=bZ(a,["media"]);if(null!=c){let a=cw(c);Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mediaChunks"],a)}let d=bZ(a,["audio"]);null!=d&&bY(b,["audio"],cz(d));let e=bZ(a,["audioStreamEnd"]);null!=e&&bY(b,["audioStreamEnd"],e);let f=bZ(a,["video"]);null!=f&&bY(b,["video"],cy(f));let g=bZ(a,["text"]);null!=g&&bY(b,["text"],g);let h=bZ(a,["activityStart"]);null!=h&&bY(b,["activityStart"],h);let i=bZ(a,["activityEnd"]);return null!=i&&bY(b,["activityEnd"],i),b}(a)}:{realtimeInput:function(a){let b={},c=bZ(a,["media"]);if(null!=c){let a=cw(c);Array.isArray(a)&&(a=a.map(a=>df(a))),bY(b,["mediaChunks"],a)}let d=bZ(a,["audio"]);null!=d&&bY(b,["audio"],df(cz(d)));let e=bZ(a,["audioStreamEnd"]);null!=e&&bY(b,["audioStreamEnd"],e);let f=bZ(a,["video"]);null!=f&&bY(b,["video"],df(cy(f)));let g=bZ(a,["text"]);null!=g&&bY(b,["text"],g);let h=bZ(a,["activityStart"]);null!=h&&bY(b,["activityStart"],h);let i=bZ(a,["activityEnd"]);return null!=i&&bY(b,["activityEnd"],i),b}(a)},this.conn.send(JSON.stringify(b))}sendToolResponse(a){if(null==a.functionResponses)throw Error("Tool response parameters are required.");let b=this.tLiveClienttToolResponse(this.apiClient,a);this.conn.send(JSON.stringify(b))}close(){this.conn.close()}}function dS(a){var b,c,d;if(null==(b=null==a?void 0:a.automaticFunctionCalling)?void 0:b.disable)return!0;let e=!1;for(let b of null!=(c=null==a?void 0:a.tools)?c:[])if(dT(b)){e=!0;break}if(!e)return!0;let f=null==(d=null==a?void 0:a.automaticFunctionCalling)?void 0:d.maximumRemoteCalls;return(!(!f||!(f<0)&&Number.isInteger(f))||0==f)&&(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",f),!0)}function dT(a){return"callTool"in a&&"function"==typeof a.callTool}function dU(a){var b;let c=[];return(null==(b=null==a?void 0:a.config)?void 0:b.tools)&&a.config.tools.forEach((a,b)=>{dT(a)||a.functionDeclarations&&a.functionDeclarations.length>0&&c.push(b)}),c}function dV(a){var b;return!(null==(b=null==a?void 0:a.automaticFunctionCalling)?void 0:b.ignoreCallHistory)}class dW extends bW{constructor(a){super(),this.apiClient=a,this.embedContent=async a=>{if(!this.apiClient.isVertexAI())return a.model.includes("gemini-embedding-2")&&(a.contents=cH(a.contents)),await this.embedContentInternal(a);if(a.model.includes("gemini")&&"gemini-embedding-001"!==a.model||a.model.includes("maas")){let b=cH(a.contents);if(b.length>1)throw Error("The embedContent API for this model only supports one content at a time.");let c=Object.assign(Object.assign({},a),{content:b[0],embeddingApiType:bn.EMBED_CONTENT});return await this.embedContentInternal(c)}{let b=Object.assign(Object.assign({},a),{embeddingApiType:bn.PREDICT});return await this.embedContentInternal(b)}},this.generateContent=async a=>{var b,c,d,e,f,g,h,i;let j,k,l=await this.processParamsMaybeAddMcpUsage(a);if(this.maybeMoveToResponseJsonSchema(a),!(null!=(i=null==(h=null==(g=a.config)?void 0:g.tools)?void 0:h.some(a=>dT(a)))&&i)||dS(a.config))return await this.generateContentInternal(l);let m=dU(a);if(m.length>0){let a=m.map(a=>`tools[${a}]`).join(", ");throw Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${a}.`)}let n=cH(l.contents),o=null!=(d=null==(c=null==(b=l.config)?void 0:b.automaticFunctionCalling)?void 0:c.maximumRemoteCalls)?d:10,p=0;for(;p<o&&(j=await this.generateContentInternal(l)).functionCalls&&0!==j.functionCalls.length;){let b=j.candidates[0].content,c=[];for(let b of null!=(f=null==(e=a.config)?void 0:e.tools)?f:[])if(dT(b)){let a=await b.callTool(j.functionCalls);c.push(...a)}p++,k={role:"user",parts:c},l.contents=cH(l.contents),l.contents.push(b),l.contents.push(k),dV(l.config)&&(n.push(b),n.push(k))}return dV(l.config)&&(j.automaticFunctionCallingHistory=n),j},this.generateContentStream=async a=>{var b,c,d,e,f;if(this.maybeMoveToResponseJsonSchema(a),dS(a.config)){let b=await this.processParamsMaybeAddMcpUsage(a);return await this.generateContentStreamInternal(b)}let g=dU(a);if(g.length>0){let a=g.map(a=>`tools[${a}]`).join(", ");throw Error(`Incompatible tools found at ${a}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let h=null==(d=null==(c=null==(b=null==a?void 0:a.config)?void 0:b.toolConfig)?void 0:c.functionCallingConfig)?void 0:d.streamFunctionCallArguments,i=null==(f=null==(e=null==a?void 0:a.config)?void 0:e.automaticFunctionCalling)?void 0:f.disable;if(h&&!i)throw Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(a)},this.generateImages=async a=>(dW.loggedGenerateImagesWarning||(dW.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(a).then(a=>{var b;let c,d=[];if(null==a?void 0:a.generatedImages)for(let e of a.generatedImages)e&&(null==e?void 0:e.safetyAttributes)&&(null==(b=null==e?void 0:e.safetyAttributes)?void 0:b.contentType)==="Positive Prompt"?c=null==e?void 0:e.safetyAttributes:d.push(e);return c?{generatedImages:d,positivePromptSafetyAttributes:c,sdkHttpResponse:a.sdkHttpResponse}:{generatedImages:d,sdkHttpResponse:a.sdkHttpResponse}})),this.list=async a=>{var b;let c={config:Object.assign(Object.assign({},{queryBase:!0}),null==a?void 0:a.config)};if(this.apiClient.isVertexAI()&&!c.config.queryBase)if(null==(b=c.config)?void 0:b.filter)throw Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");else c.config.filter="labels.tune-type:*";return new c0(bM.PAGED_ITEM_MODELS,a=>this.listInternal(a),await this.listInternal(c),c)},this.editImage=async a=>{dW.loggedEditImageWarning||(dW.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let b={model:a.model,prompt:a.prompt,referenceImages:[],config:a.config};return a.referenceImages&&a.referenceImages&&(b.referenceImages=a.referenceImages.map(a=>a.toReferenceImageAPI())),await this.editImageInternal(b)},this.upscaleImage=async a=>{let b={numberOfImages:1,mode:"upscale"};a.config&&(b=Object.assign(Object.assign({},b),a.config));let c={model:a.model,image:a.image,upscaleFactor:a.upscaleFactor,config:b};return await this.upscaleImageInternal(c)},this.generateVideos=async a=>{var b,c,d,e,f,g;if((a.prompt||a.image||a.video)&&a.source)throw Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(a.prompt||a.image||a.video)&&!dW.loggedGenerateVideosWarning&&(dW.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead.")),!this.apiClient.isVertexAI()&&((null==(b=a.video)?void 0:b.uri)&&(null==(c=a.video)?void 0:c.videoBytes)?a.video={uri:a.video.uri,mimeType:a.video.mimeType}:(null==(e=null==(d=a.source)?void 0:d.video)?void 0:e.uri)&&(null==(g=null==(f=a.source)?void 0:f.video)?void 0:g.videoBytes)&&(a.source.video={uri:a.source.video.uri,mimeType:a.source.video.mimeType})),await this.generateVideosInternal(a)}}maybeMoveToResponseJsonSchema(a){a.config&&a.config.responseSchema&&!a.config.responseJsonSchema&&Object.keys(a.config.responseSchema).includes("$schema")&&(a.config.responseJsonSchema=a.config.responseSchema,delete a.config.responseSchema)}async processParamsMaybeAddMcpUsage(a){var b,c,d;let e=null==(b=a.config)?void 0:b.tools;if(!e)return a;let f=await Promise.all(e.map(async a=>dT(a)?await a.tool():a)),g={model:a.model,contents:a.contents,config:Object.assign(Object.assign({},a.config),{tools:f})};if(g.config.tools=f,a.config&&a.config.tools&&dI(a.config.tools)){let b=Object.assign({},null!=(d=null==(c=a.config.httpOptions)?void 0:c.headers)?d:{});0===Object.keys(b).length&&(b=this.apiClient.getDefaultHeaders()),dJ(b),g.config.httpOptions=Object.assign(Object.assign({},a.config.httpOptions),{headers:b})}return g}async initAfcToolsMap(a){var b,c,d;let e=new Map;for(let f of null!=(c=null==(b=a.config)?void 0:b.tools)?c:[])if(dT(f))for(let a of null!=(d=(await f.tool()).functionDeclarations)?d:[]){if(!a.name)throw Error("Function declaration name is required.");if(e.has(a.name))throw Error(`Duplicate tool declaration name: ${a.name}`);e.set(a.name,f)}return e}async processAfcStream(a){var b,c,d;let e=null!=(d=null==(c=null==(b=a.config)?void 0:b.automaticFunctionCalling)?void 0:c.maximumRemoteCalls)?d:10,f=!1,g=0;return function(a,b,c){return c7(this,arguments,function*(){for(;g<e;){f&&(g++,f=!1);let p=yield c6(a.processParamsMaybeAddMcpUsage(c)),q=yield c6(a.generateContentStreamInternal(p)),r=[],s=[];try{for(var d,h,i,j,k,l,m,n=!0,o=(h=void 0,c8(q));!(d=(m=yield c6(o.next())).done);n=!0)if(j=m.value,n=!1,yield yield c6(j),j.candidates&&(null==(k=j.candidates[0])?void 0:k.content)){for(let a of(s.push(j.candidates[0].content),null!=(l=j.candidates[0].content.parts)?l:[]))if(g<e&&a.functionCall){if(!a.functionCall.name)throw Error("Function call name was not returned by the model.");if(b.has(a.functionCall.name)){let c=yield c6(b.get(a.functionCall.name).callTool([a.functionCall]));r.push(...c)}else throw Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${b.keys()}, missing tool: ${a.functionCall.name}`)}}}catch(a){h={error:a}}finally{try{!n&&!d&&(i=o.return)&&(yield c6(i.call(o)))}finally{if(h)throw h.error}}if(r.length>0){f=!0;let a=new b1;a.candidates=[{content:{role:"user",parts:r}}],yield yield c6(a);let b=[];b.push(...s),b.push({role:"user",parts:r});let d=cH(c.contents).concat(b);c.contents=d}else break}})}(this,await this.initAfcToolsMap(a),a)}async generateContentInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d=dl(this.apiClient,a);return f=bX("{model}:generateContent",d._url),g=d._query,delete d._url,delete d._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(d),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=dn(a),c=new b1;return Object.assign(c,b),c})}{let b=dk(this.apiClient,a);return f=bX("{model}:generateContent",b._url),g=b._query,delete b._url,delete b._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=dm(a),c=new b1;return Object.assign(c,b),c})}}async generateContentStreamInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d=dl(this.apiClient,a);return f=bX("{model}:streamGenerateContent?alt=sse",d._url),g=d._query,delete d._url,delete d._query,this.apiClient.requestStream({path:f,queryParams:g,body:JSON.stringify(d),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(function(b){return c7(this,arguments,function*(){var c,d,e,f;try{for(var g,h=!0,i=c8(b);!(c=(g=yield c6(i.next())).done);h=!0){f=g.value,h=!1;let b=dn((yield c6(f.json())),a);b.sdkHttpResponse={headers:f.headers};let c=new b1;Object.assign(c,b),yield yield c6(c)}}catch(a){d={error:a}}finally{try{!h&&!c&&(e=i.return)&&(yield c6(e.call(i)))}finally{if(d)throw d.error}}})})}{let b=dk(this.apiClient,a);return f=bX("{model}:streamGenerateContent?alt=sse",b._url),g=b._query,delete b._url,delete b._query,this.apiClient.requestStream({path:f,queryParams:g,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(function(b){return c7(this,arguments,function*(){var c,d,e,f;try{for(var g,h=!0,i=c8(b);!(c=(g=yield c6(i.next())).done);h=!0){f=g.value,h=!1;let b=dm((yield c6(f.json())),a);b.sdkHttpResponse={headers:f.headers};let c=new b1;Object.assign(c,b),yield yield c6(c)}}catch(a){d={error:a}}finally{try{!h&&!c&&(e=i.return)&&(yield c6(e.call(i)))}finally{if(d)throw d.error}}})})}}async embedContentInternal(a){var b,c,d,e,f;let g="",h={};if(this.apiClient.isVertexAI()){let d=function(a,b,c){let d={},e=bZ(b,["model"]);null!=e&&bY(d,["_url","model"],cu(a,e));let f=bZ(c,["embeddingApiType"]);if(void 0===f&&(f="PREDICT"),"PREDICT"===f){let c=bZ(b,["contents"]);if(null!=c){let b=cG(a,c);Array.isArray(b)&&(b=b.map(a=>a)),bY(d,["instances[]","content"],b)}}let g=bZ(c,["embeddingApiType"]);if(void 0===g&&(g="PREDICT"),"EMBED_CONTENT"===g){let a=bZ(b,["content"]);null!=a&&bY(d,["content"],dj(cF(a)))}let h=bZ(b,["config"]);return null!=h&&function(a,b,c){let d=bZ(c,["embeddingApiType"]);if(void 0===d&&(d="PREDICT"),"PREDICT"===d){let c=bZ(a,["taskType"]);void 0!==b&&null!=c&&bY(b,["instances[]","task_type"],c)}else if("EMBED_CONTENT"===d){let c=bZ(a,["taskType"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","taskType"],c)}let e=bZ(c,["embeddingApiType"]);if(void 0===e&&(e="PREDICT"),"PREDICT"===e){let c=bZ(a,["title"]);void 0!==b&&null!=c&&bY(b,["instances[]","title"],c)}else if("EMBED_CONTENT"===e){let c=bZ(a,["title"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","title"],c)}let f=bZ(c,["embeddingApiType"]);if(void 0===f&&(f="PREDICT"),"PREDICT"===f){let c=bZ(a,["outputDimensionality"]);void 0!==b&&null!=c&&bY(b,["parameters","outputDimensionality"],c)}else if("EMBED_CONTENT"===f){let c=bZ(a,["outputDimensionality"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","outputDimensionality"],c)}let g=bZ(c,["embeddingApiType"]);if(void 0===g&&(g="PREDICT"),"PREDICT"===g){let c=bZ(a,["mimeType"]);void 0!==b&&null!=c&&bY(b,["instances[]","mimeType"],c)}let h=bZ(c,["embeddingApiType"]);if(void 0===h&&(h="PREDICT"),"PREDICT"===h){let c=bZ(a,["autoTruncate"]);void 0!==b&&null!=c&&bY(b,["parameters","autoTruncate"],c)}else if("EMBED_CONTENT"===h){let c=bZ(a,["autoTruncate"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","autoTruncate"],c)}let i=bZ(c,["embeddingApiType"]);if(void 0===i&&(i="PREDICT"),"EMBED_CONTENT"===i){let c=bZ(a,["documentOcr"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","documentOcr"],c)}let j=bZ(c,["embeddingApiType"]);if(void 0===j&&(j="PREDICT"),"EMBED_CONTENT"===j){let c=bZ(a,["audioTrackExtraction"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","audioTrackExtraction"],c)}}(h,d,c),d}(this.apiClient,a,a);return g=bX((f=a.model).includes("gemini")&&"gemini-embedding-001"!==f||f.includes("maas")?"{model}:embedContent":"{model}:predict",d._url),h=d._query,delete d._url,delete d._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(b=>{let c=function(a,b){let c={},d=bZ(a,["sdkHttpResponse"]);null!=d&&bY(c,["sdkHttpResponse"],d);let e=bZ(a,["predictions[]","embeddings"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>{let b,c,d;return b={},null!=(c=bZ(a,["values"]))&&bY(b,["values"],c),null!=(d=bZ(a,["statistics"]))&&bY(b,["statistics"],function(a){let b={},c=bZ(a,["truncated"]);null!=c&&bY(b,["truncated"],c);let d=bZ(a,["token_count"]);null!=d&&bY(b,["tokenCount"],d);let e=bZ(a,["tokensDetails"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["tokensDetails"],a)}return b}(d)),b})),bY(c,["embeddings"],a)}let f=bZ(a,["metadata"]);if(null!=f&&bY(c,["metadata"],f),b&&"EMBED_CONTENT"===bZ(b,["embeddingApiType"])){let b=bZ(a,["embedding"]),d=bZ(a,["usageMetadata"]),e=bZ(a,["truncated"]);if(b){let a={};d&&d.promptTokenCount&&(a.tokenCount=d.promptTokenCount),d&&d.promptTokensDetails&&(a.tokensDetails=d.promptTokensDetails),e&&(a.truncated=e),b.statistics=a,bY(c,["embeddings"],[b])}}return c}(b,a),d=new b2;return Object.assign(d,c),d})}{let b=function(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["_url","model"],cu(a,d));let e=bZ(b,["contents"]);if(null!=e){let b=cG(a,e);Array.isArray(b)&&(b=b.map(a=>a)),bY(c,["requests[]","content"],b)}let f=bZ(b,["content"]);null!=f&&di(cF(f));let g=bZ(b,["config"]);null!=g&&function(a,b){let c=bZ(a,["taskType"]);void 0!==b&&null!=c&&bY(b,["requests[]","taskType"],c);let d=bZ(a,["title"]);void 0!==b&&null!=d&&bY(b,["requests[]","title"],d);let e=bZ(a,["outputDimensionality"]);if(void 0!==b&&null!=e&&bY(b,["requests[]","outputDimensionality"],e),void 0!==bZ(a,["mimeType"]))throw Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["autoTruncate"]))throw Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["documentOcr"]))throw Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["audioTrackExtraction"]))throw Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(g,c);let h=bZ(b,["model"]);return void 0!==h&&bY(c,["requests[]","model"],cu(a,h)),c}(this.apiClient,a);return g=bX("{model}:batchEmbedContents",b._url),h=b._query,delete b._url,delete b._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["embeddings"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["embeddings"],a)}let e=bZ(a,["metadata"]);return null!=e&&bY(b,["metadata"],e),b}(a),c=new b2;return Object.assign(c,b),c})}}async generateImagesInternal(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["_url","model"],cu(f,e)),null!=(g=bZ(a,["prompt"]))&&bY(d,["instances[0]","prompt"],g),null!=(j=bZ(a,["config"]))&&(k=bZ(j,["outputGcsUri"]),void 0!==d&&null!=k&&bY(d,["parameters","storageUri"],k),l=bZ(j,["negativePrompt"]),void 0!==d&&null!=l&&bY(d,["parameters","negativePrompt"],l),m=bZ(j,["numberOfImages"]),void 0!==d&&null!=m&&bY(d,["parameters","sampleCount"],m),n=bZ(j,["aspectRatio"]),void 0!==d&&null!=n&&bY(d,["parameters","aspectRatio"],n),o=bZ(j,["guidanceScale"]),void 0!==d&&null!=o&&bY(d,["parameters","guidanceScale"],o),p=bZ(j,["seed"]),void 0!==d&&null!=p&&bY(d,["parameters","seed"],p),q=bZ(j,["safetyFilterLevel"]),void 0!==d&&null!=q&&bY(d,["parameters","safetySetting"],q),r=bZ(j,["personGeneration"]),void 0!==d&&null!=r&&bY(d,["parameters","personGeneration"],r),s=bZ(j,["includeSafetyAttributes"]),void 0!==d&&null!=s&&bY(d,["parameters","includeSafetyAttributes"],s),t=bZ(j,["includeRaiReason"]),void 0!==d&&null!=t&&bY(d,["parameters","includeRaiReason"],t),u=bZ(j,["language"]),void 0!==d&&null!=u&&bY(d,["parameters","language"],u),v=bZ(j,["outputMimeType"]),void 0!==d&&null!=v&&bY(d,["parameters","outputOptions","mimeType"],v),w=bZ(j,["outputCompressionQuality"]),void 0!==d&&null!=w&&bY(d,["parameters","outputOptions","compressionQuality"],w),x=bZ(j,["addWatermark"]),void 0!==d&&null!=x&&bY(d,["parameters","addWatermark"],x),y=bZ(j,["labels"]),void 0!==d&&null!=y&&bY(d,["labels"],y),z=bZ(j,["imageSize"]),void 0!==d&&null!=z&&bY(d,["parameters","sampleImageSize"],z),A=bZ(j,["enhancePrompt"]),void 0!==d&&null!=A&&bY(d,["parameters","enhancePrompt"],A)),d);return h=bX("{model}:predict",B._url),i=B._query,delete B._url,delete B._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(B),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["predictions"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>dp(a))),bY(b,["generatedImages"],a)}let e=bZ(a,["positivePromptSafetyAttributes"]);return null!=e&&bY(b,["positivePromptSafetyAttributes"],dw(e)),b}(a),c=new b3;return Object.assign(c,b),c})}{let b,c,f,j,k=(g=this.apiClient,b={},null!=(c=bZ(a,["model"]))&&bY(b,["_url","model"],cu(g,c)),null!=(f=bZ(a,["prompt"]))&&bY(b,["instances[0]","prompt"],f),null!=(j=bZ(a,["config"]))&&function(a,b){if(void 0!==bZ(a,["outputGcsUri"]))throw Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["negativePrompt"]))throw Error("negativePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["numberOfImages"]);void 0!==b&&null!=c&&bY(b,["parameters","sampleCount"],c);let d=bZ(a,["aspectRatio"]);void 0!==b&&null!=d&&bY(b,["parameters","aspectRatio"],d);let e=bZ(a,["guidanceScale"]);if(void 0!==b&&null!=e&&bY(b,["parameters","guidanceScale"],e),void 0!==bZ(a,["seed"]))throw Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let f=bZ(a,["safetyFilterLevel"]);void 0!==b&&null!=f&&bY(b,["parameters","safetySetting"],f);let g=bZ(a,["personGeneration"]);void 0!==b&&null!=g&&bY(b,["parameters","personGeneration"],g);let h=bZ(a,["includeSafetyAttributes"]);void 0!==b&&null!=h&&bY(b,["parameters","includeSafetyAttributes"],h);let i=bZ(a,["includeRaiReason"]);void 0!==b&&null!=i&&bY(b,["parameters","includeRaiReason"],i);let j=bZ(a,["language"]);void 0!==b&&null!=j&&bY(b,["parameters","language"],j);let k=bZ(a,["outputMimeType"]);void 0!==b&&null!=k&&bY(b,["parameters","outputOptions","mimeType"],k);let l=bZ(a,["outputCompressionQuality"]);if(void 0!==b&&null!=l&&bY(b,["parameters","outputOptions","compressionQuality"],l),void 0!==bZ(a,["addWatermark"]))throw Error("addWatermark parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["labels"]))throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let m=bZ(a,["imageSize"]);if(void 0!==b&&null!=m&&bY(b,["parameters","sampleImageSize"],m),void 0!==bZ(a,["enhancePrompt"]))throw Error("enhancePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(j,b),b);return h=bX("{model}:predict",k._url),i=k._query,delete k._url,delete k._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(k),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["predictions"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>{var b,c;let d,e,f,g,h,i,j;return d={},null!=(e=bZ(b=a,["_self"]))&&bY(d,["image"],(f={},null!=(g=bZ(c=e,["bytesBase64Encoded"]))&&bY(f,["imageBytes"],b$(g)),null!=(h=bZ(c,["mimeType"]))&&bY(f,["mimeType"],h),f)),null!=(i=bZ(b,["raiFilteredReason"]))&&bY(d,["raiFilteredReason"],i),null!=(j=bZ(b,["_self"]))&&bY(d,["safetyAttributes"],dv(j)),d})),bY(b,["generatedImages"],a)}let e=bZ(a,["positivePromptSafetyAttributes"]);return null!=e&&bY(b,["positivePromptSafetyAttributes"],dv(e)),b}(a),c=new b3;return Object.assign(c,b),c})}}async editImageInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f=function(a,b){let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t={},u=bZ(b,["model"]);null!=u&&bY(t,["_url","model"],cu(a,u));let v=bZ(b,["prompt"]);null!=v&&bY(t,["instances[0]","prompt"],v);let w=bZ(b,["referenceImages"]);if(null!=w){let a=w;Array.isArray(a)&&(a=a.map(a=>(function(a){let b,c,d,e,f,g,h,i={},j=bZ(a,["referenceImage"]);null!=j&&bY(i,["referenceImage"],ds(j));let k=bZ(a,["referenceId"]);null!=k&&bY(i,["referenceId"],k);let l=bZ(a,["referenceType"]);null!=l&&bY(i,["referenceType"],l);let m=bZ(a,["maskImageConfig"]);null!=m&&bY(i,["maskImageConfig"],(b={},null!=(c=bZ(m,["maskMode"]))&&bY(b,["maskMode"],c),null!=(d=bZ(m,["segmentationClasses"]))&&bY(b,["maskClasses"],d),null!=(e=bZ(m,["maskDilation"]))&&bY(b,["dilation"],e),b));let n=bZ(a,["controlImageConfig"]);null!=n&&bY(i,["controlImageConfig"],(f={},null!=(g=bZ(n,["controlType"]))&&bY(f,["controlType"],g),null!=(h=bZ(n,["enableControlImageComputation"]))&&bY(f,["computeControl"],h),f));let o=bZ(a,["styleImageConfig"]);null!=o&&bY(i,["styleImageConfig"],o);let p=bZ(a,["subjectImageConfig"]);return null!=p&&bY(i,["subjectImageConfig"],p),i})(a))),bY(t,["instances[0]","referenceImages"],a)}let x=bZ(b,["config"]);return null!=x&&(c=bZ(x,["outputGcsUri"]),void 0!==t&&null!=c&&bY(t,["parameters","storageUri"],c),d=bZ(x,["negativePrompt"]),void 0!==t&&null!=d&&bY(t,["parameters","negativePrompt"],d),e=bZ(x,["numberOfImages"]),void 0!==t&&null!=e&&bY(t,["parameters","sampleCount"],e),f=bZ(x,["aspectRatio"]),void 0!==t&&null!=f&&bY(t,["parameters","aspectRatio"],f),g=bZ(x,["guidanceScale"]),void 0!==t&&null!=g&&bY(t,["parameters","guidanceScale"],g),h=bZ(x,["seed"]),void 0!==t&&null!=h&&bY(t,["parameters","seed"],h),i=bZ(x,["safetyFilterLevel"]),void 0!==t&&null!=i&&bY(t,["parameters","safetySetting"],i),j=bZ(x,["personGeneration"]),void 0!==t&&null!=j&&bY(t,["parameters","personGeneration"],j),k=bZ(x,["includeSafetyAttributes"]),void 0!==t&&null!=k&&bY(t,["parameters","includeSafetyAttributes"],k),l=bZ(x,["includeRaiReason"]),void 0!==t&&null!=l&&bY(t,["parameters","includeRaiReason"],l),m=bZ(x,["language"]),void 0!==t&&null!=m&&bY(t,["parameters","language"],m),n=bZ(x,["outputMimeType"]),void 0!==t&&null!=n&&bY(t,["parameters","outputOptions","mimeType"],n),o=bZ(x,["outputCompressionQuality"]),void 0!==t&&null!=o&&bY(t,["parameters","outputOptions","compressionQuality"],o),p=bZ(x,["addWatermark"]),void 0!==t&&null!=p&&bY(t,["parameters","addWatermark"],p),q=bZ(x,["labels"]),void 0!==t&&null!=q&&bY(t,["labels"],q),r=bZ(x,["editMode"]),void 0!==t&&null!=r&&bY(t,["parameters","editMode"],r),s=bZ(x,["baseSteps"]),void 0!==t&&null!=s&&bY(t,["parameters","editConfig","baseSteps"],s)),t}(this.apiClient,a);return d=bX("{model}:predict",f._url),e=f._query,delete f._url,delete f._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(f),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["predictions"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>dp(a))),bY(b,["generatedImages"],a)}return b}(a),c=new b4;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(a){var b,c,d;let e="",f={};if(this.apiClient.isVertexAI()){let g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w=(d=this.apiClient,g={},null!=(h=bZ(a,["model"]))&&bY(g,["_url","model"],cu(d,h)),null!=(i=bZ(a,["image"]))&&bY(g,["instances[0]","image"],ds(i)),null!=(j=bZ(a,["upscaleFactor"]))&&bY(g,["parameters","upscaleConfig","upscaleFactor"],j),null!=(k=bZ(a,["config"]))&&(l=bZ(k,["outputGcsUri"]),void 0!==g&&null!=l&&bY(g,["parameters","storageUri"],l),m=bZ(k,["safetyFilterLevel"]),void 0!==g&&null!=m&&bY(g,["parameters","safetySetting"],m),n=bZ(k,["personGeneration"]),void 0!==g&&null!=n&&bY(g,["parameters","personGeneration"],n),o=bZ(k,["includeRaiReason"]),void 0!==g&&null!=o&&bY(g,["parameters","includeRaiReason"],o),p=bZ(k,["outputMimeType"]),void 0!==g&&null!=p&&bY(g,["parameters","outputOptions","mimeType"],p),q=bZ(k,["outputCompressionQuality"]),void 0!==g&&null!=q&&bY(g,["parameters","outputOptions","compressionQuality"],q),r=bZ(k,["enhanceInputImage"]),void 0!==g&&null!=r&&bY(g,["parameters","upscaleConfig","enhanceInputImage"],r),s=bZ(k,["imagePreservationFactor"]),void 0!==g&&null!=s&&bY(g,["parameters","upscaleConfig","imagePreservationFactor"],s),t=bZ(k,["labels"]),void 0!==g&&null!=t&&bY(g,["labels"],t),u=bZ(k,["numberOfImages"]),void 0!==g&&null!=u&&bY(g,["parameters","sampleCount"],u),v=bZ(k,["mode"]),void 0!==g&&null!=v&&bY(g,["parameters","mode"],v)),g);return e=bX("{model}:predict",w._url),f=w._query,delete w._url,delete w._query,this.apiClient.request({path:e,queryParams:f,body:JSON.stringify(w),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["predictions"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>dp(a))),bY(b,["generatedImages"],a)}return b}(a),c=new b5;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(a){var b,c,d;let e="",f={};if(this.apiClient.isVertexAI()){let g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v=(d=this.apiClient,g={},null!=(h=bZ(a,["model"]))&&bY(g,["_url","model"],cu(d,h)),null!=(i=bZ(a,["source"]))&&function(a,b){let c=bZ(a,["prompt"]);void 0!==b&&null!=c&&bY(b,["instances[0]","prompt"],c);let d=bZ(a,["personImage"]);void 0!==b&&null!=d&&bY(b,["instances[0]","personImage","image"],ds(d));let e=bZ(a,["productImages"]);if(void 0!==b&&null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>{let b,c;return b={},null!=(c=bZ(a,["productImage"]))&&bY(b,["image"],ds(c)),b})),bY(b,["instances[0]","productImages"],a)}}(i,g),null!=(j=bZ(a,["config"]))&&(k=bZ(j,["numberOfImages"]),void 0!==g&&null!=k&&bY(g,["parameters","sampleCount"],k),l=bZ(j,["baseSteps"]),void 0!==g&&null!=l&&bY(g,["parameters","baseSteps"],l),m=bZ(j,["outputGcsUri"]),void 0!==g&&null!=m&&bY(g,["parameters","storageUri"],m),n=bZ(j,["seed"]),void 0!==g&&null!=n&&bY(g,["parameters","seed"],n),o=bZ(j,["safetyFilterLevel"]),void 0!==g&&null!=o&&bY(g,["parameters","safetySetting"],o),p=bZ(j,["personGeneration"]),void 0!==g&&null!=p&&bY(g,["parameters","personGeneration"],p),q=bZ(j,["addWatermark"]),void 0!==g&&null!=q&&bY(g,["parameters","addWatermark"],q),r=bZ(j,["outputMimeType"]),void 0!==g&&null!=r&&bY(g,["parameters","outputOptions","mimeType"],r),s=bZ(j,["outputCompressionQuality"]),void 0!==g&&null!=s&&bY(g,["parameters","outputOptions","compressionQuality"],s),t=bZ(j,["enhancePrompt"]),void 0!==g&&null!=t&&bY(g,["parameters","enhancePrompt"],t),u=bZ(j,["labels"]),void 0!==g&&null!=u&&bY(g,["labels"],u)),g);return e=bX("{model}:predict",v._url),f=v._query,delete v._url,delete v._query,this.apiClient.request({path:e,queryParams:f,body:JSON.stringify(v),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b=function(a){let b={},c=bZ(a,["predictions"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>dp(a))),bY(b,["generatedImages"],a)}return b}(a),c=new b6;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(a){var b,c,d,e,f;let g="",h={};if(this.apiClient.isVertexAI()){let i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=(d=this.apiClient,n={},null!=(o=bZ(a,["model"]))&&bY(n,["_url","model"],cu(d,o)),null!=(p=bZ(a,["source"]))&&(e=p,f=n,k=bZ(e,["prompt"]),void 0!==f&&null!=k&&bY(f,["instances[0]","prompt"],k),l=bZ(e,["image"]),void 0!==f&&null!=l&&bY(f,["instances[0]","image"],ds(l)),m=bZ(e,["scribbleImage"]),void 0!==f&&null!=m&&bY(f,["instances[0]","scribble"],(i={},null!=(j=bZ(m,["image"]))&&bY(i,["image"],ds(j)),i))),null!=(q=bZ(a,["config"]))&&(r=bZ(q,["mode"]),void 0!==n&&null!=r&&bY(n,["parameters","mode"],r),s=bZ(q,["maxPredictions"]),void 0!==n&&null!=s&&bY(n,["parameters","maxPredictions"],s),t=bZ(q,["confidenceThreshold"]),void 0!==n&&null!=t&&bY(n,["parameters","confidenceThreshold"],t),u=bZ(q,["maskDilation"]),void 0!==n&&null!=u&&bY(n,["parameters","maskDilation"],u),v=bZ(q,["binaryColorThreshold"]),void 0!==n&&null!=v&&bY(n,["parameters","binaryColorThreshold"],v),w=bZ(q,["labels"]),void 0!==n&&null!=w&&bY(n,["labels"],w)),n);return g=bX("{model}:predict",x._url),h=x._query,delete x._url,delete x._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(x),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b=function(a){let b={},c=bZ(a,["predictions"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["_self"]);null!=c&&bY(b,["mask"],dq(c));let d=bZ(a,["labels"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["labels"],a)}return b})(a))),bY(b,["generatedMasks"],a)}return b}(a),c=new b7;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["_url","name"],cu(f,e)),d);return h=bX("{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>du(a))}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["model"]))&&bY(b,["_url","name"],cu(g,c)),b);return h=bX("{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>dt(a))}}async listInternal(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g,j,k,l,m=(f=this.apiClient,d={},null!=(e=bZ(a,["config"]))&&(g=bZ(e,["pageSize"]),void 0!==d&&null!=g&&bY(d,["_query","pageSize"],g),j=bZ(e,["pageToken"]),void 0!==d&&null!=j&&bY(d,["_query","pageToken"],j),k=bZ(e,["filter"]),void 0!==d&&null!=k&&bY(d,["_query","filter"],k),l=bZ(e,["queryBase"]),void 0!==d&&null!=l&&bY(d,["_url","models_url"],cS(f,l))),d);return h=bX("{models_url}",m._url),i=m._query,delete m._url,delete m._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(m),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["_self"]);if(null!=e){let a=cT(e);Array.isArray(a)&&(a=a.map(a=>du(a))),bY(b,["models"],a)}return b}(a),c=new b8;return Object.assign(c,b),c})}{let b,c,f,j,k,l,m=(g=this.apiClient,b={},null!=(c=bZ(a,["config"]))&&(f=bZ(c,["pageSize"]),void 0!==b&&null!=f&&bY(b,["_query","pageSize"],f),j=bZ(c,["pageToken"]),void 0!==b&&null!=j&&bY(b,["_query","pageToken"],j),k=bZ(c,["filter"]),void 0!==b&&null!=k&&bY(b,["_query","filter"],k),l=bZ(c,["queryBase"]),void 0!==b&&null!=l&&bY(b,["_url","models_url"],cS(g,l))),b);return h=bX("{models_url}",m._url),i=m._query,delete m._url,delete m._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(m),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["_self"]);if(null!=e){let a=cT(e);Array.isArray(a)&&(a=a.map(a=>dt(a))),bY(b,["models"],a)}return b}(a),c=new b8;return Object.assign(c,b),c})}}async update(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g,j,k,l,m=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["_url","model"],cu(f,e)),null!=(g=bZ(a,["config"]))&&(j=bZ(g,["displayName"]),void 0!==d&&null!=j&&bY(d,["displayName"],j),k=bZ(g,["description"]),void 0!==d&&null!=k&&bY(d,["description"],k),l=bZ(g,["defaultCheckpointId"]),void 0!==d&&null!=l&&bY(d,["defaultCheckpointId"],l)),d);return h=bX("{model}",m._url),i=m._query,delete m._url,delete m._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(m),httpMethod:"PATCH",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>du(a))}{let b,c,f,j,k,l,m=(g=this.apiClient,b={},null!=(c=bZ(a,["model"]))&&bY(b,["_url","name"],cu(g,c)),null!=(f=bZ(a,["config"]))&&(j=bZ(f,["displayName"]),void 0!==b&&null!=j&&bY(b,["displayName"],j),k=bZ(f,["description"]),void 0!==b&&null!=k&&bY(b,["description"],k),l=bZ(f,["defaultCheckpointId"]),void 0!==b&&null!=l&&bY(b,["defaultCheckpointId"],l)),b);return h=bX("{name}",m._url),i=m._query,delete m._url,delete m._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(m),httpMethod:"PATCH",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>dt(a))}}async delete(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["_url","name"],cu(f,e)),d);return h=bX("{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new b9;return Object.assign(e,d),e})}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["model"]))&&bY(b,["_url","name"],cu(g,c)),b);return h=bX("{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new b9;return Object.assign(e,d),e})}}async countTokens(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d=function(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["_url","model"],cu(a,d));let e=bZ(b,["contents"]);if(null!=e){let a=cH(e);Array.isArray(a)&&(a=a.map(a=>dj(a))),bY(c,["contents"],a)}let f=bZ(b,["config"]);return null!=f&&function(a,b){let c=bZ(a,["systemInstruction"]);void 0!==b&&null!=c&&bY(b,["systemInstruction"],dj(cF(c)));let d=bZ(a,["tools"]);if(void 0!==b&&null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>dy(a))),bY(b,["tools"],a)}let e=bZ(a,["generationConfig"]);void 0!==b&&null!=e&&bY(b,["generationConfig"],function(a){let b={},c=bZ(a,["modelSelectionConfig"]);null!=c&&bY(b,["modelConfig"],c);let d=bZ(a,["responseJsonSchema"]);null!=d&&bY(b,["responseJsonSchema"],d);let e=bZ(a,["audioTranscriptionConfig"]);null!=e&&bY(b,["audioTranscriptionConfig"],e);let f=bZ(a,["audioTimestamp"]);null!=f&&bY(b,["audioTimestamp"],f);let g=bZ(a,["candidateCount"]);null!=g&&bY(b,["candidateCount"],g);let h=bZ(a,["enableAffectiveDialog"]);null!=h&&bY(b,["enableAffectiveDialog"],h);let i=bZ(a,["frequencyPenalty"]);null!=i&&bY(b,["frequencyPenalty"],i);let j=bZ(a,["logprobs"]);null!=j&&bY(b,["logprobs"],j);let k=bZ(a,["maxOutputTokens"]);null!=k&&bY(b,["maxOutputTokens"],k);let l=bZ(a,["mediaResolution"]);null!=l&&bY(b,["mediaResolution"],l);let m=bZ(a,["presencePenalty"]);null!=m&&bY(b,["presencePenalty"],m);let n=bZ(a,["responseFormat"]);if(null!=n){let a=n;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["responseFormat"],a)}let o=bZ(a,["responseLogprobs"]);null!=o&&bY(b,["responseLogprobs"],o);let p=bZ(a,["responseMimeType"]);null!=p&&bY(b,["responseMimeType"],p);let q=bZ(a,["responseModalities"]);null!=q&&bY(b,["responseModalities"],q);let r=bZ(a,["responseSchema"]);null!=r&&bY(b,["responseSchema"],r);let s=bZ(a,["routingConfig"]);null!=s&&bY(b,["routingConfig"],s);let t=bZ(a,["seed"]);null!=t&&bY(b,["seed"],t);let u=bZ(a,["speechConfig"]);null!=u&&bY(b,["speechConfig"],dx(u));let v=bZ(a,["stopSequences"]);null!=v&&bY(b,["stopSequences"],v);let w=bZ(a,["temperature"]);null!=w&&bY(b,["temperature"],w);let x=bZ(a,["thinkingConfig"]);null!=x&&bY(b,["thinkingConfig"],x);let y=bZ(a,["topK"]);null!=y&&bY(b,["topK"],y);let z=bZ(a,["topP"]);if(null!=z&&bY(b,["topP"],z),void 0!==bZ(a,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["translationConfig"]))throw Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(e))}(f,c),c}(this.apiClient,a);return f=bX("{model}:countTokens",d._url),g=d._query,delete d._url,delete d._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(d),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["totalTokens"]))&&bY(b,["totalTokens"],d),b),f=new ca;return Object.assign(f,e),f})}{let b=function(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["_url","model"],cu(a,d));let e=bZ(b,["contents"]);if(null!=e){let a=cH(e);Array.isArray(a)&&(a=a.map(a=>di(a))),bY(c,["contents"],a)}let f=bZ(b,["config"]);return null!=f&&function(a){if(void 0!==bZ(a,["systemInstruction"]))throw Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["tools"]))throw Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["generationConfig"]))throw Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(f),c}(this.apiClient,a);return f=bX("{model}:countTokens",b._url),g=b._query,delete b._url,delete b._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["totalTokens"]))&&bY(b,["totalTokens"],d),null!=(e=bZ(a,["cachedContentTokenCount"]))&&bY(b,["cachedContentTokenCount"],e),b),g=new ca;return Object.assign(g,f),g})}}async computeTokens(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f=function(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["_url","model"],cu(a,d));let e=bZ(b,["contents"]);if(null!=e){let a=cH(e);Array.isArray(a)&&(a=a.map(a=>dj(a))),bY(c,["contents"],a)}return c}(this.apiClient,a);return d=bX("{model}:computeTokens",f._url),e=f._query,delete f._url,delete f._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(f),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["tokensInfo"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["tokensInfo"],a)}return b}(a),c=new cb;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(a){var b,c,d,e,f,g,h,i,j,k;let l="",m={};if(this.apiClient.isVertexAI()){let d,e,g,j,k,n,o,p,q,r,s=(f=this.apiClient,j={},null!=(k=bZ(a,["model"]))&&bY(j,["_url","model"],cu(f,k)),null!=(n=bZ(a,["prompt"]))&&bY(j,["instances[0]","prompt"],n),null!=(o=bZ(a,["image"]))&&bY(j,["instances[0]","image"],ds(o)),null!=(p=bZ(a,["video"]))&&bY(j,["instances[0]","video"],dA(p)),null!=(q=bZ(a,["source"]))&&(h=q,i=j,d=bZ(h,["prompt"]),void 0!==i&&null!=d&&bY(i,["instances[0]","prompt"],d),e=bZ(h,["image"]),void 0!==i&&null!=e&&bY(i,["instances[0]","image"],ds(e)),g=bZ(h,["video"]),void 0!==i&&null!=g&&bY(i,["instances[0]","video"],dA(g))),null!=(r=bZ(a,["config"]))&&function(a,b){var c;let d,e,f,g=bZ(a,["numberOfVideos"]);void 0!==b&&null!=g&&bY(b,["parameters","sampleCount"],g);let h=bZ(a,["outputGcsUri"]);void 0!==b&&null!=h&&bY(b,["parameters","storageUri"],h);let i=bZ(a,["fps"]);void 0!==b&&null!=i&&bY(b,["parameters","fps"],i);let j=bZ(a,["durationSeconds"]);void 0!==b&&null!=j&&bY(b,["parameters","durationSeconds"],j);let k=bZ(a,["seed"]);void 0!==b&&null!=k&&bY(b,["parameters","seed"],k);let l=bZ(a,["aspectRatio"]);void 0!==b&&null!=l&&bY(b,["parameters","aspectRatio"],l);let m=bZ(a,["resolution"]);void 0!==b&&null!=m&&bY(b,["parameters","resolution"],m);let n=bZ(a,["personGeneration"]);void 0!==b&&null!=n&&bY(b,["parameters","personGeneration"],n);let o=bZ(a,["pubsubTopic"]);void 0!==b&&null!=o&&bY(b,["parameters","pubsubTopic"],o);let p=bZ(a,["negativePrompt"]);void 0!==b&&null!=p&&bY(b,["parameters","negativePrompt"],p);let q=bZ(a,["enhancePrompt"]);void 0!==b&&null!=q&&bY(b,["parameters","enhancePrompt"],q);let r=bZ(a,["generateAudio"]);void 0!==b&&null!=r&&bY(b,["parameters","generateAudio"],r);let s=bZ(a,["lastFrame"]);void 0!==b&&null!=s&&bY(b,["instances[0]","lastFrame"],ds(s));let t=bZ(a,["referenceImages"]);if(void 0!==b&&null!=t){let a=t;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e;return c={},null!=(d=bZ(b=a,["image"]))&&bY(c,["image"],ds(d)),null!=(e=bZ(b,["referenceType"]))&&bY(c,["referenceType"],e),c})),bY(b,["instances[0]","referenceImages"],a)}let u=bZ(a,["mask"]);void 0!==b&&null!=u&&bY(b,["instances[0]","mask"],(d={},null!=(e=bZ(c=u,["image"]))&&bY(d,["_self"],ds(e)),null!=(f=bZ(c,["maskMode"]))&&bY(d,["maskMode"],f),d));let v=bZ(a,["compressionQuality"]);void 0!==b&&null!=v&&bY(b,["parameters","compressionQuality"],v);let w=bZ(a,["labels"]);if(void 0!==b&&null!=w&&bY(b,["labels"],w),void 0!==bZ(a,["webhookConfig"]))throw Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let x=bZ(a,["resizeMode"]);void 0!==b&&null!=x&&bY(b,["parameters","resizeMode"],x)}(r,j),j);return l=bX("{model}:predictLongRunning",s._url),m=s._query,delete s._url,delete s._query,this.apiClient.request({path:l,queryParams:m,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b,c,d,e,f,g,h=(b={},null!=(c=bZ(a,["name"]))&&bY(b,["name"],c),null!=(d=bZ(a,["metadata"]))&&bY(b,["metadata"],d),null!=(e=bZ(a,["done"]))&&bY(b,["done"],e),null!=(f=bZ(a,["error"]))&&bY(b,["error"],f),null!=(g=bZ(a,["response"]))&&bY(b,["response"],function(a){let b={},c=bZ(a,["videos"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h;return c={},null!=(d=bZ(a,["_self"]))&&bY(c,["video"],(e={},null!=(f=bZ(b=d,["gcsUri"]))&&bY(e,["uri"],f),null!=(g=bZ(b,["bytesBase64Encoded"]))&&bY(e,["videoBytes"],b$(g)),null!=(h=bZ(b,["mimeType"]))&&bY(e,["mimeType"],h),e)),c})),bY(b,["generatedVideos"],a)}let d=bZ(a,["raiMediaFilteredCount"]);null!=d&&bY(b,["raiMediaFilteredCount"],d);let e=bZ(a,["raiMediaFilteredReasons"]);return null!=e&&bY(b,["raiMediaFilteredReasons"],e),b}(g)),b),i=new cc;return Object.assign(i,h),i})}{let b,c,f,h,i,n,o,p,q,r,s=(g=this.apiClient,h={},null!=(i=bZ(a,["model"]))&&bY(h,["_url","model"],cu(g,i)),null!=(n=bZ(a,["prompt"]))&&bY(h,["instances[0]","prompt"],n),null!=(o=bZ(a,["image"]))&&bY(h,["instances[0]","image"],dr(o)),null!=(p=bZ(a,["video"]))&&bY(h,["instances[0]","video"],dz(p)),null!=(q=bZ(a,["source"]))&&(j=q,k=h,b=bZ(j,["prompt"]),void 0!==k&&null!=b&&bY(k,["instances[0]","prompt"],b),c=bZ(j,["image"]),void 0!==k&&null!=c&&bY(k,["instances[0]","image"],dr(c)),f=bZ(j,["video"]),void 0!==k&&null!=f&&bY(k,["instances[0]","video"],dz(f))),null!=(r=bZ(a,["config"]))&&function(a,b){let c=bZ(a,["numberOfVideos"]);if(void 0!==b&&null!=c&&bY(b,["parameters","sampleCount"],c),void 0!==bZ(a,["outputGcsUri"]))throw Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["fps"]))throw Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["durationSeconds"]);if(void 0!==b&&null!=d&&bY(b,["parameters","durationSeconds"],d),void 0!==bZ(a,["seed"]))throw Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let e=bZ(a,["aspectRatio"]);void 0!==b&&null!=e&&bY(b,["parameters","aspectRatio"],e);let f=bZ(a,["resolution"]);void 0!==b&&null!=f&&bY(b,["parameters","resolution"],f);let g=bZ(a,["personGeneration"]);if(void 0!==b&&null!=g&&bY(b,["parameters","personGeneration"],g),void 0!==bZ(a,["pubsubTopic"]))throw Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=bZ(a,["negativePrompt"]);void 0!==b&&null!=h&&bY(b,["parameters","negativePrompt"],h);let i=bZ(a,["enhancePrompt"]);if(void 0!==b&&null!=i&&bY(b,["parameters","enhancePrompt"],i),void 0!==bZ(a,["generateAudio"]))throw Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["lastFrame"]);void 0!==b&&null!=j&&bY(b,["instances[0]","lastFrame"],dr(j));let k=bZ(a,["referenceImages"]);if(void 0!==b&&null!=k){let a=k;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e;return c={},null!=(d=bZ(b=a,["image"]))&&bY(c,["image"],dr(d)),null!=(e=bZ(b,["referenceType"]))&&bY(c,["referenceType"],e),c})),bY(b,["instances[0]","referenceImages"],a)}if(void 0!==bZ(a,["mask"]))throw Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["compressionQuality"]))throw Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["labels"]))throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let l=bZ(a,["webhookConfig"]);if(void 0!==b&&null!=l&&bY(b,["webhookConfig"],l),void 0!==bZ(a,["resizeMode"]))throw Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(r,h),h);return l=bX("{model}:predictLongRunning",s._url),m=s._query,delete s._url,delete s._query,this.apiClient.request({path:l,queryParams:m,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>{let b,c,d,e,f,g,h=(b={},null!=(c=bZ(a,["name"]))&&bY(b,["name"],c),null!=(d=bZ(a,["metadata"]))&&bY(b,["metadata"],d),null!=(e=bZ(a,["done"]))&&bY(b,["done"],e),null!=(f=bZ(a,["error"]))&&bY(b,["error"],f),null!=(g=bZ(a,["response","generateVideoResponse"]))&&bY(b,["response"],function(a){let b={},c=bZ(a,["generatedSamples"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h;return c={},null!=(d=bZ(a,["video"]))&&bY(c,["video"],(e={},null!=(f=bZ(b=d,["uri"]))&&bY(e,["uri"],f),null!=(g=bZ(b,["encodedVideo"]))&&bY(e,["videoBytes"],b$(g)),null!=(h=bZ(b,["encoding"]))&&bY(e,["mimeType"],h),e)),c})),bY(b,["generatedVideos"],a)}let d=bZ(a,["raiMediaFilteredCount"]);null!=d&&bY(b,["raiMediaFilteredCount"],d);let e=bZ(a,["raiMediaFilteredReasons"]);return null!=e&&bY(b,["raiMediaFilteredReasons"],e),b}(g)),b),i=new cc;return Object.assign(i,h),i})}}}dW.loggedGenerateImagesWarning=!1,dW.loggedEditImageWarning=!1,dW.loggedGenerateVideosWarning=!1;class dX extends bW{constructor(a){super(),this.apiClient=a}async getVideosOperation(a){let b=a.operation,c=a.config;if(void 0===b.name||""===b.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let a,d=b.name.split("/operations/")[0];c&&"httpOptions"in c&&(a=c.httpOptions);let e=await this.fetchPredictVideosOperationInternal({operationName:b.name,resourceName:d,config:{httpOptions:a}});return b._fromAPIResponse({apiResponse:e,_isVertexAI:!0})}{let a=await this.getVideosOperationInternal({operationName:b.name,config:c});return b._fromAPIResponse({apiResponse:a,_isVertexAI:!1})}}async get(a){let b=a.operation,c=a.config;if(void 0===b.name||""===b.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let a,d=b.name.split("/operations/")[0];c&&"httpOptions"in c&&(a=c.httpOptions);let e=await this.fetchPredictVideosOperationInternal({operationName:b.name,resourceName:d,config:{httpOptions:a}});return b._fromAPIResponse({apiResponse:e,_isVertexAI:!0})}{let a=await this.getVideosOperationInternal({operationName:b.name,config:c});return b._fromAPIResponse({apiResponse:a,_isVertexAI:!1})}}async getVideosOperationInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d,e,h=(d={},null!=(e=bZ(a,["operationName"]))&&bY(d,["_url","operationName"],e),d);return f=bX("{operationName}",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json())}{let b,c,h=(b={},null!=(c=bZ(a,["operationName"]))&&bY(b,["_url","operationName"],c),b);return f=bX("{operationName}",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json())}}async fetchPredictVideosOperationInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f,g,h,i=(f={},null!=(g=bZ(a,["operationName"]))&&bY(f,["operationName"],g),null!=(h=bZ(a,["resourceName"]))&&bY(f,["_url","resourceName"],h),f);return d=bX("{resourceName}:fetchPredictOperation",i._url),e=i._query,delete i._url,delete i._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json())}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}class dY extends bW{constructor(a){super(),this.apiClient=a}async create(a){var b,c,d,e,f;let g="",h={};if(this.apiClient.isVertexAI())throw Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let i,j,k,l,m,n,o,p,q,r,s=(d=this.apiClient,l={},null!=(m=bZ(a,["config"]))&&bY(l,["config"],(n=bZ(m,["expireTime"]),void 0!==l&&null!=n&&bY(l,["expireTime"],n),o=bZ(m,["newSessionExpireTime"]),void 0!==l&&null!=o&&bY(l,["newSessionExpireTime"],o),p=bZ(m,["uses"]),void 0!==l&&null!=p&&bY(l,["uses"],p),q=bZ(m,["liveConnectConstraints"]),void 0!==l&&null!=q&&bY(l,["bidiGenerateContentSetup"],(e=d,i={},null!=(j=bZ(f=q,["model"]))&&bY(i,["setup","model"],cu(e,j)),null!=(k=bZ(f,["config"]))&&bY(i,["config"],function(a,b){let c=bZ(a,["generationConfig"]);void 0!==b&&null!=c&&bY(b,["setup","generationConfig"],c);let d=bZ(a,["responseModalities"]);void 0!==b&&null!=d&&bY(b,["setup","generationConfig","responseModalities"],d);let e=bZ(a,["temperature"]);void 0!==b&&null!=e&&bY(b,["setup","generationConfig","temperature"],e);let f=bZ(a,["topP"]);void 0!==b&&null!=f&&bY(b,["setup","generationConfig","topP"],f);let g=bZ(a,["topK"]);void 0!==b&&null!=g&&bY(b,["setup","generationConfig","topK"],g);let h=bZ(a,["maxOutputTokens"]);void 0!==b&&null!=h&&bY(b,["setup","generationConfig","maxOutputTokens"],h);let i=bZ(a,["mediaResolution"]);void 0!==b&&null!=i&&bY(b,["setup","generationConfig","mediaResolution"],i);let j=bZ(a,["seed"]);void 0!==b&&null!=j&&bY(b,["setup","generationConfig","seed"],j);let k=bZ(a,["speechConfig"]);void 0!==b&&null!=k&&bY(b,["setup","generationConfig","speechConfig"],cK(k));let l=bZ(a,["thinkingConfig"]);void 0!==b&&null!=l&&bY(b,["setup","generationConfig","thinkingConfig"],l);let m=bZ(a,["enableAffectiveDialog"]);void 0!==b&&null!=m&&bY(b,["setup","generationConfig","enableAffectiveDialog"],m);let n=bZ(a,["systemInstruction"]);void 0!==b&&null!=n&&bY(b,["setup","systemInstruction"],function(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return c={},null!=(d=bZ(b=a,["mediaResolution"]))&&bY(c,["mediaResolution"],d),null!=(e=bZ(b,["toolCall"]))&&bY(c,["toolCall"],e),null!=(f=bZ(b,["toolResponse"]))&&bY(c,["toolResponse"],f),null!=(g=bZ(b,["audioTranscription"]))&&bY(c,["audioTranscription"],g),null!=(h=bZ(b,["codeExecutionResult"]))&&bY(c,["codeExecutionResult"],h),null!=(i=bZ(b,["executableCode"]))&&bY(c,["executableCode"],i),null!=(j=bZ(b,["fileData"]))&&bY(c,["fileData"],function(a){let b={};if(void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["fileUri"]);null!=c&&bY(b,["fileUri"],c);let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(j)),null!=(k=bZ(b,["functionCall"]))&&bY(c,["functionCall"],function(a){let b={},c=bZ(a,["args"]);null!=c&&bY(b,["args"],c);let d=bZ(a,["id"]);null!=d&&bY(b,["id"],d);let e=bZ(a,["name"]);if(null!=e&&bY(b,["name"],e),void 0!==bZ(a,["partialArgs"]))throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["willContinue"]))throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(k)),null!=(l=bZ(b,["functionResponse"]))&&bY(c,["functionResponse"],l),null!=(m=bZ(b,["inlineData"]))&&bY(c,["inlineData"],function(a){let b={},c=bZ(a,["data"]);if(null!=c&&bY(b,["data"],c),void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(m)),null!=(n=bZ(b,["text"]))&&bY(c,["text"],n),null!=(o=bZ(b,["thought"]))&&bY(c,["thought"],o),null!=(p=bZ(b,["thoughtSignature"]))&&bY(c,["thoughtSignature"],p),null!=(q=bZ(b,["videoMetadata"]))&&bY(c,["videoMetadata"],q),null!=(r=bZ(b,["partMetadata"]))&&bY(c,["partMetadata"],r),c})),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}(cF(n)));let o=bZ(a,["tools"]);if(void 0!==b&&null!=o){let a=cM(o);Array.isArray(a)&&(a=a.map(a=>(function(a){let b={};if(void 0!==bZ(a,["retrieval"]))throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["googleMaps"]);null!=c&&bY(b,["googleMaps"],function(a){let b={},c=bZ(a,["authConfig"]);null!=c&&bY(b,["authConfig"],function(a){let b={},c=bZ(a,["apiKey"]);if(null!=c&&bY(b,["apiKey"],c),void 0!==bZ(a,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["authType"]))throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oauthConfig"]))throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oidcConfig"]))throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["enableWidget"]);if(null!=d&&bY(b,["enableWidget"],d),void 0!==bZ(a,["groundingTypes"]))throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["mcpServers"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mcpServers"],a)}let e=bZ(a,["codeExecution"]);null!=e&&bY(b,["codeExecution"],e);let f=bZ(a,["computerUse"]);if(null!=f&&bY(b,["computerUse"],f),void 0!==bZ(a,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["exaAiSearch"]))throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=bZ(a,["functionDeclarations"]);if(null!=g){let a=g;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let h=bZ(a,["googleSearch"]);null!=h&&bY(b,["googleSearch"],function(a){let b={};if(void 0!==bZ(a,["blockingConfidence"]))throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["excludeDomains"]))throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["searchTypes"]);null!=c&&bY(b,["searchTypes"],c);let d=bZ(a,["timeRangeFilter"]);return null!=d&&bY(b,["timeRangeFilter"],d),b}(h));let i=bZ(a,["googleSearchRetrieval"]);if(null!=i&&bY(b,["googleSearchRetrieval"],i),void 0!==bZ(a,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["urlContext"]);null!=j&&bY(b,["urlContext"],j);let k=bZ(a,["fileSearch"]);return null!=k&&bY(b,["fileSearch"],k),b})(cL(a)))),bY(b,["setup","tools"],a)}let p=bZ(a,["sessionResumption"]);void 0!==b&&null!=p&&bY(b,["setup","sessionResumption"],function(a){let b={},c=bZ(a,["handle"]);if(null!=c&&bY(b,["handle"],c),void 0!==bZ(a,["transparent"]))throw Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(p));let q=bZ(a,["inputAudioTranscription"]);void 0!==b&&null!=q&&bY(b,["setup","inputAudioTranscription"],q);let r=bZ(a,["outputAudioTranscription"]);void 0!==b&&null!=r&&bY(b,["setup","outputAudioTranscription"],r);let s=bZ(a,["realtimeInputConfig"]);void 0!==b&&null!=s&&bY(b,["setup","realtimeInputConfig"],s);let t=bZ(a,["contextWindowCompression"]);void 0!==b&&null!=t&&bY(b,["setup","contextWindowCompression"],t);let u=bZ(a,["proactivity"]);if(void 0!==b&&null!=u&&bY(b,["setup","proactivity"],u),void 0!==bZ(a,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let v=bZ(a,["avatarConfig"]);void 0!==b&&null!=v&&bY(b,["setup","avatarConfig"],v);let w=bZ(a,["safetySettings"]);if(void 0!==b&&null!=w){let a=w;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["category"]);if(null!=c&&bY(b,["category"],c),void 0!==bZ(a,["method"]))throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["threshold"]);return null!=d&&bY(b,["threshold"],d),b})(a))),bY(b,["setup","safetySettings"],a)}let x=bZ(a,["translationConfig"]);return void 0!==b&&null!=x&&bY(b,["setup","generationConfig","translationConfig"],x),{}}(k,i)),i)),r=bZ(m,["lockAdditionalFields"]),void 0!==l&&null!=r&&bY(l,["fieldMask"],r),{})),l);g=bX("auth_tokens",s._url),h=s._query,delete s.config,delete s._url,delete s._query;let t=function(a,b){let c=null,d=a.bidiGenerateContentSetup;if("object"==typeof d&&null!==d&&"setup"in d){let b=d.setup;"object"==typeof b&&null!==b?(a.bidiGenerateContentSetup=b,c=b):delete a.bidiGenerateContentSetup}else void 0!==d&&delete a.bidiGenerateContentSetup;let e=a.fieldMask;if(c){let d=function(a){let b=[];for(let c in a)if(Object.prototype.hasOwnProperty.call(a,c)){let d=a[c];if("object"==typeof d&&null!=d&&Object.keys(d).length>0){let a=Object.keys(d).map(a=>`${c}.${a}`);b.push(...a)}else b.push(c)}return b.join(",")}(c);if(Array.isArray(null==b?void 0:b.lockAdditionalFields)&&(null==b?void 0:b.lockAdditionalFields.length)===0)d?a.fieldMask=d:delete a.fieldMask;else if((null==b?void 0:b.lockAdditionalFields)&&b.lockAdditionalFields.length>0&&null!==e&&Array.isArray(e)&&e.length>0){let b=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],c=[];e.length>0&&(c=e.map(a=>b.includes(a)?`generationConfig.${a}`:a));let f=[];d&&f.push(d),c.length>0&&f.push(...c),f.length>0?a.fieldMask=f.join(","):delete a.fieldMask}else delete a.fieldMask}else null!==e&&Array.isArray(e)&&e.length>0?a.fieldMask=e.join(","):delete a.fieldMask;return a}(s,a.config);return this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}}}class dZ extends bW{constructor(a){super(),this.apiClient=a,this.list=async a=>new c0(bM.PAGED_ITEM_DOCUMENTS,b=>this.listInternal({parent:a.parent,config:b.config}),await this.listInternal(a),a)}async get(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","name"],g),f);return d=bX("{name}",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}}async delete(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","name"],g),null!=(h=bZ(a,["config"]))&&(i=bZ(h,["force"]),void 0!==f&&null!=i&&bY(f,["_query","force"],i)),f);d=bX("{name}",j._url),e=j._query,delete j._url,delete j._query,await this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(j),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal})}}async listInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j,k=(f={},null!=(g=bZ(a,["parent"]))&&bY(f,["_url","parent"],g),null!=(h=bZ(a,["config"]))&&(i=bZ(h,["pageSize"]),void 0!==f&&null!=i&&bY(f,["_query","pageSize"],i),j=bZ(h,["pageToken"]),void 0!==f&&null!=j&&bY(f,["_query","pageToken"],j)),f);return d=bX("{parent}/documents",k._url),e=k._query,delete k._url,delete k._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(k),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["documents"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["documents"],a)}return b}(a),c=new ci;return Object.assign(c,b),c})}}}class d$ extends bW{constructor(a,b=new dZ(a)){super(),this.apiClient=a,this.documents=b,this.list=async(a={})=>new c0(bM.PAGED_ITEM_FILE_SEARCH_STORES,a=>this.listInternal(a),await this.listInternal(a),a)}async uploadToFileSearchStore(a){if(this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(a.fileSearchStoreName,a.file,a.config)}async downloadMedia(a,b){if(this.apiClient.isVertexAI())throw Error("This method is only supported in the Gemini Developer client.");let c=new URL(a,"http://dummy.com"),d=c.pathname;if(d.startsWith("/")&&(d=d.slice(1)),!d.includes("/media/"))throw Error(`Invalid uri format: ${a}. Expected to contain /media/`);let e={};c.searchParams.forEach((a,b)=>{e[b]=a}),e.alt="media";let f=Object.assign({},null==b?void 0:b.httpOptions),g=await this.apiClient.request({path:d,httpMethod:"GET",queryParams:e,httpOptions:f});if(g instanceof b0)return new Uint8Array(await g.responseInternal.arrayBuffer());throw Error("Unexpected response type from downloadMedia")}async create(a){var b,c,d;let e="",f={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let g,h,i,j,k=(d=this.apiClient,g={},null!=(h=bZ(a,["config"]))&&(i=bZ(h,["displayName"]),void 0!==g&&null!=i&&bY(g,["displayName"],i),j=bZ(h,["embeddingModel"]),void 0!==g&&null!=j&&bY(g,["embeddingModel"],cu(d,j))),g);return e=bX("fileSearchStores",k._url),f=k._query,delete k._url,delete k._query,this.apiClient.request({path:e,queryParams:f,body:JSON.stringify(k),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}}async get(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","name"],g),f);return d=bX("{name}",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}}async delete(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","name"],g),null!=(h=bZ(a,["config"]))&&(i=bZ(h,["force"]),void 0!==f&&null!=i&&bY(f,["_query","force"],i)),f);d=bX("{name}",j._url),e=j._query,delete j._url,delete j._query,await this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(j),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal})}}async listInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j=(f={},null!=(g=bZ(a,["config"]))&&(h=bZ(g,["pageSize"]),void 0!==f&&null!=h&&bY(f,["_query","pageSize"],h),i=bZ(g,["pageToken"]),void 0!==f&&null!=i&&bY(f,["_query","pageToken"],i)),f);return d=bX("fileSearchStores",j._url),e=j._query,delete j._url,delete j._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(j),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["fileSearchStores"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["fileSearchStores"],a)}return b}(a),c=new cj;return Object.assign(c,b),c})}}async uploadToFileSearchStoreInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i=(f={},null!=(g=bZ(a,["fileSearchStoreName"]))&&bY(f,["_url","file_search_store_name"],g),null!=(h=bZ(a,["config"]))&&dC(h,f),f);return d=bX("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",i._url),e=i._query,delete i._url,delete i._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new ck;return Object.assign(e,d),e})}}async importFile(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j=(f={},null!=(g=bZ(a,["fileSearchStoreName"]))&&bY(f,["_url","file_search_store_name"],g),null!=(h=bZ(a,["fileName"]))&&bY(f,["fileName"],h),null!=(i=bZ(a,["config"]))&&function(a,b){let c=bZ(a,["customMetadata"]);if(void 0!==b&&null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["customMetadata"],a)}let d=bZ(a,["chunkingConfig"]);void 0!==b&&null!=d&&bY(b,["chunkingConfig"],d)}(i,f),f);return d=bX("{file_search_store_name}:importFile",j._url),e=j._query,delete j._url,delete j._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(j),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m=(g={},null!=(h=bZ(a,["name"]))&&bY(g,["name"],h),null!=(i=bZ(a,["metadata"]))&&bY(g,["metadata"],i),null!=(j=bZ(a,["done"]))&&bY(g,["done"],j),null!=(k=bZ(a,["error"]))&&bY(g,["error"],k),null!=(l=bZ(a,["response"]))&&bY(g,["response"],(c={},null!=(d=bZ(b=l,["sdkHttpResponse"]))&&bY(c,["sdkHttpResponse"],d),null!=(e=bZ(b,["parent"]))&&bY(c,["parent"],e),null!=(f=bZ(b,["documentName"]))&&bY(c,["documentName"],f),c)),g),n=new cl;return Object.assign(n,m),n})}}}function d_(){var a,b,c,d,e,g;if(f)return f;let h=globalThis;return f=("Deno"in globalThis?0:1)?null!=(g=null==(e=h.process)?void 0:e.env)?g:{}:null!=(d=null==(c=null==(b=null==(a=h.Deno)?void 0:a.env)?void 0:b.toObject)?void 0:c.call(b))?d:{}}class d0{constructor(a){this.options=a}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(a){return function(a){var b,c;let d={};for(let[b,c]of a){let a=b.toLowerCase();"authorization"!==a&&"x-goog-api-key"!==a&&(d[b]=c)}let e={access_token:null!=(b=a.get("authorization"))?b:void 0,api_key:null!=(c=a.get("x-goog-api-key"))?c:void 0,default_headers:Object.keys(d).length?d:void 0};return d7(e)?e:void 0}(await this.options.getAuthHeaders(a))}}class d1{beforeCreateRequest(a,b){return Object.assign(Object.assign({},b),{url:function(a){let[,b,...c]=a.pathname.split("/");if(!b)return a;let d=decodeURIComponent(b);if(!d.includes("/"))return a;let e=new URL(a);return e.pathname=`/${d}/${c.join("/")}`,e}(b.url)})}async beforeRequest(a,b){var c,d,e,f,g,h;if(d4(b.headers,d6(c=a.security_source)?null!=(e=null==(d=c.getDefaultHeaders)?void 0:d.call(c))?e:c.defaultHeaders:d5(c)?c.default_headers:void 0),f=a,g=b.headers,void 0!==f.options.user_project&&null===g.get("x-goog-user-project")&&g.set("x-goog-user-project",f.options.user_project),null!==(h=b.headers).get("authorization")||null!==h.get("x-goog-api-key"))return b;let i=await d2(a.security_source,b.url);return d4(b.headers,null==i?void 0:i.default_headers),function(a,b){if(b){var c;if(b.api_key)return a.set("x-goog-api-key",b.api_key);b.access_token&&a.set("Authorization","bearer "===(c=b.access_token).slice(0,7).toLowerCase()?c:`Bearer ${c}`)}}(b.headers,i),b}}async function d2(a,b){if(d6(a))return a.resolveGoogleGenAISecurity(b);let c="function"==typeof a?await a():a;return d5(c)?d3(c):d3(void 0)}function d3(a){var b,c;let d=d_(),e=Object.assign(Object.assign({},a),{api_key:null!=(b=null==a?void 0:a.api_key)?b:d.GOOGLE_GENAI_API_KEY,access_token:null!=(c=null==a?void 0:a.access_token)?c:d.GOOGLE_GENAI_ACCESS_TOKEN});return d7(e)?e:void 0}function d4(a,b){if(b)for(let[c,d]of new Headers(b))null===a.get(c)&&a.set(c,d)}function d5(a){return"object"==typeof a&&null!==a}function d6(a){return"object"==typeof a&&null!==a&&"resolveGoogleGenAISecurity"in a&&"function"==typeof a.resolveGoogleGenAISecurity}function d7(a){return void 0!==a.api_key||void 0!==a.access_token||void 0!==a.default_headers}class d8 extends Error{constructor(a,b){let c=a;(null==b?void 0:b.cause)&&(c+=`: ${b.cause}`),super(c,b),this.name="HTTPClientError",void 0===this.cause&&(this.cause=null==b?void 0:b.cause)}}class d9 extends d8{constructor(){super(...arguments),this.name="UnexpectedClientError"}}class ea extends d8{constructor(){super(...arguments),this.name="InvalidRequestError"}}class eb extends d8{constructor(){super(...arguments),this.name="RequestAbortedError"}}class ec extends d8{constructor(){super(...arguments),this.name="RequestTimeoutError"}}class ed extends d8{constructor(){super(...arguments),this.name="ConnectionError"}}class ee extends Error{constructor(a,b){var c,d,e,f;super(a),this.statusCode=null==(c=null==b?void 0:b.response)?void 0:c.status,this.body=null!=(d=null==b?void 0:b.body)?d:"",this.headers=null==(e=null==b?void 0:b.response)?void 0:e.headers,this.contentType=(null==(f=null==b?void 0:b.response)?void 0:f.headers.get("content-type"))||"",this.rawResponse=null==b?void 0:b.response,this.name="GoogleGenAiError"}}class ef extends Error{}class eg extends ef{constructor(a,b,c,d){super(eg.makeMessage(a,b,c)),this.status=a,this.headers=d,this.error=b,this.statusCode=a,this.body=eu(b),this.contentType=(null==d?void 0:d.get("content-type"))||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(a,b,c){var d,e;let f=b&&null!==(e=b)&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof b.message?b.message:void 0,g=eu(b),h=null!=(d=null!=f?f:c)?d:g||"An error occurred",i=a?`${a} `:"";return`${i}${h}`}static generate(a,b,c,d){return a&&d?400===a?new ek(a,b,c,d):401===a?new el(a,b,c,d):403===a?new em(a,b,c,d):404===a?new en(a,b,c,d):409===a?new eo(a,b,c,d):422===a?new ep(a,b,c,d):429===a?new eq(a,b,c,d):a>=500?new er(a,b,c,d):new eg(a,b,c,d):new ei({message:c,cause:b instanceof Error?b:void 0})}}class eh extends eg{constructor({message:a}={}){super(void 0,void 0,a||"Request was aborted.",void 0)}}class ei extends eg{constructor({message:a,cause:b}){super(void 0,void 0,a||"Connection error.",void 0),this.cause=b}}class ej extends ei{constructor({message:a}={}){super({message:a||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}}class ek extends eg{}class el extends eg{}class em extends eg{}class en extends eg{}class eo extends eg{}class ep extends eg{}class eq extends eg{}class er extends eg{}function es(a){var b,c,d;let e,f;return"object"==typeof(b=a)&&null!==b&&eg.prototype.isPrototypeOf(b)?a:a instanceof ee?(e=function(a){let b=et(a,"data$");if(b&&"object"==typeof b)return b;try{let b=JSON.parse(a.body);if(b&&"object"==typeof b)return b}catch(a){}let c=et(a,"error");return c&&"object"==typeof c?c:void 0}(c=a),ev(f=eg.generate(c.statusCode,e,c.message,c.headers),"body",c.body),ev(f,"contentType",c.contentType),ev(f,"rawResponse",c.rawResponse),ev(f,"statusCode",c.statusCode),ev(f,"cause",c),f):a instanceof d8?(d=a)instanceof ec?new ej({message:d.message}):d instanceof eb?new eh({message:d.message}):(d instanceof ed,new ei({message:d.message,cause:d})):a}function et(a,b){return a&&"object"==typeof a?a[b]:void 0}function eu(a){if(!a)return"";try{return JSON.stringify(a)}catch(b){return String(a)}}function ev(a,b,c){Object.defineProperty(a,b,{configurable:!0,enumerable:!0,value:c,writable:!1})}class ew{constructor(){for(const a of(this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[],[]))"sdkInit"in a&&this.registerSDKInitHook(a),"beforeCreateRequest"in a&&this.registerBeforeCreateRequestHook(a),"beforeRequest"in a&&this.registerBeforeRequestHook(a),"afterSuccess"in a&&this.registerAfterSuccessHook(a),"afterError"in a&&this.registerAfterErrorHook(a);!function(a){let b=new d1;a.registerBeforeCreateRequestHook(b),a.registerBeforeRequestHook(b)}(this)}registerSDKInitHook(a){this.sdkInitHooks.push(a)}registerBeforeCreateRequestHook(a){this.beforeCreateRequestHooks.push(a)}registerBeforeRequestHook(a){this.beforeRequestHooks.push(a)}registerAfterSuccessHook(a){this.afterSuccessHooks.push(a)}registerAfterErrorHook(a){this.afterErrorHooks.push(a)}sdkInit(a){return this.sdkInitHooks.reduce((a,b)=>b.sdkInit(a),a)}beforeCreateRequest(a,b){let c=b;for(let b of this.beforeCreateRequestHooks)c=b.beforeCreateRequest(a,c);return c}async beforeRequest(a,b){let c=b;for(let b of this.beforeRequestHooks)c=await b.beforeRequest(a,c);return c}async afterSuccess(a,b){let c=b;for(let b of this.afterSuccessHooks)c=await b.afterSuccess(a,c);return c}async afterError(a,b,c){let d=b,e=c;for(let b of this.afterErrorHooks){let c=await b.afterError(a,d,e);d=c.response,e=c.error}return{response:d,error:e}}}function ex(a){return{ok:!0,value:a}}function ey(a){return{ok:!1,error:a}}function ez(a){return btoa(String.fromCodePoint(...a))}let eA=Object.prototype.hasOwnProperty;function eB(a,b){let c=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(b={}){return a.replace(c,function(a,c){if(!eA.call(b,c))throw Error(`Parameter '${c}' is required`);let d=b[c];if("string"!=typeof d&&"number"!=typeof d)throw Error(`Parameter '${c}' must be a string or number`);return`${d}`}).replace(/^\/+/,"")}}let eC=["https://generativelanguage.googleapis.com"];function eD(a){let b={};for(let[c,d]of Object.entries(a))void 0!==d&&(b[c]=d);return b}function eE(a){if(null===a||"object"!=typeof a||"[object Object]"!==Object.prototype.toString.call(a))return!1;let b=Object.getPrototypeOf(a);if(null===b||b===Object.prototype)return!0;try{return null===Object.getPrototypeOf(b)}catch(a){return!1}}let eF=(a,b,c)=>{let d="",e=(null==c?void 0:c.explode)?eI(a,b):[[a,b]];if(e.every(([a,b])=>null==b))return;let f=a=>(null==c?void 0:c.charEncoding)==="percent"?encodeURIComponent(a):a,g=f(",");return e.forEach(([a,b])=>{var c,e;let h="",i=null;null!=b&&(null==(i=Array.isArray(b)?null==(c=eL(b,a=>`${f(eJ(a))}`))?void 0:c.join(g):eE(b)?null==(e=eM(Object.entries(b),([a,b])=>`${f(a)}${g}${f(eJ(b))}`))?void 0:e.join(g):`${f(eJ(b))}`)||(h=`${f(a)}=${i}`)&&"="!==h&&(d+=`&${h}`))}),d.slice(1)};function eG(a,b,c){if(void 0===b)return;let d=a=>(null==c?void 0:c.charEncoding)==="percent"?encodeURIComponent(a):a,e=d(JSON.stringify(b,eK));return(null==c?void 0:c.explode)?e:`${d(a)}=${e}`}let eH=(a,b,c)=>{let d="",e=(null==c?void 0:c.explode)?eI(a,b):[[a,b]];if(e.every(([a,b])=>null==b))return;let f=a=>(null==c?void 0:c.charEncoding)==="percent"?encodeURIComponent(a):a;return e.forEach(([a,e])=>{var g;let h="";if(null!=e){if(Array.isArray(e))h=null==(g=eL(e,a=>`${f(eJ(a))}`))?void 0:g.join(",");else if(eE(e)){let a=eM(Object.entries(e),([a,b])=>`,${f(a)},${f(eJ(b))}`);h=null==a?void 0:a.join("").slice(1)}else{let d=(null==c?void 0:c.explode)&&eE(b)?`${a}=`:"";h=`${d}${f(eJ(e))}`}d+=h?`,${h}`:""}}),d.slice(1)};function eI(a,b){return Array.isArray(b)?b.map(b=>[a,b]):eE(b)?Object.entries(null!=b?b:{}).map(([a,b])=>[a,b]):[[a,b]]}function eJ(a){return null==a?"":a instanceof Date?a.toISOString():a instanceof Uint8Array?ez(a):"object"==typeof a?JSON.stringify(a,eK):`${a}`}function eK(a,b){return b instanceof Uint8Array?ez(b):b}function eL(a,b){let c=a.reduce((a,c)=>{if(null==c)return a;let d=b(c);return null==d||a.push(d),a},[]);return c.length?c:null}function eM(a,b){let c=[];for(let[d,e]of a){if(null==e)continue;let a=b([d,e]);null!=a&&c.push(a)}return c.length?c:null}let eN=function(a,b){var c,d,e;let f=Object.assign(Object.assign({},b),{explode:null==(c=null==b?void 0:b.explode)||c,charEncoding:null!=(d=null==b?void 0:b.charEncoding)?d:"percent"}),g=new Set(null!=(e=null==b?void 0:b.allowEmptyValue)?e:[]);return function(...a){return a.filter(Boolean).join("&")}(...Object.entries(a).map(([a,b])=>g.has(a)&&(null==b||""===b||Array.isArray(b)&&0===b.length)?`${encodeURIComponent(a)}=`:eF(a,b,f)))},eO=(a,b)=>null==b?fetch(a):fetch(a,b);class eP{constructor(a={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=a,this.fetcher=a.fetcher||eO}async request(a){let b=a;for(let a of this.requestHooks){let c=await a(b);c&&(b=c)}try{let a=await this.fetcher(b);for(let c of this.responseHooks)await c(a,b);return a}catch(a){for(let c of this.requestErrorHooks)await c(a,b);throw a}}addHook(...a){if("beforeRequest"===a[0])this.requestHooks.push(a[1]);else if("requestError"===a[0])this.requestErrorHooks.push(a[1]);else if("response"===a[0])this.responseHooks.push(a[1]);else throw Error(`Invalid hook type: ${a[0]}`);return this}removeHook(...a){let b;if("beforeRequest"===a[0])b=this.requestHooks;else if("requestError"===a[0])b=this.requestErrorHooks;else if("response"===a[0])b=this.responseHooks;else throw Error(`Invalid hook type: ${a[0]}`);let c=b.findIndex(b=>b===a[1]);return c>=0&&b.splice(c,1),this}clone(){let a=new eP(this.options);return a.requestHooks=this.requestHooks.slice(),a.requestErrorHooks=this.requestErrorHooks.slice(),a.responseHooks=this.responseHooks.slice(),a}}let eQ=/\s*;\s*/g;function eR(a,b){var c;if("*"===b)return!0;let d=(null==(c=a.headers.get("content-type"))?void 0:c.trim())||"application/octet-stream";d=d.toLowerCase();let[e="",...f]=b.toLowerCase().trim().split(eQ);if(2!==e.split("/").length)return!1;let[g="",...h]=d.split(eQ),[i="",j=""]=g.split("/");if(!i||!j||"*/*"!==e&&g!==e&&`${i}/*`!==e&&`*/${j}`!==e||h.length<f.length)return!1;let k=new Set(h);for(let a of f)if(!k.has(a))return!1;return!0}let eS=RegExp("^[0-9]xx$","i");function eT(a,b){let c=`${a.status}`,d=Array.isArray(b)?b:[b];return!!d.length&&d.some(a=>{let b=`${a}`;if("default"===b)return!0;if(!eS.test(`${b}`))return b===c;let d=b.charAt(0);if(!d)throw Error("Invalid status code range");let e=c.charAt(0);if(!e)throw Error(`Invalid response status code: ${c}`);return e===d})}function eU(a){if("object"!=typeof a||null==a)return!1;let b=a instanceof TypeError&&a.message.toLowerCase().startsWith("failed to fetch"),c=a instanceof TypeError&&a.message.toLowerCase().startsWith("fetch failed"),d="name"in a&&"ConnectionError"===a.name,e="code"in a&&"string"==typeof a.code&&"econnreset"===a.code.toLowerCase();return b||c||e||d}function eV(a){if("object"!=typeof a||null==a)return!1;let b="name"in a&&"TimeoutError"===a.name,c="code"in a&&23===a.code,d="code"in a&&"string"==typeof a.code&&"econnaborted"===a.code.toLowerCase();return b||c||d}let eW={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5};class eX extends Error{constructor(a,b){let c=a;(null==b?void 0:b.cause)&&(c+=`: ${b.cause}`),super(c,b),this.name="PermanentError",void 0===this.cause&&(this.cause=null==b?void 0:b.cause),Object.setPrototypeOf(this,eX.prototype)}}class eY extends Error{constructor(a,b){super(a),this.response=b,this.name="TemporaryError",Object.setPrototypeOf(this,eY.prototype)}}async function eZ(a,b){var c;switch(b.config.strategy){case"backoff":return e0(e$(a,{statusCodes:b.statusCodes,retryConnectionErrors:!!b.config.retryConnectionErrors}),null!=(c=b.config.backoff)?c:eW);case"attempt-count-backoff":return e1(e$(a,{statusCodes:b.statusCodes,retryConnectionErrors:!!b.config.retryConnectionErrors}),Object.assign(Object.assign({},eW),b.config.backoff),b.config);default:return await a(0)}}function e$(a,b){return async c=>{try{var d,e;let f,g=await a(c);if(d=g,e=b.statusCodes,f=`${d.status}`,e.some(a=>{if(!e_.test(a))return a===f;let b=a.charAt(0);if(!b)throw Error("Invalid status code range");let c=f.charAt(0);if(!c)throw Error(`Invalid response status code: ${f}`);return c===b}))throw new eY("Response failed with retryable status code",g);return g}catch(a){if(a instanceof eY||b.retryConnectionErrors&&(eV(a)||eU(a)))throw a;throw new eX("Permanent error",{cause:a})}}}let e_=RegExp("^[0-9]xx$","i");async function e0(a,b){let{maxElapsedTime:c,initialInterval:d,exponent:e,maxInterval:f}=b,g=Date.now(),h=0;for(;;)try{return await a(h)}catch(i){if(i instanceof eX)throw i.cause;if(Date.now()-g>c){if(i instanceof eY)return i.response;throw i}let a=0;i instanceof eY&&(a=e2(i.response)),a<=0&&(a=d*Math.pow(h,e)+1e3*Math.random());let b=Math.min(a,f);await e3(b),h++}}async function e1(a,b,c){let d=0;for(;;)try{return await a(d)}catch(f){if(f instanceof eX)throw f.cause;if(d>=c.maxRetries){if(f instanceof eY)return f.response;throw f}let a=0;f instanceof eY&&(a=e2(f.response)),a<=0&&(a=b.initialInterval*Math.pow(b.exponent,d)*(1-.25*Math.random()));let e=Math.min(a,b.maxInterval);await e3(e),d++}}function e2(a){let b=a.headers.get("retry-after-ms");if(b){let a=Number(b);if(Number.isFinite(a)&&a>=0)return a}let c=a.headers.get("retry-after")||"";if(!c)return 0;let d=Number(c);if(Number.isInteger(d))return 1e3*d;let e=Date.parse(c);if(Number.isInteger(e)){let a=e-Date.now();return a>0?Math.ceil(a):0}return 0}async function e3(a){return new Promise(b=>setTimeout(b,a))}let e4="u"<typeof globalThis?null:globalThis,e5="object"==typeof e4&&null!=e4&&"importScripts"in e4&&"function"==typeof e4.importScripts||"u">typeof navigator&&"serviceWorker"in navigator||"object"==typeof window&&void 0!==window.document;class e6{constructor(a={}){const b=a;"object"==typeof b&&null!=b&&"hooks"in b&&b.hooks instanceof ew?this._hooks=b.hooks:this._hooks=new ew;const c=new eP;a.http_client=a.http_client||c;const d=function(a){var b;let c=a.server_url;if(!c){let d=null!=(b=a.server_idx)?b:0;if(d<0||d>=eC.length)throw Error(`Invalid server index ${d}`);c=eC[d]||""}return new URL(eB(c)({}))}(a=this._hooks.sdkInit(a));d&&(d.pathname=d.pathname.replace(/\/+$/,"")+"/"),this._baseURL=d,this._httpClient=a.http_client||c,this._options=Object.assign(Object.assign({},function(a){let b=Object.assign({},a),c=d_();return void 0!==c.GOOGLE_GENAI_API_VERSION&&(null!=b.api_version||(b.api_version=c.GOOGLE_GENAI_API_VERSION)),void 0!==c.GOOGLE_GENAI_USER_PROJECT&&(null!=b.user_project||(b.user_project=c.GOOGLE_GENAI_USER_PROJECT)),b}(a)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&d_().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(a,b,c){var d,e,f,g,h,i;let j,k,{method:l,path:m,query:n,headers:o,security:p}=b,q=null!=(d=b.baseURL)?d:this._baseURL;if(!q)return ey(new ea("No base URL provided for operation"));let r=new URL(q);m?(r.pathname=r.pathname.replace(/\/+$/,"")+"/",!(j=new URL(m,r)).search&&r.search&&(j.search=r.search)):j=r,j.hash="";let s=a=>Object.entries(a).map(([a,b])=>{if(null==b)return;let c=eE(b)?JSON.stringify(b):b;return eF(a,c,{explode:Array.isArray(c),charEncoding:"percent"})}).filter(a=>void 0!==a).join("&"),t=[n||"",s((null==c?void 0:c.extra_query)||{}),s((null==p?void 0:p.queryParams)||{})].reduce((a,b)=>{if(!b)return a;let c=new Set(b.split("&").filter(a=>""!==a).map(a=>{var b;return null!=(b=a.split("=")[0])?b:""}));return[...a.split("&").filter(a=>{var b;return""!==a&&!c.has(null!=(b=a.split("=")[0])?b:"")}),b].join("&")},j.search.slice(1));t&&(j.search=`?${t}`);let u=new Headers(o),v=null==p?void 0:p.basic.username,w=null==p?void 0:p.basic.password;if(null!=v||null!=w){let a=ez((i=[v||"",w||""].join(":"),new TextEncoder().encode(i)));u.set("Authorization",`Basic ${a}`)}for(let[a,b]of new Headers((null==p?void 0:p.headers)||{}))u.set(a,b);let x=u.get("cookie")||"";for(let[a,b]of Object.entries((null==p?void 0:p.cookies)||{}))x+=`; ${a}=${b}`;for(let[a,b]of(x=x.startsWith("; ")?x.slice(2):x,u.set("cookie",x),new Headers(null!=(e=null==c?void 0:c.headers)?e:null==(f=null==c?void 0:c.fetch_options)?void 0:f.headers)))u.set(a,b);e5||u.set(null!=(g=b.uaHeader)?g:"user-agent",null!=(h=b.userAgent)?h:"speakeasy-sdk/typescript 2.4.1-preview.4 2.924.0 v1beta @google/genai");let y=b.body,z=Object.fromEntries(Object.entries((null==c?void 0:c.extra_body)||{}).filter(([,a])=>void 0!==a));if(Object.keys(z).length>0){let a,b=new Headers(o).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(b)||"string"!=typeof y&&null!=y)return ey(new ea("extra_body can only be merged into JSON object request bodies"));try{a=y?JSON.parse(y):{}}catch(a){return ey(new ea("extra_body can only be merged into JSON object request bodies",{cause:a}))}if(!eE(a))return ey(new ea("extra_body can only be merged into JSON object request bodies"));y=JSON.stringify(Object.assign(Object.assign({},a),z)),u.delete("content-length")}let A=Object.assign(Object.assign({},null==c?void 0:c.fetch_options),c);(null==A?void 0:A.signal)||null==b.timeout_ms||!(b.timeout_ms>0)||(a.timeout_ms=b.timeout_ms),b.body instanceof ReadableStream&&Object.assign(A,{duplex:"half"});try{k=this._hooks.beforeCreateRequest(a,{url:j,options:Object.assign(Object.assign({},A),{body:null!=y?y:null,headers:u,method:l})})}catch(a){return ey(new d9("Create request hook failed to execute",{cause:a}))}return ex(new Request(k.url,k.options))}async _do(a,b){let{context:c,isErrorStatusCode:d}=b,e=c.timeout_ms;return eZ(async()=>{var b;let f=a.clone(),g=f;if(null!=e&&e>0){let a=AbortSignal.timeout(e),c=null!=(b=function(...a){let b=[];for(let c of a)c&&b.push(c);switch(b.length){case 0:case 1:return b[0]||null;default:if("any"in AbortSignal&&"function"==typeof AbortSignal.any)return AbortSignal.any(b);var c=b;let d=new AbortController,e=d.signal;if(!c.length)return d.signal;if(1===c.length)return c[0]||d.signal;for(let a of c)if(a.aborted)return a;function f(){d.abort(this.reason),function(){for(let a of g){let b=a.deref();b&&b.removeEventListener("abort",f)}}()}let g=[];for(let a of c)g.push(new WeakRef(a)),a.addEventListener("abort",f);return e}}(f.signal,a))?b:a;g=new Request(f,{signal:c})}let h=await this._hooks.beforeRequest(c,g);await e9(this._logger,h).catch(a=>{var b;return null==(b=this._logger)?void 0:b.log("Failed to log request:",a)});let i=await this._httpClient.request(h);try{if(d(i.status)){let a=await this._hooks.afterError(c,i,null);if(a.error)throw a.error;i=a.response||i}else i=await this._hooks.afterSuccess(c,i)}finally{await fa(this._logger,i,h).catch(a=>{var b;return null==(b=this._logger)?void 0:b.log("Failed to log response:",a)})}return i},{config:b.retryConfig,statusCodes:b.retryCodes}).then(a=>ex(a),a=>{switch(!0){case function(a){if("object"!=typeof a||null==a)return!1;let b="name"in a&&"AbortError"===a.name,c="code"in a&&20===a.code,d="code"in a&&"string"==typeof a.code&&"econnaborted"===a.code.toLowerCase();return b||c||d}(a):return ey(new eb("Request aborted by client",{cause:a}));case eV(a):return ey(new ec("Request timed out",{cause:a}));case eU(a):return ey(new ed("Unable to make request",{cause:a}));default:return ey(new d9("Unexpected HTTP client error",{cause:a}))}})}}let e7=/^(application|text)\/([^+]+\+)*json.*/,e8=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function e9(a,b){if(!a)return;let c=b.headers.get("content-type"),d=(null==c?void 0:c.split(";")[0])||"";for(let[c,d]of(a.group(`> Request: ${b.method} ${b.url}`),a.group("Headers:"),b.headers.entries()))a.log(`${c}: ${d}`);switch(a.groupEnd(),a.group("Body:"),!0){case e7.test(d):a.log(await b.clone().json());break;case d.startsWith("text/"):a.log(await b.clone().text());break;case"multipart/form-data"===d:for(let[c,d]of(await b.clone().formData())){let b=d instanceof Blob?"<Blob>":d;a.log(`${c}: ${b}`)}break;default:a.log(`<${c}>`)}a.groupEnd(),a.groupEnd()}async function fa(a,b,c){if(!a)return;let d=b.headers.get("content-type"),e=(null==d?void 0:d.split(";")[0])||"";for(let[d,e]of(a.group(`< Response: ${c.method} ${c.url}`),a.log("Status Code:",b.status,b.statusText),a.group("Headers:"),b.headers.entries()))a.log(`${d}: ${e}`);switch(a.groupEnd(),a.group("Body:"),!0){case eR(b,"application/json")||e7.test(e)&&!e8.test(e):a.log(await b.clone().json());break;case eR(b,"application/jsonl")||e8.test(e):case eR(b,"text/event-stream"):a.log(`<${d}>`);break;case eR(b,"text/*"):a.log(await b.clone().text());break;case eR(b,"multipart/form-data"):for(let[c,d]of(await b.clone().formData())){let b=d instanceof Blob?"<Blob>":d;a.log(`${c}: ${b}`)}break;default:a.log(`<${d}>`)}a.groupEnd(),a.groupEnd()}class fb extends ee{constructor(a,b){a&&(a+=": "),a+=`Status ${b.response.status}`;const c=b.response.headers.get("content-type")||'""';"application/json"!==c&&(a+=` Content-Type ${c.includes(" ")?`"${c}"`:c}`);const d=b.body||'""';a+=d.length>100?"\n":". ";let e=d;if(d.length>1e4){const a=d.substring(0,1e4),b=d.length-1e4;e=`${a}...and ${b} more chars`}a+=`Body: ${e}`,super(a=a.trim(),b),this.name="GoogleGenAiDefaultError"}}function fc(a){try{return JSON.parse(a)}catch(b){return a}}class fd extends ReadableStream{constructor(a,b,c){var d;const e=a.getReader();let f=new Uint8Array(4096),g=0,h=0;const i={eventId:void 0},j=null==(d=null==c?void 0:c.dataRequired)||d;super({async pull(a){try{for(;;){let c=function(a,b,c){for(let d=c;d<b;d++)if(13===a[d]||10===a[d])for(let c of fe){if(d+c.length>b)continue;let e=!0;for(let b=0;b<c.length;b++)if(a[d+b]!==c[b]){e=!1;break}if(e)return{index:d,length:c.length}}return null}(f,g,h);if(!c){h=Math.max(0,g-ff+1);let b=await e.read();if(b.done)return a.close();if(g+b.value.length>f.length){let a=new Uint8Array(Math.max(2*f.length,g+b.value.length));a.set(f.subarray(0,g)),f=a}f.set(b.value,g),g+=b.value.length;continue}let d=f.slice(0,c.index);if(f.copyWithin(0,c.index+c.length,g),g-=c.index+c.length,f.length>4096&&g<=f.length>>2){let a=new Uint8Array(Math.max(4096,2*g));a.set(f.subarray(0,g)),f=a}h=0;let k=function(a,b,c,d){let e=new TextDecoder().decode(a).split(/\r\n|\r|\n/),f=[],g={},h=!0;for(let a of e){if(!a||a.startsWith(":"))continue;h=!1;let b=a.indexOf(":"),d=a,e="";b>0&&(d=a.slice(0,b),e=" "===a[b+1]?a.slice(b+2):a.slice(b+1)),"data"===d?f.push(e):"event"===d?g.event=e:"id"!==d||e.includes("\0")?"retry"===d&&/^\d+$/.test(e)&&(g.retry=Number(e)):c.eventId=e}if(!h){if(g.id=c.eventId,f.length)g.data=f.join("\n");else if(d)return;return b(g)}}(d,b,i,j);if(k&&!k.done)return a.enqueue(k.value);if(null==k?void 0:k.done)return await e.cancel("done"),a.close()}}catch(b){a.error(b),await e.cancel(b)}},cancel:a=>e.cancel(a)})}[Symbol.asyncIterator](a){let b=ReadableStream.prototype[Symbol.asyncIterator];if("function"==typeof b)return b.call(this,a);let c=this.getReader(),d={next:async()=>{let a=await c.read();return a.done?(c.releaseLock(),{done:!0,value:void 0}):{done:!1,value:a.value}},throw:async a=>(await c.cancel(a),c.releaseLock(),{done:!0,value:void 0}),return:async()=>(await c.cancel("done"),c.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},e=Symbol.asyncDispose;return e&&(d[e]=async()=>{var a;await (null==(a=d.return)?void 0:a.call(d))}),d}values(a){return this[Symbol.asyncIterator](a)}}let fe=[[13,10,13,10],[13,10,13],[13,10,10],[13,13,10],[10,13,10],[13,13],[10,13],[10,10]],ff=fe.reduce((a,b)=>Math.max(a,b.length),0),fg={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function fh(a,b,c){return Object.assign(Object.assign({},c),{err:!0,enc:"json",codes:a,errorClass:b})}function fi(a,b){return Object.assign(Object.assign({},b),{enc:"json",codes:a})}function fj(a,b,c){return Object.assign(Object.assign(Object.assign({},c),{enc:"sse",codes:a}),b?{sse:b}:{})}function fk(a){return{enc:"fail",codes:a}}function fl(...a){return async function(b,c,d){let e,f,g;for(let c of a){let{codes:a}=c,d="ctype"in c?c.ctype:fg[c.enc];if(d&&eT(b,a)&&eR(b,d)||!d&&eT(b,a)){f=c;break}}if(!f)return[{ok:!1,error:new fb("Unexpected Status or Content-Type",{response:b,request:c,body:await b.text().catch(()=>"")})},e];let h=f.enc,i="";switch(h){case"json":i=await b.text();try{e=JSON.parse(i)}catch(a){if(!("err"in f))throw a;e=i}break;case"jsonl":case"stream":e=b.body;break;case"bytes":e=new Uint8Array(await b.arrayBuffer());break;case"text":case"fail":e=i=await b.text();break;case"sse":if(b.body){let a="sse"in f&&f.sse||{};e=function(a,b={}){var c,d;let e=!0===b.flattened,f=null!=(c=b.sentinel)?c:"";return new fd(a,a=>""!==f&&a.data===f?{done:!0,value:void 0}:e?{done:!1,value:null==a.data?void 0:fc(a.data)}:{done:!1,value:Object.assign(Object.assign({},a),{data:null==a.data?a.data:fc(a.data)})},{dataRequired:null==(d=b.dataRequired)||d})}(b.body,a)}else e=null;break;case"nil":i=await b.text(),e=void 0;break;default:throw Error(`Unsupported response type: ${h}`)}if("fail"===f.enc)return[{ok:!1,error:new fb("API error occurred",{request:c,response:b,body:i})},e];let j=f.key||(null==d?void 0:d.resultKey),k=f.hdrs?{headers:function(a){let b={};for(let[c,d]of a.entries())b[c]=d.split(fm);return b}(b.headers)}:null;return(g="err"in f?Object.assign(Object.assign(Object.assign({},null==d?void 0:d.extraFields),k),eE(e)?e:null):j?Object.assign(Object.assign(Object.assign({},null==d?void 0:d.extraFields),k),{[j]:e}):f.hdrs?Object.assign(Object.assign(Object.assign({},null==d?void 0:d.extraFields),k),eE(e)?e:null):e,"err"in f)?[{ok:!1,error:f.errorClass?new f.errorClass(g,{request:c,response:b,body:i}):g},e]:[{ok:!0,value:g},e]}}let fm=/, */;class fn extends Error{constructor(a,b){super(b),this.code=a,this.name="SecurityError"}static incomplete(){return new fn("incomplete","Security requirements not met in order to perform the operation")}static unrecognizedType(a){return new fn("unrecognized_security_type",`Unrecognised security type: ${a}`)}}function fo(a,b){var c,d;return function(...a){let b={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},c=a.find(a=>a.every(a=>{if(null==a.value)return!1;if("http:basic"===a.type)return null!=a.value.username||null!=a.value.password;if("http:custom"===a.type)return null;if("oauth2:password"===a.type)return"string"==typeof a.value&&!!a.value;if("oauth2:client_credentials"===a.type)return"string"==typeof a.value?!!a.value:null!=a.value.client_id||null!=a.value.client_secret;else if("string"==typeof a.value)return!!a.value;else throw Error(`Unrecognized security type: ${a.type} (value type: ${typeof a.value})`)}));return null==c?null:(c.forEach(a=>{if(null==a.value)return;let{type:c}=a;switch(c){case"apiKey:header":b.headers[a.fieldName]=a.value;break;case"apiKey:query":b.queryParams[a.fieldName]=a.value;break;case"apiKey:cookie":b.cookies[a.fieldName]=a.value;break;case"http:basic":var d,e;d=b,null!=(e=a).value&&(d.basic=e.value);break;case"http:custom":case"oauth2:client_credentials":break;case"http:bearer":case"oauth2":case"oauth2:password":case"openIdConnect":!function(a,b){if("string"!=typeof b.value||!b.value)return;let c=b.value;"bearer "!==c.slice(0,7).toLowerCase()&&(c=`Bearer ${c}`),void 0!==b.fieldName&&(a.headers[b.fieldName]=c)}(b,a);break;default:throw fn.unrecognizedType(c)}}),b)}([{fieldName:"apiKey",type:"http:custom",value:null!=(c=null==a?void 0:a.api_key)?c:d_().GOOGLE_GENAI_API_KEY},{fieldName:"accessToken",type:"http:custom",value:null!=(d=null==a?void 0:a.access_token)?d:d_().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"defaultHeaders",type:"http:custom",value:null==a?void 0:a.default_headers}])}async function fp(a){if(null!=a)return"function"==typeof a?a():a}class fq{constructor(a,b){this[bN]="APIPromise",this._promise=a instanceof Promise?a:Promise.resolve(a),this._unwrapped=a instanceof Promise?null:Promise.resolve(a[0]),this._callSource=null!=b?b:null}_getUnwrapped(){var a;return null!=(a=this._unwrapped)?a:this._unwrapped=this._promise.then(([a])=>a)}then(a,b){return this._promise.then(a?([b])=>a(b):void 0,b)}catch(a){return this._getUnwrapped().catch(a)}finally(a){return this._getUnwrapped().finally(a)}$inspect(){return this._promise}asResponse(){var a;return(null!=(a=this._callSource)?a:this._callSource=this._promise.then(([,a])=>a)).then(a=>{if(!a.response)throw Error("APIPromise.asResponse: response unavailable");return a.response})}async withResponse(){let[[a],b]=await Promise.all([this._promise,this.asResponse()]);return{data:a,response:b}}_thenUnwrap(a){var b;let c=this._promise.then(([b,c])=>[a(b),c]);return c.catch(()=>{}),new fq(c,null!=(b=this._callSource)?b:void 0)}}function fr(a){let b=a.$inspect(),c=b.then(([a,b])=>{if(!a.ok)throw a.error;return[a.value,b]}),d=b.then(([a,b])=>{var c;if(!a.ok&&!(null==(c=b.response)?void 0:c.ok))throw a.error;return b});return c.catch(()=>{}),d.catch(()=>{}),new fq(c,d)}async function fs(a,b,c,d){var e,f;let g=eG("body",b,{explode:!0}),h={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"})},i=eB("/{api_version}/agents")(h),j=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),k=fo(await fp(a._options.security)),l={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:k,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},m=a._createRequest(l,{security:k,method:"POST",baseURL:null==d?void 0:d.server_url,path:i,headers:j,body:g,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!m.ok)return[m,{status:"invalid"}];let n=m.value,o=await a._do(n,{context:l,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:l.retry_config,retryCodes:l.retry_codes});if(!o.ok)return[o,{status:"request-error",request:n}];let p=o.value,[q]=await fl(fk("4XX"),fk("5XX"),fi("default"))(p,n);return!q.ok,[q,{status:"complete",request:n,response:p}]}async function ft(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/agents/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"DELETE",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fu(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/agents/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"GET",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fv(a,b,c,d,e,f){var g,h,i;let j={api_version:b,page_size:c,page_token:d,parent:e},k={api_version:eH("api_version",null!=(g=null==j?void 0:j.api_version)?g:a._options.api_version,{explode:!1,charEncoding:"percent"})},l=eB("/{api_version}/agents")(k),m=eN({page_size:null==j?void 0:j.page_size,page_token:null==j?void 0:j.page_token,parent:null==j?void 0:j.parent}),n=new Headers(eD({Accept:"application/json"})),o=fo(await fp(a._options.security)),p={options:a._options,base_url:null!=(i=null!=(h=null==f?void 0:f.server_url)?h:a._baseURL)?i:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:o,security_source:a._options.security,retry_config:(null==f?void 0:f.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==f?void 0:f.retry_codes)||["408","409","429","5XX"]},q=a._createRequest(p,{security:o,method:"GET",baseURL:null==f?void 0:f.server_url,path:l,headers:n,query:m,body:null,userAgent:a._options.user_agent,timeout_ms:(null==f?void 0:f.timeout_ms)||a._options.timeout_ms||-1},f);if(!q.ok)return[q,{status:"invalid"}];let r=q.value,s=await a._do(r,{context:p,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!s.ok)return[s,{status:"request-error",request:r}];let t=s.value,[u]=await fl(fk("4XX"),fk("5XX"),fi("default"))(t,r);return!u.ok,[u,{status:"complete",request:r,response:t}]}bN=Symbol.toStringTag;class fw extends e6{create(a,b){let{api_version:c}=a;return fr(new fq(fs(this,c5(a,["api_version"]),c,b)))}list(a,b){var c,d,e;return fr((c=null==a?void 0:a.api_version,d=null==a?void 0:a.page_size,e=null==a?void 0:a.page_token,new fq(fv(this,c,d,e,null==a?void 0:a.parent,b))))}get(a,b,c){return fr(new fq(fu(this,a,null==b?void 0:b.api_version,c)))}delete(a,b,c){return fr(new fq(ft(this,a,null==b?void 0:b.api_version,c)))}}async function fx(a,b,c,d){var e,f;let g=eG("body",b,{explode:!0}),h={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"})},i=eB("/{api_version}/environments")(h),j=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),k=fo(await fp(a._options.security)),l={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:k,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},m=a._createRequest(l,{security:k,method:"POST",baseURL:null==d?void 0:d.server_url,path:i,headers:j,body:g,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!m.ok)return[m,{status:"invalid"}];let n=m.value,o=await a._do(n,{context:l,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:l.retry_config,retryCodes:l.retry_codes});if(!o.ok)return[o,{status:"request-error",request:n}];let p=o.value,[q]=await fl(fk("4XX"),fk("5XX"),fi("default"))(p,n);return!q.ok,[q,{status:"complete",request:n,response:p}]}async function fy(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/environments/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"DELETE",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fz(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/environments/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"GET",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fA(a,b,c,d,e){var f,g,h;let i={api_version:b,page_size:c,page_token:d},j={api_version:eH("api_version",null!=(f=null==i?void 0:i.api_version)?f:a._options.api_version,{explode:!1,charEncoding:"percent"})},k=eB("/{api_version}/environments")(j),l=eN({page_size:null==i?void 0:i.page_size,page_token:null==i?void 0:i.page_token}),m=new Headers(eD({Accept:"application/json"})),n=fo(await fp(a._options.security)),o={options:a._options,base_url:null!=(h=null!=(g=null==e?void 0:e.server_url)?g:a._baseURL)?h:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:n,security_source:a._options.security,retry_config:(null==e?void 0:e.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==e?void 0:e.retry_codes)||["408","409","429","5XX"]},p=a._createRequest(o,{security:n,method:"GET",baseURL:null==e?void 0:e.server_url,path:k,headers:m,query:l,body:null,userAgent:a._options.user_agent,timeout_ms:(null==e?void 0:e.timeout_ms)||a._options.timeout_ms||-1},e);if(!p.ok)return[p,{status:"invalid"}];let q=p.value,r=await a._do(q,{context:o,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:o.retry_config,retryCodes:o.retry_codes});if(!r.ok)return[r,{status:"request-error",request:q}];let s=r.value,[t]=await fl(fk("4XX"),fk("5XX"),fi("default"))(s,q);return!t.ok,[t,{status:"complete",request:q,response:s}]}class fB extends e6{createEnvironment(a,b,c){return fr(new fq(fx(this,a,b,c)))}listEnvironments(a,b){var c,d;return fr((c=null==a?void 0:a.api_version,d=null==a?void 0:a.page_size,new fq(fA(this,c,d,null==a?void 0:a.page_token,b))))}getEnvironment(a,b,c){return fr(new fq(fz(this,a,null==b?void 0:b.api_version,c)))}deleteEnvironment(a,b,c){return fr(new fq(fy(this,a,null==b?void 0:b.api_version,c)))}}class fC extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="CancelInteractionByIdServerError"}}class fD extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="CancelInteractionByIdClientError"}}class fE extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="CreateInteractionServerError"}}class fF extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="CreateInteractionClientError"}}class fG extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="DeleteInteractionServerError"}}class fH extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="DeleteInteractionClientError"}}class fI extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="GetInteractionByIdServerError"}}class fJ extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="GetInteractionByIdClientError"}}async function fK(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/interactions/{id}/cancel")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"POST",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fi(200),fh("4XX",fD),fh("5XX",fC))(o,m,{extraFields:{httpMeta:{response:o,request:m}}});return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fL(a,b,c,d){var e,f,g,h;let i={body:b,api_version:c},j=eG("body",i.body,{explode:!0}),k={api_version:eH("api_version",null!=(e=i.api_version)?e:a._options.api_version,{explode:!1,charEncoding:"percent"})},l=eB("/{api_version}/interactions")(k),m=new Headers(eD({"Content-Type":"application/json",Accept:(null==(f=null==i?void 0:i.body)?void 0:f.stream)?"text/event-stream":"application/json"})),n=fo(await fp(a._options.security)),o={options:a._options,base_url:null!=(h=null!=(g=null==d?void 0:d.server_url)?g:a._baseURL)?h:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:n,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},p=a._createRequest(o,{security:n,method:"POST",baseURL:null==d?void 0:d.server_url,path:l,headers:m,body:j,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!p.ok)return[p,{status:"invalid"}];let q=p.value,r=await a._do(q,{context:o,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:o.retry_config,retryCodes:o.retry_codes});if(!r.ok)return[r,{status:"request-error",request:q}];let s=r.value,[t]=await fl(fi(200),fj(200,{sentinel:"[DONE]",flattened:!0}),fh("4XX",fF),fh("5XX",fE))(s,q,{extraFields:{httpMeta:{response:s,request:q}}});return!t.ok,[t,{status:"complete",request:q,response:s}]}async function fM(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/interactions/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"DELETE",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(Object.assign(Object.assign({},void 0),{enc:"nil",codes:200}),fh("4XX",fH),fh("5XX",fG))(o,m,{extraFields:{httpMeta:{response:o,request:m}}});return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fN(a,b,c,d,e,f,g){var h,i,j;let k={id:b,stream:c,last_event_id:d,include_input:e,api_version:f},l={api_version:eH("api_version",null!=(h=k.api_version)?h:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",k.id,{explode:!1,charEncoding:"percent"})},m=eB("/{api_version}/interactions/{id}")(l),n=eN({include_input:k.include_input,last_event_id:k.last_event_id,stream:k.stream}),o=new Headers(eD({Accept:(null==k?void 0:k.stream)?"text/event-stream":"application/json"})),p=fo(await fp(a._options.security)),q={options:a._options,base_url:null!=(j=null!=(i=null==g?void 0:g.server_url)?i:a._baseURL)?j:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:p,security_source:a._options.security,retry_config:(null==g?void 0:g.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==g?void 0:g.retry_codes)||["408","409","429","5XX"]},r=a._createRequest(q,{security:p,method:"GET",baseURL:null==g?void 0:g.server_url,path:m,headers:o,query:n,body:null,userAgent:a._options.user_agent,timeout_ms:(null==g?void 0:g.timeout_ms)||a._options.timeout_ms||-1},g);if(!r.ok)return[r,{status:"invalid"}];let s=r.value,t=await a._do(s,{context:q,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:q.retry_config,retryCodes:q.retry_codes});if(!t.ok)return[t,{status:"request-error",request:s}];let u=t.value,[v]=await fl(fi(200),fj(200,{sentinel:"[DONE]",flattened:!0}),fh("4XX",fJ),fh("5XX",fI))(u,s,{extraFields:{httpMeta:{response:u,request:s}}});return!v.ok,[v,{status:"complete",request:s,response:u}]}class fO extends e6{create(a,b){let{api_version:c}=a;return fr(new fq(fL(this,c5(a,["api_version"]),c,b)))}get(a,b,c){var d,e,f;return fr((d=null==b?void 0:b.stream,e=null==b?void 0:b.last_event_id,f=null==b?void 0:b.include_input,new fq(fN(this,a,d,e,f,null==b?void 0:b.api_version,c))))}delete(a,b,c){return fr(new fq(fM(this,a,null==b?void 0:b.api_version,c)))}cancel(a,b,c){return fr(new fq(fK(this,a,null==b?void 0:b.api_version,c)))}}async function fP(a,b,c,d){var e,f;let g=eG("body",b,{explode:!0}),h={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"})},i=eB("/{api_version}/triggers")(h),j=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),k=fo(await fp(a._options.security)),l={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:k,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},m=a._createRequest(l,{security:k,method:"POST",baseURL:null==d?void 0:d.server_url,path:i,headers:j,body:g,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!m.ok)return[m,{status:"invalid"}];let n=m.value,o=await a._do(n,{context:l,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:l.retry_config,retryCodes:l.retry_codes});if(!o.ok)return[o,{status:"request-error",request:n}];let p=o.value,[q]=await fl(fi(200),fk("4XX"),fk("5XX"))(p,n);return!q.ok,[q,{status:"complete",request:n,response:p}]}async function fQ(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/triggers/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"DELETE",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fi(200),fk("4XX"),fk("5XX"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fR(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/triggers/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"GET",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fi(200),fk("4XX"),fk("5XX"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fS(a,b,c,d,e,f){var g,h;let i={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:eH("trigger_id",b,{explode:!1,charEncoding:"percent"})},j=eB("/{api_version}/triggers/{trigger_id}/executions")(i),k=eN({page_size:d,page_token:e}),l=new Headers(eD({Accept:"application/json"})),m=fo(await fp(a._options.security)),n={options:a._options,base_url:null!=(h=null!=(g=null==f?void 0:f.server_url)?g:a._baseURL)?h:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:m,security_source:a._options.security,retry_config:(null==f?void 0:f.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==f?void 0:f.retry_codes)||["408","409","429","5XX"]},o=a._createRequest(n,{security:m,method:"GET",baseURL:null==f?void 0:f.server_url,path:j,headers:l,query:k,body:null,userAgent:a._options.user_agent,timeout_ms:(null==f?void 0:f.timeout_ms)||a._options.timeout_ms||-1},f);if(!o.ok)return[o,{status:"invalid"}];let p=o.value,q=await a._do(p,{context:n,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:n.retry_config,retryCodes:n.retry_codes});if(!q.ok)return[q,{status:"request-error",request:p}];let r=q.value,[s]=await fl(fi(200),fk("4XX"),fk("5XX"))(r,p);return!s.ok,[s,{status:"complete",request:p,response:r}]}async function fT(a,b,c,d,e,f){var g,h,i;let j={api_version:b,filter:c,page_size:d,page_token:e},k={api_version:eH("api_version",null!=(g=null==j?void 0:j.api_version)?g:a._options.api_version,{explode:!1,charEncoding:"percent"})},l=eB("/{api_version}/triggers")(k),m=eN({filter:null==j?void 0:j.filter,page_size:null==j?void 0:j.page_size,page_token:null==j?void 0:j.page_token}),n=new Headers(eD({Accept:"application/json"})),o=fo(await fp(a._options.security)),p={options:a._options,base_url:null!=(i=null!=(h=null==f?void 0:f.server_url)?h:a._baseURL)?i:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:o,security_source:a._options.security,retry_config:(null==f?void 0:f.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==f?void 0:f.retry_codes)||["408","409","429","5XX"]},q=a._createRequest(p,{security:o,method:"GET",baseURL:null==f?void 0:f.server_url,path:l,headers:n,query:m,body:null,userAgent:a._options.user_agent,timeout_ms:(null==f?void 0:f.timeout_ms)||a._options.timeout_ms||-1},f);if(!q.ok)return[q,{status:"invalid"}];let r=q.value,s=await a._do(r,{context:p,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!s.ok)return[s,{status:"request-error",request:r}];let t=s.value,[u]=await fl(fi(200),fk("4XX"),fk("5XX"))(t,r);return!u.ok,[u,{status:"complete",request:r,response:t}]}async function fU(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:eH("trigger_id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/triggers/{trigger_id}/executions")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"POST",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fi(200),fk("4XX"),fk("5XX"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fV(a,b,c,d,e){var f,g;let h=eG("body",c,{explode:!0}),i={api_version:eH("api_version",null!=d?d:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},j=eB("/{api_version}/triggers/{id}")(i),k=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),l=fo(await fp(a._options.security)),m={options:a._options,base_url:null!=(g=null!=(f=null==e?void 0:e.server_url)?f:a._baseURL)?g:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:l,security_source:a._options.security,retry_config:(null==e?void 0:e.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==e?void 0:e.retry_codes)||["408","409","429","5XX"]},n=a._createRequest(m,{security:l,method:"PATCH",baseURL:null==e?void 0:e.server_url,path:j,headers:k,body:h,userAgent:a._options.user_agent,timeout_ms:(null==e?void 0:e.timeout_ms)||a._options.timeout_ms||-1},e);if(!n.ok)return[n,{status:"invalid"}];let o=n.value,p=await a._do(o,{context:m,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!p.ok)return[p,{status:"request-error",request:o}];let q=p.value,[r]=await fl(fi(200),fk("4XX"),fk("5XX"))(q,o);return!r.ok,[r,{status:"complete",request:o,response:q}]}class fW extends e6{create(a,b){let{api_version:c}=a;return fr(new fq(fP(this,c5(a,["api_version"]),c,b)))}list(a,b){var c,d,e;return fr((c=null==a?void 0:a.api_version,d=null==a?void 0:a.filter,e=null==a?void 0:a.page_size,new fq(fT(this,c,d,e,null==a?void 0:a.page_token,b))))}get(a,b,c){return fr(new fq(fR(this,a,null==b?void 0:b.api_version,c)))}update(a,b,c){let{api_version:d}=b;return fr(new fq(fV(this,a,c5(b,["api_version"]),d,c)))}delete(a,b,c){return fr(new fq(fQ(this,a,null==b?void 0:b.api_version,c)))}run(a,b,c){return fr(new fq(fU(this,a,null==b?void 0:b.api_version,c)))}listExecutions(a,b,c){var d,e;return fr((d=null==b?void 0:b.api_version,e=null==b?void 0:b.page_size,new fq(fS(this,a,d,e,null==b?void 0:b.page_token,c))))}}async function fX(a,b,c,d){var e,f;let g=eG("body",b,{explode:!0}),h={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"})},i=eB("/{api_version}/webhooks")(h),j=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),k=fo(await fp(a._options.security)),l={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:k,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},m=a._createRequest(l,{security:k,method:"POST",baseURL:null==d?void 0:d.server_url,path:i,headers:j,body:g,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!m.ok)return[m,{status:"invalid"}];let n=m.value,o=await a._do(n,{context:l,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:l.retry_config,retryCodes:l.retry_codes});if(!o.ok)return[o,{status:"request-error",request:n}];let p=o.value,[q]=await fl(fk("4XX"),fk("5XX"),fi("default"))(p,n);return!q.ok,[q,{status:"complete",request:n,response:p}]}async function fY(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/webhooks/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"DELETE",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fZ(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/webhooks/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"GET",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function f$(a,b,c,d,e){var f,g,h;let i={api_version:b,page_size:c,page_token:d},j={api_version:eH("api_version",null!=(f=null==i?void 0:i.api_version)?f:a._options.api_version,{explode:!1,charEncoding:"percent"})},k=eB("/{api_version}/webhooks")(j),l=eN({page_size:null==i?void 0:i.page_size,page_token:null==i?void 0:i.page_token}),m=new Headers(eD({Accept:"application/json"})),n=fo(await fp(a._options.security)),o={options:a._options,base_url:null!=(h=null!=(g=null==e?void 0:e.server_url)?g:a._baseURL)?h:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:n,security_source:a._options.security,retry_config:(null==e?void 0:e.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==e?void 0:e.retry_codes)||["408","409","429","5XX"]},p=a._createRequest(o,{security:n,method:"GET",baseURL:null==e?void 0:e.server_url,path:k,headers:m,query:l,body:null,userAgent:a._options.user_agent,timeout_ms:(null==e?void 0:e.timeout_ms)||a._options.timeout_ms||-1},e);if(!p.ok)return[p,{status:"invalid"}];let q=p.value,r=await a._do(q,{context:o,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:o.retry_config,retryCodes:o.retry_codes});if(!r.ok)return[r,{status:"request-error",request:q}];let s=r.value,[t]=await fl(fk("4XX"),fk("5XX"),fi("default"))(s,q);return!t.ok,[t,{status:"complete",request:q,response:s}]}async function f_(a,b,c,d,e){var f,g;let h=eG("body",d,{explode:!0}),i={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},j=eB("/{api_version}/webhooks/{id}:ping")(i),k=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),l=fo(await fp(a._options.security)),m={options:a._options,base_url:null!=(g=null!=(f=null==e?void 0:e.server_url)?f:a._baseURL)?g:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:l,security_source:a._options.security,retry_config:(null==e?void 0:e.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==e?void 0:e.retry_codes)||["408","409","429","5XX"]},n=a._createRequest(m,{security:l,method:"POST",baseURL:null==e?void 0:e.server_url,path:j,headers:k,body:h,userAgent:a._options.user_agent,timeout_ms:(null==e?void 0:e.timeout_ms)||a._options.timeout_ms||-1},e);if(!n.ok)return[n,{status:"invalid"}];let o=n.value,p=await a._do(o,{context:m,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!p.ok)return[p,{status:"request-error",request:o}];let q=p.value,[r]=await fl(fk("4XX"),fk("5XX"),fi("default"))(q,o);return!r.ok,[r,{status:"complete",request:o,response:q}]}async function f0(a,b,c,d,e){var f,g;let h=eG("body",d,{explode:!0}),i={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},j=eB("/{api_version}/webhooks/{id}:rotateSigningSecret")(i),k=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),l=fo(await fp(a._options.security)),m={options:a._options,base_url:null!=(g=null!=(f=null==e?void 0:e.server_url)?f:a._baseURL)?g:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:l,security_source:a._options.security,retry_config:(null==e?void 0:e.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==e?void 0:e.retry_codes)||["408","409","429","5XX"]},n=a._createRequest(m,{security:l,method:"POST",baseURL:null==e?void 0:e.server_url,path:j,headers:k,body:h,userAgent:a._options.user_agent,timeout_ms:(null==e?void 0:e.timeout_ms)||a._options.timeout_ms||-1},e);if(!n.ok)return[n,{status:"invalid"}];let o=n.value,p=await a._do(o,{context:m,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!p.ok)return[p,{status:"request-error",request:o}];let q=p.value,[r]=await fl(fk("4XX"),fk("5XX"),fi("default"))(q,o);return!r.ok,[r,{status:"complete",request:o,response:q}]}async function f1(a,b,c,d,e,f){var g,h;let i=eG("body",e,{explode:!0}),j={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},k=eB("/{api_version}/webhooks/{id}")(j),l=eN({update_mask:d}),m=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),n=fo(await fp(a._options.security)),o={options:a._options,base_url:null!=(h=null!=(g=null==f?void 0:f.server_url)?g:a._baseURL)?h:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:n,security_source:a._options.security,retry_config:(null==f?void 0:f.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==f?void 0:f.retry_codes)||["408","409","429","5XX"]},p=a._createRequest(o,{security:n,method:"PATCH",baseURL:null==f?void 0:f.server_url,path:k,headers:m,query:l,body:i,userAgent:a._options.user_agent,timeout_ms:(null==f?void 0:f.timeout_ms)||a._options.timeout_ms||-1},f);if(!p.ok)return[p,{status:"invalid"}];let q=p.value,r=await a._do(q,{context:o,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:o.retry_config,retryCodes:o.retry_codes});if(!r.ok)return[r,{status:"request-error",request:q}];let s=r.value,[t]=await fl(fk("4XX"),fk("5XX"),fi("default"))(s,q);return!t.ok,[t,{status:"complete",request:q,response:s}]}class f2 extends e6{create(a,b){let{api_version:c}=a;return fr(new fq(fX(this,c5(a,["api_version"]),c,b)))}list(a,b){var c,d;return fr((c=null==a?void 0:a.api_version,d=null==a?void 0:a.page_size,new fq(f$(this,c,d,null==a?void 0:a.page_token,b))))}get(a,b,c){return fr(new fq(fZ(this,a,null==b?void 0:b.api_version,c)))}update(a,b,c){let d=null!=b?b:{},{api_version:e,update_mask:f}=d,g=c5(d,["api_version","update_mask"]);return fr(new fq(f1(this,a,e,f,void 0===b||0===Object.keys(g).length?void 0:g,c)))}delete(a,b,c){return fr(new fq(fY(this,a,null==b?void 0:b.api_version,c)))}rotateSigningSecret(a,b,c,d){return fr(new fq(f0(this,a,b,c,d)))}ping(a,b,c,d){return fr(new fq(f_(this,a,b,c,d)))}}let f3=class extends e6{get interactions(){var a;return null!=(a=this._interactions)?a:this._interactions=new fO(this._options)}get webhooks(){var a;return null!=(a=this._webhooks)?a:this._webhooks=new f2(this._options)}get agents(){var a;return null!=(a=this._agents)?a:this._agents=new fw(this._options)}get triggers(){var a;return null!=(a=this._triggers)?a:this._triggers=new fW(this._options)}get environments(){var a;return null!=(a=this._environments)?a:this._environments=new fB(this._options)}},f4=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function f5(a,b={}){var c,d,e,f,g;let h,i,j;return new f3(Object.assign(Object.assign({},b),{api_version:null!=(c=b.api_version)?c:(h=a.getApiVersion().replace(/^\/+|\/+$/g,""),i=a.getProject(),j=a.getLocation(),a.isVertexAI()&&h&&i&&j?`${h}/projects/${encodeURIComponent(i)}/locations/${encodeURIComponent(j)}`:h),security:null!=(d=b.security)?d:new d0({defaultHeaders:Object.assign(Object.assign({},null==(e=a.getDefaultHeaders)?void 0:e.call(a)),null==(f=a.getHeaders)?void 0:f.call(a)),getAuthHeaders:b=>a.getAuthHeaders(b)}),server_url:null!=(g=b.server_url)?g:function(a){let b=a.getBaseUrl();if(!b)throw Error("Base URL must be set.");return b.replace(/\/+$/,"")}(a)}))}class f6{constructor(a){this.parentClient=a}async create(a,b){let{api_version:c}=a,d=c5(a,["api_version"]);return!0===d.stream?ge(await gd(()=>this.getClient(c).interactions.create(Object.assign(Object.assign({},d),{stream:!0,api_version:c}),ga(b,!0)))):gf(await gc(new fq(fL(this.getClient(c),d,c,ga(b)))))}async get(a,b={},c){let{api_version:d,stream:e=!1,last_event_id:f,include_input:g}=null!=b?b:{};return!0===e?ge(await gd(()=>this.getClient(d).interactions.get(a,{stream:e,last_event_id:f,include_input:g,api_version:d},ga(c,!0)))):gf(await gc(new fq(fN(this.getClient(d),a,e,f,g,d,ga(c)))))}async delete(a,b={},c){return gd(()=>this.getClient(null==b?void 0:b.api_version).interactions.delete(a,{api_version:null==b?void 0:b.api_version},ga(c)))}async cancel(a,b={},c){var d;return gf(await gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fK(d,a,null==b?void 0:b.api_version,ga(c))))))}getClient(a){return a?f5(this.parentClient,{api_version:a}):(null!=this.sdk||(this.sdk=f5(this.parentClient)),this.sdk)}}class f7{constructor(a){this.parentClient=a}async create(a={},b){let c=null!=a?a:{},{api_version:d}=c,e=c5(c,["api_version"]);return gc(new fq(fs(this.getClient(d),e,d,ga(b))))}async list(a={},b){let{api_version:c,pageSize:d,pageToken:e,parent:f}=null!=a?a:{};return gc(new fq(fv(this.getClient(c),c,d,e,f,ga(b))))}async get(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fu(d,a,null==b?void 0:b.api_version,ga(c)))))}async delete(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(ft(d,a,null==b?void 0:b.api_version,ga(c)))))}getClient(a){return a?f5(this.parentClient,{api_version:a}):(null!=this.sdk||(this.sdk=f5(this.parentClient)),this.sdk)}}class f8{constructor(a){this.parentClient=a}async create(a,b){let{api_version:c}=a,d=c5(a,["api_version"]);return gc(new fq(fX(this.getClient(),d,c,ga(b))))}async list(a={},b){let{api_version:c,page_size:d,page_token:e}=null!=a?a:{};return gc(new fq(f$(this.getClient(),c,d,e,ga(b))))}async get(a,b={},c){var d;return gc((d=this.getClient(),new fq(fZ(d,a,null==b?void 0:b.api_version,ga(c)))))}async update(a,b={},c){let d=null!=b?b:{},{api_version:e,update_mask:f}=d,g=c5(d,["api_version","update_mask"]);return gc(new fq(f1(this.getClient(),a,e,f,g,ga(c))))}async delete(a,b={},c){var d;return gc((d=this.getClient(),new fq(fY(d,a,null==b?void 0:b.api_version,ga(c)))))}async rotateSigningSecret(a,b={},c){let d=null!=b?b:{},{api_version:e}=d,f=c5(d,["api_version"]);return gc(new fq(f0(this.getClient(),a,e,f,ga(c))))}async ping(a,b,c){let{api_version:d,body:e}=null!=b?b:{};return gc(new fq(f_(this.getClient(),a,d,e,ga(c))))}getClient(){return null!=this.sdk||(this.sdk=f5(this.parentClient)),this.sdk}}class f9{constructor(a){this.parentClient=a}async create(a,b){let{api_version:c}=a,d=c5(a,["api_version"]);return gc(new fq(fP(this.getClient(c),d,c,ga(b))))}async list(a={},b){let{api_version:c,filter:d,pageSize:e,pageToken:f}=null!=a?a:{};return gc(new fq(fT(this.getClient(c),c,d,e,f,ga(b))))}async get(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fR(d,a,null==b?void 0:b.api_version,ga(c)))))}async update(a,b,c){let{api_version:d}=b,e=c5(b,["api_version"]);return gc(new fq(fV(this.getClient(d),a,e,d,ga(c))))}async delete(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fQ(d,a,null==b?void 0:b.api_version,ga(c)))))}async run(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fU(d,a,null==b?void 0:b.api_version,ga(c)))))}async listExecutions(a,b={},c){let{api_version:d,pageSize:e,pageToken:f}=null!=b?b:{};return gc(new fq(fS(this.getClient(d),a,d,e,f,ga(c))))}getClient(a){return a?f5(this.parentClient,{api_version:a}):(null!=this.sdk||(this.sdk=f5(this.parentClient)),this.sdk)}}function ga(a,b=!1){var c,d,e,f;if(!a&&!b)return;let g=null!=a?a:{},{timeout:h,maxRetries:i,defaultBaseURL:j,query:k,body:l,fetchOptions:m}=g,n=c5(g,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),o=Object.assign({},n);gg(k)?o.extra_query=k:gb("query",k),gg(l)?o.extra_body=l:gb("body",l);let p=null!=(c=n.fetch_options)?c:m;p&&(o.fetch_options=p);let q=null!=(d=n.server_url)?d:j;q&&(o.server_url=q);let r=null!=(e=n.timeout_ms)?e:h;if(void 0!==r&&(o.timeout_ms=r),void 0!==i&&(o.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:i}),b){let a=new Headers(null!=(f=o.headers)?f:null==p?void 0:p.headers);a.set("Accept","text/event-stream"),o.headers=a}return o}function gb(a,b){null!=b&&console.warn(`GoogleGenAI.interactions: request option ${a} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function gc(a){var b,c;let[d,e]=await a.$inspect();if(!d.ok)throw es(d.error);return b=d.value,c=e,gg(b)&&"complete"===c.status?Object.assign(Object.assign({},b),{sdkHttpResponse:function(a,b){let c={};for(let[b,d]of a.headers.entries())c[b]=d;return{headers:c,responseInternal:a,json:async()=>b}}(c.response,b)}):b}async function gd(a){try{return await a()}catch(a){throw es(a)}}function ge(a){return new Proxy(a,{get(b,c){if(c!==Symbol.asyncIterator){let a=Reflect.get(b,c,b);return"function"==typeof a?a.bind(b):a}return function(){let b=a[Symbol.asyncIterator]();return{async next(...a){try{return await b.next(...a)}catch(a){throw es(a)}},async return(a){if(!b.return)return{done:!0,value:a};try{return await b.return(a)}catch(a){throw es(a)}},async throw(a){if(!b.throw)throw es(a);try{return await b.throw(a)}catch(a){throw es(a)}},[Symbol.asyncIterator](){return this}}}}})}function gf(a){let b=function(a){if(gg(a)){let b;if(Array.isArray(a.steps))return a;if("string"==typeof(b=a.model)&&f4.has(b)){let b=a.outputs;if(Array.isArray(b)){let{outputs:c}=a;return Object.assign(Object.assign({},c5(a,["outputs"])),{steps:[{type:"model_output",content:b}]})}}return Object.assign(Object.assign({},a),{steps:[]})}}(a);return b?function(a){var b,c,d;let e,f,g,h=Object.assign(Object.assign({},d=a),{created:gh(d.created),updated:gh(d.updated)}),i=null!=(b=h.steps)?b:[],j=[],k=!1;b:for(let a=i.length-1;a>=0;a--){let b=i[a];if("user_input"===b.type)break;if("model_output"!==b.type||!b.content){if(k)break;continue}let d=b.content;for(let a=d.length-1;a>=0;a--){let b=d[a];if("text"===b.type)k=!0,j.push(null!=(c=b.text)?c:"");else if(k)break b}}for(let a=i.length-1;a>=0;a--){let b=i[a];if("user_input"===b.type)break;if("model_output"===b.type&&b.content)for(let a=b.content.length-1;a>=0;a--){let c=b.content[a];"image"!==c.type||e||(e=c),"audio"!==c.type||f||(f=c),"video"!==c.type||g||(g=c)}}let l=j.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},h),l&&{output_text:l}),e?{output_image:e}:{}),f?{output_audio:f}:{}),g?{output_video:g}:{})}(b):a}function gg(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function gh(a){return a instanceof Date?a.toISOString():a}class gi{constructor(a){this.parentClient=a}async create(a,b){let{api_version:c}=a,d=c5(a,["api_version"]);return gc(new fq(fx(this.getClient(c),d,c,ga(b))))}async list(a={},b){let{api_version:c,page_size:d,page_token:e}=null!=a?a:{};return gc(new fq(fA(this.getClient(c),c,d,e,ga(b))))}async get(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fz(d,a,null==b?void 0:b.api_version,ga(c)))))}async delete(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fy(d,a,null==b?void 0:b.api_version,ga(c)))))}getClient(a){return a?f5(this.parentClient,{api_version:a}):(null!=this.sdk||(this.sdk=f5(this.parentClient)),this.sdk)}}let gj="x-goog-api-key",gk="https://www.googleapis.com/auth/cloud-platform";class gl{constructor(a){if(void 0!==a.apiKey){this.apiKey=a.apiKey;return}const b=function(a){let b;if(!a)return{scopes:[gk]};if((b=a).scopes){if("string"==typeof b.scopes&&b.scopes!==gk||Array.isArray(b.scopes)&&0>b.scopes.indexOf(gk))throw Error(`Invalid auth scopes. Scopes must include: ${gk}`)}else b.scopes=[gk];return b}(a.googleAuthOptions);this.googleAuth=new bP.GoogleAuth(b)}async addAuthHeaders(a,b){if(void 0!==this.apiKey){if(this.apiKey.startsWith("auth_tokens/"))throw Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(a);return}return this.addGoogleAuthHeaders(a,b)}addKeyHeader(a){if(null===a.get(gj)){if(void 0===this.apiKey)throw Error("Trying to set API key header but apiKey is not set");a.append(gj,this.apiKey)}}async addGoogleAuthHeaders(a,b){if(void 0===this.googleAuth)throw Error("Trying to set google-auth headers but googleAuth is unset");for(let[c,d]of(await this.googleAuth.getRequestHeaders(b)))null===a.get(c)&&a.append(c,d)}}class gm{async download(a,b){if(a.downloadPath){let c=await gn(a,b);if(c instanceof b0){let b=(0,bQ.createWriteStream)(a.downloadPath);bS.Readable.fromWeb(c.responseInternal.body).pipe(b),await (0,bT.finished)(b)}else try{await (0,bR.writeFile)(a.downloadPath,c,{encoding:"base64"})}catch(b){throw Error(`Failed to write file to ${a.downloadPath}: ${b}`)}}}}async function gn(a,b){var c,d,e;let f=cR(a.file);if(void 0!==f)return await b.request({path:`files/${f}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:null==(c=a.config)?void 0:c.httpOptions,abortSignal:null==(d=a.config)?void 0:d.abortSignal});if(cP(a.file)){let b=null==(e=a.file.video)?void 0:e.videoBytes;if("string"==typeof b)return b;throw Error("Failed to download generated video, Uri or videoBytes not found.")}if(cQ(a.file)){let b=a.file.videoBytes;if("string"==typeof b)return b;throw Error("Failed to download video, Uri or videoBytes not found.")}throw Error("Unsupported file type")}class go{create(a,b,c){return new gp(a,b,c)}}class gp{constructor(a,b,c){this.url=a,this.headers=b,this.callbacks=c}connect(){this.ws=new bU(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(a){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.send(a)}close(){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.close()}}function gq(a,b){let c={},d=bZ(a,["parts"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["mediaResolution"]);if(null!=c&&bY(b,["mediaResolution"],c),void 0!==bZ(a,["toolCall"]))throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["toolResponse"]))throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let d=bZ(a,["audioTranscription"]);null!=d&&bY(b,["audioTranscription"],d);let e=bZ(a,["codeExecutionResult"]);null!=e&&bY(b,["codeExecutionResult"],function(a){let b={},c=bZ(a,["outcome"]);null!=c&&bY(b,["outcome"],c);let d=bZ(a,["output"]);if(null!=d&&bY(b,["output"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(e));let f=bZ(a,["executableCode"]);null!=f&&bY(b,["executableCode"],function(a){let b={},c=bZ(a,["code"]);null!=c&&bY(b,["code"],c);let d=bZ(a,["language"]);if(null!=d&&bY(b,["language"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(f));let g=bZ(a,["fileData"]);null!=g&&bY(b,["fileData"],g);let h=bZ(a,["functionCall"]);null!=h&&bY(b,["functionCall"],h);let i=bZ(a,["functionResponse"]);null!=i&&bY(b,["functionResponse"],i);let j=bZ(a,["inlineData"]);null!=j&&bY(b,["inlineData"],j);let k=bZ(a,["text"]);null!=k&&bY(b,["text"],k);let l=bZ(a,["thought"]);null!=l&&bY(b,["thought"],l);let m=bZ(a,["thoughtSignature"]);null!=m&&bY(b,["thoughtSignature"],m);let n=bZ(a,["videoMetadata"]);if(null!=n&&bY(b,["videoMetadata"],n),void 0!==bZ(a,["partMetadata"]))throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(a))),bY(c,["parts"],a)}let e=bZ(a,["role"]);return null!=e&&bY(c,["role"],e),c}function gr(a,b){let c={},d=bZ(a,["epochCount"]);null!=d&&bY(c,["epochCount"],d);let e=bZ(a,["learningRateMultiplier"]);null!=e&&bY(c,["learningRateMultiplier"],e);let f=bZ(a,["adapterSize"]);null!=f&&bY(c,["adapterSize"],f);let g=bZ(a,["batchSize"]);null!=g&&bY(c,["batchSize"],g);let h=bZ(a,["learningRate"]);null!=h&&bY(c,["learningRate"],h);let i=bZ(a,["generationConfig"]);return null!=i&&bY(c,["generationConfig"],function(a){let b={},c=bZ(a,["modelConfig"]);null!=c&&bY(b,["modelSelectionConfig"],c);let d=bZ(a,["responseJsonSchema"]);null!=d&&bY(b,["responseJsonSchema"],d);let e=bZ(a,["audioTranscriptionConfig"]);null!=e&&bY(b,["audioTranscriptionConfig"],e);let f=bZ(a,["audioTimestamp"]);null!=f&&bY(b,["audioTimestamp"],f);let g=bZ(a,["candidateCount"]);null!=g&&bY(b,["candidateCount"],g);let h=bZ(a,["enableAffectiveDialog"]);null!=h&&bY(b,["enableAffectiveDialog"],h);let i=bZ(a,["frequencyPenalty"]);null!=i&&bY(b,["frequencyPenalty"],i);let j=bZ(a,["logprobs"]);null!=j&&bY(b,["logprobs"],j);let k=bZ(a,["maxOutputTokens"]);null!=k&&bY(b,["maxOutputTokens"],k);let l=bZ(a,["mediaResolution"]);null!=l&&bY(b,["mediaResolution"],l);let m=bZ(a,["presencePenalty"]);null!=m&&bY(b,["presencePenalty"],m);let n=bZ(a,["responseFormat"]);if(null!=n){let a=n;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["responseFormat"],a)}let o=bZ(a,["responseLogprobs"]);null!=o&&bY(b,["responseLogprobs"],o);let p=bZ(a,["responseMimeType"]);null!=p&&bY(b,["responseMimeType"],p);let q=bZ(a,["responseModalities"]);null!=q&&bY(b,["responseModalities"],q);let r=bZ(a,["responseSchema"]);null!=r&&bY(b,["responseSchema"],r);let s=bZ(a,["routingConfig"]);null!=s&&bY(b,["routingConfig"],s);let t=bZ(a,["seed"]);null!=t&&bY(b,["seed"],t);let u=bZ(a,["speechConfig"]);null!=u&&bY(b,["speechConfig"],u);let v=bZ(a,["stopSequences"]);null!=v&&bY(b,["stopSequences"],v);let w=bZ(a,["temperature"]);null!=w&&bY(b,["temperature"],w);let x=bZ(a,["thinkingConfig"]);null!=x&&bY(b,["thinkingConfig"],x);let y=bZ(a,["topK"]);null!=y&&bY(b,["topK"],y);let z=bZ(a,["topP"]);return null!=z&&bY(b,["topP"],z),b}(i)),c}function gs(a,b){let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s={},t=bZ(a,["sdkHttpResponse"]);null!=t&&bY(s,["sdkHttpResponse"],t);let u=bZ(a,["name"]);null!=u&&bY(s,["name"],u);let v=bZ(a,["state"]);null!=v&&bY(s,["state"],cO(v));let w=bZ(a,["createTime"]);null!=w&&bY(s,["createTime"],w);let x=bZ(a,["startTime"]);null!=x&&bY(s,["startTime"],x);let y=bZ(a,["endTime"]);null!=y&&bY(s,["endTime"],y);let z=bZ(a,["updateTime"]);null!=z&&bY(s,["updateTime"],z);let A=bZ(a,["error"]);null!=A&&bY(s,["error"],A);let B=bZ(a,["description"]);null!=B&&bY(s,["description"],B);let C=bZ(a,["baseModel"]);null!=C&&bY(s,["baseModel"],C);let D=bZ(a,["tunedModel"]);null!=D&&bY(s,["tunedModel"],D);let E=bZ(a,["preTunedModel"]);null!=E&&bY(s,["preTunedModel"],E);let F=bZ(a,["supervisedTuningSpec"]);null!=F&&bY(s,["supervisedTuningSpec"],F);let G=bZ(a,["preferenceOptimizationSpec"]);null!=G&&bY(s,["preferenceOptimizationSpec"],G);let H=bZ(a,["distillationSamplingSpec"]);null!=H&&bY(s,["distillationSamplingSpec"],(c={},null!=(d=bZ(H,["promptDatasetUri"]))&&bY(c,["promptDatasetUri"],d),null!=(e=bZ(H,["validationDatasetUri"]))&&bY(c,["validationDatasetUri"],e),null!=(f=bZ(H,["baseTeacherModel"]))&&bY(c,["baseTeacherModel"],f),null!=(g=bZ(H,["tunedTeacherModelSource"]))&&bY(c,["tunedTeacherModelSource"],g),null!=(h=bZ(H,["hyperparameters"]))&&bY(c,["hyperparameters"],gr(h)),c));let I=bZ(a,["distillationSpec"]);null!=I&&bY(s,["distillationSpec"],(i={},null!=(j=bZ(I,["baseTeacherModel"]))&&bY(i,["baseTeacherModel"],j),null!=(k=bZ(I,["hyperParameters"]))&&bY(i,["hyperParameters"],gr(k)),null!=(l=bZ(I,["pipelineRootDirectory"]))&&bY(i,["pipelineRootDirectory"],l),null!=(m=bZ(I,["promptDatasetUri"]))&&bY(i,["promptDatasetUri"],m),null!=(n=bZ(I,["studentModel"]))&&bY(i,["studentModel"],n),null!=(o=bZ(I,["trainingDatasetUri"]))&&bY(i,["trainingDatasetUri"],o),null!=(p=bZ(I,["tunedTeacherModelSource"]))&&bY(i,["tunedTeacherModelSource"],p),null!=(q=bZ(I,["tuningMode"]))&&bY(i,["tuningMode"],q),null!=(r=bZ(I,["validationDatasetUri"]))&&bY(i,["validationDatasetUri"],r),i));let J=bZ(a,["reinforcementTuningSpec"]);null!=J&&bY(s,["reinforcementTuningSpec"],J);let K=bZ(a,["tuningDataStats"]);null!=K&&bY(s,["tuningDataStats"],K);let L=bZ(a,["encryptionSpec"]);null!=L&&bY(s,["encryptionSpec"],L);let M=bZ(a,["partnerModelTuningSpec"]);null!=M&&bY(s,["partnerModelTuningSpec"],M);let N=bZ(a,["customBaseModel"]);null!=N&&bY(s,["customBaseModel"],N);let O=bZ(a,["evaluateDatasetRuns"]);if(null!=O){let a=O;Array.isArray(a)&&(a=a.map(a=>a)),bY(s,["evaluateDatasetRuns"],a)}let P=bZ(a,["experiment"]);null!=P&&bY(s,["experiment"],P);let Q=bZ(a,["fullFineTuningSpec"]);null!=Q&&bY(s,["fullFineTuningSpec"],Q);let R=bZ(a,["labels"]);null!=R&&bY(s,["labels"],R);let S=bZ(a,["outputUri"]);null!=S&&bY(s,["outputUri"],S);let T=bZ(a,["pipelineJob"]);null!=T&&bY(s,["pipelineJob"],T);let U=bZ(a,["serviceAccount"]);null!=U&&bY(s,["serviceAccount"],U);let V=bZ(a,["tunedModelDisplayName"]);null!=V&&bY(s,["tunedModelDisplayName"],V);let W=bZ(a,["tuningJobMetadata"]);null!=W&&bY(s,["tuningJobMetadata"],W);let X=bZ(a,["tuningJobState"]);null!=X&&bY(s,["tuningJobState"],X);let Y=bZ(a,["veoLoraTuningSpec"]);null!=Y&&bY(s,["veoLoraTuningSpec"],Y);let Z=bZ(a,["veoTuningSpec"]);return null!=Z&&bY(s,["veoTuningSpec"],Z),s}function gt(a,b){let c={},d=bZ(a,["gcsUri"]);null!=d&&bY(c,["validationDatasetUri"],d);let e=bZ(a,["vertexDatasetResource"]);return null!=e&&bY(c,["validationDatasetUri"],e),c}class gu extends bW{constructor(a){super(),this.apiClient=a,this.list=async(a={})=>new c0(bM.PAGED_ITEM_TUNING_JOBS,a=>this.listInternal(a),await this.listInternal(a),a),this.get=async a=>await this.getInternal(a),this.tune=async a=>{var b;if(this.apiClient.isVertexAI())if(a.baseModel.startsWith("projects/")){let c={tunedModelName:a.baseModel};(null==(b=a.config)?void 0:b.preTunedModelCheckpointId)&&(c.checkpointId=a.config.preTunedModelCheckpointId);let d=Object.assign(Object.assign({},a),{preTunedModel:c});return d.baseModel=void 0,await this.tuneInternal(d)}else{let b=Object.assign({},a);return await this.tuneInternal(b)}{let b=Object.assign({},a),c=await this.tuneMldevInternal(b),d="";return void 0!==c.metadata&&void 0!==c.metadata.tunedModel?d=c.metadata.tunedModel:void 0!==c.name&&c.name.includes("/operations/")&&(d=c.name.split("/operations/")[0]),{name:d,state:ba.JOB_STATE_QUEUED}}}}async getInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d,e,h=(d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],e),d);return f=bX("{name}",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>gs(a))}{let b,c,h=(b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],c),b);return f=bX("{name}",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f,g,h,i,j,k,l,m,n,o;return b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["state"]))&&bY(b,["state"],cO(e)),null!=(f=bZ(a,["createTime"]))&&bY(b,["createTime"],f),null!=(g=bZ(a,["tuningTask","startTime"]))&&bY(b,["startTime"],g),null!=(h=bZ(a,["tuningTask","completeTime"]))&&bY(b,["endTime"],h),null!=(i=bZ(a,["updateTime"]))&&bY(b,["updateTime"],i),null!=(j=bZ(a,["description"]))&&bY(b,["description"],j),null!=(k=bZ(a,["baseModel"]))&&bY(b,["baseModel"],k),null!=(l=bZ(a,["_self"]))&&bY(b,["tunedModel"],(m={},null!=(n=bZ(l,["name"]))&&bY(m,["model"],n),null!=(o=bZ(l,["name"]))&&bY(m,["endpoint"],o),m)),b})}}async listInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f,g,h,i,j,k=(f={},null!=(g=bZ(a,["config"]))&&(h=bZ(g,["pageSize"]),void 0!==f&&null!=h&&bY(f,["_query","pageSize"],h),i=bZ(g,["pageToken"]),void 0!==f&&null!=i&&bY(f,["_query","pageToken"],i),j=bZ(g,["filter"]),void 0!==f&&null!=j&&bY(f,["_query","filter"],j)),f);return d=bX("tuningJobs",k._url),e=k._query,delete k._url,delete k._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(k),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["tuningJobs"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>gs(a))),bY(b,["tuningJobs"],a)}return b}(a),c=new cd;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d,e,h=(d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],e),d);return f=bX("{name}:cancel",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new ce;return Object.assign(e,d),e})}{let b,c,h=(b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],c),b);return f=bX("{name}:cancel",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new ce;return Object.assign(e,d),e})}}async tuneInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f,g,h,i,j,k=(f={},null!=(g=bZ(a,["baseModel"]))&&bY(f,["baseModel"],g),null!=(h=bZ(a,["preTunedModel"]))&&bY(f,["preTunedModel"],h),null!=(i=bZ(a,["trainingDataset"]))&&function(a,b,c){let d=bZ(c,["config","method"]);if(void 0===d&&(d="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===d){let c=bZ(a,["gcsUri"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","trainingDatasetUri"],c)}else if("PREFERENCE_TUNING"===d){let c=bZ(a,["gcsUri"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","trainingDatasetUri"],c)}else if("DISTILLATION"===d){let c=bZ(a,["gcsUri"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","promptDatasetUri"],c)}else if("REINFORCEMENT_TUNING"===d){let c=bZ(a,["gcsUri"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","trainingDatasetUri"],c)}let e=bZ(c,["config","method"]);if(void 0===e&&(e="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===e){let c=bZ(a,["vertexDatasetResource"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","trainingDatasetUri"],c)}else if("PREFERENCE_TUNING"===e){let c=bZ(a,["vertexDatasetResource"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","trainingDatasetUri"],c)}else if("DISTILLATION"===e){let c=bZ(a,["vertexDatasetResource"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","promptDatasetUri"],c)}else if("REINFORCEMENT_TUNING"===e){let c=bZ(a,["vertexDatasetResource"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","trainingDatasetUri"],c)}if(void 0!==bZ(a,["examples"]))throw Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.")}(i,f,a),null!=(j=bZ(a,["config"]))&&function(a,b,c){let d=bZ(c,["config","method"]);if(void 0===d&&(d="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===d){let c=bZ(a,["validationDataset"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec"],gt(c))}else if("PREFERENCE_TUNING"===d){let c=bZ(a,["validationDataset"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec"],gt(c))}else if("DISTILLATION"===d){let c=bZ(a,["validationDataset"]);void 0!==b&&null!=c&&bY(b,["distillationSpec"],gt(c))}else if("REINFORCEMENT_TUNING"===d){let c=bZ(a,["validationDataset"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec"],gt(c))}let e=bZ(a,["tunedModelDisplayName"]);void 0!==b&&null!=e&&bY(b,["tunedModelDisplayName"],e);let f=bZ(a,["description"]);void 0!==b&&null!=f&&bY(b,["description"],f);let g=bZ(c,["config","method"]);if(void 0===g&&(g="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===g){let c=bZ(a,["epochCount"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","hyperParameters","epochCount"],c)}else if("PREFERENCE_TUNING"===g){let c=bZ(a,["epochCount"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","hyperParameters","epochCount"],c)}else if("DISTILLATION"===g){let c=bZ(a,["epochCount"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","hyperParameters","epochCount"],c)}else if("REINFORCEMENT_TUNING"===g){let c=bZ(a,["epochCount"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","hyperParameters","epochCount"],c)}let h=bZ(c,["config","method"]);if(void 0===h&&(h="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===h){let c=bZ(a,["learningRateMultiplier"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],c)}else if("PREFERENCE_TUNING"===h){let c=bZ(a,["learningRateMultiplier"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],c)}else if("DISTILLATION"===h){let c=bZ(a,["learningRateMultiplier"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","hyperParameters","learningRateMultiplier"],c)}else if("REINFORCEMENT_TUNING"===h){let c=bZ(a,["learningRateMultiplier"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],c)}let i=bZ(c,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){let c=bZ(a,["exportLastCheckpointOnly"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","exportLastCheckpointOnly"],c)}else if("PREFERENCE_TUNING"===i){let c=bZ(a,["exportLastCheckpointOnly"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","exportLastCheckpointOnly"],c)}else if("DISTILLATION"===i){let c=bZ(a,["exportLastCheckpointOnly"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","exportLastCheckpointOnly"],c)}let j=bZ(c,["config","method"]);if(void 0===j&&(j="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===j){let c=bZ(a,["adapterSize"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","hyperParameters","adapterSize"],c)}else if("PREFERENCE_TUNING"===j){let c=bZ(a,["adapterSize"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","hyperParameters","adapterSize"],c)}else if("DISTILLATION"===j){let c=bZ(a,["adapterSize"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","hyperParameters","adapterSize"],c)}else if("REINFORCEMENT_TUNING"===j){let c=bZ(a,["adapterSize"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","hyperParameters","adapterSize"],c)}let k=bZ(c,["config","method"]);if(void 0===k&&(k="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===k){let c=bZ(a,["tuningMode"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","tuningMode"],c)}else if("DISTILLATION"===k){let c=bZ(a,["tuningMode"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","tuningMode"],c)}let l=bZ(a,["customBaseModel"]);void 0!==b&&null!=l&&bY(b,["customBaseModel"],l);let m=bZ(c,["config","method"]);if(void 0===m&&(m="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===m){let c=bZ(a,["batchSize"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","hyperParameters","batchSize"],c)}else if("DISTILLATION"===m){let c=bZ(a,["batchSize"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","hyperParameters","batchSize"],c)}else if("REINFORCEMENT_TUNING"===m){let c=bZ(a,["batchSize"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","hyperParameters","batchSize"],c)}let n=bZ(c,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let c=bZ(a,["learningRate"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","hyperParameters","learningRate"],c)}else if("DISTILLATION"===n){let c=bZ(a,["learningRate"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","hyperParameters","learningRate"],c)}let o=bZ(a,["labels"]);void 0!==b&&null!=o&&bY(b,["labels"],o);let p=bZ(a,["beta"]);void 0!==b&&null!=p&&bY(b,["preferenceOptimizationSpec","hyperParameters","beta"],p);let q=bZ(a,["baseTeacherModel"]);void 0!==b&&null!=q&&bY(b,["distillationSpec","baseTeacherModel"],q);let r=bZ(a,["tunedTeacherModelSource"]);void 0!==b&&null!=r&&bY(b,["distillationSpec","tunedTeacherModelSource"],r);let s=bZ(a,["sftLossWeightMultiplier"]);void 0!==b&&null!=s&&bY(b,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],s);let t=bZ(a,["outputUri"]);void 0!==b&&null!=t&&bY(b,["outputUri"],t);let u=bZ(a,["rewardConfig"]);void 0!==b&&null!=u&&bY(b,["reinforcementTuningSpec","singleRewardConfig"],u);let v=bZ(a,["compositeRewardConfig"]);void 0!==b&&null!=v&&bY(b,["reinforcementTuningSpec","compositeRewardConfig"],v);let w=bZ(a,["samplesPerPrompt"]);void 0!==b&&null!=w&&bY(b,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],w);let x=bZ(a,["evaluateInterval"]);void 0!==b&&null!=x&&bY(b,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],x);let y=bZ(a,["checkpointInterval"]);void 0!==b&&null!=y&&bY(b,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],y);let z=bZ(a,["maxOutputTokens"]);void 0!==b&&null!=z&&bY(b,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],z);let A=bZ(a,["thinkingLevel"]);void 0!==b&&null!=A&&bY(b,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],A);let B=bZ(a,["validationDatasetUri"]);void 0!==b&&null!=B&&bY(b,["reinforcementTuningSpec","validationDatasetUri"],B);let C=bZ(a,["encryptionSpec"]);void 0!==b&&null!=C&&bY(b,["encryptionSpec"],C)}(j,f,a),f);return d=bX("tuningJobs",k._url),e=k._query,delete k._url,delete k._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(k),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>gs(a))}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j,k=(f={},null!=(g=bZ(a,["baseModel"]))&&bY(f,["baseModel"],g),null!=(h=bZ(a,["preTunedModel"]))&&bY(f,["preTunedModel"],h),null!=(i=bZ(a,["trainingDataset"]))&&function(a){if(void 0!==bZ(a,["gcsUri"]))throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["vertexDatasetResource"]))throw Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let b=bZ(a,["examples"]);if(null!=b){let a=b;Array.isArray(a)&&(a=a.map(a=>a)),bY({},["examples","examples"],a)}}(i),null!=(j=bZ(a,["config"]))&&function(a,b){if(void 0!==bZ(a,["validationDataset"]))throw Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["tunedModelDisplayName"]);if(void 0!==b&&null!=c&&bY(b,["displayName"],c),void 0!==bZ(a,["description"]))throw Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["epochCount"]);void 0!==b&&null!=d&&bY(b,["tuningTask","hyperparameters","epochCount"],d);let e=bZ(a,["learningRateMultiplier"]);if(null!=e&&bY({},["tuningTask","hyperparameters","learningRateMultiplier"],e),void 0!==bZ(a,["exportLastCheckpointOnly"]))throw Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["preTunedModelCheckpointId"]))throw Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["adapterSize"]))throw Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["tuningMode"]))throw Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["customBaseModel"]))throw Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let f=bZ(a,["batchSize"]);void 0!==b&&null!=f&&bY(b,["tuningTask","hyperparameters","batchSize"],f);let g=bZ(a,["learningRate"]);if(void 0!==b&&null!=g&&bY(b,["tuningTask","hyperparameters","learningRate"],g),void 0!==bZ(a,["labels"]))throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["beta"]))throw Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["baseTeacherModel"]))throw Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["tunedTeacherModelSource"]))throw Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["sftLossWeightMultiplier"]))throw Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["outputUri"]))throw Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["rewardConfig"]))throw Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["compositeRewardConfig"]))throw Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["samplesPerPrompt"]))throw Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["evaluateInterval"]))throw Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["checkpointInterval"]))throw Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["maxOutputTokens"]))throw Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["thinkingLevel"]))throw Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["validationDatasetUri"]))throw Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["encryptionSpec"]))throw Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(j,f),f);return d=bX("tunedModels",k._url),e=k._query,delete k._url,delete k._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(k),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f,g;return b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["metadata"]))&&bY(b,["metadata"],e),null!=(f=bZ(a,["done"]))&&bY(b,["done"],f),null!=(g=bZ(a,["error"]))&&bY(b,["error"],g),b})}}async validateReward(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f,g,h,i,j,k,l=(f={},null!=(g=bZ(a,["parent"]))&&bY(f,["_url","parent"],g),null!=(h=bZ(a,["sampleResponse"]))&&bY(f,["sampleResponse"],gq(h)),null!=(i=bZ(a,["example"]))&&bY(f,["example"],function(a){let b={},c=bZ(a,["references"]);null!=c&&bY(b,["references"],c);let d=bZ(a,["contents"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>gq(a))),bY(b,["contents"],a)}let e=bZ(a,["systemInstruction"]);return null!=e&&bY(b,["systemInstruction"],gq(e)),b}(i)),null!=(j=bZ(a,["singleRewardConfig"]))&&bY(f,["singleRewardConfig"],j),null!=(k=bZ(a,["compositeRewardConfig"]))&&bY(f,["compositeRewardConfig"],k),f);return d=bX("{parent}/tuningJobs:validateReinforcementTuningReward",l._url),e=l._query,delete l._url,delete l._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f,g=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["overallReward"]))&&bY(b,["overallReward"],d),null!=(e=bZ(a,["error"]))&&bY(b,["error"],e),null!=(f=bZ(a,["rewardInfoDetails"]))&&bY(b,["rewardInfoDetails"],f),b),h=new cf;return Object.assign(h,g),h})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}let gv="x-goog-upload-status";async function gw(a,b,c,d){var e;let f=await gy(a,b,c,d),g=await (null==f?void 0:f.json());if((null==(e=null==f?void 0:f.headers)?void 0:e[gv])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return g.file}async function gx(a,b,c,d){var e;let f=await gy(a,b,c,d),g=await (null==f?void 0:f.json());if((null==(e=null==f?void 0:f.headers)?void 0:e[gv])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let h=b_(g),i=new ct;return Object.assign(i,h),i}async function gy(a,b,c,d){var e,f,g;let h=b,i=(null==d?void 0:d.baseUrl)||(null==(e=c.clientOptions.httpOptions)?void 0:e.baseUrl);if(i){let a=new URL(i),c=new URL(b);c.protocol=a.protocol,c.host=a.host,c.port=a.port,h=c.toString()}let j=0,k=0,l=new b0(new Response),m="upload";for(j=a.size;k<j;){let b=Math.min(8388608,j-k),e=a.slice(k,k+b);k+b>=j&&(m+=", finalize");let i=0,n=1e3;for(;i<3;){let a=Object.assign(Object.assign({},(null==d?void 0:d.headers)||{}),{"X-Goog-Upload-Command":m,"X-Goog-Upload-Offset":String(k),"Content-Length":String(b)});if(null==(f=null==(l=await c.request({path:"",body:e,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},d),{apiVersion:"",baseUrl:h,headers:a})}))?void 0:l.headers)?void 0:f[gv])break;i++,await gA(n),n*=2}if(k+=b,(null==(g=null==l?void 0:l.headers)?void 0:g[gv])!=="active")break;if(j<=k)throw Error("All content has been uploaded, but the upload status is not finalized.")}return l}async function gz(a){return{size:a.size,type:a.type}}function gA(a){return new Promise(b=>setTimeout(b,a))}class gB{async stat(a){let b={size:0,type:void 0};return"string"==typeof a?(b.size=(await bR.stat(a)).size,b.type=this.inferMimeType(a),b):await gz(a)}async upload(a,b,c,d){return"string"==typeof a?await this.uploadFileFromPath(a,b,c,d):gw(a,b,c,d)}async uploadToFileSearchStore(a,b,c,d){return"string"==typeof a?await this.uploadFileToFileSearchStoreFromPath(a,b,c,d):gx(a,b,c,d)}inferMimeType(a){return({aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"})[a.slice(a.lastIndexOf(".")+1).toLowerCase()]}async uploadFileFromPath(a,b,c,d){var e;let f=await this.uploadFileFromPathInternal(a,b,c,d),g=await (null==f?void 0:f.json());if((null==(e=null==f?void 0:f.headers)?void 0:e[gv])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return g.file}async uploadFileToFileSearchStoreFromPath(a,b,c,d){var e;let f=await this.uploadFileFromPathInternal(a,b,c,d),g=await (null==f?void 0:f.json());if((null==(e=null==f?void 0:f.headers)?void 0:e[gv])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let h=b_(g),i=new ct;return Object.assign(i,h),i}async uploadFileFromPathInternal(a,b,c,d){var e,f,g;let h,i=b,j=(null==d?void 0:d.baseUrl)||(null==(e=c.clientOptions.httpOptions)?void 0:e.baseUrl);if(j){let a=new URL(j),c=new URL(b);c.protocol=a.protocol,c.host=a.host,c.port=a.port,i=c.toString()}let k=0,l=0,m=new b0(new Response),n="upload",o=bV.basename(a);try{if(!(h=await bR.open(a,"r")))throw Error("Failed to open file");for(k=(await h.stat()).size;l<k;){let a=Math.min(8388608,k-l);l+a>=k&&(n+=", finalize");let b=new Uint8Array(a),{bytesRead:e}=await h.read(b,0,a,l);if(e!==a)throw Error(`Failed to read ${a} bytes from file at offset ${l}. bytes actually read: ${e}`);let j=new Blob([b]),p=0,q=1e3;for(;p<3;){let a=Object.assign(Object.assign({},(null==d?void 0:d.headers)||{}),{"X-Goog-Upload-Command":n,"X-Goog-Upload-Offset":String(l),"Content-Length":String(e),"X-Goog-Upload-File-Name":o});if(null==(f=null==(m=await c.request({path:"",body:j,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},d),{apiVersion:"",baseUrl:i,headers:a})}))?void 0:m.headers)?void 0:f[gv])break;p++,await gA(q),q*=2}if(l+=e,(null==(g=null==m?void 0:m.headers)?void 0:g[gv])!=="active")break;if(k<=l)throw Error("All content has been uploaded, but the upload status is not finalized.")}return m}finally{h&&await h.close()}}}class gC extends de{async registerFiles(a){if("u"<typeof process||!process.versions||!process.versions.node)throw Error("registerFiles is only supported in Node.js environments.");let b=a.auth,c=await b.getRequestHeaders(),d=a.config||{},e=d.httpOptions||{},f=Object.assign({},e.headers||{});if(c)if("function"==typeof c[Symbol.iterator])for(let[a,b]of c)f[a]=b;else for(let[a,b]of Object.entries(c))f[a]=b;return this._registerFiles({uris:a.uris,config:Object.assign(Object.assign({},d),{httpOptions:Object.assign(Object.assign({},e),{headers:f})})})}}class gD{getNextGenClient(){let a=this.httpOptions;return void 0===this._nextGenClient&&(this._nextGenClient=f5(this.apiClient,{timeout_ms:null==a?void 0:a.timeout})),(null==a?void 0:a.extraBody)&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return void 0!==this._interactions||(this._interactions=new f6(this.apiClient)),this._interactions}get webhooks(){return void 0!==this._webhooks||(this._webhooks=new f8(this.apiClient)),this._webhooks}get agents(){return void 0!==this._agents||(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new f7(this.apiClient)),this._agents}get triggers(){return void 0!==this._triggers||(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new f9(this.apiClient)),this._triggers}get environments(){return void 0!==this._environments||(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new gi(this.apiClient)),this._environments}constructor(a){var b,c,f,g;if(this.vertexai=function(a){var b;if(void 0!==a.enterprise||void 0!==a.vertexai){if(void 0!==a.enterprise&&void 0!==a.vertexai&&a.enterprise!==a.vertexai)throw Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return null!=(b=a.enterprise)?b:a.vertexai}let c=gE("GOOGLE_GENAI_USE_ENTERPRISE"),d=gE("GOOGLE_GENAI_USE_VERTEXAI"),e=gF(c),f=gF(d);return(void 0!==c&&void 0!==d&&e!==f&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),void 0!==c)?e:void 0!==d&&f}(a),(a.project||a.location)&&!this.vertexai)throw Error("Project and location are not supported for Gemini API backend.");const h=function(){let a=gE("GOOGLE_API_KEY"),b=gE("GEMINI_API_KEY");return a&&b&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),a||b||void 0}(),i=gE("GOOGLE_CLOUD_PROJECT"),j=gE("GOOGLE_CLOUD_LOCATION");this.apiKey=null!=(b=a.apiKey)?b:h,this.project=null!=(c=a.project)?c:i,this.location=null!=(f=a.location)?f:j,this.vertexai||this.apiKey||console.warn("API key should be set when using the Gemini API."),this.vertexai&&((null==(g=a.googleAuthOptions)?void 0:g.credentials)&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!a.project&&!a.location&&(i||j)&&a.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(a.project||a.location)&&!a.apiKey&&h?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!a.project&&!a.location&&!a.apiKey&&(i||j)&&h&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),this.location||this.apiKey||(this.location="global"));const k=function(a,b,c,f){return(null==a?void 0:a.baseUrl)?a.baseUrl:b?null!=e?e:c:null!=d?d:f}(a.httpOptions,this.vertexai,gE("GOOGLE_VERTEX_BASE_URL"),gE("GOOGLE_GEMINI_BASE_URL"));k&&(a.httpOptions?a.httpOptions.baseUrl=k:a.httpOptions={baseUrl:k}),this.apiVersion=a.apiVersion,this.httpOptions=a.httpOptions;const l=new gl({apiKey:this.apiKey,googleAuthOptions:a.googleAuthOptions});this.apiClient=new dG({auth:l,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:"gl-node/"+process.version,uploader:new gB,downloader:new gm}),this.models=new dW(this.apiClient),this.live=new dP(this.apiClient,l,new go),this.batches=new c1(this.apiClient),this.chats=new db(this.models,this.apiClient),this.caches=new c4(this.apiClient),this.files=new gC(this.apiClient),this.operations=new dX(this.apiClient),this.authTokens=new dY(this.apiClient),this.tunings=new gu(this.apiClient),this.fileSearchStores=new d$(this.apiClient)}}function gE(a){var b,c,d;return null!=(d=null==(c=null==(b=null==process?void 0:process.env)?void 0:b[a])?void 0:c.trim())?d:void 0}function gF(a){return void 0!==a&&"true"===a.toLowerCase()}},97328:(a,b,c)=>{"use strict";c.d(b,{E5:()=>j,Jp:()=>g,M6:()=>e,Ne:()=>d,O:()=>i,V8:()=>k,g4:()=>h,xg:()=>f});let d=["chat","api","schedule","trigger","subflow","mcp","internal","meeting"];function e(a){return"string"==typeof a&&d.includes(a)}function f(a){return"chat"!==a&&"api"!==a}let g="TOOL_CALL",h="FINAL_RESPONSE",i="ERROR",j="STAY_ON_NODE",k="IMPLICIT_SUBFLOW_RETURN"},97337:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),b.assignDefaults=void 0;let d=c(78276),e=c(94134);function f(a,b,c){let{gen:f,compositeRule:g,data:h,opts:i}=a;if(void 0===c)return;let j=(0,d._)`${h}${(0,d.getProperty)(b)}`;if(g)return void(0,e.checkStrictMode)(a,`default is ignored for: ${j}`);let k=(0,d._)`${j} === undefined`;"empty"===i.useDefaults&&(k=(0,d._)`${k} || ${j} === null || ${j} === ""`),f.if(k,(0,d._)`${j} = ${(0,d.stringify)(c)}`)}b.assignDefaults=function(a,b){let{properties:c,items:d}=a.schema;if("object"===b&&c)for(let b in c)f(a,b,c[b].default);else"array"===b&&Array.isArray(d)&&d.forEach((b,c)=>f(a,c,b.default))}},97356:(a,b,c)=>{"use strict";let{Transform:d}=c(57075),{isASCIINumber:e,isValidLastEventId:f}=c(26376);class g extends d{state;checkBOM=!0;crlfCheck=!1;eventEndCheck=!1;buffer=null;pos=0;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(a={}){a.readableObjectMode=!0,super(a),this.state=a.eventSourceSettings||{},a.push&&(this.push=a.push)}_transform(a,b,c){if(0===a.length)return void c();if(this.buffer?this.buffer=Buffer.concat([this.buffer,a]):this.buffer=a,this.checkBOM)switch(this.buffer.length){case 1:if(239===this.buffer[0])return void c();this.checkBOM=!1,c();return;case 2:if(239===this.buffer[0]&&187===this.buffer[1])return void c();this.checkBOM=!1;break;case 3:if(239===this.buffer[0]&&187===this.buffer[1]&&191===this.buffer[2]){this.buffer=Buffer.alloc(0),this.checkBOM=!1,c();return}this.checkBOM=!1;break;default:239===this.buffer[0]&&187===this.buffer[1]&&191===this.buffer[2]&&(this.buffer=this.buffer.subarray(3)),this.checkBOM=!1}for(;this.pos<this.buffer.length;){if(this.eventEndCheck){if(this.crlfCheck){if(10===this.buffer[this.pos]){this.buffer=this.buffer.subarray(this.pos+1),this.pos=0,this.crlfCheck=!1;continue}this.crlfCheck=!1}if(10===this.buffer[this.pos]||13===this.buffer[this.pos]){13===this.buffer[this.pos]&&(this.crlfCheck=!0),this.buffer=this.buffer.subarray(this.pos+1),this.pos=0,(void 0!==this.event.data||this.event.event||void 0!==this.event.id||this.event.retry)&&this.processEvent(this.event),this.clearEvent();continue}this.eventEndCheck=!1;continue}if(10===this.buffer[this.pos]||13===this.buffer[this.pos]){13===this.buffer[this.pos]&&(this.crlfCheck=!0),this.parseLine(this.buffer.subarray(0,this.pos),this.event),this.buffer=this.buffer.subarray(this.pos+1),this.pos=0,this.eventEndCheck=!0;continue}this.pos++}c()}parseLine(a,b){if(0===a.length)return;let c=a.indexOf(58);if(0===c)return;let d="",g="";if(-1!==c){d=a.subarray(0,c).toString("utf8");let b=c+1;32===a[b]&&++b,g=a.subarray(b).toString("utf8")}else d=a.toString("utf8"),g="";switch(d){case"data":void 0===b[d]?b[d]=g:b[d]+=`
442
+ || ${g} === "boolean" || ${e} === null`).assign(h,(0,i._)`[${e}]`)}}(a);d.else(),p(a),d.endIf(),d.if((0,i._)`${h} !== undefined`,()=>{d.assign(e,h),function({gen:a,parentData:b,parentDataProperty:c},d){a.if((0,i._)`${b} !== undefined`,()=>a.assign((0,i._)`${b}[${c}]`,d))}(a,h)})}(a,b,k):p(a)})}return m};let l=new Set(["string","number","integer","boolean","null"]);function m(a,b,c,e=d.Correct){let f,g=e===d.Correct?i.operators.EQ:i.operators.NEQ;switch(a){case"null":return(0,i._)`${b} ${g} null`;case"array":f=(0,i._)`Array.isArray(${b})`;break;case"object":f=(0,i._)`${b} && typeof ${b} == "object" && !Array.isArray(${b})`;break;case"integer":f=h((0,i._)`!(${b} % 1) && !isNaN(${b})`);break;case"number":f=h();break;default:return(0,i._)`typeof ${b} ${g} ${a}`}return e===d.Correct?f:(0,i.not)(f);function h(a=i.nil){return(0,i.and)((0,i._)`typeof ${b} == "number"`,a,c?(0,i._)`isFinite(${b})`:i.nil)}}function n(a,b,c,d){let e;if(1===a.length)return m(a[0],b,c,d);let f=(0,j.toHash)(a);if(f.array&&f.object){let a=(0,i._)`typeof ${b} != "object"`;e=f.null?a:(0,i._)`!${b} || ${a}`,delete f.null,delete f.array,delete f.object}else e=i.nil;for(let a in f.number&&delete f.integer,f)e=(0,i.and)(e,m(a,b,c,d));return e}b.checkDataType=m,b.checkDataTypes=n;let o={message:({schema:a})=>`must be ${a}`,params:({schema:a,schemaValue:b})=>"string"==typeof a?(0,i._)`{type: ${a}}`:(0,i._)`{type: ${b}}`};function p(a){let b=function(a){let{gen:b,data:c,schema:d}=a,e=(0,j.schemaRefOrVal)(a,d,"type");return{gen:b,keyword:"type",data:c,schema:d.type,schemaCode:e,schemaValue:e,parentSchema:d,params:{},it:a}}(a);(0,h.reportError)(b,o)}b.reportTypeError=p},95055:(a,b,c)=>{"use strict";c.d(b,{DB:()=>O,oW:()=>W,hz:()=>X,vu:()=>$,SR:()=>R,dQ:()=>Y,od:()=>V,qV:()=>Q,Re:()=>Z});var d=c(45146),e=c(68680),f=c(8012),g=c(82964),h=c(28461),i=c(23715),j=c(36200),k=c(4669),l=c(63455),m=c(42370);let n=new Map,o=new Map;function p(a){let b=`fallback:${a}`;n.set(b,(n.get(b)??0)+1)}function q(a,b){Number.isFinite(b)&&!(b<0)&&(n.set(`stage:${a}`,(n.get(`stage:${a}`)??0)+1),o.set(a,(o.get(a)??0)+b))}class r{constructor(a={}){this.entries=new Map,this.inFlight=new Map,this.generation=0,this.hits=0,this.misses=0,this.coalesced=0,this.evictions=0,this.maxEntries=Math.max(1,Math.floor(a.maxEntries??256)),this.ttlMilliseconds=Math.max(1,Math.floor(a.ttlMilliseconds??3e5)),this.now=a.now??Date.now}cacheKey(a){return JSON.stringify([a.workspaceId,a.provider,a.modelId,a.dimensions??null,a.query.normalize("NFKC").trim().replace(/\s+/gu," ").toLowerCase()])}get(a){let b=this.cacheKey(a),c=this.entries.get(b);if(c)return c.expiresAt<=this.now()?void this.entries.delete(b):(this.entries.delete(b),this.entries.set(b,c),c.vector)}set(a,b){let c=this.cacheKey(a);for(this.entries.delete(c),this.entries.set(c,{vector:[...b],expiresAt:this.now()+this.ttlMilliseconds});this.entries.size>this.maxEntries;){let a=this.entries.keys().next().value;if(void 0===a)break;this.entries.delete(a),this.evictions+=1}}async getOrCreate(a,b){let c=this.get(a);if(c)return this.hits+=1,c;let d=this.cacheKey(a),e=this.inFlight.get(d);if(e)return this.coalesced+=1,e;this.misses+=1;let f=this.generation,g=b().then(b=>(f===this.generation&&this.set(a,b),b)).finally(()=>{this.inFlight.get(d)===g&&this.inFlight.delete(d)});return this.inFlight.set(d,g),g}clear(){this.entries.clear(),this.inFlight.clear(),this.generation+=1,this.resetStats()}resetStats(){this.hits=0,this.misses=0,this.coalesced=0,this.evictions=0}stats(){return{hits:this.hits,misses:this.misses,coalesced:this.coalesced,evictions:this.evictions,size:this.entries.size,inFlight:this.inFlight.size}}}let s=new r;var t=c(64486),u=c(51030);let v=new Set(["no","not","never","none","neither","without","isn't","aren't","wasn't","weren't","doesn't","don't","didn't","cannot","can't","won't"]),w=[["allow","deny"],["allowed","denied"],["enable","disable"],["enabled","disabled"],["increase","decrease"],["increased","decreased"],["open","closed"],["present","absent"],["required","optional"],["true","false"],["yes","no"]],x=new Map(w.flatMap(([a,b])=>[[a,b],[b,a]])),y=new Set(w.flat());function z(a){return a.normalize("NFKC").toLocaleLowerCase().match(/[\p{L}\p{N}]+(?:['’][\p{L}]+)?/gu)??[]}function A(a,b){if(0===a.size&&0===b.size)return 1;let c=[...a].filter(a=>b.has(a)).length;return c/(a.size+b.size-c)}function B(a){return a.normalize("NFKC").toLocaleLowerCase().match(/\b(?:\d{4}-\d{1,2}-\d{1,2}|\d+(?:[.,]\d+)?)\b/g)??[]}function C(a){return a.filter(a=>!v.has(a)&&!y.has(a)&&!/^\d/.test(a))}let D={score(a,b,c){let d,e,f=z(a),g=z(b),h=new Set(f),i=new Set(g),j=A(h,i),k=(d=new Set(f.slice(0,-1).map((a,b)=>`${a}\u0000${f[b+1]}`)),e=new Set(g.slice(0,-1).map((a,b)=>`${a}\u0000${g[b+1]}`)),0===d.size&&0===e.size?+(f.length===g.length&&f[0]===g[0]):2*[...d].filter(a=>e.has(a)).length/(d.size+e.size)),l=Math.max(j,k,A(new Set(C(f)),new Set(C(g)))),m={similarity:l,tokenJaccard:j,bigramDice:k,detectorVersion:"lexical-v1"};if(l<Math.min(1,Math.max(0,c)))return{...m,relation:"unrelated",reason:"low_overlap"};let n=B(a),o=B(b);return n.length>0&&o.length>0&&JSON.stringify(n)!==JSON.stringify(o)?{...m,relation:"contradict",reason:"value_mismatch"}:f.some(a=>v.has(a))!==g.some(a=>v.has(a))?{...m,relation:"contradict",reason:"polarity_mismatch"}:[...h].some(a=>{let b=x.get(a);return void 0!==b&&i.has(b)})?{...m,relation:"contradict",reason:"antonym_mismatch"}:{...m,relation:"agree",reason:"high_overlap"}}};function E(a,b){let c=Math.max(0,b-a.createdAt)/864e5;return Math.min(1,Math.max(0,a.confidence))*2**(-c/30)}var F=c(18172),G=c(66720);let H=(0,g.h)("backend/services/enduringAgents/memoryKernel"),I=d.Ik({query:d.Yj().trim().max(2e3).optional(),kinds:d.YO(d.k5(i.g_)).optional(),scopes:d.YO(d.k5(i.su)).optional(),statuses:d.YO(d.k5(i.f5)).optional(),trust:d.YO(d.k5(i.bo)).optional(),coreOnly:d.zM().optional(),mode:d.k5(["lexical","hybrid"]).optional(),order:d.k5(["review"]).optional(),asOf:d.ai().int().nonnegative().optional(),limit:d.ai().int().min(1).max(200).optional()}).strict(),J=d.Ik({content:d.Yj().trim().min(1).max(1e5),confidence:d.ai().min(0).max(1).optional(),importance:d.ai().min(0).max(1).optional(),sourceRefs:d.YO(i.Pk).min(1).max(100),validFrom:d.ai().int().nonnegative().optional(),validUntil:d.ai().int().nonnegative().optional(),expectedUpdatedAt:d.ai().int().nonnegative().optional()}).strict();function K(a,b){if(b.executionAuthority&&"locked"===a.autonomyLevel)throw new j.TP("Automatic memory changes are turned off for this Persona.","PERSONA_LEARNING_DISABLED",{reason:"learning_disabled"})}function L(a){return JSON.stringify(a.sourceRefs.map(({observedAt:a,...b})=>b))}async function M(a,b,c,d){return(0,u.NK)(await (0,G.eD)(a),{kind:b,scope:c,content:d},u.jg)}function N(a,b,c){if(!a||a.personaId!==b)throw new j.SZ("MemoryItem",c);return a}function O(a,b,c,d){if("active"===b){if("external_untrusted"===a)throw new j.TP("Untrusted external content cannot be activated.");if("model_inference"===a&&!c.reviewed)throw new j.TP("Model-inferred memory requires explicit review before activation.");if("explicit_user"===a&&!d.includes("user_statement"))throw new j.TP("Explicit-user memory requires user-statement provenance.");if("verified_tool"===a&&!d.includes("tool_result"))throw new j.TP("Verified-tool memory requires tool-result provenance.")}}async function P(a,b,c){let d,f=Date.now(),g=await (0,t.pm)(),h=!!b.executionAuthority,m=h?"model_inference":a.trust,n=h?"candidate":a.status??"candidate",o=[...a.sourceRefs];"candidate"===n&&g.candidateExpiryDays>0&&(d=f+24*g.candidateExpiryDays*36e5),c&&!o.some(a=>"activity"===a.kind&&a.id===c)&&o.push({kind:"activity",id:c,observedAt:f}),O(m,n,b,o.map(a=>a.kind));let p=i.OZ.parse({schemaVersion:i.cq,id:a.id??(0,k.WK)("memory"),personaId:a.personaId,kind:a.kind,scope:a.scope,status:n,content:a.content,confidence:a.confidence,importance:a.importance,sourceRefs:(0,F.c)(o,{now:f,producer:h?"persona-flow-proposal":void 0,digestMaterial:a.content}),trust:m,...void 0!==a.validFrom?{validFrom:a.validFrom}:{},...void 0!==a.validUntil?{validUntil:a.validUntil}:{},...a.supersedes?.length?{supersedes:a.supersedes}:{},...a.conflictsWith?.length?{conflictsWith:[...new Set(a.conflictsWith)].sort()}:{},...void 0!==d?{expiresAt:d}:{},createdAt:f,updatedAt:f}),q=[...new Set(p.conflictsWith??[])].filter(a=>a!==p.id).sort(),r=q.length>0?await (0,G.eD)(p.personaId,{ids:q}):[];if(r.length!==q.length||r.some(a=>a.personaId!==p.personaId))throw new j.TP("conflictsWith must reference existing memories owned by this Persona.");let s=e.Gv.ENABLE_MEMORY_CONFLICT_SURFACING&&g.conflictDetectionEnabled?await (0,G.eD)(p.personaId,{statuses:["active"],kinds:[p.kind],scopes:[p.scope],limit:200,order:"updated_at"}):[],v=new Set(p.supersedes??[]),w=new Map([...r,...s.filter(a=>a.id!==p.id&&!v.has(a.id)&&"contradict"===D.score(a.content,p.content,g.conflictSimilarityThreshold).relation)].map(a=>[a.id,a])),x=[...w.keys()].sort(),y=x.length>0?{...p,conflictsWith:x}:(()=>{let{conflictsWith:a,...b}=p;return b})(),z=await (0,G.Xc)(p.personaId,p.id);if(z){if(z.personaId!==p.personaId||z.kind!==p.kind||z.scope!==p.scope||z.status!==p.status||z.content!==p.content||z.confidence!==p.confidence||z.importance!==p.importance||z.trust!==p.trust||L(z)!==L(p)||JSON.stringify(z.supersedes??[])!==JSON.stringify(p.supersedes??[]))throw new j.TP(`MemoryItem ${JSON.stringify(p.id)} already exists.`);if(0===x.length)return z}if(!z&&0===x.length&&u.jg.enabled&&!b.skipNearDuplicateMerge&&!p.supersedes?.length){let a=await M(p.personaId,p.kind,p.scope,p.content);if(a){let{candidate:c,similarity:d}=a,e=await (0,G.AN)((0,l._q)(c,{now:f,incomingTrust:p.trust,incomingSourceRefs:p.sourceRefs,canUpgradeTrust:a=>{try{return O(a,c.status,b,p.sourceRefs.map(a=>a.kind)),!0}catch{return!1}}}));return H.debug("Dedup merged near-duplicate",{survivorId:c.id,similarity:d.toFixed(3),kind:p.kind,scope:p.scope}),e}}let A=z??await (0,G.AN)((()=>{let{conflictsWith:a,...b}=y;return b})());for(let a of w.values()){let b=[...new Set([...a.conflictsWith??[],p.id])].sort();JSON.stringify(b)!==JSON.stringify(a.conflictsWith??[])&&await (0,G.AN)({...a,conflictsWith:b,updatedAt:Math.max(Date.now(),a.updatedAt+1)})}if(x.length>0){let a=[...new Set([...A.conflictsWith??[],...x])].sort();A=await (0,G.AN)({...A,conflictsWith:a,updatedAt:Math.max(Date.now(),A.updatedAt+1)})}return A}async function Q(a,b={}){let c=i.Q$.parse(a);return(0,j.g7)(c.personaId,b,({persona:a,activity:d})=>(K(a,b),P(c,b,d?.id)))}async function R(a,b){return i.Qy.parse(a),i.Qy.parse(b),N(await (0,G.Xc)(a,b),a,b)}function S(a=u.ks){return{scores:new Map,floor:a,lexicalWeight:1,semanticWeight:0}}function T(a,b=u.ks){return p(a),H.debug("Semantic recall unavailable; using lexical fallback.",{reason:a}),S(b)}async function U(a,b,d){if(!b?.trim())return T("empty_query");let e=await (0,t.pm)();if(!e.semanticRecallEnabled)return T("disabled",e.semanticFloor);if(!e.semanticEmbeddingModelId)return T("missing_model",e.semanticFloor);let[{modelService:g},{getEmbeddingProvider:i}]=await Promise.all([Promise.resolve().then(c.bind(c,14493)),Promise.resolve().then(c.bind(c,49062))]),j=await g.getModel(e.semanticEmbeddingModelId);if(!j)return T("model_not_found",e.semanticFloor);if(!(0,f.VP)(j.adapter))return T("unsupported_adapter",e.semanticFloor);try{let c=performance.now(),f=await s.getOrCreate({workspaceId:(0,h.getCurrentWorkspace)(),provider:j.adapter,modelId:j.name,dimensions:e.semanticEmbeddingDimensions,query:b},async()=>{let a=await i().embed(j,{modelId:j.name,text:b,dimensions:e.semanticEmbeddingDimensions});if(0===a.vector.length||a.vector.length!==a.dimensions||!a.vector.every(Number.isFinite))throw Error("Embedding provider returned an invalid query vector.");return a.vector});q("query_embedding",performance.now()-c);let g=performance.now(),k=await (0,m.rn)(a);q("sidecar_load",performance.now()-g),0===k.length&&p("missing_sidecar");let l=performance.now(),n=(0,m.NH)(a,d,k,f,j.name);return q("cosine_scoring",performance.now()-l),{scores:n,floor:e.semanticFloor,lexicalWeight:e.lexicalWeight,semanticWeight:e.semanticWeight}}catch{return T("embedding_failure",e.semanticFloor)}}async function V(a,b={}){var c,d,f;let g;i.Qy.parse(a);let h=I.parse(b),k=await (0,G.getPersona)(a);if(!k)throw new j.SZ("Persona",a);let l=new Set(k.coreMemoryItemIds??[]),m=(c=h.query,[...new Set(c?.toLocaleLowerCase().match(/[\p{L}\p{N}_-]{2,}/gu)??[])]),o=h.asOf??Date.now(),p="review"===h.order,r=h.limit??(p?20:50),s=performance.now(),t=await (0,G.eD)(a,{statuses:p?["candidate"]:h.statuses??["active"],kinds:h.kinds?.length?h.kinds:void 0,scopes:h.scopes?.length?h.scopes:void 0,trust:h.trust?.length?h.trust:void 0,validAt:o,ids:h.coreOnly?[...l]:void 0,...!p&&0===m.length?{limit:r,order:"memory_relevance",coreIds:[...l]}:{}});q("item_load",performance.now()-s);let v=performance.now();if(p)g=t.filter(a=>"candidate"===a.status&&void 0===a.reviewedAt&&(void 0===a.expiresAt||a.expiresAt>o)&&(0===m.length||m.some(b=>a.content.toLocaleLowerCase().includes(b)))).sort((a,b)=>E(b,o)-E(a,o)||b.createdAt-a.createdAt||a.id.localeCompare(b.id)).slice(0,r).map(a=>({item:a,core:l.has(a.id),score:E(a,o)}));else{let b="lexical"===h.mode?S():await U(a,h.query,t),c=t.map(a=>{let c=m.some(b=>a.content.toLocaleLowerCase().includes(b));return{item:a,core:l.has(a.id),lexicalHit:c,semantic:b.scores.get(a.id)}}),e=c.filter(({lexicalHit:a,semantic:c})=>0===m.length||(0,u.pV)(a,c,b.floor));d=c.length,f=e.length,Number.isFinite(d)&&Number.isFinite(f)&&(n.set("candidates:before",(n.get("candidates:before")??0)+d),n.set("candidates:after",(n.get("candidates:after")??0)+f));let i={...u.nj,lexicalWeight:b.lexicalWeight,semanticWeight:b.semanticWeight},j=e.map(({item:a,core:b,semantic:c})=>({item:a,core:b,score:(0,u.Fv)({item:a,terms:m,core:b,asOf:o,semantic:c,weights:i})}));g=0===m.length?j:j.sort((a,b)=>b.score-a.score||b.item.updatedAt-a.item.updatedAt||a.item.id.localeCompare(b.item.id)).slice(0,r)}if(q("filter_rank",performance.now()-v),!e.Gv.ENABLE_MEMORY_CONFLICT_SURFACING)return g;let w=[...new Set(g.flatMap(a=>a.item.conflictsWith??[]))];if(0===w.length)return g;let x=new Map((await (0,G.eD)(a,{ids:w})).map(a=>[a.id,a]));return g.map(b=>{let c=(b.item.conflictsWith??[]).filter(a=>a!==b.item.id).map(a=>x.get(a)).filter(b=>b?.personaId===a).sort((a,b)=>Number("active"===b.status)-Number("active"===a.status)||b.updatedAt-a.updatedAt||a.id.localeCompare(b.id)).slice(0,5).map(a=>({id:a.id,content:a.content,kind:a.kind,scope:a.scope,status:a.status,trust:a.trust,confidence:a.confidence,importance:a.importance,updatedAt:a.updatedAt}));return c.length>0?{...b,conflicts:c}:b})}async function W(a,b,c,d={}){i.Qy.parse(a),i.Qy.parse(b);let e=J.parse(c);return(0,j.g7)(a,d,async({persona:c,activity:f,updatePersona:g})=>{K(c,d);let h=N(await (0,G.Xc)(a,b),a,b);if("forgotten"===h.status)throw new j.TP("Forgotten memory cannot be corrected in place.");if(void 0!==e.expectedUpdatedAt&&e.expectedUpdatedAt!==h.updatedAt)throw new j.TP("Memory changed since it was inspected.","memory_changed",{currentUpdatedAt:h.updatedAt});let i=!!d.executionAuthority,k=await P({personaId:a,kind:h.kind,scope:h.scope,status:i?"candidate":"active",content:e.content,confidence:e.confidence??h.confidence,importance:e.importance??h.importance,sourceRefs:e.sourceRefs,trust:i?"model_inference":"explicit_user",...void 0!==e.validFrom?{validFrom:e.validFrom}:{},...void 0!==e.validUntil?{validUntil:e.validUntil}:{},supersedes:[h.id]},d,f?.id);return"active"!==k.status||(c.coreMemoryItemIds?.includes(h.id)&&await g({...c,coreMemoryItemIds:(c.coreMemoryItemIds??[]).map(a=>a===h.id?k.id:a),updatedAt:Math.max(Date.now(),c.updatedAt+1)}),await (0,G.AN)({...h,status:"superseded",updatedAt:Math.max(Date.now(),h.updatedAt+1)})),k})}async function X(a,b,c={}){return(0,j.g7)(a,c,async({persona:d,updatePersona:e})=>{K(d,c);let f=N(await (0,G.Xc)(a,b),a,b);return"forgotten"===f.status?f:(d.coreMemoryItemIds?.includes(f.id)&&await e({...d,coreMemoryItemIds:d.coreMemoryItemIds.filter(a=>a!==f.id),updatedAt:Math.max(Date.now(),d.updatedAt+1)}),(0,G.AN)({...f,status:"forgotten",updatedAt:Math.max(Date.now(),f.updatedAt+1)}))})}async function Y(a,b,c={}){return(0,j.g7)(a,c,async({persona:d,updatePersona:e})=>{K(d,c);let f=N(await (0,G.Xc)(a,b),a,b);if("active"!==f.status||"explicit_user"!==f.trust&&"verified_tool"!==f.trust)throw new j.TP("Core memory requires active explicit-user or verified-tool trust.");let g=[...new Set([...d.coreMemoryItemIds??[],f.id])],h=await (0,G.lc)(d.roleVersionId),i=h?.defaults?.memory?.coreMemoryMaxItems??32;if(g.length>i)throw new j.TP(`Core memory is limited to ${i} items.`,"core_memory_capacity",{maxCoreItems:i,currentCoreItems:d.coreMemoryItemIds?.length??0});g.length!==(d.coreMemoryItemIds??[]).length&&await e({...d,coreMemoryItemIds:g,updatedAt:Math.max(Date.now(),d.updatedAt+1)});let k=new Map((await (0,G.eD)(a,{ids:g})).map(a=>[a.id,a]));return g.map(a=>k.get(a)).filter(a=>!!a)})}async function Z(a,b,c={}){return(0,j.g7)(a,c,async({persona:d,updatePersona:e})=>{K(d,c),N(await (0,G.Xc)(a,b),a,b);let f=(d.coreMemoryItemIds??[]).filter(a=>a!==b);f.length!==(d.coreMemoryItemIds??[]).length&&await e({...d,coreMemoryItemIds:f,updatedAt:Math.max(Date.now(),d.updatedAt+1)});let g=new Map((await (0,G.eD)(a,{ids:f})).map(a=>[a.id,a]));return f.map(a=>g.get(a)).filter(a=>!!a)})}async function $(a){let b=await (0,G.getPersona)(a);if(!b)throw new j.SZ("Persona",a);let c=b.coreMemoryItemIds??[];if(0===c.length)return[];let d=new Map((await (0,G.eD)(a,{ids:c})).map(a=>[a.id,a]));return c.map(a=>d.get(a)).filter(a=>!!a)}},95095:(a,b,c)=>{"use strict";let d=c(7344),e=c(31825);class f extends d{#cb=null;#cc=null;constructor(a,b={}){super(b),this.#cb=a,this.#cc=b}dispatch(a,b){let c=new e({...a,retryOptions:this.#cc},{dispatch:this.#cb.dispatch.bind(this.#cb),handler:b});return this.#cb.dispatch(a,c)}close(){return this.#cb.close()}destroy(){return this.#cb.destroy()}}a.exports=f},95195:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),b.GoogleAuth=b.GoogleAuthExceptionMessages=void 0;let d=c(79646),e=c(29021),f=c(32184),g=c(95699),h=c(21820),i=c(33873),j=c(57784),k=c(73926),l=c(24587),m=c(78072),n=c(29114),o=c(18536),p=c(70973),q=c(76808),r=c(9419),s=c(84687),t=c(22961),u=c(98953),v=c(96451);b.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:"Unable to detect a Project Id in the current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_CREDENTIALS_FOUND:"Unable to find credentials in current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:"Unable to detect a Universe Domain in the current environment.\nTo learn more about Universe Domain retrieval, visit: \nhttps://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"};class w{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#cd=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(a={}){if(this._cachedProjectId=a.projectId||null,this.cachedCredential=a.authClient||null,this.keyFilename=a.keyFilename||a.keyFile,this.scopes=a.scopes,this.clientOptions=a.clientOptions||{},this.jsonContent=a.credentials||null,this.apiKey=a.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw RangeError(b.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);a.universeDomain&&(this.clientOptions.universeDomain=a.universeDomain)}setGapicJWTValues(a){a.defaultServicePath=this.defaultServicePath,a.useJWTAccessWithScope=this.useJWTAccessWithScope,a.defaultScopes=this.defaultScopes}getProjectId(a){if(!a)return this.getProjectIdAsync();this.getProjectIdAsync().then(b=>a(null,b),a)}async getProjectIdOptional(){try{return await this.getProjectId()}catch(a){if(a instanceof Error&&a.message===b.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw a}}async findAndCacheProjectId(){let a=null;if(a||=await this.getProductionProjectId(),a||=await this.getFileProjectId(),a||=await this.getDefaultServiceProjectId(),a||=await this.getGCEProjectId(),a||=await this.getExternalAccountClientProjectId())return this._cachedProjectId=a,a;throw Error(b.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let a;try{a=await g.universe("universe-domain"),a||=s.DEFAULT_UNIVERSE}catch(b){if(b&&b?.response?.status===404)a=s.DEFAULT_UNIVERSE;else throw b}return a}async getUniverseDomain(){let a=(0,v.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{a??=(await this.getClient()).universeDomain}catch{a??=s.DEFAULT_UNIVERSE}return a}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(a={},b){let c;if("function"==typeof a?b=a:c=a,!b)return this.getApplicationDefaultAsync(c);this.getApplicationDefaultAsync(c).then(a=>b(null,a.credential,a.projectId),b)}async getApplicationDefaultAsync(a={}){let c;if(this.cachedCredential)return await this.#ce(this.cachedCredential,null);if((c=await this._tryGetApplicationCredentialsFromEnvironmentVariable(a))||(c=await this._tryGetApplicationCredentialsFromWellKnownFile(a)))return c instanceof n.JWT?c.scopes=this.scopes:c instanceof r.BaseExternalAccountClient&&(c.scopes=this.getAnyScopes()),await this.#ce(c);if(await this._checkIsGCE())return a.scopes=this.getAnyScopes(),await this.#ce(new k.Compute(a));throw Error(b.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async #ce(a,b=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let c=await this.getProjectIdOptional();return b&&(a.quotaProjectId=b),this.cachedCredential=a,{credential:a,projectId:c}}async _checkIsGCE(){return void 0===this.checkIsGCE&&(this.checkIsGCE=g.getGCPResidency()||await g.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(a){let b=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!b||0===b.length)return null;try{return await this._getApplicationCredentialsFromFilePath(b,a)}catch(a){throw a instanceof Error&&(a.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${a.message}`),a}}async _tryGetApplicationCredentialsFromWellKnownFile(a){let b=process.env.CLOUDSDK_CONFIG;if(!b)if(this._isWindows())process.env.APPDATA&&(b=i.join(process.env.APPDATA,"gcloud"));else{let a=process.env.HOME;a&&(b=i.join(a,".config","gcloud"))}if(!b)return null;let c=i.join(b,"application_default_credentials.json");return e.existsSync(c)?await this._getApplicationCredentialsFromFilePath(c,a):null}async _getApplicationCredentialsFromFilePath(a,b={}){if(!a||0===a.length)throw Error("The file path is invalid.");try{if(a=e.realpathSync(a),!e.lstatSync(a).isFile())throw Error()}catch(b){throw b instanceof Error&&(b.message=`The file at ${a} does not exist, or it is not a file. ${b.message}`),b}let c=e.createReadStream(a);return this.fromStream(c,b)}fromImpersonatedJSON(a){if(!a)throw Error("Must pass in a JSON object containing an impersonated refresh token");if(a.type!==p.IMPERSONATED_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${p.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!a.source_credentials)throw Error("The incoming JSON object does not contain a source_credentials field");if(!a.service_account_impersonation_url)throw Error("The incoming JSON object does not contain a service_account_impersonation_url field");let b=this.fromJSON(a.source_credentials);if(a.service_account_impersonation_url?.length>256)throw RangeError(`Target principal is too long: ${a.service_account_impersonation_url}`);let c=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(a.service_account_impersonation_url)?.groups?.target;if(!c)throw RangeError(`Cannot extract target principal from ${a.service_account_impersonation_url}`);let d=(this.scopes||a.scopes||this.defaultScopes)??[];return new p.Impersonated({...a,sourceClient:b,targetPrincipal:c,targetScopes:Array.isArray(d)?d:[d]})}fromJSON(a,b={}){let c,d=(0,v.originalOrCamelOptions)(b).get("universe_domain");return a.type===o.USER_REFRESH_ACCOUNT_TYPE?(c=new o.UserRefreshClient(b)).fromJSON(a):a.type===p.IMPERSONATED_ACCOUNT_TYPE?c=this.fromImpersonatedJSON(a):a.type===r.EXTERNAL_ACCOUNT_TYPE?(c=q.ExternalAccountClient.fromJSON({...a,...b})).scopes=this.getAnyScopes():a.type===t.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?c=new t.ExternalAccountAuthorizedUserClient({...a,...b}):a.type===u.GDCH_SERVICE_ACCOUNT_TYPE?(c=new u.GdchClient(b)).fromJSON(a):(b.scopes=this.scopes,c=new n.JWT(b),this.setGapicJWTValues(c),c.fromJSON(a)),d&&(c.universeDomain=d),c}_cacheClientFromJSON(a,b){let c=this.fromJSON(a,b);return this.jsonContent=a,this.cachedCredential=c,c}fromStream(a,b={},c){let d={};if("function"==typeof b?c=b:d=b,!c)return this.fromStreamAsync(a,d);this.fromStreamAsync(a,d).then(a=>c(null,a),c)}fromStreamAsync(a,b){return new Promise((c,d)=>{if(!a)throw Error("Must pass in a stream containing the Google auth settings.");let e=[];a.setEncoding("utf8").on("error",d).on("data",a=>e.push(a)).on("end",()=>{try{try{let a=JSON.parse(e.join("")),d=this._cacheClientFromJSON(a,b);return c(d)}catch(b){if(!this.keyFilename)throw b;let a=new n.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=a,this.setGapicJWTValues(a),c(a)}}catch(a){return d(a)}})})}fromAPIKey(a,b={}){return new n.JWT({...b,apiKey:a})}_isWindows(){let a=h.platform();return!!a&&!!(a.length>=3)&&"win"===a.substring(0,3).toLowerCase()}async getDefaultServiceProjectId(){return new Promise(a=>{(0,d.exec)("gcloud config config-helper --format json",(b,c)=>{if(!b&&c)try{let b=JSON.parse(c).configuration.properties.core.project;a(b);return}catch(a){}a(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let a=await this.getClient();if(a&&a.projectId)return a.projectId}let a=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return a?a.projectId:null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==r.EXTERNAL_ACCOUNT_TYPE)return null;let a=await this.getClient();return await a.getProjectId()}async getGCEProjectId(){try{return await g.project("project-id")}catch(a){return null}}getCredentials(a){if(!a)return this.getCredentialsAsync();this.getCredentialsAsync().then(b=>a(null,b),a)}async getCredentialsAsync(){let a=await this.getClient();if(a instanceof p.Impersonated)return{client_email:a.getTargetPrincipal()};if(a instanceof r.BaseExternalAccountClient){let b=a.getServiceAccountEmail();if(b)return{client_email:b,universe_domain:a.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[a,b]=await Promise.all([g.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:a,universe_domain:b}}throw Error(b.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#cd=this.#cd||this.#cf();try{let a=await this.#cd;if(a instanceof u.GdchClient&&!a.apiAudience){let b=this.clientOptions,c=b.apiEndpoint||b.servicePath;if(c){let b=c.startsWith("http")?"":"https://",d=`${b}${c}`.replace(/\/+$/,""),e=a.createWithGdchAudience(d);return this.cachedCredential=e,e}}return a}finally{this.#cd=null}}async #cf(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let a=i.resolve(this.keyFilename),b=e.createReadStream(a);return await this.fromStreamAsync(b,this.clientOptions)}if(this.apiKey){let a=await this.fromAPIKey(this.apiKey,this.clientOptions);a.scopes=this.scopes;let{credential:b}=await this.#ce(a);return b}{let{credential:a}=await this.getApplicationDefaultAsync(this.clientOptions);return a}}async getIdTokenClient(a){let b=await this.getClient();if(!("fetchIdToken"in b))throw Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new l.IdTokenClient({targetAudience:a,idTokenProvider:b})}async getAccessToken(){let a=await this.getClient();return(await a.getAccessToken()).token}async getRequestHeaders(a){return(await this.getClient()).getRequestHeaders(a)}async authorizeRequest(a={}){let b=a.url,c=await this.getClient(),d=await c.getRequestHeaders(b);return a.headers=f.Gaxios.mergeHeaders(a.headers,d),a}async fetch(...a){return(await this.getClient()).fetch(...a)}async request(a){return(await this.getClient()).request(a)}getEnv(){return(0,m.getEnv)()}async sign(a,b){let c=await this.getClient(),d=await this.getUniverseDomain();if(b=b||`https://iamcredentials.${d}/v1/projects/-/serviceAccounts/`,c instanceof p.Impersonated)return(await c.sign(a)).signedBlob;let e=(0,j.createCrypto)();if(c instanceof n.JWT&&c.key)return await e.sign(c.key,a);let f=await this.getCredentials();if(!f.client_email)throw Error("Cannot sign data without `client_email`.");return this.signBlob(e,f.client_email,a,b)}async signBlob(a,b,c,d){let e=new URL(d+`${b}:signBlob`);return(await this.request({method:"POST",url:e.href,data:{payload:a.encodeBase64StringUtf8(c)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}b.GoogleAuth=w},95296:a=>{a.exports=function(){this.__data__=[],this.size=0}},95314:function(a,b,c){"use strict";var d;let e=(this&&this.__importDefault||function(a){return a&&a.__esModule?a:{default:a}})(c(30073));function f(a){return new e.default(a)}(d=f||(f={})).HttpsProxyAgent=e.default,d.prototype=e.default.prototype,a.exports=f},95570:(a,b,c)=>{"use strict";let d,{Duplex:e}=c(27910),{randomFillSync:f}=c(55511),{types:{isUint8Array:g}}=c(28354),h=c(24869),{EMPTY_BUFFER:i,kWebSocket:j,NOOP:k}=c(52712),{isBlob:l,isValidStatusCode:m}=c(32464),{mask:n,toBuffer:o}=c(15596),p=Symbol("kByteLength"),q=Buffer.alloc(4),r=8192;class s{constructor(a,b,c){this._extensions=b||{},c&&(this._generateMask=c,this._maskBuffer=Buffer.alloc(4)),this._socket=a,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=k,this[j]=void 0}static frame(a,b){let c,e,g=!1,h=2,i=!1;b.mask&&(c=b.maskBuffer||q,b.generateMask?b.generateMask(c):(8192===r&&(void 0===d&&(d=Buffer.alloc(8192)),f(d,0,8192),r=0),c[0]=d[r++],c[1]=d[r++],c[2]=d[r++],c[3]=d[r++]),i=(c[0]|c[1]|c[2]|c[3])==0,h=6),"string"==typeof a?e=(!b.mask||i)&&void 0!==b[p]?b[p]:(a=Buffer.from(a)).length:(e=a.length,g=b.mask&&b.readOnly&&!i);let j=e;e>=65536?(h+=8,j=127):e>125&&(h+=2,j=126);let k=Buffer.allocUnsafe(g?e+h:h);return(k[0]=b.fin?128|b.opcode:b.opcode,b.rsv1&&(k[0]|=64),k[1]=j,126===j?k.writeUInt16BE(e,2):127===j&&(k[2]=k[3]=0,k.writeUIntBE(e,4,6)),b.mask)?(k[1]|=128,k[h-4]=c[0],k[h-3]=c[1],k[h-2]=c[2],k[h-1]=c[3],i)?[k,a]:g?(n(a,c,k,h,e),[k]):(n(a,c,a,0,e),[k,a]):[k,a]}close(a,b,c,d){let e;if(void 0===a)e=i;else if("number"==typeof a&&m(a))if(void 0!==b&&b.length){let c=Buffer.byteLength(b);if(c>123)throw RangeError("The message must not be greater than 123 bytes");if((e=Buffer.allocUnsafe(2+c)).writeUInt16BE(a,0),"string"==typeof b)e.write(b,2);else if(g(b))e.set(b,2);else throw TypeError("Second argument must be a string or a Uint8Array")}else(e=Buffer.allocUnsafe(2)).writeUInt16BE(a,0);else throw TypeError("First argument must be a valid error code number");let f={[p]:e.length,fin:!0,generateMask:this._generateMask,mask:c,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,e,!1,f,d]):this.sendFrame(s.frame(e,f),d)}ping(a,b,c){let d,e;if("string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),d>125)throw RangeError("The data size must not be greater than 125 bytes");let f={[p]:d,fin:!0,generateMask:this._generateMask,mask:b,maskBuffer:this._maskBuffer,opcode:9,readOnly:e,rsv1:!1};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,!1,f,c]):this.getBlobData(a,!1,f,c):0!==this._state?this.enqueue([this.dispatch,a,!1,f,c]):this.sendFrame(s.frame(a,f),c)}pong(a,b,c){let d,e;if("string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),d>125)throw RangeError("The data size must not be greater than 125 bytes");let f={[p]:d,fin:!0,generateMask:this._generateMask,mask:b,maskBuffer:this._maskBuffer,opcode:10,readOnly:e,rsv1:!1};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,!1,f,c]):this.getBlobData(a,!1,f,c):0!==this._state?this.enqueue([this.dispatch,a,!1,f,c]):this.sendFrame(s.frame(a,f),c)}send(a,b,c){let d,e,f=this._extensions[h.extensionName],g=b.binary?2:1,i=b.compress;"string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),this._firstFragment?(this._firstFragment=!1,i&&f&&f.params[f._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=d>=f._threshold),this._compress=i):(i=!1,g=0),b.fin&&(this._firstFragment=!0);let j={[p]:d,fin:b.fin,generateMask:this._generateMask,mask:b.mask,maskBuffer:this._maskBuffer,opcode:g,readOnly:e,rsv1:i};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,this._compress,j,c]):this.getBlobData(a,this._compress,j,c):0!==this._state?this.enqueue([this.dispatch,a,this._compress,j,c]):this.dispatch(a,this._compress,j,c)}getBlobData(a,b,c,d){this._bufferedBytes+=c[p],this._state=2,a.arrayBuffer().then(a=>{if(this._socket.destroyed){let a=Error("The socket was closed while the blob was being read");process.nextTick(t,this,a,d);return}this._bufferedBytes-=c[p];let e=o(a);b?this.dispatch(e,b,c,d):(this._state=0,this.sendFrame(s.frame(e,c),d),this.dequeue())}).catch(a=>{process.nextTick(u,this,a,d)})}dispatch(a,b,c,d){if(!b)return void this.sendFrame(s.frame(a,c),d);let e=this._extensions[h.extensionName];this._bufferedBytes+=c[p],this._state=1,e.compress(a,c.fin,(a,b)=>{this._socket.destroyed?t(this,Error("The socket was closed while data was being compressed"),d):(this._bufferedBytes-=c[p],this._state=0,c.readOnly=!1,this.sendFrame(s.frame(b,c),d),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){let a=this._queue.shift();this._bufferedBytes-=a[3][p],Reflect.apply(a[0],this,a.slice(1))}}enqueue(a){this._bufferedBytes+=a[3][p],this._queue.push(a)}sendFrame(a,b){2===a.length?(this._socket.cork(),this._socket.write(a[0]),this._socket.write(a[1],b),this._socket.uncork()):this._socket.write(a[0],b)}}function t(a,b,c){"function"==typeof c&&c(b);for(let c=0;c<a._queue.length;c++){let d=a._queue[c],e=d[d.length-1];"function"==typeof e&&e(b)}}function u(a,b,c){t(a,b,c),a.onerror(b)}a.exports=s},95685:(a,b,c)=>{var d=c(38534),e=c(27934),f=c(47702),g={};g["[object Float32Array]"]=g["[object Float64Array]"]=g["[object Int8Array]"]=g["[object Int16Array]"]=g["[object Int32Array]"]=g["[object Uint8Array]"]=g["[object Uint8ClampedArray]"]=g["[object Uint16Array]"]=g["[object Uint32Array]"]=!0,g["[object Arguments]"]=g["[object Array]"]=g["[object ArrayBuffer]"]=g["[object Boolean]"]=g["[object DataView]"]=g["[object Date]"]=g["[object Error]"]=g["[object Function]"]=g["[object Map]"]=g["[object Number]"]=g["[object Object]"]=g["[object RegExp]"]=g["[object Set]"]=g["[object String]"]=g["[object WeakMap]"]=!1,a.exports=function(a){return f(a)&&e(a.length)&&!!g[d(a)]}},95699:function(a,b,c){"use strict";let d;var e,f=this&&this.__createBinding||(Object.create?function(a,b,c,d){void 0===d&&(d=c);var e=Object.getOwnPropertyDescriptor(b,c);(!e||("get"in e?!b.__esModule:e.writable||e.configurable))&&(e={enumerable:!0,get:function(){return b[c]}}),Object.defineProperty(a,d,e)}:function(a,b,c,d){void 0===d&&(d=c),a[d]=b[c]}),g=this&&this.__setModuleDefault||(Object.create?function(a,b){Object.defineProperty(a,"default",{enumerable:!0,value:b})}:function(a,b){a.default=b}),h=this&&this.__importStar||(e=function(a){return(e=Object.getOwnPropertyNames||function(a){var b=[];for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[b.length]=c);return b})(a)},function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c=e(a),d=0;d<c.length;d++)"default"!==c[d]&&f(b,a,c[d]);return g(b,a),b}),i=this&&this.__exportStar||function(a,b){for(var c in a)"default"===c||Object.prototype.hasOwnProperty.call(b,c)||f(b,a,c)};Object.defineProperty(b,"__esModule",{value:!0}),b.gcpResidencyCache=b.METADATA_SERVER_DETECTION=b.HEADERS=b.HEADER_VALUE=b.HEADER_NAME=b.SECONDARY_HOST_ADDRESS=b.HOST_ADDRESS=b.BASE_PATH=void 0,b.instance=function(a){return p("instance",a)},b.project=function(a){return p("project",a)},b.universe=function(a){return p("universe",a)},b.bulk=r,b.isAvailable=s,b.resetIsAvailableCache=function(){d=void 0},b.getGCPResidency=t,b.setGCPResidency=u,b.requestTimeout=v;let j=c(32184),k=c(72831),l=c(29314),m=h(c(25850));b.BASE_PATH="/computeMetadata/v1",b.HOST_ADDRESS="http://169.254.169.254",b.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.",b.HEADER_NAME="Metadata-Flavor",b.HEADER_VALUE="Google",b.HEADERS=Object.freeze({[b.HEADER_NAME]:b.HEADER_VALUE});let n=m.log("gcp-metadata");function o(a){return a||(a=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||b.HOST_ADDRESS),/^https?:\/\//.test(a)||(a=`http://${a}`),new URL(b.BASE_PATH,a).href}async function p(a,c={},d=3,e=!1){let f=new Headers(b.HEADERS),g="",h={};("object"==typeof a?(new Headers(a.headers).forEach((a,b)=>f.set(b,a)),g=a.metadataKey,h=a.params||h,d=a.noResponseRetries||d,e=a.fastFail||e):g=a,"string"==typeof c)?g+=`/${c}`:(Object.keys(c).forEach(a=>{switch(a){case"params":case"property":case"headers":break;case"qs":throw Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw Error(`'${a}' is not a valid configuration option.`)}}),c.property&&(g+=`/${c.property}`),new Headers(c.headers).forEach((a,b)=>f.set(b,a)),h=c.params||h);let i=e?q:j.request,l={url:`${o()}/${g}`,headers:f,retryConfig:{noResponseRetries:d},params:h,responseType:"text",timeout:v()};n.info("instance request %j",l);let m=await i(l);n.info("instance metadata is %s",m.data);let r=m.headers.get(b.HEADER_NAME);if(r!==b.HEADER_VALUE)throw RangeError(`Invalid response from metadata service: incorrect ${b.HEADER_NAME} header. Expected '${b.HEADER_VALUE}', got ${r?`'${r}'`:"no header"}`);if("string"==typeof m.data)try{return k.parse(m.data)}catch{}return m.data}async function q(a){let c={...a,url:a.url?.toString().replace(o(),o(b.SECONDARY_HOST_ADDRESS))};return Promise.any([(0,j.request)(a),(0,j.request)(c)])}async function r(a){let b={};return await Promise.all(a.map(a=>(async()=>{let c=await p(a);b[a.metadataKey]=c})())),b}async function s(){if(process.env.METADATA_SERVER_DETECTION){let a=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(a in b.METADATA_SERVER_DETECTION))throw RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${a}\`, but it should be \`${Object.keys(b.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(a){case"assume-present":return!0;case"none":return!1;case"bios-only":return t()}}try{return void 0===d&&(d=p("instance",void 0,process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0,!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await d,!0}catch(a){if(process.env.DEBUG_AUTH&&console.info(a),"request-timeout"===a.type||a.response&&404===a.response.status)return!1;if(!(a.response&&404===a.response.status)&&(!a.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(a.code.toString()))){let b="UNKNOWN";a.code&&(b=a.code.toString()),process.emitWarning(`received unexpected error = ${a.message} code = ${b}`,"MetadataLookupWarning")}return!1}}function t(){return null===b.gcpResidencyCache&&u(),b.gcpResidencyCache}function u(a=null){b.gcpResidencyCache=null!==a?a:(0,l.detectGCPResidency)()}function v(){return 3e3*!t()}b.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"}),b.gcpResidencyCache=null,i(c(29314),b)},95979:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});let d=c(87204),e=c(78276),f=c(65042),g=c(94134);b.default={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,e._)`{additionalProperty: ${a.additionalProperty}}`},code(a){let{gen:b,schema:c,parentSchema:h,data:i,errsCount:j,it:k}=a;if(!j)throw Error("ajv implementation error");let{allErrors:l,opts:m}=k;if(k.props=!0,"all"!==m.removeAdditional&&(0,g.alwaysValidSchema)(k,c))return;let n=(0,d.allSchemaProperties)(h.properties),o=(0,d.allSchemaProperties)(h.patternProperties);function p(a){b.code((0,e._)`delete ${i}[${a}]`)}function q(d){if("all"===m.removeAdditional||m.removeAdditional&&!1===c)return void p(d);if(!1===c){a.setParams({additionalProperty:d}),a.error(),l||b.break();return}if("object"==typeof c&&!(0,g.alwaysValidSchema)(k,c)){let c=b.name("valid");"failing"===m.removeAdditional?(r(d,c,!1),b.if((0,e.not)(c),()=>{a.reset(),p(d)})):(r(d,c),l||b.if((0,e.not)(c),()=>b.break()))}}function r(b,c,d){let e={keyword:"additionalProperties",dataProp:b,dataPropType:g.Type.Str};!1===d&&Object.assign(e,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(e,c)}b.forIn("key",i,c=>{n.length||o.length?b.if(function(c){let f;if(n.length>8){let a=(0,g.schemaRefOrVal)(k,h.properties,"properties");f=(0,d.isOwnProperty)(b,a,c)}else f=n.length?(0,e.or)(...n.map(a=>(0,e._)`${c} === ${a}`)):e.nil;return o.length&&(f=(0,e.or)(f,...o.map(b=>(0,e._)`${(0,d.usePattern)(a,b)}.test(${c})`))),(0,e.not)(f)}(c),()=>q(c)):q(c)}),a.ok((0,e._)`${j} === ${f.default.errors}`)}}},96001:(a,b,c)=>{var d=c(34314),e=c(43677),f=c(76148),g=c(26959),h=c(93137),i=c(38534),j=c(70757),k="[object Map]",l="[object Promise]",m="[object Set]",n="[object WeakMap]",o="[object DataView]",p=j(d),q=j(e),r=j(f),s=j(g),t=j(h),u=i;(d&&u(new d(new ArrayBuffer(1)))!=o||e&&u(new e)!=k||f&&u(f.resolve())!=l||g&&u(new g)!=m||h&&u(new h)!=n)&&(u=function(a){var b=i(a),c="[object Object]"==b?a.constructor:void 0,d=c?j(c):"";if(d)switch(d){case p:return o;case q:return k;case r:return l;case s:return m;case t:return n}return b}),a.exports=u},96233:function(a,b,c){"use strict";let d;var e,f,g,h=this&&this.__createBinding||(Object.create?function(a,b,c,d){void 0===d&&(d=c);var e=Object.getOwnPropertyDescriptor(b,c);(!e||("get"in e?!b.__esModule:e.writable||e.configurable))&&(e={enumerable:!0,get:function(){return b[c]}}),Object.defineProperty(a,d,e)}:function(a,b,c,d){void 0===d&&(d=c),a[d]=b[c]}),i=this&&this.__setModuleDefault||(Object.create?function(a,b){Object.defineProperty(a,"default",{enumerable:!0,value:b})}:function(a,b){a.default=b}),j=this&&this.__importStar||(e=function(a){return(e=Object.getOwnPropertyNames||function(a){var b=[];for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[b.length]=c);return b})(a)},function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c=e(a),d=0;d<c.length;d++)"default"!==c[d]&&h(b,a,c[d]);return i(b,a),b});Object.defineProperty(b,"__esModule",{value:!0}),b.env=b.DebugLogBackendBase=b.placeholder=b.AdhocDebugLogger=b.LogSeverity=void 0,b.getNodeBackend=r,b.getDebugBackend=function(a){return new s(a)},b.getStructuredBackend=function(a){return new t(a)},b.setBackend=function(a){d=a,u.clear()},b.log=v;let k=c(94735),l=j(c(19771)),m=j(c(28354)),n=c(24709);(f=g||(b.LogSeverity=g={})).DEFAULT="DEFAULT",f.DEBUG="DEBUG",f.INFO="INFO",f.WARNING="WARNING",f.ERROR="ERROR";class o extends k.EventEmitter{constructor(a,b){super(),this.namespace=a,this.upstream=b,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(a,b)=>this.on(a,b)}),this.func.debug=(...a)=>this.invokeSeverity(g.DEBUG,...a),this.func.info=(...a)=>this.invokeSeverity(g.INFO,...a),this.func.warn=(...a)=>this.invokeSeverity(g.WARNING,...a),this.func.error=(...a)=>this.invokeSeverity(g.ERROR,...a),this.func.sublog=a=>v(a,this.func)}invoke(a,...b){if(this.upstream)try{this.upstream(a,...b)}catch(a){}try{this.emit("log",a,b)}catch(a){}}invokeSeverity(a,...b){this.invoke({severity:a},...b)}}b.AdhocDebugLogger=o,b.placeholder=new o("",()=>{}).func;class p{constructor(){var a;this.cached=new Map,this.filters=[],this.filtersSet=!1;let c=null!=(a=l.env[b.env.nodeEnables])?a:"*";"all"===c&&(c="*"),this.filters=c.split(",")}log(a,b,...c){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let d=this.cached.get(a);d||(d=this.makeLogger(a),this.cached.set(a,d)),d(b,...c)}catch(a){console.error(a)}}}b.DebugLogBackendBase=p;class q extends p{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(a){return this.enabledRegexp.test(a)}makeLogger(a){return this.enabledRegexp.test(a)?(b,...c)=>{var d;let e,f=`${n.Colours.green}${a}${n.Colours.reset}`,h=`${n.Colours.yellow}${l.pid}${n.Colours.reset}`;switch(b.severity){case g.ERROR:e=`${n.Colours.red}${b.severity}${n.Colours.reset}`;break;case g.INFO:e=`${n.Colours.magenta}${b.severity}${n.Colours.reset}`;break;case g.WARNING:e=`${n.Colours.yellow}${b.severity}${n.Colours.reset}`;break;default:e=null!=(d=b.severity)?d:g.DEFAULT}let i=m.formatWithOptions({colors:n.Colours.enabled},...c),j=Object.assign({},b);delete j.severity;let k=Object.getOwnPropertyNames(j).length?JSON.stringify(j):"",o=k?`${n.Colours.grey}${k}${n.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",h,f,e,i,k?` ${o}`:"")}:()=>{}}setFilters(){let a=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=RegExp(`^${a}$`,"i")}}function r(){return new q}class s extends p{constructor(a){super(),this.debugPkg=a}makeLogger(a){let b=this.debugPkg(a);return(a,...c)=>{b(c[0],...c.slice(1))}}setFilters(){var a;let b=null!=(a=l.env.NODE_DEBUG)?a:"";l.env.NODE_DEBUG=`${b}${b?",":""}${this.filters.join(",")}`}}class t extends p{constructor(a){super(),this.upstream=null!=a?a:void 0}makeLogger(a){var b;let c=null==(b=this.upstream)?void 0:b.makeLogger(a);return(a,...b)=>{var d;let e=JSON.stringify(Object.assign({severity:null!=(d=a.severity)?d:g.INFO,message:m.format(...b)},a));c?c(a,e):console.log("%s",e)}}setFilters(){var a;null==(a=this.upstream)||a.setFilters()}}b.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};let u=new Map;function v(a,c){let e;if(!d&&!l.env[b.env.nodeEnables]||!a)return b.placeholder;c&&(a=`${c.instance.namespace}:${a}`);let f=u.get(a);if(f)return f.func;if(null===d)return b.placeholder;void 0===d&&(d=r());let g=new o(a,(b,...c)=>{if(e!==d){if(null===d)return;void 0===d&&(d=r()),e=d}null==d||d.log(a,b,...c)});return u.set(a,g),g.func}},96363:(a,b,c)=>{var d=c(81598);a.exports=function(){try{var a=d(Object,"defineProperty");return a({},"",{}),a}catch(a){}}()},96436:(a,b,c)=>{"use strict";function d(a,b,c,d,e){if("m"===d)throw TypeError("Private method is not writable");if("a"===d&&!e)throw TypeError("Private accessor was defined without a setter");if("function"==typeof b?a!==b||!e:!b.has(a))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===d?e.call(a,c):e?e.value=c:b.set(a,c),c}function e(a,b,c,d){if("a"===c&&!d)throw TypeError("Private accessor was defined without a getter");if("function"==typeof b?a!==b||!d:!b.has(a))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===c?d:"a"===c?d.call(a):d?d.value:b.get(a)}c.d(b,{G:()=>d,g:()=>e})},96450:(a,b,c)=>{"use strict";c.d(b,{_T:()=>ae,qU:()=>y,vd:()=>af});var d=c(55511),e=c(79646),f=c(29021),g=c(33873),h=c.n(g),i=c(28354),j=c(46024);c(4669);var k=c(62471),l=c(28461);let m=(0,k.H)(),n=[".runtime-locks","enduring-agents"],o=["darwin","linux","win32"].includes(process.platform),p=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,q=(0,i.promisify)(e.execFile),r=async(a,b,c)=>{let{stdout:d}=await q(a,b,c);return{stdout:String(d)}},s=global.__flujo_enduring_agent_process_instance_id??=(0,d.randomUUID)(),t=global.__flujo_enduring_agent_active_lock_owners??=new Set,u=global.__flujo_enduring_agent_issued_runtime_lock_scopes_v2??=new WeakMap,v=global.__flujo_enduring_agent_deferred_lock_cleanups??=new Set,w=new Map,x=new Map;async function y(a,b,c){let d=function(a,b){let c=u.get(a);if(!c||c.personaId!==b||c.workspace!==(0,l.getCurrentWorkspace)())throw Error("Persona runtime lock capability was not issued by this runtime.");return c}(a,b);if(d.closing)throw Error("Persona runtime lock capability is closing.");d.activeOperations+=1;try{return await a.assertOwned(),await c()}finally{if(d.activeOperations-=1,0===d.activeOperations){for(let a of d.idleWaiters)a();d.idleWaiters.clear()}}}async function z(a){let b=u.get(a);b&&(b.closing=!0,b.activeOperations>0&&await new Promise(a=>b.idleWaiters.add(a)))}class A extends Error{constructor(a){super(`Timed out acquiring the runtime lock for Persona ${JSON.stringify(a)}.`),this.personaId=a,this.code="PERSONA_RUNTIME_LOCK_TIMEOUT",this.name="PersonaRuntimeLockTimeoutError"}}class B extends Error{constructor(a){super(`Lost the runtime lock for Persona ${JSON.stringify(a)}.`),this.personaId=a,this.code="PERSONA_RUNTIME_LOCK_LOST",this.name="PersonaRuntimeLockLostError"}}function C(a){return m.sleep(a)}async function D(){await (0,l.ensureWorkspaceDirs)((0,l.getCurrentWorkspace)());let a=h().resolve((0,l.getWorkspaceDbDir)()),b=h().join(a,...n);await f.promises.mkdir(b,{recursive:!0});let[c,d]=await Promise.all([f.promises.realpath(a),f.promises.realpath(b)]),e=h().relative(c,d);if(""===e||e.startsWith("..")||h().isAbsolute(e))throw Error(`Persona runtime lock root escapes the workspace database: ${b}`);return d}async function E(a){try{let b=JSON.parse(await f.promises.readFile(a,"utf8"));if(!b||"object"!=typeof b||Array.isArray(b))throw Error(`Persona runtime lock ${JSON.stringify(a)} is malformed.`);return b}catch(a){if("ENOENT"===a.code)return null;throw a}}function F(a,b){if("string"!=typeof b.ownerId||!p.test(b.ownerId)||"string"!=typeof b.processInstanceId||"number"!=typeof b.pid||!Number.isInteger(b.pid)||b.pid<=0||void 0!==b.processBirthMarker&&"string"!=typeof b.processBirthMarker||void 0!==b.processBirthMarkerV2&&"string"!=typeof b.processBirthMarkerV2||"string"!=typeof b.workspace||"number"!=typeof b.acquiredAt)throw Error(`Persona runtime lock ${JSON.stringify(a)} is malformed.`);return b}async function G(a){let b=await E(a);return b?F(a,b):null}async function H(a){let b=await E(a);if(!b)return null;let c=F(a,b);if("string"!=typeof b.targetOwnerId||!p.test(b.targetOwnerId)||"string"!=typeof b.targetProcessInstanceId||"number"!=typeof b.targetPid||!Number.isInteger(b.targetPid)||b.targetPid<=0)throw Error(`Persona runtime recovery lock ${JSON.stringify(a)} is malformed.`);return{...c,...b}}async function I(a,b){let c=`${h().basename(b)}.recovery.`,d=(await f.promises.readdir(a)).filter(a=>a.startsWith(c)&&p.test(a.slice(c.length)));return(await Promise.all(d.map(async b=>{let c=h().join(a,b),d=await H(c);return d?{path:c,owner:d}:null}))).filter(a=>null!==a)}function J(a,b){if(!p.test(b))throw Error(`Persona runtime lock owner id ${JSON.stringify(b)} is malformed.`);let c=h().dirname(a),d=h().join(c,`${h().basename(a)}.abandoned.${b}`);if(h().dirname(d)!==c)throw Error("Persona runtime abandonment marker escapes its lock directory.");return d}async function K(a,b){let c=`${h().basename(b)}.abandoned.`;return new Set((await f.promises.readdir(a)).filter(a=>a.startsWith(c)&&p.test(a.slice(c.length))).map(a=>a.slice(c.length)))}async function L(a,b,c){let d=J(b,c.ownerId);return await $(a,d,c),d}async function M(a){try{await Y(a)}catch{}}async function N(){let a=global.__flujo_enduring_agent_linux_boot_id??=f.promises.readFile("/proc/sys/kernel/random/boot_id","utf8").then(a=>a.trim()||null).catch(()=>null),b=await a;return b||global.__flujo_enduring_agent_linux_boot_id!==a||(global.__flujo_enduring_agent_linux_boot_id=void 0),b}async function O(a){let b=process.env.SystemRoot??process.env.WINDIR;if(!b||!h().win32.isAbsolute(b))return null;let c=h().win32.normalize(b);if(!/^[a-z]:\\/i.test(c))return null;let d=h().win32.join(c,"System32","WindowsPowerShell","v1.0","powershell.exe"),{stdout:e}=await r(d,["-NoProfile","-NonInteractive","-Command",`$p=Get-Process -Id ${a} -ErrorAction Stop; $p.StartTime.ToUniversalTime().Ticks`],{encoding:"utf8",timeout:a===process.pid?3e3:900,windowsHide:!0}),f=e.trim();return/^[1-9]\d*$/.test(f)?`win32-v2:${f}`:null}async function P(a){if("linux"===process.platform){let[b,c]=await Promise.all([f.promises.readFile(`/proc/${a}/stat`,"utf8"),N()]);if(!c)return null;let d=b.lastIndexOf(")");if(d<0)return null;let e=b.slice(d+1).trim().split(/\s+/);if("Z"===e[0])return"dead:linux-zombie";let g=e[19];return g?`linux-v2:${c}:${g}`:null}if("win32"===process.platform)return O(a);if("darwin"===process.platform){let{stdout:b}=await r("/bin/ps",["-o","state=","-o","lstart=","-p",String(a)],{encoding:"utf8",timeout:3e3,env:{...process.env,LANG:"C",LC_ALL:"C",TZ:"UTC"}}),c=b.trim(),d=/^(\S+)\s+(.+)$/.exec(c);return d?d[1].includes("Z")?"dead:darwin-zombie":`darwin-v2:${d[2].trim()}`:null}return null}async function Q(a){try{let b=await P(a);return b?{marker:b}:{marker:null,failure:"probe returned no valid birth identity"}}catch(b){let a="string"==typeof b?.code&&/^[A-Z0-9_]{1,32}$/.test(b.code)?b.code:void 0;return{marker:null,failure:b?.killed===!0||"ETIMEDOUT"===a?"process birth probe timed out":`process birth probe failed${a?` (${a})`:""}`}}}async function R(a){return(await Q(a)).marker}async function S(){if(!o)return R(process.pid);let a="probe returned no valid birth identity";for(let b=0;b<3;b+=1){let c=await Q(process.pid);if(c.marker&&V(c.marker))return c.marker;a=c.failure??"probe returned an invalid birth identity",b+1<3&&await C(100)}throw Error(`Unable to establish this process birth identity for Persona locking. Failed after 3 attempts: ${a}.`)}async function T(){let a=global.__flujo_enduring_agent_process_birth_marker_v2??=S();try{let b=await a;if(o&&(!b||!V(b)))throw Error("Unable to establish this process birth identity for Persona locking. Shared process birth identity is missing or invalid.");return b||global.__flujo_enduring_agent_process_birth_marker_v2!==a||(global.__flujo_enduring_agent_process_birth_marker_v2=void 0),b}catch(b){throw global.__flujo_enduring_agent_process_birth_marker_v2===a&&(global.__flujo_enduring_agent_process_birth_marker_v2=void 0),b}}async function U(a){if(a===process.pid)return T();let b=w.get(a);if(b&&m.monotonicNow()-b.checkedAt<1e3)return b.marker;let c=x.get(a);if(c)return c;let d=R(a).then(b=>(w.set(a,{checkedAt:m.monotonicNow(),marker:b}),b)).finally(()=>{x.get(a)===d&&x.delete(a)});return x.set(a,d),d}function V(a){return/^linux-v2:[0-9a-f-]{36}:\d+$/i.test(a)?"linux-v2":/^darwin-v2:[A-Z][a-z]{2} [A-Z][a-z]{2}\s+\d{1,2} \d{2}:\d{2}:\d{2} \d{4}$/.test(a)?"darwin-v2":/^win32-v2:\d+$/.test(a)?"win32-v2":null}function W(a,b){if(b.startsWith("dead:"))return!0;let c=V(a);return!!(c&&c===V(b)&&a!==b)}async function X(a,b){if(b.has(a.ownerId))return!1;if(a.pid===process.pid){let b=await T();return!(a.processBirthMarkerV2&&b&&W(a.processBirthMarkerV2,b))&&(a.processInstanceId===s?t.has(a.ownerId):!a.processBirthMarkerV2||!b||!W(a.processBirthMarkerV2,b))}if(!function(a){try{return process.kill(a,0),!0}catch(a){if("ESRCH"===a.code)return!1;return!0}}(a.pid))return!1;if(!a.processBirthMarkerV2){let b=await U(a.pid);return b?.startsWith("dead:")&&(b=await R(a.pid),w.set(a.pid,{checkedAt:m.monotonicNow(),marker:b})),!b?.startsWith("dead:")}let c=await U(a.pid);return c&&W(a.processBirthMarkerV2,c)&&(c=await R(a.pid),w.set(a.pid,{checkedAt:m.monotonicNow(),marker:c})),!c||!W(a.processBirthMarkerV2,c)}async function Y(a){for(let b=0;b<20;b+=1)try{await f.promises.unlink(a);return}catch(c){let a=c.code;if("ENOENT"===a)return;if(!["EACCES","EBUSY","EPERM"].includes(a??"")||19===b)throw c;await C(25)}}async function Z(a,b,c){let e=h().join(a,`${h().basename(b)}.candidate.${(0,d.randomUUID)()}`);try{await f.promises.writeFile(e,JSON.stringify(c),{encoding:"utf8",flag:"wx"});try{return await f.promises.link(e,b),!0}catch(a){if("EEXIST"===a.code)return!1;throw a}}finally{try{await f.promises.unlink(e)}catch{}}}async function $(a,b,c){let d=m.monotonicNow();for(;;)try{return await Z(a,b,c)}catch(a){if(!["EACCES","EBUSY","EPERM"].includes(a.code??"")||m.monotonicNow()-d>=15e3)throw a;await C(25)}}function _(a){return new Promise(b=>{m.setTimer(b,a).unref()})}async function aa(a,b,c,e){let f=await T(),g={ownerId:(0,d.randomUUID)(),processInstanceId:s,pid:process.pid,...f?{processBirthMarkerV2:f}:{},workspace:(0,l.getCurrentWorkspace)(),acquiredAt:m.now(),targetOwnerId:c.ownerId,targetProcessInstanceId:c.processInstanceId,targetPid:c.pid},h=`${b}.recovery.${g.ownerId}`;t.add(g.ownerId);let i=!1;try{if(!(i=await $(a,h,g)))throw Error(`Recovery intent ${JSON.stringify(g.ownerId)} already exists.`);return await e(g)}finally{if(i){let c=null;try{c=await L(a,b,g)}catch{}t.delete(g.ownerId);try{await Y(h),c&&await M(c)}catch{let c;c=`intent:${h}`,v.has(c)||(v.add(c),(async()=>{for(;;){let c=null;try{c=await L(a,b,g)}catch{}t.delete(g.ownerId);try{await Y(h),c&&await M(c);return}catch{await _(1e3)}}})().finally(()=>{v.delete(c)}))}}else t.delete(g.ownerId)}}async function ab(a,b,c){await aa(a,b,c,async()=>{let d=null;try{d=await L(a,b,c)}finally{t.delete(c.ownerId)}let e=!1;try{let a=await G(b);a?.ownerId===c.ownerId&&a.processInstanceId===c.processInstanceId&&a.pid===c.pid&&await Y(b),e=!0}finally{e&&d&&await M(d)}})}function ac(a,b,c){let d=`canonical:${b}:${c.ownerId}`;v.has(d)||(v.add(d),(async()=>{for(;;)try{await ab(a,b,c);return}catch{try{let a=await G(b);if(!a||a.ownerId!==c.ownerId||a.processInstanceId!==c.processInstanceId||a.pid!==c.pid)return}catch{}await _(1e3)}})().finally(()=>{v.delete(d)}))}async function ad(a){let b=await D(),c=h().join(b,`${a}.lock`),e=await T(),f={ownerId:(0,d.randomUUID)(),processInstanceId:s,pid:process.pid,...e?{processBirthMarkerV2:e}:{},workspace:(0,l.getCurrentWorkspace)(),acquiredAt:m.now()};t.add(f.ownerId);let g=m.monotonicNow(),i=!1;try{for(;;){let[d,e]=await Promise.all([I(b,c),K(b,c)]),h=await Promise.all(d.map(async a=>({...a,alive:await X(a.owner,e)}))),j=h.filter(a=>a.alive);if(await Promise.all(h.filter(a=>!a.alive).map(async({path:a,owner:b})=>{await Y(a),await M(J(c,b.ownerId))})),j.length>0){if(m.monotonicNow()-g>=15e3)throw new A(a);await C(25);continue}if(i){let a=await G(c);if(a?.ownerId===f.ownerId&&a.processInstanceId===f.processInstanceId&&a.pid===f.pid)break;i=!1}if(await $(b,c,f)){i=!0;let[a,d]=await Promise.all([I(b,c),K(b,c)]);if((await Promise.all(a.map(({owner:a})=>X(a,d)))).some(Boolean)){await C(25);continue}let e=await G(c);if(e?.ownerId===f.ownerId&&e.processInstanceId===f.processInstanceId&&e.pid===f.pid)break;i=!1;continue}let k=await G(c);if(k){if(!await X(k,e)){await aa(b,c,k,async a=>{let d=await G(c),e=await K(b,c);d&&d.ownerId===a.targetOwnerId&&d.processInstanceId===a.targetProcessInstanceId&&d.pid===a.targetPid&&!await X(d,e)&&(await Y(c),await M(J(c,d.ownerId)))});continue}if(m.monotonicNow()-g>=15e3)throw new A(a);await C(25)}}}catch(a){try{if(i)try{await ab(b,c,f)}catch(a){throw ac(b,c,f),a}}finally{t.delete(f.ownerId)}throw a}let j=async()=>{let b=await G(c);if(b?.ownerId!==f.ownerId||b.processInstanceId!==f.processInstanceId||b.pid!==f.pid||b.workspace!==f.workspace)throw new B(a)},k={assertOwned:j};return u.set(k,{personaId:a,workspace:f.workspace,closing:!1,activeOperations:0,idleWaiters:new Set}),{lock:k,release:async()=>{let a;await z(k);try{await j()}catch(b){a=b}try{try{await ab(b,c,f)}catch(a){throw ac(b,c,f),a}}finally{t.delete(f.ownerId),u.delete(k)}if(a)throw a}}}function ae(a,b){return(0,j.ln)(a),(0,j.l_)(`enduring-agent-runtime/${a}`,async()=>{let c=await ad(a);try{return await b(c.lock)}finally{await c.release()}})}function af(a,b){(0,j.ln)(a);let c=`.${a}`;return(0,j.l_)(`workspace-runtime/${a}`,async()=>{let a=await ad(c);try{return await b(a.lock)}finally{await a.release()}})}},96451:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),b.LRUCache=void 0,b.snakeToCamel=h,b.originalOrCamelOptions=function(a){return{get:function(b){let c=a||{};return c[b]??c[h(b)]}}},b.removeUndefinedValuesInObject=function(a){return Object.entries(a).forEach(([b,c])=>{(void 0===c||"undefined"===c)&&delete a[b]}),a},b.isValidFile=j,b.getWellKnownCertificateConfigFileLocation=function(){let a=process.env.CLOUDSDK_CONFIG||(e.platform().startsWith("win")?f.join(process.env.APPDATA||"",g):f.join(process.env.HOME||"",".config",g));return f.join(a,"certificate_config.json")};let d=c(29021),e=c(21820),f=c(33873),g="gcloud";function h(a){return a.replace(/([_][^_])/g,a=>a.slice(1).toUpperCase())}class i{capacity;#cg=new Map;maxAge;constructor(a){this.capacity=a.capacity,this.maxAge=a.maxAge}#ch(a,b){this.#cg.delete(a),this.#cg.set(a,{value:b,lastAccessed:Date.now()})}set(a,b){this.#ch(a,b),this.#ci()}get(a){let b=this.#cg.get(a);if(b)return this.#ch(a,b.value),this.#ci(),b.value}#ci(){let a=this.maxAge?Date.now()-this.maxAge:0,b=this.#cg.entries().next();for(;!b.done&&(this.#cg.size>this.capacity||b.value[1].lastAccessed<a);)this.#cg.delete(b.value[0]),b=this.#cg.entries().next()}}async function j(a){try{return(await d.promises.lstat(a)).isFile()}catch(a){return!1}}b.LRUCache=i},96650:(a,b,c)=>{"use strict";function d(a,b,c){if(!a)throw Error(`${c} does not support task creation (required for ${b})`);if("tools/call"===b&&!a.tools?.call)throw Error(`${c} does not support task creation for tools/call (required for ${b})`)}function e(a,b,c){if(!a)throw Error(`${c} does not support task creation (required for ${b})`);switch(b){case"sampling/createMessage":if(!a.sampling?.createMessage)throw Error(`${c} does not support task creation for sampling/createMessage (required for ${b})`);break;case"elicitation/create":if(!a.elicitation?.create)throw Error(`${c} does not support task creation for elicitation/create (required for ${b})`)}}c.d(b,{s:()=>e,z:()=>d})},96694:a=>{"use strict";let b="win32"===process.platform;function c(a,b){return Object.assign(Error(`${b} ${a.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${b} ${a.command}`,path:a.command,spawnargs:a.args})}function d(a,d){return b&&1===a&&!d.file?c(d.original,"spawn"):null}a.exports={hookChildProcess:function(a,c){if(!b)return;let e=a.emit;a.emit=function(b,f){if("exit"===b){let b=d(f,c);if(b)return e.call(a,"error",b)}return e.apply(a,arguments)}},verifyENOENT:d,verifyENOENTSync:function(a,d){return b&&1===a&&!d.file?c(d.original,"spawnSync"):null},notFoundError:c}},96809:(a,b,c)=>{"use strict";c.d(b,{e:()=>i,h:()=>j});var d=c(46024),e=c(28461),f=c(53348),g=c(87512);function h(a,b,c){let d=g.jc.parse(b);if(d.id!==a||d.workspaceId!==c)throw Error(`PersonaFlowDispatchRecord ${JSON.stringify(a)} has mismatched storage identity or workspace.`);return d}async function i(a){(0,d.ln)(a);let b=(0,e.getCurrentWorkspace)();return(await (0,d.$G)(f.p.flowDispatches)).map(({id:a,item:c})=>h(a,c,b)).filter(b=>b.personaId===a).sort((a,b)=>a.createdAt-b.createdAt||a.id.localeCompare(b.id))}function j(a){let b=g.jc.parse(a),c=(0,e.getCurrentWorkspace)();if(b.workspaceId!==c)throw Error(`PersonaFlowDispatchRecord ${JSON.stringify(b.id)} belongs to another workspace.`);return(0,d.ln)(b.id),(0,d.l_)(`enduring-agent:${f.p.flowDispatches}/${b.id}`,async()=>{let a=await (0,d.EI)(f.p.flowDispatches,b.id,null);if(null===a)throw Error(`Cannot compact missing PersonaFlowDispatchRecord ${JSON.stringify(b.id)}.`);let e=h(b.id,a,c);if(e.personaId!==b.personaId||e.createdAt!==b.createdAt||e.updatedAt!==b.updatedAt||e.state!==b.state)throw Error("PersonaFlowDispatchRecord changed during retention compaction.");return await (0,d.Vt)(f.p.flowDispatches,b.id,b),b})}},97151:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),b.or=b.and=b.not=b.CodeGen=b.operators=b.varKinds=b.ValueScopeName=b.ValueScope=b.Scope=b.Name=b.regexpCode=b.stringify=b.getProperty=b.nil=b.strConcat=b.str=b._=void 0;let d=c(89670),e=c(61591);var f=c(89670);Object.defineProperty(b,"_",{enumerable:!0,get:function(){return f._}}),Object.defineProperty(b,"str",{enumerable:!0,get:function(){return f.str}}),Object.defineProperty(b,"strConcat",{enumerable:!0,get:function(){return f.strConcat}}),Object.defineProperty(b,"nil",{enumerable:!0,get:function(){return f.nil}}),Object.defineProperty(b,"getProperty",{enumerable:!0,get:function(){return f.getProperty}}),Object.defineProperty(b,"stringify",{enumerable:!0,get:function(){return f.stringify}}),Object.defineProperty(b,"regexpCode",{enumerable:!0,get:function(){return f.regexpCode}}),Object.defineProperty(b,"Name",{enumerable:!0,get:function(){return f.Name}});var g=c(61591);Object.defineProperty(b,"Scope",{enumerable:!0,get:function(){return g.Scope}}),Object.defineProperty(b,"ValueScope",{enumerable:!0,get:function(){return g.ValueScope}}),Object.defineProperty(b,"ValueScopeName",{enumerable:!0,get:function(){return g.ValueScopeName}}),Object.defineProperty(b,"varKinds",{enumerable:!0,get:function(){return g.varKinds}}),b.operators={GT:new d._Code(">"),GTE:new d._Code(">="),LT:new d._Code("<"),LTE:new d._Code("<="),EQ:new d._Code("==="),NEQ:new d._Code("!=="),NOT:new d._Code("!"),OR:new d._Code("||"),AND:new d._Code("&&"),ADD:new d._Code("+")};class h{optimizeNodes(){return this}optimizeNames(a,b){return this}}class i extends h{constructor(a,b,c){super(),this.varKind=a,this.name=b,this.rhs=c}render({es5:a,_n:b}){let c=a?e.varKinds.var:this.varKind,d=void 0===this.rhs?"":` = ${this.rhs}`;return`${c} ${this.name}${d};`+b}optimizeNames(a,b){if(a[this.name.str])return this.rhs&&(this.rhs=G(this.rhs,a,b)),this}get names(){return this.rhs instanceof d._CodeOrName?this.rhs.names:{}}}class j extends h{constructor(a,b,c){super(),this.lhs=a,this.rhs=b,this.sideEffects=c}render({_n:a}){return`${this.lhs} = ${this.rhs};`+a}optimizeNames(a,b){if(!(this.lhs instanceof d.Name)||a[this.lhs.str]||this.sideEffects)return this.rhs=G(this.rhs,a,b),this}get names(){return F(this.lhs instanceof d.Name?{}:{...this.lhs.names},this.rhs)}}class k extends j{constructor(a,b,c,d){super(a,c,d),this.op=b}render({_n:a}){return`${this.lhs} ${this.op}= ${this.rhs};`+a}}class l extends h{constructor(a){super(),this.label=a,this.names={}}render({_n:a}){return`${this.label}:`+a}}class m extends h{constructor(a){super(),this.label=a,this.names={}}render({_n:a}){let b=this.label?` ${this.label}`:"";return`break${b};`+a}}class n extends h{constructor(a){super(),this.error=a}render({_n:a}){return`throw ${this.error};`+a}get names(){return this.error.names}}class o extends h{constructor(a){super(),this.code=a}render({_n:a}){return`${this.code};`+a}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(a,b){return this.code=G(this.code,a,b),this}get names(){return this.code instanceof d._CodeOrName?this.code.names:{}}}class p extends h{constructor(a=[]){super(),this.nodes=a}render(a){return this.nodes.reduce((b,c)=>b+c.render(a),"")}optimizeNodes(){let{nodes:a}=this,b=a.length;for(;b--;){let c=a[b].optimizeNodes();Array.isArray(c)?a.splice(b,1,...c):c?a[b]=c:a.splice(b,1)}return a.length>0?this:void 0}optimizeNames(a,b){let{nodes:c}=this,d=c.length;for(;d--;){let e=c[d];e.optimizeNames(a,b)||(function(a,b){for(let c in b)a[c]=(a[c]||0)-(b[c]||0)}(a,e.names),c.splice(d,1))}return c.length>0?this:void 0}get names(){return this.nodes.reduce((a,b)=>E(a,b.names),{})}}class q extends p{render(a){return"{"+a._n+super.render(a)+"}"+a._n}}class r extends p{}class s extends q{}s.kind="else";class t extends q{constructor(a,b){super(b),this.condition=a}render(a){let b=`if(${this.condition})`+super.render(a);return this.else&&(b+="else "+this.else.render(a)),b}optimizeNodes(){super.optimizeNodes();let a=this.condition;if(!0===a)return this.nodes;let b=this.else;if(b){let a=b.optimizeNodes();b=this.else=Array.isArray(a)?new s(a):a}return b?!1===a?b instanceof t?b:b.nodes:this.nodes.length?this:new t(H(a),b instanceof t?[b]:b.nodes):!1!==a&&this.nodes.length?this:void 0}optimizeNames(a,b){var c;if(this.else=null==(c=this.else)?void 0:c.optimizeNames(a,b),super.optimizeNames(a,b)||this.else)return this.condition=G(this.condition,a,b),this}get names(){let a=super.names;return F(a,this.condition),this.else&&E(a,this.else.names),a}}t.kind="if";class u extends q{}u.kind="for";class v extends u{constructor(a){super(),this.iteration=a}render(a){return`for(${this.iteration})`+super.render(a)}optimizeNames(a,b){if(super.optimizeNames(a,b))return this.iteration=G(this.iteration,a,b),this}get names(){return E(super.names,this.iteration.names)}}class w extends u{constructor(a,b,c,d){super(),this.varKind=a,this.name=b,this.from=c,this.to=d}render(a){let b=a.es5?e.varKinds.var:this.varKind,{name:c,from:d,to:f}=this;return`for(${b} ${c}=${d}; ${c}<${f}; ${c}++)`+super.render(a)}get names(){let a=F(super.names,this.from);return F(a,this.to)}}class x extends u{constructor(a,b,c,d){super(),this.loop=a,this.varKind=b,this.name=c,this.iterable=d}render(a){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(a)}optimizeNames(a,b){if(super.optimizeNames(a,b))return this.iterable=G(this.iterable,a,b),this}get names(){return E(super.names,this.iterable.names)}}class y extends q{constructor(a,b,c){super(),this.name=a,this.args=b,this.async=c}render(a){let b=this.async?"async ":"";return`${b}function ${this.name}(${this.args})`+super.render(a)}}y.kind="func";class z extends p{render(a){return"return "+super.render(a)}}z.kind="return";class A extends q{render(a){let b="try"+super.render(a);return this.catch&&(b+=this.catch.render(a)),this.finally&&(b+=this.finally.render(a)),b}optimizeNodes(){var a,b;return super.optimizeNodes(),null==(a=this.catch)||a.optimizeNodes(),null==(b=this.finally)||b.optimizeNodes(),this}optimizeNames(a,b){var c,d;return super.optimizeNames(a,b),null==(c=this.catch)||c.optimizeNames(a,b),null==(d=this.finally)||d.optimizeNames(a,b),this}get names(){let a=super.names;return this.catch&&E(a,this.catch.names),this.finally&&E(a,this.finally.names),a}}class B extends q{constructor(a){super(),this.error=a}render(a){return`catch(${this.error})`+super.render(a)}}B.kind="catch";class C extends q{render(a){return"finally"+super.render(a)}}C.kind="finally";class D{constructor(a,b={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...b,_n:b.lines?"\n":""},this._extScope=a,this._scope=new e.Scope({parent:a}),this._nodes=[new r]}toString(){return this._root.render(this.opts)}name(a){return this._scope.name(a)}scopeName(a){return this._extScope.name(a)}scopeValue(a,b){let c=this._extScope.value(a,b);return(this._values[c.prefix]||(this._values[c.prefix]=new Set)).add(c),c}getScopeValue(a,b){return this._extScope.getValue(a,b)}scopeRefs(a){return this._extScope.scopeRefs(a,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(a,b,c,d){let e=this._scope.toName(b);return void 0!==c&&d&&(this._constants[e.str]=c),this._leafNode(new i(a,e,c)),e}const(a,b,c){return this._def(e.varKinds.const,a,b,c)}let(a,b,c){return this._def(e.varKinds.let,a,b,c)}var(a,b,c){return this._def(e.varKinds.var,a,b,c)}assign(a,b,c){return this._leafNode(new j(a,b,c))}add(a,c){return this._leafNode(new k(a,b.operators.ADD,c))}code(a){return"function"==typeof a?a():a!==d.nil&&this._leafNode(new o(a)),this}object(...a){let b=["{"];for(let[c,e]of a)b.length>1&&b.push(","),b.push(c),(c!==e||this.opts.es5)&&(b.push(":"),(0,d.addCodeArg)(b,e));return b.push("}"),new d._Code(b)}if(a,b,c){if(this._blockNode(new t(a)),b&&c)this.code(b).else().code(c).endIf();else if(b)this.code(b).endIf();else if(c)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(a){return this._elseNode(new t(a))}else(){return this._elseNode(new s)}endIf(){return this._endBlockNode(t,s)}_for(a,b){return this._blockNode(a),b&&this.code(b).endFor(),this}for(a,b){return this._for(new v(a),b)}forRange(a,b,c,d,f=this.opts.es5?e.varKinds.var:e.varKinds.let){let g=this._scope.toName(a);return this._for(new w(f,g,b,c),()=>d(g))}forOf(a,b,c,f=e.varKinds.const){let g=this._scope.toName(a);if(this.opts.es5){let a=b instanceof d.Name?b:this.var("_arr",b);return this.forRange("_i",0,(0,d._)`${a}.length`,b=>{this.var(g,(0,d._)`${a}[${b}]`),c(g)})}return this._for(new x("of",f,g,b),()=>c(g))}forIn(a,b,c,f=this.opts.es5?e.varKinds.var:e.varKinds.const){if(this.opts.ownProperties)return this.forOf(a,(0,d._)`Object.keys(${b})`,c);let g=this._scope.toName(a);return this._for(new x("in",f,g,b),()=>c(g))}endFor(){return this._endBlockNode(u)}label(a){return this._leafNode(new l(a))}break(a){return this._leafNode(new m(a))}return(a){let b=new z;if(this._blockNode(b),this.code(a),1!==b.nodes.length)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(z)}try(a,b,c){if(!b&&!c)throw Error('CodeGen: "try" without "catch" and "finally"');let d=new A;if(this._blockNode(d),this.code(a),b){let a=this.name("e");this._currNode=d.catch=new B(a),b(a)}return c&&(this._currNode=d.finally=new C,this.code(c)),this._endBlockNode(B,C)}throw(a){return this._leafNode(new n(a))}block(a,b){return this._blockStarts.push(this._nodes.length),a&&this.code(a).endBlock(b),this}endBlock(a){let b=this._blockStarts.pop();if(void 0===b)throw Error("CodeGen: not in self-balancing block");let c=this._nodes.length-b;if(c<0||void 0!==a&&c!==a)throw Error(`CodeGen: wrong number of nodes: ${c} vs ${a} expected`);return this._nodes.length=b,this}func(a,b=d.nil,c,e){return this._blockNode(new y(a,b,c)),e&&this.code(e).endFunc(),this}endFunc(){return this._endBlockNode(y)}optimize(a=1){for(;a-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(a){return this._currNode.nodes.push(a),this}_blockNode(a){this._currNode.nodes.push(a),this._nodes.push(a)}_endBlockNode(a,b){let c=this._currNode;if(c instanceof a||b&&c instanceof b)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${b?`${a.kind}/${b.kind}`:a.kind}"`)}_elseNode(a){let b=this._currNode;if(!(b instanceof t))throw Error('CodeGen: "else" without "if"');return this._currNode=b.else=a,this}get _root(){return this._nodes[0]}get _currNode(){let a=this._nodes;return a[a.length-1]}set _currNode(a){let b=this._nodes;b[b.length-1]=a}}function E(a,b){for(let c in b)a[c]=(a[c]||0)+(b[c]||0);return a}function F(a,b){return b instanceof d._CodeOrName?E(a,b.names):a}function G(a,b,c){var e;if(a instanceof d.Name)return f(a);if(!((e=a)instanceof d._Code&&e._items.some(a=>a instanceof d.Name&&1===b[a.str]&&void 0!==c[a.str])))return a;return new d._Code(a._items.reduce((a,b)=>(b instanceof d.Name&&(b=f(b)),b instanceof d._Code?a.push(...b._items):a.push(b),a),[]));function f(a){let d=c[a.str];return void 0===d||1!==b[a.str]?a:(delete b[a.str],d)}}function H(a){return"boolean"==typeof a||"number"==typeof a||null===a?!a:(0,d._)`!${L(a)}`}b.CodeGen=D,b.not=H;let I=K(b.operators.AND);b.and=function(...a){return a.reduce(I)};let J=K(b.operators.OR);function K(a){return(b,c)=>b===d.nil?c:c===d.nil?b:(0,d._)`${L(b)} ${a} ${L(c)}`}function L(a){return a instanceof d.Name?a:(0,d._)`(${a})`}b.or=function(...a){return a.reduce(J)}},97210:(a,b,c)=>{"use strict";let{createInflateRaw:d,Z_DEFAULT_WINDOWBITS:e}=c(38522),{isValidClientWindowBits:f}=c(94050),{MessageSizeExceededError:g}=c(61448),h=Buffer.from([0,0,255,255]),i=Symbol("kBuffer"),j=Symbol("kLength");class k{#cj;#cc={};#bH=0;constructor(a,b){this.#cc.serverNoContextTakeover=a.has("server_no_context_takeover"),this.#cc.serverMaxWindowBits=a.get("server_max_window_bits"),this.#bH=b.maxPayloadSize}decompress(a,b,c){if(!this.#cj){let a=e;if(this.#cc.serverMaxWindowBits){if(!f(this.#cc.serverMaxWindowBits))return void c(Error("Invalid server_max_window_bits"));a=Number.parseInt(this.#cc.serverMaxWindowBits)}try{this.#cj=d({windowBits:a})}catch(a){c(a);return}this.#cj[i]=[],this.#cj[j]=0,this.#cj.on("data",a=>{if(this.#cj[j]+=a.length,this.#bH>0&&this.#cj[j]>this.#bH){c(new g),this.#cj.removeAllListeners(),this.#cj=null;return}this.#cj[i].push(a)}),this.#cj.on("error",a=>{this.#cj=null,c(a)})}this.#cj.write(a),b&&this.#cj.write(h),this.#cj.flush(()=>{if(!this.#cj)return;let a=Buffer.concat(this.#cj[i],this.#cj[j]);this.#cj[i].length=0,this.#cj[j]=0,c(null,a)})}}a.exports={PerMessageDeflate:k}},97218:(a,b,c)=>{"use strict";c.d(b,{dM:()=>s});var d=c(10220),e=c(46691),f=c(53857),g=c(38626);function h(a,b,c,d){return"number"!=typeof a||Number.isNaN(a)?d:Math.max(b,Math.min(c,Math.floor(a)))}let i={type:"arrowclosed",width:20,height:20,color:"#1976d2"},j={stroke:"#1976d2",strokeWidth:2},k={type:"arrowclosed",width:20,height:20,color:"#009688"},l={stroke:"#009688",strokeWidth:2},m=new Set(["full-history","latest-message","isolated"]),n=new Set(["steps","final-only"]),o=new Set(["full-conversation","latest-message"]);function p(a,b={}){let{keepPills:c=!1,wiredServers:d=new Set,validHandoffNames:f=new Set}=b,g=(0,e.A$)(a);if(0===g.length)return{text:a,stripped:!1,unresolved:[]};let h="",i=0,j=!1,k=[];for(let b of g){h+=a.slice(i,b.index),i=b.index+b.fullMatch.length;let e=!1;c&&(e="handoff"===b.server?f.has(b.name):d.has(b.server)),e?h+=b.fullMatch:(h+=b.name,j=!0,c&&k.push(b.fullMatch))}return{text:h+=a.slice(i),stripped:j,unresolved:k}}function q(a,b,c){let d=b.filter(b=>b.from===a).map(a=>c.get(a.to)).filter(Boolean).map(a=>({id:a.key??"",label:a.label,type:a.type}));return new Set((0,g.E9)(d).values())}function r(a,b){if(b.some(b=>b.id===a))return a;let c=a.toLowerCase(),d=b.find(a=>a.name.toLowerCase()===c);return d?d.id:null}function s(a,b={},c={}){var e,g,t;let u,v=[],w=(a,b,c)=>v.push({severity:"error",code:a,message:b,nodeKey:c}),x=(a,b,c)=>v.push({severity:"warning",code:a,message:b,nodeKey:c}),y=b.models??[],z=new Set((b.servers??[]).map(a=>a.name)),A=b.serverTools??{},B=h(c.maxDepth,0,3,3),C=h(c.maxFlows,1,8,8),D=[],E=[...(b.flows??[]).map(a=>a.name)],F=[],G=0;return e=function a(e,g,s){let t=Array.isArray(e?.nodes)?e.nodes:[],u=Array.isArray(e?.edges)?e.edges:[],v=function(a,b){let c=(a??"").trim().replace(/[^\w-]+/g,"_").replace(/^_+|_+$/g,"");c||(c="generated_flow");let d=new Set(b.map(a=>a.toLowerCase()));if(!d.has(c.toLowerCase()))return c;for(let a=2;;a++){let b=`${c}_${a}`;if(!d.has(b.toLowerCase()))return b}}(e?.name,E);E.push(v),G++;let I=(0,d.A)(),J=[...s,v],K=new Map,L=[],M=[],N=new Map(t.filter(a=>a?.key&&"string"==typeof a.key).map(a=>[a.key,a]));for(let e of t){let f=e?.key;if(!f||"string"!=typeof f){w("node-missing-key",'A node is missing its "key" — every node needs a unique key.');continue}if(K.has(f)){w("node-duplicate-key",`Duplicate node key "${f}" — keys must be unique; the later node was dropped.`,f);continue}let i=e.type;if("mcp"===i){w("mcp-node-not-allowed",`Node "${f}": do not emit "mcp" nodes — attach servers to a process node via its "servers" list instead.`,f);continue}if("start"!==i&&"process"!==i&&"finish"!==i&&"subflow"!==i&&"resource"!==i&&"signal"!==i&&"static"!==i){w("unknown-node-type",`Node "${f}" has unknown type "${String(i)}".`,f);continue}let j={},k="string"==typeof e.prompt?e.prompt:void 0;if("start"===i){let{text:a,stripped:b,unresolved:d}=p(k??"",c.keepPills?{keepPills:!0,wiredServers:new Set((e.servers??[]).map(a=>a.name)),validHandoffNames:q(f,u,N)}:{});for(let a of(b&&!c.keepPills&&x("pill-stripped",`Node "${f}": binding pills are not supported in generated prompts and were replaced with plain names.`,f),d))x("pill-unresolved",`Node "${f}": pill "${a}" not resolved against wired servers — stripped.`,f);j.promptTemplate=a}else if("process"===i){let{text:a,stripped:b,unresolved:d}=p(k??"",c.keepPills?{keepPills:!0,wiredServers:new Set((e.servers??[]).map(a=>a.name)),validHandoffNames:q(f,u,N)}:{});for(let a of(b&&!c.keepPills&&x("pill-stripped",`Node "${f}": binding pills are not supported in generated prompts and were replaced with plain names.`,f),d))x("pill-unresolved",`Node "${f}": pill "${a}" not resolved against wired servers — stripped.`,f);if(j.promptTemplate=a,e.model){let a=function(a,b){if(b.some(b=>b.id===a))return a;let c=a.toLowerCase(),d=b.find(a=>a.displayName?.toLowerCase()===c);if(d)return d.id;let e=b.find(a=>a.name?.toLowerCase()===c);return e?e.id:null}(e.model,y);a?j.boundModel=a:(j.boundModel=e.model,x("model-unresolved",`Node "${f}": model "${e.model}" does not match any configured model (by id, display name, or name).`,f))}void 0!==e.inputMode&&(m.has(e.inputMode)?(j.inputMode=e.inputMode,"isolated"===e.inputMode&&"string"==typeof e.isolatedPrompt&&(j.isolatedPrompt=e.isolatedPrompt)):x("invalid-input-mode",`Node "${f}": inputMode "${String(e.inputMode)}" is not valid (full-history | latest-message | isolated); omitted.`,f)),"boolean"==typeof e.allowCallerPrompt&&(j.allowCallerPrompt=e.allowCallerPrompt),void 0!==e.outputMode&&(o.has(e.outputMode)?j.outputMode=e.outputMode:x("invalid-output-mode",`Node "${f}": outputMode "${String(e.outputMode)}" is not valid on a process node (full-conversation | latest-message); omitted.`,f)),void 0!==e.maxTurns&&("number"!=typeof e.maxTurns||Number.isNaN(e.maxTurns)?x("invalid-max-turns",`Node "${f}": maxTurns "${String(e.maxTurns)}" is not a number; omitted.`,f):j.maxTurns=h(e.maxTurns,1,1e3,1)),"boolean"==typeof e.excludeModelPrompt&&(j.excludeModelPrompt=e.excludeModelPrompt),"boolean"==typeof e.excludeStartNodePrompt&&(j.excludeStartNodePrompt=e.excludeStartNodePrompt),"boolean"==typeof e.excludeSystemPrompt&&(j.excludeSystemPrompt=e.excludeSystemPrompt),Array.isArray(e.allowedTools)&&(j.allowedTools=e.allowedTools.filter(a=>"string"==typeof a&&a)),"string"==typeof e.captureVariable&&e.captureVariable.trim()&&(j.captureVariable=e.captureVariable.trim()),"string"==typeof e.captureResource&&e.captureResource.trim()&&x("process-capture-resource-unsupported",`Node "${f}": process captureResource is not supported; connect the process to a Resource node so it can call write_resource.`,f),"string"==typeof e.captureKv&&e.captureKv.trim()&&(j.captureKv=e.captureKv.trim())}else if("subflow"===i){if(function(c,d,e,f,g){let h=Array.isArray(c.parallelFlows)&&c.parallelFlows.length>0,i=Array.isArray(c.parallelSubflowSpecs)&&c.parallelSubflowSpecs.length>0,j="string"==typeof c.parallelFlowsVariable?c.parallelFlowsVariable.trim():"";if([void 0!==c.flow&&null!==c.flow?"flow":null,void 0!==c.subflowSpec&&null!==c.subflowSpec?"subflowSpec":null,h?"parallelFlows":null,i?"parallelSubflowSpecs":null,void 0!==c.generateSubflow&&null!==c.generateSubflow?"generateSubflow":null].filter(Boolean).length>1&&x("subflow-multiple-sources",`Node "${d}": a subflow node should have only one target source ("flow", "subflowSpec", "parallelFlows", "parallelSubflowSpecs", or "generateSubflow"); applying precedence flow > subflowSpec > parallelFlows > parallelSubflowSpecs > generateSubflow.`,d),!0===c.mapOverList){let a=void 0!==c.flow&&null!==c.flow||void 0!==c.subflowSpec&&null!==c.subflowSpec;(h||i)&&w("subflow-map-and-parallel",`Node "${d}": "mapOverList" runs a SINGLE child once per item and cannot be combined with "parallelFlows"/"parallelSubflowSpecs".`,d),a?(g.mapOverList=!0,void 0!==c.itemSplit&&("json-array"===c.itemSplit||"lines"===c.itemSplit?g.itemSplit=c.itemSplit:x("invalid-item-split",`Node "${d}": itemSplit "${String(c.itemSplit)}" is not valid (json-array | lines); using json-array.`,d)),!0===c.sequential&&(g.sequential=!0),H(c,g)):w("subflow-map-no-child",`Node "${d}": "mapOverList" needs a single child ("flow" or "subflowSpec") to run once per item.`,d)}let k=Array.isArray(c.spawnBriefs)?c.spawnBriefs.filter(a=>"string"==typeof a&&""!==a.trim()):[];if(k.length>0){let a=void 0!==c.flow&&null!==c.flow||void 0!==c.subflowSpec&&null!==c.subflowSpec;h||i?w("subflow-spawn-and-parallel",`Node "${d}": "spawnBriefs" runs a SINGLE child once per brief and cannot be combined with "parallelFlows"/"parallelSubflowSpecs".`,d):!0===c.mapOverList?w("subflow-spawn-and-map",`Node "${d}": "spawnBriefs" cannot be combined with "mapOverList"; use one lane source or the other.`,d):a?(g.spawnBriefs=k,H(c,g)):w("subflow-spawn-no-child",`Node "${d}": "spawnBriefs" needs a single child ("flow" or "subflowSpec") to spawn once per brief.`,d)}if(j&&(!0===c.mapOverList?w("subflow-map-and-parallel-var",`Node "${d}": "parallelFlowsVariable" (dynamic fan-out) cannot be combined with "mapOverList".`,d):g.parallelSubflowIdsVar=j),c.flow){if(f.some(a=>a.toLowerCase()===c.flow.toLowerCase()))return w("subflow-cycle",`Node "${d}": flow "${c.flow}" refers to an ancestor flow, which would create a cycle.`,d);let a=r(c.flow,[...b.flows??[],...F]);return a?g.subflowId=a:w("subflow-unresolved",`Node "${d}": flow "${c.flow}" does not match any existing flow (by id or name).`,d)}if(c.subflowSpec){if(e+1>B)return w("subflow-too-deep",`Node "${d}": nested subflows may not go deeper than ${B} level(s); this inline subflow was not compiled.`,d);if(G>=C)return w("subflow-too-many",`Node "${d}": compiling this inline subflow would exceed the maximum of ${C} flows in one bundle; it was not compiled.`,d);let b=a(c.subflowSpec,e+1,f);return b?g.subflowId=b.id:w("subflow-child-empty",`Node "${d}": the inline "subflowSpec" produced no usable flow.`,d)}if(h){let a=[];for(let e of c.parallelFlows){if("string"!=typeof e||!e){w("parallel-flow-invalid",`Node "${d}": a "parallelFlows" entry is missing or not a string.`,d);continue}if(f.some(a=>a.toLowerCase()===e.toLowerCase())){w("subflow-cycle",`Node "${d}": parallel flow "${e}" refers to an ancestor flow, which would create a cycle.`,d);continue}let c=r(e,[...b.flows??[],...F]);c?a.includes(c)||a.push(c):w("parallel-flow-unresolved",`Node "${d}": parallel flow "${e}" does not match any existing flow (by id or name).`,d)}a.length>0?(g.parallelSubflowIds=a,H(c,g)):w("parallel-empty",`Node "${d}": "parallelFlows" resolved to no runnable lanes.`,d);return}if(i){let b=[];for(let g of c.parallelSubflowSpecs){if(!g||"object"!=typeof g){w("parallel-spec-invalid",`Node "${d}": a "parallelSubflowSpecs" entry is not a FlowSpec object.`,d);continue}if(e+1>B){w("subflow-too-deep",`Node "${d}": nested subflows may not go deeper than ${B} level(s); a parallel inline subflow was not compiled.`,d);continue}if(G>=C){w("subflow-too-many",`Node "${d}": compiling a parallel inline subflow would exceed the maximum of ${C} flows in one bundle; it was not compiled.`,d);continue}let c=a(g,e+1,f);c?b.push(c.id):w("subflow-child-empty",`Node "${d}": a "parallelSubflowSpecs" entry produced no usable flow.`,d)}b.length>0?(g.parallelSubflowIds=b,H(c,g)):w("parallel-empty",`Node "${d}": "parallelSubflowSpecs" produced no runnable lanes.`,d);return}j&&g.parallelSubflowIdsVar?H(c,g):void 0!==c.generateSubflow&&null!==c.generateSubflow?w("subflow-generate-unsupported",`Node "${d}": "generateSubflow" is only available through the AI flow generator. Use "subflowSpec" for deterministic nested authoring, or "flow" to reference an existing flow.`,d):w("subflow-missing-flow",`Node "${d}": subflow nodes need a "flow" (existing flow), a "subflowSpec" (inline child), "parallelFlows"/"parallelSubflowSpecs" (concurrent children), or "generateSubflow".`,d)}(e,f,g,J,j),void 0!==e.inputMode&&(m.has(e.inputMode)?j.inputMode=e.inputMode:x("invalid-input-mode",`Node "${f}": inputMode "${String(e.inputMode)}" is not valid (full-history | latest-message | isolated); omitted.`,f)),void 0!==e.outputMode&&(n.has(e.outputMode)?j.outputMode=e.outputMode:x("invalid-output-mode",`Node "${f}": outputMode "${String(e.outputMode)}" is not valid (steps | final-only); omitted.`,f)),void 0!==k){let{text:a,stripped:b,unresolved:d}=p(k,c.keepPills?{keepPills:!0}:{});for(let a of(b&&!c.keepPills&&x("pill-stripped",`Node "${f}": binding pills are not supported in generated prompts and were replaced with plain names.`,f),d))x("pill-unresolved",`Node "${f}": pill "${a}" not resolved against wired servers — stripped.`,f);j.promptTemplate=a}"boolean"==typeof e.allowCallerPrompt&&(j.allowCallerPrompt=e.allowCallerPrompt),"boolean"==typeof e.allowCallerFanout&&(j.allowCallerFanout=e.allowCallerFanout);let d=e.sessionScope??(c.newSubflowDefaults?"per-key":void 0);"per-visit"===d||"per-run"===d||"per-key"===d?"per-visit"!==d&&(j.sessionScope=d):void 0!==e.sessionScope&&x("invalid-session-scope",`Node "${f}": sessionScope "${String(e.sessionScope)}" is not valid (per-visit | per-run | per-key); omitted.`,f),"string"==typeof e.sessionKey&&e.sessionKey.trim()&&(j.sessionKey=e.sessionKey.trim()),"separate"===(e.resultPresentation??"separate")&&(j.resultPresentation="separate"),"string"==typeof e.captureVariable&&e.captureVariable.trim()&&(j.captureVariable=e.captureVariable.trim()),"string"==typeof e.captureResource&&e.captureResource.trim()&&(j.captureResource=e.captureResource.trim()),"string"==typeof e.captureKv&&e.captureKv.trim()&&(j.captureKv=e.captureKv.trim())}else if("resource"===i){let a="string"==typeof e.runName?e.runName.trim():"",b="string"==typeof e.server?e.server.trim():"",c="string"==typeof e.uri?e.uri.trim():"";a?(j.scope="run",j.runName=a,(b||c)&&x("resource-both-bindings",`Node "${f}": a resource node is EITHER a run artifact ("runName") or a static MCP resource ("server"+"uri"); kept the run artifact.`,f)):(j.scope="mcp",b&&(j.boundServer=b),c&&(j.uri=c),b&&c?z.has(b)||x("server-unknown",`Node "${f}": MCP server "${b}" is not configured in FLUJO.`,f):x("resource-missing-binding",`Node "${f}": a static resource node needs both "server" and "uri" (or a "runName" for a run artifact).`,f))}else if("signal"===i){let a="string"==typeof e.topic?e.topic.trim():"";a?j.topic=a:x("signal-missing-topic",`Node "${f}": a signal node needs a "topic" to emit.`,f),"string"==typeof e.payloadTemplate&&e.payloadTemplate?j.payloadTemplate=e.payloadTemplate:void 0!==k&&(j.payloadTemplate=k)}else if("static"===i){let a=Array.isArray(e.entries)?e.entries:[],b=[];for(let c=0;c<a.length&&b.length<200;c++){let d=a[c];if(!d||"object"!=typeof d){x("static-invalid-entry",`Node "${f}": entry #${c+1} is not an object; dropped.`,f);continue}if("message"===d.kind){let a=d.role,e=d.content;if(("system"===a||"user"===a||"assistant"===a)&&"string"==typeof e){let c=Array.isArray(d.attachments)?d.attachments.flatMap(a=>a&&"object"==typeof a?"document"!==a.type&&"audio"!==a.type&&"image"!==a.type&&"video"!==a.type||"string"!=typeof a.content?[]:[{type:a.type,content:a.content,..."string"==typeof a.id?{id:a.id}:{},..."string"==typeof a.originalName?{originalName:a.originalName}:{},..."string"==typeof a.mimeType?{mimeType:a.mimeType}:{},..."string"==typeof a.transcript?{transcript:a.transcript}:{}}]:[]):[];b.push({kind:"message",role:a,content:e,...c.length>0?{attachments:c}:{}})}else x("static-invalid-entry",`Node "${f}": message entry #${c+1} has an invalid role/content; dropped.`,f)}else if("toolCall"===d.kind){let a=d.toolName,e=d.argumentsJson,g=d.result;if("string"==typeof a&&a.trim()&&"string"==typeof e&&"string"==typeof g){let h="real"===d.executionMode?"real":"mock",i="string"==typeof d.serverName?d.serverName.trim():"";if("real"!==h||i?b.push({kind:"toolCall",toolName:a,argumentsJson:e,result:g,..."real"===d.executionMode||"mock"===d.executionMode?{executionMode:h}:{},...i?{serverName:i}:{}}):(x("static-real-toolcall-missing-server",`Node "${f}": real tool-call entry #${c+1} needs a serverName; kept as a mock.`,f),b.push({kind:"toolCall",toolName:a,argumentsJson:e,result:g,executionMode:"mock"})),e.trim())try{JSON.parse(e)}catch{x("static-toolcall-invalid-json",`Node "${f}": tool-call entry #${c+1} has invalid JSON arguments.`,f)}}else x("static-invalid-entry",`Node "${f}": tool-call entry #${c+1} is missing toolName/argumentsJson/result; dropped.`,f)}else x("static-invalid-entry",`Node "${f}": entry #${c+1} has unknown kind "${String(d.kind)}"; dropped.`,f)}a.length>200&&x("static-too-many-entries",`Node "${f}": only the first 200 entries were kept.`,f),b.length>0?j.entries=b:x("static-no-entries",`Node "${f}": a static node has no entries; it injects nothing.`,f),!0===e.injectOnce?j.injectOnce=!0:void 0!==e.injectOnce&&"boolean"!=typeof e.injectOnce&&x("static-invalid-injectonce",`Node "${f}": injectOnce must be a boolean; value ignored.`,f)}let l={id:(0,d.A)(),type:i,position:{x:0,y:0},data:{label:"finish"===i?"Finish Node":e.label||`${i.charAt(0).toUpperCase()}${i.slice(1)} Node`,type:i,...e.description?{description:e.description}:{},properties:j}};K.set(f,l),L.push(l);let s=Array.isArray(e.servers)?e.servers.map(a=>({...a,...Array.isArray(a.tools)?{tools:[...a.tools]}:{}})):[];if("static"===i)for(let a of j.entries??[]){if("toolCall"!==a.kind||"real"!==a.executionMode||!a.serverName)continue;let b=s.find(b=>b.name===a.serverName);b?Array.isArray(b.tools)?b.tools.includes(a.toolName)||b.tools.push(a.toolName):b.tools=[a.toolName]:s.push({name:a.serverName,tools:[a.toolName]})}if(("process"===i||"static"===i)&&s.length>0){let a=new Set;for(let b of s){let c,e=b?.name;if(!e||"string"!=typeof e){x("server-missing-name",`Node "${f}": a server reference is missing its "name"; skipped.`,f);continue}if(a.has(e))continue;a.add(e),z.has(e)||x("server-unknown",`Node "${f}": MCP server "${e}" is not configured in FLUJO.`,f);let g=A[e];if(Array.isArray(b.tools)){if(c=b.tools.filter(a=>"string"==typeof a&&a),g){let a=c.filter(a=>!g.includes(a));a.length>0&&x("tool-unknown",`Node "${f}": server "${e}" does not report tool(s): ${a.join(", ")}.`,f)}}else c=g?[...g]:[];let h={id:(0,d.A)(),type:"mcp",position:{x:0,y:0},data:{label:e,type:"mcp",properties:{boundServer:e,enabledTools:c}}};L.push(h),M.push({consumerKey:f,mcpNode:h})}}else"process"!==i&&"static"!==i&&s.length>0&&x("servers-on-unsupported-node",`Node "${f}": only process and static nodes can have "servers"; ignored.`,f)}if(0===K.size)return w("no-usable-nodes","No usable nodes — the spec must contain at least a start node and one step."),null;let O=[],P=new Set;for(let a of u){let b,c=a?.from,d=a?.to,e=c?K.get(c):void 0,g=d?K.get(d):void 0;if(!e||!g){w("edge-unknown-node",`Edge "${String(c)}" -> "${String(d)}" references a node key that does not exist (or was dropped).`);continue}if(e===g){w("edge-self-loop",`Edge "${c}" -> "${d}": a node cannot connect to itself.`);continue}if("resource"===e.type||"resource"===g.type){if(("resource"!==e.type||"process"!==g.type)&&("process"!==e.type||"resource"!==g.type)){w("resource-edge-invalid",`Edge "${c}" -> "${d}": resource nodes connect only to process nodes.`);continue}a.condition&&x("resource-edge-condition",`Edge "${c}" -> "${d}": conditions do not apply to resource wiring; dropped.`),!0===a.bidirectional&&x("resource-edge-bidirectional",`Edge "${c}" -> "${d}": resource wiring is directional (read vs write); "bidirectional" was ignored — add the opposite edge explicitly if the step both reads and writes.`);let b=`${c}->${d}`;if(P.has(b)){x("edge-duplicate",`Edge "${c}" -> "${d}" appears more than once; kept the first.`);continue}P.add(b),O.push(function(a,b){let c="resource"===a.type?"resource-out":"process-right-resource",d="resource"===b.type?"resource-in":"process-left-resource";return{id:`${a.id}:${c}->${b.id}:${d}`,source:a.id,sourceHandle:c,target:b.id,targetHandle:d,type:"resourceEdge",data:{edgeType:"resource"},animated:!1,markerEnd:{...k},style:{...l}}}(e,g));continue}if("start"===g.type){w("edge-into-start",`Edge "${c}" -> "${d}": nothing may connect INTO a start node.`);continue}if("finish"===e.type){w("edge-out-of-finish",`Edge "${c}" -> "${d}": nothing may connect OUT OF a finish node.`);continue}let h=`${c}->${d}`;if(P.has(h)){x("edge-duplicate",`Edge "${c}" -> "${d}" appears more than once; kept the first.`);continue}P.add(h);let i=!0===a.bidirectional;i&&("start"===e.type||"finish"===g.type)&&(x("bidirectional-illegal",`Edge "${c}" -> "${d}" cannot be bidirectional; downgraded to one-way.`),i=!1);let j=a.condition;j&&"object"==typeof j&&("process"!==e.type?x("edge-condition-non-process",`Edge "${c}" -> "${d}" has a condition but leaves a ${e.type} node; conditions only route from process nodes and were dropped.`):(0,f.C)(j.kind)?"always"===j.kind?b={kind:"always",..."last-message"===j.target?{target:"last-message"}:{},...!0===j.negate?{negate:!0}:{}}:"string"!=typeof j.value||0===j.value.length?x("edge-condition-value",`Edge "${c}" -> "${d}" has a condition with no "value"; the condition was dropped.`):("regex"!==j.kind||(0,f.wM)(j.value)||x("edge-condition-regex",`Edge "${c}" -> "${d}" has a regex condition that does not compile; it is kept but will never match at runtime.`),b={kind:j.kind,value:j.value,..."last-message"===j.target?{target:"last-message"}:{},...!0===j.ignoreCase?{ignoreCase:!0}:{},...!0===j.negate?{negate:!0}:{}}):x("edge-condition-kind",`Edge "${c}" -> "${d}" has an unknown condition kind "${String(j.kind)}"; the condition was dropped.`)),O.push(function(a,b,c,d){let e=`${a.type}-bottom`,f=`${b.type}-top`;return{id:`${a.id}:${e}->${b.id}:${f}`,source:a.id,sourceHandle:e,target:b.id,targetHandle:f,type:"custom",data:{edgeType:"standard",...c?{bidirectional:!0}:{},...d?{condition:d}:{}},animated:!0}}(e,g,i,b))}for(let{consumerKey:a,mcpNode:b}of M){let c=K.get(a);O.push(function(a,b){let c="static"===a.type?"static-right-mcp":"process-right-mcp",d="mcp-left";return{id:`${a.id}:${c}->${b.id}:${d}`,source:a.id,sourceHandle:c,target:b.id,targetHandle:d,type:"mcpEdge",data:{edgeType:"mcp"},animated:!1,markerEnd:{...i},markerStart:{...i},style:{...j}}}(c,b))}!function(a,b,c,d){let e=new Map;for(let a of b){let b=a.data?.edgeType;"mcp"!==b&&"resource"!==b&&(e.has(a.source)||e.set(a.source,[]),e.get(a.source).push(a.target))}let f=[...a.values()],g=f.filter(a=>"resource"===a.type),h=f.filter(a=>"resource"!==a.type),i=h.filter(a=>"start"===a.type),j=i.length>0?i:h.slice(0,1),k=new Map,l=j.map(a=>({id:a.id,depth:0}));for(let a of l)k.set(a.id,0);for(;l.length;){let{id:a,depth:b}=l.shift();for(let c of e.get(a)??[])k.has(c)||(k.set(c,b+1),l.push({id:c,depth:b+1}))}let m=0;for(let a of k.values())m=Math.max(m,a);for(let a of h)k.has(a.id)||k.set(a.id,m+1);let n=new Map;for(let[b,c]of a)n.set(c.id,b);let o=new Map;for(let a of h){let b=n.get(a.id),c=d&&b?d[b]:void 0;if(c&&"number"==typeof c.x&&"number"==typeof c.y){a.position={x:c.x,y:c.y};continue}let e=k.get(a.id),f=o.get(e)??0;o.set(e,f+1),a.position={x:250+280*f,y:150+170*e}}let p=new Map;for(let{consumerKey:b,mcpNode:d}of c){let c=a.get(b),e=p.get(b)??0;p.set(b,e+1),d.position={x:c.position.x+320,y:c.position.y+150*e}}let q=new Map(f.map(a=>[a.id,a])),r=new Map,s=0;for(let a of g){let c=n.get(a.id),e=d&&c?d[c]:void 0;if(e&&"number"==typeof e.x&&"number"==typeof e.y){a.position={x:e.x,y:e.y};continue}let f=b.find(b=>b.data?.edgeType==="resource"&&(b.source===a.id||b.target===a.id)),g=f?f.source===a.id?f.target:f.source:void 0,i=g?q.get(g):void 0;if(i){let b=r.get(i.id)??0;r.set(i.id,b+1),a.position={x:i.position.x-320,y:i.position.y+150*b}}else{let b=0;for(let a of h)b=Math.max(b,a.position.y);a.position={x:250+280*s,y:b+170},s++}}}(K,O,M,0===g?c.positions:void 0);let Q={id:I,name:v,...e?.description?{description:e.description}:{},nodes:L,edges:O};return D.push(Q),F.push({id:Q.id,name:Q.name}),Q}(a,0,[]),g=D,u=(t=v).filter(a=>"error"===a.severity).length,{flow:e,flows:g,issues:t,errorCount:u,warningCount:t.length-u};function H(a,b){void 0!==a.concurrencyLimit&&("number"!=typeof a.concurrencyLimit||Number.isNaN(a.concurrencyLimit)?x("invalid-concurrency-limit",`Node "${a.key}": concurrencyLimit "${String(a.concurrencyLimit)}" is not a number; using the runtime default.`,a.key):b.concurrencyLimit=Math.max(1,Math.floor(a.concurrencyLimit))),"string"==typeof a.joinSeparator&&(b.joinSeparator=a.joinSeparator),void 0!==a.errorStrategy&&("fail-fast"===a.errorStrategy||"collect-all"===a.errorStrategy?b.errorStrategy=a.errorStrategy:x("invalid-error-strategy",`Node "${a.key}": errorStrategy "${String(a.errorStrategy)}" is not valid (fail-fast | collect-all); using collect-all.`,a.key))}}},97291:(a,b,c)=>{"use strict";let d,e,f;c.d(b,{M4:()=>gD});var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,aa,ab,ac,ad,ae,af,ag,ah,ai,aj,ak,al,am,an,ao,ap,aq,ar,as,at,au,av,aw,ax,ay,az,aA,aB,aC,aD,aE,aF,aG,aH,aI,aJ,aK,aL,aM,aN,aO,aP,aQ,aR,aS,aT,aU,aV,aW,aX,aY,aZ,a$,a_,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,ba,bb,bc,bd,be,bf,bg,bh,bi,bj,bk,bl,bm,bn,bo,bp,bq,br,bs,bt,bu,bv,bw,bx,by,bz,bA,bB,bC,bD,bE,bF,bG,bH,bI,bJ,bK,bL,bM,bN,bO=c(62928),bP=c(28325),bQ=c(29021),bR=c(79748),bS=c(57075),bT=c(46466);c(75397),c(20704),c(24869),c(7310),c(95570),c(1093);var bU=c(28942);c(43082);var bV=c(33873);class bW{}function bX(a,b){return a.replace(/\{([^}]+)\}/g,(a,c)=>{if(Object.prototype.hasOwnProperty.call(b,c)){let a=b[c];return null!=a?String(a):""}throw Error(`Key '${c}' not found in valueMap.`)})}function bY(a,b,c){for(let d=0;d<b.length-1;d++){let e=b[d];if(e.endsWith("[]")){let f=e.slice(0,-2);if(!(f in a))if(Array.isArray(c))a[f]=Array.from({length:c.length},()=>({}));else throw Error(`Value must be a list given an array path ${e}`);if(Array.isArray(a[f])){let e=a[f];if(Array.isArray(c))for(let a=0;a<e.length;a++)bY(e[a],b.slice(d+1),c[a]);else for(let a of e)bY(a,b.slice(d+1),c)}return}if(e.endsWith("[0]")){let f=e.slice(0,-3);f in a||(a[f]=[{}]),bY(a[f][0],b.slice(d+1),c);return}a[e]&&"object"==typeof a[e]||(a[e]={}),a=a[e]}let d=b[b.length-1],e=a[d];if(void 0!==e){if(!c||"object"==typeof c&&0===Object.keys(c).length||c===e)return;if("object"==typeof e&&"object"==typeof c&&null!==e&&null!==c)Object.assign(e,c);else throw Error(`Cannot set value for an existing key. Key: ${d}`)}else"_self"!==d||"object"!=typeof c||null===c||Array.isArray(c)?a[d]=c:Object.assign(a,c)}function bZ(a,b,c){try{if(1===b.length&&"_self"===b[0])return a;for(let d=0;d<b.length;d++){if("object"!=typeof a||null===a)return c;let e=b[d];if(e.endsWith("[]")){let f=e.slice(0,-2);if(!(f in a))return c;{let e=a[f];if(!Array.isArray(e))return c;return e.map(a=>bZ(a,b.slice(d+1),c))}}a=a[e]}return a}catch(a){if(a instanceof TypeError)return c;throw a}}function b$(a){if("string"!=typeof a)throw Error("fromImageBytes must be a string");return a}function b_(a){var b;let c,d,e,f,g={},h=bZ(a,["name"]);null!=h&&bY(g,["name"],h);let i=bZ(a,["metadata"]);null!=i&&bY(g,["metadata"],i);let j=bZ(a,["done"]);null!=j&&bY(g,["done"],j);let k=bZ(a,["error"]);null!=k&&bY(g,["error"],k);let l=bZ(a,["response"]);return null!=l&&bY(g,["response"],(c={},null!=(d=bZ(b=l,["sdkHttpResponse"]))&&bY(c,["sdkHttpResponse"],d),null!=(e=bZ(b,["parent"]))&&bY(c,["parent"],e),null!=(f=bZ(b,["documentName"]))&&bY(c,["documentName"],f),c)),g}(g=aB||(aB={})).OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",g.OUTCOME_OK="OUTCOME_OK",g.OUTCOME_FAILED="OUTCOME_FAILED",g.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED",(h=aC||(aC={})).LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",h.PYTHON="PYTHON",(i=aD||(aD={})).SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",i.SILENT="SILENT",i.WHEN_IDLE="WHEN_IDLE",i.INTERRUPT="INTERRUPT",(j=aE||(aE={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",j.STRING="STRING",j.NUMBER="NUMBER",j.INTEGER="INTEGER",j.BOOLEAN="BOOLEAN",j.ARRAY="ARRAY",j.OBJECT="OBJECT",j.NULL="NULL",(k=aF||(aF={})).AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",k.NO_AUTH="NO_AUTH",k.API_KEY_AUTH="API_KEY_AUTH",k.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",k.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",k.OAUTH="OAUTH",k.OIDC_AUTH="OIDC_AUTH",(l=aG||(aG={})).HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",l.HTTP_IN_QUERY="HTTP_IN_QUERY",l.HTTP_IN_HEADER="HTTP_IN_HEADER",l.HTTP_IN_PATH="HTTP_IN_PATH",l.HTTP_IN_BODY="HTTP_IN_BODY",l.HTTP_IN_COOKIE="HTTP_IN_COOKIE",(m=aH||(aH={})).API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",m.SIMPLE_SEARCH="SIMPLE_SEARCH",m.ELASTIC_SEARCH="ELASTIC_SEARCH",(n=aI||(aI={})).ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",n.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",n.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",n.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP",(o=aJ||(aJ={})).SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",o.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",o.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",o.COMMUNICATION_TOOL="COMMUNICATION_TOOL",o.ACCOUNT_CREATION="ACCOUNT_CREATION",o.DATA_MODIFICATION="DATA_MODIFICATION",o.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",o.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS",(p=aK||(aK={})).PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",p.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",p.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",p.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",p.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",p.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",p.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH",(q=aL||(aL={})).UNSPECIFIED="UNSPECIFIED",q.BLOCKING="BLOCKING",q.NON_BLOCKING="NON_BLOCKING",(r=aM||(aM={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",r.MODE_DYNAMIC="MODE_DYNAMIC",(s=aN||(aN={})).THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",s.MINIMAL="MINIMAL",s.LOW="LOW",s.MEDIUM="MEDIUM",s.HIGH="HIGH",(t=aO||(aO={})).DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL",(u=aP||(aP={})).PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",u.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",u.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE",(v=aQ||(aQ={})).HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",v.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",v.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",v.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",v.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",v.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",v.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",v.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",v.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",v.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",v.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",(w=aR||(aR={})).HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",w.SEVERITY="SEVERITY",w.PROBABILITY="PROBABILITY",(x=aS||(aS={})).HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",x.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",x.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",x.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",x.BLOCK_NONE="BLOCK_NONE",x.OFF="OFF",(y=aT||(aT={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",y.AUTO="AUTO",y.ANY="ANY",y.NONE="NONE",y.VALIDATED="VALIDATED",(z=aU||(aU={})).FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",z.STOP="STOP",z.MAX_TOKENS="MAX_TOKENS",z.SAFETY="SAFETY",z.RECITATION="RECITATION",z.LANGUAGE="LANGUAGE",z.OTHER="OTHER",z.BLOCKLIST="BLOCKLIST",z.PROHIBITED_CONTENT="PROHIBITED_CONTENT",z.SPII="SPII",z.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",z.IMAGE_SAFETY="IMAGE_SAFETY",z.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",z.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",z.NO_IMAGE="NO_IMAGE",z.IMAGE_RECITATION="IMAGE_RECITATION",z.IMAGE_OTHER="IMAGE_OTHER",(A=aV||(aV={})).HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",A.NEGLIGIBLE="NEGLIGIBLE",A.LOW="LOW",A.MEDIUM="MEDIUM",A.HIGH="HIGH",(B=aW||(aW={})).HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",B.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",B.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",B.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",B.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH",(C=aX||(aX={})).URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",C.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",C.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",C.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",C.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE",(D=aY||(aY={})).BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",D.SAFETY="SAFETY",D.OTHER="OTHER",D.BLOCKLIST="BLOCKLIST",D.PROHIBITED_CONTENT="PROHIBITED_CONTENT",D.IMAGE_SAFETY="IMAGE_SAFETY",D.MODEL_ARMOR="MODEL_ARMOR",D.JAILBREAK="JAILBREAK",(E=aZ||(aZ={})).TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",E.ON_DEMAND="ON_DEMAND",E.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",E.ON_DEMAND_FLEX="ON_DEMAND_FLEX",E.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT",(F=a$||(a$={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",F.TEXT="TEXT",F.IMAGE="IMAGE",F.VIDEO="VIDEO",F.AUDIO="AUDIO",F.DOCUMENT="DOCUMENT",(G=a_||(a_={})).MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",G.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",G.EXPERIMENTAL="EXPERIMENTAL",G.PREVIEW="PREVIEW",G.STABLE="STABLE",G.LEGACY="LEGACY",G.DEPRECATED="DEPRECATED",G.RETIRED="RETIRED",(H=a0||(a0={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",H.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",H.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",H.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",(I=a1||(a1={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",I.TEXT="TEXT",I.IMAGE="IMAGE",I.AUDIO="AUDIO",I.VIDEO="VIDEO",(J=a2||(a2={})).DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",J.INLINE="INLINE",J.URI="URI",(K=a3||(a3={})).ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",K.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",K.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",K.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",K.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",K.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",K.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",K.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",K.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",K.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",K.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",K.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",K.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",K.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",K.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE",(L=a4||(a4={})).IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",L.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",L.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",L.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",L.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K",(M=a5||(a5={})).TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",M.TUNING_MODE_FULL="TUNING_MODE_FULL",M.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER",(N=a6||(a6={})).ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",N.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",N.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",N.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",N.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",N.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",N.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO",(O=a7||(a7={})).RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",O.IDENTITY="IDENTITY",O.REGEX_EXTRACT="REGEX_EXTRACT",(P=a8||(a8={})).MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",P.REGEX_CONTAINS="REGEX_CONTAINS",P.PARTIAL_MATCH="PARTIAL_MATCH",P.EXACT_MATCH="EXACT_MATCH",(Q=a9||(a9={})).REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",Q.MINIMAL="MINIMAL",Q.HIGH="HIGH",(R=ba||(ba={})).JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",R.JOB_STATE_QUEUED="JOB_STATE_QUEUED",R.JOB_STATE_PENDING="JOB_STATE_PENDING",R.JOB_STATE_RUNNING="JOB_STATE_RUNNING",R.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",R.JOB_STATE_FAILED="JOB_STATE_FAILED",R.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",R.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",R.JOB_STATE_PAUSED="JOB_STATE_PAUSED",R.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",R.JOB_STATE_UPDATING="JOB_STATE_UPDATING",R.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED",(S=bb||(bb={})).TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",S.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",S.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",S.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",S.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",S.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING",(T=bc||(bc={})).AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",T.AVERAGE="AVERAGE",T.MODE="MODE",T.STANDARD_DEVIATION="STANDARD_DEVIATION",T.VARIANCE="VARIANCE",T.MINIMUM="MINIMUM",T.MAXIMUM="MAXIMUM",T.MEDIAN="MEDIAN",T.PERCENTILE_P90="PERCENTILE_P90",T.PERCENTILE_P95="PERCENTILE_P95",T.PERCENTILE_P99="PERCENTILE_P99",(U=bd||(bd={})).PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",U.BASELINE="BASELINE",U.CANDIDATE="CANDIDATE",U.TIE="TIE",(V=be||(be={})).VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",V.LANDSCAPE="LANDSCAPE",V.PORTRAIT="PORTRAIT",(W=bf||(bf={})).TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",W.REGULAR="REGULAR",W.FAST="FAST",(X=bg||(bg={})).TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",X.TUNING_TASK_I2V="TUNING_TASK_I2V",X.TUNING_TASK_T2V="TUNING_TASK_T2V",X.TUNING_TASK_R2V="TUNING_TASK_R2V",(Y=bh||(bh={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",Y.STATE_PENDING="STATE_PENDING",Y.STATE_ACTIVE="STATE_ACTIVE",Y.STATE_FAILED="STATE_FAILED",(Z=bi||(bi={})).UNSPECIFIED="unspecified",Z.FLEX="flex",Z.STANDARD="standard",Z.PRIORITY="priority",($=bj||(bj={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",$.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",$.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",$.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",$.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH",(_=bk||(bk={})).TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",_.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",_.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",_.URL_CONTEXT="URL_CONTEXT",_.GOOGLE_MAPS="GOOGLE_MAPS",_.FILE_SEARCH="FILE_SEARCH",(bl||(bl={})).COLLECTION="COLLECTION",(aa=bm||(bm={})).FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",aa.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",aa.BALANCED="BALANCED",aa.PRIORITIZE_COST="PRIORITIZE_COST",(ab=bn||(bn={})).PREDICT="PREDICT",ab.EMBED_CONTENT="EMBED_CONTENT",(ac=bo||(bo={})).BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",ac.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",ac.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",ac.BLOCK_NONE="BLOCK_NONE",(ad=bp||(bp={})).auto="auto",ad.en="en",ad.ja="ja",ad.ko="ko",ad.hi="hi",ad.zh="zh",ad.pt="pt",ad.es="es",(ae=bq||(bq={})).MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",ae.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",ae.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",ae.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",ae.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC",(af=br||(br={})).CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",af.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",af.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",af.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH",(ag=bs||(bs={})).SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",ag.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",ag.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",ag.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT",(ah=bt||(bt={})).EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",ah.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",ah.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",ah.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",ah.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",ah.EDIT_MODE_STYLE="EDIT_MODE_STYLE",ah.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",ah.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE",(ai=bu||(bu={})).FOREGROUND="FOREGROUND",ai.BACKGROUND="BACKGROUND",ai.PROMPT="PROMPT",ai.SEMANTIC="SEMANTIC",ai.INTERACTIVE="INTERACTIVE",(aj=bv||(bv={})).ASSET="ASSET",aj.STYLE="STYLE",(ak=bw||(bw={})).INSERT="INSERT",ak.REMOVE="REMOVE",ak.REMOVE_STATIC="REMOVE_STATIC",ak.OUTPAINT="OUTPAINT",(al=bx||(bx={})).OPTIMIZED="OPTIMIZED",al.LOSSLESS="LOSSLESS",(am=by||(by={})).CROP="CROP",am.PAD="PAD",(an=bz||(bz={})).SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",an.PREFERENCE_TUNING="PREFERENCE_TUNING",an.DISTILLATION="DISTILLATION",an.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING",(ao=bA||(bA={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",ao.PROCESSING="PROCESSING",ao.ACTIVE="ACTIVE",ao.FAILED="FAILED",(ap=bB||(bB={})).SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",ap.UPLOADED="UPLOADED",ap.GENERATED="GENERATED",ap.REGISTERED="REGISTERED",(aq=bC||(bC={})).TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",aq.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",aq.RESPONSE_REJECTED="RESPONSE_REJECTED",aq.NEED_MORE_INPUT="NEED_MORE_INPUT",aq.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",aq.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",aq.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",aq.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",aq.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",aq.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",aq.INPUT_OTHER="INPUT_OTHER",aq.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",aq.BLOCKLIST="BLOCKLIST",aq.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",aq.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",aq.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",aq.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",aq.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",aq.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",aq.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",aq.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",aq.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",aq.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",aq.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",aq.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",aq.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",aq.GENERATED_OTHER="GENERATED_OTHER",aq.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED",(ar=bD||(bD={})).VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",ar.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",ar.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS",(as=bE||(bE={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",as.ACTIVITY_START="ACTIVITY_START",as.ACTIVITY_END="ACTIVITY_END",(at=bF||(bF={})).START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",at.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",at.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW",(au=bG||(bG={})).END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",au.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",au.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW",(av=bH||(bH={})).ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",av.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",av.NO_INTERRUPTION="NO_INTERRUPTION",(aw=bI||(bI={})).TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",aw.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",aw.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",aw.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO",(ax=bJ||(bJ={})).SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",ax.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",ax.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",ax.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",ax.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",ax.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",ax.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",ax.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",ax.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",ax.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",ax.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",ax.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",ax.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR",(ay=bK||(bK={})).MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",ay.QUALITY="QUALITY",ay.DIVERSITY="DIVERSITY",ay.VOCALIZATION="VOCALIZATION",(az=bL||(bL={})).PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",az.PLAY="PLAY",az.PAUSE="PAUSE",az.STOP="STOP",az.RESET_CONTEXT="RESET_CONTEXT";class b0{constructor(a){const b={};for(const c of a.headers.entries())b[c[0]]=c[1];this.headers=b,this.responseInternal=a}json(){return this.responseInternal.json()}}class b1{get text(){var a,b,c,d,e,f,g,h;if((null==(d=null==(c=null==(b=null==(a=this.candidates)?void 0:a[0])?void 0:b.content)?void 0:c.parts)?void 0:d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let i="",j=!1,k=[];for(let a of null!=(h=null==(g=null==(f=null==(e=this.candidates)?void 0:e[0])?void 0:f.content)?void 0:g.parts)?h:[]){for(let[b,c]of Object.entries(a))"text"!==b&&"thought"!==b&&"thoughtSignature"!==b&&(null!==c||void 0!==c)&&k.push(b);if("string"==typeof a.text){if("boolean"==typeof a.thought&&a.thought)continue;j=!0,i+=a.text}}return k.length>0&&console.warn(`there are non-text parts ${k} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),j?i:void 0}get data(){var a,b,c,d,e,f,g,h;if((null==(d=null==(c=null==(b=null==(a=this.candidates)?void 0:a[0])?void 0:b.content)?void 0:c.parts)?void 0:d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let i="",j=[];for(let a of null!=(h=null==(g=null==(f=null==(e=this.candidates)?void 0:e[0])?void 0:f.content)?void 0:g.parts)?h:[]){for(let[b,c]of Object.entries(a))"inlineData"!==b&&(null!==c||void 0!==c)&&j.push(b);a.inlineData&&"string"==typeof a.inlineData.data&&(i+=atob(a.inlineData.data))}return j.length>0&&console.warn(`there are non-data parts ${j} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),i.length>0?btoa(i):void 0}get functionCalls(){var a,b,c,d,e,f,g,h;if((null==(d=null==(c=null==(b=null==(a=this.candidates)?void 0:a[0])?void 0:b.content)?void 0:c.parts)?void 0:d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let i=null==(h=null==(g=null==(f=null==(e=this.candidates)?void 0:e[0])?void 0:f.content)?void 0:g.parts)?void 0:h.filter(a=>a.functionCall).map(a=>a.functionCall).filter(a=>void 0!==a);if((null==i?void 0:i.length)!==0)return i}get executableCode(){var a,b,c,d,e,f,g,h,i;if((null==(d=null==(c=null==(b=null==(a=this.candidates)?void 0:a[0])?void 0:b.content)?void 0:c.parts)?void 0:d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let j=null==(h=null==(g=null==(f=null==(e=this.candidates)?void 0:e[0])?void 0:f.content)?void 0:g.parts)?void 0:h.filter(a=>a.executableCode).map(a=>a.executableCode).filter(a=>void 0!==a);if((null==j?void 0:j.length)!==0)return null==(i=null==j?void 0:j[0])?void 0:i.code}get codeExecutionResult(){var a,b,c,d,e,f,g,h,i;if((null==(d=null==(c=null==(b=null==(a=this.candidates)?void 0:a[0])?void 0:b.content)?void 0:c.parts)?void 0:d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let j=null==(h=null==(g=null==(f=null==(e=this.candidates)?void 0:e[0])?void 0:f.content)?void 0:g.parts)?void 0:h.filter(a=>a.codeExecutionResult).map(a=>a.codeExecutionResult).filter(a=>void 0!==a);if((null==j?void 0:j.length)!==0)return null==(i=null==j?void 0:j[0])?void 0:i.output}}class b2{}class b3{}class b4{}class b5{}class b6{}class b7{}class b8{}class b9{}class ca{}class cb{}class cc{_fromAPIResponse({apiResponse:a,_isVertexAI:b}){let c,d=new cc;if(b){let b,d,e,f,g,h;b={},null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["metadata"]))&&bY(b,["metadata"],e),null!=(f=bZ(a,["done"]))&&bY(b,["done"],f),null!=(g=bZ(a,["error"]))&&bY(b,["error"],g),null!=(h=bZ(a,["response"]))&&bY(b,["response"],function(a){let b={},c=bZ(a,["videos"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h;return c={},null!=(d=bZ(a,["_self"]))&&bY(c,["video"],(e={},null!=(f=bZ(b=d,["gcsUri"]))&&bY(e,["uri"],f),null!=(g=bZ(b,["bytesBase64Encoded"]))&&bY(e,["videoBytes"],b$(g)),null!=(h=bZ(b,["mimeType"]))&&bY(e,["mimeType"],h),e)),c})),bY(b,["generatedVideos"],a)}let d=bZ(a,["raiMediaFilteredCount"]);null!=d&&bY(b,["raiMediaFilteredCount"],d);let e=bZ(a,["raiMediaFilteredReasons"]);return null!=e&&bY(b,["raiMediaFilteredReasons"],e),b}(h)),c=b}else{let b,d,e,f,g,h;b={},null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["metadata"]))&&bY(b,["metadata"],e),null!=(f=bZ(a,["done"]))&&bY(b,["done"],f),null!=(g=bZ(a,["error"]))&&bY(b,["error"],g),null!=(h=bZ(a,["response","generateVideoResponse"]))&&bY(b,["response"],function(a){let b={},c=bZ(a,["generatedSamples"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h;return c={},null!=(d=bZ(a,["video"]))&&bY(c,["video"],(e={},null!=(f=bZ(b=d,["uri"]))&&bY(e,["uri"],f),null!=(g=bZ(b,["encodedVideo"]))&&bY(e,["videoBytes"],b$(g)),null!=(h=bZ(b,["encoding"]))&&bY(e,["mimeType"],h),e)),c})),bY(b,["generatedVideos"],a)}let d=bZ(a,["raiMediaFilteredCount"]);null!=d&&bY(b,["raiMediaFilteredCount"],d);let e=bZ(a,["raiMediaFilteredReasons"]);return null!=e&&bY(b,["raiMediaFilteredReasons"],e),b}(h)),c=b}return Object.assign(d,c),d}}class cd{}class ce{}class cf{}class cg{}class ch{}class ci{}class cj{}class ck{}class cl{_fromAPIResponse({apiResponse:a,_isVertexAI:b}){var c;let d,e,f,g,h,i,j,k,l,m,n=new cl;return Object.assign(n,(h={},null!=(i=bZ(a,["name"]))&&bY(h,["name"],i),null!=(j=bZ(a,["metadata"]))&&bY(h,["metadata"],j),null!=(k=bZ(a,["done"]))&&bY(h,["done"],k),null!=(l=bZ(a,["error"]))&&bY(h,["error"],l),null!=(m=bZ(a,["response"]))&&bY(h,["response"],(d={},null!=(e=bZ(c=m,["sdkHttpResponse"]))&&bY(d,["sdkHttpResponse"],e),null!=(f=bZ(c,["parent"]))&&bY(d,["parent"],f),null!=(g=bZ(c,["documentName"]))&&bY(d,["documentName"],g),d)),h)),n}}class cm{}class cn{}class co{}class cp{}class cq{}class cr{get text(){var a,b,c;let d="",e=!1,f=[];for(let g of null!=(c=null==(b=null==(a=this.serverContent)?void 0:a.modelTurn)?void 0:b.parts)?c:[]){for(let[a,b]of Object.entries(g))"text"!==a&&"thought"!==a&&null!==b&&f.push(a);if("string"==typeof g.text){if("boolean"==typeof g.thought&&g.thought)continue;e=!0,d+=g.text}}return f.length>0&&console.warn(`there are non-text parts ${f} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),e?d:void 0}get data(){var a,b,c;let d="",e=[];for(let f of null!=(c=null==(b=null==(a=this.serverContent)?void 0:a.modelTurn)?void 0:b.parts)?c:[]){for(let[a,b]of Object.entries(f))"inlineData"!==a&&null!==b&&e.push(a);f.inlineData&&"string"==typeof f.inlineData.data&&(d+=atob(f.inlineData.data))}return e.length>0&&console.warn(`there are non-data parts ${e} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),d.length>0?btoa(d):void 0}}class cs{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class ct{_fromAPIResponse({apiResponse:a,_isVertexAI:b}){let c=new ct;return Object.assign(c,b_(a)),c}}function cu(a,b){if(!b||"string"!=typeof b)throw Error("model is required and must be a string");if(b.includes("..")||b.includes("?")||b.includes("&"))throw Error("invalid model parameter");if(a.isVertexAI())if(b.startsWith("publishers/")||b.startsWith("projects/")||b.startsWith("models/"))return b;else{if(!(b.indexOf("/")>=0))return`publishers/google/models/${b}`;let a=b.split("/",2);return`publishers/${a[0]}/models/${a[1]}`}return b.startsWith("models/")||b.startsWith("tunedModels/")?b:`models/${b}`}function cv(a,b){let c=cu(a,b);return c?c.startsWith("publishers/")&&a.isVertexAI()?`projects/${a.getProject()}/locations/${a.getLocation()}/${c}`:c.startsWith("models/")&&a.isVertexAI()?`projects/${a.getProject()}/locations/${a.getLocation()}/publishers/google/${c}`:c:""}function cw(a){return Array.isArray(a)?a.map(a=>cx(a)):[cx(a)]}function cx(a){if("object"==typeof a&&null!==a)return a;throw Error(`Could not parse input as Blob. Unsupported blob type: ${typeof a}`)}function cy(a){let b=cx(a);if(b.mimeType&&b.mimeType.startsWith("image/"))return b;throw Error(`Unsupported mime type: ${b.mimeType}`)}function cz(a){let b=cx(a);if(b.mimeType&&b.mimeType.startsWith("audio/"))return b;throw Error(`Unsupported mime type: ${b.mimeType}`)}function cA(a){if(null==a)throw Error("PartUnion is required");if("object"==typeof a)return a;if("string"==typeof a)return{text:a};throw Error(`Unsupported part type: ${typeof a}`)}function cB(a){if(null==a||Array.isArray(a)&&0===a.length)throw Error("PartListUnion is required");return Array.isArray(a)?a.map(a=>cA(a)):[cA(a)]}function cC(a){return null!=a&&"object"==typeof a&&"parts"in a&&Array.isArray(a.parts)}function cD(a){return null!=a&&"object"==typeof a&&"functionCall"in a}function cE(a){return null!=a&&"object"==typeof a&&"functionResponse"in a}function cF(a){if(null==a)throw Error("ContentUnion is required");return cC(a)?a:{role:"user",parts:cB(a)}}function cG(a,b){if(!b)return[];if(a.isVertexAI()&&Array.isArray(b))return b.flatMap(a=>{let b=cF(a);return b.parts&&b.parts.length>0&&void 0!==b.parts[0].text?[b.parts[0].text]:[]});if(a.isVertexAI()){let a=cF(b);return a.parts&&a.parts.length>0&&void 0!==a.parts[0].text?[a.parts[0].text]:[]}return Array.isArray(b)?b.map(a=>cF(a)):[cF(b)]}function cH(a){if(null==a||Array.isArray(a)&&0===a.length)throw Error("contents are required");if(!Array.isArray(a)){if(cD(a)||cE(a))throw Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[cF(a)]}let b=[],c=[],d=cC(a[0]);for(let e of a){let a=cC(e);if(a!=d)throw Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(a)b.push(e);else if(cD(e)||cE(e))throw Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");else c.push(e)}return d||b.push({role:"user",parts:cB(c)}),b}function cI(a){let b={},c=["items"],d=["anyOf"],e=["properties"];if(a.type&&a.anyOf)throw Error("type and anyOf cannot be both populated.");let f=a.anyOf;for(let[g,h]of(null!=f&&2==f.length&&("null"===f[0].type?(b.nullable=!0,a=f[1]):"null"===f[1].type&&(b.nullable=!0,a=f[0])),a.type instanceof Array&&function(a,b){a.includes("null")&&(b.nullable=!0);let c=a.filter(a=>"null"!==a);if(1===c.length)b.type=Object.values(aE).includes(c[0].toUpperCase())?c[0].toUpperCase():aE.TYPE_UNSPECIFIED;else for(let a of(b.anyOf=[],c))b.anyOf.push({type:Object.values(aE).includes(a.toUpperCase())?a.toUpperCase():aE.TYPE_UNSPECIFIED})}(a.type,b),Object.entries(a)))if(null!=h)if("type"==g){if("null"===h)throw Error("type: null can not be the only possible type for the field.");if(h instanceof Array)continue;b.type=Object.values(aE).includes(h.toUpperCase())?h.toUpperCase():aE.TYPE_UNSPECIFIED}else if(c.includes(g))b[g]=cI(h);else if(d.includes(g)){let a=[];for(let c of h){if("null"==c.type){b.nullable=!0;continue}a.push(cI(c))}b[g]=a}else if(e.includes(g)){let a={};for(let[b,c]of Object.entries(h))a[b]=cI(c);b[g]=a}else{if("additionalProperties"===g)continue;b[g]=h}return b}function cJ(a){if("object"==typeof a)return a;if("string"==typeof a)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:a}}};throw Error(`Unsupported speechConfig type: ${typeof a}`)}function cK(a){if("multiSpeakerVoiceConfig"in a)throw Error("multiSpeakerVoiceConfig is not supported in the live API.");return a}function cL(a){if(a.functionDeclarations)for(let b of a.functionDeclarations)b.parameters&&(Object.keys(b.parameters).includes("$schema")?b.parametersJsonSchema||(b.parametersJsonSchema=b.parameters,delete b.parameters):b.parameters=cI(b.parameters)),b.response&&(Object.keys(b.response).includes("$schema")?b.responseJsonSchema||(b.responseJsonSchema=b.response,delete b.response):b.response=cI(b.response));return a}function cM(a){if(null==a)throw Error("tools is required");if(!Array.isArray(a))throw Error("tools is required and must be an array of Tools");let b=[];for(let c of a)b.push(c);return b}function cN(a,b){if("string"!=typeof b)throw Error("name must be a string");return function(a,b,c,d=1){let e=!b.startsWith(`${c}/`)&&b.split("/").length===d;if(a.isVertexAI())if(b.startsWith("projects/"))return b;else if(b.startsWith("locations/"))return`projects/${a.getProject()}/${b}`;else if(b.startsWith(`${c}/`))return`projects/${a.getProject()}/locations/${a.getLocation()}/${b}`;else if(e)return`projects/${a.getProject()}/locations/${a.getLocation()}/${c}/${b}`;else return b;return e?`${c}/${b}`:b}(a,b,"cachedContents")}function cO(a){switch(a){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return a}}function cP(a){return null!=a&&"object"==typeof a&&"video"in a}function cQ(a){return null!=a&&"object"==typeof a&&"uri"in a}function cR(a){var b;let c;if(null!=a&&"object"==typeof a&&"name"in a&&(c=a.name),!cQ(a)||void 0!==(c=a.uri)){if(!cP(a)||void 0!==(c=null==(b=a.video)?void 0:b.uri)){if("string"==typeof a&&(c=a),void 0===c)throw Error("Could not extract file name from the provided input.");if(c.startsWith("https://")){let a=c.split("files/")[1].match(/[a-z0-9]+/);if(null===a)throw Error(`Could not extract file name from URI ${c}`);c=a[0]}else c.startsWith("files/")&&(c=c.split("files/")[1]);return c}}}function cS(a,b){return a.isVertexAI()?b?"publishers/google/models":"models":b?"models":"tunedModels"}function cT(a){for(let d of["models","tunedModels","publisherModels"]){var b,c;if(b=a,c=d,null!==b&&"object"==typeof b&&c in b)return a[d]}return[]}function cU(a,b){let c;if("string"==typeof b)if(a.isVertexAI())if(b.startsWith("gs://"))c={format:"jsonl",gcsUri:[b]};else if(b.startsWith("bq://"))c={format:"bigquery",bigqueryUri:b};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(b))c={format:"vertex-dataset",vertexDatasetName:b};else throw Error(`Unsupported string source for Vertex AI: ${b}`);else if(b.startsWith("files/"))c={fileName:b};else throw Error(`Unsupported string source for Gemini API: ${b}`);else if(Array.isArray(b)){if(a.isVertexAI())throw Error("InlinedRequest[] is not supported in Vertex AI.");c={inlinedRequests:b}}else c=b;let d=[c.gcsUri,c.bigqueryUri,c.vertexDatasetName].filter(Boolean).length,e=[c.inlinedRequests,c.fileName].filter(Boolean).length;if(a.isVertexAI()){if(e>0||1!==d)throw Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(d>0||1!==e)throw Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return c}function cV(a){if("object"!=typeof a||null===a)return{};let b=a.inlinedResponses;if("object"!=typeof b||null===b)return a;let c=b.inlinedResponses;if(!Array.isArray(c)||0===c.length)return a;let d=!1;for(let a of c){if("object"!=typeof a||null===a)continue;let b=a.response;if("object"==typeof b&&null!==b&&void 0!==b.embedding){d=!0;break}}return d&&(a.inlinedEmbedContentResponses=a.inlinedResponses,delete a.inlinedResponses),a}function cW(a,b){if(!a.isVertexAI()){if(/batches\/[^/]+$/.test(b))return b.split("/").pop();throw Error(`Invalid batch job name: ${b}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(b))return b.split("/").pop();if(/^\d+$/.test(b))return b;throw Error(`Invalid batch job name: ${b}.`)}function cX(a){if("BATCH_STATE_UNSPECIFIED"===a)return"JOB_STATE_UNSPECIFIED";if("BATCH_STATE_PENDING"===a)return"JOB_STATE_PENDING";if("BATCH_STATE_RUNNING"===a)return"JOB_STATE_RUNNING";if("BATCH_STATE_SUCCEEDED"===a)return"JOB_STATE_SUCCEEDED";if("BATCH_STATE_FAILED"===a)return"JOB_STATE_FAILED";else if("BATCH_STATE_CANCELLED"===a)return"JOB_STATE_CANCELLED";else if("BATCH_STATE_EXPIRED"===a)return"JOB_STATE_EXPIRED";else return a}function cY(a){let b={},c=bZ(a,["name"]);null!=c&&bY(b,["name"],c);let d=bZ(a,["metadata","displayName"]);null!=d&&bY(b,["displayName"],d);let e=bZ(a,["metadata","state"]);null!=e&&bY(b,["state"],cX(e));let f=bZ(a,["metadata","createTime"]);null!=f&&bY(b,["createTime"],f);let g=bZ(a,["metadata","endTime"]);null!=g&&bY(b,["endTime"],g);let h=bZ(a,["metadata","updateTime"]);null!=h&&bY(b,["updateTime"],h);let i=bZ(a,["metadata","model"]);null!=i&&bY(b,["model"],i);let j=bZ(a,["metadata","output"]);return null!=j&&bY(b,["dest"],function(a){let b={},c=bZ(a,["responsesFile"]);null!=c&&bY(b,["fileName"],c);let d=bZ(a,["inlinedResponses","inlinedResponses"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f;return c={},null!=(d=bZ(b=a,["response"]))&&bY(c,["response"],function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["candidates"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["content"]);null!=c&&bY(b,["content"],c);let d=bZ(a,["citationMetadata"]);null!=d&&bY(b,["citationMetadata"],function(a){let b={},c=bZ(a,["citationSources"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["citations"],a)}return b}(d));let e=bZ(a,["tokenCount"]);null!=e&&bY(b,["tokenCount"],e);let f=bZ(a,["finishReason"]);null!=f&&bY(b,["finishReason"],f);let g=bZ(a,["groundingMetadata"]);null!=g&&bY(b,["groundingMetadata"],g);let h=bZ(a,["avgLogprobs"]);null!=h&&bY(b,["avgLogprobs"],h);let i=bZ(a,["index"]);null!=i&&bY(b,["index"],i);let j=bZ(a,["logprobsResult"]);null!=j&&bY(b,["logprobsResult"],j);let k=bZ(a,["safetyRatings"]);if(null!=k){let a=k;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["safetyRatings"],a)}let l=bZ(a,["urlContextMetadata"]);return null!=l&&bY(b,["urlContextMetadata"],l),b})(a))),bY(b,["candidates"],a)}let e=bZ(a,["modelVersion"]);null!=e&&bY(b,["modelVersion"],e);let f=bZ(a,["promptFeedback"]);null!=f&&bY(b,["promptFeedback"],f);let g=bZ(a,["responseId"]);null!=g&&bY(b,["responseId"],g);let h=bZ(a,["usageMetadata"]);null!=h&&bY(b,["usageMetadata"],h);let i=bZ(a,["modelStatus"]);return null!=i&&bY(b,["modelStatus"],i),b}(d)),null!=(e=bZ(b,["metadata"]))&&bY(c,["metadata"],e),null!=(f=bZ(b,["error"]))&&bY(c,["error"],f),c})),bY(b,["inlinedResponses"],a)}let e=bZ(a,["inlinedEmbedContentResponses","inlinedResponses"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["inlinedEmbedContentResponses"],a)}return b}(cV(j))),b}function cZ(a){var b,c,d;let e,f,g,h,i,j,k,l,m,n,o,p,q,r={},s=bZ(a,["name"]);null!=s&&bY(r,["name"],s);let t=bZ(a,["displayName"]);null!=t&&bY(r,["displayName"],t);let u=bZ(a,["state"]);null!=u&&bY(r,["state"],cX(u));let v=bZ(a,["error"]);null!=v&&bY(r,["error"],v);let w=bZ(a,["createTime"]);null!=w&&bY(r,["createTime"],w);let x=bZ(a,["startTime"]);null!=x&&bY(r,["startTime"],x);let y=bZ(a,["endTime"]);null!=y&&bY(r,["endTime"],y);let z=bZ(a,["updateTime"]);null!=z&&bY(r,["updateTime"],z);let A=bZ(a,["model"]);null!=A&&bY(r,["model"],A);let B=bZ(a,["inputConfig"]);null!=B&&bY(r,["src"],(e={},null!=(f=bZ(c=B,["instancesFormat"]))&&bY(e,["format"],f),null!=(g=bZ(c,["gcsSource","uris"]))&&bY(e,["gcsUri"],g),null!=(h=bZ(c,["bigquerySource","inputUri"]))&&bY(e,["bigqueryUri"],h),null!=(i=bZ(c,["vertexMultimodalDatasetSource","datasetName"]))&&bY(e,["vertexDatasetName"],i),e));let C=bZ(a,["outputConfig"]);null!=C&&bY(r,["dest"],(b=cV(C),m={},null!=(n=bZ(b,["predictionsFormat"]))&&bY(m,["format"],n),null!=(o=bZ(b,["gcsDestination","outputUriPrefix"]))&&bY(m,["gcsUri"],o),null!=(p=bZ(b,["bigqueryDestination","outputUri"]))&&bY(m,["bigqueryUri"],p),null!=(q=bZ(b,["vertexMultimodalDatasetDestination"]))&&bY(m,["vertexDataset"],(j={},null!=(k=bZ(d=q,["bigqueryDestination","outputUri"]))&&bY(j,["bigqueryDestination"],k),null!=(l=bZ(d,["displayName"]))&&bY(j,["displayName"],l),j)),m));let D=bZ(a,["outputInfo"]);null!=D&&bY(r,["outputInfo"],D);let E=bZ(a,["completionStats"]);return null!=E&&bY(r,["completionStats"],E),r}function c$(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return c={},null!=(d=bZ(b=a,["mediaResolution"]))&&bY(c,["mediaResolution"],d),null!=(e=bZ(b,["toolCall"]))&&bY(c,["toolCall"],e),null!=(f=bZ(b,["toolResponse"]))&&bY(c,["toolResponse"],f),null!=(g=bZ(b,["audioTranscription"]))&&bY(c,["audioTranscription"],g),null!=(h=bZ(b,["codeExecutionResult"]))&&bY(c,["codeExecutionResult"],h),null!=(i=bZ(b,["executableCode"]))&&bY(c,["executableCode"],i),null!=(j=bZ(b,["fileData"]))&&bY(c,["fileData"],function(a){let b={};if(void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["fileUri"]);null!=c&&bY(b,["fileUri"],c);let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(j)),null!=(k=bZ(b,["functionCall"]))&&bY(c,["functionCall"],function(a){let b={},c=bZ(a,["args"]);null!=c&&bY(b,["args"],c);let d=bZ(a,["id"]);null!=d&&bY(b,["id"],d);let e=bZ(a,["name"]);if(null!=e&&bY(b,["name"],e),void 0!==bZ(a,["partialArgs"]))throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["willContinue"]))throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(k)),null!=(l=bZ(b,["functionResponse"]))&&bY(c,["functionResponse"],l),null!=(m=bZ(b,["inlineData"]))&&bY(c,["inlineData"],function(a){let b={},c=bZ(a,["data"]);if(null!=c&&bY(b,["data"],c),void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(m)),null!=(n=bZ(b,["text"]))&&bY(c,["text"],n),null!=(o=bZ(b,["thought"]))&&bY(c,["thought"],o),null!=(p=bZ(b,["thoughtSignature"]))&&bY(c,["thoughtSignature"],p),null!=(q=bZ(b,["videoMetadata"]))&&bY(c,["videoMetadata"],q),null!=(r=bZ(b,["partMetadata"]))&&bY(c,["partMetadata"],r),c})),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}function c_(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["_url","model"],cu(a,d));let e=bZ(b,["src"]);null!=e&&bY(c,["batch","inputConfig"],function(a,b){let c={};if(void 0!==bZ(b,["format"]))throw Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(b,["gcsUri"]))throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(b,["bigqueryUri"]))throw Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(b,["vertexDatasetName"]))throw Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(b,["fileName"]);null!=d&&bY(c,["fileName"],d);let e=bZ(b,["inlinedRequests"]);if(null!=e){let b=e;Array.isArray(b)&&(b=b.map(b=>(function(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["request","model"],cu(a,d));let e=bZ(b,["contents"]);if(null!=e){let a=cH(e);Array.isArray(a)&&(a=a.map(a=>c$(a))),bY(c,["request","contents"],a)}let f=bZ(b,["metadata"]);null!=f&&bY(c,["metadata"],f);let g=bZ(b,["config"]);return null!=g&&bY(c,["request","generationConfig"],function(a,b,c){var d;let e,f,g,h,i={},j=bZ(b,["serviceTier"]);void 0!==c&&null!=j&&bY(c,["serviceTier"],j);let k=bZ(b,["systemInstruction"]);void 0!==c&&null!=k&&bY(c,["systemInstruction"],c$(cF(k)));let l=bZ(b,["temperature"]);null!=l&&bY(i,["temperature"],l);let m=bZ(b,["topP"]);null!=m&&bY(i,["topP"],m);let n=bZ(b,["topK"]);null!=n&&bY(i,["topK"],n);let o=bZ(b,["candidateCount"]);null!=o&&bY(i,["candidateCount"],o);let p=bZ(b,["maxOutputTokens"]);null!=p&&bY(i,["maxOutputTokens"],p);let q=bZ(b,["stopSequences"]);null!=q&&bY(i,["stopSequences"],q);let r=bZ(b,["responseLogprobs"]);null!=r&&bY(i,["responseLogprobs"],r);let s=bZ(b,["logprobs"]);null!=s&&bY(i,["logprobs"],s);let t=bZ(b,["presencePenalty"]);null!=t&&bY(i,["presencePenalty"],t);let u=bZ(b,["frequencyPenalty"]);null!=u&&bY(i,["frequencyPenalty"],u);let v=bZ(b,["seed"]);null!=v&&bY(i,["seed"],v);let w=bZ(b,["responseMimeType"]);null!=w&&bY(i,["responseMimeType"],w);let x=bZ(b,["responseSchema"]);null!=x&&bY(i,["responseSchema"],cI(x));let y=bZ(b,["responseJsonSchema"]);if(null!=y&&bY(i,["responseJsonSchema"],y),void 0!==bZ(b,["routingConfig"]))throw Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(b,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let z=bZ(b,["safetySettings"]);if(void 0!==c&&null!=z){let a=z;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["category"]);if(null!=c&&bY(b,["category"],c),void 0!==bZ(a,["method"]))throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["threshold"]);return null!=d&&bY(b,["threshold"],d),b})(a))),bY(c,["safetySettings"],a)}let A=bZ(b,["tools"]);if(void 0!==c&&null!=A){let a=cM(A);Array.isArray(a)&&(a=a.map(a=>(function(a){let b={};if(void 0!==bZ(a,["retrieval"]))throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["googleMaps"]);null!=c&&bY(b,["googleMaps"],function(a){let b={},c=bZ(a,["authConfig"]);null!=c&&bY(b,["authConfig"],function(a){let b={},c=bZ(a,["apiKey"]);if(null!=c&&bY(b,["apiKey"],c),void 0!==bZ(a,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["authType"]))throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oauthConfig"]))throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oidcConfig"]))throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["enableWidget"]);if(null!=d&&bY(b,["enableWidget"],d),void 0!==bZ(a,["groundingTypes"]))throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["mcpServers"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mcpServers"],a)}let e=bZ(a,["codeExecution"]);null!=e&&bY(b,["codeExecution"],e);let f=bZ(a,["computerUse"]);if(null!=f&&bY(b,["computerUse"],f),void 0!==bZ(a,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["exaAiSearch"]))throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=bZ(a,["functionDeclarations"]);if(null!=g){let a=g;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let h=bZ(a,["googleSearch"]);null!=h&&bY(b,["googleSearch"],function(a){let b={};if(void 0!==bZ(a,["blockingConfidence"]))throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["excludeDomains"]))throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["searchTypes"]);null!=c&&bY(b,["searchTypes"],c);let d=bZ(a,["timeRangeFilter"]);return null!=d&&bY(b,["timeRangeFilter"],d),b}(h));let i=bZ(a,["googleSearchRetrieval"]);if(null!=i&&bY(b,["googleSearchRetrieval"],i),void 0!==bZ(a,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["urlContext"]);null!=j&&bY(b,["urlContext"],j);let k=bZ(a,["fileSearch"]);return null!=k&&bY(b,["fileSearch"],k),b})(cL(a)))),bY(c,["tools"],a)}let B=bZ(b,["toolConfig"]);if(void 0!==c&&null!=B&&bY(c,["toolConfig"],(e={},null!=(f=bZ(d=B,["functionCallingConfig"]))&&bY(e,["functionCallingConfig"],function(a){let b={},c=bZ(a,["allowedFunctionNames"]);null!=c&&bY(b,["allowedFunctionNames"],c);let d=bZ(a,["mode"]);if(null!=d&&bY(b,["mode"],d),void 0!==bZ(a,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(f)),null!=(g=bZ(d,["retrievalConfig"]))&&bY(e,["retrievalConfig"],g),null!=(h=bZ(d,["includeServerSideToolInvocations"]))&&bY(e,["includeServerSideToolInvocations"],h),e)),void 0!==bZ(b,["labels"]))throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let C=bZ(b,["cachedContent"]);void 0!==c&&null!=C&&bY(c,["cachedContent"],cN(a,C));let D=bZ(b,["responseModalities"]);null!=D&&bY(i,["responseModalities"],D);let E=bZ(b,["mediaResolution"]);null!=E&&bY(i,["mediaResolution"],E);let F=bZ(b,["speechConfig"]);if(null!=F&&bY(i,["speechConfig"],cJ(F)),void 0!==bZ(b,["audioTimestamp"]))throw Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let G=bZ(b,["thinkingConfig"]);null!=G&&bY(i,["thinkingConfig"],G);let H=bZ(b,["audioTranscriptionConfig"]);null!=H&&bY(i,["audioTranscriptionConfig"],H);let I=bZ(b,["imageConfig"]);null!=I&&bY(i,["imageConfig"],function(a){let b={},c=bZ(a,["aspectRatio"]);null!=c&&bY(b,["aspectRatio"],c);let d=bZ(a,["imageSize"]);if(null!=d&&bY(b,["imageSize"],d),void 0!==bZ(a,["personGeneration"]))throw Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["outputMimeType"]))throw Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["imageOutputOptions"]))throw Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["prominentPeople"]))throw Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(I));let J=bZ(b,["enableEnhancedCivicAnswers"]);if(null!=J&&bY(i,["enableEnhancedCivicAnswers"],J),void 0!==bZ(b,["modelArmorConfig"]))throw Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}(a,g,bZ(c,["request"],{}))),c})(a,b))),bY(c,["requests","requests"],b)}return c}(a,cU(a,e)));let f=bZ(b,["config"]);return null!=f&&function(a,b){let c=bZ(a,["displayName"]);if(void 0!==b&&null!=c&&bY(b,["batch","displayName"],c),void 0!==bZ(a,["dest"]))throw Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["webhookConfig"]);void 0!==b&&null!=d&&bY(b,["batch","webhookConfig"],d)}(f,c),c}(aA=bM||(bM={})).PAGED_ITEM_BATCH_JOBS="batchJobs",aA.PAGED_ITEM_MODELS="models",aA.PAGED_ITEM_TUNING_JOBS="tuningJobs",aA.PAGED_ITEM_FILES="files",aA.PAGED_ITEM_CACHED_CONTENTS="cachedContents",aA.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",aA.PAGED_ITEM_DOCUMENTS="documents",aA.PAGED_ITEM_SKILLS="skills";class c0{constructor(a,b,c,d){this.pageInternal=[],this.paramsInternal={},this.requestInternal=b,this.init(a,c,d)}init(a,b,c){var d,e;this.nameInternal=a,this.pageInternal=b[this.nameInternal]||[],this.sdkHttpResponseInternal=null==b?void 0:b.sdkHttpResponse,this.idxInternal=0;let f={config:{}};(f=c&&0!==Object.keys(c).length?"object"==typeof c?Object.assign({},c):c:{config:{}}).config&&(f.config.pageToken=b.nextPageToken),this.paramsInternal=f,this.pageInternalSize=null!=(e=null==(d=f.config)?void 0:d.pageSize)?e:this.pageInternal.length}initNextPage(a){this.init(this.nameInternal,a,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(a){return this.pageInternal[a]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(!this.hasNextPage())return{value:void 0,done:!0};else await this.nextPage();let a=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:a,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw Error("No more pages to fetch.");let a=await this.requestInternal(this.params);return this.initNextPage(a),this.page}hasNextPage(){var a;return(null==(a=this.params.config)?void 0:a.pageToken)!==void 0}}class c1 extends bW{constructor(a){super(),this.apiClient=a,this.list=async(a={})=>new c0(bM.PAGED_ITEM_BATCH_JOBS,a=>this.listInternal(a),await this.listInternal(a),a),this.create=async a=>(this.apiClient.isVertexAI()&&(a.config=this.formatDestination(a.src,a.config)),this.createInternal(a)),this.createEmbeddings=async a=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(a)}}createInlinedGenerateContentRequest(a){let b=c_(this.apiClient,a),c=bX("{model}:batchGenerateContent",b._url),d=b.batch.inputConfig.requests,e=d.requests,f=[];for(let a of e){let b=Object.assign({},a);if(b.systemInstruction){let a=b.systemInstruction;delete b.systemInstruction;let c=b.request;c.systemInstruction=a,b.request=c}f.push(b)}return d.requests=f,delete b.config,delete b._url,delete b._query,{path:c,body:b}}getGcsUri(a){return"string"==typeof a?a.startsWith("gs://")?a:void 0:!Array.isArray(a)&&a.gcsUri&&a.gcsUri.length>0?a.gcsUri[0]:void 0}getBigqueryUri(a){return"string"==typeof a?a.startsWith("bq://")?a:void 0:Array.isArray(a)?void 0:a.bigqueryUri}formatDestination(a,b){let c=b?Object.assign({},b):{},d=Date.now().toString();if(c.displayName||(c.displayName=`genaiBatchJob_${d}`),void 0===c.dest){let b=this.getGcsUri(a),e=this.getBigqueryUri(a);if(b)b.endsWith(".jsonl")?c.dest=`${b.slice(0,-6)}/dest`:c.dest=`${b}_dest_${d}`;else if(e)c.dest=`${e}_dest_${d}`;else throw Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return c}async createInternal(a){var b,c,d,e,f;let g="",h={};if(this.apiClient.isVertexAI()){let d,e,i,j,k=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["model"],cu(f,e)),null!=(i=bZ(a,["src"]))&&bY(d,["inputConfig"],function(a){let b={},c=bZ(a,["format"]);null!=c&&bY(b,["instancesFormat"],c);let d=bZ(a,["gcsUri"]);null!=d&&bY(b,["gcsSource","uris"],d);let e=bZ(a,["bigqueryUri"]);null!=e&&bY(b,["bigquerySource","inputUri"],e);let f=bZ(a,["vertexDatasetName"]);if(null!=f&&bY(b,["vertexMultimodalDatasetSource","datasetName"],f),void 0!==bZ(a,["fileName"]))throw Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["inlinedRequests"]))throw Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(cU(f,i))),null!=(j=bZ(a,["config"]))&&function(a,b){let c=bZ(a,["displayName"]);void 0!==b&&null!=c&&bY(b,["displayName"],c);let d=bZ(a,["dest"]);if(void 0!==b&&null!=d&&bY(b,["outputConfig"],function(a){var b;let c,d,e,f={},g=bZ(a,["format"]);null!=g&&bY(f,["predictionsFormat"],g);let h=bZ(a,["gcsUri"]);null!=h&&bY(f,["gcsDestination","outputUriPrefix"],h);let i=bZ(a,["bigqueryUri"]);null!=i&&bY(f,["bigqueryDestination","outputUri"],i);let j=bZ(a,["vertexDataset"]);if(null!=j&&bY(f,["vertexMultimodalDatasetDestination"],(c={},null!=(d=bZ(b=j,["bigqueryDestination"]))&&bY(c,["bigqueryDestination","outputUri"],d),null!=(e=bZ(b,["displayName"]))&&bY(c,["displayName"],e),c)),void 0!==bZ(a,["fileName"]))throw Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["inlinedResponses"]))throw Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["inlinedEmbedContentResponses"]))throw Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return f}(function(a){if("string"!=typeof a)return a;if(a.startsWith("gs://"))return{format:"jsonl",gcsUri:a};if(a.startsWith("bq://"))return{format:"bigquery",bigqueryUri:a};throw Error(`Unsupported destination: ${a}`)}(d))),void 0!==bZ(a,["webhookConfig"]))throw Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.")}(j,d),d);return g=bX("batchPredictionJobs",k._url),h=k._query,delete k._url,delete k._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(k),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>cZ(a))}{let b=c_(this.apiClient,a);return g=bX("{model}:batchGenerateContent",b._url),h=b._query,delete b._url,delete b._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>cY(a))}}async createEmbeddingsInternal(a){var b,c,d,e,f;let g="",h={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let i,j,k,l,m,n,o,p,q=(d=this.apiClient,l={},null!=(m=bZ(a,["model"]))&&bY(l,["_url","model"],cu(d,m)),null!=(n=bZ(a,["src"]))&&bY(l,["batch","inputConfig"],(e=d,i={},null!=(j=bZ(f=n,["fileName"]))&&bY(i,["file_name"],j),null!=(k=bZ(f,["inlinedRequests"]))&&bY(i,["requests"],function(a,b){let c={},d=bZ(b,["contents"]);if(null!=d){let b=cG(a,d);Array.isArray(b)&&(b=b.map(a=>a)),bY(c,["requests[]","request","content"],b)}let e=bZ(b,["config"]);return null!=e&&(bY(c,["_self"],function(a,b){let c=bZ(a,["taskType"]);void 0!==b&&null!=c&&bY(b,["requests[]","taskType"],c);let d=bZ(a,["title"]);void 0!==b&&null!=d&&bY(b,["requests[]","title"],d);let e=bZ(a,["outputDimensionality"]);if(void 0!==b&&null!=e&&bY(b,["requests[]","outputDimensionality"],e),void 0!==bZ(a,["mimeType"]))throw Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["autoTruncate"]))throw Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["documentOcr"]))throw Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["audioTrackExtraction"]))throw Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return{}}(e,c)),!function(a,b){for(let[c,d]of Object.entries(b)){let b=c.split("."),e=d.split("."),f=new Set,g=-1;for(let a=0;a<b.length;a++)if("*"===b[a]){g=a;break}if(-1!==g&&e.length>g)for(let a=g;a<e.length;a++){let b=e[a];"*"===b||b.endsWith("[]")||b.endsWith("[0]")||f.add(b)}!function a(b,c,d,e,f){if(e>=c.length||"object"!=typeof b||null===b)return;let g=c[e];if(g.endsWith("[]")){let h=g.slice(0,-2);if(h in b&&Array.isArray(b[h]))for(let g of b[h])a(g,c,d,e+1,f)}else if("*"===g){if("object"==typeof b&&null!==b&&!Array.isArray(b)){let a=Object.keys(b).filter(a=>!a.startsWith("_")&&!f.has(a)),c={};for(let d of a)c[d]=b[d];for(let[a,f]of Object.entries(c)){let c=[];for(let b of d.slice(e))"*"===b?c.push(a):c.push(b);bY(b,c,f)}for(let c of a)delete b[c]}}else g in b&&a(b[g],c,d,e+1,f)}(a,b,e,0,f)}}(c,{"requests[].*":"requests[].request.*"})),c}(e,k)),i)),null!=(o=bZ(a,["config"]))&&(p=bZ(o,["displayName"]),void 0!==l&&null!=p&&bY(l,["batch","displayName"],p)),l);return g=bX("{model}:asyncBatchEmbedContent",q._url),h=q._query,delete q._url,delete q._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(q),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>cY(a))}}async get(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cW(f,e)),d);return h=bX("batchPredictionJobs/{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>cZ(a))}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cW(g,c)),b);return h=bX("batches/{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>cY(a))}}async cancel(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cW(f,e)),d);h=bX("batchPredictionJobs/{name}:cancel",g._url),i=g._query,delete g._url,delete g._query,await this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal})}else{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cW(g,c)),b);h=bX("batches/{name}:cancel",f._url),i=f._query,delete f._url,delete f._query,await this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal})}}async listInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d,e,h,i,j,k=(d={},null!=(e=bZ(a,["config"]))&&(h=bZ(e,["pageSize"]),void 0!==d&&null!=h&&bY(d,["_query","pageSize"],h),i=bZ(e,["pageToken"]),void 0!==d&&null!=i&&bY(d,["_query","pageToken"],i),j=bZ(e,["filter"]),void 0!==d&&null!=j&&bY(d,["_query","filter"],j)),d);return f=bX("batchPredictionJobs",k._url),g=k._query,delete k._url,delete k._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(k),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["batchPredictionJobs"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>cZ(a))),bY(b,["batchJobs"],a)}return b}(a),c=new cq;return Object.assign(c,b),c})}{let b,c,h=(b={},null!=(c=bZ(a,["config"]))&&function(a,b){let c=bZ(a,["pageSize"]);void 0!==b&&null!=c&&bY(b,["_query","pageSize"],c);let d=bZ(a,["pageToken"]);if(void 0!==b&&null!=d&&bY(b,["_query","pageToken"],d),void 0!==bZ(a,["filter"]))throw Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(c,b),b);return f=bX("batches",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["operations"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>cY(a))),bY(b,["batchJobs"],a)}return b}(a),c=new cq;return Object.assign(c,b),c})}}async delete(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cW(f,e)),d);return h=bX("batchPredictionJobs/{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f;return b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["done"]))&&bY(b,["done"],e),null!=(f=bZ(a,["error"]))&&bY(b,["error"],f),b})}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cW(g,c)),b);return h=bX("batches/{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f;return b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["done"]))&&bY(b,["done"],e),null!=(f=bZ(a,["error"]))&&bY(b,["error"],f),b})}}}function c2(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return c={},null!=(d=bZ(b=a,["mediaResolution"]))&&bY(c,["mediaResolution"],d),null!=(e=bZ(b,["toolCall"]))&&bY(c,["toolCall"],e),null!=(f=bZ(b,["toolResponse"]))&&bY(c,["toolResponse"],f),null!=(g=bZ(b,["audioTranscription"]))&&bY(c,["audioTranscription"],g),null!=(h=bZ(b,["codeExecutionResult"]))&&bY(c,["codeExecutionResult"],h),null!=(i=bZ(b,["executableCode"]))&&bY(c,["executableCode"],i),null!=(j=bZ(b,["fileData"]))&&bY(c,["fileData"],function(a){let b={};if(void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["fileUri"]);null!=c&&bY(b,["fileUri"],c);let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(j)),null!=(k=bZ(b,["functionCall"]))&&bY(c,["functionCall"],function(a){let b={},c=bZ(a,["args"]);null!=c&&bY(b,["args"],c);let d=bZ(a,["id"]);null!=d&&bY(b,["id"],d);let e=bZ(a,["name"]);if(null!=e&&bY(b,["name"],e),void 0!==bZ(a,["partialArgs"]))throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["willContinue"]))throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(k)),null!=(l=bZ(b,["functionResponse"]))&&bY(c,["functionResponse"],l),null!=(m=bZ(b,["inlineData"]))&&bY(c,["inlineData"],function(a){let b={},c=bZ(a,["data"]);if(null!=c&&bY(b,["data"],c),void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(m)),null!=(n=bZ(b,["text"]))&&bY(c,["text"],n),null!=(o=bZ(b,["thought"]))&&bY(c,["thought"],o),null!=(p=bZ(b,["thoughtSignature"]))&&bY(c,["thoughtSignature"],p),null!=(q=bZ(b,["videoMetadata"]))&&bY(c,["videoMetadata"],q),null!=(r=bZ(b,["partMetadata"]))&&bY(c,["partMetadata"],r),c})),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}function c3(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["mediaResolution"]);if(null!=c&&bY(b,["mediaResolution"],c),void 0!==bZ(a,["toolCall"]))throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["toolResponse"]))throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let d=bZ(a,["audioTranscription"]);null!=d&&bY(b,["audioTranscription"],d);let e=bZ(a,["codeExecutionResult"]);null!=e&&bY(b,["codeExecutionResult"],function(a){let b={},c=bZ(a,["outcome"]);null!=c&&bY(b,["outcome"],c);let d=bZ(a,["output"]);if(null!=d&&bY(b,["output"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(e));let f=bZ(a,["executableCode"]);null!=f&&bY(b,["executableCode"],function(a){let b={},c=bZ(a,["code"]);null!=c&&bY(b,["code"],c);let d=bZ(a,["language"]);if(null!=d&&bY(b,["language"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(f));let g=bZ(a,["fileData"]);null!=g&&bY(b,["fileData"],g);let h=bZ(a,["functionCall"]);null!=h&&bY(b,["functionCall"],h);let i=bZ(a,["functionResponse"]);null!=i&&bY(b,["functionResponse"],i);let j=bZ(a,["inlineData"]);null!=j&&bY(b,["inlineData"],j);let k=bZ(a,["text"]);null!=k&&bY(b,["text"],k);let l=bZ(a,["thought"]);null!=l&&bY(b,["thought"],l);let m=bZ(a,["thoughtSignature"]);null!=m&&bY(b,["thoughtSignature"],m);let n=bZ(a,["videoMetadata"]);if(null!=n&&bY(b,["videoMetadata"],n),void 0!==bZ(a,["partMetadata"]))throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(a))),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}class c4 extends bW{constructor(a){super(),this.apiClient=a,this.list=async(a={})=>new c0(bM.PAGED_ITEM_CACHED_CONTENTS,a=>this.listInternal(a),await this.listInternal(a),a)}async create(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g,j=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["model"],cv(f,e)),null!=(g=bZ(a,["config"]))&&function(a,b){let c=bZ(a,["ttl"]);void 0!==b&&null!=c&&bY(b,["ttl"],c);let d=bZ(a,["expireTime"]);void 0!==b&&null!=d&&bY(b,["expireTime"],d);let e=bZ(a,["displayName"]);void 0!==b&&null!=e&&bY(b,["displayName"],e);let f=bZ(a,["contents"]);if(void 0!==b&&null!=f){let a=cH(f);Array.isArray(a)&&(a=a.map(a=>c3(a))),bY(b,["contents"],a)}let g=bZ(a,["systemInstruction"]);void 0!==b&&null!=g&&bY(b,["systemInstruction"],c3(cF(g)));let h=bZ(a,["tools"]);if(void 0!==b&&null!=h){let a=h;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["retrieval"]);null!=c&&bY(b,["retrieval"],c);let d=bZ(a,["googleMaps"]);null!=d&&bY(b,["googleMaps"],d);let e=bZ(a,["mcpServers"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>(function(a){if(void 0!==bZ(a,["name"]))throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["streamableHttpTransport"]))throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}})(a))),bY(b,["mcpServers"],a)}let f=bZ(a,["codeExecution"]);null!=f&&bY(b,["codeExecution"],f);let g=bZ(a,["computerUse"]);null!=g&&bY(b,["computerUse"],function(a){let b={},c=bZ(a,["enablePromptInjectionDetection"]);null!=c&&bY(b,["enablePromptInjectionDetection"],c);let d=bZ(a,["environment"]);null!=d&&bY(b,["environment"],d);let e=bZ(a,["excludedPredefinedFunctions"]);if(null!=e&&bY(b,["excludedPredefinedFunctions"],e),void 0!==bZ(a,["disabledSafetyPolicies"]))throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(g));let h=bZ(a,["enterpriseWebSearch"]);null!=h&&bY(b,["enterpriseWebSearch"],h);let i=bZ(a,["exaAiSearch"]);null!=i&&bY(b,["exaAiSearch"],i);let j=bZ(a,["functionDeclarations"]);if(null!=j){let a=j;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let k=bZ(a,["googleSearch"]);null!=k&&bY(b,["googleSearch"],k);let l=bZ(a,["googleSearchRetrieval"]);null!=l&&bY(b,["googleSearchRetrieval"],l);let m=bZ(a,["parallelAiSearch"]);null!=m&&bY(b,["parallelAiSearch"],m);let n=bZ(a,["urlContext"]);if(null!=n&&bY(b,["urlContext"],n),void 0!==bZ(a,["fileSearch"]))throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(a))),bY(b,["tools"],a)}let i=bZ(a,["toolConfig"]);void 0!==b&&null!=i&&bY(b,["toolConfig"],function(a){let b={},c=bZ(a,["functionCallingConfig"]);null!=c&&bY(b,["functionCallingConfig"],c);let d=bZ(a,["retrievalConfig"]);if(null!=d&&bY(b,["retrievalConfig"],d),void 0!==bZ(a,["includeServerSideToolInvocations"]))throw Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(i));let j=bZ(a,["kmsKeyName"]);void 0!==b&&null!=j&&bY(b,["encryption_spec","kmsKeyName"],j)}(g,d),d);return h=bX("cachedContents",j._url),i=j._query,delete j._url,delete j._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(j),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}{let b,c,f,j=(g=this.apiClient,b={},null!=(c=bZ(a,["model"]))&&bY(b,["model"],cv(g,c)),null!=(f=bZ(a,["config"]))&&function(a,b){var c;let d,e,f,g,h=bZ(a,["ttl"]);void 0!==b&&null!=h&&bY(b,["ttl"],h);let i=bZ(a,["expireTime"]);void 0!==b&&null!=i&&bY(b,["expireTime"],i);let j=bZ(a,["displayName"]);void 0!==b&&null!=j&&bY(b,["displayName"],j);let k=bZ(a,["contents"]);if(void 0!==b&&null!=k){let a=cH(k);Array.isArray(a)&&(a=a.map(a=>c2(a))),bY(b,["contents"],a)}let l=bZ(a,["systemInstruction"]);void 0!==b&&null!=l&&bY(b,["systemInstruction"],c2(cF(l)));let m=bZ(a,["tools"]);if(void 0!==b&&null!=m){let a=m;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={};if(void 0!==bZ(a,["retrieval"]))throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["googleMaps"]);null!=c&&bY(b,["googleMaps"],function(a){let b={},c=bZ(a,["authConfig"]);null!=c&&bY(b,["authConfig"],function(a){let b={},c=bZ(a,["apiKey"]);if(null!=c&&bY(b,["apiKey"],c),void 0!==bZ(a,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["authType"]))throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oauthConfig"]))throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oidcConfig"]))throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["enableWidget"]);if(null!=d&&bY(b,["enableWidget"],d),void 0!==bZ(a,["groundingTypes"]))throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["mcpServers"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mcpServers"],a)}let e=bZ(a,["codeExecution"]);null!=e&&bY(b,["codeExecution"],e);let f=bZ(a,["computerUse"]);if(null!=f&&bY(b,["computerUse"],f),void 0!==bZ(a,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["exaAiSearch"]))throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=bZ(a,["functionDeclarations"]);if(null!=g){let a=g;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let h=bZ(a,["googleSearch"]);null!=h&&bY(b,["googleSearch"],function(a){let b={};if(void 0!==bZ(a,["blockingConfidence"]))throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["excludeDomains"]))throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["searchTypes"]);null!=c&&bY(b,["searchTypes"],c);let d=bZ(a,["timeRangeFilter"]);return null!=d&&bY(b,["timeRangeFilter"],d),b}(h));let i=bZ(a,["googleSearchRetrieval"]);if(null!=i&&bY(b,["googleSearchRetrieval"],i),void 0!==bZ(a,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["urlContext"]);null!=j&&bY(b,["urlContext"],j);let k=bZ(a,["fileSearch"]);return null!=k&&bY(b,["fileSearch"],k),b})(a))),bY(b,["tools"],a)}let n=bZ(a,["toolConfig"]);if(void 0!==b&&null!=n&&bY(b,["toolConfig"],(d={},null!=(e=bZ(c=n,["functionCallingConfig"]))&&bY(d,["functionCallingConfig"],function(a){let b={},c=bZ(a,["allowedFunctionNames"]);null!=c&&bY(b,["allowedFunctionNames"],c);let d=bZ(a,["mode"]);if(null!=d&&bY(b,["mode"],d),void 0!==bZ(a,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(e)),null!=(f=bZ(c,["retrievalConfig"]))&&bY(d,["retrievalConfig"],f),null!=(g=bZ(c,["includeServerSideToolInvocations"]))&&bY(d,["includeServerSideToolInvocations"],g),d)),void 0!==bZ(a,["kmsKeyName"]))throw Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(f,b),b);return h=bX("cachedContents",j._url),i=j._query,delete j._url,delete j._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(j),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>a)}}async get(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cN(f,e)),d);return h=bX("{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cN(g,c)),b);return h=bX("{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>a)}}async delete(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cN(f,e)),d);return h=bX("{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new cg;return Object.assign(e,d),e})}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cN(g,c)),b);return h=bX("{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new cg;return Object.assign(e,d),e})}}async update(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g,j,k,l=(f=this.apiClient,d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],cN(f,e)),null!=(g=bZ(a,["config"]))&&(j=bZ(g,["ttl"]),void 0!==d&&null!=j&&bY(d,["ttl"],j),k=bZ(g,["expireTime"]),void 0!==d&&null!=k&&bY(d,["expireTime"],k)),d);return h=bX("{name}",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(l),httpMethod:"PATCH",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}{let b,c,f,j,k,l=(g=this.apiClient,b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],cN(g,c)),null!=(f=bZ(a,["config"]))&&(j=bZ(f,["ttl"]),void 0!==b&&null!=j&&bY(b,["ttl"],j),k=bZ(f,["expireTime"]),void 0!==b&&null!=k&&bY(b,["expireTime"],k)),b);return h=bX("{name}",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(l),httpMethod:"PATCH",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>a)}}async listInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d,e,h,i,j=(d={},null!=(e=bZ(a,["config"]))&&(h=bZ(e,["pageSize"]),void 0!==d&&null!=h&&bY(d,["_query","pageSize"],h),i=bZ(e,["pageToken"]),void 0!==d&&null!=i&&bY(d,["_query","pageToken"],i)),d);return f=bX("cachedContents",j._url),g=j._query,delete j._url,delete j._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(j),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["cachedContents"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["cachedContents"],a)}return b}(a),c=new ch;return Object.assign(c,b),c})}{let b,c,h,i,j=(b={},null!=(c=bZ(a,["config"]))&&(h=bZ(c,["pageSize"]),void 0!==b&&null!=h&&bY(b,["_query","pageSize"],h),i=bZ(c,["pageToken"]),void 0!==b&&null!=i&&bY(b,["_query","pageToken"],i)),b);return f=bX("cachedContents",j._url),g=j._query,delete j._url,delete j._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(j),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["cachedContents"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["cachedContents"],a)}return b}(a),c=new ch;return Object.assign(c,b),c})}}}function c5(a,b){var c={};for(var d in a)Object.prototype.hasOwnProperty.call(a,d)&&0>b.indexOf(d)&&(c[d]=a[d]);if(null!=a&&"function"==typeof Object.getOwnPropertySymbols)for(var e=0,d=Object.getOwnPropertySymbols(a);e<d.length;e++)0>b.indexOf(d[e])&&Object.prototype.propertyIsEnumerable.call(a,d[e])&&(c[d[e]]=a[d[e]]);return c}function c6(a){return this instanceof c6?(this.v=a,this):new c6(a)}function c7(a,b,c){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var d,e=c.apply(a,b||[]),f=[];return d=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),g("next"),g("throw"),g("return",function(a){return function(b){return Promise.resolve(b).then(a,j)}}),d[Symbol.asyncIterator]=function(){return this},d;function g(a,b){e[a]&&(d[a]=function(b){return new Promise(function(c,d){f.push([a,b,c,d])>1||h(a,b)})},b&&(d[a]=b(d[a])))}function h(a,b){try{var c;(c=e[a](b)).value instanceof c6?Promise.resolve(c.value.v).then(i,j):k(f[0][2],c)}catch(a){k(f[0][3],a)}}function i(a){h("next",a)}function j(a){h("throw",a)}function k(a,b){a(b),f.shift(),f.length&&h(f[0][0],f[0][1])}}function c8(a){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var b,c=a[Symbol.asyncIterator];return c?c.call(a):(a=function(a){var b="function"==typeof Symbol&&Symbol.iterator,c=b&&a[b],d=0;if(c)return c.call(a);if(a&&"number"==typeof a.length)return{next:function(){return a&&d>=a.length&&(a=void 0),{value:a&&a[d++],done:!a}}};throw TypeError(b?"Object is not iterable.":"Symbol.iterator is not defined.")}(a),b={},d("next"),d("throw"),d("return"),b[Symbol.asyncIterator]=function(){return this},b);function d(c){b[c]=a[c]&&function(b){return new Promise(function(d,e){var f,g,h;f=d,g=e,h=(b=a[c](b)).done,Promise.resolve(b.value).then(function(a){f({value:a,done:h})},g)})}}}function c9(a){if(void 0===a.parts||0===a.parts.length)return!1;for(let b of a.parts)if(void 0===b||0===Object.keys(b).length)return!1;return!0}function da(a){if(void 0===a||0===a.length)return[];let b=[],c=a.length,d=0;for(;d<c;)if("user"===a[d].role)b.push(a[d]),d++;else{let e=[],f=!0;for(;d<c&&"model"===a[d].role;)e.push(a[d]),f&&!c9(a[d])&&(f=!1),d++;f?b.push(...e):b.pop()}return b}"function"==typeof SuppressedError&&SuppressedError;class db{constructor(a,b){this.modelsModule=a,this.apiClient=b}create(a){return new dc(this.apiClient,this.modelsModule,a.model,a.config,structuredClone(a.history))}}class dc{constructor(a,b,c,d={},e=[]){this.apiClient=a,this.modelsModule=b,this.model=c,this.config=d,this.history=e,this.sendPromise=Promise.resolve(),function(a){if(0!==a.length){for(let b of a)if("user"!==b.role&&"model"!==b.role)throw Error(`Role must be user or model, but got ${b.role}.`)}}(e)}async sendMessage(a){var b;await this.sendPromise;let c=cF(a.message),d=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(c),config:null!=(b=a.config)?b:this.config});return this.sendPromise=(async()=>{var a,b,e;let f=await d,g=null==(b=null==(a=f.candidates)?void 0:a[0])?void 0:b.content,h=f.automaticFunctionCallingHistory,i=this.getHistory(!0).length,j=[];null!=h&&(j=null!=(e=h.slice(i))?e:[]),this.recordHistory(c,g?[g]:[],j)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),d}async sendMessageStream(a){var b;await this.sendPromise;let c=cF(a.message),d=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(c),config:null!=(b=a.config)?b:this.config});this.sendPromise=d.then(()=>void 0).catch(()=>void 0);let e=await d;return this.processStreamResponse(e,c)}getHistory(a=!1){return structuredClone(a?da(this.history):this.history)}processStreamResponse(a,b){return c7(this,arguments,function*(){let c=[];try{for(var d,e,f,g,h,i,j,k=!0,l=c8(a);!(d=(j=yield c6(l.next())).done);k=!0){if(g=j.value,k=!1,function(a){var b;if(void 0==a.candidates||0===a.candidates.length)return!1;let c=null==(b=a.candidates[0])?void 0:b.content;return void 0!==c&&c9(c)}(g)){let a=null==(i=null==(h=g.candidates)?void 0:h[0])?void 0:i.content;void 0!==a&&c.push(a)}yield yield c6(g)}}catch(a){e={error:a}}finally{try{!k&&!d&&(f=l.return)&&(yield c6(f.call(l)))}finally{if(e)throw e.error}}this.recordHistory(b,c)})}recordHistory(a,b,c){let d=[];b.length>0&&b.every(a=>void 0!==a.role)?d=b:d.push({role:"model",parts:[]}),c&&c.length>0?this.history.push(...da(c)):this.history.push(a),this.history.push(...d)}}class dd extends Error{constructor(a){super(a.message),this.name="ApiError",this.status=a.status,Object.setPrototypeOf(this,dd.prototype)}}class de extends bW{constructor(a){super(),this.apiClient=a,this.list=async(a={})=>new c0(bM.PAGED_ITEM_FILES,a=>this.listInternal(a),await this.listInternal(a),a)}async upload(a){if(this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(a.file,a.config).then(a=>a)}async download(a){await this.apiClient.downloadFile(a)}async registerFiles(a){throw Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(a){return this.registerFilesInternal(a)}async listInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j=(f={},null!=(g=bZ(a,["config"]))&&(h=bZ(g,["pageSize"]),void 0!==f&&null!=h&&bY(f,["_query","pageSize"],h),i=bZ(g,["pageToken"]),void 0!==f&&null!=i&&bY(f,["_query","pageToken"],i)),f);return d=bX("files",j._url),e=j._query,delete j._url,delete j._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(j),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["files"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["files"],a)}return b}(a),c=new cm;return Object.assign(c,b),c})}}async createInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["file"]))&&bY(f,["file"],g),f);return d=bX("upload/v1beta/files",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new cn;return Object.assign(e,d),e})}}async get(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","file"],cR(g)),f);return d=bX("files/{file}",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}}async delete(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","file"],cR(g)),f);return d=bX("files/{file}",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new co;return Object.assign(e,d),e})}}async registerFilesInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["uris"]))&&bY(f,["uris"],g),f);return d=bX("files:register",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["files"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["files"],a)}return b}(a),c=new cp;return Object.assign(c,b),c})}}}function df(a){let b={},c=bZ(a,["data"]);if(null!=c&&bY(b,["data"],c),void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}function dg(a){let b={},c=bZ(a,["voiceConfig"]);null!=c&&bY(b,["voiceConfig"],dh(c));let d=bZ(a,["languageCode"]);null!=d&&bY(b,["languageCode"],d);let e=bZ(a,["multiSpeakerVoiceConfig"]);return null!=e&&bY(b,["multiSpeakerVoiceConfig"],function(a){let b={},c=bZ(a,["speakerVoiceConfigs"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e;return c={},null!=(d=bZ(b=a,["speaker"]))&&bY(c,["speaker"],d),null!=(e=bZ(b,["voiceConfig"]))&&bY(c,["voiceConfig"],dh(e)),c})),bY(b,["speakerVoiceConfigs"],a)}return b}(e)),b}function dh(a){let b={},c=bZ(a,["replicatedVoiceConfig"]);null!=c&&bY(b,["replicatedVoiceConfig"],function(a){let b={},c=bZ(a,["mimeType"]);null!=c&&bY(b,["mimeType"],c);let d=bZ(a,["voiceSampleAudio"]);if(null!=d&&bY(b,["voiceSampleAudio"],d),void 0!==bZ(a,["consentAudio"]))throw Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["voiceConsentSignature"]))throw Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(c));let d=bZ(a,["prebuiltVoiceConfig"]);return null!=d&&bY(b,["prebuiltVoiceConfig"],d),b}function di(a,b){let c={},d=bZ(a,["parts"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return c={},null!=(d=bZ(b=a,["mediaResolution"]))&&bY(c,["mediaResolution"],d),null!=(e=bZ(b,["toolCall"]))&&bY(c,["toolCall"],e),null!=(f=bZ(b,["toolResponse"]))&&bY(c,["toolResponse"],f),null!=(g=bZ(b,["audioTranscription"]))&&bY(c,["audioTranscription"],g),null!=(h=bZ(b,["codeExecutionResult"]))&&bY(c,["codeExecutionResult"],h),null!=(i=bZ(b,["executableCode"]))&&bY(c,["executableCode"],i),null!=(j=bZ(b,["fileData"]))&&bY(c,["fileData"],function(a){let b={};if(void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["fileUri"]);null!=c&&bY(b,["fileUri"],c);let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(j)),null!=(k=bZ(b,["functionCall"]))&&bY(c,["functionCall"],function(a){let b={},c=bZ(a,["args"]);null!=c&&bY(b,["args"],c);let d=bZ(a,["id"]);null!=d&&bY(b,["id"],d);let e=bZ(a,["name"]);if(null!=e&&bY(b,["name"],e),void 0!==bZ(a,["partialArgs"]))throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["willContinue"]))throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(k)),null!=(l=bZ(b,["functionResponse"]))&&bY(c,["functionResponse"],l),null!=(m=bZ(b,["inlineData"]))&&bY(c,["inlineData"],function(a){let b={},c=bZ(a,["data"]);if(null!=c&&bY(b,["data"],c),void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(m)),null!=(n=bZ(b,["text"]))&&bY(c,["text"],n),null!=(o=bZ(b,["thought"]))&&bY(c,["thought"],o),null!=(p=bZ(b,["thoughtSignature"]))&&bY(c,["thoughtSignature"],p),null!=(q=bZ(b,["videoMetadata"]))&&bY(c,["videoMetadata"],q),null!=(r=bZ(b,["partMetadata"]))&&bY(c,["partMetadata"],r),c})),bY(c,["parts"],a)}let e=bZ(a,["role"]);return null!=e&&bY(c,["role"],e),c}function dj(a,b){let c={},d=bZ(a,["parts"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["mediaResolution"]);if(null!=c&&bY(b,["mediaResolution"],c),void 0!==bZ(a,["toolCall"]))throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["toolResponse"]))throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let d=bZ(a,["audioTranscription"]);null!=d&&bY(b,["audioTranscription"],d);let e=bZ(a,["codeExecutionResult"]);null!=e&&bY(b,["codeExecutionResult"],function(a){let b={},c=bZ(a,["outcome"]);null!=c&&bY(b,["outcome"],c);let d=bZ(a,["output"]);if(null!=d&&bY(b,["output"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(e));let f=bZ(a,["executableCode"]);null!=f&&bY(b,["executableCode"],function(a){let b={},c=bZ(a,["code"]);null!=c&&bY(b,["code"],c);let d=bZ(a,["language"]);if(null!=d&&bY(b,["language"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(f));let g=bZ(a,["fileData"]);null!=g&&bY(b,["fileData"],g);let h=bZ(a,["functionCall"]);null!=h&&bY(b,["functionCall"],h);let i=bZ(a,["functionResponse"]);null!=i&&bY(b,["functionResponse"],i);let j=bZ(a,["inlineData"]);null!=j&&bY(b,["inlineData"],j);let k=bZ(a,["text"]);null!=k&&bY(b,["text"],k);let l=bZ(a,["thought"]);null!=l&&bY(b,["thought"],l);let m=bZ(a,["thoughtSignature"]);null!=m&&bY(b,["thoughtSignature"],m);let n=bZ(a,["videoMetadata"]);if(null!=n&&bY(b,["videoMetadata"],n),void 0!==bZ(a,["partMetadata"]))throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(a))),bY(c,["parts"],a)}let e=bZ(a,["role"]);return null!=e&&bY(c,["role"],e),c}function dk(a,b,c){let d={},e=bZ(b,["model"]);null!=e&&bY(d,["_url","model"],cu(a,e));let f=bZ(b,["contents"]);if(null!=f){let a=cH(f);Array.isArray(a)&&(a=a.map(a=>di(a))),bY(d,["contents"],a)}let g=bZ(b,["config"]);return null!=g&&bY(d,["generationConfig"],function(a,b,c){var d;let e,f,g,h,i={},j=bZ(b,["serviceTier"]);void 0!==c&&null!=j&&bY(c,["serviceTier"],j);let k=bZ(b,["systemInstruction"]);void 0!==c&&null!=k&&bY(c,["systemInstruction"],di(cF(k)));let l=bZ(b,["temperature"]);null!=l&&bY(i,["temperature"],l);let m=bZ(b,["topP"]);null!=m&&bY(i,["topP"],m);let n=bZ(b,["topK"]);null!=n&&bY(i,["topK"],n);let o=bZ(b,["candidateCount"]);null!=o&&bY(i,["candidateCount"],o);let p=bZ(b,["maxOutputTokens"]);null!=p&&bY(i,["maxOutputTokens"],p);let q=bZ(b,["stopSequences"]);null!=q&&bY(i,["stopSequences"],q);let r=bZ(b,["responseLogprobs"]);null!=r&&bY(i,["responseLogprobs"],r);let s=bZ(b,["logprobs"]);null!=s&&bY(i,["logprobs"],s);let t=bZ(b,["presencePenalty"]);null!=t&&bY(i,["presencePenalty"],t);let u=bZ(b,["frequencyPenalty"]);null!=u&&bY(i,["frequencyPenalty"],u);let v=bZ(b,["seed"]);null!=v&&bY(i,["seed"],v);let w=bZ(b,["responseMimeType"]);null!=w&&bY(i,["responseMimeType"],w);let x=bZ(b,["responseSchema"]);null!=x&&bY(i,["responseSchema"],cI(x));let y=bZ(b,["responseJsonSchema"]);if(null!=y&&bY(i,["responseJsonSchema"],y),void 0!==bZ(b,["routingConfig"]))throw Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(b,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let z=bZ(b,["safetySettings"]);if(void 0!==c&&null!=z){let a=z;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["category"]);if(null!=c&&bY(b,["category"],c),void 0!==bZ(a,["method"]))throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["threshold"]);return null!=d&&bY(b,["threshold"],d),b})(a))),bY(c,["safetySettings"],a)}let A=bZ(b,["tools"]);if(void 0!==c&&null!=A){let a=cM(A);Array.isArray(a)&&(a=a.map(a=>(function(a){let b={};if(void 0!==bZ(a,["retrieval"]))throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["googleMaps"]);null!=c&&bY(b,["googleMaps"],function(a){let b={},c=bZ(a,["authConfig"]);null!=c&&bY(b,["authConfig"],function(a){let b={},c=bZ(a,["apiKey"]);if(null!=c&&bY(b,["apiKey"],c),void 0!==bZ(a,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["authType"]))throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oauthConfig"]))throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oidcConfig"]))throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["enableWidget"]);if(null!=d&&bY(b,["enableWidget"],d),void 0!==bZ(a,["groundingTypes"]))throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["mcpServers"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mcpServers"],a)}let e=bZ(a,["codeExecution"]);null!=e&&bY(b,["codeExecution"],e);let f=bZ(a,["computerUse"]);if(null!=f&&bY(b,["computerUse"],f),void 0!==bZ(a,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["exaAiSearch"]))throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=bZ(a,["functionDeclarations"]);if(null!=g){let a=g;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let h=bZ(a,["googleSearch"]);null!=h&&bY(b,["googleSearch"],function(a){let b={};if(void 0!==bZ(a,["blockingConfidence"]))throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["excludeDomains"]))throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["searchTypes"]);null!=c&&bY(b,["searchTypes"],c);let d=bZ(a,["timeRangeFilter"]);return null!=d&&bY(b,["timeRangeFilter"],d),b}(h));let i=bZ(a,["googleSearchRetrieval"]);if(null!=i&&bY(b,["googleSearchRetrieval"],i),void 0!==bZ(a,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["urlContext"]);null!=j&&bY(b,["urlContext"],j);let k=bZ(a,["fileSearch"]);return null!=k&&bY(b,["fileSearch"],k),b})(cL(a)))),bY(c,["tools"],a)}let B=bZ(b,["toolConfig"]);if(void 0!==c&&null!=B&&bY(c,["toolConfig"],(e={},null!=(f=bZ(d=B,["functionCallingConfig"]))&&bY(e,["functionCallingConfig"],function(a){let b={},c=bZ(a,["allowedFunctionNames"]);null!=c&&bY(b,["allowedFunctionNames"],c);let d=bZ(a,["mode"]);if(null!=d&&bY(b,["mode"],d),void 0!==bZ(a,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(f)),null!=(g=bZ(d,["retrievalConfig"]))&&bY(e,["retrievalConfig"],g),null!=(h=bZ(d,["includeServerSideToolInvocations"]))&&bY(e,["includeServerSideToolInvocations"],h),e)),void 0!==bZ(b,["labels"]))throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let C=bZ(b,["cachedContent"]);void 0!==c&&null!=C&&bY(c,["cachedContent"],cN(a,C));let D=bZ(b,["responseModalities"]);null!=D&&bY(i,["responseModalities"],D);let E=bZ(b,["mediaResolution"]);null!=E&&bY(i,["mediaResolution"],E);let F=bZ(b,["speechConfig"]);if(null!=F&&bY(i,["speechConfig"],cJ(F)),void 0!==bZ(b,["audioTimestamp"]))throw Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let G=bZ(b,["thinkingConfig"]);null!=G&&bY(i,["thinkingConfig"],G);let H=bZ(b,["audioTranscriptionConfig"]);null!=H&&bY(i,["audioTranscriptionConfig"],H);let I=bZ(b,["imageConfig"]);null!=I&&bY(i,["imageConfig"],function(a){let b={},c=bZ(a,["aspectRatio"]);null!=c&&bY(b,["aspectRatio"],c);let d=bZ(a,["imageSize"]);if(null!=d&&bY(b,["imageSize"],d),void 0!==bZ(a,["personGeneration"]))throw Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["outputMimeType"]))throw Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["imageOutputOptions"]))throw Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["prominentPeople"]))throw Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(I));let J=bZ(b,["enableEnhancedCivicAnswers"]);if(null!=J&&bY(i,["enableEnhancedCivicAnswers"],J),void 0!==bZ(b,["modelArmorConfig"]))throw Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}(a,g,d)),d}function dl(a,b,c){let d={},e=bZ(b,["model"]);null!=e&&bY(d,["_url","model"],cu(a,e));let f=bZ(b,["contents"]);if(null!=f){let a=cH(f);Array.isArray(a)&&(a=a.map(a=>dj(a))),bY(d,["contents"],a)}let g=bZ(b,["config"]);return null!=g&&bY(d,["generationConfig"],function(a,b,c){var d;let e,f,g,h,i,j,k,l,m={},n=bZ(b,["serviceTier"]);void 0!==c&&null!=n&&bY(c,["serviceTier"],n);let o=bZ(b,["systemInstruction"]);void 0!==c&&null!=o&&bY(c,["systemInstruction"],dj(cF(o)));let p=bZ(b,["temperature"]);null!=p&&bY(m,["temperature"],p);let q=bZ(b,["topP"]);null!=q&&bY(m,["topP"],q);let r=bZ(b,["topK"]);null!=r&&bY(m,["topK"],r);let s=bZ(b,["candidateCount"]);null!=s&&bY(m,["candidateCount"],s);let t=bZ(b,["maxOutputTokens"]);null!=t&&bY(m,["maxOutputTokens"],t);let u=bZ(b,["stopSequences"]);null!=u&&bY(m,["stopSequences"],u);let v=bZ(b,["responseLogprobs"]);null!=v&&bY(m,["responseLogprobs"],v);let w=bZ(b,["logprobs"]);null!=w&&bY(m,["logprobs"],w);let x=bZ(b,["presencePenalty"]);null!=x&&bY(m,["presencePenalty"],x);let y=bZ(b,["frequencyPenalty"]);null!=y&&bY(m,["frequencyPenalty"],y);let z=bZ(b,["seed"]);null!=z&&bY(m,["seed"],z);let A=bZ(b,["responseMimeType"]);null!=A&&bY(m,["responseMimeType"],A);let B=bZ(b,["responseSchema"]);null!=B&&bY(m,["responseSchema"],cI(B));let C=bZ(b,["responseJsonSchema"]);null!=C&&bY(m,["responseJsonSchema"],C);let D=bZ(b,["routingConfig"]);null!=D&&bY(m,["routingConfig"],D);let E=bZ(b,["modelSelectionConfig"]);null!=E&&bY(m,["modelConfig"],E);let F=bZ(b,["safetySettings"]);if(void 0!==c&&null!=F){let a=F;Array.isArray(a)&&(a=a.map(a=>a)),bY(c,["safetySettings"],a)}let G=bZ(b,["tools"]);if(void 0!==c&&null!=G){let a=cM(G);Array.isArray(a)&&(a=a.map(a=>dy(cL(a)))),bY(c,["tools"],a)}let H=bZ(b,["toolConfig"]);void 0!==c&&null!=H&&bY(c,["toolConfig"],function(a){let b={},c=bZ(a,["functionCallingConfig"]);null!=c&&bY(b,["functionCallingConfig"],c);let d=bZ(a,["retrievalConfig"]);if(null!=d&&bY(b,["retrievalConfig"],d),void 0!==bZ(a,["includeServerSideToolInvocations"]))throw Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(H));let I=bZ(b,["labels"]);void 0!==c&&null!=I&&bY(c,["labels"],I);let J=bZ(b,["cachedContent"]);void 0!==c&&null!=J&&bY(c,["cachedContent"],cN(a,J));let K=bZ(b,["responseModalities"]);null!=K&&bY(m,["responseModalities"],K);let L=bZ(b,["mediaResolution"]);null!=L&&bY(m,["mediaResolution"],L);let M=bZ(b,["speechConfig"]);null!=M&&bY(m,["speechConfig"],dx(cJ(M)));let N=bZ(b,["audioTimestamp"]);null!=N&&bY(m,["audioTimestamp"],N);let O=bZ(b,["thinkingConfig"]);null!=O&&bY(m,["thinkingConfig"],O);let P=bZ(b,["audioTranscriptionConfig"]);null!=P&&bY(m,["audioTranscriptionConfig"],P);let Q=bZ(b,["imageConfig"]);if(null!=Q&&bY(m,["imageConfig"],(e={},null!=(f=bZ(d=Q,["aspectRatio"]))&&bY(e,["aspectRatio"],f),null!=(g=bZ(d,["imageSize"]))&&bY(e,["imageSize"],g),null!=(h=bZ(d,["personGeneration"]))&&bY(e,["personGeneration"],h),null!=(i=bZ(d,["outputMimeType"]))&&bY(e,["imageOutputOptions","mimeType"],i),null!=(j=bZ(d,["outputCompressionQuality"]))&&bY(e,["imageOutputOptions","compressionQuality"],j),null!=(k=bZ(d,["imageOutputOptions"]))&&bY(e,["imageOutputOptions"],k),null!=(l=bZ(d,["prominentPeople"]))&&bY(e,["prominentPeople"],l),e)),void 0!==bZ(b,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let R=bZ(b,["modelArmorConfig"]);return void 0!==c&&null!=R&&bY(c,["modelArmorConfig"],R),m}(a,g,d)),d}function dm(a,b){let c={},d=bZ(a,["sdkHttpResponse"]);null!=d&&bY(c,["sdkHttpResponse"],d);let e=bZ(a,["candidates"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["content"]);null!=c&&bY(b,["content"],c);let d=bZ(a,["citationMetadata"]);null!=d&&bY(b,["citationMetadata"],function(a){let b={},c=bZ(a,["citationSources"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["citations"],a)}return b}(d));let e=bZ(a,["tokenCount"]);null!=e&&bY(b,["tokenCount"],e);let f=bZ(a,["finishReason"]);null!=f&&bY(b,["finishReason"],f);let g=bZ(a,["groundingMetadata"]);null!=g&&bY(b,["groundingMetadata"],g);let h=bZ(a,["avgLogprobs"]);null!=h&&bY(b,["avgLogprobs"],h);let i=bZ(a,["index"]);null!=i&&bY(b,["index"],i);let j=bZ(a,["logprobsResult"]);null!=j&&bY(b,["logprobsResult"],j);let k=bZ(a,["safetyRatings"]);if(null!=k){let a=k;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["safetyRatings"],a)}let l=bZ(a,["urlContextMetadata"]);return null!=l&&bY(b,["urlContextMetadata"],l),b})(a))),bY(c,["candidates"],a)}let f=bZ(a,["modelVersion"]);null!=f&&bY(c,["modelVersion"],f);let g=bZ(a,["promptFeedback"]);null!=g&&bY(c,["promptFeedback"],g);let h=bZ(a,["responseId"]);null!=h&&bY(c,["responseId"],h);let i=bZ(a,["usageMetadata"]);null!=i&&bY(c,["usageMetadata"],i);let j=bZ(a,["modelStatus"]);return null!=j&&bY(c,["modelStatus"],j),c}function dn(a,b){let c={},d=bZ(a,["sdkHttpResponse"]);null!=d&&bY(c,["sdkHttpResponse"],d);let e=bZ(a,["candidates"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(c,["candidates"],a)}let f=bZ(a,["createTime"]);null!=f&&bY(c,["createTime"],f);let g=bZ(a,["modelVersion"]);null!=g&&bY(c,["modelVersion"],g);let h=bZ(a,["promptFeedback"]);null!=h&&bY(c,["promptFeedback"],h);let i=bZ(a,["responseId"]);null!=i&&bY(c,["responseId"],i);let j=bZ(a,["usageMetadata"]);return null!=j&&bY(c,["usageMetadata"],j),c}function dp(a,b){let c={},d=bZ(a,["_self"]);null!=d&&bY(c,["image"],dq(d));let e=bZ(a,["raiFilteredReason"]);null!=e&&bY(c,["raiFilteredReason"],e);let f=bZ(a,["_self"]);null!=f&&bY(c,["safetyAttributes"],dw(f));let g=bZ(a,["prompt"]);return null!=g&&bY(c,["enhancedPrompt"],g),c}function dq(a,b){let c={},d=bZ(a,["gcsUri"]);null!=d&&bY(c,["gcsUri"],d);let e=bZ(a,["bytesBase64Encoded"]);null!=e&&bY(c,["imageBytes"],b$(e));let f=bZ(a,["mimeType"]);return null!=f&&bY(c,["mimeType"],f),c}function dr(a,b){let c={};if(void 0!==bZ(a,["gcsUri"]))throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["imageBytes"]);null!=d&&bY(c,["bytesBase64Encoded"],b$(d));let e=bZ(a,["mimeType"]);return null!=e&&bY(c,["mimeType"],e),c}function ds(a,b){let c={},d=bZ(a,["gcsUri"]);null!=d&&bY(c,["gcsUri"],d);let e=bZ(a,["imageBytes"]);null!=e&&bY(c,["bytesBase64Encoded"],b$(e));let f=bZ(a,["mimeType"]);return null!=f&&bY(c,["mimeType"],f),c}function dt(a,b){var c;let d,e,f,g,h={},i=bZ(a,["name"]);null!=i&&bY(h,["name"],i);let j=bZ(a,["displayName"]);null!=j&&bY(h,["displayName"],j);let k=bZ(a,["description"]);null!=k&&bY(h,["description"],k);let l=bZ(a,["version"]);null!=l&&bY(h,["version"],l);let m=bZ(a,["_self"]);null!=m&&bY(h,["tunedModelInfo"],(d={},null!=(e=bZ(c=m,["baseModel"]))&&bY(d,["baseModel"],e),null!=(f=bZ(c,["createTime"]))&&bY(d,["createTime"],f),null!=(g=bZ(c,["updateTime"]))&&bY(d,["updateTime"],g),d));let n=bZ(a,["inputTokenLimit"]);null!=n&&bY(h,["inputTokenLimit"],n);let o=bZ(a,["outputTokenLimit"]);null!=o&&bY(h,["outputTokenLimit"],o);let p=bZ(a,["supportedGenerationMethods"]);null!=p&&bY(h,["supportedActions"],p);let q=bZ(a,["temperature"]);null!=q&&bY(h,["temperature"],q);let r=bZ(a,["maxTemperature"]);null!=r&&bY(h,["maxTemperature"],r);let s=bZ(a,["topP"]);null!=s&&bY(h,["topP"],s);let t=bZ(a,["topK"]);null!=t&&bY(h,["topK"],t);let u=bZ(a,["thinking"]);return null!=u&&bY(h,["thinking"],u),h}function du(a,b){var c;let d,e,f,g,h={},i=bZ(a,["name"]);null!=i&&bY(h,["name"],i);let j=bZ(a,["displayName"]);null!=j&&bY(h,["displayName"],j);let k=bZ(a,["description"]);null!=k&&bY(h,["description"],k);let l=bZ(a,["versionId"]);null!=l&&bY(h,["version"],l);let m=bZ(a,["deployedModels"]);if(null!=m){let a=m;Array.isArray(a)&&(a=a.map(a=>{let b,c,d;return b={},null!=(c=bZ(a,["endpoint"]))&&bY(b,["name"],c),null!=(d=bZ(a,["deployedModelId"]))&&bY(b,["deployedModelId"],d),b})),bY(h,["endpoints"],a)}let n=bZ(a,["labels"]);null!=n&&bY(h,["labels"],n);let o=bZ(a,["_self"]);null!=o&&bY(h,["tunedModelInfo"],(d={},null!=(e=bZ(c=o,["labels","google-vertex-llm-tuning-base-model-id"]))&&bY(d,["baseModel"],e),null!=(f=bZ(c,["createTime"]))&&bY(d,["createTime"],f),null!=(g=bZ(c,["updateTime"]))&&bY(d,["updateTime"],g),d));let p=bZ(a,["defaultCheckpointId"]);null!=p&&bY(h,["defaultCheckpointId"],p);let q=bZ(a,["checkpoints"]);if(null!=q){let a=q;Array.isArray(a)&&(a=a.map(a=>a)),bY(h,["checkpoints"],a)}return h}function dv(a,b){let c={},d=bZ(a,["safetyAttributes","categories"]);null!=d&&bY(c,["categories"],d);let e=bZ(a,["safetyAttributes","scores"]);null!=e&&bY(c,["scores"],e);let f=bZ(a,["contentType"]);return null!=f&&bY(c,["contentType"],f),c}function dw(a,b){let c={},d=bZ(a,["safetyAttributes","categories"]);null!=d&&bY(c,["categories"],d);let e=bZ(a,["safetyAttributes","scores"]);null!=e&&bY(c,["scores"],e);let f=bZ(a,["contentType"]);return null!=f&&bY(c,["contentType"],f),c}function dx(a,b){let c={},d=bZ(a,["voiceConfig"]);null!=d&&bY(c,["voiceConfig"],dB(d));let e=bZ(a,["languageCode"]);null!=e&&bY(c,["languageCode"],e);let f=bZ(a,["multiSpeakerVoiceConfig"]);return null!=f&&bY(c,["multiSpeakerVoiceConfig"],function(a){let b={},c=bZ(a,["speakerVoiceConfigs"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e;return c={},null!=(d=bZ(b=a,["speaker"]))&&bY(c,["speaker"],d),null!=(e=bZ(b,["voiceConfig"]))&&bY(c,["voiceConfig"],dB(e)),c})),bY(b,["speakerVoiceConfigs"],a)}return b}(f)),c}function dy(a,b){let c={},d=bZ(a,["retrieval"]);null!=d&&bY(c,["retrieval"],d);let e=bZ(a,["googleMaps"]);null!=e&&bY(c,["googleMaps"],e);let f=bZ(a,["mcpServers"]);if(null!=f){let a=f;Array.isArray(a)&&(a=a.map(a=>(function(a){if(void 0!==bZ(a,["name"]))throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["streamableHttpTransport"]))throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}})(a))),bY(c,["mcpServers"],a)}let g=bZ(a,["codeExecution"]);null!=g&&bY(c,["codeExecution"],g);let h=bZ(a,["computerUse"]);null!=h&&bY(c,["computerUse"],function(a){let b={},c=bZ(a,["enablePromptInjectionDetection"]);null!=c&&bY(b,["enablePromptInjectionDetection"],c);let d=bZ(a,["environment"]);null!=d&&bY(b,["environment"],d);let e=bZ(a,["excludedPredefinedFunctions"]);if(null!=e&&bY(b,["excludedPredefinedFunctions"],e),void 0!==bZ(a,["disabledSafetyPolicies"]))throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(h));let i=bZ(a,["enterpriseWebSearch"]);null!=i&&bY(c,["enterpriseWebSearch"],i);let j=bZ(a,["exaAiSearch"]);null!=j&&bY(c,["exaAiSearch"],j);let k=bZ(a,["functionDeclarations"]);if(null!=k){let a=k;Array.isArray(a)&&(a=a.map(a=>a)),bY(c,["functionDeclarations"],a)}let l=bZ(a,["googleSearch"]);null!=l&&bY(c,["googleSearch"],l);let m=bZ(a,["googleSearchRetrieval"]);null!=m&&bY(c,["googleSearchRetrieval"],m);let n=bZ(a,["parallelAiSearch"]);null!=n&&bY(c,["parallelAiSearch"],n);let o=bZ(a,["urlContext"]);if(null!=o&&bY(c,["urlContext"],o),void 0!==bZ(a,["fileSearch"]))throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return c}function dz(a,b){let c={},d=bZ(a,["uri"]);null!=d&&bY(c,["uri"],d);let e=bZ(a,["videoBytes"]);null!=e&&bY(c,["encodedVideo"],b$(e));let f=bZ(a,["mimeType"]);return null!=f&&bY(c,["encoding"],f),c}function dA(a,b){let c={},d=bZ(a,["uri"]);null!=d&&bY(c,["gcsUri"],d);let e=bZ(a,["videoBytes"]);null!=e&&bY(c,["bytesBase64Encoded"],b$(e));let f=bZ(a,["mimeType"]);return null!=f&&bY(c,["mimeType"],f),c}function dB(a,b){let c={},d=bZ(a,["replicatedVoiceConfig"]);null!=d&&bY(c,["replicatedVoiceConfig"],function(a){let b={},c=bZ(a,["mimeType"]);null!=c&&bY(b,["mimeType"],c);let d=bZ(a,["voiceSampleAudio"]);if(null!=d&&bY(b,["voiceSampleAudio"],d),void 0!==bZ(a,["consentAudio"]))throw Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["voiceConsentSignature"]))throw Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(d));let e=bZ(a,["prebuiltVoiceConfig"]);return null!=e&&bY(c,["prebuiltVoiceConfig"],e),c}function dC(a,b){let c=bZ(a,["mimeType"]);void 0!==b&&null!=c&&bY(b,["mimeType"],c);let d=bZ(a,["displayName"]);void 0!==b&&null!=d&&bY(b,["displayName"],d);let e=bZ(a,["customMetadata"]);if(void 0!==b&&null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["customMetadata"],a)}let f=bZ(a,["chunkingConfig"]);return void 0!==b&&null!=f&&bY(b,["chunkingConfig"],f),{}}let dD="x-goog-api-client",dE=new Set(["us","eu"]),dF=[408,429,500,502,503,504];class dG{constructor(a){var b,c,d;this.clientOptions=Object.assign({},a),this.customBaseUrl=null==(b=a.httpOptions)?void 0:b.baseUrl;const e={};if(this.clientOptions.vertexai){if(this.clientOptions.location||this.clientOptions.apiKey||this.customBaseUrl||(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");const b=a.project&&a.location||!!a.apiKey;this.customBaseUrl&&!b?(e.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||"global"===this.clientOptions.location?e.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&dE.has(this.clientOptions.location)?e.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(e.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),e.apiVersion=null!=(c=this.clientOptions.apiVersion)?c:"v1beta1"}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),e.apiVersion=null!=(d=this.clientOptions.apiVersion)?d:"v1beta",e.baseUrl="https://generativelanguage.googleapis.com/";e.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=e,a.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(e,a.httpOptions))}isVertexAI(){var a;return null!=(a=this.clientOptions.vertexai)&&a}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let a=new Headers;return await this.clientOptions.auth.addAuthHeaders(a),a}getApiVersion(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.apiVersion)return this.clientOptions.httpOptions.apiVersion;throw Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.baseUrl)return this.clientOptions.httpOptions.baseUrl;throw Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.headers)return this.clientOptions.httpOptions.headers;throw Error("Headers are not set.")}getRequestUrlInternal(a){if(!a||void 0===a.baseUrl||void 0===a.apiVersion)throw Error("HTTP options are not correctly set.");let b=[a.baseUrl.endsWith("/")?a.baseUrl.slice(0,-1):a.baseUrl];return a.apiVersion&&""!==a.apiVersion&&b.push(a.apiVersion),b.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let a=new URL(this.getBaseUrl());return a.protocol="http:"==a.protocol?"ws":"wss",a.toString()}setBaseUrl(a){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=a;else throw Error("HTTP options are not correctly set.")}constructUrl(a,b,c){let d=[this.getRequestUrlInternal(b)];return c&&d.push(this.getBaseResourcePath()),""!==a&&d.push(a),new URL(`${d.join("/")}`)}shouldPrependVertexProjectPath(a,b){return!(b.baseUrl&&b.baseUrlResourceScope===bl.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||a.path.startsWith("projects/")||"GET"===a.httpMethod&&a.path.startsWith("publishers/google/models"))}async request(a){let b=this.clientOptions.httpOptions;a.httpOptions&&(b=this.patchHttpOptions(this.clientOptions.httpOptions,a.httpOptions));let c=this.shouldPrependVertexProjectPath(a,b),d=this.constructUrl(a.path,b,c);if(a.queryParams)for(let[b,c]of Object.entries(a.queryParams))d.searchParams.append(b,String(c));let e={};if("GET"===a.httpMethod){if(a.body&&"{}"!==a.body)throw Error("Request body should be empty for GET request, but got non empty request body")}else e.body=a.body;return e=await this.includeExtraHttpOptionsToRequestInit(e,b,d.toString(),a.abortSignal),this.unaryApiCall(d,e,a.httpMethod,b.retryOptions)}patchHttpOptions(a,b){let c=JSON.parse(JSON.stringify(a));for(let[a,d]of Object.entries(b))"object"==typeof d?c[a]=Object.assign(Object.assign({},c[a]),d):void 0!==d&&(c[a]=d);return c}async requestStream(a){let b=this.clientOptions.httpOptions;a.httpOptions&&(b=this.patchHttpOptions(this.clientOptions.httpOptions,a.httpOptions));let c=this.shouldPrependVertexProjectPath(a,b),d=this.constructUrl(a.path,b,c);d.searchParams.has("alt")&&"sse"===d.searchParams.get("alt")||d.searchParams.set("alt","sse");let e={};return e.body=a.body,e=await this.includeExtraHttpOptionsToRequestInit(e,b,d.toString(),a.abortSignal),this.streamApiCall(d,e,a.httpMethod,b.retryOptions)}async includeExtraHttpOptionsToRequestInit(a,b,c,d){if(b&&b.timeout||d){let c=new AbortController,e=c.signal;if(b.timeout&&(null==b?void 0:b.timeout)>0){let a=Symbol.for("undici.globalDispatcher.1"),d=globalThis[a];if(d)for(let a of Object.getOwnPropertySymbols(d)){let c=a.description;if((null==c?void 0:c.includes("headers timeout"))||(null==c?void 0:c.includes("body timeout"))){let c=d[a];"number"==typeof c&&(d[a]=Math.max(c,b.timeout))}}let e=setTimeout(()=>c.abort(),b.timeout);e&&"function"==typeof e.unref&&e.unref()}d&&d.addEventListener("abort",()=>{c.abort()}),a.signal=e}return b&&null!==b.extraBody&&function(a,b){if(!b||0===Object.keys(b).length)return;if(a.body instanceof Blob)return console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");let c={};if("string"==typeof a.body&&a.body.length>0)try{let b=JSON.parse(a.body);if("object"!=typeof b||null===b||Array.isArray(b))return void console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");c=b}catch(a){console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}a.body=JSON.stringify(function a(b,c){let d=Object.assign({},b);for(let b in c)if(Object.prototype.hasOwnProperty.call(c,b)){let e=c[b],f=d[b];e&&"object"==typeof e&&!Array.isArray(e)&&f&&"object"==typeof f&&!Array.isArray(f)?d[b]=a(f,e):(f&&e&&typeof f!=typeof e&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${b}". Original type: ${typeof f}, New type: ${typeof e}. Overwriting.`),d[b]=e)}return d}(c,b))}(a,b.extraBody),a.headers=await this.getHeadersInternal(b,c),a}async unaryApiCall(a,b,c,d){return this.apiCall(a.toString(),Object.assign(Object.assign({},b),{method:c}),d).then(async a=>(await dH(a),new b0(a))).catch(a=>{if(a instanceof Error)throw a;throw Error(`exception ${a} sending request`,{cause:a})})}async streamApiCall(a,b,c,d){return this.apiCall(a.toString(),Object.assign(Object.assign({},b),{method:c}),d).then(async a=>(await dH(a),this.processStreamResponse(a))).catch(a=>{if(a instanceof Error)throw a;throw Error(`exception ${a} sending request`,{cause:a})})}processStreamResponse(a){return c7(this,arguments,function*(){var b;let c=null==(b=null==a?void 0:a.body)?void 0:b.getReader(),d=new TextDecoder("utf-8");if(!c)throw Error("Response body is empty");try{let b="",e="data:",f=["\n\n","\r\r","\r\n\r\n"];for(;;){let{done:g,value:h}=yield c6(c.read());if(g){if(b.trim().length>0)throw Error("Incomplete JSON segment at the end");break}let i=d.decode(h,{stream:!0});try{let a=JSON.parse(i);if("error"in a){let b=JSON.parse(JSON.stringify(a.error)),c=b.status,d=b.code,e=`got status: ${c}. ${JSON.stringify(a)}`;if(d>=400&&d<600)throw new dd({message:e,status:d})}}catch(a){if("ApiError"===a.name)throw a}b+=i;let j=-1,k=0;for(;;){for(let a of(j=-1,k=0,f)){let c=b.indexOf(a);-1!==c&&(-1===j||c<j)&&(j=c,k=a.length)}if(-1===j)break;let c=b.substring(0,j);b=b.substring(j+k);let d=c.trim();if(d.startsWith(e)){let b=d.substring(e.length).trim();try{let c=new Response(b,{headers:null==a?void 0:a.headers,status:null==a?void 0:a.status,statusText:null==a?void 0:a.statusText});yield yield c6(new b0(c))}catch(a){throw Error(`exception parsing stream chunk ${b}. ${a}`)}}}}}finally{c.releaseLock()}})}async apiCall(a,b,c){var d,e,f,g,h,i;if(!c)return fetch(a,b);let j=null!=(d=c.httpStatusCodes)?d:dF,k=async()=>{let c=await fetch(a,b);return c.ok||!j.includes(c.status)||await dH(c),c},l=Math.max(1,null!=(e=c.attempts)?e:5),m=Math.round((null!=(f=c.initialDelay)?f:1)*1e3),n=Math.max(m,Math.round((null!=(g=c.maxDelay)?g:60)*1e3));return bO(k,{retries:l-1,factor:null!=(h=c.expBase)?h:2,minTimeout:m,maxTimeout:n,randomize:(null!=(i=c.jitter)?i:1)>0})}getDefaultHeaders(){let a={},b="google-genai-sdk/2.15.0 "+this.clientOptions.userAgentExtra;return a["User-Agent"]=b,a[dD]=b,a["Content-Type"]="application/json",a}async getHeadersInternal(a,b){let c=new Headers;if(a&&a.headers)for(let[b,d]of Object.entries(a.headers))c.append(b,d);return(null==a?void 0:a.timeout)&&a.timeout>0&&c.append("X-Server-Timeout",String(Math.ceil(a.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(c,b),c}getFileName(a){var b;let c="";return"string"==typeof a&&(c=null!=(b=(c=a.replace(/[/\\]+$/,"")).split(/[/\\]/).pop())?b:""),c}async uploadFile(a,b){var c;let d={};null!=b&&(d.mimeType=b.mimeType,d.name=b.name,d.displayName=b.displayName),d.name&&!d.name.startsWith("files/")&&(d.name=`files/${d.name}`);let e=this.clientOptions.uploader,f=await e.stat(a);d.sizeBytes=String(f.size);let g=null!=(c=null==b?void 0:b.mimeType)?c:f.type;if(void 0===g||""===g)throw Error("Can not determine mimeType. Please provide mimeType in the config.");d.mimeType=g;let h={file:d},i=this.getFileName(a),j=bX("upload/v1beta/files",h._url),k=await this.fetchUploadUrl(j,d.sizeBytes,d.mimeType,i,h,null==b?void 0:b.httpOptions);return e.upload(a,k,this)}async uploadFileToFileSearchStore(a,b,c){var d;let e=this.clientOptions.uploader,f=await e.stat(b),g=String(f.size),h=null!=(d=null==c?void 0:c.mimeType)?d:f.type;if(void 0===h||""===h)throw Error("Can not determine mimeType. Please provide mimeType in the config.");let i=`upload/v1beta/${a}:uploadToFileSearchStore`,j=this.getFileName(b),k={};null!=c&&dC(c,k);let l=await this.fetchUploadUrl(i,g,h,j,k,null==c?void 0:c.httpOptions);return e.uploadToFileSearchStore(b,l,this)}async downloadFile(a){let b=this.clientOptions.downloader;await b.download(a,this)}async fetchUploadUrl(a,b,c,d,e,f){var g;let h={};h=f||{apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${b}`,"X-Goog-Upload-Header-Content-Type":`${c}`},d?{"X-Goog-Upload-File-Name":d}:{})};let i=await this.request({path:a,body:JSON.stringify(e),httpMethod:"POST",httpOptions:h});if(!i||!(null==i?void 0:i.headers))throw Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let j=null==(g=null==i?void 0:i.headers)?void 0:g["x-goog-upload-url"];if(void 0===j)throw Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return j}}async function dH(a){var b;if(void 0===a)throw Error("response is undefined");if(!a.ok){let c=a.status,d=JSON.stringify((null==(b=a.headers.get("content-type"))?void 0:b.includes("application/json"))?await a.json():{error:{message:await a.text(),code:a.status,status:a.statusText}});if(c>=400&&c<600)throw new dd({message:d,status:c});throw Error(d)}}function dI(a){for(let c of a){var b;if(null!==(b=c)&&"object"==typeof b&&b instanceof dK||"object"==typeof c&&"inputSchema"in c)return!0}return!1}function dJ(a){var b;let c=null!=(b=a[dD])?b:"";a[dD]=(c+" mcp_used/unknown").trimStart()}class dK{constructor(a=[],b){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=a,this.config=b}static create(a,b){return new dK(a,b)}async initialize(){var a,b,c,d;if(this.mcpTools.length>0)return;let e={},f=[];for(let j of this.mcpClients)try{for(var g,h=!0,i=(b=void 0,c8(function(a){return c7(this,arguments,function*(a,b=100){let c,d=0;for(;d<b;){let b=yield c6(a.listTools({cursor:c}));for(let a of b.tools)yield yield c6(a),d++;if(!b.nextCursor)break;c=b.nextCursor}})}(j)));!(a=(g=await i.next()).done);h=!0){d=g.value,h=!1,f.push(d);let a=d.name;if(e[a])throw Error(`Duplicate function name ${a} found in MCP tools. Please ensure function names are unique.`);e[a]=j}}catch(a){b={error:a}}finally{try{!h&&!a&&(c=i.return)&&await c.call(i)}finally{if(b)throw b.error}}this.mcpTools=f,this.functionNameToMcpClient=e}async tool(){return await this.initialize(),function(a,b={}){let c=[],d=new Set;for(let e of a){let a=e.name;if(d.has(a))throw Error(`Duplicate function name ${a} found in MCP tools. Please ensure function names are unique.`);d.add(a);let f=function(a,b={}){let c={name:a.name,description:a.description,parametersJsonSchema:a.inputSchema};return a.outputSchema&&(c.responseJsonSchema=a.outputSchema),b.behavior&&(c.behavior=b.behavior),{functionDeclarations:[c]}}(e,b);f.functionDeclarations&&c.push(...f.functionDeclarations)}return{functionDeclarations:c}}(this.mcpTools,this.config)}async callTool(a){await this.initialize();let b=[];for(let c of a)if(c.name in this.functionNameToMcpClient){let a,d=this.functionNameToMcpClient[c.name];this.config.timeout&&(a={timeout:this.config.timeout});let e=await d.callTool({name:c.name,arguments:c.args},void 0,a);b.push({functionResponse:{name:c.name,response:e.isError?{error:e}:e}})}return b}}async function dL(a,b,c){let d=new cs;Object.assign(d,c.data instanceof Blob?JSON.parse(await c.data.text()):JSON.parse(c.data)),b(d)}class dM{constructor(a,b,c){this.apiClient=a,this.auth=b,this.webSocketFactory=c}async connect(a){var b,c;let d;if(this.apiClient.isVertexAI())throw Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let e=this.apiClient.getWebsocketBaseUrl(),f=this.apiClient.getApiVersion(),g=function(a){let b=new Headers;for(let[c,d]of Object.entries(a))b.append(c,d);return b}(this.apiClient.getDefaultHeaders()),h=this.apiClient.getApiKey(),i=`${e}/ws/google.ai.generativelanguage.${f}.GenerativeService.BidiGenerateMusic?key=${h}`,j=()=>{},k=new Promise(a=>{j=a}),l=a.callbacks,m=this.apiClient,n={onopen:function(){j({})},onmessage:a=>{dL(m,l.onmessage,a)},onerror:null!=(b=null==l?void 0:l.onerror)?b:function(a){},onclose:null!=(c=null==l?void 0:l.onclose)?c:function(a){}},o=this.webSocketFactory.create(i,(d={},g.forEach((a,b)=>{d[b]=a}),d),n);o.connect(),await k;let p=cu(this.apiClient,a.model);return o.send(JSON.stringify({setup:{model:p}})),new dN(o,this.apiClient)}}class dN{constructor(a,b){this.conn=a,this.apiClient=b}async setWeightedPrompts(a){if(!a.weightedPrompts||0===Object.keys(a.weightedPrompts).length)throw Error("Weighted prompts must be set and contain at least one entry.");let b=function(a){let b={},c=bZ(a,["weightedPrompts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["weightedPrompts"],a)}return b}(a);this.conn.send(JSON.stringify({clientContent:b}))}async setMusicGenerationConfig(a){let b,c;a.musicGenerationConfig||(a.musicGenerationConfig={});let d=(b={},null!=(c=bZ(a,["musicGenerationConfig"]))&&bY(b,["musicGenerationConfig"],c),b);this.conn.send(JSON.stringify(d))}sendPlaybackControl(a){this.conn.send(JSON.stringify({playbackControl:a}))}play(){this.sendPlaybackControl(bL.PLAY)}pause(){this.sendPlaybackControl(bL.PAUSE)}stop(){this.sendPlaybackControl(bL.STOP)}resetContext(){this.sendPlaybackControl(bL.RESET_CONTEXT)}close(){this.conn.close()}}async function dO(a,b,c){let d=new cr,e=JSON.parse(c.data instanceof Blob?await c.data.text():c.data instanceof ArrayBuffer?new TextDecoder().decode(c.data):c.data);if(a.isVertexAI()){var f;let a,b,c,g,h,i,j,k,l,m,n,o,p;Object.assign(d,(a={},null!=(b=bZ(e,["setupComplete"]))&&bY(a,["setupComplete"],b),null!=(c=bZ(e,["serverContent"]))&&bY(a,["serverContent"],c),null!=(g=bZ(e,["toolCall"]))&&bY(a,["toolCall"],g),null!=(h=bZ(e,["toolCallCancellation"]))&&bY(a,["toolCallCancellation"],h),null!=(i=bZ(e,["usageMetadata"]))&&bY(a,["usageMetadata"],function(a){let b={},c=bZ(a,["candidatesTokenCount"]);null!=c&&bY(b,["responseTokenCount"],c);let d=bZ(a,["candidatesTokensDetails"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["responseTokensDetails"],a)}let e=bZ(a,["cacheTokensDetails"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["cacheTokensDetails"],a)}let f=bZ(a,["cachedContentTokenCount"]);null!=f&&bY(b,["cachedContentTokenCount"],f);let g=bZ(a,["promptTokenCount"]);null!=g&&bY(b,["promptTokenCount"],g);let h=bZ(a,["promptTokensDetails"]);if(null!=h){let a=h;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["promptTokensDetails"],a)}let i=bZ(a,["thoughtsTokenCount"]);null!=i&&bY(b,["thoughtsTokenCount"],i);let j=bZ(a,["toolUsePromptTokenCount"]);null!=j&&bY(b,["toolUsePromptTokenCount"],j);let k=bZ(a,["toolUsePromptTokensDetails"]);if(null!=k){let a=k;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["toolUsePromptTokensDetails"],a)}let l=bZ(a,["totalTokenCount"]);null!=l&&bY(b,["totalTokenCount"],l);let m=bZ(a,["trafficType"]);return null!=m&&bY(b,["trafficType"],m),b}(i)),null!=(j=bZ(e,["goAway"]))&&bY(a,["goAway"],j),null!=(k=bZ(e,["sessionResumptionUpdate"]))&&bY(a,["sessionResumptionUpdate"],k),null!=(l=bZ(e,["voiceActivityDetectionSignal"]))&&bY(a,["voiceActivityDetectionSignal"],l),null!=(m=bZ(e,["voiceActivity"]))&&bY(a,["voiceActivity"],(n={},null!=(o=bZ(f=m,["type"]))&&bY(n,["voiceActivityType"],o),null!=(p=bZ(f,["audioOffset"]))&&bY(n,["audioOffset"],p),n)),a))}else Object.assign(d,e);b(d)}class dP{constructor(a,b,c){this.apiClient=a,this.auth=b,this.webSocketFactory=c,this.music=new dM(this.apiClient,this.auth,this.webSocketFactory)}async connect(a){var b,c,d,e,f,g,h,i;let j,k;if(a.config&&a.config.httpOptions)throw Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let l=this.apiClient.getWebsocketBaseUrl(),m=this.apiClient.getApiVersion(),n=this.apiClient.getHeaders();a.config&&a.config.tools&&dI(a.config.tools)&&dJ(n);let o=function(a){let b=new Headers;for(let[c,d]of Object.entries(a))b.append(c,d);return b}(n);if(this.apiClient.isVertexAI()){let a=this.apiClient.getProject(),b=this.apiClient.getLocation(),c=this.apiClient.getApiKey();this.apiClient.getCustomBaseUrl()&&!(a&&b||c)?j=l:(j=`${l}/ws/google.cloud.aiplatform.${m}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(o,j))}else{let a=this.apiClient.getApiKey(),b="BidiGenerateContent",c="key";(null==a?void 0:a.startsWith("auth_tokens/"))&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),"v1alpha"!==m&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),b="BidiGenerateContentConstrained",c="access_token"),j=`${l}/ws/google.ai.generativelanguage.${m}.GenerativeService.${b}?${c}=${a}`}let p=()=>{},q=new Promise(a=>{p=a}),r=a.callbacks,s=this.apiClient,t=!1,u=[],v=()=>{},w=new Promise(a=>{v=a}),x={onopen:function(){var a;null==(a=null==r?void 0:r.onopen)||a.call(r),p({})},onmessage:a=>{dO(s,a=>{a.setupComplete&&!E.setupComplete&&(E.setupComplete=a.setupComplete,v({})),t?r.onmessage(a):u.push(a)},a)},onerror:null!=(b=null==r?void 0:r.onerror)?b:function(a){},onclose:null!=(c=null==r?void 0:r.onclose)?c:function(a){}},y=this.webSocketFactory.create(j,(k={},o.forEach((a,b)=>{k[b]=a}),k),x);y.connect(),await q;let z=cu(this.apiClient,a.model);if(this.apiClient.isVertexAI()&&z.startsWith("publishers/")){let a=this.apiClient.getProject(),b=this.apiClient.getLocation();a&&b&&(z=`projects/${a}/locations/${b}/`+z)}let A={};this.apiClient.isVertexAI()&&(null==(d=a.config)?void 0:d.responseModalities)===void 0&&(void 0===a.config?a.config={responseModalities:[a1.AUDIO]}:a.config.responseModalities=[a1.AUDIO]),(null==(e=a.config)?void 0:e.generationConfig)&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let B=null!=(g=null==(f=a.config)?void 0:f.tools)?g:[],C=[];for(let a of B)this.isCallableTool(a)?C.push(await a.tool()):C.push(a);C.length>0&&(a.config.tools=C);let D={model:z,config:a.config,callbacks:a.callbacks};if(this.apiClient.isVertexAI()){let a,b,c;h=this.apiClient,a={},null!=(b=bZ(D,["model"]))&&bY(a,["setup","model"],cu(h,b)),null!=(c=bZ(D,["config"]))&&bY(a,["config"],function(a,b){let c=bZ(a,["generationConfig"]);void 0!==b&&null!=c&&bY(b,["setup","generationConfig"],function(a){let b={},c=bZ(a,["modelSelectionConfig"]);null!=c&&bY(b,["modelConfig"],c);let d=bZ(a,["responseJsonSchema"]);null!=d&&bY(b,["responseJsonSchema"],d);let e=bZ(a,["audioTranscriptionConfig"]);null!=e&&bY(b,["audioTranscriptionConfig"],e);let f=bZ(a,["audioTimestamp"]);null!=f&&bY(b,["audioTimestamp"],f);let g=bZ(a,["candidateCount"]);null!=g&&bY(b,["candidateCount"],g);let h=bZ(a,["enableAffectiveDialog"]);null!=h&&bY(b,["enableAffectiveDialog"],h);let i=bZ(a,["frequencyPenalty"]);null!=i&&bY(b,["frequencyPenalty"],i);let j=bZ(a,["logprobs"]);null!=j&&bY(b,["logprobs"],j);let k=bZ(a,["maxOutputTokens"]);null!=k&&bY(b,["maxOutputTokens"],k);let l=bZ(a,["mediaResolution"]);null!=l&&bY(b,["mediaResolution"],l);let m=bZ(a,["presencePenalty"]);null!=m&&bY(b,["presencePenalty"],m);let n=bZ(a,["responseFormat"]);if(null!=n){let a=n;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["responseFormat"],a)}let o=bZ(a,["responseLogprobs"]);null!=o&&bY(b,["responseLogprobs"],o);let p=bZ(a,["responseMimeType"]);null!=p&&bY(b,["responseMimeType"],p);let q=bZ(a,["responseModalities"]);null!=q&&bY(b,["responseModalities"],q);let r=bZ(a,["responseSchema"]);null!=r&&bY(b,["responseSchema"],r);let s=bZ(a,["routingConfig"]);null!=s&&bY(b,["routingConfig"],s);let t=bZ(a,["seed"]);null!=t&&bY(b,["seed"],t);let u=bZ(a,["speechConfig"]);null!=u&&bY(b,["speechConfig"],dg(u));let v=bZ(a,["stopSequences"]);null!=v&&bY(b,["stopSequences"],v);let w=bZ(a,["temperature"]);null!=w&&bY(b,["temperature"],w);let x=bZ(a,["thinkingConfig"]);null!=x&&bY(b,["thinkingConfig"],x);let y=bZ(a,["topK"]);null!=y&&bY(b,["topK"],y);let z=bZ(a,["topP"]);if(null!=z&&bY(b,["topP"],z),void 0!==bZ(a,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["translationConfig"]))throw Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(c));let d=bZ(a,["responseModalities"]);void 0!==b&&null!=d&&bY(b,["setup","generationConfig","responseModalities"],d);let e=bZ(a,["temperature"]);void 0!==b&&null!=e&&bY(b,["setup","generationConfig","temperature"],e);let f=bZ(a,["topP"]);void 0!==b&&null!=f&&bY(b,["setup","generationConfig","topP"],f);let g=bZ(a,["topK"]);void 0!==b&&null!=g&&bY(b,["setup","generationConfig","topK"],g);let h=bZ(a,["maxOutputTokens"]);void 0!==b&&null!=h&&bY(b,["setup","generationConfig","maxOutputTokens"],h);let i=bZ(a,["mediaResolution"]);void 0!==b&&null!=i&&bY(b,["setup","generationConfig","mediaResolution"],i);let j=bZ(a,["seed"]);void 0!==b&&null!=j&&bY(b,["setup","generationConfig","seed"],j);let k=bZ(a,["speechConfig"]);void 0!==b&&null!=k&&bY(b,["setup","generationConfig","speechConfig"],dg(cK(k)));let l=bZ(a,["thinkingConfig"]);void 0!==b&&null!=l&&bY(b,["setup","generationConfig","thinkingConfig"],l);let m=bZ(a,["enableAffectiveDialog"]);void 0!==b&&null!=m&&bY(b,["setup","generationConfig","enableAffectiveDialog"],m);let n=bZ(a,["systemInstruction"]);void 0!==b&&null!=n&&bY(b,["setup","systemInstruction"],function(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["mediaResolution"]);if(null!=c&&bY(b,["mediaResolution"],c),void 0!==bZ(a,["toolCall"]))throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["toolResponse"]))throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let d=bZ(a,["audioTranscription"]);null!=d&&bY(b,["audioTranscription"],d);let e=bZ(a,["codeExecutionResult"]);null!=e&&bY(b,["codeExecutionResult"],function(a){let b={},c=bZ(a,["outcome"]);null!=c&&bY(b,["outcome"],c);let d=bZ(a,["output"]);if(null!=d&&bY(b,["output"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(e));let f=bZ(a,["executableCode"]);null!=f&&bY(b,["executableCode"],function(a){let b={},c=bZ(a,["code"]);null!=c&&bY(b,["code"],c);let d=bZ(a,["language"]);if(null!=d&&bY(b,["language"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(f));let g=bZ(a,["fileData"]);null!=g&&bY(b,["fileData"],g);let h=bZ(a,["functionCall"]);null!=h&&bY(b,["functionCall"],h);let i=bZ(a,["functionResponse"]);null!=i&&bY(b,["functionResponse"],i);let j=bZ(a,["inlineData"]);null!=j&&bY(b,["inlineData"],j);let k=bZ(a,["text"]);null!=k&&bY(b,["text"],k);let l=bZ(a,["thought"]);null!=l&&bY(b,["thought"],l);let m=bZ(a,["thoughtSignature"]);null!=m&&bY(b,["thoughtSignature"],m);let n=bZ(a,["videoMetadata"]);if(null!=n&&bY(b,["videoMetadata"],n),void 0!==bZ(a,["partMetadata"]))throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(a))),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}(cF(n)));let o=bZ(a,["tools"]);if(void 0!==b&&null!=o){let a=cM(o);Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["retrieval"]);null!=c&&bY(b,["retrieval"],c);let d=bZ(a,["googleMaps"]);null!=d&&bY(b,["googleMaps"],d);let e=bZ(a,["mcpServers"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>(function(a){if(void 0!==bZ(a,["name"]))throw Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["streamableHttpTransport"]))throw Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}})(a))),bY(b,["mcpServers"],a)}let f=bZ(a,["codeExecution"]);null!=f&&bY(b,["codeExecution"],f);let g=bZ(a,["computerUse"]);null!=g&&bY(b,["computerUse"],function(a){let b={},c=bZ(a,["enablePromptInjectionDetection"]);null!=c&&bY(b,["enablePromptInjectionDetection"],c);let d=bZ(a,["environment"]);null!=d&&bY(b,["environment"],d);let e=bZ(a,["excludedPredefinedFunctions"]);if(null!=e&&bY(b,["excludedPredefinedFunctions"],e),void 0!==bZ(a,["disabledSafetyPolicies"]))throw Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(g));let h=bZ(a,["enterpriseWebSearch"]);null!=h&&bY(b,["enterpriseWebSearch"],h);let i=bZ(a,["exaAiSearch"]);null!=i&&bY(b,["exaAiSearch"],i);let j=bZ(a,["functionDeclarations"]);if(null!=j){let a=j;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let k=bZ(a,["googleSearch"]);null!=k&&bY(b,["googleSearch"],k);let l=bZ(a,["googleSearchRetrieval"]);null!=l&&bY(b,["googleSearchRetrieval"],l);let m=bZ(a,["parallelAiSearch"]);null!=m&&bY(b,["parallelAiSearch"],m);let n=bZ(a,["urlContext"]);if(null!=n&&bY(b,["urlContext"],n),void 0!==bZ(a,["fileSearch"]))throw Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(cL(a)))),bY(b,["setup","tools"],a)}let p=bZ(a,["sessionResumption"]);void 0!==b&&null!=p&&bY(b,["setup","sessionResumption"],p);let q=bZ(a,["inputAudioTranscription"]);void 0!==b&&null!=q&&bY(b,["setup","inputAudioTranscription"],q);let r=bZ(a,["outputAudioTranscription"]);void 0!==b&&null!=r&&bY(b,["setup","outputAudioTranscription"],r);let s=bZ(a,["realtimeInputConfig"]);void 0!==b&&null!=s&&bY(b,["setup","realtimeInputConfig"],s);let t=bZ(a,["contextWindowCompression"]);void 0!==b&&null!=t&&bY(b,["setup","contextWindowCompression"],t);let u=bZ(a,["proactivity"]);void 0!==b&&null!=u&&bY(b,["setup","proactivity"],u);let v=bZ(a,["explicitVadSignal"]);void 0!==b&&null!=v&&bY(b,["setup","explicitVadSignal"],v);let w=bZ(a,["avatarConfig"]);void 0!==b&&null!=w&&bY(b,["setup","avatarConfig"],w);let x=bZ(a,["safetySettings"]);if(void 0!==b&&null!=x){let a=x;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["setup","safetySettings"],a)}if(void 0!==bZ(a,["translationConfig"]))throw Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}(c,a)),A=a}else{let a,b,c;i=this.apiClient,a={},null!=(b=bZ(D,["model"]))&&bY(a,["setup","model"],cu(i,b)),null!=(c=bZ(D,["config"]))&&bY(a,["config"],function(a,b){let c=bZ(a,["generationConfig"]);void 0!==b&&null!=c&&bY(b,["setup","generationConfig"],c);let d=bZ(a,["responseModalities"]);void 0!==b&&null!=d&&bY(b,["setup","generationConfig","responseModalities"],d);let e=bZ(a,["temperature"]);void 0!==b&&null!=e&&bY(b,["setup","generationConfig","temperature"],e);let f=bZ(a,["topP"]);void 0!==b&&null!=f&&bY(b,["setup","generationConfig","topP"],f);let g=bZ(a,["topK"]);void 0!==b&&null!=g&&bY(b,["setup","generationConfig","topK"],g);let h=bZ(a,["maxOutputTokens"]);void 0!==b&&null!=h&&bY(b,["setup","generationConfig","maxOutputTokens"],h);let i=bZ(a,["mediaResolution"]);void 0!==b&&null!=i&&bY(b,["setup","generationConfig","mediaResolution"],i);let j=bZ(a,["seed"]);void 0!==b&&null!=j&&bY(b,["setup","generationConfig","seed"],j);let k=bZ(a,["speechConfig"]);void 0!==b&&null!=k&&bY(b,["setup","generationConfig","speechConfig"],cK(k));let l=bZ(a,["thinkingConfig"]);void 0!==b&&null!=l&&bY(b,["setup","generationConfig","thinkingConfig"],l);let m=bZ(a,["enableAffectiveDialog"]);void 0!==b&&null!=m&&bY(b,["setup","generationConfig","enableAffectiveDialog"],m);let n=bZ(a,["systemInstruction"]);void 0!==b&&null!=n&&bY(b,["setup","systemInstruction"],function(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return c={},null!=(d=bZ(b=a,["mediaResolution"]))&&bY(c,["mediaResolution"],d),null!=(e=bZ(b,["toolCall"]))&&bY(c,["toolCall"],e),null!=(f=bZ(b,["toolResponse"]))&&bY(c,["toolResponse"],f),null!=(g=bZ(b,["audioTranscription"]))&&bY(c,["audioTranscription"],g),null!=(h=bZ(b,["codeExecutionResult"]))&&bY(c,["codeExecutionResult"],h),null!=(i=bZ(b,["executableCode"]))&&bY(c,["executableCode"],i),null!=(j=bZ(b,["fileData"]))&&bY(c,["fileData"],function(a){let b={};if(void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["fileUri"]);null!=c&&bY(b,["fileUri"],c);let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(j)),null!=(k=bZ(b,["functionCall"]))&&bY(c,["functionCall"],function(a){let b={},c=bZ(a,["args"]);null!=c&&bY(b,["args"],c);let d=bZ(a,["id"]);null!=d&&bY(b,["id"],d);let e=bZ(a,["name"]);if(null!=e&&bY(b,["name"],e),void 0!==bZ(a,["partialArgs"]))throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["willContinue"]))throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(k)),null!=(l=bZ(b,["functionResponse"]))&&bY(c,["functionResponse"],l),null!=(m=bZ(b,["inlineData"]))&&bY(c,["inlineData"],df(m)),null!=(n=bZ(b,["text"]))&&bY(c,["text"],n),null!=(o=bZ(b,["thought"]))&&bY(c,["thought"],o),null!=(p=bZ(b,["thoughtSignature"]))&&bY(c,["thoughtSignature"],p),null!=(q=bZ(b,["videoMetadata"]))&&bY(c,["videoMetadata"],q),null!=(r=bZ(b,["partMetadata"]))&&bY(c,["partMetadata"],r),c})),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}(cF(n)));let o=bZ(a,["tools"]);if(void 0!==b&&null!=o){let a=cM(o);Array.isArray(a)&&(a=a.map(a=>(function(a){let b={};if(void 0!==bZ(a,["retrieval"]))throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["googleMaps"]);null!=c&&bY(b,["googleMaps"],function(a){let b={},c=bZ(a,["authConfig"]);null!=c&&bY(b,["authConfig"],function(a){let b={},c=bZ(a,["apiKey"]);if(null!=c&&bY(b,["apiKey"],c),void 0!==bZ(a,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["authType"]))throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oauthConfig"]))throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oidcConfig"]))throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["enableWidget"]);if(null!=d&&bY(b,["enableWidget"],d),void 0!==bZ(a,["groundingTypes"]))throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["mcpServers"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mcpServers"],a)}let e=bZ(a,["codeExecution"]);null!=e&&bY(b,["codeExecution"],e);let f=bZ(a,["computerUse"]);if(null!=f&&bY(b,["computerUse"],f),void 0!==bZ(a,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["exaAiSearch"]))throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=bZ(a,["functionDeclarations"]);if(null!=g){let a=g;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let h=bZ(a,["googleSearch"]);null!=h&&bY(b,["googleSearch"],function(a){let b={};if(void 0!==bZ(a,["blockingConfidence"]))throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["excludeDomains"]))throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["searchTypes"]);null!=c&&bY(b,["searchTypes"],c);let d=bZ(a,["timeRangeFilter"]);return null!=d&&bY(b,["timeRangeFilter"],d),b}(h));let i=bZ(a,["googleSearchRetrieval"]);if(null!=i&&bY(b,["googleSearchRetrieval"],i),void 0!==bZ(a,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["urlContext"]);null!=j&&bY(b,["urlContext"],j);let k=bZ(a,["fileSearch"]);return null!=k&&bY(b,["fileSearch"],k),b})(cL(a)))),bY(b,["setup","tools"],a)}let p=bZ(a,["sessionResumption"]);void 0!==b&&null!=p&&bY(b,["setup","sessionResumption"],function(a){let b={},c=bZ(a,["handle"]);if(null!=c&&bY(b,["handle"],c),void 0!==bZ(a,["transparent"]))throw Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(p));let q=bZ(a,["inputAudioTranscription"]);void 0!==b&&null!=q&&bY(b,["setup","inputAudioTranscription"],q);let r=bZ(a,["outputAudioTranscription"]);void 0!==b&&null!=r&&bY(b,["setup","outputAudioTranscription"],r);let s=bZ(a,["realtimeInputConfig"]);void 0!==b&&null!=s&&bY(b,["setup","realtimeInputConfig"],s);let t=bZ(a,["contextWindowCompression"]);void 0!==b&&null!=t&&bY(b,["setup","contextWindowCompression"],t);let u=bZ(a,["proactivity"]);if(void 0!==b&&null!=u&&bY(b,["setup","proactivity"],u),void 0!==bZ(a,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let v=bZ(a,["avatarConfig"]);void 0!==b&&null!=v&&bY(b,["setup","avatarConfig"],v);let w=bZ(a,["safetySettings"]);if(void 0!==b&&null!=w){let a=w;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["category"]);if(null!=c&&bY(b,["category"],c),void 0!==bZ(a,["method"]))throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["threshold"]);return null!=d&&bY(b,["threshold"],d),b})(a))),bY(b,["setup","safetySettings"],a)}let x=bZ(a,["translationConfig"]);return void 0!==b&&null!=x&&bY(b,["setup","generationConfig","translationConfig"],x),{}}(c,a)),A=a}delete A.config;let E=new dR(y,this.apiClient);for(let a of(y.send(JSON.stringify(A)),await w,t=!0,u))r.onmessage(a);return E}isCallableTool(a){return"callTool"in a&&"function"==typeof a.callTool}}let dQ={turnComplete:!0};class dR{constructor(a,b){this.conn=a,this.apiClient=b}tLiveClientContent(a,b){if(null!==b.turns&&void 0!==b.turns){let c=[];try{c=cH(b.turns),a.isVertexAI()||(c=c.map(a=>di(a)))}catch(a){throw Error(`Failed to parse client content "turns", type: '${typeof b.turns}'`)}return{clientContent:{turns:c,turnComplete:b.turnComplete}}}return{clientContent:{turnComplete:b.turnComplete}}}tLiveClienttToolResponse(a,b){let c=[];if(null==b.functionResponses||0===(c=Array.isArray(b.functionResponses)?b.functionResponses:[b.functionResponses]).length)throw Error("functionResponses is required.");for(let b of c){if("object"!=typeof b||null===b||!("name"in b)||!("response"in b))throw Error(`Could not parse function response, type '${typeof b}'.`);if(!a.isVertexAI()&&!("id"in b))throw Error("FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.")}return{toolResponse:{functionResponses:c}}}sendClientContent(a){a=Object.assign(Object.assign({},dQ),a);let b=this.tLiveClientContent(this.apiClient,a);this.conn.send(JSON.stringify(b))}sendRealtimeInput(a){let b={};b=this.apiClient.isVertexAI()?{realtimeInput:function(a){let b={},c=bZ(a,["media"]);if(null!=c){let a=cw(c);Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mediaChunks"],a)}let d=bZ(a,["audio"]);null!=d&&bY(b,["audio"],cz(d));let e=bZ(a,["audioStreamEnd"]);null!=e&&bY(b,["audioStreamEnd"],e);let f=bZ(a,["video"]);null!=f&&bY(b,["video"],cy(f));let g=bZ(a,["text"]);null!=g&&bY(b,["text"],g);let h=bZ(a,["activityStart"]);null!=h&&bY(b,["activityStart"],h);let i=bZ(a,["activityEnd"]);return null!=i&&bY(b,["activityEnd"],i),b}(a)}:{realtimeInput:function(a){let b={},c=bZ(a,["media"]);if(null!=c){let a=cw(c);Array.isArray(a)&&(a=a.map(a=>df(a))),bY(b,["mediaChunks"],a)}let d=bZ(a,["audio"]);null!=d&&bY(b,["audio"],df(cz(d)));let e=bZ(a,["audioStreamEnd"]);null!=e&&bY(b,["audioStreamEnd"],e);let f=bZ(a,["video"]);null!=f&&bY(b,["video"],df(cy(f)));let g=bZ(a,["text"]);null!=g&&bY(b,["text"],g);let h=bZ(a,["activityStart"]);null!=h&&bY(b,["activityStart"],h);let i=bZ(a,["activityEnd"]);return null!=i&&bY(b,["activityEnd"],i),b}(a)},this.conn.send(JSON.stringify(b))}sendToolResponse(a){if(null==a.functionResponses)throw Error("Tool response parameters are required.");let b=this.tLiveClienttToolResponse(this.apiClient,a);this.conn.send(JSON.stringify(b))}close(){this.conn.close()}}function dS(a){var b,c,d;if(null==(b=null==a?void 0:a.automaticFunctionCalling)?void 0:b.disable)return!0;let e=!1;for(let b of null!=(c=null==a?void 0:a.tools)?c:[])if(dT(b)){e=!0;break}if(!e)return!0;let f=null==(d=null==a?void 0:a.automaticFunctionCalling)?void 0:d.maximumRemoteCalls;return(!(!f||!(f<0)&&Number.isInteger(f))||0==f)&&(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",f),!0)}function dT(a){return"callTool"in a&&"function"==typeof a.callTool}function dU(a){var b;let c=[];return(null==(b=null==a?void 0:a.config)?void 0:b.tools)&&a.config.tools.forEach((a,b)=>{dT(a)||a.functionDeclarations&&a.functionDeclarations.length>0&&c.push(b)}),c}function dV(a){var b;return!(null==(b=null==a?void 0:a.automaticFunctionCalling)?void 0:b.ignoreCallHistory)}class dW extends bW{constructor(a){super(),this.apiClient=a,this.embedContent=async a=>{if(!this.apiClient.isVertexAI())return a.model.includes("gemini-embedding-2")&&(a.contents=cH(a.contents)),await this.embedContentInternal(a);if(a.model.includes("gemini")&&"gemini-embedding-001"!==a.model||a.model.includes("maas")){let b=cH(a.contents);if(b.length>1)throw Error("The embedContent API for this model only supports one content at a time.");let c=Object.assign(Object.assign({},a),{content:b[0],embeddingApiType:bn.EMBED_CONTENT});return await this.embedContentInternal(c)}{let b=Object.assign(Object.assign({},a),{embeddingApiType:bn.PREDICT});return await this.embedContentInternal(b)}},this.generateContent=async a=>{var b,c,d,e,f,g,h,i;let j,k,l=await this.processParamsMaybeAddMcpUsage(a);if(this.maybeMoveToResponseJsonSchema(a),!(null!=(i=null==(h=null==(g=a.config)?void 0:g.tools)?void 0:h.some(a=>dT(a)))&&i)||dS(a.config))return await this.generateContentInternal(l);let m=dU(a);if(m.length>0){let a=m.map(a=>`tools[${a}]`).join(", ");throw Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${a}.`)}let n=cH(l.contents),o=null!=(d=null==(c=null==(b=l.config)?void 0:b.automaticFunctionCalling)?void 0:c.maximumRemoteCalls)?d:10,p=0;for(;p<o&&(j=await this.generateContentInternal(l)).functionCalls&&0!==j.functionCalls.length;){let b=j.candidates[0].content,c=[];for(let b of null!=(f=null==(e=a.config)?void 0:e.tools)?f:[])if(dT(b)){let a=await b.callTool(j.functionCalls);c.push(...a)}p++,k={role:"user",parts:c},l.contents=cH(l.contents),l.contents.push(b),l.contents.push(k),dV(l.config)&&(n.push(b),n.push(k))}return dV(l.config)&&(j.automaticFunctionCallingHistory=n),j},this.generateContentStream=async a=>{var b,c,d,e,f;if(this.maybeMoveToResponseJsonSchema(a),dS(a.config)){let b=await this.processParamsMaybeAddMcpUsage(a);return await this.generateContentStreamInternal(b)}let g=dU(a);if(g.length>0){let a=g.map(a=>`tools[${a}]`).join(", ");throw Error(`Incompatible tools found at ${a}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let h=null==(d=null==(c=null==(b=null==a?void 0:a.config)?void 0:b.toolConfig)?void 0:c.functionCallingConfig)?void 0:d.streamFunctionCallArguments,i=null==(f=null==(e=null==a?void 0:a.config)?void 0:e.automaticFunctionCalling)?void 0:f.disable;if(h&&!i)throw Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(a)},this.generateImages=async a=>(dW.loggedGenerateImagesWarning||(dW.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(a).then(a=>{var b;let c,d=[];if(null==a?void 0:a.generatedImages)for(let e of a.generatedImages)e&&(null==e?void 0:e.safetyAttributes)&&(null==(b=null==e?void 0:e.safetyAttributes)?void 0:b.contentType)==="Positive Prompt"?c=null==e?void 0:e.safetyAttributes:d.push(e);return c?{generatedImages:d,positivePromptSafetyAttributes:c,sdkHttpResponse:a.sdkHttpResponse}:{generatedImages:d,sdkHttpResponse:a.sdkHttpResponse}})),this.list=async a=>{var b;let c={config:Object.assign(Object.assign({},{queryBase:!0}),null==a?void 0:a.config)};if(this.apiClient.isVertexAI()&&!c.config.queryBase)if(null==(b=c.config)?void 0:b.filter)throw Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");else c.config.filter="labels.tune-type:*";return new c0(bM.PAGED_ITEM_MODELS,a=>this.listInternal(a),await this.listInternal(c),c)},this.editImage=async a=>{dW.loggedEditImageWarning||(dW.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let b={model:a.model,prompt:a.prompt,referenceImages:[],config:a.config};return a.referenceImages&&a.referenceImages&&(b.referenceImages=a.referenceImages.map(a=>a.toReferenceImageAPI())),await this.editImageInternal(b)},this.upscaleImage=async a=>{let b={numberOfImages:1,mode:"upscale"};a.config&&(b=Object.assign(Object.assign({},b),a.config));let c={model:a.model,image:a.image,upscaleFactor:a.upscaleFactor,config:b};return await this.upscaleImageInternal(c)},this.generateVideos=async a=>{var b,c,d,e,f,g;if((a.prompt||a.image||a.video)&&a.source)throw Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(a.prompt||a.image||a.video)&&!dW.loggedGenerateVideosWarning&&(dW.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead.")),!this.apiClient.isVertexAI()&&((null==(b=a.video)?void 0:b.uri)&&(null==(c=a.video)?void 0:c.videoBytes)?a.video={uri:a.video.uri,mimeType:a.video.mimeType}:(null==(e=null==(d=a.source)?void 0:d.video)?void 0:e.uri)&&(null==(g=null==(f=a.source)?void 0:f.video)?void 0:g.videoBytes)&&(a.source.video={uri:a.source.video.uri,mimeType:a.source.video.mimeType})),await this.generateVideosInternal(a)}}maybeMoveToResponseJsonSchema(a){a.config&&a.config.responseSchema&&!a.config.responseJsonSchema&&Object.keys(a.config.responseSchema).includes("$schema")&&(a.config.responseJsonSchema=a.config.responseSchema,delete a.config.responseSchema)}async processParamsMaybeAddMcpUsage(a){var b,c,d;let e=null==(b=a.config)?void 0:b.tools;if(!e)return a;let f=await Promise.all(e.map(async a=>dT(a)?await a.tool():a)),g={model:a.model,contents:a.contents,config:Object.assign(Object.assign({},a.config),{tools:f})};if(g.config.tools=f,a.config&&a.config.tools&&dI(a.config.tools)){let b=Object.assign({},null!=(d=null==(c=a.config.httpOptions)?void 0:c.headers)?d:{});0===Object.keys(b).length&&(b=this.apiClient.getDefaultHeaders()),dJ(b),g.config.httpOptions=Object.assign(Object.assign({},a.config.httpOptions),{headers:b})}return g}async initAfcToolsMap(a){var b,c,d;let e=new Map;for(let f of null!=(c=null==(b=a.config)?void 0:b.tools)?c:[])if(dT(f))for(let a of null!=(d=(await f.tool()).functionDeclarations)?d:[]){if(!a.name)throw Error("Function declaration name is required.");if(e.has(a.name))throw Error(`Duplicate tool declaration name: ${a.name}`);e.set(a.name,f)}return e}async processAfcStream(a){var b,c,d;let e=null!=(d=null==(c=null==(b=a.config)?void 0:b.automaticFunctionCalling)?void 0:c.maximumRemoteCalls)?d:10,f=!1,g=0;return function(a,b,c){return c7(this,arguments,function*(){for(;g<e;){f&&(g++,f=!1);let p=yield c6(a.processParamsMaybeAddMcpUsage(c)),q=yield c6(a.generateContentStreamInternal(p)),r=[],s=[];try{for(var d,h,i,j,k,l,m,n=!0,o=(h=void 0,c8(q));!(d=(m=yield c6(o.next())).done);n=!0)if(j=m.value,n=!1,yield yield c6(j),j.candidates&&(null==(k=j.candidates[0])?void 0:k.content)){for(let a of(s.push(j.candidates[0].content),null!=(l=j.candidates[0].content.parts)?l:[]))if(g<e&&a.functionCall){if(!a.functionCall.name)throw Error("Function call name was not returned by the model.");if(b.has(a.functionCall.name)){let c=yield c6(b.get(a.functionCall.name).callTool([a.functionCall]));r.push(...c)}else throw Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${b.keys()}, missing tool: ${a.functionCall.name}`)}}}catch(a){h={error:a}}finally{try{!n&&!d&&(i=o.return)&&(yield c6(i.call(o)))}finally{if(h)throw h.error}}if(r.length>0){f=!0;let a=new b1;a.candidates=[{content:{role:"user",parts:r}}],yield yield c6(a);let b=[];b.push(...s),b.push({role:"user",parts:r});let d=cH(c.contents).concat(b);c.contents=d}else break}})}(this,await this.initAfcToolsMap(a),a)}async generateContentInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d=dl(this.apiClient,a);return f=bX("{model}:generateContent",d._url),g=d._query,delete d._url,delete d._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(d),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=dn(a),c=new b1;return Object.assign(c,b),c})}{let b=dk(this.apiClient,a);return f=bX("{model}:generateContent",b._url),g=b._query,delete b._url,delete b._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=dm(a),c=new b1;return Object.assign(c,b),c})}}async generateContentStreamInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d=dl(this.apiClient,a);return f=bX("{model}:streamGenerateContent?alt=sse",d._url),g=d._query,delete d._url,delete d._query,this.apiClient.requestStream({path:f,queryParams:g,body:JSON.stringify(d),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(function(b){return c7(this,arguments,function*(){var c,d,e,f;try{for(var g,h=!0,i=c8(b);!(c=(g=yield c6(i.next())).done);h=!0){f=g.value,h=!1;let b=dn((yield c6(f.json())),a);b.sdkHttpResponse={headers:f.headers};let c=new b1;Object.assign(c,b),yield yield c6(c)}}catch(a){d={error:a}}finally{try{!h&&!c&&(e=i.return)&&(yield c6(e.call(i)))}finally{if(d)throw d.error}}})})}{let b=dk(this.apiClient,a);return f=bX("{model}:streamGenerateContent?alt=sse",b._url),g=b._query,delete b._url,delete b._query,this.apiClient.requestStream({path:f,queryParams:g,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(function(b){return c7(this,arguments,function*(){var c,d,e,f;try{for(var g,h=!0,i=c8(b);!(c=(g=yield c6(i.next())).done);h=!0){f=g.value,h=!1;let b=dm((yield c6(f.json())),a);b.sdkHttpResponse={headers:f.headers};let c=new b1;Object.assign(c,b),yield yield c6(c)}}catch(a){d={error:a}}finally{try{!h&&!c&&(e=i.return)&&(yield c6(e.call(i)))}finally{if(d)throw d.error}}})})}}async embedContentInternal(a){var b,c,d,e,f;let g="",h={};if(this.apiClient.isVertexAI()){let d=function(a,b,c){let d={},e=bZ(b,["model"]);null!=e&&bY(d,["_url","model"],cu(a,e));let f=bZ(c,["embeddingApiType"]);if(void 0===f&&(f="PREDICT"),"PREDICT"===f){let c=bZ(b,["contents"]);if(null!=c){let b=cG(a,c);Array.isArray(b)&&(b=b.map(a=>a)),bY(d,["instances[]","content"],b)}}let g=bZ(c,["embeddingApiType"]);if(void 0===g&&(g="PREDICT"),"EMBED_CONTENT"===g){let a=bZ(b,["content"]);null!=a&&bY(d,["content"],dj(cF(a)))}let h=bZ(b,["config"]);return null!=h&&function(a,b,c){let d=bZ(c,["embeddingApiType"]);if(void 0===d&&(d="PREDICT"),"PREDICT"===d){let c=bZ(a,["taskType"]);void 0!==b&&null!=c&&bY(b,["instances[]","task_type"],c)}else if("EMBED_CONTENT"===d){let c=bZ(a,["taskType"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","taskType"],c)}let e=bZ(c,["embeddingApiType"]);if(void 0===e&&(e="PREDICT"),"PREDICT"===e){let c=bZ(a,["title"]);void 0!==b&&null!=c&&bY(b,["instances[]","title"],c)}else if("EMBED_CONTENT"===e){let c=bZ(a,["title"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","title"],c)}let f=bZ(c,["embeddingApiType"]);if(void 0===f&&(f="PREDICT"),"PREDICT"===f){let c=bZ(a,["outputDimensionality"]);void 0!==b&&null!=c&&bY(b,["parameters","outputDimensionality"],c)}else if("EMBED_CONTENT"===f){let c=bZ(a,["outputDimensionality"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","outputDimensionality"],c)}let g=bZ(c,["embeddingApiType"]);if(void 0===g&&(g="PREDICT"),"PREDICT"===g){let c=bZ(a,["mimeType"]);void 0!==b&&null!=c&&bY(b,["instances[]","mimeType"],c)}let h=bZ(c,["embeddingApiType"]);if(void 0===h&&(h="PREDICT"),"PREDICT"===h){let c=bZ(a,["autoTruncate"]);void 0!==b&&null!=c&&bY(b,["parameters","autoTruncate"],c)}else if("EMBED_CONTENT"===h){let c=bZ(a,["autoTruncate"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","autoTruncate"],c)}let i=bZ(c,["embeddingApiType"]);if(void 0===i&&(i="PREDICT"),"EMBED_CONTENT"===i){let c=bZ(a,["documentOcr"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","documentOcr"],c)}let j=bZ(c,["embeddingApiType"]);if(void 0===j&&(j="PREDICT"),"EMBED_CONTENT"===j){let c=bZ(a,["audioTrackExtraction"]);void 0!==b&&null!=c&&bY(b,["embedContentConfig","audioTrackExtraction"],c)}}(h,d,c),d}(this.apiClient,a,a);return g=bX((f=a.model).includes("gemini")&&"gemini-embedding-001"!==f||f.includes("maas")?"{model}:embedContent":"{model}:predict",d._url),h=d._query,delete d._url,delete d._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(b=>{let c=function(a,b){let c={},d=bZ(a,["sdkHttpResponse"]);null!=d&&bY(c,["sdkHttpResponse"],d);let e=bZ(a,["predictions[]","embeddings"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>{let b,c,d;return b={},null!=(c=bZ(a,["values"]))&&bY(b,["values"],c),null!=(d=bZ(a,["statistics"]))&&bY(b,["statistics"],function(a){let b={},c=bZ(a,["truncated"]);null!=c&&bY(b,["truncated"],c);let d=bZ(a,["token_count"]);null!=d&&bY(b,["tokenCount"],d);let e=bZ(a,["tokensDetails"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["tokensDetails"],a)}return b}(d)),b})),bY(c,["embeddings"],a)}let f=bZ(a,["metadata"]);if(null!=f&&bY(c,["metadata"],f),b&&"EMBED_CONTENT"===bZ(b,["embeddingApiType"])){let b=bZ(a,["embedding"]),d=bZ(a,["usageMetadata"]),e=bZ(a,["truncated"]);if(b){let a={};d&&d.promptTokenCount&&(a.tokenCount=d.promptTokenCount),d&&d.promptTokensDetails&&(a.tokensDetails=d.promptTokensDetails),e&&(a.truncated=e),b.statistics=a,bY(c,["embeddings"],[b])}}return c}(b,a),d=new b2;return Object.assign(d,c),d})}{let b=function(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["_url","model"],cu(a,d));let e=bZ(b,["contents"]);if(null!=e){let b=cG(a,e);Array.isArray(b)&&(b=b.map(a=>a)),bY(c,["requests[]","content"],b)}let f=bZ(b,["content"]);null!=f&&di(cF(f));let g=bZ(b,["config"]);null!=g&&function(a,b){let c=bZ(a,["taskType"]);void 0!==b&&null!=c&&bY(b,["requests[]","taskType"],c);let d=bZ(a,["title"]);void 0!==b&&null!=d&&bY(b,["requests[]","title"],d);let e=bZ(a,["outputDimensionality"]);if(void 0!==b&&null!=e&&bY(b,["requests[]","outputDimensionality"],e),void 0!==bZ(a,["mimeType"]))throw Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["autoTruncate"]))throw Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["documentOcr"]))throw Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["audioTrackExtraction"]))throw Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(g,c);let h=bZ(b,["model"]);return void 0!==h&&bY(c,["requests[]","model"],cu(a,h)),c}(this.apiClient,a);return g=bX("{model}:batchEmbedContents",b._url),h=b._query,delete b._url,delete b._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["embeddings"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["embeddings"],a)}let e=bZ(a,["metadata"]);return null!=e&&bY(b,["metadata"],e),b}(a),c=new b2;return Object.assign(c,b),c})}}async generateImagesInternal(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["_url","model"],cu(f,e)),null!=(g=bZ(a,["prompt"]))&&bY(d,["instances[0]","prompt"],g),null!=(j=bZ(a,["config"]))&&(k=bZ(j,["outputGcsUri"]),void 0!==d&&null!=k&&bY(d,["parameters","storageUri"],k),l=bZ(j,["negativePrompt"]),void 0!==d&&null!=l&&bY(d,["parameters","negativePrompt"],l),m=bZ(j,["numberOfImages"]),void 0!==d&&null!=m&&bY(d,["parameters","sampleCount"],m),n=bZ(j,["aspectRatio"]),void 0!==d&&null!=n&&bY(d,["parameters","aspectRatio"],n),o=bZ(j,["guidanceScale"]),void 0!==d&&null!=o&&bY(d,["parameters","guidanceScale"],o),p=bZ(j,["seed"]),void 0!==d&&null!=p&&bY(d,["parameters","seed"],p),q=bZ(j,["safetyFilterLevel"]),void 0!==d&&null!=q&&bY(d,["parameters","safetySetting"],q),r=bZ(j,["personGeneration"]),void 0!==d&&null!=r&&bY(d,["parameters","personGeneration"],r),s=bZ(j,["includeSafetyAttributes"]),void 0!==d&&null!=s&&bY(d,["parameters","includeSafetyAttributes"],s),t=bZ(j,["includeRaiReason"]),void 0!==d&&null!=t&&bY(d,["parameters","includeRaiReason"],t),u=bZ(j,["language"]),void 0!==d&&null!=u&&bY(d,["parameters","language"],u),v=bZ(j,["outputMimeType"]),void 0!==d&&null!=v&&bY(d,["parameters","outputOptions","mimeType"],v),w=bZ(j,["outputCompressionQuality"]),void 0!==d&&null!=w&&bY(d,["parameters","outputOptions","compressionQuality"],w),x=bZ(j,["addWatermark"]),void 0!==d&&null!=x&&bY(d,["parameters","addWatermark"],x),y=bZ(j,["labels"]),void 0!==d&&null!=y&&bY(d,["labels"],y),z=bZ(j,["imageSize"]),void 0!==d&&null!=z&&bY(d,["parameters","sampleImageSize"],z),A=bZ(j,["enhancePrompt"]),void 0!==d&&null!=A&&bY(d,["parameters","enhancePrompt"],A)),d);return h=bX("{model}:predict",B._url),i=B._query,delete B._url,delete B._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(B),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["predictions"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>dp(a))),bY(b,["generatedImages"],a)}let e=bZ(a,["positivePromptSafetyAttributes"]);return null!=e&&bY(b,["positivePromptSafetyAttributes"],dw(e)),b}(a),c=new b3;return Object.assign(c,b),c})}{let b,c,f,j,k=(g=this.apiClient,b={},null!=(c=bZ(a,["model"]))&&bY(b,["_url","model"],cu(g,c)),null!=(f=bZ(a,["prompt"]))&&bY(b,["instances[0]","prompt"],f),null!=(j=bZ(a,["config"]))&&function(a,b){if(void 0!==bZ(a,["outputGcsUri"]))throw Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["negativePrompt"]))throw Error("negativePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["numberOfImages"]);void 0!==b&&null!=c&&bY(b,["parameters","sampleCount"],c);let d=bZ(a,["aspectRatio"]);void 0!==b&&null!=d&&bY(b,["parameters","aspectRatio"],d);let e=bZ(a,["guidanceScale"]);if(void 0!==b&&null!=e&&bY(b,["parameters","guidanceScale"],e),void 0!==bZ(a,["seed"]))throw Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let f=bZ(a,["safetyFilterLevel"]);void 0!==b&&null!=f&&bY(b,["parameters","safetySetting"],f);let g=bZ(a,["personGeneration"]);void 0!==b&&null!=g&&bY(b,["parameters","personGeneration"],g);let h=bZ(a,["includeSafetyAttributes"]);void 0!==b&&null!=h&&bY(b,["parameters","includeSafetyAttributes"],h);let i=bZ(a,["includeRaiReason"]);void 0!==b&&null!=i&&bY(b,["parameters","includeRaiReason"],i);let j=bZ(a,["language"]);void 0!==b&&null!=j&&bY(b,["parameters","language"],j);let k=bZ(a,["outputMimeType"]);void 0!==b&&null!=k&&bY(b,["parameters","outputOptions","mimeType"],k);let l=bZ(a,["outputCompressionQuality"]);if(void 0!==b&&null!=l&&bY(b,["parameters","outputOptions","compressionQuality"],l),void 0!==bZ(a,["addWatermark"]))throw Error("addWatermark parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["labels"]))throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let m=bZ(a,["imageSize"]);if(void 0!==b&&null!=m&&bY(b,["parameters","sampleImageSize"],m),void 0!==bZ(a,["enhancePrompt"]))throw Error("enhancePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(j,b),b);return h=bX("{model}:predict",k._url),i=k._query,delete k._url,delete k._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(k),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["predictions"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>{var b,c;let d,e,f,g,h,i,j;return d={},null!=(e=bZ(b=a,["_self"]))&&bY(d,["image"],(f={},null!=(g=bZ(c=e,["bytesBase64Encoded"]))&&bY(f,["imageBytes"],b$(g)),null!=(h=bZ(c,["mimeType"]))&&bY(f,["mimeType"],h),f)),null!=(i=bZ(b,["raiFilteredReason"]))&&bY(d,["raiFilteredReason"],i),null!=(j=bZ(b,["_self"]))&&bY(d,["safetyAttributes"],dv(j)),d})),bY(b,["generatedImages"],a)}let e=bZ(a,["positivePromptSafetyAttributes"]);return null!=e&&bY(b,["positivePromptSafetyAttributes"],dv(e)),b}(a),c=new b3;return Object.assign(c,b),c})}}async editImageInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f=function(a,b){let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t={},u=bZ(b,["model"]);null!=u&&bY(t,["_url","model"],cu(a,u));let v=bZ(b,["prompt"]);null!=v&&bY(t,["instances[0]","prompt"],v);let w=bZ(b,["referenceImages"]);if(null!=w){let a=w;Array.isArray(a)&&(a=a.map(a=>(function(a){let b,c,d,e,f,g,h,i={},j=bZ(a,["referenceImage"]);null!=j&&bY(i,["referenceImage"],ds(j));let k=bZ(a,["referenceId"]);null!=k&&bY(i,["referenceId"],k);let l=bZ(a,["referenceType"]);null!=l&&bY(i,["referenceType"],l);let m=bZ(a,["maskImageConfig"]);null!=m&&bY(i,["maskImageConfig"],(b={},null!=(c=bZ(m,["maskMode"]))&&bY(b,["maskMode"],c),null!=(d=bZ(m,["segmentationClasses"]))&&bY(b,["maskClasses"],d),null!=(e=bZ(m,["maskDilation"]))&&bY(b,["dilation"],e),b));let n=bZ(a,["controlImageConfig"]);null!=n&&bY(i,["controlImageConfig"],(f={},null!=(g=bZ(n,["controlType"]))&&bY(f,["controlType"],g),null!=(h=bZ(n,["enableControlImageComputation"]))&&bY(f,["computeControl"],h),f));let o=bZ(a,["styleImageConfig"]);null!=o&&bY(i,["styleImageConfig"],o);let p=bZ(a,["subjectImageConfig"]);return null!=p&&bY(i,["subjectImageConfig"],p),i})(a))),bY(t,["instances[0]","referenceImages"],a)}let x=bZ(b,["config"]);return null!=x&&(c=bZ(x,["outputGcsUri"]),void 0!==t&&null!=c&&bY(t,["parameters","storageUri"],c),d=bZ(x,["negativePrompt"]),void 0!==t&&null!=d&&bY(t,["parameters","negativePrompt"],d),e=bZ(x,["numberOfImages"]),void 0!==t&&null!=e&&bY(t,["parameters","sampleCount"],e),f=bZ(x,["aspectRatio"]),void 0!==t&&null!=f&&bY(t,["parameters","aspectRatio"],f),g=bZ(x,["guidanceScale"]),void 0!==t&&null!=g&&bY(t,["parameters","guidanceScale"],g),h=bZ(x,["seed"]),void 0!==t&&null!=h&&bY(t,["parameters","seed"],h),i=bZ(x,["safetyFilterLevel"]),void 0!==t&&null!=i&&bY(t,["parameters","safetySetting"],i),j=bZ(x,["personGeneration"]),void 0!==t&&null!=j&&bY(t,["parameters","personGeneration"],j),k=bZ(x,["includeSafetyAttributes"]),void 0!==t&&null!=k&&bY(t,["parameters","includeSafetyAttributes"],k),l=bZ(x,["includeRaiReason"]),void 0!==t&&null!=l&&bY(t,["parameters","includeRaiReason"],l),m=bZ(x,["language"]),void 0!==t&&null!=m&&bY(t,["parameters","language"],m),n=bZ(x,["outputMimeType"]),void 0!==t&&null!=n&&bY(t,["parameters","outputOptions","mimeType"],n),o=bZ(x,["outputCompressionQuality"]),void 0!==t&&null!=o&&bY(t,["parameters","outputOptions","compressionQuality"],o),p=bZ(x,["addWatermark"]),void 0!==t&&null!=p&&bY(t,["parameters","addWatermark"],p),q=bZ(x,["labels"]),void 0!==t&&null!=q&&bY(t,["labels"],q),r=bZ(x,["editMode"]),void 0!==t&&null!=r&&bY(t,["parameters","editMode"],r),s=bZ(x,["baseSteps"]),void 0!==t&&null!=s&&bY(t,["parameters","editConfig","baseSteps"],s)),t}(this.apiClient,a);return d=bX("{model}:predict",f._url),e=f._query,delete f._url,delete f._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(f),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["predictions"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>dp(a))),bY(b,["generatedImages"],a)}return b}(a),c=new b4;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(a){var b,c,d;let e="",f={};if(this.apiClient.isVertexAI()){let g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w=(d=this.apiClient,g={},null!=(h=bZ(a,["model"]))&&bY(g,["_url","model"],cu(d,h)),null!=(i=bZ(a,["image"]))&&bY(g,["instances[0]","image"],ds(i)),null!=(j=bZ(a,["upscaleFactor"]))&&bY(g,["parameters","upscaleConfig","upscaleFactor"],j),null!=(k=bZ(a,["config"]))&&(l=bZ(k,["outputGcsUri"]),void 0!==g&&null!=l&&bY(g,["parameters","storageUri"],l),m=bZ(k,["safetyFilterLevel"]),void 0!==g&&null!=m&&bY(g,["parameters","safetySetting"],m),n=bZ(k,["personGeneration"]),void 0!==g&&null!=n&&bY(g,["parameters","personGeneration"],n),o=bZ(k,["includeRaiReason"]),void 0!==g&&null!=o&&bY(g,["parameters","includeRaiReason"],o),p=bZ(k,["outputMimeType"]),void 0!==g&&null!=p&&bY(g,["parameters","outputOptions","mimeType"],p),q=bZ(k,["outputCompressionQuality"]),void 0!==g&&null!=q&&bY(g,["parameters","outputOptions","compressionQuality"],q),r=bZ(k,["enhanceInputImage"]),void 0!==g&&null!=r&&bY(g,["parameters","upscaleConfig","enhanceInputImage"],r),s=bZ(k,["imagePreservationFactor"]),void 0!==g&&null!=s&&bY(g,["parameters","upscaleConfig","imagePreservationFactor"],s),t=bZ(k,["labels"]),void 0!==g&&null!=t&&bY(g,["labels"],t),u=bZ(k,["numberOfImages"]),void 0!==g&&null!=u&&bY(g,["parameters","sampleCount"],u),v=bZ(k,["mode"]),void 0!==g&&null!=v&&bY(g,["parameters","mode"],v)),g);return e=bX("{model}:predict",w._url),f=w._query,delete w._url,delete w._query,this.apiClient.request({path:e,queryParams:f,body:JSON.stringify(w),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["predictions"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>dp(a))),bY(b,["generatedImages"],a)}return b}(a),c=new b5;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(a){var b,c,d;let e="",f={};if(this.apiClient.isVertexAI()){let g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v=(d=this.apiClient,g={},null!=(h=bZ(a,["model"]))&&bY(g,["_url","model"],cu(d,h)),null!=(i=bZ(a,["source"]))&&function(a,b){let c=bZ(a,["prompt"]);void 0!==b&&null!=c&&bY(b,["instances[0]","prompt"],c);let d=bZ(a,["personImage"]);void 0!==b&&null!=d&&bY(b,["instances[0]","personImage","image"],ds(d));let e=bZ(a,["productImages"]);if(void 0!==b&&null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>{let b,c;return b={},null!=(c=bZ(a,["productImage"]))&&bY(b,["image"],ds(c)),b})),bY(b,["instances[0]","productImages"],a)}}(i,g),null!=(j=bZ(a,["config"]))&&(k=bZ(j,["numberOfImages"]),void 0!==g&&null!=k&&bY(g,["parameters","sampleCount"],k),l=bZ(j,["baseSteps"]),void 0!==g&&null!=l&&bY(g,["parameters","baseSteps"],l),m=bZ(j,["outputGcsUri"]),void 0!==g&&null!=m&&bY(g,["parameters","storageUri"],m),n=bZ(j,["seed"]),void 0!==g&&null!=n&&bY(g,["parameters","seed"],n),o=bZ(j,["safetyFilterLevel"]),void 0!==g&&null!=o&&bY(g,["parameters","safetySetting"],o),p=bZ(j,["personGeneration"]),void 0!==g&&null!=p&&bY(g,["parameters","personGeneration"],p),q=bZ(j,["addWatermark"]),void 0!==g&&null!=q&&bY(g,["parameters","addWatermark"],q),r=bZ(j,["outputMimeType"]),void 0!==g&&null!=r&&bY(g,["parameters","outputOptions","mimeType"],r),s=bZ(j,["outputCompressionQuality"]),void 0!==g&&null!=s&&bY(g,["parameters","outputOptions","compressionQuality"],s),t=bZ(j,["enhancePrompt"]),void 0!==g&&null!=t&&bY(g,["parameters","enhancePrompt"],t),u=bZ(j,["labels"]),void 0!==g&&null!=u&&bY(g,["labels"],u)),g);return e=bX("{model}:predict",v._url),f=v._query,delete v._url,delete v._query,this.apiClient.request({path:e,queryParams:f,body:JSON.stringify(v),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b=function(a){let b={},c=bZ(a,["predictions"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>dp(a))),bY(b,["generatedImages"],a)}return b}(a),c=new b6;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(a){var b,c,d,e,f;let g="",h={};if(this.apiClient.isVertexAI()){let i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=(d=this.apiClient,n={},null!=(o=bZ(a,["model"]))&&bY(n,["_url","model"],cu(d,o)),null!=(p=bZ(a,["source"]))&&(e=p,f=n,k=bZ(e,["prompt"]),void 0!==f&&null!=k&&bY(f,["instances[0]","prompt"],k),l=bZ(e,["image"]),void 0!==f&&null!=l&&bY(f,["instances[0]","image"],ds(l)),m=bZ(e,["scribbleImage"]),void 0!==f&&null!=m&&bY(f,["instances[0]","scribble"],(i={},null!=(j=bZ(m,["image"]))&&bY(i,["image"],ds(j)),i))),null!=(q=bZ(a,["config"]))&&(r=bZ(q,["mode"]),void 0!==n&&null!=r&&bY(n,["parameters","mode"],r),s=bZ(q,["maxPredictions"]),void 0!==n&&null!=s&&bY(n,["parameters","maxPredictions"],s),t=bZ(q,["confidenceThreshold"]),void 0!==n&&null!=t&&bY(n,["parameters","confidenceThreshold"],t),u=bZ(q,["maskDilation"]),void 0!==n&&null!=u&&bY(n,["parameters","maskDilation"],u),v=bZ(q,["binaryColorThreshold"]),void 0!==n&&null!=v&&bY(n,["parameters","binaryColorThreshold"],v),w=bZ(q,["labels"]),void 0!==n&&null!=w&&bY(n,["labels"],w)),n);return g=bX("{model}:predict",x._url),h=x._query,delete x._url,delete x._query,this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(x),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b=function(a){let b={},c=bZ(a,["predictions"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["_self"]);null!=c&&bY(b,["mask"],dq(c));let d=bZ(a,["labels"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["labels"],a)}return b})(a))),bY(b,["generatedMasks"],a)}return b}(a),c=new b7;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["_url","name"],cu(f,e)),d);return h=bX("{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>du(a))}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["model"]))&&bY(b,["_url","name"],cu(g,c)),b);return h=bX("{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>dt(a))}}async listInternal(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g,j,k,l,m=(f=this.apiClient,d={},null!=(e=bZ(a,["config"]))&&(g=bZ(e,["pageSize"]),void 0!==d&&null!=g&&bY(d,["_query","pageSize"],g),j=bZ(e,["pageToken"]),void 0!==d&&null!=j&&bY(d,["_query","pageToken"],j),k=bZ(e,["filter"]),void 0!==d&&null!=k&&bY(d,["_query","filter"],k),l=bZ(e,["queryBase"]),void 0!==d&&null!=l&&bY(d,["_url","models_url"],cS(f,l))),d);return h=bX("{models_url}",m._url),i=m._query,delete m._url,delete m._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(m),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["_self"]);if(null!=e){let a=cT(e);Array.isArray(a)&&(a=a.map(a=>du(a))),bY(b,["models"],a)}return b}(a),c=new b8;return Object.assign(c,b),c})}{let b,c,f,j,k,l,m=(g=this.apiClient,b={},null!=(c=bZ(a,["config"]))&&(f=bZ(c,["pageSize"]),void 0!==b&&null!=f&&bY(b,["_query","pageSize"],f),j=bZ(c,["pageToken"]),void 0!==b&&null!=j&&bY(b,["_query","pageToken"],j),k=bZ(c,["filter"]),void 0!==b&&null!=k&&bY(b,["_query","filter"],k),l=bZ(c,["queryBase"]),void 0!==b&&null!=l&&bY(b,["_url","models_url"],cS(g,l))),b);return h=bX("{models_url}",m._url),i=m._query,delete m._url,delete m._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(m),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["_self"]);if(null!=e){let a=cT(e);Array.isArray(a)&&(a=a.map(a=>dt(a))),bY(b,["models"],a)}return b}(a),c=new b8;return Object.assign(c,b),c})}}async update(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g,j,k,l,m=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["_url","model"],cu(f,e)),null!=(g=bZ(a,["config"]))&&(j=bZ(g,["displayName"]),void 0!==d&&null!=j&&bY(d,["displayName"],j),k=bZ(g,["description"]),void 0!==d&&null!=k&&bY(d,["description"],k),l=bZ(g,["defaultCheckpointId"]),void 0!==d&&null!=l&&bY(d,["defaultCheckpointId"],l)),d);return h=bX("{model}",m._url),i=m._query,delete m._url,delete m._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(m),httpMethod:"PATCH",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>du(a))}{let b,c,f,j,k,l,m=(g=this.apiClient,b={},null!=(c=bZ(a,["model"]))&&bY(b,["_url","name"],cu(g,c)),null!=(f=bZ(a,["config"]))&&(j=bZ(f,["displayName"]),void 0!==b&&null!=j&&bY(b,["displayName"],j),k=bZ(f,["description"]),void 0!==b&&null!=k&&bY(b,["description"],k),l=bZ(f,["defaultCheckpointId"]),void 0!==b&&null!=l&&bY(b,["defaultCheckpointId"],l)),b);return h=bX("{name}",m._url),i=m._query,delete m._url,delete m._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(m),httpMethod:"PATCH",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>dt(a))}}async delete(a){var b,c,d,e,f,g;let h="",i={};if(this.apiClient.isVertexAI()){let d,e,g=(f=this.apiClient,d={},null!=(e=bZ(a,["model"]))&&bY(d,["_url","name"],cu(f,e)),d);return h=bX("{name}",g._url),i=g._query,delete g._url,delete g._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(g),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new b9;return Object.assign(e,d),e})}{let b,c,f=(g=this.apiClient,b={},null!=(c=bZ(a,["model"]))&&bY(b,["_url","name"],cu(g,c)),b);return h=bX("{name}",f._url),i=f._query,delete f._url,delete f._query,this.apiClient.request({path:h,queryParams:i,body:JSON.stringify(f),httpMethod:"DELETE",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new b9;return Object.assign(e,d),e})}}async countTokens(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d=function(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["_url","model"],cu(a,d));let e=bZ(b,["contents"]);if(null!=e){let a=cH(e);Array.isArray(a)&&(a=a.map(a=>dj(a))),bY(c,["contents"],a)}let f=bZ(b,["config"]);return null!=f&&function(a,b){let c=bZ(a,["systemInstruction"]);void 0!==b&&null!=c&&bY(b,["systemInstruction"],dj(cF(c)));let d=bZ(a,["tools"]);if(void 0!==b&&null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>dy(a))),bY(b,["tools"],a)}let e=bZ(a,["generationConfig"]);void 0!==b&&null!=e&&bY(b,["generationConfig"],function(a){let b={},c=bZ(a,["modelSelectionConfig"]);null!=c&&bY(b,["modelConfig"],c);let d=bZ(a,["responseJsonSchema"]);null!=d&&bY(b,["responseJsonSchema"],d);let e=bZ(a,["audioTranscriptionConfig"]);null!=e&&bY(b,["audioTranscriptionConfig"],e);let f=bZ(a,["audioTimestamp"]);null!=f&&bY(b,["audioTimestamp"],f);let g=bZ(a,["candidateCount"]);null!=g&&bY(b,["candidateCount"],g);let h=bZ(a,["enableAffectiveDialog"]);null!=h&&bY(b,["enableAffectiveDialog"],h);let i=bZ(a,["frequencyPenalty"]);null!=i&&bY(b,["frequencyPenalty"],i);let j=bZ(a,["logprobs"]);null!=j&&bY(b,["logprobs"],j);let k=bZ(a,["maxOutputTokens"]);null!=k&&bY(b,["maxOutputTokens"],k);let l=bZ(a,["mediaResolution"]);null!=l&&bY(b,["mediaResolution"],l);let m=bZ(a,["presencePenalty"]);null!=m&&bY(b,["presencePenalty"],m);let n=bZ(a,["responseFormat"]);if(null!=n){let a=n;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["responseFormat"],a)}let o=bZ(a,["responseLogprobs"]);null!=o&&bY(b,["responseLogprobs"],o);let p=bZ(a,["responseMimeType"]);null!=p&&bY(b,["responseMimeType"],p);let q=bZ(a,["responseModalities"]);null!=q&&bY(b,["responseModalities"],q);let r=bZ(a,["responseSchema"]);null!=r&&bY(b,["responseSchema"],r);let s=bZ(a,["routingConfig"]);null!=s&&bY(b,["routingConfig"],s);let t=bZ(a,["seed"]);null!=t&&bY(b,["seed"],t);let u=bZ(a,["speechConfig"]);null!=u&&bY(b,["speechConfig"],dx(u));let v=bZ(a,["stopSequences"]);null!=v&&bY(b,["stopSequences"],v);let w=bZ(a,["temperature"]);null!=w&&bY(b,["temperature"],w);let x=bZ(a,["thinkingConfig"]);null!=x&&bY(b,["thinkingConfig"],x);let y=bZ(a,["topK"]);null!=y&&bY(b,["topK"],y);let z=bZ(a,["topP"]);if(null!=z&&bY(b,["topP"],z),void 0!==bZ(a,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["translationConfig"]))throw Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(e))}(f,c),c}(this.apiClient,a);return f=bX("{model}:countTokens",d._url),g=d._query,delete d._url,delete d._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(d),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["totalTokens"]))&&bY(b,["totalTokens"],d),b),f=new ca;return Object.assign(f,e),f})}{let b=function(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["_url","model"],cu(a,d));let e=bZ(b,["contents"]);if(null!=e){let a=cH(e);Array.isArray(a)&&(a=a.map(a=>di(a))),bY(c,["contents"],a)}let f=bZ(b,["config"]);return null!=f&&function(a){if(void 0!==bZ(a,["systemInstruction"]))throw Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["tools"]))throw Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["generationConfig"]))throw Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(f),c}(this.apiClient,a);return f=bX("{model}:countTokens",b._url),g=b._query,delete b._url,delete b._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["totalTokens"]))&&bY(b,["totalTokens"],d),null!=(e=bZ(a,["cachedContentTokenCount"]))&&bY(b,["cachedContentTokenCount"],e),b),g=new ca;return Object.assign(g,f),g})}}async computeTokens(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f=function(a,b){let c={},d=bZ(b,["model"]);null!=d&&bY(c,["_url","model"],cu(a,d));let e=bZ(b,["contents"]);if(null!=e){let a=cH(e);Array.isArray(a)&&(a=a.map(a=>dj(a))),bY(c,["contents"],a)}return c}(this.apiClient,a);return d=bX("{model}:computeTokens",f._url),e=f._query,delete f._url,delete f._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(f),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["tokensInfo"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["tokensInfo"],a)}return b}(a),c=new cb;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(a){var b,c,d,e,f,g,h,i,j,k;let l="",m={};if(this.apiClient.isVertexAI()){let d,e,g,j,k,n,o,p,q,r,s=(f=this.apiClient,j={},null!=(k=bZ(a,["model"]))&&bY(j,["_url","model"],cu(f,k)),null!=(n=bZ(a,["prompt"]))&&bY(j,["instances[0]","prompt"],n),null!=(o=bZ(a,["image"]))&&bY(j,["instances[0]","image"],ds(o)),null!=(p=bZ(a,["video"]))&&bY(j,["instances[0]","video"],dA(p)),null!=(q=bZ(a,["source"]))&&(h=q,i=j,d=bZ(h,["prompt"]),void 0!==i&&null!=d&&bY(i,["instances[0]","prompt"],d),e=bZ(h,["image"]),void 0!==i&&null!=e&&bY(i,["instances[0]","image"],ds(e)),g=bZ(h,["video"]),void 0!==i&&null!=g&&bY(i,["instances[0]","video"],dA(g))),null!=(r=bZ(a,["config"]))&&function(a,b){var c;let d,e,f,g=bZ(a,["numberOfVideos"]);void 0!==b&&null!=g&&bY(b,["parameters","sampleCount"],g);let h=bZ(a,["outputGcsUri"]);void 0!==b&&null!=h&&bY(b,["parameters","storageUri"],h);let i=bZ(a,["fps"]);void 0!==b&&null!=i&&bY(b,["parameters","fps"],i);let j=bZ(a,["durationSeconds"]);void 0!==b&&null!=j&&bY(b,["parameters","durationSeconds"],j);let k=bZ(a,["seed"]);void 0!==b&&null!=k&&bY(b,["parameters","seed"],k);let l=bZ(a,["aspectRatio"]);void 0!==b&&null!=l&&bY(b,["parameters","aspectRatio"],l);let m=bZ(a,["resolution"]);void 0!==b&&null!=m&&bY(b,["parameters","resolution"],m);let n=bZ(a,["personGeneration"]);void 0!==b&&null!=n&&bY(b,["parameters","personGeneration"],n);let o=bZ(a,["pubsubTopic"]);void 0!==b&&null!=o&&bY(b,["parameters","pubsubTopic"],o);let p=bZ(a,["negativePrompt"]);void 0!==b&&null!=p&&bY(b,["parameters","negativePrompt"],p);let q=bZ(a,["enhancePrompt"]);void 0!==b&&null!=q&&bY(b,["parameters","enhancePrompt"],q);let r=bZ(a,["generateAudio"]);void 0!==b&&null!=r&&bY(b,["parameters","generateAudio"],r);let s=bZ(a,["lastFrame"]);void 0!==b&&null!=s&&bY(b,["instances[0]","lastFrame"],ds(s));let t=bZ(a,["referenceImages"]);if(void 0!==b&&null!=t){let a=t;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e;return c={},null!=(d=bZ(b=a,["image"]))&&bY(c,["image"],ds(d)),null!=(e=bZ(b,["referenceType"]))&&bY(c,["referenceType"],e),c})),bY(b,["instances[0]","referenceImages"],a)}let u=bZ(a,["mask"]);void 0!==b&&null!=u&&bY(b,["instances[0]","mask"],(d={},null!=(e=bZ(c=u,["image"]))&&bY(d,["_self"],ds(e)),null!=(f=bZ(c,["maskMode"]))&&bY(d,["maskMode"],f),d));let v=bZ(a,["compressionQuality"]);void 0!==b&&null!=v&&bY(b,["parameters","compressionQuality"],v);let w=bZ(a,["labels"]);if(void 0!==b&&null!=w&&bY(b,["labels"],w),void 0!==bZ(a,["webhookConfig"]))throw Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let x=bZ(a,["resizeMode"]);void 0!==b&&null!=x&&bY(b,["parameters","resizeMode"],x)}(r,j),j);return l=bX("{model}:predictLongRunning",s._url),m=s._query,delete s._url,delete s._query,this.apiClient.request({path:l,queryParams:m,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b,c,d,e,f,g,h=(b={},null!=(c=bZ(a,["name"]))&&bY(b,["name"],c),null!=(d=bZ(a,["metadata"]))&&bY(b,["metadata"],d),null!=(e=bZ(a,["done"]))&&bY(b,["done"],e),null!=(f=bZ(a,["error"]))&&bY(b,["error"],f),null!=(g=bZ(a,["response"]))&&bY(b,["response"],function(a){let b={},c=bZ(a,["videos"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h;return c={},null!=(d=bZ(a,["_self"]))&&bY(c,["video"],(e={},null!=(f=bZ(b=d,["gcsUri"]))&&bY(e,["uri"],f),null!=(g=bZ(b,["bytesBase64Encoded"]))&&bY(e,["videoBytes"],b$(g)),null!=(h=bZ(b,["mimeType"]))&&bY(e,["mimeType"],h),e)),c})),bY(b,["generatedVideos"],a)}let d=bZ(a,["raiMediaFilteredCount"]);null!=d&&bY(b,["raiMediaFilteredCount"],d);let e=bZ(a,["raiMediaFilteredReasons"]);return null!=e&&bY(b,["raiMediaFilteredReasons"],e),b}(g)),b),i=new cc;return Object.assign(i,h),i})}{let b,c,f,h,i,n,o,p,q,r,s=(g=this.apiClient,h={},null!=(i=bZ(a,["model"]))&&bY(h,["_url","model"],cu(g,i)),null!=(n=bZ(a,["prompt"]))&&bY(h,["instances[0]","prompt"],n),null!=(o=bZ(a,["image"]))&&bY(h,["instances[0]","image"],dr(o)),null!=(p=bZ(a,["video"]))&&bY(h,["instances[0]","video"],dz(p)),null!=(q=bZ(a,["source"]))&&(j=q,k=h,b=bZ(j,["prompt"]),void 0!==k&&null!=b&&bY(k,["instances[0]","prompt"],b),c=bZ(j,["image"]),void 0!==k&&null!=c&&bY(k,["instances[0]","image"],dr(c)),f=bZ(j,["video"]),void 0!==k&&null!=f&&bY(k,["instances[0]","video"],dz(f))),null!=(r=bZ(a,["config"]))&&function(a,b){let c=bZ(a,["numberOfVideos"]);if(void 0!==b&&null!=c&&bY(b,["parameters","sampleCount"],c),void 0!==bZ(a,["outputGcsUri"]))throw Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["fps"]))throw Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["durationSeconds"]);if(void 0!==b&&null!=d&&bY(b,["parameters","durationSeconds"],d),void 0!==bZ(a,["seed"]))throw Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let e=bZ(a,["aspectRatio"]);void 0!==b&&null!=e&&bY(b,["parameters","aspectRatio"],e);let f=bZ(a,["resolution"]);void 0!==b&&null!=f&&bY(b,["parameters","resolution"],f);let g=bZ(a,["personGeneration"]);if(void 0!==b&&null!=g&&bY(b,["parameters","personGeneration"],g),void 0!==bZ(a,["pubsubTopic"]))throw Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let h=bZ(a,["negativePrompt"]);void 0!==b&&null!=h&&bY(b,["parameters","negativePrompt"],h);let i=bZ(a,["enhancePrompt"]);if(void 0!==b&&null!=i&&bY(b,["parameters","enhancePrompt"],i),void 0!==bZ(a,["generateAudio"]))throw Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["lastFrame"]);void 0!==b&&null!=j&&bY(b,["instances[0]","lastFrame"],dr(j));let k=bZ(a,["referenceImages"]);if(void 0!==b&&null!=k){let a=k;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e;return c={},null!=(d=bZ(b=a,["image"]))&&bY(c,["image"],dr(d)),null!=(e=bZ(b,["referenceType"]))&&bY(c,["referenceType"],e),c})),bY(b,["instances[0]","referenceImages"],a)}if(void 0!==bZ(a,["mask"]))throw Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["compressionQuality"]))throw Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["labels"]))throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let l=bZ(a,["webhookConfig"]);if(void 0!==b&&null!=l&&bY(b,["webhookConfig"],l),void 0!==bZ(a,["resizeMode"]))throw Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(r,h),h);return l=bX("{model}:predictLongRunning",s._url),m=s._query,delete s._url,delete s._query,this.apiClient.request({path:l,queryParams:m,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json()).then(a=>{let b,c,d,e,f,g,h=(b={},null!=(c=bZ(a,["name"]))&&bY(b,["name"],c),null!=(d=bZ(a,["metadata"]))&&bY(b,["metadata"],d),null!=(e=bZ(a,["done"]))&&bY(b,["done"],e),null!=(f=bZ(a,["error"]))&&bY(b,["error"],f),null!=(g=bZ(a,["response","generateVideoResponse"]))&&bY(b,["response"],function(a){let b={},c=bZ(a,["generatedSamples"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h;return c={},null!=(d=bZ(a,["video"]))&&bY(c,["video"],(e={},null!=(f=bZ(b=d,["uri"]))&&bY(e,["uri"],f),null!=(g=bZ(b,["encodedVideo"]))&&bY(e,["videoBytes"],b$(g)),null!=(h=bZ(b,["encoding"]))&&bY(e,["mimeType"],h),e)),c})),bY(b,["generatedVideos"],a)}let d=bZ(a,["raiMediaFilteredCount"]);null!=d&&bY(b,["raiMediaFilteredCount"],d);let e=bZ(a,["raiMediaFilteredReasons"]);return null!=e&&bY(b,["raiMediaFilteredReasons"],e),b}(g)),b),i=new cc;return Object.assign(i,h),i})}}}dW.loggedGenerateImagesWarning=!1,dW.loggedEditImageWarning=!1,dW.loggedGenerateVideosWarning=!1;class dX extends bW{constructor(a){super(),this.apiClient=a}async getVideosOperation(a){let b=a.operation,c=a.config;if(void 0===b.name||""===b.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let a,d=b.name.split("/operations/")[0];c&&"httpOptions"in c&&(a=c.httpOptions);let e=await this.fetchPredictVideosOperationInternal({operationName:b.name,resourceName:d,config:{httpOptions:a}});return b._fromAPIResponse({apiResponse:e,_isVertexAI:!0})}{let a=await this.getVideosOperationInternal({operationName:b.name,config:c});return b._fromAPIResponse({apiResponse:a,_isVertexAI:!1})}}async get(a){let b=a.operation,c=a.config;if(void 0===b.name||""===b.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let a,d=b.name.split("/operations/")[0];c&&"httpOptions"in c&&(a=c.httpOptions);let e=await this.fetchPredictVideosOperationInternal({operationName:b.name,resourceName:d,config:{httpOptions:a}});return b._fromAPIResponse({apiResponse:e,_isVertexAI:!0})}{let a=await this.getVideosOperationInternal({operationName:b.name,config:c});return b._fromAPIResponse({apiResponse:a,_isVertexAI:!1})}}async getVideosOperationInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d,e,h=(d={},null!=(e=bZ(a,["operationName"]))&&bY(d,["_url","operationName"],e),d);return f=bX("{operationName}",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json())}{let b,c,h=(b={},null!=(c=bZ(a,["operationName"]))&&bY(b,["_url","operationName"],c),b);return f=bX("{operationName}",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json())}}async fetchPredictVideosOperationInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f,g,h,i=(f={},null!=(g=bZ(a,["operationName"]))&&bY(f,["operationName"],g),null!=(h=bZ(a,["resourceName"]))&&bY(f,["_url","resourceName"],h),f);return d=bX("{resourceName}:fetchPredictOperation",i._url),e=i._query,delete i._url,delete i._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json())}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}class dY extends bW{constructor(a){super(),this.apiClient=a}async create(a){var b,c,d,e,f;let g="",h={};if(this.apiClient.isVertexAI())throw Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let i,j,k,l,m,n,o,p,q,r,s=(d=this.apiClient,l={},null!=(m=bZ(a,["config"]))&&bY(l,["config"],(n=bZ(m,["expireTime"]),void 0!==l&&null!=n&&bY(l,["expireTime"],n),o=bZ(m,["newSessionExpireTime"]),void 0!==l&&null!=o&&bY(l,["newSessionExpireTime"],o),p=bZ(m,["uses"]),void 0!==l&&null!=p&&bY(l,["uses"],p),q=bZ(m,["liveConnectConstraints"]),void 0!==l&&null!=q&&bY(l,["bidiGenerateContentSetup"],(e=d,i={},null!=(j=bZ(f=q,["model"]))&&bY(i,["setup","model"],cu(e,j)),null!=(k=bZ(f,["config"]))&&bY(i,["config"],function(a,b){let c=bZ(a,["generationConfig"]);void 0!==b&&null!=c&&bY(b,["setup","generationConfig"],c);let d=bZ(a,["responseModalities"]);void 0!==b&&null!=d&&bY(b,["setup","generationConfig","responseModalities"],d);let e=bZ(a,["temperature"]);void 0!==b&&null!=e&&bY(b,["setup","generationConfig","temperature"],e);let f=bZ(a,["topP"]);void 0!==b&&null!=f&&bY(b,["setup","generationConfig","topP"],f);let g=bZ(a,["topK"]);void 0!==b&&null!=g&&bY(b,["setup","generationConfig","topK"],g);let h=bZ(a,["maxOutputTokens"]);void 0!==b&&null!=h&&bY(b,["setup","generationConfig","maxOutputTokens"],h);let i=bZ(a,["mediaResolution"]);void 0!==b&&null!=i&&bY(b,["setup","generationConfig","mediaResolution"],i);let j=bZ(a,["seed"]);void 0!==b&&null!=j&&bY(b,["setup","generationConfig","seed"],j);let k=bZ(a,["speechConfig"]);void 0!==b&&null!=k&&bY(b,["setup","generationConfig","speechConfig"],cK(k));let l=bZ(a,["thinkingConfig"]);void 0!==b&&null!=l&&bY(b,["setup","generationConfig","thinkingConfig"],l);let m=bZ(a,["enableAffectiveDialog"]);void 0!==b&&null!=m&&bY(b,["setup","generationConfig","enableAffectiveDialog"],m);let n=bZ(a,["systemInstruction"]);void 0!==b&&null!=n&&bY(b,["setup","systemInstruction"],function(a){let b={},c=bZ(a,["parts"]);if(null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;return c={},null!=(d=bZ(b=a,["mediaResolution"]))&&bY(c,["mediaResolution"],d),null!=(e=bZ(b,["toolCall"]))&&bY(c,["toolCall"],e),null!=(f=bZ(b,["toolResponse"]))&&bY(c,["toolResponse"],f),null!=(g=bZ(b,["audioTranscription"]))&&bY(c,["audioTranscription"],g),null!=(h=bZ(b,["codeExecutionResult"]))&&bY(c,["codeExecutionResult"],h),null!=(i=bZ(b,["executableCode"]))&&bY(c,["executableCode"],i),null!=(j=bZ(b,["fileData"]))&&bY(c,["fileData"],function(a){let b={};if(void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["fileUri"]);null!=c&&bY(b,["fileUri"],c);let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(j)),null!=(k=bZ(b,["functionCall"]))&&bY(c,["functionCall"],function(a){let b={},c=bZ(a,["args"]);null!=c&&bY(b,["args"],c);let d=bZ(a,["id"]);null!=d&&bY(b,["id"],d);let e=bZ(a,["name"]);if(null!=e&&bY(b,["name"],e),void 0!==bZ(a,["partialArgs"]))throw Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["willContinue"]))throw Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(k)),null!=(l=bZ(b,["functionResponse"]))&&bY(c,["functionResponse"],l),null!=(m=bZ(b,["inlineData"]))&&bY(c,["inlineData"],function(a){let b={},c=bZ(a,["data"]);if(null!=c&&bY(b,["data"],c),void 0!==bZ(a,["displayName"]))throw Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["mimeType"]);return null!=d&&bY(b,["mimeType"],d),b}(m)),null!=(n=bZ(b,["text"]))&&bY(c,["text"],n),null!=(o=bZ(b,["thought"]))&&bY(c,["thought"],o),null!=(p=bZ(b,["thoughtSignature"]))&&bY(c,["thoughtSignature"],p),null!=(q=bZ(b,["videoMetadata"]))&&bY(c,["videoMetadata"],q),null!=(r=bZ(b,["partMetadata"]))&&bY(c,["partMetadata"],r),c})),bY(b,["parts"],a)}let d=bZ(a,["role"]);return null!=d&&bY(b,["role"],d),b}(cF(n)));let o=bZ(a,["tools"]);if(void 0!==b&&null!=o){let a=cM(o);Array.isArray(a)&&(a=a.map(a=>(function(a){let b={};if(void 0!==bZ(a,["retrieval"]))throw Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["googleMaps"]);null!=c&&bY(b,["googleMaps"],function(a){let b={},c=bZ(a,["authConfig"]);null!=c&&bY(b,["authConfig"],function(a){let b={},c=bZ(a,["apiKey"]);if(null!=c&&bY(b,["apiKey"],c),void 0!==bZ(a,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["authType"]))throw Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oauthConfig"]))throw Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["oidcConfig"]))throw Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["enableWidget"]);if(null!=d&&bY(b,["enableWidget"],d),void 0!==bZ(a,["groundingTypes"]))throw Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(c));let d=bZ(a,["mcpServers"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["mcpServers"],a)}let e=bZ(a,["codeExecution"]);null!=e&&bY(b,["codeExecution"],e);let f=bZ(a,["computerUse"]);if(null!=f&&bY(b,["computerUse"],f),void 0!==bZ(a,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["exaAiSearch"]))throw Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let g=bZ(a,["functionDeclarations"]);if(null!=g){let a=g;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["functionDeclarations"],a)}let h=bZ(a,["googleSearch"]);null!=h&&bY(b,["googleSearch"],function(a){let b={};if(void 0!==bZ(a,["blockingConfidence"]))throw Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["excludeDomains"]))throw Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["searchTypes"]);null!=c&&bY(b,["searchTypes"],c);let d=bZ(a,["timeRangeFilter"]);return null!=d&&bY(b,["timeRangeFilter"],d),b}(h));let i=bZ(a,["googleSearchRetrieval"]);if(null!=i&&bY(b,["googleSearchRetrieval"],i),void 0!==bZ(a,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let j=bZ(a,["urlContext"]);null!=j&&bY(b,["urlContext"],j);let k=bZ(a,["fileSearch"]);return null!=k&&bY(b,["fileSearch"],k),b})(cL(a)))),bY(b,["setup","tools"],a)}let p=bZ(a,["sessionResumption"]);void 0!==b&&null!=p&&bY(b,["setup","sessionResumption"],function(a){let b={},c=bZ(a,["handle"]);if(null!=c&&bY(b,["handle"],c),void 0!==bZ(a,["transparent"]))throw Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return b}(p));let q=bZ(a,["inputAudioTranscription"]);void 0!==b&&null!=q&&bY(b,["setup","inputAudioTranscription"],q);let r=bZ(a,["outputAudioTranscription"]);void 0!==b&&null!=r&&bY(b,["setup","outputAudioTranscription"],r);let s=bZ(a,["realtimeInputConfig"]);void 0!==b&&null!=s&&bY(b,["setup","realtimeInputConfig"],s);let t=bZ(a,["contextWindowCompression"]);void 0!==b&&null!=t&&bY(b,["setup","contextWindowCompression"],t);let u=bZ(a,["proactivity"]);if(void 0!==b&&null!=u&&bY(b,["setup","proactivity"],u),void 0!==bZ(a,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let v=bZ(a,["avatarConfig"]);void 0!==b&&null!=v&&bY(b,["setup","avatarConfig"],v);let w=bZ(a,["safetySettings"]);if(void 0!==b&&null!=w){let a=w;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["category"]);if(null!=c&&bY(b,["category"],c),void 0!==bZ(a,["method"]))throw Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["threshold"]);return null!=d&&bY(b,["threshold"],d),b})(a))),bY(b,["setup","safetySettings"],a)}let x=bZ(a,["translationConfig"]);return void 0!==b&&null!=x&&bY(b,["setup","generationConfig","translationConfig"],x),{}}(k,i)),i)),r=bZ(m,["lockAdditionalFields"]),void 0!==l&&null!=r&&bY(l,["fieldMask"],r),{})),l);g=bX("auth_tokens",s._url),h=s._query,delete s.config,delete s._url,delete s._query;let t=function(a,b){let c=null,d=a.bidiGenerateContentSetup;if("object"==typeof d&&null!==d&&"setup"in d){let b=d.setup;"object"==typeof b&&null!==b?(a.bidiGenerateContentSetup=b,c=b):delete a.bidiGenerateContentSetup}else void 0!==d&&delete a.bidiGenerateContentSetup;let e=a.fieldMask;if(c){let d=function(a){let b=[];for(let c in a)if(Object.prototype.hasOwnProperty.call(a,c)){let d=a[c];if("object"==typeof d&&null!=d&&Object.keys(d).length>0){let a=Object.keys(d).map(a=>`${c}.${a}`);b.push(...a)}else b.push(c)}return b.join(",")}(c);if(Array.isArray(null==b?void 0:b.lockAdditionalFields)&&(null==b?void 0:b.lockAdditionalFields.length)===0)d?a.fieldMask=d:delete a.fieldMask;else if((null==b?void 0:b.lockAdditionalFields)&&b.lockAdditionalFields.length>0&&null!==e&&Array.isArray(e)&&e.length>0){let b=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],c=[];e.length>0&&(c=e.map(a=>b.includes(a)?`generationConfig.${a}`:a));let f=[];d&&f.push(d),c.length>0&&f.push(...c),f.length>0?a.fieldMask=f.join(","):delete a.fieldMask}else delete a.fieldMask}else null!==e&&Array.isArray(e)&&e.length>0?a.fieldMask=e.join(","):delete a.fieldMask;return a}(s,a.config);return this.apiClient.request({path:g,queryParams:h,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}}}class dZ extends bW{constructor(a){super(),this.apiClient=a,this.list=async a=>new c0(bM.PAGED_ITEM_DOCUMENTS,b=>this.listInternal({parent:a.parent,config:b.config}),await this.listInternal(a),a)}async get(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","name"],g),f);return d=bX("{name}",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}}async delete(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","name"],g),null!=(h=bZ(a,["config"]))&&(i=bZ(h,["force"]),void 0!==f&&null!=i&&bY(f,["_query","force"],i)),f);d=bX("{name}",j._url),e=j._query,delete j._url,delete j._query,await this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(j),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal})}}async listInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j,k=(f={},null!=(g=bZ(a,["parent"]))&&bY(f,["_url","parent"],g),null!=(h=bZ(a,["config"]))&&(i=bZ(h,["pageSize"]),void 0!==f&&null!=i&&bY(f,["_query","pageSize"],i),j=bZ(h,["pageToken"]),void 0!==f&&null!=j&&bY(f,["_query","pageToken"],j)),f);return d=bX("{parent}/documents",k._url),e=k._query,delete k._url,delete k._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(k),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["documents"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["documents"],a)}return b}(a),c=new ci;return Object.assign(c,b),c})}}}class d$ extends bW{constructor(a,b=new dZ(a)){super(),this.apiClient=a,this.documents=b,this.list=async(a={})=>new c0(bM.PAGED_ITEM_FILE_SEARCH_STORES,a=>this.listInternal(a),await this.listInternal(a),a)}async uploadToFileSearchStore(a){if(this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(a.fileSearchStoreName,a.file,a.config)}async downloadMedia(a,b){if(this.apiClient.isVertexAI())throw Error("This method is only supported in the Gemini Developer client.");let c=new URL(a,"http://dummy.com"),d=c.pathname;if(d.startsWith("/")&&(d=d.slice(1)),!d.includes("/media/"))throw Error(`Invalid uri format: ${a}. Expected to contain /media/`);let e={};c.searchParams.forEach((a,b)=>{e[b]=a}),e.alt="media";let f=Object.assign({},null==b?void 0:b.httpOptions),g=await this.apiClient.request({path:d,httpMethod:"GET",queryParams:e,httpOptions:f});if(g instanceof b0)return new Uint8Array(await g.responseInternal.arrayBuffer());throw Error("Unexpected response type from downloadMedia")}async create(a){var b,c,d;let e="",f={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let g,h,i,j,k=(d=this.apiClient,g={},null!=(h=bZ(a,["config"]))&&(i=bZ(h,["displayName"]),void 0!==g&&null!=i&&bY(g,["displayName"],i),j=bZ(h,["embeddingModel"]),void 0!==g&&null!=j&&bY(g,["embeddingModel"],cu(d,j))),g);return e=bX("fileSearchStores",k._url),f=k._query,delete k._url,delete k._query,this.apiClient.request({path:e,queryParams:f,body:JSON.stringify(k),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}}async get(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","name"],g),f);return d=bX("{name}",h._url),e=h._query,delete h._url,delete h._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>a)}}async delete(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j=(f={},null!=(g=bZ(a,["name"]))&&bY(f,["_url","name"],g),null!=(h=bZ(a,["config"]))&&(i=bZ(h,["force"]),void 0!==f&&null!=i&&bY(f,["_query","force"],i)),f);d=bX("{name}",j._url),e=j._query,delete j._url,delete j._query,await this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(j),httpMethod:"DELETE",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal})}}async listInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j=(f={},null!=(g=bZ(a,["config"]))&&(h=bZ(g,["pageSize"]),void 0!==f&&null!=h&&bY(f,["_query","pageSize"],h),i=bZ(g,["pageToken"]),void 0!==f&&null!=i&&bY(f,["_query","pageToken"],i)),f);return d=bX("fileSearchStores",j._url),e=j._query,delete j._url,delete j._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(j),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["fileSearchStores"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["fileSearchStores"],a)}return b}(a),c=new cj;return Object.assign(c,b),c})}}async uploadToFileSearchStoreInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i=(f={},null!=(g=bZ(a,["fileSearchStoreName"]))&&bY(f,["_url","file_search_store_name"],g),null!=(h=bZ(a,["config"]))&&dC(h,f),f);return d=bX("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",i._url),e=i._query,delete i._url,delete i._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new ck;return Object.assign(e,d),e})}}async importFile(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j=(f={},null!=(g=bZ(a,["fileSearchStoreName"]))&&bY(f,["_url","file_search_store_name"],g),null!=(h=bZ(a,["fileName"]))&&bY(f,["fileName"],h),null!=(i=bZ(a,["config"]))&&function(a,b){let c=bZ(a,["customMetadata"]);if(void 0!==b&&null!=c){let a=c;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["customMetadata"],a)}let d=bZ(a,["chunkingConfig"]);void 0!==b&&null!=d&&bY(b,["chunkingConfig"],d)}(i,f),f);return d=bX("{file_search_store_name}:importFile",j._url),e=j._query,delete j._url,delete j._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(j),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json()).then(a=>{var b;let c,d,e,f,g,h,i,j,k,l,m=(g={},null!=(h=bZ(a,["name"]))&&bY(g,["name"],h),null!=(i=bZ(a,["metadata"]))&&bY(g,["metadata"],i),null!=(j=bZ(a,["done"]))&&bY(g,["done"],j),null!=(k=bZ(a,["error"]))&&bY(g,["error"],k),null!=(l=bZ(a,["response"]))&&bY(g,["response"],(c={},null!=(d=bZ(b=l,["sdkHttpResponse"]))&&bY(c,["sdkHttpResponse"],d),null!=(e=bZ(b,["parent"]))&&bY(c,["parent"],e),null!=(f=bZ(b,["documentName"]))&&bY(c,["documentName"],f),c)),g),n=new cl;return Object.assign(n,m),n})}}}function d_(){var a,b,c,d,e,g;if(f)return f;let h=globalThis;return f=("Deno"in globalThis?0:1)?null!=(g=null==(e=h.process)?void 0:e.env)?g:{}:null!=(d=null==(c=null==(b=null==(a=h.Deno)?void 0:a.env)?void 0:b.toObject)?void 0:c.call(b))?d:{}}class d0{constructor(a){this.options=a}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(a){return function(a){var b,c;let d={};for(let[b,c]of a){let a=b.toLowerCase();"authorization"!==a&&"x-goog-api-key"!==a&&(d[b]=c)}let e={access_token:null!=(b=a.get("authorization"))?b:void 0,api_key:null!=(c=a.get("x-goog-api-key"))?c:void 0,default_headers:Object.keys(d).length?d:void 0};return d7(e)?e:void 0}(await this.options.getAuthHeaders(a))}}class d1{beforeCreateRequest(a,b){return Object.assign(Object.assign({},b),{url:function(a){let[,b,...c]=a.pathname.split("/");if(!b)return a;let d=decodeURIComponent(b);if(!d.includes("/"))return a;let e=new URL(a);return e.pathname=`/${d}/${c.join("/")}`,e}(b.url)})}async beforeRequest(a,b){var c,d,e,f,g,h;if(d4(b.headers,d6(c=a.security_source)?null!=(e=null==(d=c.getDefaultHeaders)?void 0:d.call(c))?e:c.defaultHeaders:d5(c)?c.default_headers:void 0),f=a,g=b.headers,void 0!==f.options.user_project&&null===g.get("x-goog-user-project")&&g.set("x-goog-user-project",f.options.user_project),null!==(h=b.headers).get("authorization")||null!==h.get("x-goog-api-key"))return b;let i=await d2(a.security_source,b.url);return d4(b.headers,null==i?void 0:i.default_headers),function(a,b){if(b){var c;if(b.api_key)return a.set("x-goog-api-key",b.api_key);b.access_token&&a.set("Authorization","bearer "===(c=b.access_token).slice(0,7).toLowerCase()?c:`Bearer ${c}`)}}(b.headers,i),b}}async function d2(a,b){if(d6(a))return a.resolveGoogleGenAISecurity(b);let c="function"==typeof a?await a():a;return d5(c)?d3(c):d3(void 0)}function d3(a){var b,c;let d=d_(),e=Object.assign(Object.assign({},a),{api_key:null!=(b=null==a?void 0:a.api_key)?b:d.GOOGLE_GENAI_API_KEY,access_token:null!=(c=null==a?void 0:a.access_token)?c:d.GOOGLE_GENAI_ACCESS_TOKEN});return d7(e)?e:void 0}function d4(a,b){if(b)for(let[c,d]of new Headers(b))null===a.get(c)&&a.set(c,d)}function d5(a){return"object"==typeof a&&null!==a}function d6(a){return"object"==typeof a&&null!==a&&"resolveGoogleGenAISecurity"in a&&"function"==typeof a.resolveGoogleGenAISecurity}function d7(a){return void 0!==a.api_key||void 0!==a.access_token||void 0!==a.default_headers}class d8 extends Error{constructor(a,b){let c=a;(null==b?void 0:b.cause)&&(c+=`: ${b.cause}`),super(c,b),this.name="HTTPClientError",void 0===this.cause&&(this.cause=null==b?void 0:b.cause)}}class d9 extends d8{constructor(){super(...arguments),this.name="UnexpectedClientError"}}class ea extends d8{constructor(){super(...arguments),this.name="InvalidRequestError"}}class eb extends d8{constructor(){super(...arguments),this.name="RequestAbortedError"}}class ec extends d8{constructor(){super(...arguments),this.name="RequestTimeoutError"}}class ed extends d8{constructor(){super(...arguments),this.name="ConnectionError"}}class ee extends Error{constructor(a,b){var c,d,e,f;super(a),this.statusCode=null==(c=null==b?void 0:b.response)?void 0:c.status,this.body=null!=(d=null==b?void 0:b.body)?d:"",this.headers=null==(e=null==b?void 0:b.response)?void 0:e.headers,this.contentType=(null==(f=null==b?void 0:b.response)?void 0:f.headers.get("content-type"))||"",this.rawResponse=null==b?void 0:b.response,this.name="GoogleGenAiError"}}class ef extends Error{}class eg extends ef{constructor(a,b,c,d){super(eg.makeMessage(a,b,c)),this.status=a,this.headers=d,this.error=b,this.statusCode=a,this.body=eu(b),this.contentType=(null==d?void 0:d.get("content-type"))||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(a,b,c){var d,e;let f=b&&null!==(e=b)&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof b.message?b.message:void 0,g=eu(b),h=null!=(d=null!=f?f:c)?d:g||"An error occurred",i=a?`${a} `:"";return`${i}${h}`}static generate(a,b,c,d){return a&&d?400===a?new ek(a,b,c,d):401===a?new el(a,b,c,d):403===a?new em(a,b,c,d):404===a?new en(a,b,c,d):409===a?new eo(a,b,c,d):422===a?new ep(a,b,c,d):429===a?new eq(a,b,c,d):a>=500?new er(a,b,c,d):new eg(a,b,c,d):new ei({message:c,cause:b instanceof Error?b:void 0})}}class eh extends eg{constructor({message:a}={}){super(void 0,void 0,a||"Request was aborted.",void 0)}}class ei extends eg{constructor({message:a,cause:b}){super(void 0,void 0,a||"Connection error.",void 0),this.cause=b}}class ej extends ei{constructor({message:a}={}){super({message:a||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}}class ek extends eg{}class el extends eg{}class em extends eg{}class en extends eg{}class eo extends eg{}class ep extends eg{}class eq extends eg{}class er extends eg{}function es(a){var b,c,d;let e,f;return"object"==typeof(b=a)&&null!==b&&eg.prototype.isPrototypeOf(b)?a:a instanceof ee?(e=function(a){let b=et(a,"data$");if(b&&"object"==typeof b)return b;try{let b=JSON.parse(a.body);if(b&&"object"==typeof b)return b}catch(a){}let c=et(a,"error");return c&&"object"==typeof c?c:void 0}(c=a),ev(f=eg.generate(c.statusCode,e,c.message,c.headers),"body",c.body),ev(f,"contentType",c.contentType),ev(f,"rawResponse",c.rawResponse),ev(f,"statusCode",c.statusCode),ev(f,"cause",c),f):a instanceof d8?(d=a)instanceof ec?new ej({message:d.message}):d instanceof eb?new eh({message:d.message}):(d instanceof ed,new ei({message:d.message,cause:d})):a}function et(a,b){return a&&"object"==typeof a?a[b]:void 0}function eu(a){if(!a)return"";try{return JSON.stringify(a)}catch(b){return String(a)}}function ev(a,b,c){Object.defineProperty(a,b,{configurable:!0,enumerable:!0,value:c,writable:!1})}class ew{constructor(){for(const a of(this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[],[]))"sdkInit"in a&&this.registerSDKInitHook(a),"beforeCreateRequest"in a&&this.registerBeforeCreateRequestHook(a),"beforeRequest"in a&&this.registerBeforeRequestHook(a),"afterSuccess"in a&&this.registerAfterSuccessHook(a),"afterError"in a&&this.registerAfterErrorHook(a);!function(a){let b=new d1;a.registerBeforeCreateRequestHook(b),a.registerBeforeRequestHook(b)}(this)}registerSDKInitHook(a){this.sdkInitHooks.push(a)}registerBeforeCreateRequestHook(a){this.beforeCreateRequestHooks.push(a)}registerBeforeRequestHook(a){this.beforeRequestHooks.push(a)}registerAfterSuccessHook(a){this.afterSuccessHooks.push(a)}registerAfterErrorHook(a){this.afterErrorHooks.push(a)}sdkInit(a){return this.sdkInitHooks.reduce((a,b)=>b.sdkInit(a),a)}beforeCreateRequest(a,b){let c=b;for(let b of this.beforeCreateRequestHooks)c=b.beforeCreateRequest(a,c);return c}async beforeRequest(a,b){let c=b;for(let b of this.beforeRequestHooks)c=await b.beforeRequest(a,c);return c}async afterSuccess(a,b){let c=b;for(let b of this.afterSuccessHooks)c=await b.afterSuccess(a,c);return c}async afterError(a,b,c){let d=b,e=c;for(let b of this.afterErrorHooks){let c=await b.afterError(a,d,e);d=c.response,e=c.error}return{response:d,error:e}}}function ex(a){return{ok:!0,value:a}}function ey(a){return{ok:!1,error:a}}function ez(a){return btoa(String.fromCodePoint(...a))}let eA=Object.prototype.hasOwnProperty;function eB(a,b){let c=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(b={}){return a.replace(c,function(a,c){if(!eA.call(b,c))throw Error(`Parameter '${c}' is required`);let d=b[c];if("string"!=typeof d&&"number"!=typeof d)throw Error(`Parameter '${c}' must be a string or number`);return`${d}`}).replace(/^\/+/,"")}}let eC=["https://generativelanguage.googleapis.com"];function eD(a){let b={};for(let[c,d]of Object.entries(a))void 0!==d&&(b[c]=d);return b}function eE(a){if(null===a||"object"!=typeof a||"[object Object]"!==Object.prototype.toString.call(a))return!1;let b=Object.getPrototypeOf(a);if(null===b||b===Object.prototype)return!0;try{return null===Object.getPrototypeOf(b)}catch(a){return!1}}let eF=(a,b,c)=>{let d="",e=(null==c?void 0:c.explode)?eI(a,b):[[a,b]];if(e.every(([a,b])=>null==b))return;let f=a=>(null==c?void 0:c.charEncoding)==="percent"?encodeURIComponent(a):a,g=f(",");return e.forEach(([a,b])=>{var c,e;let h="",i=null;null!=b&&(null==(i=Array.isArray(b)?null==(c=eL(b,a=>`${f(eJ(a))}`))?void 0:c.join(g):eE(b)?null==(e=eM(Object.entries(b),([a,b])=>`${f(a)}${g}${f(eJ(b))}`))?void 0:e.join(g):`${f(eJ(b))}`)||(h=`${f(a)}=${i}`)&&"="!==h&&(d+=`&${h}`))}),d.slice(1)};function eG(a,b,c){if(void 0===b)return;let d=a=>(null==c?void 0:c.charEncoding)==="percent"?encodeURIComponent(a):a,e=d(JSON.stringify(b,eK));return(null==c?void 0:c.explode)?e:`${d(a)}=${e}`}let eH=(a,b,c)=>{let d="",e=(null==c?void 0:c.explode)?eI(a,b):[[a,b]];if(e.every(([a,b])=>null==b))return;let f=a=>(null==c?void 0:c.charEncoding)==="percent"?encodeURIComponent(a):a;return e.forEach(([a,e])=>{var g;let h="";if(null!=e){if(Array.isArray(e))h=null==(g=eL(e,a=>`${f(eJ(a))}`))?void 0:g.join(",");else if(eE(e)){let a=eM(Object.entries(e),([a,b])=>`,${f(a)},${f(eJ(b))}`);h=null==a?void 0:a.join("").slice(1)}else{let d=(null==c?void 0:c.explode)&&eE(b)?`${a}=`:"";h=`${d}${f(eJ(e))}`}d+=h?`,${h}`:""}}),d.slice(1)};function eI(a,b){return Array.isArray(b)?b.map(b=>[a,b]):eE(b)?Object.entries(null!=b?b:{}).map(([a,b])=>[a,b]):[[a,b]]}function eJ(a){return null==a?"":a instanceof Date?a.toISOString():a instanceof Uint8Array?ez(a):"object"==typeof a?JSON.stringify(a,eK):`${a}`}function eK(a,b){return b instanceof Uint8Array?ez(b):b}function eL(a,b){let c=a.reduce((a,c)=>{if(null==c)return a;let d=b(c);return null==d||a.push(d),a},[]);return c.length?c:null}function eM(a,b){let c=[];for(let[d,e]of a){if(null==e)continue;let a=b([d,e]);null!=a&&c.push(a)}return c.length?c:null}let eN=function(a,b){var c,d,e;let f=Object.assign(Object.assign({},b),{explode:null==(c=null==b?void 0:b.explode)||c,charEncoding:null!=(d=null==b?void 0:b.charEncoding)?d:"percent"}),g=new Set(null!=(e=null==b?void 0:b.allowEmptyValue)?e:[]);return function(...a){return a.filter(Boolean).join("&")}(...Object.entries(a).map(([a,b])=>g.has(a)&&(null==b||""===b||Array.isArray(b)&&0===b.length)?`${encodeURIComponent(a)}=`:eF(a,b,f)))},eO=(a,b)=>null==b?fetch(a):fetch(a,b);class eP{constructor(a={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=a,this.fetcher=a.fetcher||eO}async request(a){let b=a;for(let a of this.requestHooks){let c=await a(b);c&&(b=c)}try{let a=await this.fetcher(b);for(let c of this.responseHooks)await c(a,b);return a}catch(a){for(let c of this.requestErrorHooks)await c(a,b);throw a}}addHook(...a){if("beforeRequest"===a[0])this.requestHooks.push(a[1]);else if("requestError"===a[0])this.requestErrorHooks.push(a[1]);else if("response"===a[0])this.responseHooks.push(a[1]);else throw Error(`Invalid hook type: ${a[0]}`);return this}removeHook(...a){let b;if("beforeRequest"===a[0])b=this.requestHooks;else if("requestError"===a[0])b=this.requestErrorHooks;else if("response"===a[0])b=this.responseHooks;else throw Error(`Invalid hook type: ${a[0]}`);let c=b.findIndex(b=>b===a[1]);return c>=0&&b.splice(c,1),this}clone(){let a=new eP(this.options);return a.requestHooks=this.requestHooks.slice(),a.requestErrorHooks=this.requestErrorHooks.slice(),a.responseHooks=this.responseHooks.slice(),a}}let eQ=/\s*;\s*/g;function eR(a,b){var c;if("*"===b)return!0;let d=(null==(c=a.headers.get("content-type"))?void 0:c.trim())||"application/octet-stream";d=d.toLowerCase();let[e="",...f]=b.toLowerCase().trim().split(eQ);if(2!==e.split("/").length)return!1;let[g="",...h]=d.split(eQ),[i="",j=""]=g.split("/");if(!i||!j||"*/*"!==e&&g!==e&&`${i}/*`!==e&&`*/${j}`!==e||h.length<f.length)return!1;let k=new Set(h);for(let a of f)if(!k.has(a))return!1;return!0}let eS=RegExp("^[0-9]xx$","i");function eT(a,b){let c=`${a.status}`,d=Array.isArray(b)?b:[b];return!!d.length&&d.some(a=>{let b=`${a}`;if("default"===b)return!0;if(!eS.test(`${b}`))return b===c;let d=b.charAt(0);if(!d)throw Error("Invalid status code range");let e=c.charAt(0);if(!e)throw Error(`Invalid response status code: ${c}`);return e===d})}function eU(a){if("object"!=typeof a||null==a)return!1;let b=a instanceof TypeError&&a.message.toLowerCase().startsWith("failed to fetch"),c=a instanceof TypeError&&a.message.toLowerCase().startsWith("fetch failed"),d="name"in a&&"ConnectionError"===a.name,e="code"in a&&"string"==typeof a.code&&"econnreset"===a.code.toLowerCase();return b||c||e||d}function eV(a){if("object"!=typeof a||null==a)return!1;let b="name"in a&&"TimeoutError"===a.name,c="code"in a&&23===a.code,d="code"in a&&"string"==typeof a.code&&"econnaborted"===a.code.toLowerCase();return b||c||d}let eW={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5};class eX extends Error{constructor(a,b){let c=a;(null==b?void 0:b.cause)&&(c+=`: ${b.cause}`),super(c,b),this.name="PermanentError",void 0===this.cause&&(this.cause=null==b?void 0:b.cause),Object.setPrototypeOf(this,eX.prototype)}}class eY extends Error{constructor(a,b){super(a),this.response=b,this.name="TemporaryError",Object.setPrototypeOf(this,eY.prototype)}}async function eZ(a,b){var c;switch(b.config.strategy){case"backoff":return e0(e$(a,{statusCodes:b.statusCodes,retryConnectionErrors:!!b.config.retryConnectionErrors}),null!=(c=b.config.backoff)?c:eW);case"attempt-count-backoff":return e1(e$(a,{statusCodes:b.statusCodes,retryConnectionErrors:!!b.config.retryConnectionErrors}),Object.assign(Object.assign({},eW),b.config.backoff),b.config);default:return await a(0)}}function e$(a,b){return async c=>{try{var d,e;let f,g=await a(c);if(d=g,e=b.statusCodes,f=`${d.status}`,e.some(a=>{if(!e_.test(a))return a===f;let b=a.charAt(0);if(!b)throw Error("Invalid status code range");let c=f.charAt(0);if(!c)throw Error(`Invalid response status code: ${f}`);return c===b}))throw new eY("Response failed with retryable status code",g);return g}catch(a){if(a instanceof eY||b.retryConnectionErrors&&(eV(a)||eU(a)))throw a;throw new eX("Permanent error",{cause:a})}}}let e_=RegExp("^[0-9]xx$","i");async function e0(a,b){let{maxElapsedTime:c,initialInterval:d,exponent:e,maxInterval:f}=b,g=Date.now(),h=0;for(;;)try{return await a(h)}catch(i){if(i instanceof eX)throw i.cause;if(Date.now()-g>c){if(i instanceof eY)return i.response;throw i}let a=0;i instanceof eY&&(a=e2(i.response)),a<=0&&(a=d*Math.pow(h,e)+1e3*Math.random());let b=Math.min(a,f);await e3(b),h++}}async function e1(a,b,c){let d=0;for(;;)try{return await a(d)}catch(f){if(f instanceof eX)throw f.cause;if(d>=c.maxRetries){if(f instanceof eY)return f.response;throw f}let a=0;f instanceof eY&&(a=e2(f.response)),a<=0&&(a=b.initialInterval*Math.pow(b.exponent,d)*(1-.25*Math.random()));let e=Math.min(a,b.maxInterval);await e3(e),d++}}function e2(a){let b=a.headers.get("retry-after-ms");if(b){let a=Number(b);if(Number.isFinite(a)&&a>=0)return a}let c=a.headers.get("retry-after")||"";if(!c)return 0;let d=Number(c);if(Number.isInteger(d))return 1e3*d;let e=Date.parse(c);if(Number.isInteger(e)){let a=e-Date.now();return a>0?Math.ceil(a):0}return 0}async function e3(a){return new Promise(b=>setTimeout(b,a))}let e4="u"<typeof globalThis?null:globalThis,e5="object"==typeof e4&&null!=e4&&"importScripts"in e4&&"function"==typeof e4.importScripts||"u">typeof navigator&&"serviceWorker"in navigator||"object"==typeof window&&void 0!==window.document;class e6{constructor(a={}){const b=a;"object"==typeof b&&null!=b&&"hooks"in b&&b.hooks instanceof ew?this._hooks=b.hooks:this._hooks=new ew;const c=new eP;a.http_client=a.http_client||c;const d=function(a){var b;let c=a.server_url;if(!c){let d=null!=(b=a.server_idx)?b:0;if(d<0||d>=eC.length)throw Error(`Invalid server index ${d}`);c=eC[d]||""}return new URL(eB(c)({}))}(a=this._hooks.sdkInit(a));d&&(d.pathname=d.pathname.replace(/\/+$/,"")+"/"),this._baseURL=d,this._httpClient=a.http_client||c,this._options=Object.assign(Object.assign({},function(a){let b=Object.assign({},a),c=d_();return void 0!==c.GOOGLE_GENAI_API_VERSION&&(null!=b.api_version||(b.api_version=c.GOOGLE_GENAI_API_VERSION)),void 0!==c.GOOGLE_GENAI_USER_PROJECT&&(null!=b.user_project||(b.user_project=c.GOOGLE_GENAI_USER_PROJECT)),b}(a)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&d_().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(a,b,c){var d,e,f,g,h,i;let j,k,{method:l,path:m,query:n,headers:o,security:p}=b,q=null!=(d=b.baseURL)?d:this._baseURL;if(!q)return ey(new ea("No base URL provided for operation"));let r=new URL(q);m?(r.pathname=r.pathname.replace(/\/+$/,"")+"/",!(j=new URL(m,r)).search&&r.search&&(j.search=r.search)):j=r,j.hash="";let s=a=>Object.entries(a).map(([a,b])=>{if(null==b)return;let c=eE(b)?JSON.stringify(b):b;return eF(a,c,{explode:Array.isArray(c),charEncoding:"percent"})}).filter(a=>void 0!==a).join("&"),t=[n||"",s((null==c?void 0:c.extra_query)||{}),s((null==p?void 0:p.queryParams)||{})].reduce((a,b)=>{if(!b)return a;let c=new Set(b.split("&").filter(a=>""!==a).map(a=>{var b;return null!=(b=a.split("=")[0])?b:""}));return[...a.split("&").filter(a=>{var b;return""!==a&&!c.has(null!=(b=a.split("=")[0])?b:"")}),b].join("&")},j.search.slice(1));t&&(j.search=`?${t}`);let u=new Headers(o),v=null==p?void 0:p.basic.username,w=null==p?void 0:p.basic.password;if(null!=v||null!=w){let a=ez((i=[v||"",w||""].join(":"),new TextEncoder().encode(i)));u.set("Authorization",`Basic ${a}`)}for(let[a,b]of new Headers((null==p?void 0:p.headers)||{}))u.set(a,b);let x=u.get("cookie")||"";for(let[a,b]of Object.entries((null==p?void 0:p.cookies)||{}))x+=`; ${a}=${b}`;for(let[a,b]of(x=x.startsWith("; ")?x.slice(2):x,u.set("cookie",x),new Headers(null!=(e=null==c?void 0:c.headers)?e:null==(f=null==c?void 0:c.fetch_options)?void 0:f.headers)))u.set(a,b);e5||u.set(null!=(g=b.uaHeader)?g:"user-agent",null!=(h=b.userAgent)?h:"speakeasy-sdk/typescript 2.4.1-preview.4 2.924.0 v1beta @google/genai");let y=b.body,z=Object.fromEntries(Object.entries((null==c?void 0:c.extra_body)||{}).filter(([,a])=>void 0!==a));if(Object.keys(z).length>0){let a,b=new Headers(o).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(b)||"string"!=typeof y&&null!=y)return ey(new ea("extra_body can only be merged into JSON object request bodies"));try{a=y?JSON.parse(y):{}}catch(a){return ey(new ea("extra_body can only be merged into JSON object request bodies",{cause:a}))}if(!eE(a))return ey(new ea("extra_body can only be merged into JSON object request bodies"));y=JSON.stringify(Object.assign(Object.assign({},a),z)),u.delete("content-length")}let A=Object.assign(Object.assign({},null==c?void 0:c.fetch_options),c);(null==A?void 0:A.signal)||null==b.timeout_ms||!(b.timeout_ms>0)||(a.timeout_ms=b.timeout_ms),b.body instanceof ReadableStream&&Object.assign(A,{duplex:"half"});try{k=this._hooks.beforeCreateRequest(a,{url:j,options:Object.assign(Object.assign({},A),{body:null!=y?y:null,headers:u,method:l})})}catch(a){return ey(new d9("Create request hook failed to execute",{cause:a}))}return ex(new Request(k.url,k.options))}async _do(a,b){let{context:c,isErrorStatusCode:d}=b,e=c.timeout_ms;return eZ(async()=>{var b;let f=a.clone(),g=f;if(null!=e&&e>0){let a=AbortSignal.timeout(e),c=null!=(b=function(...a){let b=[];for(let c of a)c&&b.push(c);switch(b.length){case 0:case 1:return b[0]||null;default:if("any"in AbortSignal&&"function"==typeof AbortSignal.any)return AbortSignal.any(b);var c=b;let d=new AbortController,e=d.signal;if(!c.length)return d.signal;if(1===c.length)return c[0]||d.signal;for(let a of c)if(a.aborted)return a;function f(){d.abort(this.reason),function(){for(let a of g){let b=a.deref();b&&b.removeEventListener("abort",f)}}()}let g=[];for(let a of c)g.push(new WeakRef(a)),a.addEventListener("abort",f);return e}}(f.signal,a))?b:a;g=new Request(f,{signal:c})}let h=await this._hooks.beforeRequest(c,g);await e9(this._logger,h).catch(a=>{var b;return null==(b=this._logger)?void 0:b.log("Failed to log request:",a)});let i=await this._httpClient.request(h);try{if(d(i.status)){let a=await this._hooks.afterError(c,i,null);if(a.error)throw a.error;i=a.response||i}else i=await this._hooks.afterSuccess(c,i)}finally{await fa(this._logger,i,h).catch(a=>{var b;return null==(b=this._logger)?void 0:b.log("Failed to log response:",a)})}return i},{config:b.retryConfig,statusCodes:b.retryCodes}).then(a=>ex(a),a=>{switch(!0){case function(a){if("object"!=typeof a||null==a)return!1;let b="name"in a&&"AbortError"===a.name,c="code"in a&&20===a.code,d="code"in a&&"string"==typeof a.code&&"econnaborted"===a.code.toLowerCase();return b||c||d}(a):return ey(new eb("Request aborted by client",{cause:a}));case eV(a):return ey(new ec("Request timed out",{cause:a}));case eU(a):return ey(new ed("Unable to make request",{cause:a}));default:return ey(new d9("Unexpected HTTP client error",{cause:a}))}})}}let e7=/^(application|text)\/([^+]+\+)*json.*/,e8=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function e9(a,b){if(!a)return;let c=b.headers.get("content-type"),d=(null==c?void 0:c.split(";")[0])||"";for(let[c,d]of(a.group(`> Request: ${b.method} ${b.url}`),a.group("Headers:"),b.headers.entries()))a.log(`${c}: ${d}`);switch(a.groupEnd(),a.group("Body:"),!0){case e7.test(d):a.log(await b.clone().json());break;case d.startsWith("text/"):a.log(await b.clone().text());break;case"multipart/form-data"===d:for(let[c,d]of(await b.clone().formData())){let b=d instanceof Blob?"<Blob>":d;a.log(`${c}: ${b}`)}break;default:a.log(`<${c}>`)}a.groupEnd(),a.groupEnd()}async function fa(a,b,c){if(!a)return;let d=b.headers.get("content-type"),e=(null==d?void 0:d.split(";")[0])||"";for(let[d,e]of(a.group(`< Response: ${c.method} ${c.url}`),a.log("Status Code:",b.status,b.statusText),a.group("Headers:"),b.headers.entries()))a.log(`${d}: ${e}`);switch(a.groupEnd(),a.group("Body:"),!0){case eR(b,"application/json")||e7.test(e)&&!e8.test(e):a.log(await b.clone().json());break;case eR(b,"application/jsonl")||e8.test(e):case eR(b,"text/event-stream"):a.log(`<${d}>`);break;case eR(b,"text/*"):a.log(await b.clone().text());break;case eR(b,"multipart/form-data"):for(let[c,d]of(await b.clone().formData())){let b=d instanceof Blob?"<Blob>":d;a.log(`${c}: ${b}`)}break;default:a.log(`<${d}>`)}a.groupEnd(),a.groupEnd()}class fb extends ee{constructor(a,b){a&&(a+=": "),a+=`Status ${b.response.status}`;const c=b.response.headers.get("content-type")||'""';"application/json"!==c&&(a+=` Content-Type ${c.includes(" ")?`"${c}"`:c}`);const d=b.body||'""';a+=d.length>100?"\n":". ";let e=d;if(d.length>1e4){const a=d.substring(0,1e4),b=d.length-1e4;e=`${a}...and ${b} more chars`}a+=`Body: ${e}`,super(a=a.trim(),b),this.name="GoogleGenAiDefaultError"}}function fc(a){try{return JSON.parse(a)}catch(b){return a}}class fd extends ReadableStream{constructor(a,b,c){var d;const e=a.getReader();let f=new Uint8Array(4096),g=0,h=0;const i={eventId:void 0},j=null==(d=null==c?void 0:c.dataRequired)||d;super({async pull(a){try{for(;;){let c=function(a,b,c){for(let d=c;d<b;d++)if(13===a[d]||10===a[d])for(let c of fe){if(d+c.length>b)continue;let e=!0;for(let b=0;b<c.length;b++)if(a[d+b]!==c[b]){e=!1;break}if(e)return{index:d,length:c.length}}return null}(f,g,h);if(!c){h=Math.max(0,g-ff+1);let b=await e.read();if(b.done)return a.close();if(g+b.value.length>f.length){let a=new Uint8Array(Math.max(2*f.length,g+b.value.length));a.set(f.subarray(0,g)),f=a}f.set(b.value,g),g+=b.value.length;continue}let d=f.slice(0,c.index);if(f.copyWithin(0,c.index+c.length,g),g-=c.index+c.length,f.length>4096&&g<=f.length>>2){let a=new Uint8Array(Math.max(4096,2*g));a.set(f.subarray(0,g)),f=a}h=0;let k=function(a,b,c,d){let e=new TextDecoder().decode(a).split(/\r\n|\r|\n/),f=[],g={},h=!0;for(let a of e){if(!a||a.startsWith(":"))continue;h=!1;let b=a.indexOf(":"),d=a,e="";b>0&&(d=a.slice(0,b),e=" "===a[b+1]?a.slice(b+2):a.slice(b+1)),"data"===d?f.push(e):"event"===d?g.event=e:"id"!==d||e.includes("\0")?"retry"===d&&/^\d+$/.test(e)&&(g.retry=Number(e)):c.eventId=e}if(!h){if(g.id=c.eventId,f.length)g.data=f.join("\n");else if(d)return;return b(g)}}(d,b,i,j);if(k&&!k.done)return a.enqueue(k.value);if(null==k?void 0:k.done)return await e.cancel("done"),a.close()}}catch(b){a.error(b),await e.cancel(b)}},cancel:a=>e.cancel(a)})}[Symbol.asyncIterator](a){let b=ReadableStream.prototype[Symbol.asyncIterator];if("function"==typeof b)return b.call(this,a);let c=this.getReader(),d={next:async()=>{let a=await c.read();return a.done?(c.releaseLock(),{done:!0,value:void 0}):{done:!1,value:a.value}},throw:async a=>(await c.cancel(a),c.releaseLock(),{done:!0,value:void 0}),return:async()=>(await c.cancel("done"),c.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},e=Symbol.asyncDispose;return e&&(d[e]=async()=>{var a;await (null==(a=d.return)?void 0:a.call(d))}),d}values(a){return this[Symbol.asyncIterator](a)}}let fe=[[13,10,13,10],[13,10,13],[13,10,10],[13,13,10],[10,13,10],[13,13],[10,13],[10,10]],ff=fe.reduce((a,b)=>Math.max(a,b.length),0),fg={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function fh(a,b,c){return Object.assign(Object.assign({},c),{err:!0,enc:"json",codes:a,errorClass:b})}function fi(a,b){return Object.assign(Object.assign({},b),{enc:"json",codes:a})}function fj(a,b,c){return Object.assign(Object.assign(Object.assign({},c),{enc:"sse",codes:a}),b?{sse:b}:{})}function fk(a){return{enc:"fail",codes:a}}function fl(...a){return async function(b,c,d){let e,f,g;for(let c of a){let{codes:a}=c,d="ctype"in c?c.ctype:fg[c.enc];if(d&&eT(b,a)&&eR(b,d)||!d&&eT(b,a)){f=c;break}}if(!f)return[{ok:!1,error:new fb("Unexpected Status or Content-Type",{response:b,request:c,body:await b.text().catch(()=>"")})},e];let h=f.enc,i="";switch(h){case"json":i=await b.text();try{e=JSON.parse(i)}catch(a){if(!("err"in f))throw a;e=i}break;case"jsonl":case"stream":e=b.body;break;case"bytes":e=new Uint8Array(await b.arrayBuffer());break;case"text":case"fail":e=i=await b.text();break;case"sse":if(b.body){let a="sse"in f&&f.sse||{};e=function(a,b={}){var c,d;let e=!0===b.flattened,f=null!=(c=b.sentinel)?c:"";return new fd(a,a=>""!==f&&a.data===f?{done:!0,value:void 0}:e?{done:!1,value:null==a.data?void 0:fc(a.data)}:{done:!1,value:Object.assign(Object.assign({},a),{data:null==a.data?a.data:fc(a.data)})},{dataRequired:null==(d=b.dataRequired)||d})}(b.body,a)}else e=null;break;case"nil":i=await b.text(),e=void 0;break;default:throw Error(`Unsupported response type: ${h}`)}if("fail"===f.enc)return[{ok:!1,error:new fb("API error occurred",{request:c,response:b,body:i})},e];let j=f.key||(null==d?void 0:d.resultKey),k=f.hdrs?{headers:function(a){let b={};for(let[c,d]of a.entries())b[c]=d.split(fm);return b}(b.headers)}:null;return(g="err"in f?Object.assign(Object.assign(Object.assign({},null==d?void 0:d.extraFields),k),eE(e)?e:null):j?Object.assign(Object.assign(Object.assign({},null==d?void 0:d.extraFields),k),{[j]:e}):f.hdrs?Object.assign(Object.assign(Object.assign({},null==d?void 0:d.extraFields),k),eE(e)?e:null):e,"err"in f)?[{ok:!1,error:f.errorClass?new f.errorClass(g,{request:c,response:b,body:i}):g},e]:[{ok:!0,value:g},e]}}let fm=/, */;class fn extends Error{constructor(a,b){super(b),this.code=a,this.name="SecurityError"}static incomplete(){return new fn("incomplete","Security requirements not met in order to perform the operation")}static unrecognizedType(a){return new fn("unrecognized_security_type",`Unrecognised security type: ${a}`)}}function fo(a,b){var c,d;return function(...a){let b={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},c=a.find(a=>a.every(a=>{if(null==a.value)return!1;if("http:basic"===a.type)return null!=a.value.username||null!=a.value.password;if("http:custom"===a.type)return null;if("oauth2:password"===a.type)return"string"==typeof a.value&&!!a.value;if("oauth2:client_credentials"===a.type)return"string"==typeof a.value?!!a.value:null!=a.value.client_id||null!=a.value.client_secret;else if("string"==typeof a.value)return!!a.value;else throw Error(`Unrecognized security type: ${a.type} (value type: ${typeof a.value})`)}));return null==c?null:(c.forEach(a=>{if(null==a.value)return;let{type:c}=a;switch(c){case"apiKey:header":b.headers[a.fieldName]=a.value;break;case"apiKey:query":b.queryParams[a.fieldName]=a.value;break;case"apiKey:cookie":b.cookies[a.fieldName]=a.value;break;case"http:basic":var d,e;d=b,null!=(e=a).value&&(d.basic=e.value);break;case"http:custom":case"oauth2:client_credentials":break;case"http:bearer":case"oauth2":case"oauth2:password":case"openIdConnect":!function(a,b){if("string"!=typeof b.value||!b.value)return;let c=b.value;"bearer "!==c.slice(0,7).toLowerCase()&&(c=`Bearer ${c}`),void 0!==b.fieldName&&(a.headers[b.fieldName]=c)}(b,a);break;default:throw fn.unrecognizedType(c)}}),b)}([{fieldName:"apiKey",type:"http:custom",value:null!=(c=null==a?void 0:a.api_key)?c:d_().GOOGLE_GENAI_API_KEY},{fieldName:"accessToken",type:"http:custom",value:null!=(d=null==a?void 0:a.access_token)?d:d_().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"defaultHeaders",type:"http:custom",value:null==a?void 0:a.default_headers}])}async function fp(a){if(null!=a)return"function"==typeof a?a():a}class fq{constructor(a,b){this[bN]="APIPromise",this._promise=a instanceof Promise?a:Promise.resolve(a),this._unwrapped=a instanceof Promise?null:Promise.resolve(a[0]),this._callSource=null!=b?b:null}_getUnwrapped(){var a;return null!=(a=this._unwrapped)?a:this._unwrapped=this._promise.then(([a])=>a)}then(a,b){return this._promise.then(a?([b])=>a(b):void 0,b)}catch(a){return this._getUnwrapped().catch(a)}finally(a){return this._getUnwrapped().finally(a)}$inspect(){return this._promise}asResponse(){var a;return(null!=(a=this._callSource)?a:this._callSource=this._promise.then(([,a])=>a)).then(a=>{if(!a.response)throw Error("APIPromise.asResponse: response unavailable");return a.response})}async withResponse(){let[[a],b]=await Promise.all([this._promise,this.asResponse()]);return{data:a,response:b}}_thenUnwrap(a){var b;let c=this._promise.then(([b,c])=>[a(b),c]);return c.catch(()=>{}),new fq(c,null!=(b=this._callSource)?b:void 0)}}function fr(a){let b=a.$inspect(),c=b.then(([a,b])=>{if(!a.ok)throw a.error;return[a.value,b]}),d=b.then(([a,b])=>{var c;if(!a.ok&&!(null==(c=b.response)?void 0:c.ok))throw a.error;return b});return c.catch(()=>{}),d.catch(()=>{}),new fq(c,d)}async function fs(a,b,c,d){var e,f;let g=eG("body",b,{explode:!0}),h={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"})},i=eB("/{api_version}/agents")(h),j=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),k=fo(await fp(a._options.security)),l={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:k,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},m=a._createRequest(l,{security:k,method:"POST",baseURL:null==d?void 0:d.server_url,path:i,headers:j,body:g,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!m.ok)return[m,{status:"invalid"}];let n=m.value,o=await a._do(n,{context:l,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:l.retry_config,retryCodes:l.retry_codes});if(!o.ok)return[o,{status:"request-error",request:n}];let p=o.value,[q]=await fl(fk("4XX"),fk("5XX"),fi("default"))(p,n);return!q.ok,[q,{status:"complete",request:n,response:p}]}async function ft(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/agents/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"DELETE",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fu(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/agents/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"GET",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fv(a,b,c,d,e,f){var g,h,i;let j={api_version:b,page_size:c,page_token:d,parent:e},k={api_version:eH("api_version",null!=(g=null==j?void 0:j.api_version)?g:a._options.api_version,{explode:!1,charEncoding:"percent"})},l=eB("/{api_version}/agents")(k),m=eN({page_size:null==j?void 0:j.page_size,page_token:null==j?void 0:j.page_token,parent:null==j?void 0:j.parent}),n=new Headers(eD({Accept:"application/json"})),o=fo(await fp(a._options.security)),p={options:a._options,base_url:null!=(i=null!=(h=null==f?void 0:f.server_url)?h:a._baseURL)?i:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:o,security_source:a._options.security,retry_config:(null==f?void 0:f.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==f?void 0:f.retry_codes)||["408","409","429","5XX"]},q=a._createRequest(p,{security:o,method:"GET",baseURL:null==f?void 0:f.server_url,path:l,headers:n,query:m,body:null,userAgent:a._options.user_agent,timeout_ms:(null==f?void 0:f.timeout_ms)||a._options.timeout_ms||-1},f);if(!q.ok)return[q,{status:"invalid"}];let r=q.value,s=await a._do(r,{context:p,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!s.ok)return[s,{status:"request-error",request:r}];let t=s.value,[u]=await fl(fk("4XX"),fk("5XX"),fi("default"))(t,r);return!u.ok,[u,{status:"complete",request:r,response:t}]}bN=Symbol.toStringTag;class fw extends e6{create(a,b){let{api_version:c}=a;return fr(new fq(fs(this,c5(a,["api_version"]),c,b)))}list(a,b){var c,d,e;return fr((c=null==a?void 0:a.api_version,d=null==a?void 0:a.page_size,e=null==a?void 0:a.page_token,new fq(fv(this,c,d,e,null==a?void 0:a.parent,b))))}get(a,b,c){return fr(new fq(fu(this,a,null==b?void 0:b.api_version,c)))}delete(a,b,c){return fr(new fq(ft(this,a,null==b?void 0:b.api_version,c)))}}async function fx(a,b,c,d){var e,f;let g=eG("body",b,{explode:!0}),h={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"})},i=eB("/{api_version}/environments")(h),j=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),k=fo(await fp(a._options.security)),l={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:k,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},m=a._createRequest(l,{security:k,method:"POST",baseURL:null==d?void 0:d.server_url,path:i,headers:j,body:g,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!m.ok)return[m,{status:"invalid"}];let n=m.value,o=await a._do(n,{context:l,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:l.retry_config,retryCodes:l.retry_codes});if(!o.ok)return[o,{status:"request-error",request:n}];let p=o.value,[q]=await fl(fk("4XX"),fk("5XX"),fi("default"))(p,n);return!q.ok,[q,{status:"complete",request:n,response:p}]}async function fy(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/environments/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"DELETE",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fz(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/environments/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"GET",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fA(a,b,c,d,e){var f,g,h;let i={api_version:b,page_size:c,page_token:d},j={api_version:eH("api_version",null!=(f=null==i?void 0:i.api_version)?f:a._options.api_version,{explode:!1,charEncoding:"percent"})},k=eB("/{api_version}/environments")(j),l=eN({page_size:null==i?void 0:i.page_size,page_token:null==i?void 0:i.page_token}),m=new Headers(eD({Accept:"application/json"})),n=fo(await fp(a._options.security)),o={options:a._options,base_url:null!=(h=null!=(g=null==e?void 0:e.server_url)?g:a._baseURL)?h:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:n,security_source:a._options.security,retry_config:(null==e?void 0:e.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==e?void 0:e.retry_codes)||["408","409","429","5XX"]},p=a._createRequest(o,{security:n,method:"GET",baseURL:null==e?void 0:e.server_url,path:k,headers:m,query:l,body:null,userAgent:a._options.user_agent,timeout_ms:(null==e?void 0:e.timeout_ms)||a._options.timeout_ms||-1},e);if(!p.ok)return[p,{status:"invalid"}];let q=p.value,r=await a._do(q,{context:o,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:o.retry_config,retryCodes:o.retry_codes});if(!r.ok)return[r,{status:"request-error",request:q}];let s=r.value,[t]=await fl(fk("4XX"),fk("5XX"),fi("default"))(s,q);return!t.ok,[t,{status:"complete",request:q,response:s}]}class fB extends e6{createEnvironment(a,b,c){return fr(new fq(fx(this,a,b,c)))}listEnvironments(a,b){var c,d;return fr((c=null==a?void 0:a.api_version,d=null==a?void 0:a.page_size,new fq(fA(this,c,d,null==a?void 0:a.page_token,b))))}getEnvironment(a,b,c){return fr(new fq(fz(this,a,null==b?void 0:b.api_version,c)))}deleteEnvironment(a,b,c){return fr(new fq(fy(this,a,null==b?void 0:b.api_version,c)))}}class fC extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="CancelInteractionByIdServerError"}}class fD extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="CancelInteractionByIdClientError"}}class fE extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="CreateInteractionServerError"}}class fF extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="CreateInteractionClientError"}}class fG extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="DeleteInteractionServerError"}}class fH extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="DeleteInteractionClientError"}}class fI extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="GetInteractionByIdServerError"}}class fJ extends ee{constructor(a,b){var c;super((null==(c=a.error)?void 0:c.message)||`API error occurred: ${JSON.stringify(a)}`,b),this.data$=a,this.error=a.error,this.name="GetInteractionByIdClientError"}}async function fK(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/interactions/{id}/cancel")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"POST",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fi(200),fh("4XX",fD),fh("5XX",fC))(o,m,{extraFields:{httpMeta:{response:o,request:m}}});return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fL(a,b,c,d){var e,f,g,h;let i={body:b,api_version:c},j=eG("body",i.body,{explode:!0}),k={api_version:eH("api_version",null!=(e=i.api_version)?e:a._options.api_version,{explode:!1,charEncoding:"percent"})},l=eB("/{api_version}/interactions")(k),m=new Headers(eD({"Content-Type":"application/json",Accept:(null==(f=null==i?void 0:i.body)?void 0:f.stream)?"text/event-stream":"application/json"})),n=fo(await fp(a._options.security)),o={options:a._options,base_url:null!=(h=null!=(g=null==d?void 0:d.server_url)?g:a._baseURL)?h:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:n,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},p=a._createRequest(o,{security:n,method:"POST",baseURL:null==d?void 0:d.server_url,path:l,headers:m,body:j,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!p.ok)return[p,{status:"invalid"}];let q=p.value,r=await a._do(q,{context:o,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:o.retry_config,retryCodes:o.retry_codes});if(!r.ok)return[r,{status:"request-error",request:q}];let s=r.value,[t]=await fl(fi(200),fj(200,{sentinel:"[DONE]",flattened:!0}),fh("4XX",fF),fh("5XX",fE))(s,q,{extraFields:{httpMeta:{response:s,request:q}}});return!t.ok,[t,{status:"complete",request:q,response:s}]}async function fM(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/interactions/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"DELETE",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(Object.assign(Object.assign({},void 0),{enc:"nil",codes:200}),fh("4XX",fH),fh("5XX",fG))(o,m,{extraFields:{httpMeta:{response:o,request:m}}});return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fN(a,b,c,d,e,f,g){var h,i,j;let k={id:b,stream:c,last_event_id:d,include_input:e,api_version:f},l={api_version:eH("api_version",null!=(h=k.api_version)?h:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",k.id,{explode:!1,charEncoding:"percent"})},m=eB("/{api_version}/interactions/{id}")(l),n=eN({include_input:k.include_input,last_event_id:k.last_event_id,stream:k.stream}),o=new Headers(eD({Accept:(null==k?void 0:k.stream)?"text/event-stream":"application/json"})),p=fo(await fp(a._options.security)),q={options:a._options,base_url:null!=(j=null!=(i=null==g?void 0:g.server_url)?i:a._baseURL)?j:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:p,security_source:a._options.security,retry_config:(null==g?void 0:g.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==g?void 0:g.retry_codes)||["408","409","429","5XX"]},r=a._createRequest(q,{security:p,method:"GET",baseURL:null==g?void 0:g.server_url,path:m,headers:o,query:n,body:null,userAgent:a._options.user_agent,timeout_ms:(null==g?void 0:g.timeout_ms)||a._options.timeout_ms||-1},g);if(!r.ok)return[r,{status:"invalid"}];let s=r.value,t=await a._do(s,{context:q,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:q.retry_config,retryCodes:q.retry_codes});if(!t.ok)return[t,{status:"request-error",request:s}];let u=t.value,[v]=await fl(fi(200),fj(200,{sentinel:"[DONE]",flattened:!0}),fh("4XX",fJ),fh("5XX",fI))(u,s,{extraFields:{httpMeta:{response:u,request:s}}});return!v.ok,[v,{status:"complete",request:s,response:u}]}class fO extends e6{create(a,b){let{api_version:c}=a;return fr(new fq(fL(this,c5(a,["api_version"]),c,b)))}get(a,b,c){var d,e,f;return fr((d=null==b?void 0:b.stream,e=null==b?void 0:b.last_event_id,f=null==b?void 0:b.include_input,new fq(fN(this,a,d,e,f,null==b?void 0:b.api_version,c))))}delete(a,b,c){return fr(new fq(fM(this,a,null==b?void 0:b.api_version,c)))}cancel(a,b,c){return fr(new fq(fK(this,a,null==b?void 0:b.api_version,c)))}}async function fP(a,b,c,d){var e,f;let g=eG("body",b,{explode:!0}),h={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"})},i=eB("/{api_version}/triggers")(h),j=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),k=fo(await fp(a._options.security)),l={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:k,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},m=a._createRequest(l,{security:k,method:"POST",baseURL:null==d?void 0:d.server_url,path:i,headers:j,body:g,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!m.ok)return[m,{status:"invalid"}];let n=m.value,o=await a._do(n,{context:l,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:l.retry_config,retryCodes:l.retry_codes});if(!o.ok)return[o,{status:"request-error",request:n}];let p=o.value,[q]=await fl(fi(200),fk("4XX"),fk("5XX"))(p,n);return!q.ok,[q,{status:"complete",request:n,response:p}]}async function fQ(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/triggers/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"DELETE",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fi(200),fk("4XX"),fk("5XX"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fR(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/triggers/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"GET",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fi(200),fk("4XX"),fk("5XX"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fS(a,b,c,d,e,f){var g,h;let i={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:eH("trigger_id",b,{explode:!1,charEncoding:"percent"})},j=eB("/{api_version}/triggers/{trigger_id}/executions")(i),k=eN({page_size:d,page_token:e}),l=new Headers(eD({Accept:"application/json"})),m=fo(await fp(a._options.security)),n={options:a._options,base_url:null!=(h=null!=(g=null==f?void 0:f.server_url)?g:a._baseURL)?h:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:m,security_source:a._options.security,retry_config:(null==f?void 0:f.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==f?void 0:f.retry_codes)||["408","409","429","5XX"]},o=a._createRequest(n,{security:m,method:"GET",baseURL:null==f?void 0:f.server_url,path:j,headers:l,query:k,body:null,userAgent:a._options.user_agent,timeout_ms:(null==f?void 0:f.timeout_ms)||a._options.timeout_ms||-1},f);if(!o.ok)return[o,{status:"invalid"}];let p=o.value,q=await a._do(p,{context:n,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:n.retry_config,retryCodes:n.retry_codes});if(!q.ok)return[q,{status:"request-error",request:p}];let r=q.value,[s]=await fl(fi(200),fk("4XX"),fk("5XX"))(r,p);return!s.ok,[s,{status:"complete",request:p,response:r}]}async function fT(a,b,c,d,e,f){var g,h,i;let j={api_version:b,filter:c,page_size:d,page_token:e},k={api_version:eH("api_version",null!=(g=null==j?void 0:j.api_version)?g:a._options.api_version,{explode:!1,charEncoding:"percent"})},l=eB("/{api_version}/triggers")(k),m=eN({filter:null==j?void 0:j.filter,page_size:null==j?void 0:j.page_size,page_token:null==j?void 0:j.page_token}),n=new Headers(eD({Accept:"application/json"})),o=fo(await fp(a._options.security)),p={options:a._options,base_url:null!=(i=null!=(h=null==f?void 0:f.server_url)?h:a._baseURL)?i:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:o,security_source:a._options.security,retry_config:(null==f?void 0:f.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==f?void 0:f.retry_codes)||["408","409","429","5XX"]},q=a._createRequest(p,{security:o,method:"GET",baseURL:null==f?void 0:f.server_url,path:l,headers:n,query:m,body:null,userAgent:a._options.user_agent,timeout_ms:(null==f?void 0:f.timeout_ms)||a._options.timeout_ms||-1},f);if(!q.ok)return[q,{status:"invalid"}];let r=q.value,s=await a._do(r,{context:p,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!s.ok)return[s,{status:"request-error",request:r}];let t=s.value,[u]=await fl(fi(200),fk("4XX"),fk("5XX"))(t,r);return!u.ok,[u,{status:"complete",request:r,response:t}]}async function fU(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:eH("trigger_id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/triggers/{trigger_id}/executions")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"POST",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fi(200),fk("4XX"),fk("5XX"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fV(a,b,c,d,e){var f,g;let h=eG("body",c,{explode:!0}),i={api_version:eH("api_version",null!=d?d:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},j=eB("/{api_version}/triggers/{id}")(i),k=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),l=fo(await fp(a._options.security)),m={options:a._options,base_url:null!=(g=null!=(f=null==e?void 0:e.server_url)?f:a._baseURL)?g:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:l,security_source:a._options.security,retry_config:(null==e?void 0:e.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==e?void 0:e.retry_codes)||["408","409","429","5XX"]},n=a._createRequest(m,{security:l,method:"PATCH",baseURL:null==e?void 0:e.server_url,path:j,headers:k,body:h,userAgent:a._options.user_agent,timeout_ms:(null==e?void 0:e.timeout_ms)||a._options.timeout_ms||-1},e);if(!n.ok)return[n,{status:"invalid"}];let o=n.value,p=await a._do(o,{context:m,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!p.ok)return[p,{status:"request-error",request:o}];let q=p.value,[r]=await fl(fi(200),fk("4XX"),fk("5XX"))(q,o);return!r.ok,[r,{status:"complete",request:o,response:q}]}class fW extends e6{create(a,b){let{api_version:c}=a;return fr(new fq(fP(this,c5(a,["api_version"]),c,b)))}list(a,b){var c,d,e;return fr((c=null==a?void 0:a.api_version,d=null==a?void 0:a.filter,e=null==a?void 0:a.page_size,new fq(fT(this,c,d,e,null==a?void 0:a.page_token,b))))}get(a,b,c){return fr(new fq(fR(this,a,null==b?void 0:b.api_version,c)))}update(a,b,c){let{api_version:d}=b;return fr(new fq(fV(this,a,c5(b,["api_version"]),d,c)))}delete(a,b,c){return fr(new fq(fQ(this,a,null==b?void 0:b.api_version,c)))}run(a,b,c){return fr(new fq(fU(this,a,null==b?void 0:b.api_version,c)))}listExecutions(a,b,c){var d,e;return fr((d=null==b?void 0:b.api_version,e=null==b?void 0:b.page_size,new fq(fS(this,a,d,e,null==b?void 0:b.page_token,c))))}}async function fX(a,b,c,d){var e,f;let g=eG("body",b,{explode:!0}),h={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"})},i=eB("/{api_version}/webhooks")(h),j=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),k=fo(await fp(a._options.security)),l={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:k,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},m=a._createRequest(l,{security:k,method:"POST",baseURL:null==d?void 0:d.server_url,path:i,headers:j,body:g,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!m.ok)return[m,{status:"invalid"}];let n=m.value,o=await a._do(n,{context:l,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:l.retry_config,retryCodes:l.retry_codes});if(!o.ok)return[o,{status:"request-error",request:n}];let p=o.value,[q]=await fl(fk("4XX"),fk("5XX"),fi("default"))(p,n);return!q.ok,[q,{status:"complete",request:n,response:p}]}async function fY(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/webhooks/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"DELETE",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function fZ(a,b,c,d){var e,f;let g={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},h=eB("/{api_version}/webhooks/{id}")(g),i=new Headers(eD({Accept:"application/json"})),j=fo(await fp(a._options.security)),k={options:a._options,base_url:null!=(f=null!=(e=null==d?void 0:d.server_url)?e:a._baseURL)?f:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:j,security_source:a._options.security,retry_config:(null==d?void 0:d.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==d?void 0:d.retry_codes)||["408","409","429","5XX"]},l=a._createRequest(k,{security:j,method:"GET",baseURL:null==d?void 0:d.server_url,path:h,headers:i,body:null,userAgent:a._options.user_agent,timeout_ms:(null==d?void 0:d.timeout_ms)||a._options.timeout_ms||-1},d);if(!l.ok)return[l,{status:"invalid"}];let m=l.value,n=await a._do(m,{context:k,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:k.retry_config,retryCodes:k.retry_codes});if(!n.ok)return[n,{status:"request-error",request:m}];let o=n.value,[p]=await fl(fk("4XX"),fk("5XX"),fi("default"))(o,m);return!p.ok,[p,{status:"complete",request:m,response:o}]}async function f$(a,b,c,d,e){var f,g,h;let i={api_version:b,page_size:c,page_token:d},j={api_version:eH("api_version",null!=(f=null==i?void 0:i.api_version)?f:a._options.api_version,{explode:!1,charEncoding:"percent"})},k=eB("/{api_version}/webhooks")(j),l=eN({page_size:null==i?void 0:i.page_size,page_token:null==i?void 0:i.page_token}),m=new Headers(eD({Accept:"application/json"})),n=fo(await fp(a._options.security)),o={options:a._options,base_url:null!=(h=null!=(g=null==e?void 0:e.server_url)?g:a._baseURL)?h:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:n,security_source:a._options.security,retry_config:(null==e?void 0:e.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==e?void 0:e.retry_codes)||["408","409","429","5XX"]},p=a._createRequest(o,{security:n,method:"GET",baseURL:null==e?void 0:e.server_url,path:k,headers:m,query:l,body:null,userAgent:a._options.user_agent,timeout_ms:(null==e?void 0:e.timeout_ms)||a._options.timeout_ms||-1},e);if(!p.ok)return[p,{status:"invalid"}];let q=p.value,r=await a._do(q,{context:o,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:o.retry_config,retryCodes:o.retry_codes});if(!r.ok)return[r,{status:"request-error",request:q}];let s=r.value,[t]=await fl(fk("4XX"),fk("5XX"),fi("default"))(s,q);return!t.ok,[t,{status:"complete",request:q,response:s}]}async function f_(a,b,c,d,e){var f,g;let h=eG("body",d,{explode:!0}),i={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},j=eB("/{api_version}/webhooks/{id}:ping")(i),k=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),l=fo(await fp(a._options.security)),m={options:a._options,base_url:null!=(g=null!=(f=null==e?void 0:e.server_url)?f:a._baseURL)?g:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:l,security_source:a._options.security,retry_config:(null==e?void 0:e.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==e?void 0:e.retry_codes)||["408","409","429","5XX"]},n=a._createRequest(m,{security:l,method:"POST",baseURL:null==e?void 0:e.server_url,path:j,headers:k,body:h,userAgent:a._options.user_agent,timeout_ms:(null==e?void 0:e.timeout_ms)||a._options.timeout_ms||-1},e);if(!n.ok)return[n,{status:"invalid"}];let o=n.value,p=await a._do(o,{context:m,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!p.ok)return[p,{status:"request-error",request:o}];let q=p.value,[r]=await fl(fk("4XX"),fk("5XX"),fi("default"))(q,o);return!r.ok,[r,{status:"complete",request:o,response:q}]}async function f0(a,b,c,d,e){var f,g;let h=eG("body",d,{explode:!0}),i={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},j=eB("/{api_version}/webhooks/{id}:rotateSigningSecret")(i),k=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),l=fo(await fp(a._options.security)),m={options:a._options,base_url:null!=(g=null!=(f=null==e?void 0:e.server_url)?f:a._baseURL)?g:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:l,security_source:a._options.security,retry_config:(null==e?void 0:e.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==e?void 0:e.retry_codes)||["408","409","429","5XX"]},n=a._createRequest(m,{security:l,method:"POST",baseURL:null==e?void 0:e.server_url,path:j,headers:k,body:h,userAgent:a._options.user_agent,timeout_ms:(null==e?void 0:e.timeout_ms)||a._options.timeout_ms||-1},e);if(!n.ok)return[n,{status:"invalid"}];let o=n.value,p=await a._do(o,{context:m,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!p.ok)return[p,{status:"request-error",request:o}];let q=p.value,[r]=await fl(fk("4XX"),fk("5XX"),fi("default"))(q,o);return!r.ok,[r,{status:"complete",request:o,response:q}]}async function f1(a,b,c,d,e,f){var g,h;let i=eG("body",e,{explode:!0}),j={api_version:eH("api_version",null!=c?c:a._options.api_version,{explode:!1,charEncoding:"percent"}),id:eH("id",b,{explode:!1,charEncoding:"percent"})},k=eB("/{api_version}/webhooks/{id}")(j),l=eN({update_mask:d}),m=new Headers(eD({"Content-Type":"application/json",Accept:"application/json"})),n=fo(await fp(a._options.security)),o={options:a._options,base_url:null!=(h=null!=(g=null==f?void 0:f.server_url)?g:a._baseURL)?h:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:n,security_source:a._options.security,retry_config:(null==f?void 0:f.retries)||a._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==f?void 0:f.retry_codes)||["408","409","429","5XX"]},p=a._createRequest(o,{security:n,method:"PATCH",baseURL:null==f?void 0:f.server_url,path:k,headers:m,query:l,body:i,userAgent:a._options.user_agent,timeout_ms:(null==f?void 0:f.timeout_ms)||a._options.timeout_ms||-1},f);if(!p.ok)return[p,{status:"invalid"}];let q=p.value,r=await a._do(q,{context:o,isErrorStatusCode:a=>eT({status:a},["4XX","5XX"]),retryConfig:o.retry_config,retryCodes:o.retry_codes});if(!r.ok)return[r,{status:"request-error",request:q}];let s=r.value,[t]=await fl(fk("4XX"),fk("5XX"),fi("default"))(s,q);return!t.ok,[t,{status:"complete",request:q,response:s}]}class f2 extends e6{create(a,b){let{api_version:c}=a;return fr(new fq(fX(this,c5(a,["api_version"]),c,b)))}list(a,b){var c,d;return fr((c=null==a?void 0:a.api_version,d=null==a?void 0:a.page_size,new fq(f$(this,c,d,null==a?void 0:a.page_token,b))))}get(a,b,c){return fr(new fq(fZ(this,a,null==b?void 0:b.api_version,c)))}update(a,b,c){let d=null!=b?b:{},{api_version:e,update_mask:f}=d,g=c5(d,["api_version","update_mask"]);return fr(new fq(f1(this,a,e,f,void 0===b||0===Object.keys(g).length?void 0:g,c)))}delete(a,b,c){return fr(new fq(fY(this,a,null==b?void 0:b.api_version,c)))}rotateSigningSecret(a,b,c,d){return fr(new fq(f0(this,a,b,c,d)))}ping(a,b,c,d){return fr(new fq(f_(this,a,b,c,d)))}}let f3=class extends e6{get interactions(){var a;return null!=(a=this._interactions)?a:this._interactions=new fO(this._options)}get webhooks(){var a;return null!=(a=this._webhooks)?a:this._webhooks=new f2(this._options)}get agents(){var a;return null!=(a=this._agents)?a:this._agents=new fw(this._options)}get triggers(){var a;return null!=(a=this._triggers)?a:this._triggers=new fW(this._options)}get environments(){var a;return null!=(a=this._environments)?a:this._environments=new fB(this._options)}},f4=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function f5(a,b={}){var c,d,e,f,g;let h,i,j;return new f3(Object.assign(Object.assign({},b),{api_version:null!=(c=b.api_version)?c:(h=a.getApiVersion().replace(/^\/+|\/+$/g,""),i=a.getProject(),j=a.getLocation(),a.isVertexAI()&&h&&i&&j?`${h}/projects/${encodeURIComponent(i)}/locations/${encodeURIComponent(j)}`:h),security:null!=(d=b.security)?d:new d0({defaultHeaders:Object.assign(Object.assign({},null==(e=a.getDefaultHeaders)?void 0:e.call(a)),null==(f=a.getHeaders)?void 0:f.call(a)),getAuthHeaders:b=>a.getAuthHeaders(b)}),server_url:null!=(g=b.server_url)?g:function(a){let b=a.getBaseUrl();if(!b)throw Error("Base URL must be set.");return b.replace(/\/+$/,"")}(a)}))}class f6{constructor(a){this.parentClient=a}async create(a,b){let{api_version:c}=a,d=c5(a,["api_version"]);return!0===d.stream?ge(await gd(()=>this.getClient(c).interactions.create(Object.assign(Object.assign({},d),{stream:!0,api_version:c}),ga(b,!0)))):gf(await gc(new fq(fL(this.getClient(c),d,c,ga(b)))))}async get(a,b={},c){let{api_version:d,stream:e=!1,last_event_id:f,include_input:g}=null!=b?b:{};return!0===e?ge(await gd(()=>this.getClient(d).interactions.get(a,{stream:e,last_event_id:f,include_input:g,api_version:d},ga(c,!0)))):gf(await gc(new fq(fN(this.getClient(d),a,e,f,g,d,ga(c)))))}async delete(a,b={},c){return gd(()=>this.getClient(null==b?void 0:b.api_version).interactions.delete(a,{api_version:null==b?void 0:b.api_version},ga(c)))}async cancel(a,b={},c){var d;return gf(await gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fK(d,a,null==b?void 0:b.api_version,ga(c))))))}getClient(a){return a?f5(this.parentClient,{api_version:a}):(null!=this.sdk||(this.sdk=f5(this.parentClient)),this.sdk)}}class f7{constructor(a){this.parentClient=a}async create(a={},b){let c=null!=a?a:{},{api_version:d}=c,e=c5(c,["api_version"]);return gc(new fq(fs(this.getClient(d),e,d,ga(b))))}async list(a={},b){let{api_version:c,pageSize:d,pageToken:e,parent:f}=null!=a?a:{};return gc(new fq(fv(this.getClient(c),c,d,e,f,ga(b))))}async get(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fu(d,a,null==b?void 0:b.api_version,ga(c)))))}async delete(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(ft(d,a,null==b?void 0:b.api_version,ga(c)))))}getClient(a){return a?f5(this.parentClient,{api_version:a}):(null!=this.sdk||(this.sdk=f5(this.parentClient)),this.sdk)}}class f8{constructor(a){this.parentClient=a}async create(a,b){let{api_version:c}=a,d=c5(a,["api_version"]);return gc(new fq(fX(this.getClient(),d,c,ga(b))))}async list(a={},b){let{api_version:c,page_size:d,page_token:e}=null!=a?a:{};return gc(new fq(f$(this.getClient(),c,d,e,ga(b))))}async get(a,b={},c){var d;return gc((d=this.getClient(),new fq(fZ(d,a,null==b?void 0:b.api_version,ga(c)))))}async update(a,b={},c){let d=null!=b?b:{},{api_version:e,update_mask:f}=d,g=c5(d,["api_version","update_mask"]);return gc(new fq(f1(this.getClient(),a,e,f,g,ga(c))))}async delete(a,b={},c){var d;return gc((d=this.getClient(),new fq(fY(d,a,null==b?void 0:b.api_version,ga(c)))))}async rotateSigningSecret(a,b={},c){let d=null!=b?b:{},{api_version:e}=d,f=c5(d,["api_version"]);return gc(new fq(f0(this.getClient(),a,e,f,ga(c))))}async ping(a,b,c){let{api_version:d,body:e}=null!=b?b:{};return gc(new fq(f_(this.getClient(),a,d,e,ga(c))))}getClient(){return null!=this.sdk||(this.sdk=f5(this.parentClient)),this.sdk}}class f9{constructor(a){this.parentClient=a}async create(a,b){let{api_version:c}=a,d=c5(a,["api_version"]);return gc(new fq(fP(this.getClient(c),d,c,ga(b))))}async list(a={},b){let{api_version:c,filter:d,pageSize:e,pageToken:f}=null!=a?a:{};return gc(new fq(fT(this.getClient(c),c,d,e,f,ga(b))))}async get(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fR(d,a,null==b?void 0:b.api_version,ga(c)))))}async update(a,b,c){let{api_version:d}=b,e=c5(b,["api_version"]);return gc(new fq(fV(this.getClient(d),a,e,d,ga(c))))}async delete(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fQ(d,a,null==b?void 0:b.api_version,ga(c)))))}async run(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fU(d,a,null==b?void 0:b.api_version,ga(c)))))}async listExecutions(a,b={},c){let{api_version:d,pageSize:e,pageToken:f}=null!=b?b:{};return gc(new fq(fS(this.getClient(d),a,d,e,f,ga(c))))}getClient(a){return a?f5(this.parentClient,{api_version:a}):(null!=this.sdk||(this.sdk=f5(this.parentClient)),this.sdk)}}function ga(a,b=!1){var c,d,e,f;if(!a&&!b)return;let g=null!=a?a:{},{timeout:h,maxRetries:i,defaultBaseURL:j,query:k,body:l,fetchOptions:m}=g,n=c5(g,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),o=Object.assign({},n);gg(k)?o.extra_query=k:gb("query",k),gg(l)?o.extra_body=l:gb("body",l);let p=null!=(c=n.fetch_options)?c:m;p&&(o.fetch_options=p);let q=null!=(d=n.server_url)?d:j;q&&(o.server_url=q);let r=null!=(e=n.timeout_ms)?e:h;if(void 0!==r&&(o.timeout_ms=r),void 0!==i&&(o.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:i}),b){let a=new Headers(null!=(f=o.headers)?f:null==p?void 0:p.headers);a.set("Accept","text/event-stream"),o.headers=a}return o}function gb(a,b){null!=b&&console.warn(`GoogleGenAI.interactions: request option ${a} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function gc(a){var b,c;let[d,e]=await a.$inspect();if(!d.ok)throw es(d.error);return b=d.value,c=e,gg(b)&&"complete"===c.status?Object.assign(Object.assign({},b),{sdkHttpResponse:function(a,b){let c={};for(let[b,d]of a.headers.entries())c[b]=d;return{headers:c,responseInternal:a,json:async()=>b}}(c.response,b)}):b}async function gd(a){try{return await a()}catch(a){throw es(a)}}function ge(a){return new Proxy(a,{get(b,c){if(c!==Symbol.asyncIterator){let a=Reflect.get(b,c,b);return"function"==typeof a?a.bind(b):a}return function(){let b=a[Symbol.asyncIterator]();return{async next(...a){try{return await b.next(...a)}catch(a){throw es(a)}},async return(a){if(!b.return)return{done:!0,value:a};try{return await b.return(a)}catch(a){throw es(a)}},async throw(a){if(!b.throw)throw es(a);try{return await b.throw(a)}catch(a){throw es(a)}},[Symbol.asyncIterator](){return this}}}}})}function gf(a){let b=function(a){if(gg(a)){let b;if(Array.isArray(a.steps))return a;if("string"==typeof(b=a.model)&&f4.has(b)){let b=a.outputs;if(Array.isArray(b)){let{outputs:c}=a;return Object.assign(Object.assign({},c5(a,["outputs"])),{steps:[{type:"model_output",content:b}]})}}return Object.assign(Object.assign({},a),{steps:[]})}}(a);return b?function(a){var b,c,d;let e,f,g,h=Object.assign(Object.assign({},d=a),{created:gh(d.created),updated:gh(d.updated)}),i=null!=(b=h.steps)?b:[],j=[],k=!1;b:for(let a=i.length-1;a>=0;a--){let b=i[a];if("user_input"===b.type)break;if("model_output"!==b.type||!b.content){if(k)break;continue}let d=b.content;for(let a=d.length-1;a>=0;a--){let b=d[a];if("text"===b.type)k=!0,j.push(null!=(c=b.text)?c:"");else if(k)break b}}for(let a=i.length-1;a>=0;a--){let b=i[a];if("user_input"===b.type)break;if("model_output"===b.type&&b.content)for(let a=b.content.length-1;a>=0;a--){let c=b.content[a];"image"!==c.type||e||(e=c),"audio"!==c.type||f||(f=c),"video"!==c.type||g||(g=c)}}let l=j.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},h),l&&{output_text:l}),e?{output_image:e}:{}),f?{output_audio:f}:{}),g?{output_video:g}:{})}(b):a}function gg(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function gh(a){return a instanceof Date?a.toISOString():a}class gi{constructor(a){this.parentClient=a}async create(a,b){let{api_version:c}=a,d=c5(a,["api_version"]);return gc(new fq(fx(this.getClient(c),d,c,ga(b))))}async list(a={},b){let{api_version:c,page_size:d,page_token:e}=null!=a?a:{};return gc(new fq(fA(this.getClient(c),c,d,e,ga(b))))}async get(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fz(d,a,null==b?void 0:b.api_version,ga(c)))))}async delete(a,b={},c){var d;return gc((d=this.getClient(null==b?void 0:b.api_version),new fq(fy(d,a,null==b?void 0:b.api_version,ga(c)))))}getClient(a){return a?f5(this.parentClient,{api_version:a}):(null!=this.sdk||(this.sdk=f5(this.parentClient)),this.sdk)}}let gj="x-goog-api-key",gk="https://www.googleapis.com/auth/cloud-platform";class gl{constructor(a){if(void 0!==a.apiKey){this.apiKey=a.apiKey;return}const b=function(a){let b;if(!a)return{scopes:[gk]};if((b=a).scopes){if("string"==typeof b.scopes&&b.scopes!==gk||Array.isArray(b.scopes)&&0>b.scopes.indexOf(gk))throw Error(`Invalid auth scopes. Scopes must include: ${gk}`)}else b.scopes=[gk];return b}(a.googleAuthOptions);this.googleAuth=new bP.GoogleAuth(b)}async addAuthHeaders(a,b){if(void 0!==this.apiKey){if(this.apiKey.startsWith("auth_tokens/"))throw Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(a);return}return this.addGoogleAuthHeaders(a,b)}addKeyHeader(a){if(null===a.get(gj)){if(void 0===this.apiKey)throw Error("Trying to set API key header but apiKey is not set");a.append(gj,this.apiKey)}}async addGoogleAuthHeaders(a,b){if(void 0===this.googleAuth)throw Error("Trying to set google-auth headers but googleAuth is unset");for(let[c,d]of(await this.googleAuth.getRequestHeaders(b)))null===a.get(c)&&a.append(c,d)}}class gm{async download(a,b){if(a.downloadPath){let c=await gn(a,b);if(c instanceof b0){let b=(0,bQ.createWriteStream)(a.downloadPath);bS.Readable.fromWeb(c.responseInternal.body).pipe(b),await (0,bT.finished)(b)}else try{await (0,bR.writeFile)(a.downloadPath,c,{encoding:"base64"})}catch(b){throw Error(`Failed to write file to ${a.downloadPath}: ${b}`)}}}}async function gn(a,b){var c,d,e;let f=cR(a.file);if(void 0!==f)return await b.request({path:`files/${f}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:null==(c=a.config)?void 0:c.httpOptions,abortSignal:null==(d=a.config)?void 0:d.abortSignal});if(cP(a.file)){let b=null==(e=a.file.video)?void 0:e.videoBytes;if("string"==typeof b)return b;throw Error("Failed to download generated video, Uri or videoBytes not found.")}if(cQ(a.file)){let b=a.file.videoBytes;if("string"==typeof b)return b;throw Error("Failed to download video, Uri or videoBytes not found.")}throw Error("Unsupported file type")}class go{create(a,b,c){return new gp(a,b,c)}}class gp{constructor(a,b,c){this.url=a,this.headers=b,this.callbacks=c}connect(){this.ws=new bU(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(a){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.send(a)}close(){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.close()}}function gq(a,b){let c={},d=bZ(a,["parts"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>(function(a){let b={},c=bZ(a,["mediaResolution"]);if(null!=c&&bY(b,["mediaResolution"],c),void 0!==bZ(a,["toolCall"]))throw Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==bZ(a,["toolResponse"]))throw Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let d=bZ(a,["audioTranscription"]);null!=d&&bY(b,["audioTranscription"],d);let e=bZ(a,["codeExecutionResult"]);null!=e&&bY(b,["codeExecutionResult"],function(a){let b={},c=bZ(a,["outcome"]);null!=c&&bY(b,["outcome"],c);let d=bZ(a,["output"]);if(null!=d&&bY(b,["output"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(e));let f=bZ(a,["executableCode"]);null!=f&&bY(b,["executableCode"],function(a){let b={},c=bZ(a,["code"]);null!=c&&bY(b,["code"],c);let d=bZ(a,["language"]);if(null!=d&&bY(b,["language"],d),void 0!==bZ(a,["id"]))throw Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b}(f));let g=bZ(a,["fileData"]);null!=g&&bY(b,["fileData"],g);let h=bZ(a,["functionCall"]);null!=h&&bY(b,["functionCall"],h);let i=bZ(a,["functionResponse"]);null!=i&&bY(b,["functionResponse"],i);let j=bZ(a,["inlineData"]);null!=j&&bY(b,["inlineData"],j);let k=bZ(a,["text"]);null!=k&&bY(b,["text"],k);let l=bZ(a,["thought"]);null!=l&&bY(b,["thought"],l);let m=bZ(a,["thoughtSignature"]);null!=m&&bY(b,["thoughtSignature"],m);let n=bZ(a,["videoMetadata"]);if(null!=n&&bY(b,["videoMetadata"],n),void 0!==bZ(a,["partMetadata"]))throw Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return b})(a))),bY(c,["parts"],a)}let e=bZ(a,["role"]);return null!=e&&bY(c,["role"],e),c}function gr(a,b){let c={},d=bZ(a,["epochCount"]);null!=d&&bY(c,["epochCount"],d);let e=bZ(a,["learningRateMultiplier"]);null!=e&&bY(c,["learningRateMultiplier"],e);let f=bZ(a,["adapterSize"]);null!=f&&bY(c,["adapterSize"],f);let g=bZ(a,["batchSize"]);null!=g&&bY(c,["batchSize"],g);let h=bZ(a,["learningRate"]);null!=h&&bY(c,["learningRate"],h);let i=bZ(a,["generationConfig"]);return null!=i&&bY(c,["generationConfig"],function(a){let b={},c=bZ(a,["modelConfig"]);null!=c&&bY(b,["modelSelectionConfig"],c);let d=bZ(a,["responseJsonSchema"]);null!=d&&bY(b,["responseJsonSchema"],d);let e=bZ(a,["audioTranscriptionConfig"]);null!=e&&bY(b,["audioTranscriptionConfig"],e);let f=bZ(a,["audioTimestamp"]);null!=f&&bY(b,["audioTimestamp"],f);let g=bZ(a,["candidateCount"]);null!=g&&bY(b,["candidateCount"],g);let h=bZ(a,["enableAffectiveDialog"]);null!=h&&bY(b,["enableAffectiveDialog"],h);let i=bZ(a,["frequencyPenalty"]);null!=i&&bY(b,["frequencyPenalty"],i);let j=bZ(a,["logprobs"]);null!=j&&bY(b,["logprobs"],j);let k=bZ(a,["maxOutputTokens"]);null!=k&&bY(b,["maxOutputTokens"],k);let l=bZ(a,["mediaResolution"]);null!=l&&bY(b,["mediaResolution"],l);let m=bZ(a,["presencePenalty"]);null!=m&&bY(b,["presencePenalty"],m);let n=bZ(a,["responseFormat"]);if(null!=n){let a=n;Array.isArray(a)&&(a=a.map(a=>a)),bY(b,["responseFormat"],a)}let o=bZ(a,["responseLogprobs"]);null!=o&&bY(b,["responseLogprobs"],o);let p=bZ(a,["responseMimeType"]);null!=p&&bY(b,["responseMimeType"],p);let q=bZ(a,["responseModalities"]);null!=q&&bY(b,["responseModalities"],q);let r=bZ(a,["responseSchema"]);null!=r&&bY(b,["responseSchema"],r);let s=bZ(a,["routingConfig"]);null!=s&&bY(b,["routingConfig"],s);let t=bZ(a,["seed"]);null!=t&&bY(b,["seed"],t);let u=bZ(a,["speechConfig"]);null!=u&&bY(b,["speechConfig"],u);let v=bZ(a,["stopSequences"]);null!=v&&bY(b,["stopSequences"],v);let w=bZ(a,["temperature"]);null!=w&&bY(b,["temperature"],w);let x=bZ(a,["thinkingConfig"]);null!=x&&bY(b,["thinkingConfig"],x);let y=bZ(a,["topK"]);null!=y&&bY(b,["topK"],y);let z=bZ(a,["topP"]);return null!=z&&bY(b,["topP"],z),b}(i)),c}function gs(a,b){let c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s={},t=bZ(a,["sdkHttpResponse"]);null!=t&&bY(s,["sdkHttpResponse"],t);let u=bZ(a,["name"]);null!=u&&bY(s,["name"],u);let v=bZ(a,["state"]);null!=v&&bY(s,["state"],cO(v));let w=bZ(a,["createTime"]);null!=w&&bY(s,["createTime"],w);let x=bZ(a,["startTime"]);null!=x&&bY(s,["startTime"],x);let y=bZ(a,["endTime"]);null!=y&&bY(s,["endTime"],y);let z=bZ(a,["updateTime"]);null!=z&&bY(s,["updateTime"],z);let A=bZ(a,["error"]);null!=A&&bY(s,["error"],A);let B=bZ(a,["description"]);null!=B&&bY(s,["description"],B);let C=bZ(a,["baseModel"]);null!=C&&bY(s,["baseModel"],C);let D=bZ(a,["tunedModel"]);null!=D&&bY(s,["tunedModel"],D);let E=bZ(a,["preTunedModel"]);null!=E&&bY(s,["preTunedModel"],E);let F=bZ(a,["supervisedTuningSpec"]);null!=F&&bY(s,["supervisedTuningSpec"],F);let G=bZ(a,["preferenceOptimizationSpec"]);null!=G&&bY(s,["preferenceOptimizationSpec"],G);let H=bZ(a,["distillationSamplingSpec"]);null!=H&&bY(s,["distillationSamplingSpec"],(c={},null!=(d=bZ(H,["promptDatasetUri"]))&&bY(c,["promptDatasetUri"],d),null!=(e=bZ(H,["validationDatasetUri"]))&&bY(c,["validationDatasetUri"],e),null!=(f=bZ(H,["baseTeacherModel"]))&&bY(c,["baseTeacherModel"],f),null!=(g=bZ(H,["tunedTeacherModelSource"]))&&bY(c,["tunedTeacherModelSource"],g),null!=(h=bZ(H,["hyperparameters"]))&&bY(c,["hyperparameters"],gr(h)),c));let I=bZ(a,["distillationSpec"]);null!=I&&bY(s,["distillationSpec"],(i={},null!=(j=bZ(I,["baseTeacherModel"]))&&bY(i,["baseTeacherModel"],j),null!=(k=bZ(I,["hyperParameters"]))&&bY(i,["hyperParameters"],gr(k)),null!=(l=bZ(I,["pipelineRootDirectory"]))&&bY(i,["pipelineRootDirectory"],l),null!=(m=bZ(I,["promptDatasetUri"]))&&bY(i,["promptDatasetUri"],m),null!=(n=bZ(I,["studentModel"]))&&bY(i,["studentModel"],n),null!=(o=bZ(I,["trainingDatasetUri"]))&&bY(i,["trainingDatasetUri"],o),null!=(p=bZ(I,["tunedTeacherModelSource"]))&&bY(i,["tunedTeacherModelSource"],p),null!=(q=bZ(I,["tuningMode"]))&&bY(i,["tuningMode"],q),null!=(r=bZ(I,["validationDatasetUri"]))&&bY(i,["validationDatasetUri"],r),i));let J=bZ(a,["reinforcementTuningSpec"]);null!=J&&bY(s,["reinforcementTuningSpec"],J);let K=bZ(a,["tuningDataStats"]);null!=K&&bY(s,["tuningDataStats"],K);let L=bZ(a,["encryptionSpec"]);null!=L&&bY(s,["encryptionSpec"],L);let M=bZ(a,["partnerModelTuningSpec"]);null!=M&&bY(s,["partnerModelTuningSpec"],M);let N=bZ(a,["customBaseModel"]);null!=N&&bY(s,["customBaseModel"],N);let O=bZ(a,["evaluateDatasetRuns"]);if(null!=O){let a=O;Array.isArray(a)&&(a=a.map(a=>a)),bY(s,["evaluateDatasetRuns"],a)}let P=bZ(a,["experiment"]);null!=P&&bY(s,["experiment"],P);let Q=bZ(a,["fullFineTuningSpec"]);null!=Q&&bY(s,["fullFineTuningSpec"],Q);let R=bZ(a,["labels"]);null!=R&&bY(s,["labels"],R);let S=bZ(a,["outputUri"]);null!=S&&bY(s,["outputUri"],S);let T=bZ(a,["pipelineJob"]);null!=T&&bY(s,["pipelineJob"],T);let U=bZ(a,["serviceAccount"]);null!=U&&bY(s,["serviceAccount"],U);let V=bZ(a,["tunedModelDisplayName"]);null!=V&&bY(s,["tunedModelDisplayName"],V);let W=bZ(a,["tuningJobMetadata"]);null!=W&&bY(s,["tuningJobMetadata"],W);let X=bZ(a,["tuningJobState"]);null!=X&&bY(s,["tuningJobState"],X);let Y=bZ(a,["veoLoraTuningSpec"]);null!=Y&&bY(s,["veoLoraTuningSpec"],Y);let Z=bZ(a,["veoTuningSpec"]);return null!=Z&&bY(s,["veoTuningSpec"],Z),s}function gt(a,b){let c={},d=bZ(a,["gcsUri"]);null!=d&&bY(c,["validationDatasetUri"],d);let e=bZ(a,["vertexDatasetResource"]);return null!=e&&bY(c,["validationDatasetUri"],e),c}class gu extends bW{constructor(a){super(),this.apiClient=a,this.list=async(a={})=>new c0(bM.PAGED_ITEM_TUNING_JOBS,a=>this.listInternal(a),await this.listInternal(a),a),this.get=async a=>await this.getInternal(a),this.tune=async a=>{var b;if(this.apiClient.isVertexAI())if(a.baseModel.startsWith("projects/")){let c={tunedModelName:a.baseModel};(null==(b=a.config)?void 0:b.preTunedModelCheckpointId)&&(c.checkpointId=a.config.preTunedModelCheckpointId);let d=Object.assign(Object.assign({},a),{preTunedModel:c});return d.baseModel=void 0,await this.tuneInternal(d)}else{let b=Object.assign({},a);return await this.tuneInternal(b)}{let b=Object.assign({},a),c=await this.tuneMldevInternal(b),d="";return void 0!==c.metadata&&void 0!==c.metadata.tunedModel?d=c.metadata.tunedModel:void 0!==c.name&&c.name.includes("/operations/")&&(d=c.name.split("/operations/")[0]),{name:d,state:ba.JOB_STATE_QUEUED}}}}async getInternal(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d,e,h=(d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],e),d);return f=bX("{name}",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>gs(a))}{let b,c,h=(b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],c),b);return f=bX("{name}",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f,g,h,i,j,k,l,m,n,o;return b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["state"]))&&bY(b,["state"],cO(e)),null!=(f=bZ(a,["createTime"]))&&bY(b,["createTime"],f),null!=(g=bZ(a,["tuningTask","startTime"]))&&bY(b,["startTime"],g),null!=(h=bZ(a,["tuningTask","completeTime"]))&&bY(b,["endTime"],h),null!=(i=bZ(a,["updateTime"]))&&bY(b,["updateTime"],i),null!=(j=bZ(a,["description"]))&&bY(b,["description"],j),null!=(k=bZ(a,["baseModel"]))&&bY(b,["baseModel"],k),null!=(l=bZ(a,["_self"]))&&bY(b,["tunedModel"],(m={},null!=(n=bZ(l,["name"]))&&bY(m,["model"],n),null!=(o=bZ(l,["name"]))&&bY(m,["endpoint"],o),m)),b})}}async listInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f,g,h,i,j,k=(f={},null!=(g=bZ(a,["config"]))&&(h=bZ(g,["pageSize"]),void 0!==f&&null!=h&&bY(f,["_query","pageSize"],h),i=bZ(g,["pageToken"]),void 0!==f&&null!=i&&bY(f,["_query","pageToken"],i),j=bZ(g,["filter"]),void 0!==f&&null!=j&&bY(f,["_query","filter"],j)),f);return d=bX("tuningJobs",k._url),e=k._query,delete k._url,delete k._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(k),httpMethod:"GET",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b=function(a){let b={},c=bZ(a,["sdkHttpResponse"]);null!=c&&bY(b,["sdkHttpResponse"],c);let d=bZ(a,["nextPageToken"]);null!=d&&bY(b,["nextPageToken"],d);let e=bZ(a,["tuningJobs"]);if(null!=e){let a=e;Array.isArray(a)&&(a=a.map(a=>gs(a))),bY(b,["tuningJobs"],a)}return b}(a),c=new cd;return Object.assign(c,b),c})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(a){var b,c,d,e;let f="",g={};if(this.apiClient.isVertexAI()){let d,e,h=(d={},null!=(e=bZ(a,["name"]))&&bY(d,["_url","name"],e),d);return f=bX("{name}:cancel",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new ce;return Object.assign(e,d),e})}{let b,c,h=(b={},null!=(c=bZ(a,["name"]))&&bY(b,["_url","name"],c),b);return f=bX("{name}:cancel",h._url),g=h._query,delete h._url,delete h._query,this.apiClient.request({path:f,queryParams:g,body:JSON.stringify(h),httpMethod:"POST",httpOptions:null==(d=a.config)?void 0:d.httpOptions,abortSignal:null==(e=a.config)?void 0:e.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),b),e=new ce;return Object.assign(e,d),e})}}async tuneInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f,g,h,i,j,k=(f={},null!=(g=bZ(a,["baseModel"]))&&bY(f,["baseModel"],g),null!=(h=bZ(a,["preTunedModel"]))&&bY(f,["preTunedModel"],h),null!=(i=bZ(a,["trainingDataset"]))&&function(a,b,c){let d=bZ(c,["config","method"]);if(void 0===d&&(d="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===d){let c=bZ(a,["gcsUri"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","trainingDatasetUri"],c)}else if("PREFERENCE_TUNING"===d){let c=bZ(a,["gcsUri"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","trainingDatasetUri"],c)}else if("DISTILLATION"===d){let c=bZ(a,["gcsUri"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","promptDatasetUri"],c)}else if("REINFORCEMENT_TUNING"===d){let c=bZ(a,["gcsUri"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","trainingDatasetUri"],c)}let e=bZ(c,["config","method"]);if(void 0===e&&(e="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===e){let c=bZ(a,["vertexDatasetResource"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","trainingDatasetUri"],c)}else if("PREFERENCE_TUNING"===e){let c=bZ(a,["vertexDatasetResource"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","trainingDatasetUri"],c)}else if("DISTILLATION"===e){let c=bZ(a,["vertexDatasetResource"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","promptDatasetUri"],c)}else if("REINFORCEMENT_TUNING"===e){let c=bZ(a,["vertexDatasetResource"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","trainingDatasetUri"],c)}if(void 0!==bZ(a,["examples"]))throw Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.")}(i,f,a),null!=(j=bZ(a,["config"]))&&function(a,b,c){let d=bZ(c,["config","method"]);if(void 0===d&&(d="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===d){let c=bZ(a,["validationDataset"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec"],gt(c))}else if("PREFERENCE_TUNING"===d){let c=bZ(a,["validationDataset"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec"],gt(c))}else if("DISTILLATION"===d){let c=bZ(a,["validationDataset"]);void 0!==b&&null!=c&&bY(b,["distillationSpec"],gt(c))}else if("REINFORCEMENT_TUNING"===d){let c=bZ(a,["validationDataset"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec"],gt(c))}let e=bZ(a,["tunedModelDisplayName"]);void 0!==b&&null!=e&&bY(b,["tunedModelDisplayName"],e);let f=bZ(a,["description"]);void 0!==b&&null!=f&&bY(b,["description"],f);let g=bZ(c,["config","method"]);if(void 0===g&&(g="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===g){let c=bZ(a,["epochCount"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","hyperParameters","epochCount"],c)}else if("PREFERENCE_TUNING"===g){let c=bZ(a,["epochCount"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","hyperParameters","epochCount"],c)}else if("DISTILLATION"===g){let c=bZ(a,["epochCount"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","hyperParameters","epochCount"],c)}else if("REINFORCEMENT_TUNING"===g){let c=bZ(a,["epochCount"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","hyperParameters","epochCount"],c)}let h=bZ(c,["config","method"]);if(void 0===h&&(h="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===h){let c=bZ(a,["learningRateMultiplier"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],c)}else if("PREFERENCE_TUNING"===h){let c=bZ(a,["learningRateMultiplier"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],c)}else if("DISTILLATION"===h){let c=bZ(a,["learningRateMultiplier"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","hyperParameters","learningRateMultiplier"],c)}else if("REINFORCEMENT_TUNING"===h){let c=bZ(a,["learningRateMultiplier"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],c)}let i=bZ(c,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){let c=bZ(a,["exportLastCheckpointOnly"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","exportLastCheckpointOnly"],c)}else if("PREFERENCE_TUNING"===i){let c=bZ(a,["exportLastCheckpointOnly"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","exportLastCheckpointOnly"],c)}else if("DISTILLATION"===i){let c=bZ(a,["exportLastCheckpointOnly"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","exportLastCheckpointOnly"],c)}let j=bZ(c,["config","method"]);if(void 0===j&&(j="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===j){let c=bZ(a,["adapterSize"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","hyperParameters","adapterSize"],c)}else if("PREFERENCE_TUNING"===j){let c=bZ(a,["adapterSize"]);void 0!==b&&null!=c&&bY(b,["preferenceOptimizationSpec","hyperParameters","adapterSize"],c)}else if("DISTILLATION"===j){let c=bZ(a,["adapterSize"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","hyperParameters","adapterSize"],c)}else if("REINFORCEMENT_TUNING"===j){let c=bZ(a,["adapterSize"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","hyperParameters","adapterSize"],c)}let k=bZ(c,["config","method"]);if(void 0===k&&(k="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===k){let c=bZ(a,["tuningMode"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","tuningMode"],c)}else if("DISTILLATION"===k){let c=bZ(a,["tuningMode"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","tuningMode"],c)}let l=bZ(a,["customBaseModel"]);void 0!==b&&null!=l&&bY(b,["customBaseModel"],l);let m=bZ(c,["config","method"]);if(void 0===m&&(m="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===m){let c=bZ(a,["batchSize"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","hyperParameters","batchSize"],c)}else if("DISTILLATION"===m){let c=bZ(a,["batchSize"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","hyperParameters","batchSize"],c)}else if("REINFORCEMENT_TUNING"===m){let c=bZ(a,["batchSize"]);void 0!==b&&null!=c&&bY(b,["reinforcementTuningSpec","hyperParameters","batchSize"],c)}let n=bZ(c,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let c=bZ(a,["learningRate"]);void 0!==b&&null!=c&&bY(b,["supervisedTuningSpec","hyperParameters","learningRate"],c)}else if("DISTILLATION"===n){let c=bZ(a,["learningRate"]);void 0!==b&&null!=c&&bY(b,["distillationSpec","hyperParameters","learningRate"],c)}let o=bZ(a,["labels"]);void 0!==b&&null!=o&&bY(b,["labels"],o);let p=bZ(a,["beta"]);void 0!==b&&null!=p&&bY(b,["preferenceOptimizationSpec","hyperParameters","beta"],p);let q=bZ(a,["baseTeacherModel"]);void 0!==b&&null!=q&&bY(b,["distillationSpec","baseTeacherModel"],q);let r=bZ(a,["tunedTeacherModelSource"]);void 0!==b&&null!=r&&bY(b,["distillationSpec","tunedTeacherModelSource"],r);let s=bZ(a,["sftLossWeightMultiplier"]);void 0!==b&&null!=s&&bY(b,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],s);let t=bZ(a,["outputUri"]);void 0!==b&&null!=t&&bY(b,["outputUri"],t);let u=bZ(a,["rewardConfig"]);void 0!==b&&null!=u&&bY(b,["reinforcementTuningSpec","singleRewardConfig"],u);let v=bZ(a,["compositeRewardConfig"]);void 0!==b&&null!=v&&bY(b,["reinforcementTuningSpec","compositeRewardConfig"],v);let w=bZ(a,["samplesPerPrompt"]);void 0!==b&&null!=w&&bY(b,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],w);let x=bZ(a,["evaluateInterval"]);void 0!==b&&null!=x&&bY(b,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],x);let y=bZ(a,["checkpointInterval"]);void 0!==b&&null!=y&&bY(b,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],y);let z=bZ(a,["maxOutputTokens"]);void 0!==b&&null!=z&&bY(b,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],z);let A=bZ(a,["thinkingLevel"]);void 0!==b&&null!=A&&bY(b,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],A);let B=bZ(a,["validationDatasetUri"]);void 0!==b&&null!=B&&bY(b,["reinforcementTuningSpec","validationDatasetUri"],B);let C=bZ(a,["encryptionSpec"]);void 0!==b&&null!=C&&bY(b,["encryptionSpec"],C)}(j,f,a),f);return d=bX("tuningJobs",k._url),e=k._query,delete k._url,delete k._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(k),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>gs(a))}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let f,g,h,i,j,k=(f={},null!=(g=bZ(a,["baseModel"]))&&bY(f,["baseModel"],g),null!=(h=bZ(a,["preTunedModel"]))&&bY(f,["preTunedModel"],h),null!=(i=bZ(a,["trainingDataset"]))&&function(a){if(void 0!==bZ(a,["gcsUri"]))throw Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["vertexDatasetResource"]))throw Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let b=bZ(a,["examples"]);if(null!=b){let a=b;Array.isArray(a)&&(a=a.map(a=>a)),bY({},["examples","examples"],a)}}(i),null!=(j=bZ(a,["config"]))&&function(a,b){if(void 0!==bZ(a,["validationDataset"]))throw Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=bZ(a,["tunedModelDisplayName"]);if(void 0!==b&&null!=c&&bY(b,["displayName"],c),void 0!==bZ(a,["description"]))throw Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=bZ(a,["epochCount"]);void 0!==b&&null!=d&&bY(b,["tuningTask","hyperparameters","epochCount"],d);let e=bZ(a,["learningRateMultiplier"]);if(null!=e&&bY({},["tuningTask","hyperparameters","learningRateMultiplier"],e),void 0!==bZ(a,["exportLastCheckpointOnly"]))throw Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["preTunedModelCheckpointId"]))throw Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["adapterSize"]))throw Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["tuningMode"]))throw Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["customBaseModel"]))throw Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let f=bZ(a,["batchSize"]);void 0!==b&&null!=f&&bY(b,["tuningTask","hyperparameters","batchSize"],f);let g=bZ(a,["learningRate"]);if(void 0!==b&&null!=g&&bY(b,["tuningTask","hyperparameters","learningRate"],g),void 0!==bZ(a,["labels"]))throw Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["beta"]))throw Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["baseTeacherModel"]))throw Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["tunedTeacherModelSource"]))throw Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["sftLossWeightMultiplier"]))throw Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["outputUri"]))throw Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["rewardConfig"]))throw Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["compositeRewardConfig"]))throw Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["samplesPerPrompt"]))throw Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["evaluateInterval"]))throw Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["checkpointInterval"]))throw Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["maxOutputTokens"]))throw Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["thinkingLevel"]))throw Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["validationDatasetUri"]))throw Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==bZ(a,["encryptionSpec"]))throw Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(j,f),f);return d=bX("tunedModels",k._url),e=k._query,delete k._url,delete k._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(k),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f,g;return b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["name"]))&&bY(b,["name"],d),null!=(e=bZ(a,["metadata"]))&&bY(b,["metadata"],e),null!=(f=bZ(a,["done"]))&&bY(b,["done"],f),null!=(g=bZ(a,["error"]))&&bY(b,["error"],g),b})}}async validateReward(a){var b,c;let d="",e={};if(this.apiClient.isVertexAI()){let f,g,h,i,j,k,l=(f={},null!=(g=bZ(a,["parent"]))&&bY(f,["_url","parent"],g),null!=(h=bZ(a,["sampleResponse"]))&&bY(f,["sampleResponse"],gq(h)),null!=(i=bZ(a,["example"]))&&bY(f,["example"],function(a){let b={},c=bZ(a,["references"]);null!=c&&bY(b,["references"],c);let d=bZ(a,["contents"]);if(null!=d){let a=d;Array.isArray(a)&&(a=a.map(a=>gq(a))),bY(b,["contents"],a)}let e=bZ(a,["systemInstruction"]);return null!=e&&bY(b,["systemInstruction"],gq(e)),b}(i)),null!=(j=bZ(a,["singleRewardConfig"]))&&bY(f,["singleRewardConfig"],j),null!=(k=bZ(a,["compositeRewardConfig"]))&&bY(f,["compositeRewardConfig"],k),f);return d=bX("{parent}/tuningJobs:validateReinforcementTuningReward",l._url),e=l._query,delete l._url,delete l._query,this.apiClient.request({path:d,queryParams:e,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(b=a.config)?void 0:b.httpOptions,abortSignal:null==(c=a.config)?void 0:c.abortSignal}).then(a=>a.json().then(b=>(b.sdkHttpResponse={headers:a.headers},b))).then(a=>{let b,c,d,e,f,g=(b={},null!=(c=bZ(a,["sdkHttpResponse"]))&&bY(b,["sdkHttpResponse"],c),null!=(d=bZ(a,["overallReward"]))&&bY(b,["overallReward"],d),null!=(e=bZ(a,["error"]))&&bY(b,["error"],e),null!=(f=bZ(a,["rewardInfoDetails"]))&&bY(b,["rewardInfoDetails"],f),b),h=new cf;return Object.assign(h,g),h})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}let gv="x-goog-upload-status";async function gw(a,b,c,d){var e;let f=await gy(a,b,c,d),g=await (null==f?void 0:f.json());if((null==(e=null==f?void 0:f.headers)?void 0:e[gv])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return g.file}async function gx(a,b,c,d){var e;let f=await gy(a,b,c,d),g=await (null==f?void 0:f.json());if((null==(e=null==f?void 0:f.headers)?void 0:e[gv])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let h=b_(g),i=new ct;return Object.assign(i,h),i}async function gy(a,b,c,d){var e,f,g;let h=b,i=(null==d?void 0:d.baseUrl)||(null==(e=c.clientOptions.httpOptions)?void 0:e.baseUrl);if(i){let a=new URL(i),c=new URL(b);c.protocol=a.protocol,c.host=a.host,c.port=a.port,h=c.toString()}let j=0,k=0,l=new b0(new Response),m="upload";for(j=a.size;k<j;){let b=Math.min(8388608,j-k),e=a.slice(k,k+b);k+b>=j&&(m+=", finalize");let i=0,n=1e3;for(;i<3;){let a=Object.assign(Object.assign({},(null==d?void 0:d.headers)||{}),{"X-Goog-Upload-Command":m,"X-Goog-Upload-Offset":String(k),"Content-Length":String(b)});if(null==(f=null==(l=await c.request({path:"",body:e,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},d),{apiVersion:"",baseUrl:h,headers:a})}))?void 0:l.headers)?void 0:f[gv])break;i++,await gA(n),n*=2}if(k+=b,(null==(g=null==l?void 0:l.headers)?void 0:g[gv])!=="active")break;if(j<=k)throw Error("All content has been uploaded, but the upload status is not finalized.")}return l}async function gz(a){return{size:a.size,type:a.type}}function gA(a){return new Promise(b=>setTimeout(b,a))}class gB{async stat(a){let b={size:0,type:void 0};return"string"==typeof a?(b.size=(await bR.stat(a)).size,b.type=this.inferMimeType(a),b):await gz(a)}async upload(a,b,c,d){return"string"==typeof a?await this.uploadFileFromPath(a,b,c,d):gw(a,b,c,d)}async uploadToFileSearchStore(a,b,c,d){return"string"==typeof a?await this.uploadFileToFileSearchStoreFromPath(a,b,c,d):gx(a,b,c,d)}inferMimeType(a){return({aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"})[a.slice(a.lastIndexOf(".")+1).toLowerCase()]}async uploadFileFromPath(a,b,c,d){var e;let f=await this.uploadFileFromPathInternal(a,b,c,d),g=await (null==f?void 0:f.json());if((null==(e=null==f?void 0:f.headers)?void 0:e[gv])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return g.file}async uploadFileToFileSearchStoreFromPath(a,b,c,d){var e;let f=await this.uploadFileFromPathInternal(a,b,c,d),g=await (null==f?void 0:f.json());if((null==(e=null==f?void 0:f.headers)?void 0:e[gv])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let h=b_(g),i=new ct;return Object.assign(i,h),i}async uploadFileFromPathInternal(a,b,c,d){var e,f,g;let h,i=b,j=(null==d?void 0:d.baseUrl)||(null==(e=c.clientOptions.httpOptions)?void 0:e.baseUrl);if(j){let a=new URL(j),c=new URL(b);c.protocol=a.protocol,c.host=a.host,c.port=a.port,i=c.toString()}let k=0,l=0,m=new b0(new Response),n="upload",o=bV.basename(a);try{if(!(h=await bR.open(a,"r")))throw Error("Failed to open file");for(k=(await h.stat()).size;l<k;){let a=Math.min(8388608,k-l);l+a>=k&&(n+=", finalize");let b=new Uint8Array(a),{bytesRead:e}=await h.read(b,0,a,l);if(e!==a)throw Error(`Failed to read ${a} bytes from file at offset ${l}. bytes actually read: ${e}`);let j=new Blob([b]),p=0,q=1e3;for(;p<3;){let a=Object.assign(Object.assign({},(null==d?void 0:d.headers)||{}),{"X-Goog-Upload-Command":n,"X-Goog-Upload-Offset":String(l),"Content-Length":String(e),"X-Goog-Upload-File-Name":o});if(null==(f=null==(m=await c.request({path:"",body:j,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},d),{apiVersion:"",baseUrl:i,headers:a})}))?void 0:m.headers)?void 0:f[gv])break;p++,await gA(q),q*=2}if(l+=e,(null==(g=null==m?void 0:m.headers)?void 0:g[gv])!=="active")break;if(k<=l)throw Error("All content has been uploaded, but the upload status is not finalized.")}return m}finally{h&&await h.close()}}}class gC extends de{async registerFiles(a){if("u"<typeof process||!process.versions||!process.versions.node)throw Error("registerFiles is only supported in Node.js environments.");let b=a.auth,c=await b.getRequestHeaders(),d=a.config||{},e=d.httpOptions||{},f=Object.assign({},e.headers||{});if(c)if("function"==typeof c[Symbol.iterator])for(let[a,b]of c)f[a]=b;else for(let[a,b]of Object.entries(c))f[a]=b;return this._registerFiles({uris:a.uris,config:Object.assign(Object.assign({},d),{httpOptions:Object.assign(Object.assign({},e),{headers:f})})})}}class gD{getNextGenClient(){let a=this.httpOptions;return void 0===this._nextGenClient&&(this._nextGenClient=f5(this.apiClient,{timeout_ms:null==a?void 0:a.timeout})),(null==a?void 0:a.extraBody)&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return void 0!==this._interactions||(this._interactions=new f6(this.apiClient)),this._interactions}get webhooks(){return void 0!==this._webhooks||(this._webhooks=new f8(this.apiClient)),this._webhooks}get agents(){return void 0!==this._agents||(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new f7(this.apiClient)),this._agents}get triggers(){return void 0!==this._triggers||(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new f9(this.apiClient)),this._triggers}get environments(){return void 0!==this._environments||(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new gi(this.apiClient)),this._environments}constructor(a){var b,c,f,g;if(this.vertexai=function(a){var b;if(void 0!==a.enterprise||void 0!==a.vertexai){if(void 0!==a.enterprise&&void 0!==a.vertexai&&a.enterprise!==a.vertexai)throw Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return null!=(b=a.enterprise)?b:a.vertexai}let c=gE("GOOGLE_GENAI_USE_ENTERPRISE"),d=gE("GOOGLE_GENAI_USE_VERTEXAI"),e=gF(c),f=gF(d);return(void 0!==c&&void 0!==d&&e!==f&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),void 0!==c)?e:void 0!==d&&f}(a),(a.project||a.location)&&!this.vertexai)throw Error("Project and location are not supported for Gemini API backend.");const h=function(){let a=gE("GOOGLE_API_KEY"),b=gE("GEMINI_API_KEY");return a&&b&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),a||b||void 0}(),i=gE("GOOGLE_CLOUD_PROJECT"),j=gE("GOOGLE_CLOUD_LOCATION");this.apiKey=null!=(b=a.apiKey)?b:h,this.project=null!=(c=a.project)?c:i,this.location=null!=(f=a.location)?f:j,this.vertexai||this.apiKey||console.warn("API key should be set when using the Gemini API."),this.vertexai&&((null==(g=a.googleAuthOptions)?void 0:g.credentials)&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!a.project&&!a.location&&(i||j)&&a.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(a.project||a.location)&&!a.apiKey&&h?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!a.project&&!a.location&&!a.apiKey&&(i||j)&&h&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),this.location||this.apiKey||(this.location="global"));const k=function(a,b,c,f){return(null==a?void 0:a.baseUrl)?a.baseUrl:b?null!=e?e:c:null!=d?d:f}(a.httpOptions,this.vertexai,gE("GOOGLE_VERTEX_BASE_URL"),gE("GOOGLE_GEMINI_BASE_URL"));k&&(a.httpOptions?a.httpOptions.baseUrl=k:a.httpOptions={baseUrl:k}),this.apiVersion=a.apiVersion,this.httpOptions=a.httpOptions;const l=new gl({apiKey:this.apiKey,googleAuthOptions:a.googleAuthOptions});this.apiClient=new dG({auth:l,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:"gl-node/"+process.version,uploader:new gB,downloader:new gm}),this.models=new dW(this.apiClient),this.live=new dP(this.apiClient,l,new go),this.batches=new c1(this.apiClient),this.chats=new db(this.models,this.apiClient),this.caches=new c4(this.apiClient),this.files=new gC(this.apiClient),this.operations=new dX(this.apiClient),this.authTokens=new dY(this.apiClient),this.tunings=new gu(this.apiClient),this.fileSearchStores=new d$(this.apiClient)}}function gE(a){var b,c,d;return null!=(d=null==(c=null==(b=null==process?void 0:process.env)?void 0:b[a])?void 0:c.trim())?d:void 0}function gF(a){return void 0!==a&&"true"===a.toLowerCase()}},97328:(a,b,c)=>{"use strict";c.d(b,{E5:()=>j,Jp:()=>g,M6:()=>e,Ne:()=>d,O:()=>i,V8:()=>k,g4:()=>h,xg:()=>f});let d=["chat","api","schedule","trigger","subflow","mcp","internal","meeting"];function e(a){return"string"==typeof a&&d.includes(a)}function f(a){return"chat"!==a&&"api"!==a}let g="TOOL_CALL",h="FINAL_RESPONSE",i="ERROR",j="STAY_ON_NODE",k="IMPLICIT_SUBFLOW_RETURN"},97337:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),b.assignDefaults=void 0;let d=c(78276),e=c(94134);function f(a,b,c){let{gen:f,compositeRule:g,data:h,opts:i}=a;if(void 0===c)return;let j=(0,d._)`${h}${(0,d.getProperty)(b)}`;if(g)return void(0,e.checkStrictMode)(a,`default is ignored for: ${j}`);let k=(0,d._)`${j} === undefined`;"empty"===i.useDefaults&&(k=(0,d._)`${k} || ${j} === null || ${j} === ""`),f.if(k,(0,d._)`${j} = ${(0,d.stringify)(c)}`)}b.assignDefaults=function(a,b){let{properties:c,items:d}=a.schema;if("object"===b&&c)for(let b in c)f(a,b,c[b].default);else"array"===b&&Array.isArray(d)&&d.forEach((b,c)=>f(a,c,b.default))}},97356:(a,b,c)=>{"use strict";let{Transform:d}=c(57075),{isASCIINumber:e,isValidLastEventId:f}=c(26376);class g extends d{state;checkBOM=!0;crlfCheck=!1;eventEndCheck=!1;buffer=null;pos=0;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(a={}){a.readableObjectMode=!0,super(a),this.state=a.eventSourceSettings||{},a.push&&(this.push=a.push)}_transform(a,b,c){if(0===a.length)return void c();if(this.buffer?this.buffer=Buffer.concat([this.buffer,a]):this.buffer=a,this.checkBOM)switch(this.buffer.length){case 1:if(239===this.buffer[0])return void c();this.checkBOM=!1,c();return;case 2:if(239===this.buffer[0]&&187===this.buffer[1])return void c();this.checkBOM=!1;break;case 3:if(239===this.buffer[0]&&187===this.buffer[1]&&191===this.buffer[2]){this.buffer=Buffer.alloc(0),this.checkBOM=!1,c();return}this.checkBOM=!1;break;default:239===this.buffer[0]&&187===this.buffer[1]&&191===this.buffer[2]&&(this.buffer=this.buffer.subarray(3)),this.checkBOM=!1}for(;this.pos<this.buffer.length;){if(this.eventEndCheck){if(this.crlfCheck){if(10===this.buffer[this.pos]){this.buffer=this.buffer.subarray(this.pos+1),this.pos=0,this.crlfCheck=!1;continue}this.crlfCheck=!1}if(10===this.buffer[this.pos]||13===this.buffer[this.pos]){13===this.buffer[this.pos]&&(this.crlfCheck=!0),this.buffer=this.buffer.subarray(this.pos+1),this.pos=0,(void 0!==this.event.data||this.event.event||void 0!==this.event.id||this.event.retry)&&this.processEvent(this.event),this.clearEvent();continue}this.eventEndCheck=!1;continue}if(10===this.buffer[this.pos]||13===this.buffer[this.pos]){13===this.buffer[this.pos]&&(this.crlfCheck=!0),this.parseLine(this.buffer.subarray(0,this.pos),this.event),this.buffer=this.buffer.subarray(this.pos+1),this.pos=0,this.eventEndCheck=!0;continue}this.pos++}c()}parseLine(a,b){if(0===a.length)return;let c=a.indexOf(58);if(0===c)return;let d="",g="";if(-1!==c){d=a.subarray(0,c).toString("utf8");let b=c+1;32===a[b]&&++b,g=a.subarray(b).toString("utf8")}else d=a.toString("utf8"),g="";switch(d){case"data":void 0===b[d]?b[d]=g:b[d]+=`
443
443
  ${g}`;break;case"retry":e(g)&&(b[d]=g);break;case"id":f(g)&&(b[d]=g);break;case"event":g.length>0&&(b[d]=g)}}processEvent(a){a.retry&&e(a.retry)&&(this.state.reconnectionTime=parseInt(a.retry,10)),void 0!==a.id&&f(a.id)&&(this.state.lastEventId=a.id),void 0!==a.data&&this.push({type:a.event||"message",options:{data:a.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event={data:void 0,event:void 0,id:void 0,retry:void 0}}}a.exports={EventSourceStream:g}},97437:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});let d=c(98233);b.default={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:a=>(0,d.validateTuple)(a,"items")}},97465:(a,b,c)=>{"use strict";let d=c(34589),{AsyncResource:e}=c(16698),{InvalidArgumentError:f,SocketError:g}=c(61448),h=c(84285),{addSignal:i,removeSignal:j}=c(73135);class k extends e{constructor(a,b){if(!a||"object"!=typeof a)throw new f("invalid opts");if("function"!=typeof b)throw new f("invalid callback");const{signal:c,opaque:d,responseHeaders:e}=a;if(c&&"function"!=typeof c.on&&"function"!=typeof c.addEventListener)throw new f("signal must be an EventEmitter or EventTarget");super("UNDICI_CONNECT"),this.opaque=d||null,this.responseHeaders=e||null,this.callback=b,this.abort=null,i(this,c)}onConnect(a,b){this.reason?a(this.reason):(d(this.callback),this.abort=a,this.context=b)}onHeaders(){throw new g("bad connect",null)}onUpgrade(a,b,c){let{callback:d,opaque:e,context:f}=this;j(this),this.callback=null;let g=b;null!=g&&(g="raw"===this.responseHeaders?h.parseRawHeaders(b):h.parseHeaders(b)),this.runInAsyncScope(d,null,null,{statusCode:a,headers:g,socket:c,opaque:e,context:f})}onError(a){let{callback:b,opaque:c}=this;j(this),b&&(this.callback=null,queueMicrotask(()=>{this.runInAsyncScope(b,null,a,{opaque:c})}))}}a.exports=function a(b,c){if(void 0===c)return new Promise((c,d)=>{a.call(this,b,(a,b)=>a?d(a):c(b))});try{let a=new k(b,c),d={...b,method:"CONNECT"};this.dispatch(d,a)}catch(d){if("function"!=typeof c)throw d;let a=b?.opaque;queueMicrotask(()=>c(d,{opaque:a}))}}},97678:(a,b,c)=>{"use strict";let d,e=c(34589),f=c(84285),{channels:g}=c(62571),h=c(64704),{RequestContentLengthMismatchError:i,ResponseContentLengthMismatchError:j,RequestAbortedError:k,InvalidArgumentError:l,HeadersTimeoutError:m,HeadersOverflowError:n,SocketError:o,InformationalError:p,BodyTimeoutError:q,HTTPParserError:r,ResponseExceededMaxSizeError:s}=c(61448),{kUrl:t,kReset:u,kClient:v,kParser:w,kBlocking:x,kRunning:y,kPending:z,kSize:A,kWriting:B,kQueue:C,kNoRef:D,kKeepAliveDefaultTimeout:E,kHostHeader:F,kPendingIdx:G,kRunningIdx:H,kError:I,kPipelining:J,kSocket:K,kKeepAliveTimeoutValue:L,kMaxHeadersSize:M,kKeepAliveMaxTimeout:N,kKeepAliveTimeoutThreshold:O,kHeadersTimeout:P,kBodyTimeout:Q,kStrictContentLength:R,kMaxRequests:S,kCounter:T,kMaxResponseSize:U,kOnError:V,kResume:W,kHTTPContext:X,kClosed:Y}=c(49176),Z=c(65429),$=Buffer.alloc(0),_=Buffer[Symbol.species],aa=f.removeAllListeners,ab=Symbol("kIdleSocketValidation"),ac=Symbol("kIdleSocketValidationTimeout"),ad=Symbol("kSocketUsed"),ae=null,af=null,ag=null,ah=0,ai=null;class aj{constructor(a,b,{exports:c}){this.llhttp=c,this.ptr=this.llhttp.llhttp_alloc(Z.TYPE.RESPONSE),this.client=a,this.socket=b,this.timeout=null,this.timeoutWeakRef=new WeakRef(this),this.timeoutValue=null,this.timeoutType=null,this.statusCode=0,this.statusText="",this.upgrade=!1,this.headers=[],this.headersSize=0,this.headersMaxSize=a[M],this.shouldKeepAlive=!1,this.paused=!1,this.resume=this.resume.bind(this),this.bytesRead=0,this.keepAlive="",this.contentLength="",this.connection="",this.maxResponseSize=a[U]}setTimeout(a,b){a!==this.timeoutValue||1&b^1&this.timeoutType?(this.timeout&&(h.clearTimeout(this.timeout),this.timeout=null),a&&(1&b?this.timeout=h.setFastTimeout(ak,a,this.timeoutWeakRef):(this.timeout=setTimeout(ak,a,this.timeoutWeakRef),this.timeout?.unref())),this.timeoutValue=a):this.timeout&&this.timeout.refresh&&this.timeout.refresh(),this.timeoutType=b}resume(){!this.socket.destroyed&&this.paused&&(e(null!=this.ptr),e(null===af),this.llhttp.llhttp_resume(this.ptr),e(5===this.timeoutType),this.timeout&&this.timeout.refresh&&this.timeout.refresh(),this.paused=!1,this.execute(this.socket.read()||$),this.readMore())}readMore(){for(;!this.paused&&this.ptr;){let a=this.socket.read();if(null===a)break;this.execute(a)}}execute(a){e(null===af),e(null!=this.ptr),e(!this.paused);let{socket:b,llhttp:c}=this;a.length>ah&&(ai&&c.free(ai),ah=4096*Math.ceil(a.length/4096),ai=c.malloc(ah)),new Uint8Array(c.memory.buffer,ai,ah).set(a);try{let d;try{ag=a,af=this,d=c.llhttp_execute(this.ptr,ai,a.length)}finally{af=null,ag=null}if(d!==Z.ERROR.OK){let e=a.subarray(c.llhttp_get_error_pos(this.ptr)-ai);if(d===Z.ERROR.PAUSED_UPGRADE)this.onUpgrade(e);else if(d===Z.ERROR.PAUSED)this.paused=!0,b.unshift(e);else throw this.createError(d,e)}}catch(a){f.destroy(b,a)}}finish(){let a;e(null===af),e(null!=this.ptr),e(!this.paused);let{llhttp:b}=this;try{af=this,a=b.llhttp_finish(this.ptr)}finally{af=null}return a===Z.ERROR.OK?null:a===Z.ERROR.PAUSED||a===Z.ERROR.PAUSED_UPGRADE?(this.paused=!0,null):this.createError(a,$)}createError(a,b){let{llhttp:c,contentLength:d,bytesRead:e}=this;if(d&&e!==parseInt(d,10))return new j;let f=c.llhttp_get_error_reason(this.ptr),g="";if(f){let a=new Uint8Array(c.memory.buffer,f).indexOf(0);g="Response does not match the HTTP/1.1 protocol ("+Buffer.from(c.memory.buffer,f,a).toString()+")"}return new r(g,Z.ERROR[a],b)}destroy(){e(null===af),e(null!=this.ptr),this.llhttp.llhttp_free(this.ptr),this.ptr=null,this.timeout&&h.clearTimeout(this.timeout),this.timeout=null,this.timeoutValue=null,this.timeoutType=null,this.paused=!1}onStatus(a){return this.statusText=a.toString(),0}onMessageBegin(){let{socket:a,client:b}=this;if(a.destroyed)return -1;if(0===b[y])return f.destroy(a,new o("bad response",f.getSocketInfo(a))),-1;let c=b[C][b[H]];return c?(c.onResponseStarted(),0):-1}onHeaderField(a){let b=this.headers.length;return(1&b)==0?this.headers.push(a):this.headers[b-1]=Buffer.concat([this.headers[b-1],a]),this.trackHeader(a.length),0}onHeaderValue(a){let b=this.headers.length;(1&b)==1?(this.headers.push(a),b+=1):this.headers[b-1]=Buffer.concat([this.headers[b-1],a]);let c=this.headers[b-2];if(10===c.length){let b=f.bufferToLowerCasedHeaderName(c);"keep-alive"===b?this.keepAlive+=a.toString():"connection"===b&&(this.connection+=a.toString())}else 14===c.length&&"content-length"===f.bufferToLowerCasedHeaderName(c)&&(this.contentLength+=a.toString());return this.trackHeader(a.length),0}trackHeader(a){this.headersSize+=a,this.headersSize>=this.headersMaxSize&&f.destroy(this.socket,new n)}onUpgrade(a){let{upgrade:b,client:c,socket:d,headers:g,statusCode:h}=this;e(b),e(c[K]===d),e(!d.destroyed),e(!this.paused),e((1&g.length)==0);let i=c[C][c[H]];e(i),e(i.upgrade||"CONNECT"===i.method),this.statusCode=0,this.statusText="",this.shouldKeepAlive=!1,this.headers=[],this.headersSize=0,d.unshift(a),d[w].destroy(),d[w]=null,d[v]=null,d[I]=null,aa(d),c[K]=null,c[X]=null,c[C][c[H]++]=null,c.emit("disconnect",c[t],[c],new p("upgrade"));try{i.onUpgrade(h,g,d)}catch(a){f.destroy(d,a)}c[W]()}onHeadersComplete(a,b,c){let{client:d,socket:g,headers:h,statusText:i}=this;if(g.destroyed)return -1;if(0===d[y])return f.destroy(g,new o("bad response",f.getSocketInfo(g))),-1;let j=d[C][d[H]];if(!j)return -1;if(e(!this.upgrade),e(this.statusCode<200),100===a)return f.destroy(g,new o("bad response",f.getSocketInfo(g))),-1;if(b&&!j.upgrade)return f.destroy(g,new o("bad upgrade",f.getSocketInfo(g))),-1;if(e(3===this.timeoutType),this.statusCode=a,this.shouldKeepAlive=c||"HEAD"===j.method&&!g[u]&&"keep-alive"===this.connection.toLowerCase(),this.statusCode>=200){let a=null!=j.bodyTimeout?j.bodyTimeout:d[Q];this.setTimeout(a,5)}else this.timeout&&this.timeout.refresh&&this.timeout.refresh();if("CONNECT"===j.method||b)return e(1===d[y]),this.upgrade=!0,2;if(e((1&this.headers.length)==0),this.headers=[],this.headersSize=0,this.shouldKeepAlive&&d[J]){let a=this.keepAlive?f.parseKeepAliveTimeout(this.keepAlive):null;if(null!=a){let b=Math.min(a-d[O],d[N]);b<=0?g[u]=!0:d[L]=b}else d[L]=d[E]}else g[u]=!0;let k=!1===j.onHeaders(a,h,this.resume,i);return j.aborted?-1:"HEAD"===j.method||a<200?1:(g[x]&&(g[x]=!1,d[W]()),k?Z.ERROR.PAUSED:0)}onBody(a){let{client:b,socket:c,statusCode:d,maxResponseSize:g}=this;if(c.destroyed)return -1;let h=b[C][b[H]];return(e(h),e(5===this.timeoutType),this.timeout&&this.timeout.refresh&&this.timeout.refresh(),e(d>=200),g>-1&&this.bytesRead+a.length>g)?(f.destroy(c,new s),-1):(this.bytesRead+=a.length,!1===h.onData(a))?Z.ERROR.PAUSED:0}onMessageComplete(){let{client:a,socket:b,statusCode:c,upgrade:d,headers:g,contentLength:h,bytesRead:i,shouldKeepAlive:k}=this;if(b.destroyed&&(!c||k))return -1;if(d)return 0;e(c>=100),e((1&this.headers.length)==0);let l=a[C][a[H]];return(e(l),this.statusCode=0,this.statusText="",this.bytesRead=0,this.contentLength="",this.keepAlive="",this.connection="",this.headers=[],this.headersSize=0,c<200)?0:"HEAD"!==l.method&&h&&i!==parseInt(h,10)?(f.destroy(b,new j),-1):(l.onComplete(g),a[C][a[H]++]=null,b[ad]=0===a[z],b[B])?(e(0===a[y]),f.destroy(b,new p("reset")),Z.ERROR.PAUSED):k?b[u]&&0===a[y]?(f.destroy(b,new p("reset")),Z.ERROR.PAUSED):(null==a[J]||1===a[J]?setImmediate(a[W]):a[W](),0):(f.destroy(b,new p("reset")),Z.ERROR.PAUSED)}}function ak(a){let b=a.deref();if(!b)return;let{socket:c,timeoutType:d,client:g,paused:h}=b;3===d?(!c[B]||c.writableNeedDrain||g[y]>1)&&(e(!h,"cannot be paused while waiting for headers"),f.destroy(c,new m)):5===d?h||f.destroy(c,new q):8===d&&(e(0===g[y]&&g[L]),f.destroy(c,new p("socket idle timeout")))}function al(a){e("ERR_TLS_CERT_ALTNAME_INVALID"!==a.code);let b=this[w];if("ECONNRESET"===a.code&&b.statusCode&&!b.shouldKeepAlive){let a=b.finish();a&&(this[I]=a,this[v][V](a));return}this[I]=a,this[v][V](a)}function am(){this[w]?.readMore()}function an(){let a=this[w];if(a.statusCode&&!a.shouldKeepAlive){let b=a.finish();b&&f.destroy(this,b);return}f.destroy(this,new o("other side closed",f.getSocketInfo(this)))}function ao(){let a=this[w];aq(this),a&&(this[I]||!a.statusCode||a.shouldKeepAlive||(this[I]=a.finish()||this[I]),this[w].destroy(),this[w]=null);let b=this[I]||new o("closed",f.getSocketInfo(this)),c=this[v];if(c[K]=null,c[X]=null,c.destroyed){e(0===c[z]);let a=c[C].splice(c[H]);for(let d=0;d<a.length;d++){let e=a[d];f.errorRequest(c,e,b)}}else if(c[y]>0&&"UND_ERR_INFO"!==b.code){let a=c[C][c[H]];c[C][c[H]++]=null,f.errorRequest(c,a,b)}c[G]=c[H],e(0===c[y]),c.emit("disconnect",c[t],[c],b),c[W]()}function ap(){this[Y]=!0}function aq(a){a[ac]&&(clearTimeout(a[ac]),a[ac]=null),a[ab]=0}function ar(a,b,c,d,g,h,i,j){try{b?f.isBuffer(b)&&(e(h===b.byteLength,"buffer body must have content length"),g.cork(),g.write(`${i}content-length: ${h}\r
444
444
  \r
445
445
  `,"latin1"),g.write(b),g.uncork(),d.onBodySent(b),j||!1===d.reset||(g[u]=!0)):0===h?g.write(`${i}content-length: 0\r