@ibgib/space-gib 0.0.7 → 0.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/bootstrap.mjs +1 -1
- package/dist/client/{chunk-ULFNE26Y.mjs → chunk-DBHMHCGD.mjs} +190 -65
- package/dist/client/chunk-DBHMHCGD.mjs.map +7 -0
- package/dist/client/chunk-SUQ5QJH4.mjs +42 -0
- package/dist/client/chunk-SUQ5QJH4.mjs.map +7 -0
- package/dist/client/index.mjs +1 -1
- package/dist/client/script.mjs +1 -1
- package/dist/server/server.mjs +5446 -5165
- package/dist/server/server.mjs.map +4 -4
- package/package.json +4 -4
- package/src/client/AUTO-GENERATED-version.mts +1 -1
- package/src/client/api/space-gib-api-bridge.mts +7 -2
- package/src/client/components/keystone-details/keystone-details.css +117 -20
- package/src/client/components/keystone-details/keystone-details.html +33 -5
- package/src/client/components/keystone-details/keystone-details.mts +206 -14
- package/src/server/serve-gib/handlers/api/keystone/keystone-evolve.handler.mts +33 -0
- package/src/server/serve-gib/handlers/api/keystone/sso-link.handler.mts +25 -4
- package/src/server/serve-gib/handlers/api/keystone/sso-login.handler.mts +4 -3
- package/dist/client/chunk-RXFIBFRK.mjs +0 -42
- package/dist/client/chunk-RXFIBFRK.mjs.map +0 -7
- package/dist/client/chunk-ULFNE26Y.mjs.map +0 -7
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Aa as
|
|
1
|
+
import{Aa as ji,B as K,C as Ki,D as Je,Db as no,E as ot,Fb as fr,G as Xi,Gb as pr,H as Yi,Hb as mr,I as ne,Ib as hr,Jb as gr,La as Ht,Mb as br,Sa as er,Sb as O,Ua as tr,Ub as Se,Vb as oo,W as Qi,Wb as yr,X as Zi,Xb as Er,Yb as Ir,Zb as vr,_b as wr,a as f,ab as eo,ac as ye,b as Dt,bb as nr,bc as Tr,c as te,d as kt,db as se,dc as Cr,e as Lt,eb as oe,ec as $e,f as zi,fb as V,fc as _r,g as M,gc as Ge,h as W,hb as or,hc as it,i as y,ib as ir,jb as rr,k as ze,kb as sr,lb as ar,m as It,mb as Vt,mc as Sr,n as nt,nb as q,nc as io,o as Ut,ob as lr,oc as rt,p as Ft,pb as Tt,pc as Q,q as vt,qb as cr,rb as ke,sb as Le,t as z,tb as dr,u as Ji,ub as ur,v as S,vb as Bt,w as F,wb as to,y as Wi,yb as me,z as wt,zb as qt}from"./chunk-SUQ5QJH4.mjs";var Ee=V,ro=class n{static{f(this,"IbGibComponentService")}lc=`[${n.name}]`;_registeredComponentsMeta=[];initialized;constructor(){this.initialized=this.initialize()}async initialize(){let e=`[${this.initialize.name}]`;try{Ee&&console.log(`${e} starting... (I: 1cf04e8d768f4b5c55e7c3861e2d2225)`),console.log(`${e} does nothing atow (I: 65bb46c88c82b637ad928b8bf1a07225)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Ee&&console.log(`${e} complete.`)}}registerComponentMeta(e){this._registeredComponentsMeta.push(e),Ee&&console.log(`${this.lc}[registerComponentMeta] component meta registered: ${e.constructor.name} (I: 88ddcbd0c8caa2342af0e7348f171225)`)}unregisterComponentMeta(e){this._registeredComponentsMeta=this._registeredComponentsMeta.filter(t=>t!==e),Ee&&console.log(`${this.lc}[unregisterComponentMeta] component meta unregistered: ${e.constructor.name} (I: 4e84b5274de688248984896a90f5cc25)`)}async getComponentInstance({useRegExpPrefilter:e,path:t,ibGibAddr:o}){let i=`${this.lc}[${this.getComponentInstance.name}]`;try{Ee&&console.log(`${i} starting... (I: 684ef316cbdb4a3b1fdc96096c273b25)`);let r,a=Ct.getRegisteredComponentsMeta(),c=e?a.filter(d=>{let u=d.routeRegExp?d.routeRegExp.test(t):!1;return Ee&&console.log(`${i} ${d.componentName} ${d.routeRegExp} componentMatchesPath: ${u} (I: 3758520e6a4a57f218396c8649283425)`),u}):a.concat();for(let d of c)if(d.fnHandleRoute?await d.fnHandleRoute({path:t,ibGibAddr:o}):!0){r=await d.createInstance({path:t,ibGibAddr:o});break}return r}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{Ee&&console.log(`${i} complete.`)}}async inject({parentEl:e,componentToInject:t}){let o=`${this.lc}[${this.inject.name}]`;try{if(Ee&&console.log(`${o} starting... (I: 6844cf07eaf8a5b1b106784f7db17125)`),!e)throw new Error(`${o} parentEl required. (E: 6f4eb2d682856ef47d173b970ec3c825)`);if(!t)throw new Error(`${o} componentToInject required. (E: decf0b51ad49257ce44fecbcf84c3a25)`);if(!t.meta)throw new Error(`${o} componentToInject.meta required. (E: f8827c0602ca7b0e030d0b3e2c4a4825)`);if(!t.meta.componentName)throw new Error(`${o} componentToInject.meta.componentName required. (E: 5dcae244ae32690f7b73ce27a32a3c25)`);e.innerHTML="",e.appendChild(t),e.classList.remove("fade-out")}catch(i){console.error(`${o} ${y(i)}`),e.innerHTML=`<p class="error">Error loading component for route. error:</p><br /><br /><p>${i.message}</p>`}finally{Ee&&console.log(`${o} complete.`)}}getRegisteredComponentsMeta(){return[...this._registeredComponentsMeta]}},Ct;async function ce(){let n=`[${ce.name}]`;try{return Ee&&console.log(`${n} starting... (I: 853694c88223381339103a3765129925)`),Ct||(Ct=new ro,await Ct.initialized),Ct}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{Ee&&console.log(`${n} complete.`)}}f(ce,"getComponentSvc");var Ar="left-panel";var xr="right-panel";var Pr="left-resizer",Nr="right-resizer",$r="footer-resizer",Gr="btn-left-panel-toggle",Rr="btn-right-panel-toggle",Mr="btn-create-keystone",so="center-panel-content";var Dr=`:host {
|
|
2
2
|
display: block;
|
|
3
3
|
width: 100%;
|
|
4
4
|
max-width: 600px;
|
|
@@ -62,7 +62,7 @@ h2 {
|
|
|
62
62
|
font-size: 0.8rem;
|
|
63
63
|
color: var(--clr-warn);
|
|
64
64
|
margin: 0.5rem 0 0;
|
|
65
|
-
}`;var
|
|
65
|
+
}`;var kr=`<div id="container" class="component-container">\r
|
|
66
66
|
<h2 id="title">Keystone Creator</h2>\r
|
|
67
67
|
<div class="content">\r
|
|
68
68
|
<p>This will generate a new root keystone (identity) for your space.</p>\r
|
|
@@ -1161,41 +1161,41 @@ body::before {
|
|
|
1161
1161
|
font-size: 0.85rem;
|
|
1162
1162
|
word-break: break-all;
|
|
1163
1163
|
color: var(--clr-accent);
|
|
1164
|
-
}`;var Dr={$schema:"../schemas/keystone.high.schema.json",metadata:{name:"High Security Profile",securityLevel:"high"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-512",rounds:4,behavior:{size:2e3,replenish:"top-up",selectSequentially:10,selectRandomly:10,targetBindingCount:16}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-512",rounds:4,behavior:{size:2e3,replenish:"replace-all",selectSequentially:10,selectRandomly:10,targetBindingCount:16}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-512",rounds:20,behavior:{size:2e3,replenish:"delete-all",selectSequentially:50,selectRandomly:50,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-512",rounds:4,behavior:{size:2e3,replenish:"top-up",selectSequentially:10,selectRandomly:10,targetBindingCount:16}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-512",rounds:4,behavior:{size:2e3,replenish:"top-up",selectSequentially:10,selectRandomly:10,targetBindingCount:16}}}};var Lr={$schema:"../schemas/keystone.medium.schema.json",metadata:{name:"Medium Security Profile",securityLevel:"medium"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:2,behavior:{size:500,replenish:"top-up",selectSequentially:5,selectRandomly:5,targetBindingCount:10}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:500,replenish:"replace-all",selectSequentially:5,selectRandomly:5,targetBindingCount:10}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:10,behavior:{size:500,replenish:"delete-all",selectSequentially:20,selectRandomly:20,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:2,behavior:{size:500,replenish:"top-up",selectSequentially:5,selectRandomly:5,targetBindingCount:10}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:500,replenish:"top-up",selectSequentially:5,selectRandomly:5,targetBindingCount:10}}}};var kr={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Low Security Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"replace-all",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:5,behavior:{size:100,replenish:"delete-all",selectSequentially:3,selectRandomly:3,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}}}};var Ur={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Session/Saga Identity Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:50,replenish:"replace-all",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:5,behavior:{size:50,replenish:"delete-all",selectSequentially:3,selectRandomly:3,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}}}};var Fr={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Test Identity Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:12,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:3}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:12,replenish:"replace-all",selectSequentially:1,selectRandomly:2,targetBindingCount:3}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:5,behavior:{size:12,replenish:"delete-all",selectSequentially:3,selectRandomly:3,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:12,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:3}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:20,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:3}}}};var Hr={$schema:"../schemas/keystone.high.schema.json",metadata:{name:"Domain Identity Profile",securityLevel:"high"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-512",rounds:4,behavior:{size:2e3,replenish:"top-up",selectSequentially:10,selectRandomly:10,targetBindingCount:16}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-512",rounds:6,behavior:{size:2e3,replenish:"replace-all",selectSequentially:12,selectRandomly:12,targetBindingCount:16}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-512",rounds:20,behavior:{size:2e3,replenish:"delete-all",selectSequentially:50,selectRandomly:50,targetBindingCount:0}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-512",rounds:4,behavior:{size:2e3,replenish:"top-up",selectSequentially:10,selectRandomly:10,targetBindingCount:16}}}};var Vr={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Sync Delegate Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"replace-all",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:5,behavior:{size:100,replenish:"delete-all",selectSequentially:3,selectRandomly:3,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}}}};var Ct=class n{static{f(this,"KeystoneProfileBuilder")}_template;_username;_email;_description;_details;_customizations={};constructor(e){this._template=JSON.parse(JSON.stringify(e))}static buildKeystone(e){let t;switch(e){case"high":t=Dr;break;case"medium":t=Lr;break;case"low":t=kr;break;case"session":t=Ur;break;case"test":t=Fr;break;case"domain":t=Hr;break;case"sync":t=Vr;break;default:throw new Error(`Unknown profile name: ${e} (E: fc10a8ad482ef2bda871ac567d268d26)`)}return new n(t)}withUsername(e){return this._username=e,this}withEmail(e){return this._email=e,this}withDescription(e){return this._description=e,this}withDetails(e){return this._details=e,this}customizePool(e,t){let{behavior:o,...i}=t;return this._customizations[e]={template:i,behavior:o},this}getFrameDetails(){let e={...this._details};return this._username&&(e.username=this._username),this._email&&(e.email=this._email),this._description&&(e.description=this._description),e}async compileConfigs(){let e=[],t="";if(this._username||this._email){let o=`${this._username||""}:${this._email||""}`;t=await kt({s:o})}else t=await kt({s:"default-keystone-salt"});for(let[o,i]of Object.entries(this._template.pools)){let r=this._customizations[i.id];r&&(r.template&&Object.assign(i,r.template),r.behavior&&i.behavior&&Object.assign(i.behavior,r.behavior));let l=`${t}-${i.id}`,c=await kt({s:l}),d=vr({template:i,salt:c});e.push(d)}return e}};var St=!1,Ot=class n{static{f(this,"WitnessBase_V1")}lc=`[${n.name}]`;set trace(e){let t=`${this.lc}[set trace]`;e!==(this.data?.trace||!1)&&(this.data?(this.data.trace=e,delete this.gib):console.warn(`${t} data is falsy. Can't set.`))}get trace(){return this.data?.trace??!1}set catchAllErrors(e){let t=`${this.lc}[set catchAllErrors]`;e!==this.data?.catchAllErrors&&(this.data?(this.data.catchAllErrors=e,delete this.gib):console.error(`${t} data is falsy. Can't set value.`))}get catchAllErrors(){let e=`${this.lc}[catchAllErrors]`,t=this.data?.catchAllErrors||!1;return(St||this.trace)&&console.log(`${e} result: ${t}`),t}ib="";gib;data;rel8ns;initialized;constructor(e,t){e&&(this.data=e),t&&(this.rel8ns=t),this.initialized=this.initialize()}initialize(){return Promise.resolve()}toIbGibDto(){return se({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return St&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=te(e.ib),this.gib=te(e.gib),e.data?this.data=te(e.data):delete this.data,e.rel8ns?this.rel8ns=te(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(o){throw console.error(`${t} ${o.message}`),o}finally{St&&console.log(`${t} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{await this.initialized,this.gib||(this.gib=await Oi(this.toIbGibDto()));let o=await this.validateThis();if(o?.length>0){for(let l of o)console.error(`${t} ${l}`);throw new Error("internal witness validation failed. See `WitnessBase_V1.validateThis` (E: 2b5f73cadbfa416ba189346f3c31cd0c)")}let i=await this.validateWitnessArg(e);if(i?.length>0){for(let l of i)console.error(`${t} ${l}`);throw new Error("arg validation failed. See `WitnessBase_V1.validateWitnessArg` (E: 51531a1d928a485e8ffc277145ec44e9)")}(St||this.trace)&&console.log(`${t} addr: ${S(e)}`),St&&console.log(`${t} addr: ${S(e)} (I: f4cf13a44c4e4fc3903f14018e616c64)`);let r=await this.witnessImpl(e);return this.data?.persistOptsAndResultIbGibs&&await this.persistOptsAndResultIbGibs({arg:e,result:r}),r}catch(o){if(console.error(`${t} ${o.message||"unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)"}`),this.catchAllErrors)return;throw o}}async validateWitnessArg(e){let t=`${this.lc}[${this.validateWitnessArg.name}]`;try{let o=[];e||o.push("arg required (E: a222db3b668e4bb09cfd82e75c07bfa6)");let i=Wi({ib:e?.ib});(i?.length??!1)&&o.push(`invalid arg.ib (E: 2ae362ef274d4c3bb9716800f2106d28) errors: ${i.join(`
|
|
1165
|
-
`)}`);let r=
|
|
1166
|
-
`)}`);let
|
|
1167
|
-
`)}`):this.data?.allowPrimitiveArgs||K({gib:e.gib}).isPrimitive&&o.push('arg is primitive (i.e. gib === "gib") and witness.data.allowPrimitiveArgs is falsy. (E: d0aa3d7ad4f54b01bd0023300d15ecd9)'),o}catch(o){throw console.error(`${t} ${o.message}`),o}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`,t=[];try{this.ib||t.push("this.ib is falsy."),this.gib||t.push("this.gib is falsy.")}catch(o){throw console.error(`${e} ${o.message}`),o}return t}persistOptsAndResultIbGibs({arg:e,result:t}){let o=`${this.lc}[${this.persistOptsAndResultIbGibs.name}]`;return console.warn(`${o} not implemented in this base class. Override this in descendent class. (W: 087514e851704322a4ec8069a73ce944)`),Promise.resolve()}};var Br="___whitespace___";var Ee=!1;function qr({commentText:n,addlMetadataText:e}){let t=`[${qr.name}]`;try{if(!n)throw new Error("commentText required. (E: 22fdfd0aa0524a18b63a9405b312c99e)");let o=Et({text:n,length:20,replaceMap:{"?":"__qm__"}});if(e){e.length>128&&console.warn(`${t} addlMetadataText (${e.length}) is too long. Max length: ${128}`);let i=Et({text:e,length:128});if(!i)throw new Error("(UNEXPECTED) addlMetadataText contains no safe characters? (E: dd03c578ada2836b05c94a4aa1785222)");return`comment ${o} ${i}`}else return`comment ${o}`}catch(o){throw console.error(`${t} ${o.message}`),o}}f(qr,"getCommentIb");function Ke({ib:n}){let e=`${Ke.name}]`;try{if(Ee&&console.log(`${e} starting... (I: 1a16f5e3134599eeb585eae77ee6af22)`),!n)throw new Error("ib required (E: d89f8c4df46b970585c82bc89c1c6322)");let[t,o,i]=n.split(" ");for(;o.includes("__qm__");)o=o.replace("__qm__","?");return{safeIbCommentText:o,safeIbCommentMetadataText:i}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ee&&console.log(`${e} complete.`)}}f(Ke,"parseCommentIb");async function Xe({text:n,addlMetadataText:e,saveInSpace:t,space:o,dontTrimText:i}){let r=`[${Xe.name}]`;Ee&&console.log(`${r} starting...`);try{if(!n)throw new Error("text required (E: 3e3d0f555e1a83771a6548eb10943522)");if(i||(n=n.trim()),!n)throw new Error("text cannot be only whitespace when dontTrimText is falsy. (E: d6db3537b9834294836aeb70987c908e)");let l={text:n,textTimestamp:Lt()},c={parentIbGib:ne.primitive({ib:"comment"}),ib:qr({commentText:n.trim()||Br,addlMetadataText:e}),data:l,dna:!0,tjp:{uuid:!0,timestamp:!0},nCounter:!0};Ee&&console.log(`${r} opts: ${M(c)}`);let d=await ne.firstGen(c);if(t){if(!o)throw new Error("space required if saveInSpace is truthy (E: 40f69f22f21b4279a83cb746cb4b0da1)");await Qi({resTransform:d,space:o})}return d}catch(l){throw console.error(`${r} ${l.message}`),l}}f(Xe,"createCommentIbGib");function Ye({ibGib:n}){let e=`[${Ye.name}]`;try{if(Ee&&console.log(`${e} starting...`),!n)throw new Error("ibGib required (E: f204dac30ae548b0a049f1c4d8048502)");let{ib:t,data:o,rel8ns:i}=n;if(!i)return Ee&&console.log(`${e} rel8ns falsy, NOT a comment (I: 6e145eb2d0ba46629746215a3b655fd5)`),!1;let r=i.ancestor||[];return r&&r.includes("comment^gib")?(Ee&&console.log(`${e} descends from comment^gib, YES is a comment (I: 1a8557780e2e4c1580d5a2585567762b)`),!0):o?o.text&&t?.includes("comment")?(Ee&&console.log(`${e} has text, and ib has 'comment', YES is a comment (I: 3aa03bcd639d4ec7abd7ead917eda3d8)`),!0):(Ee&&console.log(`${e} reached end, doesn't have comment qualities. NOT a comment. (I: cfa529f27f9d490abd476c924ef77087)`),!1):(Ee&&console.log(`${e} data falsy, NOT a comment (I: 30b20ff6785f432f98489f11efe24299)`),!1)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ee&&console.log(`${e} complete.`)}}f(Ye,"isComment");var U=!1,zt=class n extends Ot{static{f(this,"WitnessWithContextBase_V1")}lc=`[${n.name}]`;metaspace;_contextChangesSubscription;_currentWorkingContextIbGib;_currentWorkingContextIbGib_PriorChildrenAddrs=[];_updatingContext=!1;constructor(e,t){super(e,t),this.initialized=this.initialize()}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{U&&console.log(`${e} starting... (I: f0e65ab0f80046a59668ddfbf9f47a4a5)`),await super.initialize()}catch(t){console.error(`${e} ${y(t)}`)}finally{U&&console.log(`${e} complete.`)}}async loadNewerSelfIfAvailable(){let e=`${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;try{if(U&&console.log(`${e} starting... (I: 94755c3131f4dfa12d20fa38e2926522)`),this.metaspace){let t=S({ibGib:this}),o=await this.metaspace.getLatestAddr({ibGib:this});if(o&&o!==t){let i=await this.metaspace.get({addr:o});if(!i||!i?.success||(i?.ibGibs??[]).length===0)throw new Error("could not get newer ibgib in timeline (E: 15fa346c8ac17edb96e4b0870104c122)");await this.loadIbGibDto(i.ibGibs[0]);let r=await this.validateThis();if(r?.length>0)throw new Error(`validationErrors when loading newer version: ${M(r)} (E: 0d9f0684a1ff6af44e20a57130e3ac22)`)}}else console.warn(`${e} this.metaspace undefined (W: 44cc5bf1b14b4695b8de4c589787be06)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{U&&console.log(`${e} complete.`)}}async rel8To({ibGibs:e,rel8nName:t,linked:o,metaspace:i}){let r=`${this.lc}[${this.rel8To.name}]`;try{if(U&&console.log(`${r} starting...`),(e??[]).length===0)throw new Error("ibGibs required (E: 2fd13de0f025b170885bede4d7a50922)");if(t=t||this.data?.defaultRel8nName,!t)throw new Error("rel8nName required either as an arg or in this.data.defaultRel8nName (E: 43ab8ae63694a2a82cd8a70ed6b6b522)");let l=await this.validateThis();if(l?.length>0)throw new Error(`this is an invalid ibGib. thisValidationErrors: ${l.join("|")} (E: 8f08716866cd13bf254222ee9e6a6722)`);if(i=i??this.metaspace,!i)throw new Error("either metaspace or this.metaspace required (E: b5f9453ddb394a2b76dec74c7304df22)");let d=(this.rel8ns?this.rel8ns[t]??[]:[]).map(b=>K({ibGibAddr:b}).tjpGib),u=e.filter(b=>{let E=K({ibGibAddr:S({ibGib:b})}).tjpGib;return!d.includes(E)});if(u.length===0){U&&console.log(`${r} already rel8d to all incoming ibGib(s) via tjp. (I: 5e9d94a98ba262f146c0c0b765157922)`);return}let p=u.map(b=>S({ibGib:b})),m=await Je({src:this.toIbGibDto(),rel8nsToAddByAddr:{[t]:p},linkedRel8ns:o?["past","ancestor",t]:["past","ancestor"],dna:!0,nCounter:!0}),h=m.newIbGib,g=await ot({ibGib:h});if(g?.length??!1)throw new Error(`new this ibgib would have validation errors. aborting. newThisValidationErrors: ${g.join("|")} (E: eb816a27156c246c121ef55e37d59322)`);await i.persistTransformResult({resTransform:m}),await this.loadIbGibDto(h),await i.registerNewIbGib({ibGib:h})}catch(l){throw console.error(`${r} ${y(l)}`),l}finally{U&&console.log(`${r} complete.`)}}async rel8ToContextIbGib({ibGibToRel8:e,ibGibAddrToRel8:t,contextIbGib:o,rel8nNames:i}){let r=`${this.lc}[${this.rel8ToContextIbGib.name}]`;try{if(!e&&!t)throw new Error("ibGibToRel8 or ibGibAddrToRel8 required (E: 3ee14659fd22355a5ba0e537a477be22)");if(!o)throw new Error("contextIbGib required (E: 85f27c7cbf713704c21084c141cd8822)");if(!this.metaspace)throw new Error("this.metaspace required (E: 6a38c4274bdefc8d44cafd2d6faaa222)");if((i??[]).length===0){if(!this.data?.defaultRel8nName)throw new Error("either rel8nNames or this.data.defaultRel8nName required (E: a14ab4b3e479d9274c61bc5a30bc2222)");i=[this.data.defaultRel8nName]}let l={};t=t||S({ibGib:e}),i.forEach(u=>{l[u]=[t]});let c=await Je({src:o,rel8nsToAddByAddr:l,dna:!0,nCounter:!0});await this.metaspace.persistTransformResult({resTransform:c});let{newIbGib:d}=c;await this.metaspace.registerNewIbGib({ibGib:d})}catch(l){throw console.error(`${r} ${y(l)}`),l}}async createCommentAndRel8ToContextIbGib({text:e,contextIbGib:t,rel8nName:o}){let i=`${this.lc}[${this.createCommentAndRel8ToContextIbGib.name}]`;try{if(U&&console.log(`${i} starting... (I: c3a005f7d323468a5b4e1b2710901d22)`),!this.metaspace)throw new Error("this.metaspace required (E: 5dbb1a7f0ff5469b8ce3cb1be175e521)");let r=await this.metaspace.getLocalUserSpace({lock:!0}),l=await Xe({text:e,addlMetadataText:this.getAddlMetadata(),saveInSpace:!0,space:r});r=await this.metaspace.getLocalUserSpace({lock:!0});let c=l.newIbGib;if(!c)throw new Error("(UNEXPECTED) failed to create comment? (E: 6d668f4e55198e654324622eabaac922)");await this.metaspace.registerNewIbGib({ibGib:c}),await this.rel8ToContextIbGib({ibGibToRel8:c,contextIbGib:t,rel8nNames:["comment"]}),await this.rel8To({ibGibs:[c],rel8nName:o})}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{U&&console.log(`${i} complete.`)}}getThisAtom(){return Et({text:this.data?.classname??"this",length:16})}getAddlMetadata(){let e=`${this.lc}[${this.getAddlMetadata.name}]`;try{if(U&&console.log(`${e} starting... (I: 7800732facf3783943fdf1b2423b0c22)`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 7cb044b39b2b8e31f363f3b82f256323)");let t=this.getThisAtom();if(!t)throw new Error("(UNEXPECTED) atom couldn't be gotten? (E: b260de391356e04abd334e0cd8b09123)");if(t.includes(" "))throw new Error("(UNEXPECTED) atom contains space? (E: 574d088eea13d3afe5fcd2999ab6b423)");let o=this.data.classname?.replace(/[_]/mg,"")||void 0,i=this.data.name?.slice(0,8).replace(/[__]/mg,"")||void 0,r=this.data.uuid?.slice(0,8)||void 0,l=`${t}_${o}_${i}_${r}`;return U&&console.log(`${e} addlMetadataText: ${l} (I: 53c0044671dc99fb75635367d2e63c22)`),l}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{U&&console.log(`${e} complete.`)}}async getContextIbGibFromArgOrAddr({arg:e,addr:t,latest:o}){let i=`${this.lc}[${this.getContextIbGibFromArgOrAddr.name}]`;try{U&&console.log(`${i} starting... (I: c13f7cb92133984048f606075efb8a22)`);let r;if(!e&&!t)throw new Error("either arg or addr required. (E: 3f647b65742242fd9ba878521acf7c22)");if(!this.metaspace)throw new Error("(UNEXPECTED) this.metaspace required (E: f0046290b0d66d28c4bbbf83d9d9f523)");if(e){if((e.ibGibs??[]).length===0)throw new Error("(UNEXPECTED) invalid arg? no context ibgib on arg (E: 89997eb4bdeb3885bee9de5d33ee0f22)");if((e.ibGibs??[]).length!==1)throw new Error("(UNEXPECTED) invalid arg? only expected one ibgib on arg.ibGibs (E: 1a1498af668740fe9439f4953a74ea8a)");r=e.ibGibs[0]}else{let l=await this.metaspace.get({addr:t});if(!l.success||l.ibGibs?.length!==1)throw new Error(`could not get context addr (${t}) (E: 834492313512a45b23a7bebacdc48122)`);r=l.ibGibs[0]}if(o){let l=await this.metaspace.getLatestAddr({ibGib:r});if(l!==S({ibGib:r})){let c=await this.metaspace.get({addr:l});if(c.success&&c.ibGibs?.length===1)r=c.ibGibs[0];else throw new Error(`unable to get resLatestAddr (${l}) (E: ce1e1297743e9a16c8f082321e52a122)`)}}return r}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{U&&console.log(`${i} complete.`)}}async initializeContext({arg:e,contextIbGib:t,rel8nName:o}){let i=`${this.lc}[${this.initializeContext.name}]`;try{if(U&&console.log(`${i} starting... (I: d93429c85b0a494388f66fba3eece922)`),!this.metaspace)throw new Error("this.metaspace (metaspace) required. set this before using this witness. (E: 67db388a0223bf813b40accd9941ad23)");e&&t&&console.warn(`${i} both arg and contextIbGib provided. using raw contextIbGib (W: d6d723ad7fb942079833c40647aecd22)`);let r=t??await this.getContextIbGibFromArgOrAddr({arg:e,latest:!1});if(this._currentWorkingContextIbGib){let d=re({ibGib:this._currentWorkingContextIbGib}),u=re({ibGib:r});if(d===u){U&&console.warn(`${i} initializing context but it's the same timeline (${d}). (W: 7609f8f51172443183e0c93ad52bfe56)`);return}else await this.finalizeContext({arg:e})}let l=f(()=>{this._currentWorkingContextIbGib_PriorChildrenAddrs=[...this._currentWorkingContextIbGib?.rel8ns?.comment??[],...this._currentWorkingContextIbGib?.rel8ns?.pic??[],...this._currentWorkingContextIbGib?.rel8ns?.link??[]]},"updatePriorChildren");this._currentWorkingContextIbGib=t?await this.getContextIbGibFromArgOrAddr({addr:S({ibGib:t}),latest:!0}):await this.getContextIbGibFromArgOrAddr({arg:e,latest:!0}),l();let c=re({ibGib:this._currentWorkingContextIbGib});if(!this.metaspace)throw new Error("(UNEXPECTED) this.metaspace falsy...not initialized? (E: 6e38bfdc5c2eb5fef884f0183889e823)");if(!this.metaspace.latestObs)throw new Error("(UNEXPECTED) this.metaspace.latestObs falsy? (E: 831936570c14ed526f9c9ab511929923)");this._contextChangesSubscription=await this.metaspace.latestObs.subscribe($e({next:f(async d=>{let u=`${i}[latestObs.next]`;if(d.tjpAddr!==c)return;let p=S({ibGib:this._currentWorkingContextIbGib});if(d.latestAddr!==p){if(U&&console.warn(`${u} checking if new context is actually new...damn getLatestAddr maybe not working in ionic space... argh (W: 3d1a12154dfafb9c96d07e6f75f7a322)`),d.latestIbGib){let m=d.latestIbGib.data?.n??-1,h=this._currentWorkingContextIbGib?.data?.n??-2;if(m<=h){console.warn(`${u} latestN is not really the latest. latestN_Supposedly: ${m}, currentN: ${h}. (tjpGib: ${d.tjpAddr}) (W: 6792c9a596c44c03b262614ae79a715e)`);return}}U&&console.log(`${u} update to context.
|
|
1164
|
+
}`;var Lr={$schema:"../schemas/keystone.high.schema.json",metadata:{name:"High Security Profile",securityLevel:"high"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-512",rounds:4,behavior:{size:2e3,replenish:"top-up",selectSequentially:10,selectRandomly:10,targetBindingCount:16}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-512",rounds:4,behavior:{size:2e3,replenish:"replace-all",selectSequentially:10,selectRandomly:10,targetBindingCount:16}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-512",rounds:20,behavior:{size:2e3,replenish:"delete-all",selectSequentially:50,selectRandomly:50,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-512",rounds:4,behavior:{size:2e3,replenish:"top-up",selectSequentially:10,selectRandomly:10,targetBindingCount:16}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-512",rounds:4,behavior:{size:2e3,replenish:"top-up",selectSequentially:10,selectRandomly:10,targetBindingCount:16}}}};var Ur={$schema:"../schemas/keystone.medium.schema.json",metadata:{name:"Medium Security Profile",securityLevel:"medium"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:2,behavior:{size:500,replenish:"top-up",selectSequentially:5,selectRandomly:5,targetBindingCount:10}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:500,replenish:"replace-all",selectSequentially:5,selectRandomly:5,targetBindingCount:10}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:10,behavior:{size:500,replenish:"delete-all",selectSequentially:20,selectRandomly:20,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:2,behavior:{size:500,replenish:"top-up",selectSequentially:5,selectRandomly:5,targetBindingCount:10}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:500,replenish:"top-up",selectSequentially:5,selectRandomly:5,targetBindingCount:10}}}};var Fr={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Low Security Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"replace-all",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:5,behavior:{size:100,replenish:"delete-all",selectSequentially:3,selectRandomly:3,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}}}};var Hr={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Session/Saga Identity Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:50,replenish:"replace-all",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:5,behavior:{size:50,replenish:"delete-all",selectSequentially:3,selectRandomly:3,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}}}};var Vr={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Test Identity Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:12,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:3}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:12,replenish:"replace-all",selectSequentially:1,selectRandomly:2,targetBindingCount:3}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:5,behavior:{size:12,replenish:"delete-all",selectSequentially:3,selectRandomly:3,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:12,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:3}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:20,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:3}}}};var Br={$schema:"../schemas/keystone.high.schema.json",metadata:{name:"Domain Identity Profile",securityLevel:"high"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:6,behavior:{size:2e3,replenish:"replace-all",selectSequentially:12,selectRandomly:12,targetBindingCount:16}}}};var qr={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Sync Delegate Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"replace-all",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:3,selectRandomly:3,targetBindingCount:8}}}};var _t=class n{static{f(this,"KeystoneProfileBuilder")}_template;_username;_email;_description;_details;_customizations={};constructor(e){this._template=JSON.parse(JSON.stringify(e))}static buildKeystone(e){let t;switch(e){case"high":t=Lr;break;case"medium":t=Ur;break;case"low":t=Fr;break;case"session":t=Hr;break;case"test":t=Vr;break;case"domain":t=Br;break;case"sync":t=qr;break;default:throw new Error(`Unknown profile name: ${e} (E: fc10a8ad482ef2bda871ac567d268d26)`)}return new n(t)}withUsername(e){return this._username=e,this}withEmail(e){return this._email=e,this}withDescription(e){return this._description=e,this}withDetails(e){return this._details=e,this}customizePool(e,t){let{behavior:o,...i}=t;return this._customizations[e]={template:i,behavior:o},this}getFrameDetails(){let e={...this._details};return this._username&&(e.username=this._username),this._email&&(e.email=this._email),this._description&&(e.description=this._description),e}async compileConfigs(){let e=[],t="";if(this._username||this._email){let o=`${this._username||""}:${this._email||""}`;t=await Lt({s:o})}else t=await Lt({s:"default-keystone-salt"});for(let[o,i]of Object.entries(this._template.pools)){let r=this._customizations[i.id];r&&(r.template&&Object.assign(i,r.template),r.behavior&&i.behavior&&Object.assign(i.behavior,r.behavior));let a=`${t}-${i.id}`,c=await Lt({s:a}),d=Tr({template:i,salt:c});e.push(d)}return e}};var St=!1,Ot=class n{static{f(this,"WitnessBase_V1")}lc=`[${n.name}]`;set trace(e){let t=`${this.lc}[set trace]`;e!==(this.data?.trace||!1)&&(this.data?(this.data.trace=e,delete this.gib):console.warn(`${t} data is falsy. Can't set.`))}get trace(){return this.data?.trace??!1}set catchAllErrors(e){let t=`${this.lc}[set catchAllErrors]`;e!==this.data?.catchAllErrors&&(this.data?(this.data.catchAllErrors=e,delete this.gib):console.error(`${t} data is falsy. Can't set value.`))}get catchAllErrors(){let e=`${this.lc}[catchAllErrors]`,t=this.data?.catchAllErrors||!1;return(St||this.trace)&&console.log(`${e} result: ${t}`),t}ib="";gib;data;rel8ns;initialized;constructor(e,t){e&&(this.data=e),t&&(this.rel8ns=t),this.initialized=this.initialize()}initialize(){return Promise.resolve()}toIbGibDto(){return oe({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return St&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=te(e.ib),this.gib=te(e.gib),e.data?this.data=te(e.data):delete this.data,e.rel8ns?this.rel8ns=te(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(o){throw console.error(`${t} ${o.message}`),o}finally{St&&console.log(`${t} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{await this.initialized,this.gib||(this.gib=await Ji(this.toIbGibDto()));let o=await this.validateThis();if(o?.length>0){for(let a of o)console.error(`${t} ${a}`);throw new Error("internal witness validation failed. See `WitnessBase_V1.validateThis` (E: 2b5f73cadbfa416ba189346f3c31cd0c)")}let i=await this.validateWitnessArg(e);if(i?.length>0){for(let a of i)console.error(`${t} ${a}`);throw new Error("arg validation failed. See `WitnessBase_V1.validateWitnessArg` (E: 51531a1d928a485e8ffc277145ec44e9)")}(St||this.trace)&&console.log(`${t} addr: ${S(e)}`),St&&console.log(`${t} addr: ${S(e)} (I: f4cf13a44c4e4fc3903f14018e616c64)`);let r=await this.witnessImpl(e);return this.data?.persistOptsAndResultIbGibs&&await this.persistOptsAndResultIbGibs({arg:e,result:r}),r}catch(o){if(console.error(`${t} ${o.message||"unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)"}`),this.catchAllErrors)return;throw o}}async validateWitnessArg(e){let t=`${this.lc}[${this.validateWitnessArg.name}]`;try{let o=[];e||o.push("arg required (E: a222db3b668e4bb09cfd82e75c07bfa6)");let i=Xi({ib:e?.ib});(i?.length??!1)&&o.push(`invalid arg.ib (E: 2ae362ef274d4c3bb9716800f2106d28) errors: ${i.join(`
|
|
1165
|
+
`)}`);let r=Yi({gib:e?.gib});(r?.length??!1)&&o.push(`invalid arg.gib (E: 73be275058084d768a39299337f2ce34) errors: ${r.join(`
|
|
1166
|
+
`)}`);let a=await ot({ibGib:e});return a?.length??!1?o.push(`arg ibgib invalid intrinsically (E: 73be275058084d768a39299337f2ce34) errors: ${a.join(`
|
|
1167
|
+
`)}`):this.data?.allowPrimitiveArgs||K({gib:e.gib}).isPrimitive&&o.push('arg is primitive (i.e. gib === "gib") and witness.data.allowPrimitiveArgs is falsy. (E: d0aa3d7ad4f54b01bd0023300d15ecd9)'),o}catch(o){throw console.error(`${t} ${o.message}`),o}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`,t=[];try{this.ib||t.push("this.ib is falsy."),this.gib||t.push("this.gib is falsy.")}catch(o){throw console.error(`${e} ${o.message}`),o}return t}persistOptsAndResultIbGibs({arg:e,result:t}){let o=`${this.lc}[${this.persistOptsAndResultIbGibs.name}]`;return console.warn(`${o} not implemented in this base class. Override this in descendent class. (W: 087514e851704322a4ec8069a73ce944)`),Promise.resolve()}};var Or="___whitespace___";var Ie=!1;function zr({commentText:n,addlMetadataText:e}){let t=`[${zr.name}]`;try{if(!n)throw new Error("commentText required. (E: 22fdfd0aa0524a18b63a9405b312c99e)");let o=It({text:n,length:20,replaceMap:{"?":"__qm__"}});if(e){e.length>128&&console.warn(`${t} addlMetadataText (${e.length}) is too long. Max length: ${128}`);let i=It({text:e,length:128});if(!i)throw new Error("(UNEXPECTED) addlMetadataText contains no safe characters? (E: dd03c578ada2836b05c94a4aa1785222)");return`comment ${o} ${i}`}else return`comment ${o}`}catch(o){throw console.error(`${t} ${o.message}`),o}}f(zr,"getCommentIb");function Ke({ib:n}){let e=`${Ke.name}]`;try{if(Ie&&console.log(`${e} starting... (I: 1a16f5e3134599eeb585eae77ee6af22)`),!n)throw new Error("ib required (E: d89f8c4df46b970585c82bc89c1c6322)");let[t,o,i]=n.split(" ");for(;o.includes("__qm__");)o=o.replace("__qm__","?");return{safeIbCommentText:o,safeIbCommentMetadataText:i}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ie&&console.log(`${e} complete.`)}}f(Ke,"parseCommentIb");async function Xe({text:n,addlMetadataText:e,saveInSpace:t,space:o,dontTrimText:i}){let r=`[${Xe.name}]`;Ie&&console.log(`${r} starting...`);try{if(!n)throw new Error("text required (E: 3e3d0f555e1a83771a6548eb10943522)");if(i||(n=n.trim()),!n)throw new Error("text cannot be only whitespace when dontTrimText is falsy. (E: d6db3537b9834294836aeb70987c908e)");let a={text:n,textTimestamp:kt()},c={parentIbGib:ne.primitive({ib:"comment"}),ib:zr({commentText:n.trim()||Or,addlMetadataText:e}),data:a,dna:!0,tjp:{uuid:!0,timestamp:!0},nCounter:!0};Ie&&console.log(`${r} opts: ${M(c)}`);let d=await ne.firstGen(c);if(t){if(!o)throw new Error("space required if saveInSpace is truthy (E: 40f69f22f21b4279a83cb746cb4b0da1)");await ji({resTransform:d,space:o})}return d}catch(a){throw console.error(`${r} ${a.message}`),a}}f(Xe,"createCommentIbGib");function Ye({ibGib:n}){let e=`[${Ye.name}]`;try{if(Ie&&console.log(`${e} starting...`),!n)throw new Error("ibGib required (E: f204dac30ae548b0a049f1c4d8048502)");let{ib:t,data:o,rel8ns:i}=n;if(!i)return Ie&&console.log(`${e} rel8ns falsy, NOT a comment (I: 6e145eb2d0ba46629746215a3b655fd5)`),!1;let r=i.ancestor||[];return r&&r.includes("comment^gib")?(Ie&&console.log(`${e} descends from comment^gib, YES is a comment (I: 1a8557780e2e4c1580d5a2585567762b)`),!0):o?o.text&&t?.includes("comment")?(Ie&&console.log(`${e} has text, and ib has 'comment', YES is a comment (I: 3aa03bcd639d4ec7abd7ead917eda3d8)`),!0):(Ie&&console.log(`${e} reached end, doesn't have comment qualities. NOT a comment. (I: cfa529f27f9d490abd476c924ef77087)`),!1):(Ie&&console.log(`${e} data falsy, NOT a comment (I: 30b20ff6785f432f98489f11efe24299)`),!1)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ie&&console.log(`${e} complete.`)}}f(Ye,"isComment");var U=!1,zt=class n extends Ot{static{f(this,"WitnessWithContextBase_V1")}lc=`[${n.name}]`;metaspace;_contextChangesSubscription;_currentWorkingContextIbGib;_currentWorkingContextIbGib_PriorChildrenAddrs=[];_updatingContext=!1;constructor(e,t){super(e,t),this.initialized=this.initialize()}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{U&&console.log(`${e} starting... (I: f0e65ab0f80046a59668ddfbf9f47a4a5)`),await super.initialize()}catch(t){console.error(`${e} ${y(t)}`)}finally{U&&console.log(`${e} complete.`)}}async loadNewerSelfIfAvailable(){let e=`${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;try{if(U&&console.log(`${e} starting... (I: 94755c3131f4dfa12d20fa38e2926522)`),this.metaspace){let t=S({ibGib:this}),o=await this.metaspace.getLatestAddr({ibGib:this});if(o&&o!==t){let i=await this.metaspace.get({addr:o});if(!i||!i?.success||(i?.ibGibs??[]).length===0)throw new Error("could not get newer ibgib in timeline (E: 15fa346c8ac17edb96e4b0870104c122)");await this.loadIbGibDto(i.ibGibs[0]);let r=await this.validateThis();if(r?.length>0)throw new Error(`validationErrors when loading newer version: ${M(r)} (E: 0d9f0684a1ff6af44e20a57130e3ac22)`)}}else console.warn(`${e} this.metaspace undefined (W: 44cc5bf1b14b4695b8de4c589787be06)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{U&&console.log(`${e} complete.`)}}async rel8To({ibGibs:e,rel8nName:t,linked:o,metaspace:i}){let r=`${this.lc}[${this.rel8To.name}]`;try{if(U&&console.log(`${r} starting...`),(e??[]).length===0)throw new Error("ibGibs required (E: 2fd13de0f025b170885bede4d7a50922)");if(t=t||this.data?.defaultRel8nName,!t)throw new Error("rel8nName required either as an arg or in this.data.defaultRel8nName (E: 43ab8ae63694a2a82cd8a70ed6b6b522)");let a=await this.validateThis();if(a?.length>0)throw new Error(`this is an invalid ibGib. thisValidationErrors: ${a.join("|")} (E: 8f08716866cd13bf254222ee9e6a6722)`);if(i=i??this.metaspace,!i)throw new Error("either metaspace or this.metaspace required (E: b5f9453ddb394a2b76dec74c7304df22)");let d=(this.rel8ns?this.rel8ns[t]??[]:[]).map(b=>K({ibGibAddr:b}).tjpGib),u=e.filter(b=>{let E=K({ibGibAddr:S({ibGib:b})}).tjpGib;return!d.includes(E)});if(u.length===0){U&&console.log(`${r} already rel8d to all incoming ibGib(s) via tjp. (I: 5e9d94a98ba262f146c0c0b765157922)`);return}let p=u.map(b=>S({ibGib:b})),m=await Je({src:this.toIbGibDto(),rel8nsToAddByAddr:{[t]:p},linkedRel8ns:o?["past","ancestor",t]:["past","ancestor"],dna:!0,nCounter:!0}),h=m.newIbGib,g=await ot({ibGib:h});if(g?.length??!1)throw new Error(`new this ibgib would have validation errors. aborting. newThisValidationErrors: ${g.join("|")} (E: eb816a27156c246c121ef55e37d59322)`);await i.persistTransformResult({resTransform:m}),await this.loadIbGibDto(h),await i.registerNewIbGib({ibGib:h})}catch(a){throw console.error(`${r} ${y(a)}`),a}finally{U&&console.log(`${r} complete.`)}}async rel8ToContextIbGib({ibGibToRel8:e,ibGibAddrToRel8:t,contextIbGib:o,rel8nNames:i}){let r=`${this.lc}[${this.rel8ToContextIbGib.name}]`;try{if(!e&&!t)throw new Error("ibGibToRel8 or ibGibAddrToRel8 required (E: 3ee14659fd22355a5ba0e537a477be22)");if(!o)throw new Error("contextIbGib required (E: 85f27c7cbf713704c21084c141cd8822)");if(!this.metaspace)throw new Error("this.metaspace required (E: 6a38c4274bdefc8d44cafd2d6faaa222)");if((i??[]).length===0){if(!this.data?.defaultRel8nName)throw new Error("either rel8nNames or this.data.defaultRel8nName required (E: a14ab4b3e479d9274c61bc5a30bc2222)");i=[this.data.defaultRel8nName]}let a={};t=t||S({ibGib:e}),i.forEach(u=>{a[u]=[t]});let c=await Je({src:o,rel8nsToAddByAddr:a,dna:!0,nCounter:!0});await this.metaspace.persistTransformResult({resTransform:c});let{newIbGib:d}=c;await this.metaspace.registerNewIbGib({ibGib:d})}catch(a){throw console.error(`${r} ${y(a)}`),a}}async createCommentAndRel8ToContextIbGib({text:e,contextIbGib:t,rel8nName:o}){let i=`${this.lc}[${this.createCommentAndRel8ToContextIbGib.name}]`;try{if(U&&console.log(`${i} starting... (I: c3a005f7d323468a5b4e1b2710901d22)`),!this.metaspace)throw new Error("this.metaspace required (E: 5dbb1a7f0ff5469b8ce3cb1be175e521)");let r=await this.metaspace.getLocalUserSpace({lock:!0}),a=await Xe({text:e,addlMetadataText:this.getAddlMetadata(),saveInSpace:!0,space:r});r=await this.metaspace.getLocalUserSpace({lock:!0});let c=a.newIbGib;if(!c)throw new Error("(UNEXPECTED) failed to create comment? (E: 6d668f4e55198e654324622eabaac922)");await this.metaspace.registerNewIbGib({ibGib:c}),await this.rel8ToContextIbGib({ibGibToRel8:c,contextIbGib:t,rel8nNames:["comment"]}),await this.rel8To({ibGibs:[c],rel8nName:o})}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{U&&console.log(`${i} complete.`)}}getThisAtom(){return It({text:this.data?.classname??"this",length:16})}getAddlMetadata(){let e=`${this.lc}[${this.getAddlMetadata.name}]`;try{if(U&&console.log(`${e} starting... (I: 7800732facf3783943fdf1b2423b0c22)`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 7cb044b39b2b8e31f363f3b82f256323)");let t=this.getThisAtom();if(!t)throw new Error("(UNEXPECTED) atom couldn't be gotten? (E: b260de391356e04abd334e0cd8b09123)");if(t.includes(" "))throw new Error("(UNEXPECTED) atom contains space? (E: 574d088eea13d3afe5fcd2999ab6b423)");let o=this.data.classname?.replace(/[_]/mg,"")||void 0,i=this.data.name?.slice(0,8).replace(/[__]/mg,"")||void 0,r=this.data.uuid?.slice(0,8)||void 0,a=`${t}_${o}_${i}_${r}`;return U&&console.log(`${e} addlMetadataText: ${a} (I: 53c0044671dc99fb75635367d2e63c22)`),a}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{U&&console.log(`${e} complete.`)}}async getContextIbGibFromArgOrAddr({arg:e,addr:t,latest:o}){let i=`${this.lc}[${this.getContextIbGibFromArgOrAddr.name}]`;try{U&&console.log(`${i} starting... (I: c13f7cb92133984048f606075efb8a22)`);let r;if(!e&&!t)throw new Error("either arg or addr required. (E: 3f647b65742242fd9ba878521acf7c22)");if(!this.metaspace)throw new Error("(UNEXPECTED) this.metaspace required (E: f0046290b0d66d28c4bbbf83d9d9f523)");if(e){if((e.ibGibs??[]).length===0)throw new Error("(UNEXPECTED) invalid arg? no context ibgib on arg (E: 89997eb4bdeb3885bee9de5d33ee0f22)");if((e.ibGibs??[]).length!==1)throw new Error("(UNEXPECTED) invalid arg? only expected one ibgib on arg.ibGibs (E: 1a1498af668740fe9439f4953a74ea8a)");r=e.ibGibs[0]}else{let a=await this.metaspace.get({addr:t});if(!a.success||a.ibGibs?.length!==1)throw new Error(`could not get context addr (${t}) (E: 834492313512a45b23a7bebacdc48122)`);r=a.ibGibs[0]}if(o){let a=await this.metaspace.getLatestAddr({ibGib:r});if(a!==S({ibGib:r})){let c=await this.metaspace.get({addr:a});if(c.success&&c.ibGibs?.length===1)r=c.ibGibs[0];else throw new Error(`unable to get resLatestAddr (${a}) (E: ce1e1297743e9a16c8f082321e52a122)`)}}return r}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{U&&console.log(`${i} complete.`)}}async initializeContext({arg:e,contextIbGib:t,rel8nName:o}){let i=`${this.lc}[${this.initializeContext.name}]`;try{if(U&&console.log(`${i} starting... (I: d93429c85b0a494388f66fba3eece922)`),!this.metaspace)throw new Error("this.metaspace (metaspace) required. set this before using this witness. (E: 67db388a0223bf813b40accd9941ad23)");e&&t&&console.warn(`${i} both arg and contextIbGib provided. using raw contextIbGib (W: d6d723ad7fb942079833c40647aecd22)`);let r=t??await this.getContextIbGibFromArgOrAddr({arg:e,latest:!1});if(this._currentWorkingContextIbGib){let d=se({ibGib:this._currentWorkingContextIbGib}),u=se({ibGib:r});if(d===u){U&&console.warn(`${i} initializing context but it's the same timeline (${d}). (W: 7609f8f51172443183e0c93ad52bfe56)`);return}else await this.finalizeContext({arg:e})}let a=f(()=>{this._currentWorkingContextIbGib_PriorChildrenAddrs=[...this._currentWorkingContextIbGib?.rel8ns?.comment??[],...this._currentWorkingContextIbGib?.rel8ns?.pic??[],...this._currentWorkingContextIbGib?.rel8ns?.link??[]]},"updatePriorChildren");this._currentWorkingContextIbGib=t?await this.getContextIbGibFromArgOrAddr({addr:S({ibGib:t}),latest:!0}):await this.getContextIbGibFromArgOrAddr({arg:e,latest:!0}),a();let c=se({ibGib:this._currentWorkingContextIbGib});if(!this.metaspace)throw new Error("(UNEXPECTED) this.metaspace falsy...not initialized? (E: 6e38bfdc5c2eb5fef884f0183889e823)");if(!this.metaspace.latestObs)throw new Error("(UNEXPECTED) this.metaspace.latestObs falsy? (E: 831936570c14ed526f9c9ab511929923)");this._contextChangesSubscription=await this.metaspace.latestObs.subscribe($e({next:f(async d=>{let u=`${i}[latestObs.next]`;if(d.tjpAddr!==c)return;let p=S({ibGib:this._currentWorkingContextIbGib});if(d.latestAddr!==p){if(U&&console.warn(`${u} checking if new context is actually new...damn getLatestAddr maybe not working in ionic space... argh (W: 3d1a12154dfafb9c96d07e6f75f7a322)`),d.latestIbGib){let m=d.latestIbGib.data?.n??-1,h=this._currentWorkingContextIbGib?.data?.n??-2;if(m<=h){console.warn(`${u} latestN is not really the latest. latestN_Supposedly: ${m}, currentN: ${h}. (tjpGib: ${d.tjpAddr}) (W: 6792c9a596c44c03b262614ae79a715e)`);return}}U&&console.log(`${u} update to context.
|
|
1168
1168
|
currentAddr: ${p}
|
|
1169
|
-
latestAddr: ${d.latestAddr} (I: d0adcc392e6e974c9917730ebad51322)`),this._currentWorkingContextIbGib=d.latestIbGib??await this.getContextIbGibFromArgOrAddr({addr:d.latestAddr,latest:!1}),this._updatingContext?U&&console.log(`${u} already updating context (I: f856f9414627ab00418dccd285b55822)`):(await this.handleContextUpdate({update:d}),l())}},"next"),error:f(async d=>{let u=`${i}[latestObs.error]`;console.error(`${u} this.metaspace.latestObs error: ${wr({err:d})}. (E: 99df4c42195d46d0a9dbfb06ac45ae00)`)},"error")})),o&&await this.rel8To({ibGibs:[this._currentWorkingContextIbGib],rel8nName:o})}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{U&&console.log(`${i} complete.`)}}async finalizeContext({arg:e}){let t=`${this.lc}[${this.finalizeContext.name}]`;try{U&&console.log(`${t} starting... (I: dd53dfc745864dd19fde5f209ceb82c8)`);let o=0,i=100;for(;this._updatingContext&&o<i;)await W(100),o++,o%10===0&&console.log(`${t} already updating context and taking a litle while... waiting still. tries: ${o}/${i} (I: d45ab59af9ea43518432e34ddad95c19)`);throw this._updatingContext&&console.error(`${t} previous call to updatingContext took too long. Ignoring flag and finalizing context. (E: 9a2dc4e1923442fa90fbeae72f358acd)`),this._updatingContext=!0,this._contextChangesSubscription&&(await this._contextChangesSubscription.unsubscribe(),delete this._contextChangesSubscription),delete this._currentWorkingContextIbGib,new Error("not refactored yet. the proceeding code needs to be introduced in the robbot descending class. (E: 066aa414693672d868dbf953617aab23)")}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{this._updatingContext=!1,U&&console.log(`${t} complete.`)}}async handleContextUpdate({update:e}){let t=`${this.lc}[${this.handleContextUpdate.name}]`;for(;this._updatingContext;)console.warn(`${t} already updating context? delaying... (W: 19d2ebeaaf2340fb91a7d6c717e9cb41)`),await W(1e3);this._updatingContext=!0;try{if(U&&console.log(`${t} starting... (I: 3eeaa40cad49094f125f9f5cd6ff6e22)`),U&&(console.log(`${t} update: (I: ad0abae7de472e3b4d3891ea0b937322)`),console.table(e)),!e.latestIbGib){debugger;throw new Error("(UNEXPECTED) update.latestIbGib falsy? (E: e18a048d7e95757238396ddd84748f22)")}let o=e.latestIbGib,i=await this.getNewChildrenIbGibs({newContext:o});if(i.length===1){let r=i[0];await this.handleNewContextChild({newChild:r})}else if(i.length>1){console.warn(`${t} (UNEXPECTED) multiple new children in context update. iterating through each one. (W: 02d82a8f755f418d95fa30f0f52ad58e)`);for(let r of i)await this.handleNewContextChild({newChild:r})}else{U&&console.log(`${t} no new children in context update. returning early... (I: 31397b04965351ab29bb3f78cb709122)`);return}}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{this._updatingContext=!1,U&&console.log(`${t} complete.`)}}async getNewChildrenIbGibs({newContext:e}){let t=`${this.lc}[${this.getNewChildrenIbGibs.name}]`;try{U&&console.log(`${t} starting... (I: 1b3d1cf908489087fa3b281f55b9a522)`);let i=[...e.rel8ns?.comment??[],...e.rel8ns?.pic??[],...e.rel8ns?.link??[]].filter(u=>!this._currentWorkingContextIbGib_PriorChildrenAddrs.includes(u));if(i.length===0)return U&&console.log(`${t} no new children addrs in newContext. returning early... (I: 8f9c3658c194c472cb1e2bc19d847b22)`),[];if(!this.metaspace)throw new Error("this.metaspace falsy. not initialized? (E: 1cc26ca7de7fadcdbaecbd6613350e23)");let r=await this.metaspace.getLocalUserSpace({});if(!r)throw new Error("couldn't get local user space? (E: f118f75e5852fc22bba3a6495beec723)");let l=await ji({addrs:i,space:r}),c=Object.values(l?.data?.latestAddrsMap??{});if(!l?.data?.success||c.length!==i.length)throw new Error("could not get latest addrs. (E: 2e1619e7e2e166696fe8ff78cb02cc22)");if(c.some(u=>u===null))throw new Error("some addrs were not found in the space. (E: 2216d8e5ad7fb600ceb025ed7c90f323)");let d=await this.metaspace.get({addrs:c});if(!d.success||d.ibGibs?.length!==i.length)throw new Error(`failed to get newChildren with addrs: ${i.join("|")}. Error: ${d.errorMsg??"unknown error 5737bd0996d5445b8bd80975bedc0d57"} (E: 05722e11350ec6ffffdb5c7d0caa2922)`);return d.ibGibs}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{U&&console.log(`${t} complete.`)}}async handleNewContextChild({newChild:e}){let t=`${this.lc}[${this.handleNewContextChild.name}]`;try{throw new Error("not implemented in base class (E: ea6b2b13d9504d93b33b70191d106084)")}catch(o){throw console.error(`${t} ${y(o)}`),o}}};var oe=V,Ue=class extends zt{static{f(this,"LiveProxyIbGib")}lc="";ib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.ib:Ut;gib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.gib:Ft;data=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.data:void 0;rel8ns=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.rel8ns:void 0;async loadNewerSelfIfAvailable(){let e=`${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;try{oe&&console.log(`${e} starting... (I: genuuid)`),console.warn(`${e} does nothing in this class. I just have this warning here because I want to see if this gets executed. (W: genuuid)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{oe&&console.log(`${e} complete.`)}}async loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{oe&&console.log(`${t} starting... (I: genuuid)`);debugger;console.warn(`${t} does nothing in this class. I just have this warning here because I want to see if this gets executed. (W: genuuid)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{oe&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;return oe&&console.log(`${e} elided in this proxy class because this isn't a true witness atow (04/2025) (I: fd223814f169798d9f499d6e9cdc0325)`),[]}get ibGib(){return this._currentWorkingContextIbGib}spaceId;constructor(e,t){super(e,t)}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{oe&&console.log(`${e} starting... (I: 1bd72217a5f334effc63f8d51e7b2225)`),await super.initialize(),this._contextUpdated$=await no(),this.contextUpdated$=this._contextUpdated$.asObservable(),this._newContextChild$=await no(),this.newContextChild$=this._newContextChild$.asObservable()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{oe&&console.log(`${e} complete.`)}}parseAddlMetadataString({ib:e}){let t=`${this.lc}[${this.parseAddlMetadataString.name}]`;return console.warn(`${t} not really implemented in this class atow (04/2025). (W: genuuid)`),{}}_initialContext;async witnessImpl(e){let t=`${this.lc}[${this.witnessImpl.name}]`;try{if(oe&&console.log(`${t} starting...`),Zi({ib:e.ib})){if(!e.data)throw new Error("arg has space ib but arg.data is falsy (E: b2af9226c067d5e72f117fa36e239525)");let o=e.data.uuid;return this.spaceId=o,oe&&console.log(`${t} spaceId set to the ${o} (I: 018724a5431ba421b71fad36924c5a25)`),ne.primitive({ib:`spaceId set to ${o}`})}else if(this._initialContext){debugger;console.error(`${t} (UNEXPECTED) context already initialized. returning early without doing anything. NOTE: This error was not thrown, only logged. (E: genuuid)`)}else{let o=await this.metaspace?.getLocalUserSpace({localSpaceId:this.spaceId});return await this.setWrappedIbGib({ibGib:e,space:o}),It}}catch(o){throw console.error(`${t} ${o.message}`),o}finally{oe&&console.log(`${t} complete.`)}}_contextUpdated$;contextUpdated$;_newContextChild$;newContextChild$;async handleContextUpdate({update:e}){let t=`${this.lc}[${this.handleContextUpdate.name}]`;try{if(oe&&console.log(`${t} starting... (I: c262bcda065c086ffe9e3ac5899abe25)`),await super.handleContextUpdate({update:e}),!this._contextUpdated$)throw new Error("(UNEXPECTED) this._contextUpdated$ falsy? (E: a184df090502bed9649f8df88bd4c125)");await this._contextUpdated$.next(this._currentWorkingContextIbGib)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{oe&&console.log(`${t} complete.`)}}async setWrappedIbGib({ibGib:e,ibGibAddr:t,space:o}){let i=`${this.lc}[${this.setWrappedIbGib.name}]`;try{if(oe&&console.log(`${i} starting... (I: a4b0acda259c121801aa701534320125)`),this.metaspace||(this.metaspace=await me()),!e){if(!t)throw new Error("(UNEXPECTED) both ibGib AND ibGibAddr falsy? (E: 6fac98ba2d4cfdec2b7ee974dec74625)");if(o??=await this.metaspace.getLocalUserSpace({lock:!1}),!o)throw new Error("(UNEXPECTED) space falsy? no space provided and couldn't get default local user space? (E: e14d1b7a6586f99453fc571396d4df25)");let r=await this.metaspace.get({addrs:[t],space:o});if(!r.success||r.ibGibs?.length!==1)throw new Error(`${i} failed to get ibGib(?) (${t}). space.ib: ${o.ib} (E: b38f0a25d92e44c0aa5cc3b038a43c6c)`);e=r.ibGibs.at(0)}await this.initializeContext({contextIbGib:e,rel8nName:""})}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{oe&&console.log(`${i} complete.`)}}async handleNewContextChild({newChild:e}){let t=`[${this.handleNewContextChild.name}]`;try{if(oe&&console.log(`${t} starting... (I: 7e9b6b7a4bb2726e9c717f230dfe1925)`),!this._newContextChild$)throw new Error("(UNEXPECTED) this._contextUpdated$ falsy? (E: a184df090502bed9649f8df88bd4c125)");await this._newContextChild$.next(e)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{oe&&console.log(`${t} complete.`)}}};var rt="witness_agent",st=/^[a-zA-Z0-9_\-.]{1,32}$/,so=/.{1,255}/,Or="",zr="Manco",Jr="This is a generic, unspecified agent.";var Jt="List of function info ibgib addresses. These contain info on both the requests you made and the resultant values.",Qe="agent",lb={type:"string",description:"unique identifier for the agent. Should be provided to the agent in system instructions upon creation."},cb={type:"string",description:"type of the agent that governs basic responsibilities. Should be provided to the agent in system instructions upon creation."};var kl="hardcoded",Ul="human",Fl="ai",Hl="function",Vl="unknown",X={HARDCODED:kl,HUMAN:Ul,AI:Fl,FUNCTION:Hl,UNKNOWN:Vl},ao=Object.freeze(Object.values(X));function Wr(n){return!!n&&ao.includes(n)}f(Wr,"isTextSource");var db={type:"string",description:`The agent should pick a name with which to represent him/her/itself to the user. This should not be "Gemini" or something bland like that, rather, it should be a name that the agent likes. Should contain no spaces, only alphanumerics. Note that the example given has a name, but really it should be up to the agent's own preference. Please be consistent with this with yourself, i.e., don't change it once established. Must pass regex: ${st.source}`},Kr="primaryagent";var Xr=!1;async function lo({ibGib:n,addr:e,tagIbGib:t,metaspace:o,space:i}){let r=`[${lo.name}]`;try{if(Xr&&console.log(`${r} starting... (I: b1fd25ec28bce8f1916b4ab55f48a724)`),!e&&!n)throw new Error("either addr or ibGib required (E: 3d580f8ecc251a0c81c7ea8bc3d38524)");if(e??=S({ibGib:n}),e!==S({ibGib:n}))throw new Error(`addr (${e}) differs from incoming ibGib's addr (${S({ibGib:n})}). (E: f2c14234a78c917fb9f587beaee89324)`);let l=await o.getLatestAddr({ibGib:t,space:i});if(l!==S({ibGib:t})){let p=await o.get({addr:l,space:i});if(!p.success||p.ibGibs?.length!==1)throw new Error(`could not get latest tag (${l}) from space (${i.ib}). error: ${p.errorMsg??"[unknown error (E: a4e31c98398b417db8f617f98a5f2741)]"} (E: 73c085d81efdab0e7b8939222ec07524)`);t=p.ibGibs.at(0)}let c={[Yi]:[e]},d=await Je({src:t,rel8nsToAddByAddr:c,dna:!0,nCounter:!0}),u=d.newIbGib;return await o.persistTransformResult({resTransform:d,space:i}),await o.registerNewIbGib({ibGib:u,space:i}),u}catch(l){throw console.error(`${r} ${y(l)}`),l}finally{Xr&&console.log(`${r} complete.`)}}f(lo,"rel8ToTag");var j=V,uo=class n{static{f(this,"AgentsService_V1")}lc=`[${n.name}]`;latestAgents=new Map;factoryFns={};constructor(){}async getAgentById(e){let t=`${this.lc}[${this.getAgentById.name}]`;try{let{agentId:o,agentType:i,spaceId:r}=e;j&&console.log(`${t} starting... (I: 0c4214b4614a43bd2825978e54aee325)`);let l=this.latestAgents.get(o);if(!l){let c=await me();l=(await Wt({metaspace:c,type:i,spaceId:r})).find(u=>u.data.uuid===o)}return l||console.warn(`${t} couldn't find any agent by id. opts: ${M(e)} (W: 70cf51ecbe68dfdcfe1e9995a7468f25)`),l}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{j&&console.log(`${t} complete.`)}}async updateOrSetLatestAgent({agent:e,throwIfNewerFound:t}){let o=`${this.lc}[${this.updateOrSetLatestAgent.name}]`;try{if(j&&console.log(`${o} starting... (I: 9bb74f19b989fc0ee969cb4c2c2aa525)`),!e.data)throw new Error(`invalid agent. data falsy. agent.ib: ${e.ib} (E: 7356db7395cb0c5664d13437dd62c425)`);if(!e.data.uuid)throw new Error(`invalid agent. data.uuid falsy. agent.ib: ${e.ib} (E: 48afcd6658154bee1138fca31cbfbf25)`);let i=await this.getLatestAgent({id:e.data.uuid});if(i){if(!i.data)throw new Error("(UNEXPECTED) existing.data falsy? should have thrown on previous set function call? (E: f3cbae9922ea9849ada25db2eea40825)");if(i.data.n===e.data.n){if(i.gib===e.gib)return;console.warn(`existing.data.n === agent.data.n but gibs are different. We have a branched timeline. just logging this error, need to figure out wth is going on here. we should not have this with the timeline being locked. The only thing I can think of is if the ibgib is updated very quickly, but even then, the n should be incremented. still the approach is valid. anyway, we're going ahead and taking the newer agent.
|
|
1170
|
-
existing: ${M(
|
|
1171
|
-
new: ${M(se({ibGib:e}))} (E: 5e079b566ff3533acdb2d01359f08625)`),await i.loadIbGibDto(e.toIbGibDto()),this.latestAgents.set(e.data.uuid,e);return}else if(i.data.n>e.data.n){let r="existing.data.n > agent.data.n, i.e., the one we already have is newer. So why was the caller trying to set to the older agent thinking it was the most recent? Probably have a branched timeline.";if(t)throw new Error(`${o} ${r} (E: bb2cc3ce8cfa88b80fb62149b0e70225)`);console.warn(`${o} ${r} (W: caaf66deb4e6fd8e2eb9261685dc0325)`);return}else{await i.loadIbGibDto(e.toIbGibDto()),this.latestAgents.set(e.data.uuid,e);return}}else{this.latestAgents.set(e.data.uuid,e);return}}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{j&&console.log(`${o} complete.`)}}getLatestAgent({id:e}){let t=`${this.lc}[${this.getLatestAgent.name}]`;try{return j&&console.log(`${t} starting... (I: 8e85b55057760b712a913a92e88ead25)`),Promise.resolve(this.latestAgents.get(e))}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{j&&console.log(`${t} complete.`)}}registerFactory({classname:e,fnDtoToAgentWitness:t}){this.factoryFns[e]=t}async getAgentWitnessFromDto({dto:e,classname:t}){let o=`${this.lc}[${this.getAgentWitnessFromDto.name}]`;try{if(j&&console.log(`${o} starting... (I: 718837d4ee3d590177f3425b99106225)`),!e.data)throw new Error("dto.data falsy (E: fad89dd4c787b687a657c13968946925)");let i;if(t??=e.data.classname,t){let r=this.factoryFns[t],l=await r(e);if(l.applies){if(!l.agent)throw new Error("(UNEXPECTED) factory function for agent dto applies: true, but the resulting agent is undefined? (E: b13cdf0f3d9c50f1fa419f2c409ebf25)");i=l.agent}else throw new Error(`classname (${t}) factory function found and attempted, but result says applied: false. (E: 751a2502c9a7e2d61c76c8ae2f7fb125)`)}else{let r=Object.keys(this.factoryFns);for(let l of r){let c=this.factoryFns[l],d=await c(e);if(d.applies){if(!d.agent)throw new Error("(UNEXPECTED) factory function for agent dto applies: true, but the resulting agent is undefined? (E: 60e97c083a668baf11efcd6adf6a3525)");i=d.agent;break}}}return i}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{j&&console.log(`${o} complete.`)}}async getAgentByAddr({agentAddr:e,spaceId:t,metaspace:o}){let i=`${this.lc}[${this.getAgentByAddr.name}]`;try{if(j&&console.log(`${i} starting... (I: 42dfecbe6d6b5a3a7d392af5a66cc625)`),!e)throw new Error(`${i} agentAddr is required. (E: 389351659a2e08fa179ceede16925a25)`);let{ib:r}=F({ibGibAddr:e}),{uuid:l,type:c}=Yr({ib:r});if(!l){debugger;throw new Error(`(UNEXPECTED) agentAddr doesn't have uuid in the ib? agentAddr: ${e} (E: fedcacffed98fdc78b1e80e45c413925)`)}let d=await this.getAgentById({agentId:l,agentType:c});if(d)return j&&console.log(`${i} agent found already in agents svc so didn't need to go get it from the space. (I: ec6abaf3badd8e301d79a7476845bc25)`),d;o??=await me();let u=await o.getLocalUserSpace({localSpaceId:t,lock:!1});if(!u)throw t?new Error(`couldn't get space with spaceId (${t}) (E: 26b3f1414a93cc339e704d0162cb8b25)`):new Error("(UNEXPECTED) couldn't get default local user space? (E: 2e19a1fae8b3f00595257f51426ac225)");let p=await o.get({addrs:[e],space:u});if(!p.success||!p.ibGibs||p.ibGibs.length===0){j&&console.log(`${i} Agent ibGib not found in space (${t}) at address ${e}. (I: 29c5c7994fb3ed388b28a81a9ed68325)`);return}let m=p.ibGibs[0],h=await this.getAgentWitnessFromDto({dto:m});if(!h){debugger;throw new Error(`${i} Couldn't get actual agent witness from agent dto (${e}). Have we registered classname (${m.data?.classname}) and factory fn with agents service? (E: e6e9da6c91d14bd7acb5c571c8de1a25)`)}return await this.updateOrSetLatestAgent({agent:h,throwIfNewerFound:!0}),j&&console.log(`${i} Cached agent witness with id ${l}. (I: b862f63147a3fac3c6e6210d5ab87c25)`),j&&console.log(`${i} complete. Retrieved and cached agent witness for address ${e}.`),h}catch(r){throw console.error(`${i} ${y(r)}`),r}}async createNewAgent(e){let t=`[${this.createNewAgent.name}]`;try{j&&console.log(`${t} starting... (I: a3e07b54bb7bf45f7739eff2d738c825)`);let{metaspace:o,superSpace:i,name:r,availableFunctions:l,initialSystemText:c,initialChatText:d,fnGetAPIKey:u,addToAgentsTag:p,type:m}=e;if(i??=await o.getLocalUserSpace({}),!i)throw new Error("(UNEXPECTED) superSpace falsy? (E: ceb60d96ff25b6d6aaa5aa69a7a51d25)");if(!i.data)throw new Error("(UNEXPECTED) superSpace.data falsy? (E: 56b4ec127f8559da96e6f70c7cb13825)");let h=po(e),g=await h.createInitialData(i);if(!g.uuid)throw new Error("(UNEXPECTED) data.uuid falsy? (E: 4e4f6fcf89d1e3775971ad843a083725)");let b=await o.createLocalSpaceAndUpdateBootstrap({allowCancel:!1,zeroSpace:o.zeroSpace,spaceName:r+g.uuid.substring(0,5),createBootstrap:!1});if(!b)throw new Error("(UNEXPECTED) newSubSpace falsy after creating locally? (E: af8b5503c15d4292e2f591b316e7d825)");g.subSpaceId=b.data.uuid;let E=await h.createInitialRel8ns(),I=await ne.firstGen({ib:mo({data:g}),parentIbGib:ne.primitive({ib:rt}),data:g,rel8ns:E,nCounter:!0,dna:!0,tjp:{timestamp:!0}});await o.persistTransformResult({resTransform:I});let v=I.newIbGib,w=await h.createWitness();if(w.fnGetAPIKey=u,await w.loadIbGibDto(v),p){let C=await fo({metaspace:o,space:i}),A=await lo({ibGib:v,metaspace:o,space:i,tagIbGib:C})}await ke({type:m,rel8nInfos:[{rel8nName:Qe,ibGibs:[v]}],metaspace:o,space:i}),l.length>0&&await w.addAvailableFunctions(l);let T=[];return T.push({textSrc:"hardcoded",text:at({tagText:rr,contentText:`Your id (agent id) is: ${g.uuid}. Your superSpaceId is: ${g.superSpaceId}. Your subSpaceId is: ${g.subSpaceId}. These may be useful/required in some functions, though you should refer to those functions' instructions/descriptions for applicability.`}),isSystem:!0}),c&&T.push({textSrc:"hardcoded",text:c,isSystem:!0}),d&&T.push({textSrc:"hardcoded",text:d}),await w.addTexts({infos:T}),this.latestAgents.set(w.data.uuid,w),w}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{j&&console.log(`${t} complete.`)}}getAgents(e){let t=`${this.lc}[${this.getAgents.name}]`;try{return j&&console.log(`${t} starting... (I: 4663f125c3a21fa3ecccc2c5a38d1225)`),Wt(e)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{j&&console.log(`${t} complete.`)}}},co;function xe(){return co||(co=new uo),co}f(xe,"getAgentsSvc");var Bl="gemini-3.1-pro-preview",ql="gemini-3-flash-preview",Ol="gemini-3.1-flash-lite-preview",zl="gemini-3.1-flash-live-preview",Jl="gemini-2.5-pro",Wl="gemini-2.5-flash",Kl="gemini-2.5-flash-lite",Xl="gemini-2.5-flash-preview-tts",Yl="gemini-2.0-flash",Ql="gemini-2.0-flash-lite",ho={GEMINI_3_1_PRO_PREVIEW:Bl,GEMINI_3_FLASH_PREVIEW:ql,GEMINI_3_1_FLASH_LITE_PREVIEW:Ol,GEMINI_3_1_FLASH_LIVE_PREVIEW:zl,GEMINI_2_5_PRO:Jl,GEMINI_2_5_FLASH:Wl,GEMINI_2_5_FLASH_LITE:Kl,GEMINI_2_5_FLASH_PREVIEW_TTS:Xl,GEMINI_2_0_FLASH:Yl,GEMINI_2_0_FLASH_LITE:Ql},Rb=Object.freeze(Object.values(ho));var Qr=ho.GEMINI_2_5_FLASH,lt=ho.GEMINI_2_5_FLASH_LITE,go=5;var Zr={version:"1",uuid:Or,name:zr,description:Jr,classname:"AgentWitness_V1",icon:"happy",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1,subSpaceId:"",superSpaceId:"",availableFunctionNameOrIds:[],model:Qr,api:"gemini",type:Kr,"@currentContextTjpAddr":q},bo=void 0;var Zl,jl;function ec(){return{geminiUrl:Zl,vertexUrl:jl}}f(ec,"getDefaultBaseUrls");function tc(n,e,t,o){var i,r;if(!n?.baseUrl){let l=ec();return e?(i=l.vertexUrl)!==null&&i!==void 0?i:t:(r=l.geminiUrl)!==null&&r!==void 0?r:o}return n.baseUrl}f(tc,"getBaseUrl");var we=class{static{f(this,"BaseModule")}};function _(n,e){let t=/\{([^}]+)\}/g;return n.replace(t,(o,i)=>{if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];return r!=null?String(r):""}else throw new Error(`Key '${i}' not found in valueMap.`)})}f(_,"formatMap");function a(n,e,t){for(let r=0;r<e.length-1;r++){let l=e[r];if(l.endsWith("[]")){let c=l.slice(0,-2);if(!(c in n))if(Array.isArray(t))n[c]=Array.from({length:t.length},()=>({}));else throw new Error(`Value must be a list given an array path ${l}`);if(Array.isArray(n[c])){let d=n[c];if(Array.isArray(t))for(let u=0;u<d.length;u++){let p=d[u];a(p,e.slice(r+1),t[u])}else for(let u of d)a(u,e.slice(r+1),t)}return}else if(l.endsWith("[0]")){let c=l.slice(0,-3);c in n||(n[c]=[{}]);let d=n[c];a(d[0],e.slice(r+1),t);return}(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l]}let o=e[e.length-1],i=n[o];if(i!==void 0){if(!t||typeof t=="object"&&Object.keys(t).length===0||t===i)return;if(typeof i=="object"&&typeof t=="object"&&i!==null&&t!==null)Object.assign(i,t);else throw new Error(`Cannot set value for an existing key. Key: ${o}`)}else o==="_self"&&typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.assign(n,t):n[o]=t}f(a,"setValueByPath");function s(n,e,t=void 0){try{if(e.length===1&&e[0]==="_self")return n;for(let o=0;o<e.length;o++){if(typeof n!="object"||n===null)return t;let i=e[o];if(i.endsWith("[]")){let r=i.slice(0,-2);if(r in n){let l=n[r];return Array.isArray(l)?l.map(c=>s(c,e.slice(o+1),t)):t}else return t}else n=n[i]}return n}catch(o){if(o instanceof TypeError)return t;throw o}}f(s,"getValueByPath");function nc(n,e){for(let[t,o]of Object.entries(e)){let i=t.split("."),r=o.split("."),l=new Set,c=-1;for(let d=0;d<i.length;d++)if(i[d]==="*"){c=d;break}if(c!==-1&&r.length>c)for(let d=c;d<r.length;d++){let u=r[d];u!=="*"&&!u.endsWith("[]")&&!u.endsWith("[0]")&&l.add(u)}vo(n,i,r,0,l)}}f(nc,"moveValueByPath");function vo(n,e,t,o,i){if(o>=e.length||typeof n!="object"||n===null)return;let r=e[o];if(r.endsWith("[]")){let l=r.slice(0,-2),c=n;if(l in c&&Array.isArray(c[l]))for(let d of c[l])vo(d,e,t,o+1,i)}else if(r==="*"){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let l=n,c=Object.keys(l).filter(u=>!u.startsWith("_")&&!i.has(u)),d={};for(let u of c)d[u]=l[u];for(let[u,p]of Object.entries(d)){let m=[];for(let h of t.slice(o))h==="*"?m.push(u):m.push(h);a(l,m,p)}for(let u of c)delete l[u]}}else{let l=n;r in l&&vo(l[r],e,t,o+1,i)}}f(vo,"_moveValueRecursive");function Ei(n){if(typeof n!="string")throw new Error("fromImageBytes must be a string");return n}f(Ei,"tBytes$1");function oc(n){let e={},t=s(n,["operationName"]);t!=null&&a(e,["operationName"],t);let o=s(n,["resourceName"]);return o!=null&&a(e,["_url","resourceName"],o),e}f(oc,"fetchPredictOperationParametersToVertex");function ic(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["metadata"]);o!=null&&a(e,["metadata"],o);let i=s(n,["done"]);i!=null&&a(e,["done"],i);let r=s(n,["error"]);r!=null&&a(e,["error"],r);let l=s(n,["response","generateVideoResponse"]);return l!=null&&a(e,["response"],sc(l)),e}f(ic,"generateVideosOperationFromMldev$1");function rc(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["metadata"]);o!=null&&a(e,["metadata"],o);let i=s(n,["done"]);i!=null&&a(e,["done"],i);let r=s(n,["error"]);r!=null&&a(e,["error"],r);let l=s(n,["response"]);return l!=null&&a(e,["response"],ac(l)),e}f(rc,"generateVideosOperationFromVertex$1");function sc(n){let e={},t=s(n,["generatedSamples"]);if(t!=null){let r=t;Array.isArray(r)&&(r=r.map(l=>lc(l))),a(e,["generatedVideos"],r)}let o=s(n,["raiMediaFilteredCount"]);o!=null&&a(e,["raiMediaFilteredCount"],o);let i=s(n,["raiMediaFilteredReasons"]);return i!=null&&a(e,["raiMediaFilteredReasons"],i),e}f(sc,"generateVideosResponseFromMldev$1");function ac(n){let e={},t=s(n,["videos"]);if(t!=null){let r=t;Array.isArray(r)&&(r=r.map(l=>cc(l))),a(e,["generatedVideos"],r)}let o=s(n,["raiMediaFilteredCount"]);o!=null&&a(e,["raiMediaFilteredCount"],o);let i=s(n,["raiMediaFilteredReasons"]);return i!=null&&a(e,["raiMediaFilteredReasons"],i),e}f(ac,"generateVideosResponseFromVertex$1");function lc(n){let e={},t=s(n,["video"]);return t!=null&&a(e,["video"],hc(t)),e}f(lc,"generatedVideoFromMldev$1");function cc(n){let e={},t=s(n,["_self"]);return t!=null&&a(e,["video"],gc(t)),e}f(cc,"generatedVideoFromVertex$1");function dc(n){let e={},t=s(n,["operationName"]);return t!=null&&a(e,["_url","operationName"],t),e}f(dc,"getOperationParametersToMldev");function uc(n){let e={},t=s(n,["operationName"]);return t!=null&&a(e,["_url","operationName"],t),e}f(uc,"getOperationParametersToVertex");function fc(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["metadata"]);o!=null&&a(e,["metadata"],o);let i=s(n,["done"]);i!=null&&a(e,["done"],i);let r=s(n,["error"]);r!=null&&a(e,["error"],r);let l=s(n,["response"]);return l!=null&&a(e,["response"],pc(l)),e}f(fc,"importFileOperationFromMldev$1");function pc(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["parent"]);o!=null&&a(e,["parent"],o);let i=s(n,["documentName"]);return i!=null&&a(e,["documentName"],i),e}f(pc,"importFileResponseFromMldev$1");function va(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["metadata"]);o!=null&&a(e,["metadata"],o);let i=s(n,["done"]);i!=null&&a(e,["done"],i);let r=s(n,["error"]);r!=null&&a(e,["error"],r);let l=s(n,["response"]);return l!=null&&a(e,["response"],mc(l)),e}f(va,"uploadToFileSearchStoreOperationFromMldev");function mc(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["parent"]);o!=null&&a(e,["parent"],o);let i=s(n,["documentName"]);return i!=null&&a(e,["documentName"],i),e}f(mc,"uploadToFileSearchStoreResponseFromMldev");function hc(n){let e={},t=s(n,["uri"]);t!=null&&a(e,["uri"],t);let o=s(n,["encodedVideo"]);o!=null&&a(e,["videoBytes"],Ei(o));let i=s(n,["encoding"]);return i!=null&&a(e,["mimeType"],i),e}f(hc,"videoFromMldev$1");function gc(n){let e={},t=s(n,["gcsUri"]);t!=null&&a(e,["uri"],t);let o=s(n,["bytesBase64Encoded"]);o!=null&&a(e,["videoBytes"],Ei(o));let i=s(n,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}f(gc,"videoFromVertex$1");var jr;(function(n){n.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",n.OUTCOME_OK="OUTCOME_OK",n.OUTCOME_FAILED="OUTCOME_FAILED",n.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(jr||(jr={}));var es;(function(n){n.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",n.PYTHON="PYTHON"})(es||(es={}));var ts;(function(n){n.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",n.SILENT="SILENT",n.WHEN_IDLE="WHEN_IDLE",n.INTERRUPT="INTERRUPT"})(ts||(ts={}));var Fe;(function(n){n.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",n.STRING="STRING",n.NUMBER="NUMBER",n.INTEGER="INTEGER",n.BOOLEAN="BOOLEAN",n.ARRAY="ARRAY",n.OBJECT="OBJECT",n.NULL="NULL"})(Fe||(Fe={}));var ns;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(ns||(ns={}));var os;(function(n){n.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",n.SIMPLE_SEARCH="SIMPLE_SEARCH",n.ELASTIC_SEARCH="ELASTIC_SEARCH"})(os||(os={}));var is;(function(n){n.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",n.NO_AUTH="NO_AUTH",n.API_KEY_AUTH="API_KEY_AUTH",n.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",n.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",n.OAUTH="OAUTH",n.OIDC_AUTH="OIDC_AUTH"})(is||(is={}));var rs;(function(n){n.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",n.HTTP_IN_QUERY="HTTP_IN_QUERY",n.HTTP_IN_HEADER="HTTP_IN_HEADER",n.HTTP_IN_PATH="HTTP_IN_PATH",n.HTTP_IN_BODY="HTTP_IN_BODY",n.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(rs||(rs={}));var ss;(function(n){n.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",n.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",n.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",n.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",n.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",n.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",n.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(ss||(ss={}));var as;(function(n){n.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",n.LOW="LOW",n.HIGH="HIGH"})(as||(as={}));var ls;(function(n){n.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",n.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",n.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",n.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",n.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",n.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",n.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",n.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",n.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",n.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",n.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"})(ls||(ls={}));var cs;(function(n){n.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",n.SEVERITY="SEVERITY",n.PROBABILITY="PROBABILITY"})(cs||(cs={}));var ds;(function(n){n.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",n.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",n.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",n.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",n.BLOCK_NONE="BLOCK_NONE",n.OFF="OFF"})(ds||(ds={}));var us;(function(n){n.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",n.STOP="STOP",n.MAX_TOKENS="MAX_TOKENS",n.SAFETY="SAFETY",n.RECITATION="RECITATION",n.LANGUAGE="LANGUAGE",n.OTHER="OTHER",n.BLOCKLIST="BLOCKLIST",n.PROHIBITED_CONTENT="PROHIBITED_CONTENT",n.SPII="SPII",n.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",n.IMAGE_SAFETY="IMAGE_SAFETY",n.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",n.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",n.NO_IMAGE="NO_IMAGE",n.IMAGE_RECITATION="IMAGE_RECITATION",n.IMAGE_OTHER="IMAGE_OTHER"})(us||(us={}));var fs;(function(n){n.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",n.NEGLIGIBLE="NEGLIGIBLE",n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH"})(fs||(fs={}));var ps;(function(n){n.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",n.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",n.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",n.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",n.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(ps||(ps={}));var ms;(function(n){n.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",n.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",n.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",n.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",n.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(ms||(ms={}));var hs;(function(n){n.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",n.SAFETY="SAFETY",n.OTHER="OTHER",n.BLOCKLIST="BLOCKLIST",n.PROHIBITED_CONTENT="PROHIBITED_CONTENT",n.IMAGE_SAFETY="IMAGE_SAFETY",n.MODEL_ARMOR="MODEL_ARMOR",n.JAILBREAK="JAILBREAK"})(hs||(hs={}));var gs;(function(n){n.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",n.ON_DEMAND="ON_DEMAND",n.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(gs||(gs={}));var tn;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.AUDIO="AUDIO"})(tn||(tn={}));var bs;(function(n){n.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",n.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",n.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",n.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(bs||(bs={}));var ys;(function(n){n.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",n.TUNING_MODE_FULL="TUNING_MODE_FULL",n.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(ys||(ys={}));var Es;(function(n){n.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"})(Es||(Es={}));var wo;(function(n){n.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",n.JOB_STATE_QUEUED="JOB_STATE_QUEUED",n.JOB_STATE_PENDING="JOB_STATE_PENDING",n.JOB_STATE_RUNNING="JOB_STATE_RUNNING",n.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",n.JOB_STATE_FAILED="JOB_STATE_FAILED",n.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",n.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",n.JOB_STATE_PAUSED="JOB_STATE_PAUSED",n.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",n.JOB_STATE_UPDATING="JOB_STATE_UPDATING",n.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(wo||(wo={}));var Is;(function(n){n.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",n.TUNING_TASK_I2V="TUNING_TASK_I2V",n.TUNING_TASK_T2V="TUNING_TASK_T2V",n.TUNING_TASK_R2V="TUNING_TASK_R2V"})(Is||(Is={}));var vs;(function(n){n.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",n.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",n.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",n.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(vs||(vs={}));var ws;(function(n){n.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",n.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",n.BALANCED="BALANCED",n.PRIORITIZE_COST="PRIORITIZE_COST"})(ws||(ws={}));var Ts;(function(n){n.UNSPECIFIED="UNSPECIFIED",n.BLOCKING="BLOCKING",n.NON_BLOCKING="NON_BLOCKING"})(Ts||(Ts={}));var _s;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(_s||(_s={}));var Cs;(function(n){n.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",n.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(Cs||(Cs={}));var nn;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.AUTO="AUTO",n.ANY="ANY",n.NONE="NONE",n.VALIDATED="VALIDATED"})(nn||(nn={}));var Ss;(function(n){n.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",n.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",n.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",n.BLOCK_NONE="BLOCK_NONE"})(Ss||(Ss={}));var As;(function(n){n.DONT_ALLOW="DONT_ALLOW",n.ALLOW_ADULT="ALLOW_ADULT",n.ALLOW_ALL="ALLOW_ALL"})(As||(As={}));var xs;(function(n){n.auto="auto",n.en="en",n.ja="ja",n.ko="ko",n.hi="hi",n.zh="zh",n.pt="pt",n.es="es"})(xs||(xs={}));var Ps;(function(n){n.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",n.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",n.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",n.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",n.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(Ps||(Ps={}));var Ns;(function(n){n.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",n.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",n.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",n.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(Ns||(Ns={}));var $s;(function(n){n.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",n.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",n.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",n.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})($s||($s={}));var Rs;(function(n){n.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",n.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",n.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",n.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",n.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",n.EDIT_MODE_STYLE="EDIT_MODE_STYLE",n.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",n.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(Rs||(Rs={}));var Gs;(function(n){n.FOREGROUND="FOREGROUND",n.BACKGROUND="BACKGROUND",n.PROMPT="PROMPT",n.SEMANTIC="SEMANTIC",n.INTERACTIVE="INTERACTIVE"})(Gs||(Gs={}));var Ms;(function(n){n.ASSET="ASSET",n.STYLE="STYLE"})(Ms||(Ms={}));var Ds;(function(n){n.INSERT="INSERT",n.REMOVE="REMOVE",n.REMOVE_STATIC="REMOVE_STATIC",n.OUTPAINT="OUTPAINT"})(Ds||(Ds={}));var Ls;(function(n){n.OPTIMIZED="OPTIMIZED",n.LOSSLESS="LOSSLESS"})(Ls||(Ls={}));var ks;(function(n){n.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",n.PREFERENCE_TUNING="PREFERENCE_TUNING"})(ks||(ks={}));var Us;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.STATE_PENDING="STATE_PENDING",n.STATE_ACTIVE="STATE_ACTIVE",n.STATE_FAILED="STATE_FAILED"})(Us||(Us={}));var Fs;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.PROCESSING="PROCESSING",n.ACTIVE="ACTIVE",n.FAILED="FAILED"})(Fs||(Fs={}));var Hs;(function(n){n.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",n.UPLOADED="UPLOADED",n.GENERATED="GENERATED"})(Hs||(Hs={}));var Vs;(function(n){n.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",n.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",n.RESPONSE_REJECTED="RESPONSE_REJECTED",n.NEED_MORE_INPUT="NEED_MORE_INPUT"})(Vs||(Vs={}));var Bs;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.VIDEO="VIDEO",n.AUDIO="AUDIO",n.DOCUMENT="DOCUMENT"})(Bs||(Bs={}));var qs;(function(n){n.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",n.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",n.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(qs||(qs={}));var Os;(function(n){n.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",n.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",n.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(Os||(Os={}));var zs;(function(n){n.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",n.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",n.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(zs||(zs={}));var Js;(function(n){n.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",n.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",n.NO_INTERRUPTION="NO_INTERRUPTION"})(Js||(Js={}));var Ws;(function(n){n.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",n.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",n.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT"})(Ws||(Ws={}));var Ks;(function(n){n.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",n.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",n.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",n.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",n.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",n.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",n.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",n.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",n.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",n.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",n.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",n.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",n.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(Ks||(Ks={}));var Xs;(function(n){n.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",n.QUALITY="QUALITY",n.DIVERSITY="DIVERSITY",n.VOCALIZATION="VOCALIZATION"})(Xs||(Xs={}));var dt;(function(n){n.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",n.PLAY="PLAY",n.PAUSE="PAUSE",n.STOP="STOP",n.RESET_CONTEXT="RESET_CONTEXT"})(dt||(dt={}));var xt=class{static{f(this,"HttpResponse")}constructor(e){let t={};for(let o of e.headers.entries())t[o[0]]=o[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}};var je=class{static{f(this,"GenerateContentResponse")}get text(){var e,t,o,i,r,l,c,d;if(((i=(o=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.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 u="",p=!1,m=[];for(let h of(d=(c=(l=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||l===void 0?void 0:l.content)===null||c===void 0?void 0:c.parts)!==null&&d!==void 0?d:[]){for(let[g,b]of Object.entries(h))g!=="text"&&g!=="thought"&&g!=="thoughtSignature"&&(b!==null||b!==void 0)&&m.push(g);if(typeof h.text=="string"){if(typeof h.thought=="boolean"&&h.thought)continue;p=!0,u+=h.text}}return m.length>0&&console.warn(`there are non-text parts ${m} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),p?u:void 0}get data(){var e,t,o,i,r,l,c,d;if(((i=(o=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.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 u="",p=[];for(let m of(d=(c=(l=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||l===void 0?void 0:l.content)===null||c===void 0?void 0:c.parts)!==null&&d!==void 0?d:[]){for(let[h,g]of Object.entries(m))h!=="inlineData"&&(g!==null||g!==void 0)&&p.push(h);m.inlineData&&typeof m.inlineData.data=="string"&&(u+=atob(m.inlineData.data))}return p.length>0&&console.warn(`there are non-data parts ${p} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),u.length>0?btoa(u):void 0}get functionCalls(){var e,t,o,i,r,l,c,d;if(((i=(o=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.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 u=(d=(c=(l=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||l===void 0?void 0:l.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter(p=>p.functionCall).map(p=>p.functionCall).filter(p=>p!==void 0);if(u?.length!==0)return u}get executableCode(){var e,t,o,i,r,l,c,d,u;if(((i=(o=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.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 p=(d=(c=(l=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||l===void 0?void 0:l.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter(m=>m.executableCode).map(m=>m.executableCode).filter(m=>m!==void 0);if(p?.length!==0)return(u=p?.[0])===null||u===void 0?void 0:u.code}get codeExecutionResult(){var e,t,o,i,r,l,c,d,u;if(((i=(o=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.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 p=(d=(c=(l=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||l===void 0?void 0:l.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter(m=>m.codeExecutionResult).map(m=>m.codeExecutionResult).filter(m=>m!==void 0);if(p?.length!==0)return(u=p?.[0])===null||u===void 0?void 0:u.output}},on=class{static{f(this,"EmbedContentResponse")}},rn=class{static{f(this,"GenerateImagesResponse")}},To=class{static{f(this,"EditImageResponse")}},_o=class{static{f(this,"UpscaleImageResponse")}},Co=class{static{f(this,"RecontextImageResponse")}},So=class{static{f(this,"SegmentImageResponse")}},sn=class{static{f(this,"ListModelsResponse")}},an=class{static{f(this,"DeleteModelResponse")}},ln=class{static{f(this,"CountTokensResponse")}},Ao=class{static{f(this,"ComputeTokensResponse")}};var cn=class n{static{f(this,"GenerateVideosOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let o=new n,i,r=e;return t?i=rc(r):i=ic(r),Object.assign(o,i),o}},dn=class{static{f(this,"ListTuningJobsResponse")}},un=class{static{f(this,"CancelTuningJobResponse")}},fn=class{static{f(this,"DeleteCachedContentResponse")}},pn=class{static{f(this,"ListCachedContentsResponse")}},xo=class{static{f(this,"ListDocumentsResponse")}},Po=class{static{f(this,"ListFileSearchStoresResponse")}},No=class{static{f(this,"UploadToFileSearchStoreResumableResponse")}};var $o=class n{static{f(this,"ImportFileOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let o=new n,r=fc(e);return Object.assign(o,r),o}},Ro=class{static{f(this,"ListFilesResponse")}},Go=class{static{f(this,"CreateFileResponse")}},Mo=class{static{f(this,"DeleteFileResponse")}};var mn=class{static{f(this,"ListBatchJobsResponse")}};var Do=class{static{f(this,"LiveServerMessage")}get text(){var e,t,o;let i="",r=!1,l=[];for(let c of(o=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&o!==void 0?o:[]){for(let[d,u]of Object.entries(c))d!=="text"&&d!=="thought"&&u!==null&&l.push(d);if(typeof c.text=="string"){if(typeof c.thought=="boolean"&&c.thought)continue;r=!0,i+=c.text}}return l.length>0&&console.warn(`there are non-text parts ${l} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),r?i:void 0}get data(){var e,t,o;let i="",r=[];for(let l of(o=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&o!==void 0?o:[]){for(let[c,d]of Object.entries(l))c!=="inlineData"&&d!==null&&r.push(c);l.inlineData&&typeof l.inlineData.data=="string"&&(i+=atob(l.inlineData.data))}return r.length>0&&console.warn(`there are non-data parts ${r} 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}};var Lo=class{static{f(this,"LiveMusicServerMessage")}get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var ko=class n{static{f(this,"UploadToFileSearchStoreOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let o=new n,r=va(e);return Object.assign(o,r),o}};function L(n,e){if(!e||typeof e!="string")throw new Error("model is required and must be a string");if(e.includes("..")||e.includes("?")||e.includes("&"))throw new Error("invalid model parameter");if(n.isVertexAI()){if(e.startsWith("publishers/")||e.startsWith("projects/")||e.startsWith("models/"))return e;if(e.indexOf("/")>=0){let t=e.split("/",2);return`publishers/${t[0]}/models/${t[1]}`}else return`publishers/google/models/${e}`}else return e.startsWith("models/")||e.startsWith("tunedModels/")?e:`models/${e}`}f(L,"tModel");function wa(n,e){let t=L(n,e);return t?t.startsWith("publishers/")&&n.isVertexAI()?`projects/${n.getProject()}/locations/${n.getLocation()}/${t}`:t.startsWith("models/")&&n.isVertexAI()?`projects/${n.getProject()}/locations/${n.getLocation()}/publishers/google/${t}`:t:""}f(wa,"tCachesModel");function Ta(n){return Array.isArray(n)?n.map(e=>hn(e)):[hn(n)]}f(Ta,"tBlobs");function hn(n){if(typeof n=="object"&&n!==null)return n;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof n}`)}f(hn,"tBlob");function _a(n){let e=hn(n);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}f(_a,"tImageBlob");function Ca(n){let e=hn(n);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}f(Ca,"tAudioBlob");function Ys(n){if(n==null)throw new Error("PartUnion is required");if(typeof n=="object")return n;if(typeof n=="string")return{text:n};throw new Error(`Unsupported part type: ${typeof n}`)}f(Ys,"tPart");function Sa(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("PartListUnion is required");return Array.isArray(n)?n.map(e=>Ys(e)):[Ys(n)]}f(Sa,"tParts");function Uo(n){return n!=null&&typeof n=="object"&&"parts"in n&&Array.isArray(n.parts)}f(Uo,"_isContent");function Qs(n){return n!=null&&typeof n=="object"&&"functionCall"in n}f(Qs,"_isFunctionCallPart");function Zs(n){return n!=null&&typeof n=="object"&&"functionResponse"in n}f(Zs,"_isFunctionResponsePart");function ie(n){if(n==null)throw new Error("ContentUnion is required");return Uo(n)?n:{role:"user",parts:Sa(n)}}f(ie,"tContent");function Ii(n,e){if(!e)return[];if(n.isVertexAI()&&Array.isArray(e))return e.flatMap(t=>{let o=ie(t);return o.parts&&o.parts.length>0&&o.parts[0].text!==void 0?[o.parts[0].text]:[]});if(n.isVertexAI()){let t=ie(e);return t.parts&&t.parts.length>0&&t.parts[0].text!==void 0?[t.parts[0].text]:[]}return Array.isArray(e)?e.map(t=>ie(t)):[ie(e)]}f(Ii,"tContentsForEmbed");function he(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("contents are required");if(!Array.isArray(n)){if(Qs(n)||Zs(n))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[ie(n)]}let e=[],t=[],o=Uo(n[0]);for(let i of n){let r=Uo(i);if(r!=o)throw new 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(r)e.push(i);else{if(Qs(i)||Zs(i))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");t.push(i)}}return o||e.push({role:"user",parts:Sa(t)}),e}f(he,"tContents");function bc(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1)e.type=Object.values(Fe).includes(t[0].toUpperCase())?t[0].toUpperCase():Fe.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let o of t)e.anyOf.push({type:Object.values(Fe).includes(o.toUpperCase())?o.toUpperCase():Fe.TYPE_UNSPECIFIED})}}f(bc,"flattenTypeArrayToAnyOf");function ut(n){let e={},t=["items"],o=["anyOf"],i=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let r=n.anyOf;r!=null&&r.length==2&&(r[0].type==="null"?(e.nullable=!0,n=r[1]):r[1].type==="null"&&(e.nullable=!0,n=r[0])),n.type instanceof Array&&bc(n.type,e);for(let[l,c]of Object.entries(n))if(c!=null)if(l=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(c instanceof Array)continue;e.type=Object.values(Fe).includes(c.toUpperCase())?c.toUpperCase():Fe.TYPE_UNSPECIFIED}else if(t.includes(l))e[l]=ut(c);else if(o.includes(l)){let d=[];for(let u of c){if(u.type=="null"){e.nullable=!0;continue}d.push(ut(u))}e[l]=d}else if(i.includes(l)){let d={};for(let[u,p]of Object.entries(c))d[u]=ut(p);e[l]=d}else{if(l==="additionalProperties")continue;e[l]=c}return e}f(ut,"processJsonSchema");function vi(n){return ut(n)}f(vi,"tSchema");function wi(n){if(typeof n=="object")return n;if(typeof n=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:n}}};throw new Error(`Unsupported speechConfig type: ${typeof n}`)}f(wi,"tSpeechConfig");function Ti(n){if("multiSpeakerVoiceConfig"in n)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return n}f(Ti,"tLiveSpeechConfig");function ht(n){if(n.functionDeclarations)for(let e of n.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=ut(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=ut(e.response));return n}f(ht,"tTool");function gt(n){if(n==null)throw new Error("tools is required");if(!Array.isArray(n))throw new Error("tools is required and must be an array of Tools");let e=[];for(let t of n)e.push(t);return e}f(gt,"tTools");function yc(n,e,t,o=1){let i=!e.startsWith(`${t}/`)&&e.split("/").length===o;return n.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${n.getProject()}/${e}`:e.startsWith(`${t}/`)?`projects/${n.getProject()}/locations/${n.getLocation()}/${e}`:i?`projects/${n.getProject()}/locations/${n.getLocation()}/${t}/${e}`:e:i?`${t}/${e}`:e}f(yc,"resourceName");function Me(n,e){if(typeof e!="string")throw new Error("name must be a string");return yc(n,e,"cachedContents")}f(Me,"tCachedContentName");function Aa(n){switch(n){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 n}}f(Aa,"tTuningJobStatus");function He(n){return Ei(n)}f(He,"tBytes");function Ec(n){return n!=null&&typeof n=="object"&&"name"in n}f(Ec,"_isFile");function Ic(n){return n!=null&&typeof n=="object"&&"video"in n}f(Ic,"isGeneratedVideo");function vc(n){return n!=null&&typeof n=="object"&&"uri"in n}f(vc,"isVideo");function xa(n){var e;let t;if(Ec(n)&&(t=n.name),!(vc(n)&&(t=n.uri,t===void 0))&&!(Ic(n)&&(t=(e=n.video)===null||e===void 0?void 0:e.uri,t===void 0))){if(typeof n=="string"&&(t=n),t===void 0)throw new Error("Could not extract file name from the provided input.");if(t.startsWith("https://")){let i=t.split("files/")[1].match(/[a-z0-9]+/);if(i===null)throw new Error(`Could not extract file name from URI ${t}`);t=i[0]}else t.startsWith("files/")&&(t=t.split("files/")[1]);return t}}f(xa,"tFileName");function Pa(n,e){let t;return n.isVertexAI()?t=e?"publishers/google/models":"models":t=e?"models":"tunedModels",t}f(Pa,"tModelsUrl");function Na(n){for(let e of["models","tunedModels","publisherModels"])if(wc(n,e))return n[e];return[]}f(Na,"tExtractModels");function wc(n,e){return n!==null&&typeof n=="object"&&e in n}f(wc,"hasField");function Tc(n,e={}){let t=n,o={name:t.name,description:t.description,parametersJsonSchema:t.inputSchema};return t.outputSchema&&(o.responseJsonSchema=t.outputSchema),e.behavior&&(o.behavior=e.behavior),{functionDeclarations:[o]}}f(Tc,"mcpToGeminiTool");function _c(n,e={}){let t=[],o=new Set;for(let i of n){let r=i.name;if(o.has(r))throw new Error(`Duplicate function name ${r} found in MCP tools. Please ensure function names are unique.`);o.add(r);let l=Tc(i,e);l.functionDeclarations&&t.push(...l.functionDeclarations)}return{functionDeclarations:t}}f(_c,"mcpToolsToGeminiTool");function $a(n,e){let t;if(typeof e=="string")if(n.isVertexAI())if(e.startsWith("gs://"))t={format:"jsonl",gcsUri:[e]};else if(e.startsWith("bq://"))t={format:"bigquery",bigqueryUri:e};else throw new Error(`Unsupported string source for Vertex AI: ${e}`);else if(e.startsWith("files/"))t={fileName:e};else throw new Error(`Unsupported string source for Gemini API: ${e}`);else if(Array.isArray(e)){if(n.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");t={inlinedRequests:e}}else t=e;let o=[t.gcsUri,t.bigqueryUri].filter(Boolean).length,i=[t.inlinedRequests,t.fileName].filter(Boolean).length;if(n.isVertexAI()){if(i>0||o!==1)throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(o>0||i!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return t}f($a,"tBatchJobSource");function Cc(n){if(typeof n!="string")return n;let e=n;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw new Error(`Unsupported destination: ${e}`)}f(Cc,"tBatchJobDestination");function Ra(n){if(typeof n!="object"||n===null)return{};let e=n,t=e.inlinedResponses;if(typeof t!="object"||t===null)return n;let i=t.inlinedResponses;if(!Array.isArray(i)||i.length===0)return n;let r=!1;for(let l of i){if(typeof l!="object"||l===null)continue;let d=l.response;if(typeof d!="object"||d===null)continue;if(d.embedding!==void 0){r=!0;break}}return r&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),n}f(Ra,"tRecvBatchJobDestination");function bt(n,e){let t=e;if(!n.isVertexAI()){if(/batches\/[^/]+$/.test(t))return t.split("/").pop();throw new Error(`Invalid batch job name: ${t}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(t))return t.split("/").pop();if(/^\d+$/.test(t))return t;throw new Error(`Invalid batch job name: ${t}.`)}f(bt,"tBatchJobName");function Ga(n){let e=n;return e==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":e==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":e==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":e==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":e==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":e==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":e==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":e}f(Ga,"tJobState");function Sc(n){let e={},t=s(n,["responsesFile"]);t!=null&&a(e,["fileName"],t);let o=s(n,["inlinedResponses","inlinedResponses"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>sd(l))),a(e,["inlinedResponses"],r)}let i=s(n,["inlinedEmbedContentResponses","inlinedResponses"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(l=>l)),a(e,["inlinedEmbedContentResponses"],r)}return e}f(Sc,"batchJobDestinationFromMldev");function Ac(n){let e={},t=s(n,["predictionsFormat"]);t!=null&&a(e,["format"],t);let o=s(n,["gcsDestination","outputUriPrefix"]);o!=null&&a(e,["gcsUri"],o);let i=s(n,["bigqueryDestination","outputUri"]);return i!=null&&a(e,["bigqueryUri"],i),e}f(Ac,"batchJobDestinationFromVertex");function xc(n){let e={},t=s(n,["format"]);t!=null&&a(e,["predictionsFormat"],t);let o=s(n,["gcsUri"]);o!=null&&a(e,["gcsDestination","outputUriPrefix"],o);let i=s(n,["bigqueryUri"]);if(i!=null&&a(e,["bigqueryDestination","outputUri"],i),s(n,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(s(n,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is not supported in Vertex AI.");if(s(n,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");return e}f(xc,"batchJobDestinationToVertex");function jt(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["metadata","displayName"]);o!=null&&a(e,["displayName"],o);let i=s(n,["metadata","state"]);i!=null&&a(e,["state"],Ga(i));let r=s(n,["metadata","createTime"]);r!=null&&a(e,["createTime"],r);let l=s(n,["metadata","endTime"]);l!=null&&a(e,["endTime"],l);let c=s(n,["metadata","updateTime"]);c!=null&&a(e,["updateTime"],c);let d=s(n,["metadata","model"]);d!=null&&a(e,["model"],d);let u=s(n,["metadata","output"]);return u!=null&&a(e,["dest"],Sc(Ra(u))),e}f(jt,"batchJobFromMldev");function Fo(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["displayName"]);o!=null&&a(e,["displayName"],o);let i=s(n,["state"]);i!=null&&a(e,["state"],Ga(i));let r=s(n,["error"]);r!=null&&a(e,["error"],r);let l=s(n,["createTime"]);l!=null&&a(e,["createTime"],l);let c=s(n,["startTime"]);c!=null&&a(e,["startTime"],c);let d=s(n,["endTime"]);d!=null&&a(e,["endTime"],d);let u=s(n,["updateTime"]);u!=null&&a(e,["updateTime"],u);let p=s(n,["model"]);p!=null&&a(e,["model"],p);let m=s(n,["inputConfig"]);m!=null&&a(e,["src"],Pc(m));let h=s(n,["outputConfig"]);h!=null&&a(e,["dest"],Ac(Ra(h)));let g=s(n,["completionStats"]);return g!=null&&a(e,["completionStats"],g),e}f(Fo,"batchJobFromVertex");function Pc(n){let e={},t=s(n,["instancesFormat"]);t!=null&&a(e,["format"],t);let o=s(n,["gcsSource","uris"]);o!=null&&a(e,["gcsUri"],o);let i=s(n,["bigquerySource","inputUri"]);return i!=null&&a(e,["bigqueryUri"],i),e}f(Pc,"batchJobSourceFromVertex");function Nc(n,e){let t={};if(s(e,["format"])!==void 0)throw new Error("format parameter is not supported in Gemini API.");if(s(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(s(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is not supported in Gemini API.");let o=s(e,["fileName"]);o!=null&&a(t,["fileName"],o);let i=s(e,["inlinedRequests"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(l=>rd(n,l))),a(t,["requests","requests"],r)}return t}f(Nc,"batchJobSourceToMldev");function $c(n){let e={},t=s(n,["format"]);t!=null&&a(e,["instancesFormat"],t);let o=s(n,["gcsUri"]);o!=null&&a(e,["gcsSource","uris"],o);let i=s(n,["bigqueryUri"]);if(i!=null&&a(e,["bigquerySource","inputUri"],i),s(n,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(s(n,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is not supported in Vertex AI.");return e}f($c,"batchJobSourceToVertex");function Rc(n){let e={},t=s(n,["data"]);if(t!=null&&a(e,["data"],t),s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(Rc,"blobToMldev$4");function Gc(n,e){let t={},o=s(e,["name"]);return o!=null&&a(t,["_url","name"],bt(n,o)),t}f(Gc,"cancelBatchJobParametersToMldev");function Mc(n,e){let t={},o=s(e,["name"]);return o!=null&&a(t,["_url","name"],bt(n,o)),t}f(Mc,"cancelBatchJobParametersToVertex");function Dc(n){let e={},t=s(n,["content"]);t!=null&&a(e,["content"],t);let o=s(n,["citationMetadata"]);o!=null&&a(e,["citationMetadata"],Lc(o));let i=s(n,["tokenCount"]);i!=null&&a(e,["tokenCount"],i);let r=s(n,["finishReason"]);r!=null&&a(e,["finishReason"],r);let l=s(n,["avgLogprobs"]);l!=null&&a(e,["avgLogprobs"],l);let c=s(n,["groundingMetadata"]);c!=null&&a(e,["groundingMetadata"],c);let d=s(n,["index"]);d!=null&&a(e,["index"],d);let u=s(n,["logprobsResult"]);u!=null&&a(e,["logprobsResult"],u);let p=s(n,["safetyRatings"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(g=>g)),a(e,["safetyRatings"],h)}let m=s(n,["urlContextMetadata"]);return m!=null&&a(e,["urlContextMetadata"],m),e}f(Dc,"candidateFromMldev$1");function Lc(n){let e={},t=s(n,["citationSources"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(i=>i)),a(e,["citations"],o)}return e}f(Lc,"citationMetadataFromMldev$1");function Ma(n){let e={},t=s(n,["parts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(r=>pd(r))),a(e,["parts"],i)}let o=s(n,["role"]);return o!=null&&a(e,["role"],o),e}f(Ma,"contentToMldev$4");function kc(n,e){let t={},o=s(n,["displayName"]);if(e!==void 0&&o!=null&&a(e,["batch","displayName"],o),s(n,["dest"])!==void 0)throw new Error("dest parameter is not supported in Gemini API.");return t}f(kc,"createBatchJobConfigToMldev");function Uc(n,e){let t={},o=s(n,["displayName"]);e!==void 0&&o!=null&&a(e,["displayName"],o);let i=s(n,["dest"]);return e!==void 0&&i!=null&&a(e,["outputConfig"],xc(Cc(i))),t}f(Uc,"createBatchJobConfigToVertex");function js(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["src"]);i!=null&&a(t,["batch","inputConfig"],Nc(n,$a(n,i)));let r=s(e,["config"]);return r!=null&&kc(r,t),t}f(js,"createBatchJobParametersToMldev");function Fc(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["model"],L(n,o));let i=s(e,["src"]);i!=null&&a(t,["inputConfig"],$c($a(n,i)));let r=s(e,["config"]);return r!=null&&Uc(r,t),t}f(Fc,"createBatchJobParametersToVertex");function Hc(n,e){let t={},o=s(n,["displayName"]);return e!==void 0&&o!=null&&a(e,["batch","displayName"],o),t}f(Hc,"createEmbeddingsBatchJobConfigToMldev");function Vc(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["src"]);i!=null&&a(t,["batch","inputConfig"],Kc(n,i));let r=s(e,["config"]);return r!=null&&Hc(r,t),t}f(Vc,"createEmbeddingsBatchJobParametersToMldev");function Bc(n,e){let t={},o=s(e,["name"]);return o!=null&&a(t,["_url","name"],bt(n,o)),t}f(Bc,"deleteBatchJobParametersToMldev");function qc(n,e){let t={},o=s(e,["name"]);return o!=null&&a(t,["_url","name"],bt(n,o)),t}f(qc,"deleteBatchJobParametersToVertex");function Oc(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["name"]);o!=null&&a(e,["name"],o);let i=s(n,["done"]);i!=null&&a(e,["done"],i);let r=s(n,["error"]);return r!=null&&a(e,["error"],r),e}f(Oc,"deleteResourceJobFromMldev");function zc(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["name"]);o!=null&&a(e,["name"],o);let i=s(n,["done"]);i!=null&&a(e,["done"],i);let r=s(n,["error"]);return r!=null&&a(e,["error"],r),e}f(zc,"deleteResourceJobFromVertex");function Jc(n,e){let t={},o=s(e,["contents"]);if(o!=null){let r=Ii(n,o);Array.isArray(r)&&(r=r.map(l=>l)),a(t,["requests[]","request","content"],r)}let i=s(e,["config"]);return i!=null&&(a(t,["_self"],Wc(i,t)),nc(t,{"requests[].*":"requests[].request.*"})),t}f(Jc,"embedContentBatchToMldev");function Wc(n,e){let t={},o=s(n,["taskType"]);e!==void 0&&o!=null&&a(e,["requests[]","taskType"],o);let i=s(n,["title"]);e!==void 0&&i!=null&&a(e,["requests[]","title"],i);let r=s(n,["outputDimensionality"]);if(e!==void 0&&r!=null&&a(e,["requests[]","outputDimensionality"],r),s(n,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(s(n,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return t}f(Wc,"embedContentConfigToMldev$1");function Kc(n,e){let t={},o=s(e,["fileName"]);o!=null&&a(t,["file_name"],o);let i=s(e,["inlinedRequests"]);return i!=null&&a(t,["requests"],Jc(n,i)),t}f(Kc,"embeddingsBatchJobSourceToMldev");function Xc(n){let e={};if(s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=s(n,["fileUri"]);t!=null&&a(e,["fileUri"],t);let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(Xc,"fileDataToMldev$4");function Yc(n){let e={},t=s(n,["id"]);t!=null&&a(e,["id"],t);let o=s(n,["args"]);o!=null&&a(e,["args"],o);let i=s(n,["name"]);if(i!=null&&a(e,["name"],i),s(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(s(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}f(Yc,"functionCallToMldev$4");function Qc(n){let e={},t=s(n,["mode"]);t!=null&&a(e,["mode"],t);let o=s(n,["allowedFunctionNames"]);if(o!=null&&a(e,["allowedFunctionNames"],o),s(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}f(Qc,"functionCallingConfigToMldev$2");function Zc(n,e,t){let o={},i=s(e,["systemInstruction"]);t!==void 0&&i!=null&&a(t,["systemInstruction"],Ma(ie(i)));let r=s(e,["temperature"]);r!=null&&a(o,["temperature"],r);let l=s(e,["topP"]);l!=null&&a(o,["topP"],l);let c=s(e,["topK"]);c!=null&&a(o,["topK"],c);let d=s(e,["candidateCount"]);d!=null&&a(o,["candidateCount"],d);let u=s(e,["maxOutputTokens"]);u!=null&&a(o,["maxOutputTokens"],u);let p=s(e,["stopSequences"]);p!=null&&a(o,["stopSequences"],p);let m=s(e,["responseLogprobs"]);m!=null&&a(o,["responseLogprobs"],m);let h=s(e,["logprobs"]);h!=null&&a(o,["logprobs"],h);let g=s(e,["presencePenalty"]);g!=null&&a(o,["presencePenalty"],g);let b=s(e,["frequencyPenalty"]);b!=null&&a(o,["frequencyPenalty"],b);let E=s(e,["seed"]);E!=null&&a(o,["seed"],E);let I=s(e,["responseMimeType"]);I!=null&&a(o,["responseMimeType"],I);let v=s(e,["responseSchema"]);v!=null&&a(o,["responseSchema"],vi(v));let w=s(e,["responseJsonSchema"]);if(w!=null&&a(o,["responseJsonSchema"],w),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");let T=s(e,["safetySettings"]);if(t!==void 0&&T!=null){let B=T;Array.isArray(B)&&(B=B.map(_e=>md(_e))),a(t,["safetySettings"],B)}let C=s(e,["tools"]);if(t!==void 0&&C!=null){let B=gt(C);Array.isArray(B)&&(B=B.map(_e=>gd(ht(_e)))),a(t,["tools"],B)}let A=s(e,["toolConfig"]);if(t!==void 0&&A!=null&&a(t,["toolConfig"],hd(A)),s(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let G=s(e,["cachedContent"]);t!==void 0&&G!=null&&a(t,["cachedContent"],Me(n,G));let N=s(e,["responseModalities"]);N!=null&&a(o,["responseModalities"],N);let H=s(e,["mediaResolution"]);H!=null&&a(o,["mediaResolution"],H);let x=s(e,["speechConfig"]);if(x!=null&&a(o,["speechConfig"],wi(x)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let D=s(e,["thinkingConfig"]);D!=null&&a(o,["thinkingConfig"],D);let J=s(e,["imageConfig"]);J!=null&&a(o,["imageConfig"],id(J));let Pe=s(e,["enableEnhancedCivicAnswers"]);return Pe!=null&&a(o,["enableEnhancedCivicAnswers"],Pe),o}f(Zc,"generateContentConfigToMldev$1");function jc(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["candidates"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(u=>Dc(u))),a(e,["candidates"],d)}let i=s(n,["modelVersion"]);i!=null&&a(e,["modelVersion"],i);let r=s(n,["promptFeedback"]);r!=null&&a(e,["promptFeedback"],r);let l=s(n,["responseId"]);l!=null&&a(e,["responseId"],l);let c=s(n,["usageMetadata"]);return c!=null&&a(e,["usageMetadata"],c),e}f(jc,"generateContentResponseFromMldev$1");function ed(n,e){let t={},o=s(e,["name"]);return o!=null&&a(t,["_url","name"],bt(n,o)),t}f(ed,"getBatchJobParametersToMldev");function td(n,e){let t={},o=s(e,["name"]);return o!=null&&a(t,["_url","name"],bt(n,o)),t}f(td,"getBatchJobParametersToVertex");function nd(n){let e={};if(s(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=s(n,["enableWidget"]);return t!=null&&a(e,["enableWidget"],t),e}f(nd,"googleMapsToMldev$4");function od(n){let e={};if(s(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(s(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=s(n,["timeRangeFilter"]);return t!=null&&a(e,["timeRangeFilter"],t),e}f(od,"googleSearchToMldev$4");function id(n){let e={},t=s(n,["aspectRatio"]);t!=null&&a(e,["aspectRatio"],t);let o=s(n,["imageSize"]);if(o!=null&&a(e,["imageSize"],o),s(n,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(s(n,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}f(id,"imageConfigToMldev$1");function rd(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["request","model"],L(n,o));let i=s(e,["contents"]);if(i!=null){let c=he(i);Array.isArray(c)&&(c=c.map(d=>Ma(d))),a(t,["request","contents"],c)}let r=s(e,["metadata"]);r!=null&&a(t,["metadata"],r);let l=s(e,["config"]);return l!=null&&a(t,["request","generationConfig"],Zc(n,l,s(t,["request"],{}))),t}f(rd,"inlinedRequestToMldev");function sd(n){let e={},t=s(n,["response"]);t!=null&&a(e,["response"],jc(t));let o=s(n,["error"]);return o!=null&&a(e,["error"],o),e}f(sd,"inlinedResponseFromMldev");function ad(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&a(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);if(e!==void 0&&i!=null&&a(e,["_query","pageToken"],i),s(n,["filter"])!==void 0)throw new Error("filter parameter is not supported in Gemini API.");return t}f(ad,"listBatchJobsConfigToMldev");function ld(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&a(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);e!==void 0&&i!=null&&a(e,["_query","pageToken"],i);let r=s(n,["filter"]);return e!==void 0&&r!=null&&a(e,["_query","filter"],r),t}f(ld,"listBatchJobsConfigToVertex");function cd(n){let e={},t=s(n,["config"]);return t!=null&&ad(t,e),e}f(cd,"listBatchJobsParametersToMldev");function dd(n){let e={},t=s(n,["config"]);return t!=null&&ld(t,e),e}f(dd,"listBatchJobsParametersToVertex");function ud(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&a(e,["nextPageToken"],o);let i=s(n,["operations"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(l=>jt(l))),a(e,["batchJobs"],r)}return e}f(ud,"listBatchJobsResponseFromMldev");function fd(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&a(e,["nextPageToken"],o);let i=s(n,["batchPredictionJobs"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(l=>Fo(l))),a(e,["batchJobs"],r)}return e}f(fd,"listBatchJobsResponseFromVertex");function pd(n){let e={},t=s(n,["mediaResolution"]);t!=null&&a(e,["mediaResolution"],t);let o=s(n,["codeExecutionResult"]);o!=null&&a(e,["codeExecutionResult"],o);let i=s(n,["executableCode"]);i!=null&&a(e,["executableCode"],i);let r=s(n,["fileData"]);r!=null&&a(e,["fileData"],Xc(r));let l=s(n,["functionCall"]);l!=null&&a(e,["functionCall"],Yc(l));let c=s(n,["functionResponse"]);c!=null&&a(e,["functionResponse"],c);let d=s(n,["inlineData"]);d!=null&&a(e,["inlineData"],Rc(d));let u=s(n,["text"]);u!=null&&a(e,["text"],u);let p=s(n,["thought"]);p!=null&&a(e,["thought"],p);let m=s(n,["thoughtSignature"]);m!=null&&a(e,["thoughtSignature"],m);let h=s(n,["videoMetadata"]);return h!=null&&a(e,["videoMetadata"],h),e}f(pd,"partToMldev$4");function md(n){let e={},t=s(n,["category"]);if(t!=null&&a(e,["category"],t),s(n,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let o=s(n,["threshold"]);return o!=null&&a(e,["threshold"],o),e}f(md,"safetySettingToMldev$1");function hd(n){let e={},t=s(n,["functionCallingConfig"]);t!=null&&a(e,["functionCallingConfig"],Qc(t));let o=s(n,["retrievalConfig"]);return o!=null&&a(e,["retrievalConfig"],o),e}f(hd,"toolConfigToMldev$2");function gd(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let p=t;Array.isArray(p)&&(p=p.map(m=>m)),a(e,["functionDeclarations"],p)}if(s(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let o=s(n,["googleSearchRetrieval"]);o!=null&&a(e,["googleSearchRetrieval"],o);let i=s(n,["computerUse"]);i!=null&&a(e,["computerUse"],i);let r=s(n,["fileSearch"]);r!=null&&a(e,["fileSearch"],r);let l=s(n,["codeExecution"]);if(l!=null&&a(e,["codeExecution"],l),s(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=s(n,["googleMaps"]);c!=null&&a(e,["googleMaps"],nd(c));let d=s(n,["googleSearch"]);d!=null&&a(e,["googleSearch"],od(d));let u=s(n,["urlContext"]);return u!=null&&a(e,["urlContext"],u),e}f(gd,"toolToMldev$4");var Re;(function(n){n.PAGED_ITEM_BATCH_JOBS="batchJobs",n.PAGED_ITEM_MODELS="models",n.PAGED_ITEM_TUNING_JOBS="tuningJobs",n.PAGED_ITEM_FILES="files",n.PAGED_ITEM_CACHED_CONTENTS="cachedContents",n.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",n.PAGED_ITEM_DOCUMENTS="documents"})(Re||(Re={}));var Ge=class{static{f(this,"Pager")}constructor(e,t,o,i){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,o,i)}init(e,t,o){var i,r;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=t?.sdkHttpResponse,this.idxInternal=0;let l={config:{}};!o||Object.keys(o).length===0?l={config:{}}:typeof o=="object"?l=Object.assign({},o):l=o,l.config&&(l.config.pageToken=t.nextPageToken),this.paramsInternal=l,this.pageInternalSize=(r=(i=l.config)===null||i===void 0?void 0:i.pageSize)!==null&&r!==void 0?r:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,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(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:f(async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},"next"),return:f(async()=>({value:void 0,done:!0}),"return")}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}};var Ho=class extends we{static{f(this,"Batches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Ge(Re.PAGED_ITEM_BATCH_JOBS,o=>this.listInternal(o),await this.listInternal(t),t),this.create=async t=>(this.apiClient.isVertexAI()&&(t.config=this.formatDestination(t.src,t.config)),this.createInternal(t)),this.createEmbeddings=async t=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Vertex AI does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(t)}}createInlinedGenerateContentRequest(e){let t=js(this.apiClient,e),o=t._url,i=_("{model}:batchGenerateContent",o),c=t.batch.inputConfig.requests,d=c.requests,u=[];for(let p of d){let m=Object.assign({},p);if(m.systemInstruction){let h=m.systemInstruction;delete m.systemInstruction;let g=m.request;g.systemInstruction=h,m.request=g}u.push(m)}return c.requests=u,delete t.config,delete t._url,delete t._query,{path:i,body:t}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,t){let o=t?Object.assign({},t):{},i=Date.now().toString();if(o.displayName||(o.displayName=`genaiBatchJob_${i}`),o.dest===void 0){let r=this.getGcsUri(e),l=this.getBigqueryUri(e);if(r)r.endsWith(".jsonl")?o.dest=`${r.slice(0,-6)}/dest`:o.dest=`${r}_dest_${i}`;else if(l)o.dest=`${l}_dest_${i}`;else throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.")}return o}async createInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=Fc(this.apiClient,e);return c=_("batchPredictionJobs",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),l.then(p=>Fo(p))}else{let u=js(this.apiClient,e);return c=_("{model}:batchGenerateContent",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),l.then(p=>jt(p))}}async createEmbeddingsInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Vc(this.apiClient,e);return r=_("{model}:asyncBatchEmbedContent",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>jt(d))}}async get(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=td(this.apiClient,e);return c=_("batchPredictionJobs/{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),l.then(p=>Fo(p))}else{let u=ed(this.apiClient,e);return c=_("batches/{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),l.then(p=>jt(p))}}async cancel(e){var t,o,i,r;let l="",c={};if(this.apiClient.isVertexAI()){let d=Mc(this.apiClient,e);l=_("batchPredictionJobs/{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,await this.apiClient.request({path:l,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}else{let d=Gc(this.apiClient,e);l=_("batches/{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,await this.apiClient.request({path:l,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}}async listInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=dd(e);return c=_("batchPredictionJobs",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=fd(p),h=new mn;return Object.assign(h,m),h})}else{let u=cd(e);return c=_("batches",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=ud(p),h=new mn;return Object.assign(h,m),h})}}async delete(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=qc(this.apiClient,e);return c=_("batchPredictionJobs/{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>zc(p))}else{let u=Bc(this.apiClient,e);return c=_("batches/{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>Oc(p))}}};function bd(n){let e={},t=s(n,["data"]);if(t!=null&&a(e,["data"],t),s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(bd,"blobToMldev$3");function ea(n){let e={},t=s(n,["parts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(r=>Hd(r))),a(e,["parts"],i)}let o=s(n,["role"]);return o!=null&&a(e,["role"],o),e}f(ea,"contentToMldev$3");function yd(n,e){let t={},o=s(n,["ttl"]);e!==void 0&&o!=null&&a(e,["ttl"],o);let i=s(n,["expireTime"]);e!==void 0&&i!=null&&a(e,["expireTime"],i);let r=s(n,["displayName"]);e!==void 0&&r!=null&&a(e,["displayName"],r);let l=s(n,["contents"]);if(e!==void 0&&l!=null){let p=he(l);Array.isArray(p)&&(p=p.map(m=>ea(m))),a(e,["contents"],p)}let c=s(n,["systemInstruction"]);e!==void 0&&c!=null&&a(e,["systemInstruction"],ea(ie(c)));let d=s(n,["tools"]);if(e!==void 0&&d!=null){let p=d;Array.isArray(p)&&(p=p.map(m=>Bd(m))),a(e,["tools"],p)}let u=s(n,["toolConfig"]);if(e!==void 0&&u!=null&&a(e,["toolConfig"],Vd(u)),s(n,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return t}f(yd,"createCachedContentConfigToMldev");function Ed(n,e){let t={},o=s(n,["ttl"]);e!==void 0&&o!=null&&a(e,["ttl"],o);let i=s(n,["expireTime"]);e!==void 0&&i!=null&&a(e,["expireTime"],i);let r=s(n,["displayName"]);e!==void 0&&r!=null&&a(e,["displayName"],r);let l=s(n,["contents"]);if(e!==void 0&&l!=null){let m=he(l);Array.isArray(m)&&(m=m.map(h=>h)),a(e,["contents"],m)}let c=s(n,["systemInstruction"]);e!==void 0&&c!=null&&a(e,["systemInstruction"],ie(c));let d=s(n,["tools"]);if(e!==void 0&&d!=null){let m=d;Array.isArray(m)&&(m=m.map(h=>qd(h))),a(e,["tools"],m)}let u=s(n,["toolConfig"]);e!==void 0&&u!=null&&a(e,["toolConfig"],u);let p=s(n,["kmsKeyName"]);return e!==void 0&&p!=null&&a(e,["encryption_spec","kmsKeyName"],p),t}f(Ed,"createCachedContentConfigToVertex");function Id(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["model"],wa(n,o));let i=s(e,["config"]);return i!=null&&yd(i,t),t}f(Id,"createCachedContentParametersToMldev");function vd(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["model"],wa(n,o));let i=s(e,["config"]);return i!=null&&Ed(i,t),t}f(vd,"createCachedContentParametersToVertex");function wd(n,e){let t={},o=s(e,["name"]);return o!=null&&a(t,["_url","name"],Me(n,o)),t}f(wd,"deleteCachedContentParametersToMldev");function Td(n,e){let t={},o=s(e,["name"]);return o!=null&&a(t,["_url","name"],Me(n,o)),t}f(Td,"deleteCachedContentParametersToVertex");function _d(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&a(e,["sdkHttpResponse"],t),e}f(_d,"deleteCachedContentResponseFromMldev");function Cd(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&a(e,["sdkHttpResponse"],t),e}f(Cd,"deleteCachedContentResponseFromVertex");function Sd(n){let e={};if(s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=s(n,["fileUri"]);t!=null&&a(e,["fileUri"],t);let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(Sd,"fileDataToMldev$3");function Ad(n){let e={},t=s(n,["id"]);t!=null&&a(e,["id"],t);let o=s(n,["args"]);o!=null&&a(e,["args"],o);let i=s(n,["name"]);if(i!=null&&a(e,["name"],i),s(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(s(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}f(Ad,"functionCallToMldev$3");function xd(n){let e={},t=s(n,["mode"]);t!=null&&a(e,["mode"],t);let o=s(n,["allowedFunctionNames"]);if(o!=null&&a(e,["allowedFunctionNames"],o),s(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}f(xd,"functionCallingConfigToMldev$1");function Pd(n){let e={};if(s(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=s(n,["description"]);t!=null&&a(e,["description"],t);let o=s(n,["name"]);o!=null&&a(e,["name"],o);let i=s(n,["parameters"]);i!=null&&a(e,["parameters"],i);let r=s(n,["parametersJsonSchema"]);r!=null&&a(e,["parametersJsonSchema"],r);let l=s(n,["response"]);l!=null&&a(e,["response"],l);let c=s(n,["responseJsonSchema"]);return c!=null&&a(e,["responseJsonSchema"],c),e}f(Pd,"functionDeclarationToVertex$2");function Nd(n,e){let t={},o=s(e,["name"]);return o!=null&&a(t,["_url","name"],Me(n,o)),t}f(Nd,"getCachedContentParametersToMldev");function $d(n,e){let t={},o=s(e,["name"]);return o!=null&&a(t,["_url","name"],Me(n,o)),t}f($d,"getCachedContentParametersToVertex");function Rd(n){let e={};if(s(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=s(n,["enableWidget"]);return t!=null&&a(e,["enableWidget"],t),e}f(Rd,"googleMapsToMldev$3");function Gd(n){let e={};if(s(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(s(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=s(n,["timeRangeFilter"]);return t!=null&&a(e,["timeRangeFilter"],t),e}f(Gd,"googleSearchToMldev$3");function Md(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&a(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);return e!==void 0&&i!=null&&a(e,["_query","pageToken"],i),t}f(Md,"listCachedContentsConfigToMldev");function Dd(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&a(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);return e!==void 0&&i!=null&&a(e,["_query","pageToken"],i),t}f(Dd,"listCachedContentsConfigToVertex");function Ld(n){let e={},t=s(n,["config"]);return t!=null&&Md(t,e),e}f(Ld,"listCachedContentsParametersToMldev");function kd(n){let e={},t=s(n,["config"]);return t!=null&&Dd(t,e),e}f(kd,"listCachedContentsParametersToVertex");function Ud(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&a(e,["nextPageToken"],o);let i=s(n,["cachedContents"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(l=>l)),a(e,["cachedContents"],r)}return e}f(Ud,"listCachedContentsResponseFromMldev");function Fd(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&a(e,["nextPageToken"],o);let i=s(n,["cachedContents"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(l=>l)),a(e,["cachedContents"],r)}return e}f(Fd,"listCachedContentsResponseFromVertex");function Hd(n){let e={},t=s(n,["mediaResolution"]);t!=null&&a(e,["mediaResolution"],t);let o=s(n,["codeExecutionResult"]);o!=null&&a(e,["codeExecutionResult"],o);let i=s(n,["executableCode"]);i!=null&&a(e,["executableCode"],i);let r=s(n,["fileData"]);r!=null&&a(e,["fileData"],Sd(r));let l=s(n,["functionCall"]);l!=null&&a(e,["functionCall"],Ad(l));let c=s(n,["functionResponse"]);c!=null&&a(e,["functionResponse"],c);let d=s(n,["inlineData"]);d!=null&&a(e,["inlineData"],bd(d));let u=s(n,["text"]);u!=null&&a(e,["text"],u);let p=s(n,["thought"]);p!=null&&a(e,["thought"],p);let m=s(n,["thoughtSignature"]);m!=null&&a(e,["thoughtSignature"],m);let h=s(n,["videoMetadata"]);return h!=null&&a(e,["videoMetadata"],h),e}f(Hd,"partToMldev$3");function Vd(n){let e={},t=s(n,["functionCallingConfig"]);t!=null&&a(e,["functionCallingConfig"],xd(t));let o=s(n,["retrievalConfig"]);return o!=null&&a(e,["retrievalConfig"],o),e}f(Vd,"toolConfigToMldev$1");function Bd(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let p=t;Array.isArray(p)&&(p=p.map(m=>m)),a(e,["functionDeclarations"],p)}if(s(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let o=s(n,["googleSearchRetrieval"]);o!=null&&a(e,["googleSearchRetrieval"],o);let i=s(n,["computerUse"]);i!=null&&a(e,["computerUse"],i);let r=s(n,["fileSearch"]);r!=null&&a(e,["fileSearch"],r);let l=s(n,["codeExecution"]);if(l!=null&&a(e,["codeExecution"],l),s(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=s(n,["googleMaps"]);c!=null&&a(e,["googleMaps"],Rd(c));let d=s(n,["googleSearch"]);d!=null&&a(e,["googleSearch"],Gd(d));let u=s(n,["urlContext"]);return u!=null&&a(e,["urlContext"],u),e}f(Bd,"toolToMldev$3");function qd(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let m=t;Array.isArray(m)&&(m=m.map(h=>Pd(h))),a(e,["functionDeclarations"],m)}let o=s(n,["retrieval"]);o!=null&&a(e,["retrieval"],o);let i=s(n,["googleSearchRetrieval"]);i!=null&&a(e,["googleSearchRetrieval"],i);let r=s(n,["computerUse"]);if(r!=null&&a(e,["computerUse"],r),s(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let l=s(n,["codeExecution"]);l!=null&&a(e,["codeExecution"],l);let c=s(n,["enterpriseWebSearch"]);c!=null&&a(e,["enterpriseWebSearch"],c);let d=s(n,["googleMaps"]);d!=null&&a(e,["googleMaps"],d);let u=s(n,["googleSearch"]);u!=null&&a(e,["googleSearch"],u);let p=s(n,["urlContext"]);return p!=null&&a(e,["urlContext"],p),e}f(qd,"toolToVertex$2");function Od(n,e){let t={},o=s(n,["ttl"]);e!==void 0&&o!=null&&a(e,["ttl"],o);let i=s(n,["expireTime"]);return e!==void 0&&i!=null&&a(e,["expireTime"],i),t}f(Od,"updateCachedContentConfigToMldev");function zd(n,e){let t={},o=s(n,["ttl"]);e!==void 0&&o!=null&&a(e,["ttl"],o);let i=s(n,["expireTime"]);return e!==void 0&&i!=null&&a(e,["expireTime"],i),t}f(zd,"updateCachedContentConfigToVertex");function Jd(n,e){let t={},o=s(e,["name"]);o!=null&&a(t,["_url","name"],Me(n,o));let i=s(e,["config"]);return i!=null&&Od(i,t),t}f(Jd,"updateCachedContentParametersToMldev");function Wd(n,e){let t={},o=s(e,["name"]);o!=null&&a(t,["_url","name"],Me(n,o));let i=s(e,["config"]);return i!=null&&zd(i,t),t}f(Wd,"updateCachedContentParametersToVertex");var Vo=class extends we{static{f(this,"Caches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Ge(Re.PAGED_ITEM_CACHED_CONTENTS,o=>this.listInternal(o),await this.listInternal(t),t)}async create(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=vd(this.apiClient,e);return c=_("cachedContents",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),l.then(p=>p)}else{let u=Id(this.apiClient,e);return c=_("cachedContents",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),l.then(p=>p)}}async get(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=$d(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),l.then(p=>p)}else{let u=Nd(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),l.then(p=>p)}}async delete(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=Td(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=Cd(p),h=new fn;return Object.assign(h,m),h})}else{let u=wd(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=_d(p),h=new fn;return Object.assign(h,m),h})}}async update(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=Wd(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),l.then(p=>p)}else{let u=Jd(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),l.then(p=>p)}}async listInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=kd(e);return c=_("cachedContents",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=Fd(p),h=new pn;return Object.assign(h,m),h})}else{let u=Ld(e);return c=_("cachedContents",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=Ud(p),h=new pn;return Object.assign(h,m),h})}}};function gn(n,e){var t={};for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,o=Object.getOwnPropertySymbols(n);i<o.length;i++)e.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(n,o[i])&&(t[o[i]]=n[o[i]]);return t}f(gn,"__rest");function ta(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],o=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:f(function(){return n&&o>=n.length&&(n=void 0),{value:n&&n[o++],done:!n}},"next")};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}f(ta,"__values");function $(n){return this instanceof $?(this.v=n,this):new $(n)}f($,"__await");function Ie(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=t.apply(n,e||[]),i,r=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",l),i[Symbol.asyncIterator]=function(){return this},i;function l(g){return function(b){return Promise.resolve(b).then(g,m)}}function c(g,b){o[g]&&(i[g]=function(E){return new Promise(function(I,v){r.push([g,E,I,v])>1||d(g,E)})},b&&(i[g]=b(i[g])))}function d(g,b){try{u(o[g](b))}catch(E){h(r[0][3],E)}}function u(g){g.value instanceof $?Promise.resolve(g.value.v).then(p,m):h(r[0][2],g)}function p(g){d("next",g)}function m(g){d("throw",g)}function h(g,b){g(b),r.shift(),r.length&&d(r[0][0],r[0][1])}}f(Ie,"__asyncGenerator");function ve(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof ta=="function"?ta(n):n[Symbol.iterator](),t={},o("next"),o("throw"),o("return"),t[Symbol.asyncIterator]=function(){return this},t);function o(r){t[r]=n[r]&&function(l){return new Promise(function(c,d){l=n[r](l),i(c,d,l.done,l.value)})}}function i(r,l,c,d){Promise.resolve(d).then(function(u){r({value:u,done:c})},l)}}f(ve,"__asyncValues");function Kd(n){var e;if(n.candidates==null||n.candidates.length===0)return!1;let t=(e=n.candidates[0])===null||e===void 0?void 0:e.content;return t===void 0?!1:Da(t)}f(Kd,"isValidResponse");function Da(n){if(n.parts===void 0||n.parts.length===0)return!1;for(let e of n.parts)if(e===void 0||Object.keys(e).length===0)return!1;return!0}f(Da,"isValidContent");function Xd(n){if(n.length!==0){for(let e of n)if(e.role!=="user"&&e.role!=="model")throw new Error(`Role must be user or model, but got ${e.role}.`)}}f(Xd,"validateHistory");function na(n){if(n===void 0||n.length===0)return[];let e=[],t=n.length,o=0;for(;o<t;)if(n[o].role==="user")e.push(n[o]),o++;else{let i=[],r=!0;for(;o<t&&n[o].role==="model";)i.push(n[o]),r&&!Da(n[o])&&(r=!1),o++;r?e.push(...i):e.pop()}return e}f(na,"extractCuratedHistory");var Bo=class{static{f(this,"Chats")}constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new qo(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},qo=class{static{f(this,"Chat")}constructor(e,t,o,i={},r=[]){this.apiClient=e,this.modelsModule=t,this.model=o,this.config=i,this.history=r,this.sendPromise=Promise.resolve(),Xd(r)}async sendMessage(e){var t;await this.sendPromise;let o=ie(e.message),i=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(o),config:(t=e.config)!==null&&t!==void 0?t:this.config});return this.sendPromise=(async()=>{var r,l,c;let d=await i,u=(l=(r=d.candidates)===null||r===void 0?void 0:r[0])===null||l===void 0?void 0:l.content,p=d.automaticFunctionCallingHistory,m=this.getHistory(!0).length,h=[];p!=null&&(h=(c=p.slice(m))!==null&&c!==void 0?c:[]);let g=u?[u]:[];this.recordHistory(o,g,h)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),i}async sendMessageStream(e){var t;await this.sendPromise;let o=ie(e.message),i=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(o),config:(t=e.config)!==null&&t!==void 0?t:this.config});this.sendPromise=i.then(()=>{}).catch(()=>{});let r=await i;return this.processStreamResponse(r,o)}getHistory(e=!1){let t=e?na(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return Ie(this,arguments,f(function*(){var i,r,l,c,d,u;let p=[];try{for(var m=!0,h=ve(e),g;g=yield $(h.next()),i=g.done,!i;m=!0){c=g.value,m=!1;let b=c;if(Kd(b)){let E=(u=(d=b.candidates)===null||d===void 0?void 0:d[0])===null||u===void 0?void 0:u.content;E!==void 0&&p.push(E)}yield yield $(b)}}catch(b){r={error:b}}finally{try{!m&&!i&&(l=h.return)&&(yield $(l.call(h)))}finally{if(r)throw r.error}}this.recordHistory(t,p)},"processStreamResponse_1"))}recordHistory(e,t,o){let i=[];t.length>0&&t.every(r=>r.role!==void 0)?i=t:i.push({role:"model",parts:[]}),o&&o.length>0?this.history.push(...na(o)):this.history.push(e),this.history.push(...i)}};var bn=class n extends Error{static{f(this,"ApiError")}constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,n.prototype)}};function Yd(n){let e={},t=s(n,["file"]);return t!=null&&a(e,["file"],t),e}f(Yd,"createFileParametersToMldev");function Qd(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&a(e,["sdkHttpResponse"],t),e}f(Qd,"createFileResponseFromMldev");function Zd(n){let e={},t=s(n,["name"]);return t!=null&&a(e,["_url","file"],xa(t)),e}f(Zd,"deleteFileParametersToMldev");function jd(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&a(e,["sdkHttpResponse"],t),e}f(jd,"deleteFileResponseFromMldev");function eu(n){let e={},t=s(n,["name"]);return t!=null&&a(e,["_url","file"],xa(t)),e}f(eu,"getFileParametersToMldev");function tu(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&a(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);return e!==void 0&&i!=null&&a(e,["_query","pageToken"],i),t}f(tu,"listFilesConfigToMldev");function nu(n){let e={},t=s(n,["config"]);return t!=null&&tu(t,e),e}f(nu,"listFilesParametersToMldev");function ou(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&a(e,["nextPageToken"],o);let i=s(n,["files"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(l=>l)),a(e,["files"],r)}return e}f(ou,"listFilesResponseFromMldev");var Oo=class extends we{static{f(this,"Files")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Ge(Re.PAGED_ITEM_FILES,o=>this.listInternal(o),await this.listInternal(t),t)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(t=>t)}async download(e){await this.apiClient.downloadFile(e)}async listInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=nu(e);return r=_("files",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>{let u=ou(d),p=new Ro;return Object.assign(p,u),p})}}async createInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Yd(e);return r=_("upload/v1beta/files",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=Qd(d),p=new Go;return Object.assign(p,u),p})}}async get(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=eu(e);return r=_("files/{file}",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>d)}}async delete(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Zd(e);return r=_("files/{file}",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>{let u=jd(d),p=new Mo;return Object.assign(p,u),p})}}};function en(n){let e={},t=s(n,["data"]);if(t!=null&&a(e,["data"],t),s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(en,"blobToMldev$2");function iu(n){let e={},t=s(n,["parts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(r=>Iu(r))),a(e,["parts"],i)}let o=s(n,["role"]);return o!=null&&a(e,["role"],o),e}f(iu,"contentToMldev$2");function ru(n){let e={};if(s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=s(n,["fileUri"]);t!=null&&a(e,["fileUri"],t);let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(ru,"fileDataToMldev$2");function su(n){let e={},t=s(n,["id"]);t!=null&&a(e,["id"],t);let o=s(n,["args"]);o!=null&&a(e,["args"],o);let i=s(n,["name"]);if(i!=null&&a(e,["name"],i),s(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(s(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}f(su,"functionCallToMldev$2");function au(n){let e={};if(s(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=s(n,["description"]);t!=null&&a(e,["description"],t);let o=s(n,["name"]);o!=null&&a(e,["name"],o);let i=s(n,["parameters"]);i!=null&&a(e,["parameters"],i);let r=s(n,["parametersJsonSchema"]);r!=null&&a(e,["parametersJsonSchema"],r);let l=s(n,["response"]);l!=null&&a(e,["response"],l);let c=s(n,["responseJsonSchema"]);return c!=null&&a(e,["responseJsonSchema"],c),e}f(au,"functionDeclarationToVertex$1");function lu(n){let e={},t=s(n,["modelSelectionConfig"]);t!=null&&a(e,["modelConfig"],t);let o=s(n,["responseJsonSchema"]);o!=null&&a(e,["responseJsonSchema"],o);let i=s(n,["audioTimestamp"]);i!=null&&a(e,["audioTimestamp"],i);let r=s(n,["candidateCount"]);r!=null&&a(e,["candidateCount"],r);let l=s(n,["enableAffectiveDialog"]);l!=null&&a(e,["enableAffectiveDialog"],l);let c=s(n,["frequencyPenalty"]);c!=null&&a(e,["frequencyPenalty"],c);let d=s(n,["logprobs"]);d!=null&&a(e,["logprobs"],d);let u=s(n,["maxOutputTokens"]);u!=null&&a(e,["maxOutputTokens"],u);let p=s(n,["mediaResolution"]);p!=null&&a(e,["mediaResolution"],p);let m=s(n,["presencePenalty"]);m!=null&&a(e,["presencePenalty"],m);let h=s(n,["responseLogprobs"]);h!=null&&a(e,["responseLogprobs"],h);let g=s(n,["responseMimeType"]);g!=null&&a(e,["responseMimeType"],g);let b=s(n,["responseModalities"]);b!=null&&a(e,["responseModalities"],b);let E=s(n,["responseSchema"]);E!=null&&a(e,["responseSchema"],E);let I=s(n,["routingConfig"]);I!=null&&a(e,["routingConfig"],I);let v=s(n,["seed"]);v!=null&&a(e,["seed"],v);let w=s(n,["speechConfig"]);w!=null&&a(e,["speechConfig"],La(w));let T=s(n,["stopSequences"]);T!=null&&a(e,["stopSequences"],T);let C=s(n,["temperature"]);C!=null&&a(e,["temperature"],C);let A=s(n,["thinkingConfig"]);A!=null&&a(e,["thinkingConfig"],A);let G=s(n,["topK"]);G!=null&&a(e,["topK"],G);let N=s(n,["topP"]);if(N!=null&&a(e,["topP"],N),s(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}f(lu,"generationConfigToVertex$1");function cu(n){let e={};if(s(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=s(n,["enableWidget"]);return t!=null&&a(e,["enableWidget"],t),e}f(cu,"googleMapsToMldev$2");function du(n){let e={};if(s(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(s(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=s(n,["timeRangeFilter"]);return t!=null&&a(e,["timeRangeFilter"],t),e}f(du,"googleSearchToMldev$2");function uu(n,e){let t={},o=s(n,["generationConfig"]);e!==void 0&&o!=null&&a(e,["setup","generationConfig"],o);let i=s(n,["responseModalities"]);e!==void 0&&i!=null&&a(e,["setup","generationConfig","responseModalities"],i);let r=s(n,["temperature"]);e!==void 0&&r!=null&&a(e,["setup","generationConfig","temperature"],r);let l=s(n,["topP"]);e!==void 0&&l!=null&&a(e,["setup","generationConfig","topP"],l);let c=s(n,["topK"]);e!==void 0&&c!=null&&a(e,["setup","generationConfig","topK"],c);let d=s(n,["maxOutputTokens"]);e!==void 0&&d!=null&&a(e,["setup","generationConfig","maxOutputTokens"],d);let u=s(n,["mediaResolution"]);e!==void 0&&u!=null&&a(e,["setup","generationConfig","mediaResolution"],u);let p=s(n,["seed"]);e!==void 0&&p!=null&&a(e,["setup","generationConfig","seed"],p);let m=s(n,["speechConfig"]);e!==void 0&&m!=null&&a(e,["setup","generationConfig","speechConfig"],Ti(m));let h=s(n,["thinkingConfig"]);e!==void 0&&h!=null&&a(e,["setup","generationConfig","thinkingConfig"],h);let g=s(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&a(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=s(n,["systemInstruction"]);e!==void 0&&b!=null&&a(e,["setup","systemInstruction"],iu(ie(b)));let E=s(n,["tools"]);if(e!==void 0&&E!=null){let G=gt(E);Array.isArray(G)&&(G=G.map(N=>wu(ht(N)))),a(e,["setup","tools"],G)}let I=s(n,["sessionResumption"]);e!==void 0&&I!=null&&a(e,["setup","sessionResumption"],vu(I));let v=s(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&a(e,["setup","inputAudioTranscription"],v);let w=s(n,["outputAudioTranscription"]);e!==void 0&&w!=null&&a(e,["setup","outputAudioTranscription"],w);let T=s(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&a(e,["setup","realtimeInputConfig"],T);let C=s(n,["contextWindowCompression"]);e!==void 0&&C!=null&&a(e,["setup","contextWindowCompression"],C);let A=s(n,["proactivity"]);if(e!==void 0&&A!=null&&a(e,["setup","proactivity"],A),s(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}f(uu,"liveConnectConfigToMldev$1");function fu(n,e){let t={},o=s(n,["generationConfig"]);e!==void 0&&o!=null&&a(e,["setup","generationConfig"],lu(o));let i=s(n,["responseModalities"]);e!==void 0&&i!=null&&a(e,["setup","generationConfig","responseModalities"],i);let r=s(n,["temperature"]);e!==void 0&&r!=null&&a(e,["setup","generationConfig","temperature"],r);let l=s(n,["topP"]);e!==void 0&&l!=null&&a(e,["setup","generationConfig","topP"],l);let c=s(n,["topK"]);e!==void 0&&c!=null&&a(e,["setup","generationConfig","topK"],c);let d=s(n,["maxOutputTokens"]);e!==void 0&&d!=null&&a(e,["setup","generationConfig","maxOutputTokens"],d);let u=s(n,["mediaResolution"]);e!==void 0&&u!=null&&a(e,["setup","generationConfig","mediaResolution"],u);let p=s(n,["seed"]);e!==void 0&&p!=null&&a(e,["setup","generationConfig","seed"],p);let m=s(n,["speechConfig"]);e!==void 0&&m!=null&&a(e,["setup","generationConfig","speechConfig"],La(Ti(m)));let h=s(n,["thinkingConfig"]);e!==void 0&&h!=null&&a(e,["setup","generationConfig","thinkingConfig"],h);let g=s(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&a(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=s(n,["systemInstruction"]);e!==void 0&&b!=null&&a(e,["setup","systemInstruction"],ie(b));let E=s(n,["tools"]);if(e!==void 0&&E!=null){let N=gt(E);Array.isArray(N)&&(N=N.map(H=>Tu(ht(H)))),a(e,["setup","tools"],N)}let I=s(n,["sessionResumption"]);e!==void 0&&I!=null&&a(e,["setup","sessionResumption"],I);let v=s(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&a(e,["setup","inputAudioTranscription"],v);let w=s(n,["outputAudioTranscription"]);e!==void 0&&w!=null&&a(e,["setup","outputAudioTranscription"],w);let T=s(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&a(e,["setup","realtimeInputConfig"],T);let C=s(n,["contextWindowCompression"]);e!==void 0&&C!=null&&a(e,["setup","contextWindowCompression"],C);let A=s(n,["proactivity"]);e!==void 0&&A!=null&&a(e,["setup","proactivity"],A);let G=s(n,["explicitVadSignal"]);return e!==void 0&&G!=null&&a(e,["setup","explicitVadSignal"],G),t}f(fu,"liveConnectConfigToVertex");function pu(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["setup","model"],L(n,o));let i=s(e,["config"]);return i!=null&&a(t,["config"],uu(i,t)),t}f(pu,"liveConnectParametersToMldev");function mu(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["setup","model"],L(n,o));let i=s(e,["config"]);return i!=null&&a(t,["config"],fu(i,t)),t}f(mu,"liveConnectParametersToVertex");function hu(n){let e={},t=s(n,["musicGenerationConfig"]);return t!=null&&a(e,["musicGenerationConfig"],t),e}f(hu,"liveMusicSetConfigParametersToMldev");function gu(n){let e={},t=s(n,["weightedPrompts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(i=>i)),a(e,["weightedPrompts"],o)}return e}f(gu,"liveMusicSetWeightedPromptsParametersToMldev");function bu(n){let e={},t=s(n,["media"]);if(t!=null){let u=Ta(t);Array.isArray(u)&&(u=u.map(p=>en(p))),a(e,["mediaChunks"],u)}let o=s(n,["audio"]);o!=null&&a(e,["audio"],en(Ca(o)));let i=s(n,["audioStreamEnd"]);i!=null&&a(e,["audioStreamEnd"],i);let r=s(n,["video"]);r!=null&&a(e,["video"],en(_a(r)));let l=s(n,["text"]);l!=null&&a(e,["text"],l);let c=s(n,["activityStart"]);c!=null&&a(e,["activityStart"],c);let d=s(n,["activityEnd"]);return d!=null&&a(e,["activityEnd"],d),e}f(bu,"liveSendRealtimeInputParametersToMldev");function yu(n){let e={},t=s(n,["media"]);if(t!=null){let u=Ta(t);Array.isArray(u)&&(u=u.map(p=>p)),a(e,["mediaChunks"],u)}let o=s(n,["audio"]);o!=null&&a(e,["audio"],Ca(o));let i=s(n,["audioStreamEnd"]);i!=null&&a(e,["audioStreamEnd"],i);let r=s(n,["video"]);r!=null&&a(e,["video"],_a(r));let l=s(n,["text"]);l!=null&&a(e,["text"],l);let c=s(n,["activityStart"]);c!=null&&a(e,["activityStart"],c);let d=s(n,["activityEnd"]);return d!=null&&a(e,["activityEnd"],d),e}f(yu,"liveSendRealtimeInputParametersToVertex");function Eu(n){let e={},t=s(n,["setupComplete"]);t!=null&&a(e,["setupComplete"],t);let o=s(n,["serverContent"]);o!=null&&a(e,["serverContent"],o);let i=s(n,["toolCall"]);i!=null&&a(e,["toolCall"],i);let r=s(n,["toolCallCancellation"]);r!=null&&a(e,["toolCallCancellation"],r);let l=s(n,["usageMetadata"]);l!=null&&a(e,["usageMetadata"],_u(l));let c=s(n,["goAway"]);c!=null&&a(e,["goAway"],c);let d=s(n,["sessionResumptionUpdate"]);d!=null&&a(e,["sessionResumptionUpdate"],d);let u=s(n,["voiceActivityDetectionSignal"]);return u!=null&&a(e,["voiceActivityDetectionSignal"],u),e}f(Eu,"liveServerMessageFromVertex");function Iu(n){let e={},t=s(n,["mediaResolution"]);t!=null&&a(e,["mediaResolution"],t);let o=s(n,["codeExecutionResult"]);o!=null&&a(e,["codeExecutionResult"],o);let i=s(n,["executableCode"]);i!=null&&a(e,["executableCode"],i);let r=s(n,["fileData"]);r!=null&&a(e,["fileData"],ru(r));let l=s(n,["functionCall"]);l!=null&&a(e,["functionCall"],su(l));let c=s(n,["functionResponse"]);c!=null&&a(e,["functionResponse"],c);let d=s(n,["inlineData"]);d!=null&&a(e,["inlineData"],en(d));let u=s(n,["text"]);u!=null&&a(e,["text"],u);let p=s(n,["thought"]);p!=null&&a(e,["thought"],p);let m=s(n,["thoughtSignature"]);m!=null&&a(e,["thoughtSignature"],m);let h=s(n,["videoMetadata"]);return h!=null&&a(e,["videoMetadata"],h),e}f(Iu,"partToMldev$2");function vu(n){let e={},t=s(n,["handle"]);if(t!=null&&a(e,["handle"],t),s(n,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}f(vu,"sessionResumptionConfigToMldev$1");function La(n){let e={},t=s(n,["voiceConfig"]);t!=null&&a(e,["voiceConfig"],t);let o=s(n,["languageCode"]);if(o!=null&&a(e,["languageCode"],o),s(n,["multiSpeakerVoiceConfig"])!==void 0)throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");return e}f(La,"speechConfigToVertex$1");function wu(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let p=t;Array.isArray(p)&&(p=p.map(m=>m)),a(e,["functionDeclarations"],p)}if(s(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let o=s(n,["googleSearchRetrieval"]);o!=null&&a(e,["googleSearchRetrieval"],o);let i=s(n,["computerUse"]);i!=null&&a(e,["computerUse"],i);let r=s(n,["fileSearch"]);r!=null&&a(e,["fileSearch"],r);let l=s(n,["codeExecution"]);if(l!=null&&a(e,["codeExecution"],l),s(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=s(n,["googleMaps"]);c!=null&&a(e,["googleMaps"],cu(c));let d=s(n,["googleSearch"]);d!=null&&a(e,["googleSearch"],du(d));let u=s(n,["urlContext"]);return u!=null&&a(e,["urlContext"],u),e}f(wu,"toolToMldev$2");function Tu(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let m=t;Array.isArray(m)&&(m=m.map(h=>au(h))),a(e,["functionDeclarations"],m)}let o=s(n,["retrieval"]);o!=null&&a(e,["retrieval"],o);let i=s(n,["googleSearchRetrieval"]);i!=null&&a(e,["googleSearchRetrieval"],i);let r=s(n,["computerUse"]);if(r!=null&&a(e,["computerUse"],r),s(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let l=s(n,["codeExecution"]);l!=null&&a(e,["codeExecution"],l);let c=s(n,["enterpriseWebSearch"]);c!=null&&a(e,["enterpriseWebSearch"],c);let d=s(n,["googleMaps"]);d!=null&&a(e,["googleMaps"],d);let u=s(n,["googleSearch"]);u!=null&&a(e,["googleSearch"],u);let p=s(n,["urlContext"]);return p!=null&&a(e,["urlContext"],p),e}f(Tu,"toolToVertex$1");function _u(n){let e={},t=s(n,["promptTokenCount"]);t!=null&&a(e,["promptTokenCount"],t);let o=s(n,["cachedContentTokenCount"]);o!=null&&a(e,["cachedContentTokenCount"],o);let i=s(n,["candidatesTokenCount"]);i!=null&&a(e,["responseTokenCount"],i);let r=s(n,["toolUsePromptTokenCount"]);r!=null&&a(e,["toolUsePromptTokenCount"],r);let l=s(n,["thoughtsTokenCount"]);l!=null&&a(e,["thoughtsTokenCount"],l);let c=s(n,["totalTokenCount"]);c!=null&&a(e,["totalTokenCount"],c);let d=s(n,["promptTokensDetails"]);if(d!=null){let g=d;Array.isArray(g)&&(g=g.map(b=>b)),a(e,["promptTokensDetails"],g)}let u=s(n,["cacheTokensDetails"]);if(u!=null){let g=u;Array.isArray(g)&&(g=g.map(b=>b)),a(e,["cacheTokensDetails"],g)}let p=s(n,["candidatesTokensDetails"]);if(p!=null){let g=p;Array.isArray(g)&&(g=g.map(b=>b)),a(e,["responseTokensDetails"],g)}let m=s(n,["toolUsePromptTokensDetails"]);if(m!=null){let g=m;Array.isArray(g)&&(g=g.map(b=>b)),a(e,["toolUsePromptTokensDetails"],g)}let h=s(n,["trafficType"]);return h!=null&&a(e,["trafficType"],h),e}f(_u,"usageMetadataFromVertex");function Cu(n){let e={},t=s(n,["data"]);if(t!=null&&a(e,["data"],t),s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(Cu,"blobToMldev$1");function Su(n){let e={},t=s(n,["content"]);t!=null&&a(e,["content"],t);let o=s(n,["citationMetadata"]);o!=null&&a(e,["citationMetadata"],Au(o));let i=s(n,["tokenCount"]);i!=null&&a(e,["tokenCount"],i);let r=s(n,["finishReason"]);r!=null&&a(e,["finishReason"],r);let l=s(n,["avgLogprobs"]);l!=null&&a(e,["avgLogprobs"],l);let c=s(n,["groundingMetadata"]);c!=null&&a(e,["groundingMetadata"],c);let d=s(n,["index"]);d!=null&&a(e,["index"],d);let u=s(n,["logprobsResult"]);u!=null&&a(e,["logprobsResult"],u);let p=s(n,["safetyRatings"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(g=>g)),a(e,["safetyRatings"],h)}let m=s(n,["urlContextMetadata"]);return m!=null&&a(e,["urlContextMetadata"],m),e}f(Su,"candidateFromMldev");function Au(n){let e={},t=s(n,["citationSources"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(i=>i)),a(e,["citations"],o)}return e}f(Au,"citationMetadataFromMldev");function xu(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["contents"]);if(i!=null){let r=he(i);Array.isArray(r)&&(r=r.map(l=>l)),a(t,["contents"],r)}return t}f(xu,"computeTokensParametersToVertex");function Pu(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["tokensInfo"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>r)),a(e,["tokensInfo"],i)}return e}f(Pu,"computeTokensResponseFromVertex");function Nu(n){let e={},t=s(n,["values"]);t!=null&&a(e,["values"],t);let o=s(n,["statistics"]);return o!=null&&a(e,["statistics"],$u(o)),e}f(Nu,"contentEmbeddingFromVertex");function $u(n){let e={},t=s(n,["truncated"]);t!=null&&a(e,["truncated"],t);let o=s(n,["token_count"]);return o!=null&&a(e,["tokenCount"],o),e}f($u,"contentEmbeddingStatisticsFromVertex");function Gn(n){let e={},t=s(n,["parts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(r=>Vf(r))),a(e,["parts"],i)}let o=s(n,["role"]);return o!=null&&a(e,["role"],o),e}f(Gn,"contentToMldev$1");function Ru(n){let e={},t=s(n,["controlType"]);t!=null&&a(e,["controlType"],t);let o=s(n,["enableControlImageComputation"]);return o!=null&&a(e,["computeControl"],o),e}f(Ru,"controlReferenceConfigToVertex");function Gu(n){let e={};if(s(n,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is not supported in Gemini API.");if(s(n,["tools"])!==void 0)throw new Error("tools parameter is not supported in Gemini API.");if(s(n,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is not supported in Gemini API.");return e}f(Gu,"countTokensConfigToMldev");function Mu(n,e){let t={},o=s(n,["systemInstruction"]);e!==void 0&&o!=null&&a(e,["systemInstruction"],ie(o));let i=s(n,["tools"]);if(e!==void 0&&i!=null){let l=i;Array.isArray(l)&&(l=l.map(c=>Va(c))),a(e,["tools"],l)}let r=s(n,["generationConfig"]);return e!==void 0&&r!=null&&a(e,["generationConfig"],Sf(r)),t}f(Mu,"countTokensConfigToVertex");function Du(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["contents"]);if(i!=null){let l=he(i);Array.isArray(l)&&(l=l.map(c=>Gn(c))),a(t,["contents"],l)}let r=s(e,["config"]);return r!=null&&Gu(r),t}f(Du,"countTokensParametersToMldev");function Lu(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["contents"]);if(i!=null){let l=he(i);Array.isArray(l)&&(l=l.map(c=>c)),a(t,["contents"],l)}let r=s(e,["config"]);return r!=null&&Mu(r,t),t}f(Lu,"countTokensParametersToVertex");function ku(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["totalTokens"]);o!=null&&a(e,["totalTokens"],o);let i=s(n,["cachedContentTokenCount"]);return i!=null&&a(e,["cachedContentTokenCount"],i),e}f(ku,"countTokensResponseFromMldev");function Uu(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["totalTokens"]);return o!=null&&a(e,["totalTokens"],o),e}f(Uu,"countTokensResponseFromVertex");function Fu(n,e){let t={},o=s(e,["model"]);return o!=null&&a(t,["_url","name"],L(n,o)),t}f(Fu,"deleteModelParametersToMldev");function Hu(n,e){let t={},o=s(e,["model"]);return o!=null&&a(t,["_url","name"],L(n,o)),t}f(Hu,"deleteModelParametersToVertex");function Vu(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&a(e,["sdkHttpResponse"],t),e}f(Vu,"deleteModelResponseFromMldev");function Bu(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&a(e,["sdkHttpResponse"],t),e}f(Bu,"deleteModelResponseFromVertex");function qu(n,e){let t={},o=s(n,["outputGcsUri"]);e!==void 0&&o!=null&&a(e,["parameters","storageUri"],o);let i=s(n,["negativePrompt"]);e!==void 0&&i!=null&&a(e,["parameters","negativePrompt"],i);let r=s(n,["numberOfImages"]);e!==void 0&&r!=null&&a(e,["parameters","sampleCount"],r);let l=s(n,["aspectRatio"]);e!==void 0&&l!=null&&a(e,["parameters","aspectRatio"],l);let c=s(n,["guidanceScale"]);e!==void 0&&c!=null&&a(e,["parameters","guidanceScale"],c);let d=s(n,["seed"]);e!==void 0&&d!=null&&a(e,["parameters","seed"],d);let u=s(n,["safetyFilterLevel"]);e!==void 0&&u!=null&&a(e,["parameters","safetySetting"],u);let p=s(n,["personGeneration"]);e!==void 0&&p!=null&&a(e,["parameters","personGeneration"],p);let m=s(n,["includeSafetyAttributes"]);e!==void 0&&m!=null&&a(e,["parameters","includeSafetyAttributes"],m);let h=s(n,["includeRaiReason"]);e!==void 0&&h!=null&&a(e,["parameters","includeRaiReason"],h);let g=s(n,["language"]);e!==void 0&&g!=null&&a(e,["parameters","language"],g);let b=s(n,["outputMimeType"]);e!==void 0&&b!=null&&a(e,["parameters","outputOptions","mimeType"],b);let E=s(n,["outputCompressionQuality"]);e!==void 0&&E!=null&&a(e,["parameters","outputOptions","compressionQuality"],E);let I=s(n,["addWatermark"]);e!==void 0&&I!=null&&a(e,["parameters","addWatermark"],I);let v=s(n,["labels"]);e!==void 0&&v!=null&&a(e,["labels"],v);let w=s(n,["editMode"]);e!==void 0&&w!=null&&a(e,["parameters","editMode"],w);let T=s(n,["baseSteps"]);return e!==void 0&&T!=null&&a(e,["parameters","editConfig","baseSteps"],T),t}f(qu,"editImageConfigToVertex");function Ou(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["prompt"]);i!=null&&a(t,["instances[0]","prompt"],i);let r=s(e,["referenceImages"]);if(r!=null){let c=r;Array.isArray(c)&&(c=c.map(d=>Wf(d))),a(t,["instances[0]","referenceImages"],c)}let l=s(e,["config"]);return l!=null&&qu(l,t),t}f(Ou,"editImageParametersInternalToVertex");function zu(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>Mn(r))),a(e,["generatedImages"],i)}return e}f(zu,"editImageResponseFromVertex");function Ju(n,e){let t={},o=s(n,["taskType"]);e!==void 0&&o!=null&&a(e,["requests[]","taskType"],o);let i=s(n,["title"]);e!==void 0&&i!=null&&a(e,["requests[]","title"],i);let r=s(n,["outputDimensionality"]);if(e!==void 0&&r!=null&&a(e,["requests[]","outputDimensionality"],r),s(n,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(s(n,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return t}f(Ju,"embedContentConfigToMldev");function Wu(n,e){let t={},o=s(n,["taskType"]);e!==void 0&&o!=null&&a(e,["instances[]","task_type"],o);let i=s(n,["title"]);e!==void 0&&i!=null&&a(e,["instances[]","title"],i);let r=s(n,["outputDimensionality"]);e!==void 0&&r!=null&&a(e,["parameters","outputDimensionality"],r);let l=s(n,["mimeType"]);e!==void 0&&l!=null&&a(e,["instances[]","mimeType"],l);let c=s(n,["autoTruncate"]);return e!==void 0&&c!=null&&a(e,["parameters","autoTruncate"],c),t}f(Wu,"embedContentConfigToVertex");function Ku(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["contents"]);if(i!=null){let c=Ii(n,i);Array.isArray(c)&&(c=c.map(d=>d)),a(t,["requests[]","content"],c)}let r=s(e,["config"]);r!=null&&Ju(r,t);let l=s(e,["model"]);return l!==void 0&&a(t,["requests[]","model"],L(n,l)),t}f(Ku,"embedContentParametersToMldev");function Xu(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["contents"]);if(i!=null){let l=Ii(n,i);Array.isArray(l)&&(l=l.map(c=>c)),a(t,["instances[]","content"],l)}let r=s(e,["config"]);return r!=null&&Wu(r,t),t}f(Xu,"embedContentParametersToVertex");function Yu(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["embeddings"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>l)),a(e,["embeddings"],r)}let i=s(n,["metadata"]);return i!=null&&a(e,["metadata"],i),e}f(Yu,"embedContentResponseFromMldev");function Qu(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["predictions[]","embeddings"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>Nu(l))),a(e,["embeddings"],r)}let i=s(n,["metadata"]);return i!=null&&a(e,["metadata"],i),e}f(Qu,"embedContentResponseFromVertex");function Zu(n){let e={},t=s(n,["endpoint"]);t!=null&&a(e,["name"],t);let o=s(n,["deployedModelId"]);return o!=null&&a(e,["deployedModelId"],o),e}f(Zu,"endpointFromVertex");function ju(n){let e={};if(s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=s(n,["fileUri"]);t!=null&&a(e,["fileUri"],t);let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(ju,"fileDataToMldev$1");function ef(n){let e={},t=s(n,["id"]);t!=null&&a(e,["id"],t);let o=s(n,["args"]);o!=null&&a(e,["args"],o);let i=s(n,["name"]);if(i!=null&&a(e,["name"],i),s(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(s(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}f(ef,"functionCallToMldev$1");function tf(n){let e={},t=s(n,["mode"]);t!=null&&a(e,["mode"],t);let o=s(n,["allowedFunctionNames"]);if(o!=null&&a(e,["allowedFunctionNames"],o),s(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}f(tf,"functionCallingConfigToMldev");function nf(n){let e={};if(s(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=s(n,["description"]);t!=null&&a(e,["description"],t);let o=s(n,["name"]);o!=null&&a(e,["name"],o);let i=s(n,["parameters"]);i!=null&&a(e,["parameters"],i);let r=s(n,["parametersJsonSchema"]);r!=null&&a(e,["parametersJsonSchema"],r);let l=s(n,["response"]);l!=null&&a(e,["response"],l);let c=s(n,["responseJsonSchema"]);return c!=null&&a(e,["responseJsonSchema"],c),e}f(nf,"functionDeclarationToVertex");function of(n,e,t){let o={},i=s(e,["systemInstruction"]);t!==void 0&&i!=null&&a(t,["systemInstruction"],Gn(ie(i)));let r=s(e,["temperature"]);r!=null&&a(o,["temperature"],r);let l=s(e,["topP"]);l!=null&&a(o,["topP"],l);let c=s(e,["topK"]);c!=null&&a(o,["topK"],c);let d=s(e,["candidateCount"]);d!=null&&a(o,["candidateCount"],d);let u=s(e,["maxOutputTokens"]);u!=null&&a(o,["maxOutputTokens"],u);let p=s(e,["stopSequences"]);p!=null&&a(o,["stopSequences"],p);let m=s(e,["responseLogprobs"]);m!=null&&a(o,["responseLogprobs"],m);let h=s(e,["logprobs"]);h!=null&&a(o,["logprobs"],h);let g=s(e,["presencePenalty"]);g!=null&&a(o,["presencePenalty"],g);let b=s(e,["frequencyPenalty"]);b!=null&&a(o,["frequencyPenalty"],b);let E=s(e,["seed"]);E!=null&&a(o,["seed"],E);let I=s(e,["responseMimeType"]);I!=null&&a(o,["responseMimeType"],I);let v=s(e,["responseSchema"]);v!=null&&a(o,["responseSchema"],vi(v));let w=s(e,["responseJsonSchema"]);if(w!=null&&a(o,["responseJsonSchema"],w),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");let T=s(e,["safetySettings"]);if(t!==void 0&&T!=null){let B=T;Array.isArray(B)&&(B=B.map(_e=>Kf(_e))),a(t,["safetySettings"],B)}let C=s(e,["tools"]);if(t!==void 0&&C!=null){let B=gt(C);Array.isArray(B)&&(B=B.map(_e=>tp(ht(_e)))),a(t,["tools"],B)}let A=s(e,["toolConfig"]);if(t!==void 0&&A!=null&&a(t,["toolConfig"],ep(A)),s(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let G=s(e,["cachedContent"]);t!==void 0&&G!=null&&a(t,["cachedContent"],Me(n,G));let N=s(e,["responseModalities"]);N!=null&&a(o,["responseModalities"],N);let H=s(e,["mediaResolution"]);H!=null&&a(o,["mediaResolution"],H);let x=s(e,["speechConfig"]);if(x!=null&&a(o,["speechConfig"],wi(x)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let D=s(e,["thinkingConfig"]);D!=null&&a(o,["thinkingConfig"],D);let J=s(e,["imageConfig"]);J!=null&&a(o,["imageConfig"],$f(J));let Pe=s(e,["enableEnhancedCivicAnswers"]);return Pe!=null&&a(o,["enableEnhancedCivicAnswers"],Pe),o}f(of,"generateContentConfigToMldev");function rf(n,e,t){let o={},i=s(e,["systemInstruction"]);t!==void 0&&i!=null&&a(t,["systemInstruction"],ie(i));let r=s(e,["temperature"]);r!=null&&a(o,["temperature"],r);let l=s(e,["topP"]);l!=null&&a(o,["topP"],l);let c=s(e,["topK"]);c!=null&&a(o,["topK"],c);let d=s(e,["candidateCount"]);d!=null&&a(o,["candidateCount"],d);let u=s(e,["maxOutputTokens"]);u!=null&&a(o,["maxOutputTokens"],u);let p=s(e,["stopSequences"]);p!=null&&a(o,["stopSequences"],p);let m=s(e,["responseLogprobs"]);m!=null&&a(o,["responseLogprobs"],m);let h=s(e,["logprobs"]);h!=null&&a(o,["logprobs"],h);let g=s(e,["presencePenalty"]);g!=null&&a(o,["presencePenalty"],g);let b=s(e,["frequencyPenalty"]);b!=null&&a(o,["frequencyPenalty"],b);let E=s(e,["seed"]);E!=null&&a(o,["seed"],E);let I=s(e,["responseMimeType"]);I!=null&&a(o,["responseMimeType"],I);let v=s(e,["responseSchema"]);v!=null&&a(o,["responseSchema"],vi(v));let w=s(e,["responseJsonSchema"]);w!=null&&a(o,["responseJsonSchema"],w);let T=s(e,["routingConfig"]);T!=null&&a(o,["routingConfig"],T);let C=s(e,["modelSelectionConfig"]);C!=null&&a(o,["modelConfig"],C);let A=s(e,["safetySettings"]);if(t!==void 0&&A!=null){let Ne=A;Array.isArray(Ne)&&(Ne=Ne.map(Zn=>Zn)),a(t,["safetySettings"],Ne)}let G=s(e,["tools"]);if(t!==void 0&&G!=null){let Ne=gt(G);Array.isArray(Ne)&&(Ne=Ne.map(Zn=>Va(ht(Zn)))),a(t,["tools"],Ne)}let N=s(e,["toolConfig"]);t!==void 0&&N!=null&&a(t,["toolConfig"],N);let H=s(e,["labels"]);t!==void 0&&H!=null&&a(t,["labels"],H);let x=s(e,["cachedContent"]);t!==void 0&&x!=null&&a(t,["cachedContent"],Me(n,x));let D=s(e,["responseModalities"]);D!=null&&a(o,["responseModalities"],D);let J=s(e,["mediaResolution"]);J!=null&&a(o,["mediaResolution"],J);let Pe=s(e,["speechConfig"]);Pe!=null&&a(o,["speechConfig"],Ha(wi(Pe)));let B=s(e,["audioTimestamp"]);B!=null&&a(o,["audioTimestamp"],B);let _e=s(e,["thinkingConfig"]);_e!=null&&a(o,["thinkingConfig"],_e);let Bi=s(e,["imageConfig"]);if(Bi!=null&&a(o,["imageConfig"],Rf(Bi)),s(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return o}f(rf,"generateContentConfigToVertex");function oa(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["contents"]);if(i!=null){let l=he(i);Array.isArray(l)&&(l=l.map(c=>Gn(c))),a(t,["contents"],l)}let r=s(e,["config"]);return r!=null&&a(t,["generationConfig"],of(n,r,t)),t}f(oa,"generateContentParametersToMldev");function ia(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["contents"]);if(i!=null){let l=he(i);Array.isArray(l)&&(l=l.map(c=>c)),a(t,["contents"],l)}let r=s(e,["config"]);return r!=null&&a(t,["generationConfig"],rf(n,r,t)),t}f(ia,"generateContentParametersToVertex");function ra(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["candidates"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(u=>Su(u))),a(e,["candidates"],d)}let i=s(n,["modelVersion"]);i!=null&&a(e,["modelVersion"],i);let r=s(n,["promptFeedback"]);r!=null&&a(e,["promptFeedback"],r);let l=s(n,["responseId"]);l!=null&&a(e,["responseId"],l);let c=s(n,["usageMetadata"]);return c!=null&&a(e,["usageMetadata"],c),e}f(ra,"generateContentResponseFromMldev");function sa(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["candidates"]);if(o!=null){let u=o;Array.isArray(u)&&(u=u.map(p=>p)),a(e,["candidates"],u)}let i=s(n,["createTime"]);i!=null&&a(e,["createTime"],i);let r=s(n,["modelVersion"]);r!=null&&a(e,["modelVersion"],r);let l=s(n,["promptFeedback"]);l!=null&&a(e,["promptFeedback"],l);let c=s(n,["responseId"]);c!=null&&a(e,["responseId"],c);let d=s(n,["usageMetadata"]);return d!=null&&a(e,["usageMetadata"],d),e}f(sa,"generateContentResponseFromVertex");function sf(n,e){let t={};if(s(n,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(s(n,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is not supported in Gemini API.");let o=s(n,["numberOfImages"]);e!==void 0&&o!=null&&a(e,["parameters","sampleCount"],o);let i=s(n,["aspectRatio"]);e!==void 0&&i!=null&&a(e,["parameters","aspectRatio"],i);let r=s(n,["guidanceScale"]);if(e!==void 0&&r!=null&&a(e,["parameters","guidanceScale"],r),s(n,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");let l=s(n,["safetyFilterLevel"]);e!==void 0&&l!=null&&a(e,["parameters","safetySetting"],l);let c=s(n,["personGeneration"]);e!==void 0&&c!=null&&a(e,["parameters","personGeneration"],c);let d=s(n,["includeSafetyAttributes"]);e!==void 0&&d!=null&&a(e,["parameters","includeSafetyAttributes"],d);let u=s(n,["includeRaiReason"]);e!==void 0&&u!=null&&a(e,["parameters","includeRaiReason"],u);let p=s(n,["language"]);e!==void 0&&p!=null&&a(e,["parameters","language"],p);let m=s(n,["outputMimeType"]);e!==void 0&&m!=null&&a(e,["parameters","outputOptions","mimeType"],m);let h=s(n,["outputCompressionQuality"]);if(e!==void 0&&h!=null&&a(e,["parameters","outputOptions","compressionQuality"],h),s(n,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is not supported in Gemini API.");if(s(n,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let g=s(n,["imageSize"]);if(e!==void 0&&g!=null&&a(e,["parameters","sampleImageSize"],g),s(n,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is not supported in Gemini API.");return t}f(sf,"generateImagesConfigToMldev");function af(n,e){let t={},o=s(n,["outputGcsUri"]);e!==void 0&&o!=null&&a(e,["parameters","storageUri"],o);let i=s(n,["negativePrompt"]);e!==void 0&&i!=null&&a(e,["parameters","negativePrompt"],i);let r=s(n,["numberOfImages"]);e!==void 0&&r!=null&&a(e,["parameters","sampleCount"],r);let l=s(n,["aspectRatio"]);e!==void 0&&l!=null&&a(e,["parameters","aspectRatio"],l);let c=s(n,["guidanceScale"]);e!==void 0&&c!=null&&a(e,["parameters","guidanceScale"],c);let d=s(n,["seed"]);e!==void 0&&d!=null&&a(e,["parameters","seed"],d);let u=s(n,["safetyFilterLevel"]);e!==void 0&&u!=null&&a(e,["parameters","safetySetting"],u);let p=s(n,["personGeneration"]);e!==void 0&&p!=null&&a(e,["parameters","personGeneration"],p);let m=s(n,["includeSafetyAttributes"]);e!==void 0&&m!=null&&a(e,["parameters","includeSafetyAttributes"],m);let h=s(n,["includeRaiReason"]);e!==void 0&&h!=null&&a(e,["parameters","includeRaiReason"],h);let g=s(n,["language"]);e!==void 0&&g!=null&&a(e,["parameters","language"],g);let b=s(n,["outputMimeType"]);e!==void 0&&b!=null&&a(e,["parameters","outputOptions","mimeType"],b);let E=s(n,["outputCompressionQuality"]);e!==void 0&&E!=null&&a(e,["parameters","outputOptions","compressionQuality"],E);let I=s(n,["addWatermark"]);e!==void 0&&I!=null&&a(e,["parameters","addWatermark"],I);let v=s(n,["labels"]);e!==void 0&&v!=null&&a(e,["labels"],v);let w=s(n,["imageSize"]);e!==void 0&&w!=null&&a(e,["parameters","sampleImageSize"],w);let T=s(n,["enhancePrompt"]);return e!==void 0&&T!=null&&a(e,["parameters","enhancePrompt"],T),t}f(af,"generateImagesConfigToVertex");function lf(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["prompt"]);i!=null&&a(t,["instances[0]","prompt"],i);let r=s(e,["config"]);return r!=null&&sf(r,t),t}f(lf,"generateImagesParametersToMldev");function cf(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["prompt"]);i!=null&&a(t,["instances[0]","prompt"],i);let r=s(e,["config"]);return r!=null&&af(r,t),t}f(cf,"generateImagesParametersToVertex");function df(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["predictions"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>wf(l))),a(e,["generatedImages"],r)}let i=s(n,["positivePromptSafetyAttributes"]);return i!=null&&a(e,["positivePromptSafetyAttributes"],Ua(i)),e}f(df,"generateImagesResponseFromMldev");function uf(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["predictions"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>Mn(l))),a(e,["generatedImages"],r)}let i=s(n,["positivePromptSafetyAttributes"]);return i!=null&&a(e,["positivePromptSafetyAttributes"],Fa(i)),e}f(uf,"generateImagesResponseFromVertex");function ff(n,e){let t={},o=s(n,["numberOfVideos"]);if(e!==void 0&&o!=null&&a(e,["parameters","sampleCount"],o),s(n,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(s(n,["fps"])!==void 0)throw new Error("fps parameter is not supported in Gemini API.");let i=s(n,["durationSeconds"]);if(e!==void 0&&i!=null&&a(e,["parameters","durationSeconds"],i),s(n,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");let r=s(n,["aspectRatio"]);e!==void 0&&r!=null&&a(e,["parameters","aspectRatio"],r);let l=s(n,["resolution"]);e!==void 0&&l!=null&&a(e,["parameters","resolution"],l);let c=s(n,["personGeneration"]);if(e!==void 0&&c!=null&&a(e,["parameters","personGeneration"],c),s(n,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is not supported in Gemini API.");let d=s(n,["negativePrompt"]);e!==void 0&&d!=null&&a(e,["parameters","negativePrompt"],d);let u=s(n,["enhancePrompt"]);if(e!==void 0&&u!=null&&a(e,["parameters","enhancePrompt"],u),s(n,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is not supported in Gemini API.");let p=s(n,["lastFrame"]);e!==void 0&&p!=null&&a(e,["instances[0]","lastFrame"],Dn(p));let m=s(n,["referenceImages"]);if(e!==void 0&&m!=null){let h=m;Array.isArray(h)&&(h=h.map(g=>mp(g))),a(e,["instances[0]","referenceImages"],h)}if(s(n,["mask"])!==void 0)throw new Error("mask parameter is not supported in Gemini API.");if(s(n,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is not supported in Gemini API.");return t}f(ff,"generateVideosConfigToMldev");function pf(n,e){let t={},o=s(n,["numberOfVideos"]);e!==void 0&&o!=null&&a(e,["parameters","sampleCount"],o);let i=s(n,["outputGcsUri"]);e!==void 0&&i!=null&&a(e,["parameters","storageUri"],i);let r=s(n,["fps"]);e!==void 0&&r!=null&&a(e,["parameters","fps"],r);let l=s(n,["durationSeconds"]);e!==void 0&&l!=null&&a(e,["parameters","durationSeconds"],l);let c=s(n,["seed"]);e!==void 0&&c!=null&&a(e,["parameters","seed"],c);let d=s(n,["aspectRatio"]);e!==void 0&&d!=null&&a(e,["parameters","aspectRatio"],d);let u=s(n,["resolution"]);e!==void 0&&u!=null&&a(e,["parameters","resolution"],u);let p=s(n,["personGeneration"]);e!==void 0&&p!=null&&a(e,["parameters","personGeneration"],p);let m=s(n,["pubsubTopic"]);e!==void 0&&m!=null&&a(e,["parameters","pubsubTopic"],m);let h=s(n,["negativePrompt"]);e!==void 0&&h!=null&&a(e,["parameters","negativePrompt"],h);let g=s(n,["enhancePrompt"]);e!==void 0&&g!=null&&a(e,["parameters","enhancePrompt"],g);let b=s(n,["generateAudio"]);e!==void 0&&b!=null&&a(e,["parameters","generateAudio"],b);let E=s(n,["lastFrame"]);e!==void 0&&E!=null&&a(e,["instances[0]","lastFrame"],Te(E));let I=s(n,["referenceImages"]);if(e!==void 0&&I!=null){let T=I;Array.isArray(T)&&(T=T.map(C=>hp(C))),a(e,["instances[0]","referenceImages"],T)}let v=s(n,["mask"]);e!==void 0&&v!=null&&a(e,["instances[0]","mask"],pp(v));let w=s(n,["compressionQuality"]);return e!==void 0&&w!=null&&a(e,["parameters","compressionQuality"],w),t}f(pf,"generateVideosConfigToVertex");function mf(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["metadata"]);o!=null&&a(e,["metadata"],o);let i=s(n,["done"]);i!=null&&a(e,["done"],i);let r=s(n,["error"]);r!=null&&a(e,["error"],r);let l=s(n,["response","generateVideoResponse"]);return l!=null&&a(e,["response"],yf(l)),e}f(mf,"generateVideosOperationFromMldev");function hf(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["metadata"]);o!=null&&a(e,["metadata"],o);let i=s(n,["done"]);i!=null&&a(e,["done"],i);let r=s(n,["error"]);r!=null&&a(e,["error"],r);let l=s(n,["response"]);return l!=null&&a(e,["response"],Ef(l)),e}f(hf,"generateVideosOperationFromVertex");function gf(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["prompt"]);i!=null&&a(t,["instances[0]","prompt"],i);let r=s(e,["image"]);r!=null&&a(t,["instances[0]","image"],Dn(r));let l=s(e,["video"]);l!=null&&a(t,["instances[0]","video"],Ba(l));let c=s(e,["source"]);c!=null&&If(c,t);let d=s(e,["config"]);return d!=null&&ff(d,t),t}f(gf,"generateVideosParametersToMldev");function bf(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["prompt"]);i!=null&&a(t,["instances[0]","prompt"],i);let r=s(e,["image"]);r!=null&&a(t,["instances[0]","image"],Te(r));let l=s(e,["video"]);l!=null&&a(t,["instances[0]","video"],qa(l));let c=s(e,["source"]);c!=null&&vf(c,t);let d=s(e,["config"]);return d!=null&&pf(d,t),t}f(bf,"generateVideosParametersToVertex");function yf(n){let e={},t=s(n,["generatedSamples"]);if(t!=null){let r=t;Array.isArray(r)&&(r=r.map(l=>_f(l))),a(e,["generatedVideos"],r)}let o=s(n,["raiMediaFilteredCount"]);o!=null&&a(e,["raiMediaFilteredCount"],o);let i=s(n,["raiMediaFilteredReasons"]);return i!=null&&a(e,["raiMediaFilteredReasons"],i),e}f(yf,"generateVideosResponseFromMldev");function Ef(n){let e={},t=s(n,["videos"]);if(t!=null){let r=t;Array.isArray(r)&&(r=r.map(l=>Cf(l))),a(e,["generatedVideos"],r)}let o=s(n,["raiMediaFilteredCount"]);o!=null&&a(e,["raiMediaFilteredCount"],o);let i=s(n,["raiMediaFilteredReasons"]);return i!=null&&a(e,["raiMediaFilteredReasons"],i),e}f(Ef,"generateVideosResponseFromVertex");function If(n,e){let t={},o=s(n,["prompt"]);e!==void 0&&o!=null&&a(e,["instances[0]","prompt"],o);let i=s(n,["image"]);e!==void 0&&i!=null&&a(e,["instances[0]","image"],Dn(i));let r=s(n,["video"]);return e!==void 0&&r!=null&&a(e,["instances[0]","video"],Ba(r)),t}f(If,"generateVideosSourceToMldev");function vf(n,e){let t={},o=s(n,["prompt"]);e!==void 0&&o!=null&&a(e,["instances[0]","prompt"],o);let i=s(n,["image"]);e!==void 0&&i!=null&&a(e,["instances[0]","image"],Te(i));let r=s(n,["video"]);return e!==void 0&&r!=null&&a(e,["instances[0]","video"],qa(r)),t}f(vf,"generateVideosSourceToVertex");function wf(n){let e={},t=s(n,["_self"]);t!=null&&a(e,["image"],Gf(t));let o=s(n,["raiFilteredReason"]);o!=null&&a(e,["raiFilteredReason"],o);let i=s(n,["_self"]);return i!=null&&a(e,["safetyAttributes"],Ua(i)),e}f(wf,"generatedImageFromMldev");function Mn(n){let e={},t=s(n,["_self"]);t!=null&&a(e,["image"],ka(t));let o=s(n,["raiFilteredReason"]);o!=null&&a(e,["raiFilteredReason"],o);let i=s(n,["_self"]);i!=null&&a(e,["safetyAttributes"],Fa(i));let r=s(n,["prompt"]);return r!=null&&a(e,["enhancedPrompt"],r),e}f(Mn,"generatedImageFromVertex");function Tf(n){let e={},t=s(n,["_self"]);t!=null&&a(e,["mask"],ka(t));let o=s(n,["labels"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>r)),a(e,["labels"],i)}return e}f(Tf,"generatedImageMaskFromVertex");function _f(n){let e={},t=s(n,["video"]);return t!=null&&a(e,["video"],up(t)),e}f(_f,"generatedVideoFromMldev");function Cf(n){let e={},t=s(n,["_self"]);return t!=null&&a(e,["video"],fp(t)),e}f(Cf,"generatedVideoFromVertex");function Sf(n){let e={},t=s(n,["modelSelectionConfig"]);t!=null&&a(e,["modelConfig"],t);let o=s(n,["responseJsonSchema"]);o!=null&&a(e,["responseJsonSchema"],o);let i=s(n,["audioTimestamp"]);i!=null&&a(e,["audioTimestamp"],i);let r=s(n,["candidateCount"]);r!=null&&a(e,["candidateCount"],r);let l=s(n,["enableAffectiveDialog"]);l!=null&&a(e,["enableAffectiveDialog"],l);let c=s(n,["frequencyPenalty"]);c!=null&&a(e,["frequencyPenalty"],c);let d=s(n,["logprobs"]);d!=null&&a(e,["logprobs"],d);let u=s(n,["maxOutputTokens"]);u!=null&&a(e,["maxOutputTokens"],u);let p=s(n,["mediaResolution"]);p!=null&&a(e,["mediaResolution"],p);let m=s(n,["presencePenalty"]);m!=null&&a(e,["presencePenalty"],m);let h=s(n,["responseLogprobs"]);h!=null&&a(e,["responseLogprobs"],h);let g=s(n,["responseMimeType"]);g!=null&&a(e,["responseMimeType"],g);let b=s(n,["responseModalities"]);b!=null&&a(e,["responseModalities"],b);let E=s(n,["responseSchema"]);E!=null&&a(e,["responseSchema"],E);let I=s(n,["routingConfig"]);I!=null&&a(e,["routingConfig"],I);let v=s(n,["seed"]);v!=null&&a(e,["seed"],v);let w=s(n,["speechConfig"]);w!=null&&a(e,["speechConfig"],Ha(w));let T=s(n,["stopSequences"]);T!=null&&a(e,["stopSequences"],T);let C=s(n,["temperature"]);C!=null&&a(e,["temperature"],C);let A=s(n,["thinkingConfig"]);A!=null&&a(e,["thinkingConfig"],A);let G=s(n,["topK"]);G!=null&&a(e,["topK"],G);let N=s(n,["topP"]);if(N!=null&&a(e,["topP"],N),s(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}f(Sf,"generationConfigToVertex");function Af(n,e){let t={},o=s(e,["model"]);return o!=null&&a(t,["_url","name"],L(n,o)),t}f(Af,"getModelParametersToMldev");function xf(n,e){let t={},o=s(e,["model"]);return o!=null&&a(t,["_url","name"],L(n,o)),t}f(xf,"getModelParametersToVertex");function Pf(n){let e={};if(s(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=s(n,["enableWidget"]);return t!=null&&a(e,["enableWidget"],t),e}f(Pf,"googleMapsToMldev$1");function Nf(n){let e={};if(s(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(s(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=s(n,["timeRangeFilter"]);return t!=null&&a(e,["timeRangeFilter"],t),e}f(Nf,"googleSearchToMldev$1");function $f(n){let e={},t=s(n,["aspectRatio"]);t!=null&&a(e,["aspectRatio"],t);let o=s(n,["imageSize"]);if(o!=null&&a(e,["imageSize"],o),s(n,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(s(n,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}f($f,"imageConfigToMldev");function Rf(n){let e={},t=s(n,["aspectRatio"]);t!=null&&a(e,["aspectRatio"],t);let o=s(n,["imageSize"]);o!=null&&a(e,["imageSize"],o);let i=s(n,["outputMimeType"]);i!=null&&a(e,["imageOutputOptions","mimeType"],i);let r=s(n,["outputCompressionQuality"]);return r!=null&&a(e,["imageOutputOptions","compressionQuality"],r),e}f(Rf,"imageConfigToVertex");function Gf(n){let e={},t=s(n,["bytesBase64Encoded"]);t!=null&&a(e,["imageBytes"],He(t));let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(Gf,"imageFromMldev");function ka(n){let e={},t=s(n,["gcsUri"]);t!=null&&a(e,["gcsUri"],t);let o=s(n,["bytesBase64Encoded"]);o!=null&&a(e,["imageBytes"],He(o));let i=s(n,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}f(ka,"imageFromVertex");function Dn(n){let e={};if(s(n,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");let t=s(n,["imageBytes"]);t!=null&&a(e,["bytesBase64Encoded"],He(t));let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(Dn,"imageToMldev");function Te(n){let e={},t=s(n,["gcsUri"]);t!=null&&a(e,["gcsUri"],t);let o=s(n,["imageBytes"]);o!=null&&a(e,["bytesBase64Encoded"],He(o));let i=s(n,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}f(Te,"imageToVertex");function Mf(n,e,t){let o={},i=s(e,["pageSize"]);t!==void 0&&i!=null&&a(t,["_query","pageSize"],i);let r=s(e,["pageToken"]);t!==void 0&&r!=null&&a(t,["_query","pageToken"],r);let l=s(e,["filter"]);t!==void 0&&l!=null&&a(t,["_query","filter"],l);let c=s(e,["queryBase"]);return t!==void 0&&c!=null&&a(t,["_url","models_url"],Pa(n,c)),o}f(Mf,"listModelsConfigToMldev");function Df(n,e,t){let o={},i=s(e,["pageSize"]);t!==void 0&&i!=null&&a(t,["_query","pageSize"],i);let r=s(e,["pageToken"]);t!==void 0&&r!=null&&a(t,["_query","pageToken"],r);let l=s(e,["filter"]);t!==void 0&&l!=null&&a(t,["_query","filter"],l);let c=s(e,["queryBase"]);return t!==void 0&&c!=null&&a(t,["_url","models_url"],Pa(n,c)),o}f(Df,"listModelsConfigToVertex");function Lf(n,e){let t={},o=s(e,["config"]);return o!=null&&Mf(n,o,t),t}f(Lf,"listModelsParametersToMldev");function kf(n,e){let t={},o=s(e,["config"]);return o!=null&&Df(n,o,t),t}f(kf,"listModelsParametersToVertex");function Uf(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&a(e,["nextPageToken"],o);let i=s(n,["_self"]);if(i!=null){let r=Na(i);Array.isArray(r)&&(r=r.map(l=>zo(l))),a(e,["models"],r)}return e}f(Uf,"listModelsResponseFromMldev");function Ff(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&a(e,["nextPageToken"],o);let i=s(n,["_self"]);if(i!=null){let r=Na(i);Array.isArray(r)&&(r=r.map(l=>Jo(l))),a(e,["models"],r)}return e}f(Ff,"listModelsResponseFromVertex");function Hf(n){let e={},t=s(n,["maskMode"]);t!=null&&a(e,["maskMode"],t);let o=s(n,["segmentationClasses"]);o!=null&&a(e,["maskClasses"],o);let i=s(n,["maskDilation"]);return i!=null&&a(e,["dilation"],i),e}f(Hf,"maskReferenceConfigToVertex");function zo(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["displayName"]);o!=null&&a(e,["displayName"],o);let i=s(n,["description"]);i!=null&&a(e,["description"],i);let r=s(n,["version"]);r!=null&&a(e,["version"],r);let l=s(n,["_self"]);l!=null&&a(e,["tunedModelInfo"],np(l));let c=s(n,["inputTokenLimit"]);c!=null&&a(e,["inputTokenLimit"],c);let d=s(n,["outputTokenLimit"]);d!=null&&a(e,["outputTokenLimit"],d);let u=s(n,["supportedGenerationMethods"]);u!=null&&a(e,["supportedActions"],u);let p=s(n,["temperature"]);p!=null&&a(e,["temperature"],p);let m=s(n,["maxTemperature"]);m!=null&&a(e,["maxTemperature"],m);let h=s(n,["topP"]);h!=null&&a(e,["topP"],h);let g=s(n,["topK"]);g!=null&&a(e,["topK"],g);let b=s(n,["thinking"]);return b!=null&&a(e,["thinking"],b),e}f(zo,"modelFromMldev");function Jo(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["displayName"]);o!=null&&a(e,["displayName"],o);let i=s(n,["description"]);i!=null&&a(e,["description"],i);let r=s(n,["versionId"]);r!=null&&a(e,["version"],r);let l=s(n,["deployedModels"]);if(l!=null){let m=l;Array.isArray(m)&&(m=m.map(h=>Zu(h))),a(e,["endpoints"],m)}let c=s(n,["labels"]);c!=null&&a(e,["labels"],c);let d=s(n,["_self"]);d!=null&&a(e,["tunedModelInfo"],op(d));let u=s(n,["defaultCheckpointId"]);u!=null&&a(e,["defaultCheckpointId"],u);let p=s(n,["checkpoints"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(h=>h)),a(e,["checkpoints"],m)}return e}f(Jo,"modelFromVertex");function Vf(n){let e={},t=s(n,["mediaResolution"]);t!=null&&a(e,["mediaResolution"],t);let o=s(n,["codeExecutionResult"]);o!=null&&a(e,["codeExecutionResult"],o);let i=s(n,["executableCode"]);i!=null&&a(e,["executableCode"],i);let r=s(n,["fileData"]);r!=null&&a(e,["fileData"],ju(r));let l=s(n,["functionCall"]);l!=null&&a(e,["functionCall"],ef(l));let c=s(n,["functionResponse"]);c!=null&&a(e,["functionResponse"],c);let d=s(n,["inlineData"]);d!=null&&a(e,["inlineData"],Cu(d));let u=s(n,["text"]);u!=null&&a(e,["text"],u);let p=s(n,["thought"]);p!=null&&a(e,["thought"],p);let m=s(n,["thoughtSignature"]);m!=null&&a(e,["thoughtSignature"],m);let h=s(n,["videoMetadata"]);return h!=null&&a(e,["videoMetadata"],h),e}f(Vf,"partToMldev$1");function Bf(n){let e={},t=s(n,["productImage"]);return t!=null&&a(e,["image"],Te(t)),e}f(Bf,"productImageToVertex");function qf(n,e){let t={},o=s(n,["numberOfImages"]);e!==void 0&&o!=null&&a(e,["parameters","sampleCount"],o);let i=s(n,["baseSteps"]);e!==void 0&&i!=null&&a(e,["parameters","baseSteps"],i);let r=s(n,["outputGcsUri"]);e!==void 0&&r!=null&&a(e,["parameters","storageUri"],r);let l=s(n,["seed"]);e!==void 0&&l!=null&&a(e,["parameters","seed"],l);let c=s(n,["safetyFilterLevel"]);e!==void 0&&c!=null&&a(e,["parameters","safetySetting"],c);let d=s(n,["personGeneration"]);e!==void 0&&d!=null&&a(e,["parameters","personGeneration"],d);let u=s(n,["addWatermark"]);e!==void 0&&u!=null&&a(e,["parameters","addWatermark"],u);let p=s(n,["outputMimeType"]);e!==void 0&&p!=null&&a(e,["parameters","outputOptions","mimeType"],p);let m=s(n,["outputCompressionQuality"]);e!==void 0&&m!=null&&a(e,["parameters","outputOptions","compressionQuality"],m);let h=s(n,["enhancePrompt"]);e!==void 0&&h!=null&&a(e,["parameters","enhancePrompt"],h);let g=s(n,["labels"]);return e!==void 0&&g!=null&&a(e,["labels"],g),t}f(qf,"recontextImageConfigToVertex");function Of(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["source"]);i!=null&&Jf(i,t);let r=s(e,["config"]);return r!=null&&qf(r,t),t}f(Of,"recontextImageParametersToVertex");function zf(n){let e={},t=s(n,["predictions"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(i=>Mn(i))),a(e,["generatedImages"],o)}return e}f(zf,"recontextImageResponseFromVertex");function Jf(n,e){let t={},o=s(n,["prompt"]);e!==void 0&&o!=null&&a(e,["instances[0]","prompt"],o);let i=s(n,["personImage"]);e!==void 0&&i!=null&&a(e,["instances[0]","personImage","image"],Te(i));let r=s(n,["productImages"]);if(e!==void 0&&r!=null){let l=r;Array.isArray(l)&&(l=l.map(c=>Bf(c))),a(e,["instances[0]","productImages"],l)}return t}f(Jf,"recontextImageSourceToVertex");function Wf(n){let e={},t=s(n,["referenceImage"]);t!=null&&a(e,["referenceImage"],Te(t));let o=s(n,["referenceId"]);o!=null&&a(e,["referenceId"],o);let i=s(n,["referenceType"]);i!=null&&a(e,["referenceType"],i);let r=s(n,["maskImageConfig"]);r!=null&&a(e,["maskImageConfig"],Hf(r));let l=s(n,["controlImageConfig"]);l!=null&&a(e,["controlImageConfig"],Ru(l));let c=s(n,["styleImageConfig"]);c!=null&&a(e,["styleImageConfig"],c);let d=s(n,["subjectImageConfig"]);return d!=null&&a(e,["subjectImageConfig"],d),e}f(Wf,"referenceImageAPIInternalToVertex");function Ua(n){let e={},t=s(n,["safetyAttributes","categories"]);t!=null&&a(e,["categories"],t);let o=s(n,["safetyAttributes","scores"]);o!=null&&a(e,["scores"],o);let i=s(n,["contentType"]);return i!=null&&a(e,["contentType"],i),e}f(Ua,"safetyAttributesFromMldev");function Fa(n){let e={},t=s(n,["safetyAttributes","categories"]);t!=null&&a(e,["categories"],t);let o=s(n,["safetyAttributes","scores"]);o!=null&&a(e,["scores"],o);let i=s(n,["contentType"]);return i!=null&&a(e,["contentType"],i),e}f(Fa,"safetyAttributesFromVertex");function Kf(n){let e={},t=s(n,["category"]);if(t!=null&&a(e,["category"],t),s(n,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let o=s(n,["threshold"]);return o!=null&&a(e,["threshold"],o),e}f(Kf,"safetySettingToMldev");function Xf(n){let e={},t=s(n,["image"]);return t!=null&&a(e,["image"],Te(t)),e}f(Xf,"scribbleImageToVertex");function Yf(n,e){let t={},o=s(n,["mode"]);e!==void 0&&o!=null&&a(e,["parameters","mode"],o);let i=s(n,["maxPredictions"]);e!==void 0&&i!=null&&a(e,["parameters","maxPredictions"],i);let r=s(n,["confidenceThreshold"]);e!==void 0&&r!=null&&a(e,["parameters","confidenceThreshold"],r);let l=s(n,["maskDilation"]);e!==void 0&&l!=null&&a(e,["parameters","maskDilation"],l);let c=s(n,["binaryColorThreshold"]);e!==void 0&&c!=null&&a(e,["parameters","binaryColorThreshold"],c);let d=s(n,["labels"]);return e!==void 0&&d!=null&&a(e,["labels"],d),t}f(Yf,"segmentImageConfigToVertex");function Qf(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["source"]);i!=null&&jf(i,t);let r=s(e,["config"]);return r!=null&&Yf(r,t),t}f(Qf,"segmentImageParametersToVertex");function Zf(n){let e={},t=s(n,["predictions"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(i=>Tf(i))),a(e,["generatedMasks"],o)}return e}f(Zf,"segmentImageResponseFromVertex");function jf(n,e){let t={},o=s(n,["prompt"]);e!==void 0&&o!=null&&a(e,["instances[0]","prompt"],o);let i=s(n,["image"]);e!==void 0&&i!=null&&a(e,["instances[0]","image"],Te(i));let r=s(n,["scribbleImage"]);return e!==void 0&&r!=null&&a(e,["instances[0]","scribble"],Xf(r)),t}f(jf,"segmentImageSourceToVertex");function Ha(n){let e={},t=s(n,["voiceConfig"]);t!=null&&a(e,["voiceConfig"],t);let o=s(n,["languageCode"]);if(o!=null&&a(e,["languageCode"],o),s(n,["multiSpeakerVoiceConfig"])!==void 0)throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");return e}f(Ha,"speechConfigToVertex");function ep(n){let e={},t=s(n,["functionCallingConfig"]);t!=null&&a(e,["functionCallingConfig"],tf(t));let o=s(n,["retrievalConfig"]);return o!=null&&a(e,["retrievalConfig"],o),e}f(ep,"toolConfigToMldev");function tp(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let p=t;Array.isArray(p)&&(p=p.map(m=>m)),a(e,["functionDeclarations"],p)}if(s(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let o=s(n,["googleSearchRetrieval"]);o!=null&&a(e,["googleSearchRetrieval"],o);let i=s(n,["computerUse"]);i!=null&&a(e,["computerUse"],i);let r=s(n,["fileSearch"]);r!=null&&a(e,["fileSearch"],r);let l=s(n,["codeExecution"]);if(l!=null&&a(e,["codeExecution"],l),s(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=s(n,["googleMaps"]);c!=null&&a(e,["googleMaps"],Pf(c));let d=s(n,["googleSearch"]);d!=null&&a(e,["googleSearch"],Nf(d));let u=s(n,["urlContext"]);return u!=null&&a(e,["urlContext"],u),e}f(tp,"toolToMldev$1");function Va(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let m=t;Array.isArray(m)&&(m=m.map(h=>nf(h))),a(e,["functionDeclarations"],m)}let o=s(n,["retrieval"]);o!=null&&a(e,["retrieval"],o);let i=s(n,["googleSearchRetrieval"]);i!=null&&a(e,["googleSearchRetrieval"],i);let r=s(n,["computerUse"]);if(r!=null&&a(e,["computerUse"],r),s(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let l=s(n,["codeExecution"]);l!=null&&a(e,["codeExecution"],l);let c=s(n,["enterpriseWebSearch"]);c!=null&&a(e,["enterpriseWebSearch"],c);let d=s(n,["googleMaps"]);d!=null&&a(e,["googleMaps"],d);let u=s(n,["googleSearch"]);u!=null&&a(e,["googleSearch"],u);let p=s(n,["urlContext"]);return p!=null&&a(e,["urlContext"],p),e}f(Va,"toolToVertex");function np(n){let e={},t=s(n,["baseModel"]);t!=null&&a(e,["baseModel"],t);let o=s(n,["createTime"]);o!=null&&a(e,["createTime"],o);let i=s(n,["updateTime"]);return i!=null&&a(e,["updateTime"],i),e}f(np,"tunedModelInfoFromMldev");function op(n){let e={},t=s(n,["labels","google-vertex-llm-tuning-base-model-id"]);t!=null&&a(e,["baseModel"],t);let o=s(n,["createTime"]);o!=null&&a(e,["createTime"],o);let i=s(n,["updateTime"]);return i!=null&&a(e,["updateTime"],i),e}f(op,"tunedModelInfoFromVertex");function ip(n,e){let t={},o=s(n,["displayName"]);e!==void 0&&o!=null&&a(e,["displayName"],o);let i=s(n,["description"]);e!==void 0&&i!=null&&a(e,["description"],i);let r=s(n,["defaultCheckpointId"]);return e!==void 0&&r!=null&&a(e,["defaultCheckpointId"],r),t}f(ip,"updateModelConfigToMldev");function rp(n,e){let t={},o=s(n,["displayName"]);e!==void 0&&o!=null&&a(e,["displayName"],o);let i=s(n,["description"]);e!==void 0&&i!=null&&a(e,["description"],i);let r=s(n,["defaultCheckpointId"]);return e!==void 0&&r!=null&&a(e,["defaultCheckpointId"],r),t}f(rp,"updateModelConfigToVertex");function sp(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","name"],L(n,o));let i=s(e,["config"]);return i!=null&&ip(i,t),t}f(sp,"updateModelParametersToMldev");function ap(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["config"]);return i!=null&&rp(i,t),t}f(ap,"updateModelParametersToVertex");function lp(n,e){let t={},o=s(n,["outputGcsUri"]);e!==void 0&&o!=null&&a(e,["parameters","storageUri"],o);let i=s(n,["safetyFilterLevel"]);e!==void 0&&i!=null&&a(e,["parameters","safetySetting"],i);let r=s(n,["personGeneration"]);e!==void 0&&r!=null&&a(e,["parameters","personGeneration"],r);let l=s(n,["includeRaiReason"]);e!==void 0&&l!=null&&a(e,["parameters","includeRaiReason"],l);let c=s(n,["outputMimeType"]);e!==void 0&&c!=null&&a(e,["parameters","outputOptions","mimeType"],c);let d=s(n,["outputCompressionQuality"]);e!==void 0&&d!=null&&a(e,["parameters","outputOptions","compressionQuality"],d);let u=s(n,["enhanceInputImage"]);e!==void 0&&u!=null&&a(e,["parameters","upscaleConfig","enhanceInputImage"],u);let p=s(n,["imagePreservationFactor"]);e!==void 0&&p!=null&&a(e,["parameters","upscaleConfig","imagePreservationFactor"],p);let m=s(n,["labels"]);e!==void 0&&m!=null&&a(e,["labels"],m);let h=s(n,["numberOfImages"]);e!==void 0&&h!=null&&a(e,["parameters","sampleCount"],h);let g=s(n,["mode"]);return e!==void 0&&g!=null&&a(e,["parameters","mode"],g),t}f(lp,"upscaleImageAPIConfigInternalToVertex");function cp(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["_url","model"],L(n,o));let i=s(e,["image"]);i!=null&&a(t,["instances[0]","image"],Te(i));let r=s(e,["upscaleFactor"]);r!=null&&a(t,["parameters","upscaleConfig","upscaleFactor"],r);let l=s(e,["config"]);return l!=null&&lp(l,t),t}f(cp,"upscaleImageAPIParametersInternalToVertex");function dp(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>Mn(r))),a(e,["generatedImages"],i)}return e}f(dp,"upscaleImageResponseFromVertex");function up(n){let e={},t=s(n,["uri"]);t!=null&&a(e,["uri"],t);let o=s(n,["encodedVideo"]);o!=null&&a(e,["videoBytes"],He(o));let i=s(n,["encoding"]);return i!=null&&a(e,["mimeType"],i),e}f(up,"videoFromMldev");function fp(n){let e={},t=s(n,["gcsUri"]);t!=null&&a(e,["uri"],t);let o=s(n,["bytesBase64Encoded"]);o!=null&&a(e,["videoBytes"],He(o));let i=s(n,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}f(fp,"videoFromVertex");function pp(n){let e={},t=s(n,["image"]);t!=null&&a(e,["_self"],Te(t));let o=s(n,["maskMode"]);return o!=null&&a(e,["maskMode"],o),e}f(pp,"videoGenerationMaskToVertex");function mp(n){let e={},t=s(n,["image"]);t!=null&&a(e,["image"],Dn(t));let o=s(n,["referenceType"]);return o!=null&&a(e,["referenceType"],o),e}f(mp,"videoGenerationReferenceImageToMldev");function hp(n){let e={},t=s(n,["image"]);t!=null&&a(e,["image"],Te(t));let o=s(n,["referenceType"]);return o!=null&&a(e,["referenceType"],o),e}f(hp,"videoGenerationReferenceImageToVertex");function Ba(n){let e={},t=s(n,["uri"]);t!=null&&a(e,["uri"],t);let o=s(n,["videoBytes"]);o!=null&&a(e,["encodedVideo"],He(o));let i=s(n,["mimeType"]);return i!=null&&a(e,["encoding"],i),e}f(Ba,"videoToMldev");function qa(n){let e={},t=s(n,["uri"]);t!=null&&a(e,["gcsUri"],t);let o=s(n,["videoBytes"]);o!=null&&a(e,["bytesBase64Encoded"],He(o));let i=s(n,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}f(qa,"videoToVertex");function gp(n,e){let t={},o=s(n,["displayName"]);return e!==void 0&&o!=null&&a(e,["displayName"],o),t}f(gp,"createFileSearchStoreConfigToMldev");function bp(n){let e={},t=s(n,["config"]);return t!=null&&gp(t,e),e}f(bp,"createFileSearchStoreParametersToMldev");function yp(n,e){let t={},o=s(n,["force"]);return e!==void 0&&o!=null&&a(e,["_query","force"],o),t}f(yp,"deleteFileSearchStoreConfigToMldev");function Ep(n){let e={},t=s(n,["name"]);t!=null&&a(e,["_url","name"],t);let o=s(n,["config"]);return o!=null&&yp(o,e),e}f(Ep,"deleteFileSearchStoreParametersToMldev");function Ip(n){let e={},t=s(n,["name"]);return t!=null&&a(e,["_url","name"],t),e}f(Ip,"getFileSearchStoreParametersToMldev");function vp(n,e){let t={},o=s(n,["customMetadata"]);if(e!==void 0&&o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>l)),a(e,["customMetadata"],r)}let i=s(n,["chunkingConfig"]);return e!==void 0&&i!=null&&a(e,["chunkingConfig"],i),t}f(vp,"importFileConfigToMldev");function wp(n){let e={},t=s(n,["name"]);t!=null&&a(e,["name"],t);let o=s(n,["metadata"]);o!=null&&a(e,["metadata"],o);let i=s(n,["done"]);i!=null&&a(e,["done"],i);let r=s(n,["error"]);r!=null&&a(e,["error"],r);let l=s(n,["response"]);return l!=null&&a(e,["response"],_p(l)),e}f(wp,"importFileOperationFromMldev");function Tp(n){let e={},t=s(n,["fileSearchStoreName"]);t!=null&&a(e,["_url","file_search_store_name"],t);let o=s(n,["fileName"]);o!=null&&a(e,["fileName"],o);let i=s(n,["config"]);return i!=null&&vp(i,e),e}f(Tp,"importFileParametersToMldev");function _p(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["parent"]);o!=null&&a(e,["parent"],o);let i=s(n,["documentName"]);return i!=null&&a(e,["documentName"],i),e}f(_p,"importFileResponseFromMldev");function Cp(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&a(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);return e!==void 0&&i!=null&&a(e,["_query","pageToken"],i),t}f(Cp,"listFileSearchStoresConfigToMldev");function Sp(n){let e={},t=s(n,["config"]);return t!=null&&Cp(t,e),e}f(Sp,"listFileSearchStoresParametersToMldev");function Ap(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&a(e,["nextPageToken"],o);let i=s(n,["fileSearchStores"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(l=>l)),a(e,["fileSearchStores"],r)}return e}f(Ap,"listFileSearchStoresResponseFromMldev");function Oa(n,e){let t={},o=s(n,["mimeType"]);e!==void 0&&o!=null&&a(e,["mimeType"],o);let i=s(n,["displayName"]);e!==void 0&&i!=null&&a(e,["displayName"],i);let r=s(n,["customMetadata"]);if(e!==void 0&&r!=null){let c=r;Array.isArray(c)&&(c=c.map(d=>d)),a(e,["customMetadata"],c)}let l=s(n,["chunkingConfig"]);return e!==void 0&&l!=null&&a(e,["chunkingConfig"],l),t}f(Oa,"uploadToFileSearchStoreConfigToMldev");function xp(n){let e={},t=s(n,["fileSearchStoreName"]);t!=null&&a(e,["_url","file_search_store_name"],t);let o=s(n,["config"]);return o!=null&&Oa(o,e),e}f(xp,"uploadToFileSearchStoreParametersToMldev");function Pp(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&a(e,["sdkHttpResponse"],t),e}f(Pp,"uploadToFileSearchStoreResumableResponseFromMldev");var Np="Content-Type",$p="X-Server-Timeout",Rp="User-Agent",Wo="x-goog-api-client",Gp="1.33.0",Mp=`google-genai-sdk/${Gp}`,Dp="v1beta1",Lp="v1beta",Ko=class{static{f(this,"ApiClient")}constructor(e){var t,o;this.clientOptions=Object.assign(Object.assign({},e),{project:e.project,location:e.location,apiKey:e.apiKey,vertexai:e.vertexai});let i={};this.clientOptions.vertexai?(i.apiVersion=(t=this.clientOptions.apiVersion)!==null&&t!==void 0?t:Dp,i.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(i.apiVersion=(o=this.clientOptions.apiVersion)!==null&&o!==void 0?o:Lp,i.baseUrl="https://generativelanguage.googleapis.com/"),i.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=i,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(i,e.httpOptions))}baseUrlFromProjectLocation(){return this.clientOptions.project&&this.clientOptions.location&&this.clientOptions.location!=="global"?`https://${this.clientOptions.location}-aiplatform.googleapis.com/`:"https://aiplatform.googleapis.com/"}normalizeAuthParameters(){if(this.clientOptions.project&&this.clientOptions.location){this.clientOptions.apiKey=void 0;return}this.clientOptions.project=void 0,this.clientOptions.location=void 0}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let o=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&o.push(e.apiVersion),o.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=this.getBaseUrl(),t=new URL(e);return t.protocol=t.protocol=="http:"?"ws":"wss",t.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}constructUrl(e,t,o){let i=[this.getRequestUrlInternal(t)];return o&&i.push(this.getBaseResourcePath()),e!==""&&i.push(e),new URL(`${i.join("/")}`)}shouldPrependVertexProjectPath(e){return!(this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let o=this.shouldPrependVertexProjectPath(e),i=this.constructUrl(e.path,t,o);if(e.queryParams)for(let[l,c]of Object.entries(e.queryParams))i.searchParams.append(l,String(c));let r={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else r.body=e.body;return r=await this.includeExtraHttpOptionsToRequestInit(r,t,i.toString(),e.abortSignal),this.unaryApiCall(i,r,e.httpMethod)}patchHttpOptions(e,t){let o=JSON.parse(JSON.stringify(e));for(let[i,r]of Object.entries(t))typeof r=="object"?o[i]=Object.assign(Object.assign({},o[i]),r):r!==void 0&&(o[i]=r);return o}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let o=this.shouldPrependVertexProjectPath(e),i=this.constructUrl(e.path,t,o);(!i.searchParams.has("alt")||i.searchParams.get("alt")!=="sse")&&i.searchParams.set("alt","sse");let r={};return r.body=e.body,r=await this.includeExtraHttpOptionsToRequestInit(r,t,i.toString(),e.abortSignal),this.streamApiCall(i,r,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,t,o,i){if(t&&t.timeout||i){let r=new AbortController,l=r.signal;if(t.timeout&&t?.timeout>0){let c=setTimeout(()=>r.abort(),t.timeout);c&&typeof c.unref=="function"&&c.unref()}i&&i.addEventListener("abort",()=>{r.abort()}),e.signal=l}return t&&t.extraBody!==null&&kp(e,t.extraBody),e.headers=await this.getHeadersInternal(t,o),e}async unaryApiCall(e,t,o){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:o})).then(async i=>(await aa(i),new xt(i))).catch(i=>{throw i instanceof Error?i:new Error(JSON.stringify(i))})}async streamApiCall(e,t,o){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:o})).then(async i=>(await aa(i),this.processStreamResponse(i))).catch(i=>{throw i instanceof Error?i:new Error(JSON.stringify(i))})}processStreamResponse(e){return Ie(this,arguments,f(function*(){var o;let i=(o=e?.body)===null||o===void 0?void 0:o.getReader(),r=new TextDecoder("utf-8");if(!i)throw new Error("Response body is empty");try{let l="",c="data:",d=[`
|
|
1169
|
+
latestAddr: ${d.latestAddr} (I: d0adcc392e6e974c9917730ebad51322)`),this._currentWorkingContextIbGib=d.latestIbGib??await this.getContextIbGibFromArgOrAddr({addr:d.latestAddr,latest:!1}),this._updatingContext?U&&console.log(`${u} already updating context (I: f856f9414627ab00418dccd285b55822)`):(await this.handleContextUpdate({update:d}),a())}},"next"),error:f(async d=>{let u=`${i}[latestObs.error]`;console.error(`${u} this.metaspace.latestObs error: ${Cr({err:d})}. (E: 99df4c42195d46d0a9dbfb06ac45ae00)`)},"error")})),o&&await this.rel8To({ibGibs:[this._currentWorkingContextIbGib],rel8nName:o})}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{U&&console.log(`${i} complete.`)}}async finalizeContext({arg:e}){let t=`${this.lc}[${this.finalizeContext.name}]`;try{U&&console.log(`${t} starting... (I: dd53dfc745864dd19fde5f209ceb82c8)`);let o=0,i=100;for(;this._updatingContext&&o<i;)await W(100),o++,o%10===0&&console.log(`${t} already updating context and taking a litle while... waiting still. tries: ${o}/${i} (I: d45ab59af9ea43518432e34ddad95c19)`);throw this._updatingContext&&console.error(`${t} previous call to updatingContext took too long. Ignoring flag and finalizing context. (E: 9a2dc4e1923442fa90fbeae72f358acd)`),this._updatingContext=!0,this._contextChangesSubscription&&(await this._contextChangesSubscription.unsubscribe(),delete this._contextChangesSubscription),delete this._currentWorkingContextIbGib,new Error("not refactored yet. the proceeding code needs to be introduced in the robbot descending class. (E: 066aa414693672d868dbf953617aab23)")}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{this._updatingContext=!1,U&&console.log(`${t} complete.`)}}async handleContextUpdate({update:e}){let t=`${this.lc}[${this.handleContextUpdate.name}]`;for(;this._updatingContext;)console.warn(`${t} already updating context? delaying... (W: 19d2ebeaaf2340fb91a7d6c717e9cb41)`),await W(1e3);this._updatingContext=!0;try{if(U&&console.log(`${t} starting... (I: 3eeaa40cad49094f125f9f5cd6ff6e22)`),U&&(console.log(`${t} update: (I: ad0abae7de472e3b4d3891ea0b937322)`),console.table(e)),!e.latestIbGib){debugger;throw new Error("(UNEXPECTED) update.latestIbGib falsy? (E: e18a048d7e95757238396ddd84748f22)")}let o=e.latestIbGib,i=await this.getNewChildrenIbGibs({newContext:o});if(i.length===1){let r=i[0];await this.handleNewContextChild({newChild:r})}else if(i.length>1){console.warn(`${t} (UNEXPECTED) multiple new children in context update. iterating through each one. (W: 02d82a8f755f418d95fa30f0f52ad58e)`);for(let r of i)await this.handleNewContextChild({newChild:r})}else{U&&console.log(`${t} no new children in context update. returning early... (I: 31397b04965351ab29bb3f78cb709122)`);return}}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{this._updatingContext=!1,U&&console.log(`${t} complete.`)}}async getNewChildrenIbGibs({newContext:e}){let t=`${this.lc}[${this.getNewChildrenIbGibs.name}]`;try{U&&console.log(`${t} starting... (I: 1b3d1cf908489087fa3b281f55b9a522)`);let i=[...e.rel8ns?.comment??[],...e.rel8ns?.pic??[],...e.rel8ns?.link??[]].filter(u=>!this._currentWorkingContextIbGib_PriorChildrenAddrs.includes(u));if(i.length===0)return U&&console.log(`${t} no new children addrs in newContext. returning early... (I: 8f9c3658c194c472cb1e2bc19d847b22)`),[];if(!this.metaspace)throw new Error("this.metaspace falsy. not initialized? (E: 1cc26ca7de7fadcdbaecbd6613350e23)");let r=await this.metaspace.getLocalUserSpace({});if(!r)throw new Error("couldn't get local user space? (E: f118f75e5852fc22bba3a6495beec723)");let a=await tr({addrs:i,space:r}),c=Object.values(a?.data?.latestAddrsMap??{});if(!a?.data?.success||c.length!==i.length)throw new Error("could not get latest addrs. (E: 2e1619e7e2e166696fe8ff78cb02cc22)");if(c.some(u=>u===null))throw new Error("some addrs were not found in the space. (E: 2216d8e5ad7fb600ceb025ed7c90f323)");let d=await this.metaspace.get({addrs:c});if(!d.success||d.ibGibs?.length!==i.length)throw new Error(`failed to get newChildren with addrs: ${i.join("|")}. Error: ${d.errorMsg??"unknown error 5737bd0996d5445b8bd80975bedc0d57"} (E: 05722e11350ec6ffffdb5c7d0caa2922)`);return d.ibGibs}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{U&&console.log(`${t} complete.`)}}async handleNewContextChild({newChild:e}){let t=`${this.lc}[${this.handleNewContextChild.name}]`;try{throw new Error("not implemented in base class (E: ea6b2b13d9504d93b33b70191d106084)")}catch(o){throw console.error(`${t} ${y(o)}`),o}}};var ie=V,Ue=class extends zt{static{f(this,"LiveProxyIbGib")}lc="";ib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.ib:Ut;gib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.gib:Ft;data=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.data:void 0;rel8ns=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.rel8ns:void 0;async loadNewerSelfIfAvailable(){let e=`${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;try{ie&&console.log(`${e} starting... (I: genuuid)`),console.warn(`${e} does nothing in this class. I just have this warning here because I want to see if this gets executed. (W: genuuid)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{ie&&console.log(`${e} complete.`)}}async loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{ie&&console.log(`${t} starting... (I: genuuid)`);debugger;console.warn(`${t} does nothing in this class. I just have this warning here because I want to see if this gets executed. (W: genuuid)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{ie&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;return ie&&console.log(`${e} elided in this proxy class because this isn't a true witness atow (04/2025) (I: fd223814f169798d9f499d6e9cdc0325)`),[]}get ibGib(){return this._currentWorkingContextIbGib}spaceId;constructor(e,t){super(e,t)}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{ie&&console.log(`${e} starting... (I: 1bd72217a5f334effc63f8d51e7b2225)`),await super.initialize(),this._contextUpdated$=await io(),this.contextUpdated$=this._contextUpdated$.asObservable(),this._newContextChild$=await io(),this.newContextChild$=this._newContextChild$.asObservable()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{ie&&console.log(`${e} complete.`)}}parseAddlMetadataString({ib:e}){let t=`${this.lc}[${this.parseAddlMetadataString.name}]`;return console.warn(`${t} not really implemented in this class atow (04/2025). (W: genuuid)`),{}}_initialContext;async witnessImpl(e){let t=`${this.lc}[${this.witnessImpl.name}]`;try{if(ie&&console.log(`${t} starting...`),er({ib:e.ib})){if(!e.data)throw new Error("arg has space ib but arg.data is falsy (E: b2af9226c067d5e72f117fa36e239525)");let o=e.data.uuid;return this.spaceId=o,ie&&console.log(`${t} spaceId set to the ${o} (I: 018724a5431ba421b71fad36924c5a25)`),ne.primitive({ib:`spaceId set to ${o}`})}else if(this._initialContext){debugger;console.error(`${t} (UNEXPECTED) context already initialized. returning early without doing anything. NOTE: This error was not thrown, only logged. (E: genuuid)`)}else{let o=await this.metaspace?.getLocalUserSpace({localSpaceId:this.spaceId});return await this.setWrappedIbGib({ibGib:e,space:o}),vt}}catch(o){throw console.error(`${t} ${o.message}`),o}finally{ie&&console.log(`${t} complete.`)}}_contextUpdated$;contextUpdated$;_newContextChild$;newContextChild$;async handleContextUpdate({update:e}){let t=`${this.lc}[${this.handleContextUpdate.name}]`;try{if(ie&&console.log(`${t} starting... (I: c262bcda065c086ffe9e3ac5899abe25)`),await super.handleContextUpdate({update:e}),!this._contextUpdated$)throw new Error("(UNEXPECTED) this._contextUpdated$ falsy? (E: a184df090502bed9649f8df88bd4c125)");await this._contextUpdated$.next(this._currentWorkingContextIbGib)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{ie&&console.log(`${t} complete.`)}}async setWrappedIbGib({ibGib:e,ibGibAddr:t,space:o}){let i=`${this.lc}[${this.setWrappedIbGib.name}]`;try{if(ie&&console.log(`${i} starting... (I: a4b0acda259c121801aa701534320125)`),this.metaspace||(this.metaspace=await me()),!e){if(!t)throw new Error("(UNEXPECTED) both ibGib AND ibGibAddr falsy? (E: 6fac98ba2d4cfdec2b7ee974dec74625)");if(o??=await this.metaspace.getLocalUserSpace({lock:!1}),!o)throw new Error("(UNEXPECTED) space falsy? no space provided and couldn't get default local user space? (E: e14d1b7a6586f99453fc571396d4df25)");let r=await this.metaspace.get({addrs:[t],space:o});if(!r.success||r.ibGibs?.length!==1)throw new Error(`${i} failed to get ibGib(?) (${t}). space.ib: ${o.ib} (E: b38f0a25d92e44c0aa5cc3b038a43c6c)`);e=r.ibGibs.at(0)}await this.initializeContext({contextIbGib:e,rel8nName:""})}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{ie&&console.log(`${i} complete.`)}}async handleNewContextChild({newChild:e}){let t=`[${this.handleNewContextChild.name}]`;try{if(ie&&console.log(`${t} starting... (I: 7e9b6b7a4bb2726e9c717f230dfe1925)`),!this._newContextChild$)throw new Error("(UNEXPECTED) this._contextUpdated$ falsy? (E: a184df090502bed9649f8df88bd4c125)");await this._newContextChild$.next(e)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{ie&&console.log(`${t} complete.`)}}};var st="witness_agent",at=/^[a-zA-Z0-9_\-.]{1,32}$/,lo=/.{1,255}/,Jr="",Wr="Manco",Kr="This is a generic, unspecified agent.";var Jt="List of function info ibgib addresses. These contain info on both the requests you made and the resultant values.",Qe="agent",db={type:"string",description:"unique identifier for the agent. Should be provided to the agent in system instructions upon creation."},ub={type:"string",description:"type of the agent that governs basic responsibilities. Should be provided to the agent in system instructions upon creation."};var Fl="hardcoded",Hl="human",Vl="ai",Bl="function",ql="unknown",X={HARDCODED:Fl,HUMAN:Hl,AI:Vl,FUNCTION:Bl,UNKNOWN:ql},co=Object.freeze(Object.values(X));function Xr(n){return!!n&&co.includes(n)}f(Xr,"isTextSource");var fb={type:"string",description:`The agent should pick a name with which to represent him/her/itself to the user. This should not be "Gemini" or something bland like that, rather, it should be a name that the agent likes. Should contain no spaces, only alphanumerics. Note that the example given has a name, but really it should be up to the agent's own preference. Please be consistent with this with yourself, i.e., don't change it once established. Must pass regex: ${at.source}`},Yr="primaryagent";var Qr=!1;async function uo({ibGib:n,addr:e,tagIbGib:t,metaspace:o,space:i}){let r=`[${uo.name}]`;try{if(Qr&&console.log(`${r} starting... (I: b1fd25ec28bce8f1916b4ab55f48a724)`),!e&&!n)throw new Error("either addr or ibGib required (E: 3d580f8ecc251a0c81c7ea8bc3d38524)");if(e??=S({ibGib:n}),e!==S({ibGib:n}))throw new Error(`addr (${e}) differs from incoming ibGib's addr (${S({ibGib:n})}). (E: f2c14234a78c917fb9f587beaee89324)`);let a=await o.getLatestAddr({ibGib:t,space:i});if(a!==S({ibGib:t})){let p=await o.get({addr:a,space:i});if(!p.success||p.ibGibs?.length!==1)throw new Error(`could not get latest tag (${a}) from space (${i.ib}). error: ${p.errorMsg??"[unknown error (E: a4e31c98398b417db8f617f98a5f2741)]"} (E: 73c085d81efdab0e7b8939222ec07524)`);t=p.ibGibs.at(0)}let c={[Zi]:[e]},d=await Je({src:t,rel8nsToAddByAddr:c,dna:!0,nCounter:!0}),u=d.newIbGib;return await o.persistTransformResult({resTransform:d,space:i}),await o.registerNewIbGib({ibGib:u,space:i}),u}catch(a){throw console.error(`${r} ${y(a)}`),a}finally{Qr&&console.log(`${r} complete.`)}}f(uo,"rel8ToTag");var j=V,po=class n{static{f(this,"AgentsService_V1")}lc=`[${n.name}]`;latestAgents=new Map;factoryFns={};constructor(){}async getAgentById(e){let t=`${this.lc}[${this.getAgentById.name}]`;try{let{agentId:o,agentType:i,spaceId:r}=e;j&&console.log(`${t} starting... (I: 0c4214b4614a43bd2825978e54aee325)`);let a=this.latestAgents.get(o);if(!a){let c=await me();a=(await Wt({metaspace:c,type:i,spaceId:r})).find(u=>u.data.uuid===o)}return a||console.warn(`${t} couldn't find any agent by id. opts: ${M(e)} (W: 70cf51ecbe68dfdcfe1e9995a7468f25)`),a}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{j&&console.log(`${t} complete.`)}}async updateOrSetLatestAgent({agent:e,throwIfNewerFound:t}){let o=`${this.lc}[${this.updateOrSetLatestAgent.name}]`;try{if(j&&console.log(`${o} starting... (I: 9bb74f19b989fc0ee969cb4c2c2aa525)`),!e.data)throw new Error(`invalid agent. data falsy. agent.ib: ${e.ib} (E: 7356db7395cb0c5664d13437dd62c425)`);if(!e.data.uuid)throw new Error(`invalid agent. data.uuid falsy. agent.ib: ${e.ib} (E: 48afcd6658154bee1138fca31cbfbf25)`);let i=await this.getLatestAgent({id:e.data.uuid});if(i){if(!i.data)throw new Error("(UNEXPECTED) existing.data falsy? should have thrown on previous set function call? (E: f3cbae9922ea9849ada25db2eea40825)");if(i.data.n===e.data.n){if(i.gib===e.gib)return;console.warn(`existing.data.n === agent.data.n but gibs are different. We have a branched timeline. just logging this error, need to figure out wth is going on here. we should not have this with the timeline being locked. The only thing I can think of is if the ibgib is updated very quickly, but even then, the n should be incremented. still the approach is valid. anyway, we're going ahead and taking the newer agent.
|
|
1170
|
+
existing: ${M(oe({ibGib:i}))}
|
|
1171
|
+
new: ${M(oe({ibGib:e}))} (E: 5e079b566ff3533acdb2d01359f08625)`),await i.loadIbGibDto(e.toIbGibDto()),this.latestAgents.set(e.data.uuid,e);return}else if(i.data.n>e.data.n){let r="existing.data.n > agent.data.n, i.e., the one we already have is newer. So why was the caller trying to set to the older agent thinking it was the most recent? Probably have a branched timeline.";if(t)throw new Error(`${o} ${r} (E: bb2cc3ce8cfa88b80fb62149b0e70225)`);console.warn(`${o} ${r} (W: caaf66deb4e6fd8e2eb9261685dc0325)`);return}else{await i.loadIbGibDto(e.toIbGibDto()),this.latestAgents.set(e.data.uuid,e);return}}else{this.latestAgents.set(e.data.uuid,e);return}}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{j&&console.log(`${o} complete.`)}}getLatestAgent({id:e}){let t=`${this.lc}[${this.getLatestAgent.name}]`;try{return j&&console.log(`${t} starting... (I: 8e85b55057760b712a913a92e88ead25)`),Promise.resolve(this.latestAgents.get(e))}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{j&&console.log(`${t} complete.`)}}registerFactory({classname:e,fnDtoToAgentWitness:t}){this.factoryFns[e]=t}async getAgentWitnessFromDto({dto:e,classname:t}){let o=`${this.lc}[${this.getAgentWitnessFromDto.name}]`;try{if(j&&console.log(`${o} starting... (I: 718837d4ee3d590177f3425b99106225)`),!e.data)throw new Error("dto.data falsy (E: fad89dd4c787b687a657c13968946925)");let i;if(t??=e.data.classname,t){let r=this.factoryFns[t],a=await r(e);if(a.applies){if(!a.agent)throw new Error("(UNEXPECTED) factory function for agent dto applies: true, but the resulting agent is undefined? (E: b13cdf0f3d9c50f1fa419f2c409ebf25)");i=a.agent}else throw new Error(`classname (${t}) factory function found and attempted, but result says applied: false. (E: 751a2502c9a7e2d61c76c8ae2f7fb125)`)}else{let r=Object.keys(this.factoryFns);for(let a of r){let c=this.factoryFns[a],d=await c(e);if(d.applies){if(!d.agent)throw new Error("(UNEXPECTED) factory function for agent dto applies: true, but the resulting agent is undefined? (E: 60e97c083a668baf11efcd6adf6a3525)");i=d.agent;break}}}return i}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{j&&console.log(`${o} complete.`)}}async getAgentByAddr({agentAddr:e,spaceId:t,metaspace:o}){let i=`${this.lc}[${this.getAgentByAddr.name}]`;try{if(j&&console.log(`${i} starting... (I: 42dfecbe6d6b5a3a7d392af5a66cc625)`),!e)throw new Error(`${i} agentAddr is required. (E: 389351659a2e08fa179ceede16925a25)`);let{ib:r}=F({ibGibAddr:e}),{uuid:a,type:c}=Zr({ib:r});if(!a){debugger;throw new Error(`(UNEXPECTED) agentAddr doesn't have uuid in the ib? agentAddr: ${e} (E: fedcacffed98fdc78b1e80e45c413925)`)}let d=await this.getAgentById({agentId:a,agentType:c});if(d)return j&&console.log(`${i} agent found already in agents svc so didn't need to go get it from the space. (I: ec6abaf3badd8e301d79a7476845bc25)`),d;o??=await me();let u=await o.getLocalUserSpace({localSpaceId:t,lock:!1});if(!u)throw t?new Error(`couldn't get space with spaceId (${t}) (E: 26b3f1414a93cc339e704d0162cb8b25)`):new Error("(UNEXPECTED) couldn't get default local user space? (E: 2e19a1fae8b3f00595257f51426ac225)");let p=await o.get({addrs:[e],space:u});if(!p.success||!p.ibGibs||p.ibGibs.length===0){j&&console.log(`${i} Agent ibGib not found in space (${t}) at address ${e}. (I: 29c5c7994fb3ed388b28a81a9ed68325)`);return}let m=p.ibGibs[0],h=await this.getAgentWitnessFromDto({dto:m});if(!h){debugger;throw new Error(`${i} Couldn't get actual agent witness from agent dto (${e}). Have we registered classname (${m.data?.classname}) and factory fn with agents service? (E: e6e9da6c91d14bd7acb5c571c8de1a25)`)}return await this.updateOrSetLatestAgent({agent:h,throwIfNewerFound:!0}),j&&console.log(`${i} Cached agent witness with id ${a}. (I: b862f63147a3fac3c6e6210d5ab87c25)`),j&&console.log(`${i} complete. Retrieved and cached agent witness for address ${e}.`),h}catch(r){throw console.error(`${i} ${y(r)}`),r}}async createNewAgent(e){let t=`[${this.createNewAgent.name}]`;try{j&&console.log(`${t} starting... (I: a3e07b54bb7bf45f7739eff2d738c825)`);let{metaspace:o,superSpace:i,name:r,availableFunctions:a,initialSystemText:c,initialChatText:d,fnGetAPIKey:u,addToAgentsTag:p,type:m}=e;if(i??=await o.getLocalUserSpace({}),!i)throw new Error("(UNEXPECTED) superSpace falsy? (E: ceb60d96ff25b6d6aaa5aa69a7a51d25)");if(!i.data)throw new Error("(UNEXPECTED) superSpace.data falsy? (E: 56b4ec127f8559da96e6f70c7cb13825)");let h=ho(e),g=await h.createInitialData(i);if(!g.uuid)throw new Error("(UNEXPECTED) data.uuid falsy? (E: 4e4f6fcf89d1e3775971ad843a083725)");let b=await o.createLocalSpaceAndUpdateBootstrap({allowCancel:!1,zeroSpace:o.zeroSpace,spaceName:r+g.uuid.substring(0,5),createBootstrap:!1});if(!b)throw new Error("(UNEXPECTED) newSubSpace falsy after creating locally? (E: af8b5503c15d4292e2f591b316e7d825)");g.subSpaceId=b.data.uuid;let E=await h.createInitialRel8ns(),I=await ne.firstGen({ib:go({data:g}),parentIbGib:ne.primitive({ib:st}),data:g,rel8ns:E,nCounter:!0,dna:!0,tjp:{timestamp:!0}});await o.persistTransformResult({resTransform:I});let v=I.newIbGib,w=await h.createWitness();if(w.fnGetAPIKey=u,await w.loadIbGibDto(v),p){let _=await mo({metaspace:o,space:i}),A=await uo({ibGib:v,metaspace:o,space:i,tagIbGib:_})}await Ge({type:m,rel8nInfos:[{rel8nName:Qe,ibGibs:[v]}],metaspace:o,space:i}),a.length>0&&await w.addAvailableFunctions(a);let T=[];return T.push({textSrc:"hardcoded",text:lt({tagText:ar,contentText:`Your id (agent id) is: ${g.uuid}. Your superSpaceId is: ${g.superSpaceId}. Your subSpaceId is: ${g.subSpaceId}. These may be useful/required in some functions, though you should refer to those functions' instructions/descriptions for applicability.`}),isSystem:!0}),c&&T.push({textSrc:"hardcoded",text:c,isSystem:!0}),d&&T.push({textSrc:"hardcoded",text:d}),await w.addTexts({infos:T}),this.latestAgents.set(w.data.uuid,w),w}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{j&&console.log(`${t} complete.`)}}getAgents(e){let t=`${this.lc}[${this.getAgents.name}]`;try{return j&&console.log(`${t} starting... (I: 4663f125c3a21fa3ecccc2c5a38d1225)`),Wt(e)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{j&&console.log(`${t} complete.`)}}},fo;function xe(){return fo||(fo=new po),fo}f(xe,"getAgentsSvc");var Ol="gemini-3.1-pro-preview",zl="gemini-3-flash-preview",Jl="gemini-3.1-flash-lite-preview",Wl="gemini-3.1-flash-live-preview",Kl="gemini-2.5-pro",Xl="gemini-2.5-flash",Yl="gemini-2.5-flash-lite",Ql="gemini-2.5-flash-preview-tts",Zl="gemini-2.0-flash",jl="gemini-2.0-flash-lite",bo={GEMINI_3_1_PRO_PREVIEW:Ol,GEMINI_3_FLASH_PREVIEW:zl,GEMINI_3_1_FLASH_LITE_PREVIEW:Jl,GEMINI_3_1_FLASH_LIVE_PREVIEW:Wl,GEMINI_2_5_PRO:Kl,GEMINI_2_5_FLASH:Xl,GEMINI_2_5_FLASH_LITE:Yl,GEMINI_2_5_FLASH_PREVIEW_TTS:Ql,GEMINI_2_0_FLASH:Zl,GEMINI_2_0_FLASH_LITE:jl},Mb=Object.freeze(Object.values(bo));var jr=bo.GEMINI_2_5_FLASH,ct=bo.GEMINI_2_5_FLASH_LITE,yo=5;var es={version:"1",uuid:Jr,name:Wr,description:Kr,classname:"AgentWitness_V1",icon:"happy",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1,subSpaceId:"",superSpaceId:"",availableFunctionNameOrIds:[],model:jr,api:"gemini",type:Yr,"@currentContextTjpAddr":z},Eo=void 0;var ec,tc;function nc(){return{geminiUrl:ec,vertexUrl:tc}}f(nc,"getDefaultBaseUrls");function oc(n,e,t,o){var i,r;if(!n?.baseUrl){let a=nc();return e?(i=a.vertexUrl)!==null&&i!==void 0?i:t:(r=a.geminiUrl)!==null&&r!==void 0?r:o}return n.baseUrl}f(oc,"getBaseUrl");var Te=class{static{f(this,"BaseModule")}};function C(n,e){let t=/\{([^}]+)\}/g;return n.replace(t,(o,i)=>{if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];return r!=null?String(r):""}else throw new Error(`Key '${i}' not found in valueMap.`)})}f(C,"formatMap");function l(n,e,t){for(let r=0;r<e.length-1;r++){let a=e[r];if(a.endsWith("[]")){let c=a.slice(0,-2);if(!(c in n))if(Array.isArray(t))n[c]=Array.from({length:t.length},()=>({}));else throw new Error(`Value must be a list given an array path ${a}`);if(Array.isArray(n[c])){let d=n[c];if(Array.isArray(t))for(let u=0;u<d.length;u++){let p=d[u];l(p,e.slice(r+1),t[u])}else for(let u of d)l(u,e.slice(r+1),t)}return}else if(a.endsWith("[0]")){let c=a.slice(0,-3);c in n||(n[c]=[{}]);let d=n[c];l(d[0],e.slice(r+1),t);return}(!n[a]||typeof n[a]!="object")&&(n[a]={}),n=n[a]}let o=e[e.length-1],i=n[o];if(i!==void 0){if(!t||typeof t=="object"&&Object.keys(t).length===0||t===i)return;if(typeof i=="object"&&typeof t=="object"&&i!==null&&t!==null)Object.assign(i,t);else throw new Error(`Cannot set value for an existing key. Key: ${o}`)}else o==="_self"&&typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.assign(n,t):n[o]=t}f(l,"setValueByPath");function s(n,e,t=void 0){try{if(e.length===1&&e[0]==="_self")return n;for(let o=0;o<e.length;o++){if(typeof n!="object"||n===null)return t;let i=e[o];if(i.endsWith("[]")){let r=i.slice(0,-2);if(r in n){let a=n[r];return Array.isArray(a)?a.map(c=>s(c,e.slice(o+1),t)):t}else return t}else n=n[i]}return n}catch(o){if(o instanceof TypeError)return t;throw o}}f(s,"getValueByPath");function ic(n,e){for(let[t,o]of Object.entries(e)){let i=t.split("."),r=o.split("."),a=new Set,c=-1;for(let d=0;d<i.length;d++)if(i[d]==="*"){c=d;break}if(c!==-1&&r.length>c)for(let d=c;d<r.length;d++){let u=r[d];u!=="*"&&!u.endsWith("[]")&&!u.endsWith("[0]")&&a.add(u)}To(n,i,r,0,a)}}f(ic,"moveValueByPath");function To(n,e,t,o,i){if(o>=e.length||typeof n!="object"||n===null)return;let r=e[o];if(r.endsWith("[]")){let a=r.slice(0,-2),c=n;if(a in c&&Array.isArray(c[a]))for(let d of c[a])To(d,e,t,o+1,i)}else if(r==="*"){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let a=n,c=Object.keys(a).filter(u=>!u.startsWith("_")&&!i.has(u)),d={};for(let u of c)d[u]=a[u];for(let[u,p]of Object.entries(d)){let m=[];for(let h of t.slice(o))h==="*"?m.push(u):m.push(h);l(a,m,p)}for(let u of c)delete a[u]}}else{let a=n;r in a&&To(a[r],e,t,o+1,i)}}f(To,"_moveValueRecursive");function vi(n){if(typeof n!="string")throw new Error("fromImageBytes must be a string");return n}f(vi,"tBytes$1");function rc(n){let e={},t=s(n,["operationName"]);t!=null&&l(e,["operationName"],t);let o=s(n,["resourceName"]);return o!=null&&l(e,["_url","resourceName"],o),e}f(rc,"fetchPredictOperationParametersToVertex");function sc(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(n,["done"]);i!=null&&l(e,["done"],i);let r=s(n,["error"]);r!=null&&l(e,["error"],r);let a=s(n,["response","generateVideoResponse"]);return a!=null&&l(e,["response"],lc(a)),e}f(sc,"generateVideosOperationFromMldev$1");function ac(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(n,["done"]);i!=null&&l(e,["done"],i);let r=s(n,["error"]);r!=null&&l(e,["error"],r);let a=s(n,["response"]);return a!=null&&l(e,["response"],cc(a)),e}f(ac,"generateVideosOperationFromVertex$1");function lc(n){let e={},t=s(n,["generatedSamples"]);if(t!=null){let r=t;Array.isArray(r)&&(r=r.map(a=>dc(a))),l(e,["generatedVideos"],r)}let o=s(n,["raiMediaFilteredCount"]);o!=null&&l(e,["raiMediaFilteredCount"],o);let i=s(n,["raiMediaFilteredReasons"]);return i!=null&&l(e,["raiMediaFilteredReasons"],i),e}f(lc,"generateVideosResponseFromMldev$1");function cc(n){let e={},t=s(n,["videos"]);if(t!=null){let r=t;Array.isArray(r)&&(r=r.map(a=>uc(a))),l(e,["generatedVideos"],r)}let o=s(n,["raiMediaFilteredCount"]);o!=null&&l(e,["raiMediaFilteredCount"],o);let i=s(n,["raiMediaFilteredReasons"]);return i!=null&&l(e,["raiMediaFilteredReasons"],i),e}f(cc,"generateVideosResponseFromVertex$1");function dc(n){let e={},t=s(n,["video"]);return t!=null&&l(e,["video"],bc(t)),e}f(dc,"generatedVideoFromMldev$1");function uc(n){let e={},t=s(n,["_self"]);return t!=null&&l(e,["video"],yc(t)),e}f(uc,"generatedVideoFromVertex$1");function fc(n){let e={},t=s(n,["operationName"]);return t!=null&&l(e,["_url","operationName"],t),e}f(fc,"getOperationParametersToMldev");function pc(n){let e={},t=s(n,["operationName"]);return t!=null&&l(e,["_url","operationName"],t),e}f(pc,"getOperationParametersToVertex");function mc(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(n,["done"]);i!=null&&l(e,["done"],i);let r=s(n,["error"]);r!=null&&l(e,["error"],r);let a=s(n,["response"]);return a!=null&&l(e,["response"],hc(a)),e}f(mc,"importFileOperationFromMldev$1");function hc(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["parent"]);o!=null&&l(e,["parent"],o);let i=s(n,["documentName"]);return i!=null&&l(e,["documentName"],i),e}f(hc,"importFileResponseFromMldev$1");function Ta(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(n,["done"]);i!=null&&l(e,["done"],i);let r=s(n,["error"]);r!=null&&l(e,["error"],r);let a=s(n,["response"]);return a!=null&&l(e,["response"],gc(a)),e}f(Ta,"uploadToFileSearchStoreOperationFromMldev");function gc(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["parent"]);o!=null&&l(e,["parent"],o);let i=s(n,["documentName"]);return i!=null&&l(e,["documentName"],i),e}f(gc,"uploadToFileSearchStoreResponseFromMldev");function bc(n){let e={},t=s(n,["uri"]);t!=null&&l(e,["uri"],t);let o=s(n,["encodedVideo"]);o!=null&&l(e,["videoBytes"],vi(o));let i=s(n,["encoding"]);return i!=null&&l(e,["mimeType"],i),e}f(bc,"videoFromMldev$1");function yc(n){let e={},t=s(n,["gcsUri"]);t!=null&&l(e,["uri"],t);let o=s(n,["bytesBase64Encoded"]);o!=null&&l(e,["videoBytes"],vi(o));let i=s(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}f(yc,"videoFromVertex$1");var ts;(function(n){n.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",n.OUTCOME_OK="OUTCOME_OK",n.OUTCOME_FAILED="OUTCOME_FAILED",n.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(ts||(ts={}));var ns;(function(n){n.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",n.PYTHON="PYTHON"})(ns||(ns={}));var os;(function(n){n.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",n.SILENT="SILENT",n.WHEN_IDLE="WHEN_IDLE",n.INTERRUPT="INTERRUPT"})(os||(os={}));var Fe;(function(n){n.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",n.STRING="STRING",n.NUMBER="NUMBER",n.INTEGER="INTEGER",n.BOOLEAN="BOOLEAN",n.ARRAY="ARRAY",n.OBJECT="OBJECT",n.NULL="NULL"})(Fe||(Fe={}));var is;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(is||(is={}));var rs;(function(n){n.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",n.SIMPLE_SEARCH="SIMPLE_SEARCH",n.ELASTIC_SEARCH="ELASTIC_SEARCH"})(rs||(rs={}));var ss;(function(n){n.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",n.NO_AUTH="NO_AUTH",n.API_KEY_AUTH="API_KEY_AUTH",n.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",n.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",n.OAUTH="OAUTH",n.OIDC_AUTH="OIDC_AUTH"})(ss||(ss={}));var as;(function(n){n.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",n.HTTP_IN_QUERY="HTTP_IN_QUERY",n.HTTP_IN_HEADER="HTTP_IN_HEADER",n.HTTP_IN_PATH="HTTP_IN_PATH",n.HTTP_IN_BODY="HTTP_IN_BODY",n.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(as||(as={}));var ls;(function(n){n.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",n.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",n.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",n.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",n.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",n.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",n.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(ls||(ls={}));var cs;(function(n){n.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",n.LOW="LOW",n.HIGH="HIGH"})(cs||(cs={}));var ds;(function(n){n.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",n.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",n.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",n.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",n.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",n.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",n.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",n.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",n.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",n.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",n.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"})(ds||(ds={}));var us;(function(n){n.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",n.SEVERITY="SEVERITY",n.PROBABILITY="PROBABILITY"})(us||(us={}));var fs;(function(n){n.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",n.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",n.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",n.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",n.BLOCK_NONE="BLOCK_NONE",n.OFF="OFF"})(fs||(fs={}));var ps;(function(n){n.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",n.STOP="STOP",n.MAX_TOKENS="MAX_TOKENS",n.SAFETY="SAFETY",n.RECITATION="RECITATION",n.LANGUAGE="LANGUAGE",n.OTHER="OTHER",n.BLOCKLIST="BLOCKLIST",n.PROHIBITED_CONTENT="PROHIBITED_CONTENT",n.SPII="SPII",n.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",n.IMAGE_SAFETY="IMAGE_SAFETY",n.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",n.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",n.NO_IMAGE="NO_IMAGE",n.IMAGE_RECITATION="IMAGE_RECITATION",n.IMAGE_OTHER="IMAGE_OTHER"})(ps||(ps={}));var ms;(function(n){n.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",n.NEGLIGIBLE="NEGLIGIBLE",n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH"})(ms||(ms={}));var hs;(function(n){n.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",n.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",n.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",n.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",n.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(hs||(hs={}));var gs;(function(n){n.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",n.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",n.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",n.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",n.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(gs||(gs={}));var bs;(function(n){n.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",n.SAFETY="SAFETY",n.OTHER="OTHER",n.BLOCKLIST="BLOCKLIST",n.PROHIBITED_CONTENT="PROHIBITED_CONTENT",n.IMAGE_SAFETY="IMAGE_SAFETY",n.MODEL_ARMOR="MODEL_ARMOR",n.JAILBREAK="JAILBREAK"})(bs||(bs={}));var ys;(function(n){n.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",n.ON_DEMAND="ON_DEMAND",n.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(ys||(ys={}));var tn;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.AUDIO="AUDIO"})(tn||(tn={}));var Es;(function(n){n.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",n.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",n.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",n.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(Es||(Es={}));var Is;(function(n){n.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",n.TUNING_MODE_FULL="TUNING_MODE_FULL",n.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(Is||(Is={}));var vs;(function(n){n.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"})(vs||(vs={}));var Co;(function(n){n.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",n.JOB_STATE_QUEUED="JOB_STATE_QUEUED",n.JOB_STATE_PENDING="JOB_STATE_PENDING",n.JOB_STATE_RUNNING="JOB_STATE_RUNNING",n.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",n.JOB_STATE_FAILED="JOB_STATE_FAILED",n.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",n.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",n.JOB_STATE_PAUSED="JOB_STATE_PAUSED",n.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",n.JOB_STATE_UPDATING="JOB_STATE_UPDATING",n.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(Co||(Co={}));var ws;(function(n){n.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",n.TUNING_TASK_I2V="TUNING_TASK_I2V",n.TUNING_TASK_T2V="TUNING_TASK_T2V",n.TUNING_TASK_R2V="TUNING_TASK_R2V"})(ws||(ws={}));var Ts;(function(n){n.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",n.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",n.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",n.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(Ts||(Ts={}));var Cs;(function(n){n.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",n.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",n.BALANCED="BALANCED",n.PRIORITIZE_COST="PRIORITIZE_COST"})(Cs||(Cs={}));var _s;(function(n){n.UNSPECIFIED="UNSPECIFIED",n.BLOCKING="BLOCKING",n.NON_BLOCKING="NON_BLOCKING"})(_s||(_s={}));var Ss;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(Ss||(Ss={}));var As;(function(n){n.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",n.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(As||(As={}));var nn;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.AUTO="AUTO",n.ANY="ANY",n.NONE="NONE",n.VALIDATED="VALIDATED"})(nn||(nn={}));var xs;(function(n){n.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",n.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",n.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",n.BLOCK_NONE="BLOCK_NONE"})(xs||(xs={}));var Ps;(function(n){n.DONT_ALLOW="DONT_ALLOW",n.ALLOW_ADULT="ALLOW_ADULT",n.ALLOW_ALL="ALLOW_ALL"})(Ps||(Ps={}));var Ns;(function(n){n.auto="auto",n.en="en",n.ja="ja",n.ko="ko",n.hi="hi",n.zh="zh",n.pt="pt",n.es="es"})(Ns||(Ns={}));var $s;(function(n){n.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",n.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",n.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",n.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",n.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})($s||($s={}));var Gs;(function(n){n.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",n.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",n.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",n.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(Gs||(Gs={}));var Rs;(function(n){n.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",n.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",n.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",n.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(Rs||(Rs={}));var Ms;(function(n){n.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",n.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",n.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",n.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",n.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",n.EDIT_MODE_STYLE="EDIT_MODE_STYLE",n.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",n.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(Ms||(Ms={}));var Ds;(function(n){n.FOREGROUND="FOREGROUND",n.BACKGROUND="BACKGROUND",n.PROMPT="PROMPT",n.SEMANTIC="SEMANTIC",n.INTERACTIVE="INTERACTIVE"})(Ds||(Ds={}));var ks;(function(n){n.ASSET="ASSET",n.STYLE="STYLE"})(ks||(ks={}));var Ls;(function(n){n.INSERT="INSERT",n.REMOVE="REMOVE",n.REMOVE_STATIC="REMOVE_STATIC",n.OUTPAINT="OUTPAINT"})(Ls||(Ls={}));var Us;(function(n){n.OPTIMIZED="OPTIMIZED",n.LOSSLESS="LOSSLESS"})(Us||(Us={}));var Fs;(function(n){n.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",n.PREFERENCE_TUNING="PREFERENCE_TUNING"})(Fs||(Fs={}));var Hs;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.STATE_PENDING="STATE_PENDING",n.STATE_ACTIVE="STATE_ACTIVE",n.STATE_FAILED="STATE_FAILED"})(Hs||(Hs={}));var Vs;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.PROCESSING="PROCESSING",n.ACTIVE="ACTIVE",n.FAILED="FAILED"})(Vs||(Vs={}));var Bs;(function(n){n.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",n.UPLOADED="UPLOADED",n.GENERATED="GENERATED"})(Bs||(Bs={}));var qs;(function(n){n.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",n.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",n.RESPONSE_REJECTED="RESPONSE_REJECTED",n.NEED_MORE_INPUT="NEED_MORE_INPUT"})(qs||(qs={}));var Os;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.VIDEO="VIDEO",n.AUDIO="AUDIO",n.DOCUMENT="DOCUMENT"})(Os||(Os={}));var zs;(function(n){n.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",n.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",n.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(zs||(zs={}));var Js;(function(n){n.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",n.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",n.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(Js||(Js={}));var Ws;(function(n){n.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",n.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",n.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(Ws||(Ws={}));var Ks;(function(n){n.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",n.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",n.NO_INTERRUPTION="NO_INTERRUPTION"})(Ks||(Ks={}));var Xs;(function(n){n.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",n.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",n.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT"})(Xs||(Xs={}));var Ys;(function(n){n.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",n.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",n.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",n.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",n.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",n.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",n.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",n.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",n.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",n.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",n.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",n.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",n.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(Ys||(Ys={}));var Qs;(function(n){n.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",n.QUALITY="QUALITY",n.DIVERSITY="DIVERSITY",n.VOCALIZATION="VOCALIZATION"})(Qs||(Qs={}));var ut;(function(n){n.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",n.PLAY="PLAY",n.PAUSE="PAUSE",n.STOP="STOP",n.RESET_CONTEXT="RESET_CONTEXT"})(ut||(ut={}));var xt=class{static{f(this,"HttpResponse")}constructor(e){let t={};for(let o of e.headers.entries())t[o[0]]=o[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}};var je=class{static{f(this,"GenerateContentResponse")}get text(){var e,t,o,i,r,a,c,d;if(((i=(o=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.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 u="",p=!1,m=[];for(let h of(d=(c=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)!==null&&d!==void 0?d:[]){for(let[g,b]of Object.entries(h))g!=="text"&&g!=="thought"&&g!=="thoughtSignature"&&(b!==null||b!==void 0)&&m.push(g);if(typeof h.text=="string"){if(typeof h.thought=="boolean"&&h.thought)continue;p=!0,u+=h.text}}return m.length>0&&console.warn(`there are non-text parts ${m} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),p?u:void 0}get data(){var e,t,o,i,r,a,c,d;if(((i=(o=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.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 u="",p=[];for(let m of(d=(c=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)!==null&&d!==void 0?d:[]){for(let[h,g]of Object.entries(m))h!=="inlineData"&&(g!==null||g!==void 0)&&p.push(h);m.inlineData&&typeof m.inlineData.data=="string"&&(u+=atob(m.inlineData.data))}return p.length>0&&console.warn(`there are non-data parts ${p} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),u.length>0?btoa(u):void 0}get functionCalls(){var e,t,o,i,r,a,c,d;if(((i=(o=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.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 u=(d=(c=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter(p=>p.functionCall).map(p=>p.functionCall).filter(p=>p!==void 0);if(u?.length!==0)return u}get executableCode(){var e,t,o,i,r,a,c,d,u;if(((i=(o=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.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 p=(d=(c=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter(m=>m.executableCode).map(m=>m.executableCode).filter(m=>m!==void 0);if(p?.length!==0)return(u=p?.[0])===null||u===void 0?void 0:u.code}get codeExecutionResult(){var e,t,o,i,r,a,c,d,u;if(((i=(o=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.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 p=(d=(c=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)===null||d===void 0?void 0:d.filter(m=>m.codeExecutionResult).map(m=>m.codeExecutionResult).filter(m=>m!==void 0);if(p?.length!==0)return(u=p?.[0])===null||u===void 0?void 0:u.output}},on=class{static{f(this,"EmbedContentResponse")}},rn=class{static{f(this,"GenerateImagesResponse")}},_o=class{static{f(this,"EditImageResponse")}},So=class{static{f(this,"UpscaleImageResponse")}},Ao=class{static{f(this,"RecontextImageResponse")}},xo=class{static{f(this,"SegmentImageResponse")}},sn=class{static{f(this,"ListModelsResponse")}},an=class{static{f(this,"DeleteModelResponse")}},ln=class{static{f(this,"CountTokensResponse")}},Po=class{static{f(this,"ComputeTokensResponse")}};var cn=class n{static{f(this,"GenerateVideosOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let o=new n,i,r=e;return t?i=ac(r):i=sc(r),Object.assign(o,i),o}},dn=class{static{f(this,"ListTuningJobsResponse")}},un=class{static{f(this,"CancelTuningJobResponse")}},fn=class{static{f(this,"DeleteCachedContentResponse")}},pn=class{static{f(this,"ListCachedContentsResponse")}},No=class{static{f(this,"ListDocumentsResponse")}},$o=class{static{f(this,"ListFileSearchStoresResponse")}},Go=class{static{f(this,"UploadToFileSearchStoreResumableResponse")}};var Ro=class n{static{f(this,"ImportFileOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let o=new n,r=mc(e);return Object.assign(o,r),o}},Mo=class{static{f(this,"ListFilesResponse")}},Do=class{static{f(this,"CreateFileResponse")}},ko=class{static{f(this,"DeleteFileResponse")}};var mn=class{static{f(this,"ListBatchJobsResponse")}};var Lo=class{static{f(this,"LiveServerMessage")}get text(){var e,t,o;let i="",r=!1,a=[];for(let c of(o=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&o!==void 0?o:[]){for(let[d,u]of Object.entries(c))d!=="text"&&d!=="thought"&&u!==null&&a.push(d);if(typeof c.text=="string"){if(typeof c.thought=="boolean"&&c.thought)continue;r=!0,i+=c.text}}return a.length>0&&console.warn(`there are non-text parts ${a} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),r?i:void 0}get data(){var e,t,o;let i="",r=[];for(let a of(o=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&o!==void 0?o:[]){for(let[c,d]of Object.entries(a))c!=="inlineData"&&d!==null&&r.push(c);a.inlineData&&typeof a.inlineData.data=="string"&&(i+=atob(a.inlineData.data))}return r.length>0&&console.warn(`there are non-data parts ${r} 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}};var Uo=class{static{f(this,"LiveMusicServerMessage")}get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var Fo=class n{static{f(this,"UploadToFileSearchStoreOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let o=new n,r=Ta(e);return Object.assign(o,r),o}};function k(n,e){if(!e||typeof e!="string")throw new Error("model is required and must be a string");if(e.includes("..")||e.includes("?")||e.includes("&"))throw new Error("invalid model parameter");if(n.isVertexAI()){if(e.startsWith("publishers/")||e.startsWith("projects/")||e.startsWith("models/"))return e;if(e.indexOf("/")>=0){let t=e.split("/",2);return`publishers/${t[0]}/models/${t[1]}`}else return`publishers/google/models/${e}`}else return e.startsWith("models/")||e.startsWith("tunedModels/")?e:`models/${e}`}f(k,"tModel");function Ca(n,e){let t=k(n,e);return t?t.startsWith("publishers/")&&n.isVertexAI()?`projects/${n.getProject()}/locations/${n.getLocation()}/${t}`:t.startsWith("models/")&&n.isVertexAI()?`projects/${n.getProject()}/locations/${n.getLocation()}/publishers/google/${t}`:t:""}f(Ca,"tCachesModel");function _a(n){return Array.isArray(n)?n.map(e=>hn(e)):[hn(n)]}f(_a,"tBlobs");function hn(n){if(typeof n=="object"&&n!==null)return n;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof n}`)}f(hn,"tBlob");function Sa(n){let e=hn(n);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}f(Sa,"tImageBlob");function Aa(n){let e=hn(n);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}f(Aa,"tAudioBlob");function Zs(n){if(n==null)throw new Error("PartUnion is required");if(typeof n=="object")return n;if(typeof n=="string")return{text:n};throw new Error(`Unsupported part type: ${typeof n}`)}f(Zs,"tPart");function xa(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("PartListUnion is required");return Array.isArray(n)?n.map(e=>Zs(e)):[Zs(n)]}f(xa,"tParts");function Ho(n){return n!=null&&typeof n=="object"&&"parts"in n&&Array.isArray(n.parts)}f(Ho,"_isContent");function js(n){return n!=null&&typeof n=="object"&&"functionCall"in n}f(js,"_isFunctionCallPart");function ea(n){return n!=null&&typeof n=="object"&&"functionResponse"in n}f(ea,"_isFunctionResponsePart");function re(n){if(n==null)throw new Error("ContentUnion is required");return Ho(n)?n:{role:"user",parts:xa(n)}}f(re,"tContent");function wi(n,e){if(!e)return[];if(n.isVertexAI()&&Array.isArray(e))return e.flatMap(t=>{let o=re(t);return o.parts&&o.parts.length>0&&o.parts[0].text!==void 0?[o.parts[0].text]:[]});if(n.isVertexAI()){let t=re(e);return t.parts&&t.parts.length>0&&t.parts[0].text!==void 0?[t.parts[0].text]:[]}return Array.isArray(e)?e.map(t=>re(t)):[re(e)]}f(wi,"tContentsForEmbed");function he(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("contents are required");if(!Array.isArray(n)){if(js(n)||ea(n))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[re(n)]}let e=[],t=[],o=Ho(n[0]);for(let i of n){let r=Ho(i);if(r!=o)throw new 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(r)e.push(i);else{if(js(i)||ea(i))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");t.push(i)}}return o||e.push({role:"user",parts:xa(t)}),e}f(he,"tContents");function Ec(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(o=>o!=="null");if(t.length===1)e.type=Object.values(Fe).includes(t[0].toUpperCase())?t[0].toUpperCase():Fe.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let o of t)e.anyOf.push({type:Object.values(Fe).includes(o.toUpperCase())?o.toUpperCase():Fe.TYPE_UNSPECIFIED})}}f(Ec,"flattenTypeArrayToAnyOf");function ft(n){let e={},t=["items"],o=["anyOf"],i=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let r=n.anyOf;r!=null&&r.length==2&&(r[0].type==="null"?(e.nullable=!0,n=r[1]):r[1].type==="null"&&(e.nullable=!0,n=r[0])),n.type instanceof Array&&Ec(n.type,e);for(let[a,c]of Object.entries(n))if(c!=null)if(a=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(c instanceof Array)continue;e.type=Object.values(Fe).includes(c.toUpperCase())?c.toUpperCase():Fe.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=ft(c);else if(o.includes(a)){let d=[];for(let u of c){if(u.type=="null"){e.nullable=!0;continue}d.push(ft(u))}e[a]=d}else if(i.includes(a)){let d={};for(let[u,p]of Object.entries(c))d[u]=ft(p);e[a]=d}else{if(a==="additionalProperties")continue;e[a]=c}return e}f(ft,"processJsonSchema");function Ti(n){return ft(n)}f(Ti,"tSchema");function Ci(n){if(typeof n=="object")return n;if(typeof n=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:n}}};throw new Error(`Unsupported speechConfig type: ${typeof n}`)}f(Ci,"tSpeechConfig");function _i(n){if("multiSpeakerVoiceConfig"in n)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return n}f(_i,"tLiveSpeechConfig");function gt(n){if(n.functionDeclarations)for(let e of n.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=ft(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=ft(e.response));return n}f(gt,"tTool");function bt(n){if(n==null)throw new Error("tools is required");if(!Array.isArray(n))throw new Error("tools is required and must be an array of Tools");let e=[];for(let t of n)e.push(t);return e}f(bt,"tTools");function Ic(n,e,t,o=1){let i=!e.startsWith(`${t}/`)&&e.split("/").length===o;return n.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${n.getProject()}/${e}`:e.startsWith(`${t}/`)?`projects/${n.getProject()}/locations/${n.getLocation()}/${e}`:i?`projects/${n.getProject()}/locations/${n.getLocation()}/${t}/${e}`:e:i?`${t}/${e}`:e}f(Ic,"resourceName");function De(n,e){if(typeof e!="string")throw new Error("name must be a string");return Ic(n,e,"cachedContents")}f(De,"tCachedContentName");function Pa(n){switch(n){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 n}}f(Pa,"tTuningJobStatus");function He(n){return vi(n)}f(He,"tBytes");function vc(n){return n!=null&&typeof n=="object"&&"name"in n}f(vc,"_isFile");function wc(n){return n!=null&&typeof n=="object"&&"video"in n}f(wc,"isGeneratedVideo");function Tc(n){return n!=null&&typeof n=="object"&&"uri"in n}f(Tc,"isVideo");function Na(n){var e;let t;if(vc(n)&&(t=n.name),!(Tc(n)&&(t=n.uri,t===void 0))&&!(wc(n)&&(t=(e=n.video)===null||e===void 0?void 0:e.uri,t===void 0))){if(typeof n=="string"&&(t=n),t===void 0)throw new Error("Could not extract file name from the provided input.");if(t.startsWith("https://")){let i=t.split("files/")[1].match(/[a-z0-9]+/);if(i===null)throw new Error(`Could not extract file name from URI ${t}`);t=i[0]}else t.startsWith("files/")&&(t=t.split("files/")[1]);return t}}f(Na,"tFileName");function $a(n,e){let t;return n.isVertexAI()?t=e?"publishers/google/models":"models":t=e?"models":"tunedModels",t}f($a,"tModelsUrl");function Ga(n){for(let e of["models","tunedModels","publisherModels"])if(Cc(n,e))return n[e];return[]}f(Ga,"tExtractModels");function Cc(n,e){return n!==null&&typeof n=="object"&&e in n}f(Cc,"hasField");function _c(n,e={}){let t=n,o={name:t.name,description:t.description,parametersJsonSchema:t.inputSchema};return t.outputSchema&&(o.responseJsonSchema=t.outputSchema),e.behavior&&(o.behavior=e.behavior),{functionDeclarations:[o]}}f(_c,"mcpToGeminiTool");function Sc(n,e={}){let t=[],o=new Set;for(let i of n){let r=i.name;if(o.has(r))throw new Error(`Duplicate function name ${r} found in MCP tools. Please ensure function names are unique.`);o.add(r);let a=_c(i,e);a.functionDeclarations&&t.push(...a.functionDeclarations)}return{functionDeclarations:t}}f(Sc,"mcpToolsToGeminiTool");function Ra(n,e){let t;if(typeof e=="string")if(n.isVertexAI())if(e.startsWith("gs://"))t={format:"jsonl",gcsUri:[e]};else if(e.startsWith("bq://"))t={format:"bigquery",bigqueryUri:e};else throw new Error(`Unsupported string source for Vertex AI: ${e}`);else if(e.startsWith("files/"))t={fileName:e};else throw new Error(`Unsupported string source for Gemini API: ${e}`);else if(Array.isArray(e)){if(n.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");t={inlinedRequests:e}}else t=e;let o=[t.gcsUri,t.bigqueryUri].filter(Boolean).length,i=[t.inlinedRequests,t.fileName].filter(Boolean).length;if(n.isVertexAI()){if(i>0||o!==1)throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(o>0||i!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return t}f(Ra,"tBatchJobSource");function Ac(n){if(typeof n!="string")return n;let e=n;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw new Error(`Unsupported destination: ${e}`)}f(Ac,"tBatchJobDestination");function Ma(n){if(typeof n!="object"||n===null)return{};let e=n,t=e.inlinedResponses;if(typeof t!="object"||t===null)return n;let i=t.inlinedResponses;if(!Array.isArray(i)||i.length===0)return n;let r=!1;for(let a of i){if(typeof a!="object"||a===null)continue;let d=a.response;if(typeof d!="object"||d===null)continue;if(d.embedding!==void 0){r=!0;break}}return r&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),n}f(Ma,"tRecvBatchJobDestination");function yt(n,e){let t=e;if(!n.isVertexAI()){if(/batches\/[^/]+$/.test(t))return t.split("/").pop();throw new Error(`Invalid batch job name: ${t}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(t))return t.split("/").pop();if(/^\d+$/.test(t))return t;throw new Error(`Invalid batch job name: ${t}.`)}f(yt,"tBatchJobName");function Da(n){let e=n;return e==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":e==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":e==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":e==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":e==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":e==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":e==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":e}f(Da,"tJobState");function xc(n){let e={},t=s(n,["responsesFile"]);t!=null&&l(e,["fileName"],t);let o=s(n,["inlinedResponses","inlinedResponses"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>ld(a))),l(e,["inlinedResponses"],r)}let i=s(n,["inlinedEmbedContentResponses","inlinedResponses"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["inlinedEmbedContentResponses"],r)}return e}f(xc,"batchJobDestinationFromMldev");function Pc(n){let e={},t=s(n,["predictionsFormat"]);t!=null&&l(e,["format"],t);let o=s(n,["gcsDestination","outputUriPrefix"]);o!=null&&l(e,["gcsUri"],o);let i=s(n,["bigqueryDestination","outputUri"]);return i!=null&&l(e,["bigqueryUri"],i),e}f(Pc,"batchJobDestinationFromVertex");function Nc(n){let e={},t=s(n,["format"]);t!=null&&l(e,["predictionsFormat"],t);let o=s(n,["gcsUri"]);o!=null&&l(e,["gcsDestination","outputUriPrefix"],o);let i=s(n,["bigqueryUri"]);if(i!=null&&l(e,["bigqueryDestination","outputUri"],i),s(n,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(s(n,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is not supported in Vertex AI.");if(s(n,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");return e}f(Nc,"batchJobDestinationToVertex");function jt(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["metadata","displayName"]);o!=null&&l(e,["displayName"],o);let i=s(n,["metadata","state"]);i!=null&&l(e,["state"],Da(i));let r=s(n,["metadata","createTime"]);r!=null&&l(e,["createTime"],r);let a=s(n,["metadata","endTime"]);a!=null&&l(e,["endTime"],a);let c=s(n,["metadata","updateTime"]);c!=null&&l(e,["updateTime"],c);let d=s(n,["metadata","model"]);d!=null&&l(e,["model"],d);let u=s(n,["metadata","output"]);return u!=null&&l(e,["dest"],xc(Ma(u))),e}f(jt,"batchJobFromMldev");function Vo(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["displayName"]);o!=null&&l(e,["displayName"],o);let i=s(n,["state"]);i!=null&&l(e,["state"],Da(i));let r=s(n,["error"]);r!=null&&l(e,["error"],r);let a=s(n,["createTime"]);a!=null&&l(e,["createTime"],a);let c=s(n,["startTime"]);c!=null&&l(e,["startTime"],c);let d=s(n,["endTime"]);d!=null&&l(e,["endTime"],d);let u=s(n,["updateTime"]);u!=null&&l(e,["updateTime"],u);let p=s(n,["model"]);p!=null&&l(e,["model"],p);let m=s(n,["inputConfig"]);m!=null&&l(e,["src"],$c(m));let h=s(n,["outputConfig"]);h!=null&&l(e,["dest"],Pc(Ma(h)));let g=s(n,["completionStats"]);return g!=null&&l(e,["completionStats"],g),e}f(Vo,"batchJobFromVertex");function $c(n){let e={},t=s(n,["instancesFormat"]);t!=null&&l(e,["format"],t);let o=s(n,["gcsSource","uris"]);o!=null&&l(e,["gcsUri"],o);let i=s(n,["bigquerySource","inputUri"]);return i!=null&&l(e,["bigqueryUri"],i),e}f($c,"batchJobSourceFromVertex");function Gc(n,e){let t={};if(s(e,["format"])!==void 0)throw new Error("format parameter is not supported in Gemini API.");if(s(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(s(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is not supported in Gemini API.");let o=s(e,["fileName"]);o!=null&&l(t,["fileName"],o);let i=s(e,["inlinedRequests"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>ad(n,a))),l(t,["requests","requests"],r)}return t}f(Gc,"batchJobSourceToMldev");function Rc(n){let e={},t=s(n,["format"]);t!=null&&l(e,["instancesFormat"],t);let o=s(n,["gcsUri"]);o!=null&&l(e,["gcsSource","uris"],o);let i=s(n,["bigqueryUri"]);if(i!=null&&l(e,["bigquerySource","inputUri"],i),s(n,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(s(n,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is not supported in Vertex AI.");return e}f(Rc,"batchJobSourceToVertex");function Mc(n){let e={},t=s(n,["data"]);if(t!=null&&l(e,["data"],t),s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(Mc,"blobToMldev$4");function Dc(n,e){let t={},o=s(e,["name"]);return o!=null&&l(t,["_url","name"],yt(n,o)),t}f(Dc,"cancelBatchJobParametersToMldev");function kc(n,e){let t={},o=s(e,["name"]);return o!=null&&l(t,["_url","name"],yt(n,o)),t}f(kc,"cancelBatchJobParametersToVertex");function Lc(n){let e={},t=s(n,["content"]);t!=null&&l(e,["content"],t);let o=s(n,["citationMetadata"]);o!=null&&l(e,["citationMetadata"],Uc(o));let i=s(n,["tokenCount"]);i!=null&&l(e,["tokenCount"],i);let r=s(n,["finishReason"]);r!=null&&l(e,["finishReason"],r);let a=s(n,["avgLogprobs"]);a!=null&&l(e,["avgLogprobs"],a);let c=s(n,["groundingMetadata"]);c!=null&&l(e,["groundingMetadata"],c);let d=s(n,["index"]);d!=null&&l(e,["index"],d);let u=s(n,["logprobsResult"]);u!=null&&l(e,["logprobsResult"],u);let p=s(n,["safetyRatings"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(g=>g)),l(e,["safetyRatings"],h)}let m=s(n,["urlContextMetadata"]);return m!=null&&l(e,["urlContextMetadata"],m),e}f(Lc,"candidateFromMldev$1");function Uc(n){let e={},t=s(n,["citationSources"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(i=>i)),l(e,["citations"],o)}return e}f(Uc,"citationMetadataFromMldev$1");function ka(n){let e={},t=s(n,["parts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(r=>hd(r))),l(e,["parts"],i)}let o=s(n,["role"]);return o!=null&&l(e,["role"],o),e}f(ka,"contentToMldev$4");function Fc(n,e){let t={},o=s(n,["displayName"]);if(e!==void 0&&o!=null&&l(e,["batch","displayName"],o),s(n,["dest"])!==void 0)throw new Error("dest parameter is not supported in Gemini API.");return t}f(Fc,"createBatchJobConfigToMldev");function Hc(n,e){let t={},o=s(n,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let i=s(n,["dest"]);return e!==void 0&&i!=null&&l(e,["outputConfig"],Nc(Ac(i))),t}f(Hc,"createBatchJobConfigToVertex");function ta(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["src"]);i!=null&&l(t,["batch","inputConfig"],Gc(n,Ra(n,i)));let r=s(e,["config"]);return r!=null&&Fc(r,t),t}f(ta,"createBatchJobParametersToMldev");function Vc(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["model"],k(n,o));let i=s(e,["src"]);i!=null&&l(t,["inputConfig"],Rc(Ra(n,i)));let r=s(e,["config"]);return r!=null&&Hc(r,t),t}f(Vc,"createBatchJobParametersToVertex");function Bc(n,e){let t={},o=s(n,["displayName"]);return e!==void 0&&o!=null&&l(e,["batch","displayName"],o),t}f(Bc,"createEmbeddingsBatchJobConfigToMldev");function qc(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["src"]);i!=null&&l(t,["batch","inputConfig"],Yc(n,i));let r=s(e,["config"]);return r!=null&&Bc(r,t),t}f(qc,"createEmbeddingsBatchJobParametersToMldev");function Oc(n,e){let t={},o=s(e,["name"]);return o!=null&&l(t,["_url","name"],yt(n,o)),t}f(Oc,"deleteBatchJobParametersToMldev");function zc(n,e){let t={},o=s(e,["name"]);return o!=null&&l(t,["_url","name"],yt(n,o)),t}f(zc,"deleteBatchJobParametersToVertex");function Jc(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["name"]);o!=null&&l(e,["name"],o);let i=s(n,["done"]);i!=null&&l(e,["done"],i);let r=s(n,["error"]);return r!=null&&l(e,["error"],r),e}f(Jc,"deleteResourceJobFromMldev");function Wc(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["name"]);o!=null&&l(e,["name"],o);let i=s(n,["done"]);i!=null&&l(e,["done"],i);let r=s(n,["error"]);return r!=null&&l(e,["error"],r),e}f(Wc,"deleteResourceJobFromVertex");function Kc(n,e){let t={},o=s(e,["contents"]);if(o!=null){let r=wi(n,o);Array.isArray(r)&&(r=r.map(a=>a)),l(t,["requests[]","request","content"],r)}let i=s(e,["config"]);return i!=null&&(l(t,["_self"],Xc(i,t)),ic(t,{"requests[].*":"requests[].request.*"})),t}f(Kc,"embedContentBatchToMldev");function Xc(n,e){let t={},o=s(n,["taskType"]);e!==void 0&&o!=null&&l(e,["requests[]","taskType"],o);let i=s(n,["title"]);e!==void 0&&i!=null&&l(e,["requests[]","title"],i);let r=s(n,["outputDimensionality"]);if(e!==void 0&&r!=null&&l(e,["requests[]","outputDimensionality"],r),s(n,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(s(n,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return t}f(Xc,"embedContentConfigToMldev$1");function Yc(n,e){let t={},o=s(e,["fileName"]);o!=null&&l(t,["file_name"],o);let i=s(e,["inlinedRequests"]);return i!=null&&l(t,["requests"],Kc(n,i)),t}f(Yc,"embeddingsBatchJobSourceToMldev");function Qc(n){let e={};if(s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=s(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(Qc,"fileDataToMldev$4");function Zc(n){let e={},t=s(n,["id"]);t!=null&&l(e,["id"],t);let o=s(n,["args"]);o!=null&&l(e,["args"],o);let i=s(n,["name"]);if(i!=null&&l(e,["name"],i),s(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(s(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}f(Zc,"functionCallToMldev$4");function jc(n){let e={},t=s(n,["mode"]);t!=null&&l(e,["mode"],t);let o=s(n,["allowedFunctionNames"]);if(o!=null&&l(e,["allowedFunctionNames"],o),s(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}f(jc,"functionCallingConfigToMldev$2");function ed(n,e,t){let o={},i=s(e,["systemInstruction"]);t!==void 0&&i!=null&&l(t,["systemInstruction"],ka(re(i)));let r=s(e,["temperature"]);r!=null&&l(o,["temperature"],r);let a=s(e,["topP"]);a!=null&&l(o,["topP"],a);let c=s(e,["topK"]);c!=null&&l(o,["topK"],c);let d=s(e,["candidateCount"]);d!=null&&l(o,["candidateCount"],d);let u=s(e,["maxOutputTokens"]);u!=null&&l(o,["maxOutputTokens"],u);let p=s(e,["stopSequences"]);p!=null&&l(o,["stopSequences"],p);let m=s(e,["responseLogprobs"]);m!=null&&l(o,["responseLogprobs"],m);let h=s(e,["logprobs"]);h!=null&&l(o,["logprobs"],h);let g=s(e,["presencePenalty"]);g!=null&&l(o,["presencePenalty"],g);let b=s(e,["frequencyPenalty"]);b!=null&&l(o,["frequencyPenalty"],b);let E=s(e,["seed"]);E!=null&&l(o,["seed"],E);let I=s(e,["responseMimeType"]);I!=null&&l(o,["responseMimeType"],I);let v=s(e,["responseSchema"]);v!=null&&l(o,["responseSchema"],Ti(v));let w=s(e,["responseJsonSchema"]);if(w!=null&&l(o,["responseJsonSchema"],w),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");let T=s(e,["safetySettings"]);if(t!==void 0&&T!=null){let B=T;Array.isArray(B)&&(B=B.map(_e=>gd(_e))),l(t,["safetySettings"],B)}let _=s(e,["tools"]);if(t!==void 0&&_!=null){let B=bt(_);Array.isArray(B)&&(B=B.map(_e=>yd(gt(_e)))),l(t,["tools"],B)}let A=s(e,["toolConfig"]);if(t!==void 0&&A!=null&&l(t,["toolConfig"],bd(A)),s(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let R=s(e,["cachedContent"]);t!==void 0&&R!=null&&l(t,["cachedContent"],De(n,R));let N=s(e,["responseModalities"]);N!=null&&l(o,["responseModalities"],N);let H=s(e,["mediaResolution"]);H!=null&&l(o,["mediaResolution"],H);let x=s(e,["speechConfig"]);if(x!=null&&l(o,["speechConfig"],Ci(x)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let D=s(e,["thinkingConfig"]);D!=null&&l(o,["thinkingConfig"],D);let J=s(e,["imageConfig"]);J!=null&&l(o,["imageConfig"],sd(J));let Pe=s(e,["enableEnhancedCivicAnswers"]);return Pe!=null&&l(o,["enableEnhancedCivicAnswers"],Pe),o}f(ed,"generateContentConfigToMldev$1");function td(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["candidates"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(u=>Lc(u))),l(e,["candidates"],d)}let i=s(n,["modelVersion"]);i!=null&&l(e,["modelVersion"],i);let r=s(n,["promptFeedback"]);r!=null&&l(e,["promptFeedback"],r);let a=s(n,["responseId"]);a!=null&&l(e,["responseId"],a);let c=s(n,["usageMetadata"]);return c!=null&&l(e,["usageMetadata"],c),e}f(td,"generateContentResponseFromMldev$1");function nd(n,e){let t={},o=s(e,["name"]);return o!=null&&l(t,["_url","name"],yt(n,o)),t}f(nd,"getBatchJobParametersToMldev");function od(n,e){let t={},o=s(e,["name"]);return o!=null&&l(t,["_url","name"],yt(n,o)),t}f(od,"getBatchJobParametersToVertex");function id(n){let e={};if(s(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=s(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}f(id,"googleMapsToMldev$4");function rd(n){let e={};if(s(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(s(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=s(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}f(rd,"googleSearchToMldev$4");function sd(n){let e={},t=s(n,["aspectRatio"]);t!=null&&l(e,["aspectRatio"],t);let o=s(n,["imageSize"]);if(o!=null&&l(e,["imageSize"],o),s(n,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(s(n,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}f(sd,"imageConfigToMldev$1");function ad(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["request","model"],k(n,o));let i=s(e,["contents"]);if(i!=null){let c=he(i);Array.isArray(c)&&(c=c.map(d=>ka(d))),l(t,["request","contents"],c)}let r=s(e,["metadata"]);r!=null&&l(t,["metadata"],r);let a=s(e,["config"]);return a!=null&&l(t,["request","generationConfig"],ed(n,a,s(t,["request"],{}))),t}f(ad,"inlinedRequestToMldev");function ld(n){let e={},t=s(n,["response"]);t!=null&&l(e,["response"],td(t));let o=s(n,["error"]);return o!=null&&l(e,["error"],o),e}f(ld,"inlinedResponseFromMldev");function cd(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);if(e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),s(n,["filter"])!==void 0)throw new Error("filter parameter is not supported in Gemini API.");return t}f(cd,"listBatchJobsConfigToMldev");function dd(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);e!==void 0&&i!=null&&l(e,["_query","pageToken"],i);let r=s(n,["filter"]);return e!==void 0&&r!=null&&l(e,["_query","filter"],r),t}f(dd,"listBatchJobsConfigToVertex");function ud(n){let e={},t=s(n,["config"]);return t!=null&&cd(t,e),e}f(ud,"listBatchJobsParametersToMldev");function fd(n){let e={},t=s(n,["config"]);return t!=null&&dd(t,e),e}f(fd,"listBatchJobsParametersToVertex");function pd(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(n,["operations"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>jt(a))),l(e,["batchJobs"],r)}return e}f(pd,"listBatchJobsResponseFromMldev");function md(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(n,["batchPredictionJobs"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>Vo(a))),l(e,["batchJobs"],r)}return e}f(md,"listBatchJobsResponseFromVertex");function hd(n){let e={},t=s(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let o=s(n,["codeExecutionResult"]);o!=null&&l(e,["codeExecutionResult"],o);let i=s(n,["executableCode"]);i!=null&&l(e,["executableCode"],i);let r=s(n,["fileData"]);r!=null&&l(e,["fileData"],Qc(r));let a=s(n,["functionCall"]);a!=null&&l(e,["functionCall"],Zc(a));let c=s(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=s(n,["inlineData"]);d!=null&&l(e,["inlineData"],Mc(d));let u=s(n,["text"]);u!=null&&l(e,["text"],u);let p=s(n,["thought"]);p!=null&&l(e,["thought"],p);let m=s(n,["thoughtSignature"]);m!=null&&l(e,["thoughtSignature"],m);let h=s(n,["videoMetadata"]);return h!=null&&l(e,["videoMetadata"],h),e}f(hd,"partToMldev$4");function gd(n){let e={},t=s(n,["category"]);if(t!=null&&l(e,["category"],t),s(n,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let o=s(n,["threshold"]);return o!=null&&l(e,["threshold"],o),e}f(gd,"safetySettingToMldev$1");function bd(n){let e={},t=s(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],jc(t));let o=s(n,["retrievalConfig"]);return o!=null&&l(e,["retrievalConfig"],o),e}f(bd,"toolConfigToMldev$2");function yd(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let p=t;Array.isArray(p)&&(p=p.map(m=>m)),l(e,["functionDeclarations"],p)}if(s(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let o=s(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let i=s(n,["computerUse"]);i!=null&&l(e,["computerUse"],i);let r=s(n,["fileSearch"]);r!=null&&l(e,["fileSearch"],r);let a=s(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),s(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=s(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],id(c));let d=s(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],rd(d));let u=s(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}f(yd,"toolToMldev$4");var Re;(function(n){n.PAGED_ITEM_BATCH_JOBS="batchJobs",n.PAGED_ITEM_MODELS="models",n.PAGED_ITEM_TUNING_JOBS="tuningJobs",n.PAGED_ITEM_FILES="files",n.PAGED_ITEM_CACHED_CONTENTS="cachedContents",n.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",n.PAGED_ITEM_DOCUMENTS="documents"})(Re||(Re={}));var Me=class{static{f(this,"Pager")}constructor(e,t,o,i){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,o,i)}init(e,t,o){var i,r;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=t?.sdkHttpResponse,this.idxInternal=0;let a={config:{}};!o||Object.keys(o).length===0?a={config:{}}:typeof o=="object"?a=Object.assign({},o):a=o,a.config&&(a.config.pageToken=t.nextPageToken),this.paramsInternal=a,this.pageInternalSize=(r=(i=a.config)===null||i===void 0?void 0:i.pageSize)!==null&&r!==void 0?r:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,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(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:f(async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},"next"),return:f(async()=>({value:void 0,done:!0}),"return")}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}};var Bo=class extends Te{static{f(this,"Batches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Me(Re.PAGED_ITEM_BATCH_JOBS,o=>this.listInternal(o),await this.listInternal(t),t),this.create=async t=>(this.apiClient.isVertexAI()&&(t.config=this.formatDestination(t.src,t.config)),this.createInternal(t)),this.createEmbeddings=async t=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Vertex AI does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(t)}}createInlinedGenerateContentRequest(e){let t=ta(this.apiClient,e),o=t._url,i=C("{model}:batchGenerateContent",o),c=t.batch.inputConfig.requests,d=c.requests,u=[];for(let p of d){let m=Object.assign({},p);if(m.systemInstruction){let h=m.systemInstruction;delete m.systemInstruction;let g=m.request;g.systemInstruction=h,m.request=g}u.push(m)}return c.requests=u,delete t.config,delete t._url,delete t._query,{path:i,body:t}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,t){let o=t?Object.assign({},t):{},i=Date.now().toString();if(o.displayName||(o.displayName=`genaiBatchJob_${i}`),o.dest===void 0){let r=this.getGcsUri(e),a=this.getBigqueryUri(e);if(r)r.endsWith(".jsonl")?o.dest=`${r.slice(0,-6)}/dest`:o.dest=`${r}_dest_${i}`;else if(a)o.dest=`${a}_dest_${i}`;else throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.")}return o}async createInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Vc(this.apiClient,e);return c=C("batchPredictionJobs",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),a.then(p=>Vo(p))}else{let u=ta(this.apiClient,e);return c=C("{model}:batchGenerateContent",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),a.then(p=>jt(p))}}async createEmbeddingsInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=qc(this.apiClient,e);return r=C("{model}:asyncBatchEmbedContent",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>jt(d))}}async get(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=od(this.apiClient,e);return c=C("batchPredictionJobs/{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),a.then(p=>Vo(p))}else{let u=nd(this.apiClient,e);return c=C("batches/{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),a.then(p=>jt(p))}}async cancel(e){var t,o,i,r;let a="",c={};if(this.apiClient.isVertexAI()){let d=kc(this.apiClient,e);a=C("batchPredictionJobs/{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,await this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}else{let d=Dc(this.apiClient,e);a=C("batches/{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,await this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}}async listInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=fd(e);return c=C("batchPredictionJobs",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=md(p),h=new mn;return Object.assign(h,m),h})}else{let u=ud(e);return c=C("batches",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=pd(p),h=new mn;return Object.assign(h,m),h})}}async delete(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=zc(this.apiClient,e);return c=C("batchPredictionJobs/{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>Wc(p))}else{let u=Oc(this.apiClient,e);return c=C("batches/{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>Jc(p))}}};function Ed(n){let e={},t=s(n,["data"]);if(t!=null&&l(e,["data"],t),s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(Ed,"blobToMldev$3");function na(n){let e={},t=s(n,["parts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(r=>Bd(r))),l(e,["parts"],i)}let o=s(n,["role"]);return o!=null&&l(e,["role"],o),e}f(na,"contentToMldev$3");function Id(n,e){let t={},o=s(n,["ttl"]);e!==void 0&&o!=null&&l(e,["ttl"],o);let i=s(n,["expireTime"]);e!==void 0&&i!=null&&l(e,["expireTime"],i);let r=s(n,["displayName"]);e!==void 0&&r!=null&&l(e,["displayName"],r);let a=s(n,["contents"]);if(e!==void 0&&a!=null){let p=he(a);Array.isArray(p)&&(p=p.map(m=>na(m))),l(e,["contents"],p)}let c=s(n,["systemInstruction"]);e!==void 0&&c!=null&&l(e,["systemInstruction"],na(re(c)));let d=s(n,["tools"]);if(e!==void 0&&d!=null){let p=d;Array.isArray(p)&&(p=p.map(m=>Od(m))),l(e,["tools"],p)}let u=s(n,["toolConfig"]);if(e!==void 0&&u!=null&&l(e,["toolConfig"],qd(u)),s(n,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return t}f(Id,"createCachedContentConfigToMldev");function vd(n,e){let t={},o=s(n,["ttl"]);e!==void 0&&o!=null&&l(e,["ttl"],o);let i=s(n,["expireTime"]);e!==void 0&&i!=null&&l(e,["expireTime"],i);let r=s(n,["displayName"]);e!==void 0&&r!=null&&l(e,["displayName"],r);let a=s(n,["contents"]);if(e!==void 0&&a!=null){let m=he(a);Array.isArray(m)&&(m=m.map(h=>h)),l(e,["contents"],m)}let c=s(n,["systemInstruction"]);e!==void 0&&c!=null&&l(e,["systemInstruction"],re(c));let d=s(n,["tools"]);if(e!==void 0&&d!=null){let m=d;Array.isArray(m)&&(m=m.map(h=>zd(h))),l(e,["tools"],m)}let u=s(n,["toolConfig"]);e!==void 0&&u!=null&&l(e,["toolConfig"],u);let p=s(n,["kmsKeyName"]);return e!==void 0&&p!=null&&l(e,["encryption_spec","kmsKeyName"],p),t}f(vd,"createCachedContentConfigToVertex");function wd(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["model"],Ca(n,o));let i=s(e,["config"]);return i!=null&&Id(i,t),t}f(wd,"createCachedContentParametersToMldev");function Td(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["model"],Ca(n,o));let i=s(e,["config"]);return i!=null&&vd(i,t),t}f(Td,"createCachedContentParametersToVertex");function Cd(n,e){let t={},o=s(e,["name"]);return o!=null&&l(t,["_url","name"],De(n,o)),t}f(Cd,"deleteCachedContentParametersToMldev");function _d(n,e){let t={},o=s(e,["name"]);return o!=null&&l(t,["_url","name"],De(n,o)),t}f(_d,"deleteCachedContentParametersToVertex");function Sd(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}f(Sd,"deleteCachedContentResponseFromMldev");function Ad(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}f(Ad,"deleteCachedContentResponseFromVertex");function xd(n){let e={};if(s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=s(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(xd,"fileDataToMldev$3");function Pd(n){let e={},t=s(n,["id"]);t!=null&&l(e,["id"],t);let o=s(n,["args"]);o!=null&&l(e,["args"],o);let i=s(n,["name"]);if(i!=null&&l(e,["name"],i),s(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(s(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}f(Pd,"functionCallToMldev$3");function Nd(n){let e={},t=s(n,["mode"]);t!=null&&l(e,["mode"],t);let o=s(n,["allowedFunctionNames"]);if(o!=null&&l(e,["allowedFunctionNames"],o),s(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}f(Nd,"functionCallingConfigToMldev$1");function $d(n){let e={};if(s(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=s(n,["description"]);t!=null&&l(e,["description"],t);let o=s(n,["name"]);o!=null&&l(e,["name"],o);let i=s(n,["parameters"]);i!=null&&l(e,["parameters"],i);let r=s(n,["parametersJsonSchema"]);r!=null&&l(e,["parametersJsonSchema"],r);let a=s(n,["response"]);a!=null&&l(e,["response"],a);let c=s(n,["responseJsonSchema"]);return c!=null&&l(e,["responseJsonSchema"],c),e}f($d,"functionDeclarationToVertex$2");function Gd(n,e){let t={},o=s(e,["name"]);return o!=null&&l(t,["_url","name"],De(n,o)),t}f(Gd,"getCachedContentParametersToMldev");function Rd(n,e){let t={},o=s(e,["name"]);return o!=null&&l(t,["_url","name"],De(n,o)),t}f(Rd,"getCachedContentParametersToVertex");function Md(n){let e={};if(s(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=s(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}f(Md,"googleMapsToMldev$3");function Dd(n){let e={};if(s(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(s(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=s(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}f(Dd,"googleSearchToMldev$3");function kd(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),t}f(kd,"listCachedContentsConfigToMldev");function Ld(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),t}f(Ld,"listCachedContentsConfigToVertex");function Ud(n){let e={},t=s(n,["config"]);return t!=null&&kd(t,e),e}f(Ud,"listCachedContentsParametersToMldev");function Fd(n){let e={},t=s(n,["config"]);return t!=null&&Ld(t,e),e}f(Fd,"listCachedContentsParametersToVertex");function Hd(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(n,["cachedContents"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["cachedContents"],r)}return e}f(Hd,"listCachedContentsResponseFromMldev");function Vd(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(n,["cachedContents"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["cachedContents"],r)}return e}f(Vd,"listCachedContentsResponseFromVertex");function Bd(n){let e={},t=s(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let o=s(n,["codeExecutionResult"]);o!=null&&l(e,["codeExecutionResult"],o);let i=s(n,["executableCode"]);i!=null&&l(e,["executableCode"],i);let r=s(n,["fileData"]);r!=null&&l(e,["fileData"],xd(r));let a=s(n,["functionCall"]);a!=null&&l(e,["functionCall"],Pd(a));let c=s(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=s(n,["inlineData"]);d!=null&&l(e,["inlineData"],Ed(d));let u=s(n,["text"]);u!=null&&l(e,["text"],u);let p=s(n,["thought"]);p!=null&&l(e,["thought"],p);let m=s(n,["thoughtSignature"]);m!=null&&l(e,["thoughtSignature"],m);let h=s(n,["videoMetadata"]);return h!=null&&l(e,["videoMetadata"],h),e}f(Bd,"partToMldev$3");function qd(n){let e={},t=s(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],Nd(t));let o=s(n,["retrievalConfig"]);return o!=null&&l(e,["retrievalConfig"],o),e}f(qd,"toolConfigToMldev$1");function Od(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let p=t;Array.isArray(p)&&(p=p.map(m=>m)),l(e,["functionDeclarations"],p)}if(s(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let o=s(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let i=s(n,["computerUse"]);i!=null&&l(e,["computerUse"],i);let r=s(n,["fileSearch"]);r!=null&&l(e,["fileSearch"],r);let a=s(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),s(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=s(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],Md(c));let d=s(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],Dd(d));let u=s(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}f(Od,"toolToMldev$3");function zd(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let m=t;Array.isArray(m)&&(m=m.map(h=>$d(h))),l(e,["functionDeclarations"],m)}let o=s(n,["retrieval"]);o!=null&&l(e,["retrieval"],o);let i=s(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let r=s(n,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let a=s(n,["codeExecution"]);a!=null&&l(e,["codeExecution"],a);let c=s(n,["enterpriseWebSearch"]);c!=null&&l(e,["enterpriseWebSearch"],c);let d=s(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],d);let u=s(n,["googleSearch"]);u!=null&&l(e,["googleSearch"],u);let p=s(n,["urlContext"]);return p!=null&&l(e,["urlContext"],p),e}f(zd,"toolToVertex$2");function Jd(n,e){let t={},o=s(n,["ttl"]);e!==void 0&&o!=null&&l(e,["ttl"],o);let i=s(n,["expireTime"]);return e!==void 0&&i!=null&&l(e,["expireTime"],i),t}f(Jd,"updateCachedContentConfigToMldev");function Wd(n,e){let t={},o=s(n,["ttl"]);e!==void 0&&o!=null&&l(e,["ttl"],o);let i=s(n,["expireTime"]);return e!==void 0&&i!=null&&l(e,["expireTime"],i),t}f(Wd,"updateCachedContentConfigToVertex");function Kd(n,e){let t={},o=s(e,["name"]);o!=null&&l(t,["_url","name"],De(n,o));let i=s(e,["config"]);return i!=null&&Jd(i,t),t}f(Kd,"updateCachedContentParametersToMldev");function Xd(n,e){let t={},o=s(e,["name"]);o!=null&&l(t,["_url","name"],De(n,o));let i=s(e,["config"]);return i!=null&&Wd(i,t),t}f(Xd,"updateCachedContentParametersToVertex");var qo=class extends Te{static{f(this,"Caches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Me(Re.PAGED_ITEM_CACHED_CONTENTS,o=>this.listInternal(o),await this.listInternal(t),t)}async create(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Td(this.apiClient,e);return c=C("cachedContents",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),a.then(p=>p)}else{let u=wd(this.apiClient,e);return c=C("cachedContents",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),a.then(p=>p)}}async get(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Rd(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),a.then(p=>p)}else{let u=Gd(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),a.then(p=>p)}}async delete(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=_d(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=Ad(p),h=new fn;return Object.assign(h,m),h})}else{let u=Cd(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=Sd(p),h=new fn;return Object.assign(h,m),h})}}async update(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Xd(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),a.then(p=>p)}else{let u=Kd(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),a.then(p=>p)}}async listInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Fd(e);return c=C("cachedContents",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=Vd(p),h=new pn;return Object.assign(h,m),h})}else{let u=Ud(e);return c=C("cachedContents",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=Hd(p),h=new pn;return Object.assign(h,m),h})}}};function gn(n,e){var t={};for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,o=Object.getOwnPropertySymbols(n);i<o.length;i++)e.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(n,o[i])&&(t[o[i]]=n[o[i]]);return t}f(gn,"__rest");function oa(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],o=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:f(function(){return n&&o>=n.length&&(n=void 0),{value:n&&n[o++],done:!n}},"next")};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}f(oa,"__values");function $(n){return this instanceof $?(this.v=n,this):new $(n)}f($,"__await");function ve(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=t.apply(n,e||[]),i,r=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",a),i[Symbol.asyncIterator]=function(){return this},i;function a(g){return function(b){return Promise.resolve(b).then(g,m)}}function c(g,b){o[g]&&(i[g]=function(E){return new Promise(function(I,v){r.push([g,E,I,v])>1||d(g,E)})},b&&(i[g]=b(i[g])))}function d(g,b){try{u(o[g](b))}catch(E){h(r[0][3],E)}}function u(g){g.value instanceof $?Promise.resolve(g.value.v).then(p,m):h(r[0][2],g)}function p(g){d("next",g)}function m(g){d("throw",g)}function h(g,b){g(b),r.shift(),r.length&&d(r[0][0],r[0][1])}}f(ve,"__asyncGenerator");function we(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof oa=="function"?oa(n):n[Symbol.iterator](),t={},o("next"),o("throw"),o("return"),t[Symbol.asyncIterator]=function(){return this},t);function o(r){t[r]=n[r]&&function(a){return new Promise(function(c,d){a=n[r](a),i(c,d,a.done,a.value)})}}function i(r,a,c,d){Promise.resolve(d).then(function(u){r({value:u,done:c})},a)}}f(we,"__asyncValues");function Yd(n){var e;if(n.candidates==null||n.candidates.length===0)return!1;let t=(e=n.candidates[0])===null||e===void 0?void 0:e.content;return t===void 0?!1:La(t)}f(Yd,"isValidResponse");function La(n){if(n.parts===void 0||n.parts.length===0)return!1;for(let e of n.parts)if(e===void 0||Object.keys(e).length===0)return!1;return!0}f(La,"isValidContent");function Qd(n){if(n.length!==0){for(let e of n)if(e.role!=="user"&&e.role!=="model")throw new Error(`Role must be user or model, but got ${e.role}.`)}}f(Qd,"validateHistory");function ia(n){if(n===void 0||n.length===0)return[];let e=[],t=n.length,o=0;for(;o<t;)if(n[o].role==="user")e.push(n[o]),o++;else{let i=[],r=!0;for(;o<t&&n[o].role==="model";)i.push(n[o]),r&&!La(n[o])&&(r=!1),o++;r?e.push(...i):e.pop()}return e}f(ia,"extractCuratedHistory");var Oo=class{static{f(this,"Chats")}constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new zo(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},zo=class{static{f(this,"Chat")}constructor(e,t,o,i={},r=[]){this.apiClient=e,this.modelsModule=t,this.model=o,this.config=i,this.history=r,this.sendPromise=Promise.resolve(),Qd(r)}async sendMessage(e){var t;await this.sendPromise;let o=re(e.message),i=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(o),config:(t=e.config)!==null&&t!==void 0?t:this.config});return this.sendPromise=(async()=>{var r,a,c;let d=await i,u=(a=(r=d.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content,p=d.automaticFunctionCallingHistory,m=this.getHistory(!0).length,h=[];p!=null&&(h=(c=p.slice(m))!==null&&c!==void 0?c:[]);let g=u?[u]:[];this.recordHistory(o,g,h)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),i}async sendMessageStream(e){var t;await this.sendPromise;let o=re(e.message),i=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(o),config:(t=e.config)!==null&&t!==void 0?t:this.config});this.sendPromise=i.then(()=>{}).catch(()=>{});let r=await i;return this.processStreamResponse(r,o)}getHistory(e=!1){let t=e?ia(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return ve(this,arguments,f(function*(){var i,r,a,c,d,u;let p=[];try{for(var m=!0,h=we(e),g;g=yield $(h.next()),i=g.done,!i;m=!0){c=g.value,m=!1;let b=c;if(Yd(b)){let E=(u=(d=b.candidates)===null||d===void 0?void 0:d[0])===null||u===void 0?void 0:u.content;E!==void 0&&p.push(E)}yield yield $(b)}}catch(b){r={error:b}}finally{try{!m&&!i&&(a=h.return)&&(yield $(a.call(h)))}finally{if(r)throw r.error}}this.recordHistory(t,p)},"processStreamResponse_1"))}recordHistory(e,t,o){let i=[];t.length>0&&t.every(r=>r.role!==void 0)?i=t:i.push({role:"model",parts:[]}),o&&o.length>0?this.history.push(...ia(o)):this.history.push(e),this.history.push(...i)}};var bn=class n extends Error{static{f(this,"ApiError")}constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,n.prototype)}};function Zd(n){let e={},t=s(n,["file"]);return t!=null&&l(e,["file"],t),e}f(Zd,"createFileParametersToMldev");function jd(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}f(jd,"createFileResponseFromMldev");function eu(n){let e={},t=s(n,["name"]);return t!=null&&l(e,["_url","file"],Na(t)),e}f(eu,"deleteFileParametersToMldev");function tu(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}f(tu,"deleteFileResponseFromMldev");function nu(n){let e={},t=s(n,["name"]);return t!=null&&l(e,["_url","file"],Na(t)),e}f(nu,"getFileParametersToMldev");function ou(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),t}f(ou,"listFilesConfigToMldev");function iu(n){let e={},t=s(n,["config"]);return t!=null&&ou(t,e),e}f(iu,"listFilesParametersToMldev");function ru(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(n,["files"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["files"],r)}return e}f(ru,"listFilesResponseFromMldev");var Jo=class extends Te{static{f(this,"Files")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Me(Re.PAGED_ITEM_FILES,o=>this.listInternal(o),await this.listInternal(t),t)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(t=>t)}async download(e){await this.apiClient.downloadFile(e)}async listInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=iu(e);return r=C("files",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>{let u=ru(d),p=new Mo;return Object.assign(p,u),p})}}async createInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Zd(e);return r=C("upload/v1beta/files",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=jd(d),p=new Do;return Object.assign(p,u),p})}}async get(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=nu(e);return r=C("files/{file}",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>d)}}async delete(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=eu(e);return r=C("files/{file}",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>{let u=tu(d),p=new ko;return Object.assign(p,u),p})}}};function en(n){let e={},t=s(n,["data"]);if(t!=null&&l(e,["data"],t),s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(en,"blobToMldev$2");function su(n){let e={},t=s(n,["parts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(r=>wu(r))),l(e,["parts"],i)}let o=s(n,["role"]);return o!=null&&l(e,["role"],o),e}f(su,"contentToMldev$2");function au(n){let e={};if(s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=s(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(au,"fileDataToMldev$2");function lu(n){let e={},t=s(n,["id"]);t!=null&&l(e,["id"],t);let o=s(n,["args"]);o!=null&&l(e,["args"],o);let i=s(n,["name"]);if(i!=null&&l(e,["name"],i),s(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(s(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}f(lu,"functionCallToMldev$2");function cu(n){let e={};if(s(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=s(n,["description"]);t!=null&&l(e,["description"],t);let o=s(n,["name"]);o!=null&&l(e,["name"],o);let i=s(n,["parameters"]);i!=null&&l(e,["parameters"],i);let r=s(n,["parametersJsonSchema"]);r!=null&&l(e,["parametersJsonSchema"],r);let a=s(n,["response"]);a!=null&&l(e,["response"],a);let c=s(n,["responseJsonSchema"]);return c!=null&&l(e,["responseJsonSchema"],c),e}f(cu,"functionDeclarationToVertex$1");function du(n){let e={},t=s(n,["modelSelectionConfig"]);t!=null&&l(e,["modelConfig"],t);let o=s(n,["responseJsonSchema"]);o!=null&&l(e,["responseJsonSchema"],o);let i=s(n,["audioTimestamp"]);i!=null&&l(e,["audioTimestamp"],i);let r=s(n,["candidateCount"]);r!=null&&l(e,["candidateCount"],r);let a=s(n,["enableAffectiveDialog"]);a!=null&&l(e,["enableAffectiveDialog"],a);let c=s(n,["frequencyPenalty"]);c!=null&&l(e,["frequencyPenalty"],c);let d=s(n,["logprobs"]);d!=null&&l(e,["logprobs"],d);let u=s(n,["maxOutputTokens"]);u!=null&&l(e,["maxOutputTokens"],u);let p=s(n,["mediaResolution"]);p!=null&&l(e,["mediaResolution"],p);let m=s(n,["presencePenalty"]);m!=null&&l(e,["presencePenalty"],m);let h=s(n,["responseLogprobs"]);h!=null&&l(e,["responseLogprobs"],h);let g=s(n,["responseMimeType"]);g!=null&&l(e,["responseMimeType"],g);let b=s(n,["responseModalities"]);b!=null&&l(e,["responseModalities"],b);let E=s(n,["responseSchema"]);E!=null&&l(e,["responseSchema"],E);let I=s(n,["routingConfig"]);I!=null&&l(e,["routingConfig"],I);let v=s(n,["seed"]);v!=null&&l(e,["seed"],v);let w=s(n,["speechConfig"]);w!=null&&l(e,["speechConfig"],Ua(w));let T=s(n,["stopSequences"]);T!=null&&l(e,["stopSequences"],T);let _=s(n,["temperature"]);_!=null&&l(e,["temperature"],_);let A=s(n,["thinkingConfig"]);A!=null&&l(e,["thinkingConfig"],A);let R=s(n,["topK"]);R!=null&&l(e,["topK"],R);let N=s(n,["topP"]);if(N!=null&&l(e,["topP"],N),s(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}f(du,"generationConfigToVertex$1");function uu(n){let e={};if(s(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=s(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}f(uu,"googleMapsToMldev$2");function fu(n){let e={};if(s(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(s(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=s(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}f(fu,"googleSearchToMldev$2");function pu(n,e){let t={},o=s(n,["generationConfig"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig"],o);let i=s(n,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let r=s(n,["temperature"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig","temperature"],r);let a=s(n,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let c=s(n,["topK"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","topK"],c);let d=s(n,["maxOutputTokens"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","maxOutputTokens"],d);let u=s(n,["mediaResolution"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","mediaResolution"],u);let p=s(n,["seed"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","seed"],p);let m=s(n,["speechConfig"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","speechConfig"],_i(m));let h=s(n,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let g=s(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=s(n,["systemInstruction"]);e!==void 0&&b!=null&&l(e,["setup","systemInstruction"],su(re(b)));let E=s(n,["tools"]);if(e!==void 0&&E!=null){let R=bt(E);Array.isArray(R)&&(R=R.map(N=>Cu(gt(N)))),l(e,["setup","tools"],R)}let I=s(n,["sessionResumption"]);e!==void 0&&I!=null&&l(e,["setup","sessionResumption"],Tu(I));let v=s(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&l(e,["setup","inputAudioTranscription"],v);let w=s(n,["outputAudioTranscription"]);e!==void 0&&w!=null&&l(e,["setup","outputAudioTranscription"],w);let T=s(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&l(e,["setup","realtimeInputConfig"],T);let _=s(n,["contextWindowCompression"]);e!==void 0&&_!=null&&l(e,["setup","contextWindowCompression"],_);let A=s(n,["proactivity"]);if(e!==void 0&&A!=null&&l(e,["setup","proactivity"],A),s(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}f(pu,"liveConnectConfigToMldev$1");function mu(n,e){let t={},o=s(n,["generationConfig"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig"],du(o));let i=s(n,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let r=s(n,["temperature"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig","temperature"],r);let a=s(n,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let c=s(n,["topK"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","topK"],c);let d=s(n,["maxOutputTokens"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","maxOutputTokens"],d);let u=s(n,["mediaResolution"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","mediaResolution"],u);let p=s(n,["seed"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","seed"],p);let m=s(n,["speechConfig"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","speechConfig"],Ua(_i(m)));let h=s(n,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let g=s(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=s(n,["systemInstruction"]);e!==void 0&&b!=null&&l(e,["setup","systemInstruction"],re(b));let E=s(n,["tools"]);if(e!==void 0&&E!=null){let N=bt(E);Array.isArray(N)&&(N=N.map(H=>_u(gt(H)))),l(e,["setup","tools"],N)}let I=s(n,["sessionResumption"]);e!==void 0&&I!=null&&l(e,["setup","sessionResumption"],I);let v=s(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&l(e,["setup","inputAudioTranscription"],v);let w=s(n,["outputAudioTranscription"]);e!==void 0&&w!=null&&l(e,["setup","outputAudioTranscription"],w);let T=s(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&l(e,["setup","realtimeInputConfig"],T);let _=s(n,["contextWindowCompression"]);e!==void 0&&_!=null&&l(e,["setup","contextWindowCompression"],_);let A=s(n,["proactivity"]);e!==void 0&&A!=null&&l(e,["setup","proactivity"],A);let R=s(n,["explicitVadSignal"]);return e!==void 0&&R!=null&&l(e,["setup","explicitVadSignal"],R),t}f(mu,"liveConnectConfigToVertex");function hu(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["setup","model"],k(n,o));let i=s(e,["config"]);return i!=null&&l(t,["config"],pu(i,t)),t}f(hu,"liveConnectParametersToMldev");function gu(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["setup","model"],k(n,o));let i=s(e,["config"]);return i!=null&&l(t,["config"],mu(i,t)),t}f(gu,"liveConnectParametersToVertex");function bu(n){let e={},t=s(n,["musicGenerationConfig"]);return t!=null&&l(e,["musicGenerationConfig"],t),e}f(bu,"liveMusicSetConfigParametersToMldev");function yu(n){let e={},t=s(n,["weightedPrompts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(i=>i)),l(e,["weightedPrompts"],o)}return e}f(yu,"liveMusicSetWeightedPromptsParametersToMldev");function Eu(n){let e={},t=s(n,["media"]);if(t!=null){let u=_a(t);Array.isArray(u)&&(u=u.map(p=>en(p))),l(e,["mediaChunks"],u)}let o=s(n,["audio"]);o!=null&&l(e,["audio"],en(Aa(o)));let i=s(n,["audioStreamEnd"]);i!=null&&l(e,["audioStreamEnd"],i);let r=s(n,["video"]);r!=null&&l(e,["video"],en(Sa(r)));let a=s(n,["text"]);a!=null&&l(e,["text"],a);let c=s(n,["activityStart"]);c!=null&&l(e,["activityStart"],c);let d=s(n,["activityEnd"]);return d!=null&&l(e,["activityEnd"],d),e}f(Eu,"liveSendRealtimeInputParametersToMldev");function Iu(n){let e={},t=s(n,["media"]);if(t!=null){let u=_a(t);Array.isArray(u)&&(u=u.map(p=>p)),l(e,["mediaChunks"],u)}let o=s(n,["audio"]);o!=null&&l(e,["audio"],Aa(o));let i=s(n,["audioStreamEnd"]);i!=null&&l(e,["audioStreamEnd"],i);let r=s(n,["video"]);r!=null&&l(e,["video"],Sa(r));let a=s(n,["text"]);a!=null&&l(e,["text"],a);let c=s(n,["activityStart"]);c!=null&&l(e,["activityStart"],c);let d=s(n,["activityEnd"]);return d!=null&&l(e,["activityEnd"],d),e}f(Iu,"liveSendRealtimeInputParametersToVertex");function vu(n){let e={},t=s(n,["setupComplete"]);t!=null&&l(e,["setupComplete"],t);let o=s(n,["serverContent"]);o!=null&&l(e,["serverContent"],o);let i=s(n,["toolCall"]);i!=null&&l(e,["toolCall"],i);let r=s(n,["toolCallCancellation"]);r!=null&&l(e,["toolCallCancellation"],r);let a=s(n,["usageMetadata"]);a!=null&&l(e,["usageMetadata"],Su(a));let c=s(n,["goAway"]);c!=null&&l(e,["goAway"],c);let d=s(n,["sessionResumptionUpdate"]);d!=null&&l(e,["sessionResumptionUpdate"],d);let u=s(n,["voiceActivityDetectionSignal"]);return u!=null&&l(e,["voiceActivityDetectionSignal"],u),e}f(vu,"liveServerMessageFromVertex");function wu(n){let e={},t=s(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let o=s(n,["codeExecutionResult"]);o!=null&&l(e,["codeExecutionResult"],o);let i=s(n,["executableCode"]);i!=null&&l(e,["executableCode"],i);let r=s(n,["fileData"]);r!=null&&l(e,["fileData"],au(r));let a=s(n,["functionCall"]);a!=null&&l(e,["functionCall"],lu(a));let c=s(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=s(n,["inlineData"]);d!=null&&l(e,["inlineData"],en(d));let u=s(n,["text"]);u!=null&&l(e,["text"],u);let p=s(n,["thought"]);p!=null&&l(e,["thought"],p);let m=s(n,["thoughtSignature"]);m!=null&&l(e,["thoughtSignature"],m);let h=s(n,["videoMetadata"]);return h!=null&&l(e,["videoMetadata"],h),e}f(wu,"partToMldev$2");function Tu(n){let e={},t=s(n,["handle"]);if(t!=null&&l(e,["handle"],t),s(n,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}f(Tu,"sessionResumptionConfigToMldev$1");function Ua(n){let e={},t=s(n,["voiceConfig"]);t!=null&&l(e,["voiceConfig"],t);let o=s(n,["languageCode"]);if(o!=null&&l(e,["languageCode"],o),s(n,["multiSpeakerVoiceConfig"])!==void 0)throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");return e}f(Ua,"speechConfigToVertex$1");function Cu(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let p=t;Array.isArray(p)&&(p=p.map(m=>m)),l(e,["functionDeclarations"],p)}if(s(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let o=s(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let i=s(n,["computerUse"]);i!=null&&l(e,["computerUse"],i);let r=s(n,["fileSearch"]);r!=null&&l(e,["fileSearch"],r);let a=s(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),s(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=s(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],uu(c));let d=s(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],fu(d));let u=s(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}f(Cu,"toolToMldev$2");function _u(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let m=t;Array.isArray(m)&&(m=m.map(h=>cu(h))),l(e,["functionDeclarations"],m)}let o=s(n,["retrieval"]);o!=null&&l(e,["retrieval"],o);let i=s(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let r=s(n,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let a=s(n,["codeExecution"]);a!=null&&l(e,["codeExecution"],a);let c=s(n,["enterpriseWebSearch"]);c!=null&&l(e,["enterpriseWebSearch"],c);let d=s(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],d);let u=s(n,["googleSearch"]);u!=null&&l(e,["googleSearch"],u);let p=s(n,["urlContext"]);return p!=null&&l(e,["urlContext"],p),e}f(_u,"toolToVertex$1");function Su(n){let e={},t=s(n,["promptTokenCount"]);t!=null&&l(e,["promptTokenCount"],t);let o=s(n,["cachedContentTokenCount"]);o!=null&&l(e,["cachedContentTokenCount"],o);let i=s(n,["candidatesTokenCount"]);i!=null&&l(e,["responseTokenCount"],i);let r=s(n,["toolUsePromptTokenCount"]);r!=null&&l(e,["toolUsePromptTokenCount"],r);let a=s(n,["thoughtsTokenCount"]);a!=null&&l(e,["thoughtsTokenCount"],a);let c=s(n,["totalTokenCount"]);c!=null&&l(e,["totalTokenCount"],c);let d=s(n,["promptTokensDetails"]);if(d!=null){let g=d;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["promptTokensDetails"],g)}let u=s(n,["cacheTokensDetails"]);if(u!=null){let g=u;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["cacheTokensDetails"],g)}let p=s(n,["candidatesTokensDetails"]);if(p!=null){let g=p;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["responseTokensDetails"],g)}let m=s(n,["toolUsePromptTokensDetails"]);if(m!=null){let g=m;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["toolUsePromptTokensDetails"],g)}let h=s(n,["trafficType"]);return h!=null&&l(e,["trafficType"],h),e}f(Su,"usageMetadataFromVertex");function Au(n){let e={},t=s(n,["data"]);if(t!=null&&l(e,["data"],t),s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(Au,"blobToMldev$1");function xu(n){let e={},t=s(n,["content"]);t!=null&&l(e,["content"],t);let o=s(n,["citationMetadata"]);o!=null&&l(e,["citationMetadata"],Pu(o));let i=s(n,["tokenCount"]);i!=null&&l(e,["tokenCount"],i);let r=s(n,["finishReason"]);r!=null&&l(e,["finishReason"],r);let a=s(n,["avgLogprobs"]);a!=null&&l(e,["avgLogprobs"],a);let c=s(n,["groundingMetadata"]);c!=null&&l(e,["groundingMetadata"],c);let d=s(n,["index"]);d!=null&&l(e,["index"],d);let u=s(n,["logprobsResult"]);u!=null&&l(e,["logprobsResult"],u);let p=s(n,["safetyRatings"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(g=>g)),l(e,["safetyRatings"],h)}let m=s(n,["urlContextMetadata"]);return m!=null&&l(e,["urlContextMetadata"],m),e}f(xu,"candidateFromMldev");function Pu(n){let e={},t=s(n,["citationSources"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(i=>i)),l(e,["citations"],o)}return e}f(Pu,"citationMetadataFromMldev");function Nu(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["contents"]);if(i!=null){let r=he(i);Array.isArray(r)&&(r=r.map(a=>a)),l(t,["contents"],r)}return t}f(Nu,"computeTokensParametersToVertex");function $u(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["tokensInfo"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>r)),l(e,["tokensInfo"],i)}return e}f($u,"computeTokensResponseFromVertex");function Gu(n){let e={},t=s(n,["values"]);t!=null&&l(e,["values"],t);let o=s(n,["statistics"]);return o!=null&&l(e,["statistics"],Ru(o)),e}f(Gu,"contentEmbeddingFromVertex");function Ru(n){let e={},t=s(n,["truncated"]);t!=null&&l(e,["truncated"],t);let o=s(n,["token_count"]);return o!=null&&l(e,["tokenCount"],o),e}f(Ru,"contentEmbeddingStatisticsFromVertex");function Rn(n){let e={},t=s(n,["parts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(r=>qf(r))),l(e,["parts"],i)}let o=s(n,["role"]);return o!=null&&l(e,["role"],o),e}f(Rn,"contentToMldev$1");function Mu(n){let e={},t=s(n,["controlType"]);t!=null&&l(e,["controlType"],t);let o=s(n,["enableControlImageComputation"]);return o!=null&&l(e,["computeControl"],o),e}f(Mu,"controlReferenceConfigToVertex");function Du(n){let e={};if(s(n,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is not supported in Gemini API.");if(s(n,["tools"])!==void 0)throw new Error("tools parameter is not supported in Gemini API.");if(s(n,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is not supported in Gemini API.");return e}f(Du,"countTokensConfigToMldev");function ku(n,e){let t={},o=s(n,["systemInstruction"]);e!==void 0&&o!=null&&l(e,["systemInstruction"],re(o));let i=s(n,["tools"]);if(e!==void 0&&i!=null){let a=i;Array.isArray(a)&&(a=a.map(c=>qa(c))),l(e,["tools"],a)}let r=s(n,["generationConfig"]);return e!==void 0&&r!=null&&l(e,["generationConfig"],xf(r)),t}f(ku,"countTokensConfigToVertex");function Lu(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["contents"]);if(i!=null){let a=he(i);Array.isArray(a)&&(a=a.map(c=>Rn(c))),l(t,["contents"],a)}let r=s(e,["config"]);return r!=null&&Du(r),t}f(Lu,"countTokensParametersToMldev");function Uu(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["contents"]);if(i!=null){let a=he(i);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["contents"],a)}let r=s(e,["config"]);return r!=null&&ku(r,t),t}f(Uu,"countTokensParametersToVertex");function Fu(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["totalTokens"]);o!=null&&l(e,["totalTokens"],o);let i=s(n,["cachedContentTokenCount"]);return i!=null&&l(e,["cachedContentTokenCount"],i),e}f(Fu,"countTokensResponseFromMldev");function Hu(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["totalTokens"]);return o!=null&&l(e,["totalTokens"],o),e}f(Hu,"countTokensResponseFromVertex");function Vu(n,e){let t={},o=s(e,["model"]);return o!=null&&l(t,["_url","name"],k(n,o)),t}f(Vu,"deleteModelParametersToMldev");function Bu(n,e){let t={},o=s(e,["model"]);return o!=null&&l(t,["_url","name"],k(n,o)),t}f(Bu,"deleteModelParametersToVertex");function qu(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}f(qu,"deleteModelResponseFromMldev");function Ou(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}f(Ou,"deleteModelResponseFromVertex");function zu(n,e){let t={},o=s(n,["outputGcsUri"]);e!==void 0&&o!=null&&l(e,["parameters","storageUri"],o);let i=s(n,["negativePrompt"]);e!==void 0&&i!=null&&l(e,["parameters","negativePrompt"],i);let r=s(n,["numberOfImages"]);e!==void 0&&r!=null&&l(e,["parameters","sampleCount"],r);let a=s(n,["aspectRatio"]);e!==void 0&&a!=null&&l(e,["parameters","aspectRatio"],a);let c=s(n,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=s(n,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let u=s(n,["safetyFilterLevel"]);e!==void 0&&u!=null&&l(e,["parameters","safetySetting"],u);let p=s(n,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let m=s(n,["includeSafetyAttributes"]);e!==void 0&&m!=null&&l(e,["parameters","includeSafetyAttributes"],m);let h=s(n,["includeRaiReason"]);e!==void 0&&h!=null&&l(e,["parameters","includeRaiReason"],h);let g=s(n,["language"]);e!==void 0&&g!=null&&l(e,["parameters","language"],g);let b=s(n,["outputMimeType"]);e!==void 0&&b!=null&&l(e,["parameters","outputOptions","mimeType"],b);let E=s(n,["outputCompressionQuality"]);e!==void 0&&E!=null&&l(e,["parameters","outputOptions","compressionQuality"],E);let I=s(n,["addWatermark"]);e!==void 0&&I!=null&&l(e,["parameters","addWatermark"],I);let v=s(n,["labels"]);e!==void 0&&v!=null&&l(e,["labels"],v);let w=s(n,["editMode"]);e!==void 0&&w!=null&&l(e,["parameters","editMode"],w);let T=s(n,["baseSteps"]);return e!==void 0&&T!=null&&l(e,["parameters","editConfig","baseSteps"],T),t}f(zu,"editImageConfigToVertex");function Ju(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["prompt"]);i!=null&&l(t,["instances[0]","prompt"],i);let r=s(e,["referenceImages"]);if(r!=null){let c=r;Array.isArray(c)&&(c=c.map(d=>Xf(d))),l(t,["instances[0]","referenceImages"],c)}let a=s(e,["config"]);return a!=null&&zu(a,t),t}f(Ju,"editImageParametersInternalToVertex");function Wu(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>Mn(r))),l(e,["generatedImages"],i)}return e}f(Wu,"editImageResponseFromVertex");function Ku(n,e){let t={},o=s(n,["taskType"]);e!==void 0&&o!=null&&l(e,["requests[]","taskType"],o);let i=s(n,["title"]);e!==void 0&&i!=null&&l(e,["requests[]","title"],i);let r=s(n,["outputDimensionality"]);if(e!==void 0&&r!=null&&l(e,["requests[]","outputDimensionality"],r),s(n,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(s(n,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return t}f(Ku,"embedContentConfigToMldev");function Xu(n,e){let t={},o=s(n,["taskType"]);e!==void 0&&o!=null&&l(e,["instances[]","task_type"],o);let i=s(n,["title"]);e!==void 0&&i!=null&&l(e,["instances[]","title"],i);let r=s(n,["outputDimensionality"]);e!==void 0&&r!=null&&l(e,["parameters","outputDimensionality"],r);let a=s(n,["mimeType"]);e!==void 0&&a!=null&&l(e,["instances[]","mimeType"],a);let c=s(n,["autoTruncate"]);return e!==void 0&&c!=null&&l(e,["parameters","autoTruncate"],c),t}f(Xu,"embedContentConfigToVertex");function Yu(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["contents"]);if(i!=null){let c=wi(n,i);Array.isArray(c)&&(c=c.map(d=>d)),l(t,["requests[]","content"],c)}let r=s(e,["config"]);r!=null&&Ku(r,t);let a=s(e,["model"]);return a!==void 0&&l(t,["requests[]","model"],k(n,a)),t}f(Yu,"embedContentParametersToMldev");function Qu(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["contents"]);if(i!=null){let a=wi(n,i);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["instances[]","content"],a)}let r=s(e,["config"]);return r!=null&&Xu(r,t),t}f(Qu,"embedContentParametersToVertex");function Zu(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["embeddings"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["embeddings"],r)}let i=s(n,["metadata"]);return i!=null&&l(e,["metadata"],i),e}f(Zu,"embedContentResponseFromMldev");function ju(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["predictions[]","embeddings"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>Gu(a))),l(e,["embeddings"],r)}let i=s(n,["metadata"]);return i!=null&&l(e,["metadata"],i),e}f(ju,"embedContentResponseFromVertex");function ef(n){let e={},t=s(n,["endpoint"]);t!=null&&l(e,["name"],t);let o=s(n,["deployedModelId"]);return o!=null&&l(e,["deployedModelId"],o),e}f(ef,"endpointFromVertex");function tf(n){let e={};if(s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=s(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(tf,"fileDataToMldev$1");function nf(n){let e={},t=s(n,["id"]);t!=null&&l(e,["id"],t);let o=s(n,["args"]);o!=null&&l(e,["args"],o);let i=s(n,["name"]);if(i!=null&&l(e,["name"],i),s(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(s(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}f(nf,"functionCallToMldev$1");function of(n){let e={},t=s(n,["mode"]);t!=null&&l(e,["mode"],t);let o=s(n,["allowedFunctionNames"]);if(o!=null&&l(e,["allowedFunctionNames"],o),s(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}f(of,"functionCallingConfigToMldev");function rf(n){let e={};if(s(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=s(n,["description"]);t!=null&&l(e,["description"],t);let o=s(n,["name"]);o!=null&&l(e,["name"],o);let i=s(n,["parameters"]);i!=null&&l(e,["parameters"],i);let r=s(n,["parametersJsonSchema"]);r!=null&&l(e,["parametersJsonSchema"],r);let a=s(n,["response"]);a!=null&&l(e,["response"],a);let c=s(n,["responseJsonSchema"]);return c!=null&&l(e,["responseJsonSchema"],c),e}f(rf,"functionDeclarationToVertex");function sf(n,e,t){let o={},i=s(e,["systemInstruction"]);t!==void 0&&i!=null&&l(t,["systemInstruction"],Rn(re(i)));let r=s(e,["temperature"]);r!=null&&l(o,["temperature"],r);let a=s(e,["topP"]);a!=null&&l(o,["topP"],a);let c=s(e,["topK"]);c!=null&&l(o,["topK"],c);let d=s(e,["candidateCount"]);d!=null&&l(o,["candidateCount"],d);let u=s(e,["maxOutputTokens"]);u!=null&&l(o,["maxOutputTokens"],u);let p=s(e,["stopSequences"]);p!=null&&l(o,["stopSequences"],p);let m=s(e,["responseLogprobs"]);m!=null&&l(o,["responseLogprobs"],m);let h=s(e,["logprobs"]);h!=null&&l(o,["logprobs"],h);let g=s(e,["presencePenalty"]);g!=null&&l(o,["presencePenalty"],g);let b=s(e,["frequencyPenalty"]);b!=null&&l(o,["frequencyPenalty"],b);let E=s(e,["seed"]);E!=null&&l(o,["seed"],E);let I=s(e,["responseMimeType"]);I!=null&&l(o,["responseMimeType"],I);let v=s(e,["responseSchema"]);v!=null&&l(o,["responseSchema"],Ti(v));let w=s(e,["responseJsonSchema"]);if(w!=null&&l(o,["responseJsonSchema"],w),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");let T=s(e,["safetySettings"]);if(t!==void 0&&T!=null){let B=T;Array.isArray(B)&&(B=B.map(_e=>Yf(_e))),l(t,["safetySettings"],B)}let _=s(e,["tools"]);if(t!==void 0&&_!=null){let B=bt(_);Array.isArray(B)&&(B=B.map(_e=>op(gt(_e)))),l(t,["tools"],B)}let A=s(e,["toolConfig"]);if(t!==void 0&&A!=null&&l(t,["toolConfig"],np(A)),s(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let R=s(e,["cachedContent"]);t!==void 0&&R!=null&&l(t,["cachedContent"],De(n,R));let N=s(e,["responseModalities"]);N!=null&&l(o,["responseModalities"],N);let H=s(e,["mediaResolution"]);H!=null&&l(o,["mediaResolution"],H);let x=s(e,["speechConfig"]);if(x!=null&&l(o,["speechConfig"],Ci(x)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let D=s(e,["thinkingConfig"]);D!=null&&l(o,["thinkingConfig"],D);let J=s(e,["imageConfig"]);J!=null&&l(o,["imageConfig"],Rf(J));let Pe=s(e,["enableEnhancedCivicAnswers"]);return Pe!=null&&l(o,["enableEnhancedCivicAnswers"],Pe),o}f(sf,"generateContentConfigToMldev");function af(n,e,t){let o={},i=s(e,["systemInstruction"]);t!==void 0&&i!=null&&l(t,["systemInstruction"],re(i));let r=s(e,["temperature"]);r!=null&&l(o,["temperature"],r);let a=s(e,["topP"]);a!=null&&l(o,["topP"],a);let c=s(e,["topK"]);c!=null&&l(o,["topK"],c);let d=s(e,["candidateCount"]);d!=null&&l(o,["candidateCount"],d);let u=s(e,["maxOutputTokens"]);u!=null&&l(o,["maxOutputTokens"],u);let p=s(e,["stopSequences"]);p!=null&&l(o,["stopSequences"],p);let m=s(e,["responseLogprobs"]);m!=null&&l(o,["responseLogprobs"],m);let h=s(e,["logprobs"]);h!=null&&l(o,["logprobs"],h);let g=s(e,["presencePenalty"]);g!=null&&l(o,["presencePenalty"],g);let b=s(e,["frequencyPenalty"]);b!=null&&l(o,["frequencyPenalty"],b);let E=s(e,["seed"]);E!=null&&l(o,["seed"],E);let I=s(e,["responseMimeType"]);I!=null&&l(o,["responseMimeType"],I);let v=s(e,["responseSchema"]);v!=null&&l(o,["responseSchema"],Ti(v));let w=s(e,["responseJsonSchema"]);w!=null&&l(o,["responseJsonSchema"],w);let T=s(e,["routingConfig"]);T!=null&&l(o,["routingConfig"],T);let _=s(e,["modelSelectionConfig"]);_!=null&&l(o,["modelConfig"],_);let A=s(e,["safetySettings"]);if(t!==void 0&&A!=null){let Ne=A;Array.isArray(Ne)&&(Ne=Ne.map(jn=>jn)),l(t,["safetySettings"],Ne)}let R=s(e,["tools"]);if(t!==void 0&&R!=null){let Ne=bt(R);Array.isArray(Ne)&&(Ne=Ne.map(jn=>qa(gt(jn)))),l(t,["tools"],Ne)}let N=s(e,["toolConfig"]);t!==void 0&&N!=null&&l(t,["toolConfig"],N);let H=s(e,["labels"]);t!==void 0&&H!=null&&l(t,["labels"],H);let x=s(e,["cachedContent"]);t!==void 0&&x!=null&&l(t,["cachedContent"],De(n,x));let D=s(e,["responseModalities"]);D!=null&&l(o,["responseModalities"],D);let J=s(e,["mediaResolution"]);J!=null&&l(o,["mediaResolution"],J);let Pe=s(e,["speechConfig"]);Pe!=null&&l(o,["speechConfig"],Ba(Ci(Pe)));let B=s(e,["audioTimestamp"]);B!=null&&l(o,["audioTimestamp"],B);let _e=s(e,["thinkingConfig"]);_e!=null&&l(o,["thinkingConfig"],_e);let Oi=s(e,["imageConfig"]);if(Oi!=null&&l(o,["imageConfig"],Mf(Oi)),s(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return o}f(af,"generateContentConfigToVertex");function ra(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["contents"]);if(i!=null){let a=he(i);Array.isArray(a)&&(a=a.map(c=>Rn(c))),l(t,["contents"],a)}let r=s(e,["config"]);return r!=null&&l(t,["generationConfig"],sf(n,r,t)),t}f(ra,"generateContentParametersToMldev");function sa(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["contents"]);if(i!=null){let a=he(i);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["contents"],a)}let r=s(e,["config"]);return r!=null&&l(t,["generationConfig"],af(n,r,t)),t}f(sa,"generateContentParametersToVertex");function aa(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["candidates"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(u=>xu(u))),l(e,["candidates"],d)}let i=s(n,["modelVersion"]);i!=null&&l(e,["modelVersion"],i);let r=s(n,["promptFeedback"]);r!=null&&l(e,["promptFeedback"],r);let a=s(n,["responseId"]);a!=null&&l(e,["responseId"],a);let c=s(n,["usageMetadata"]);return c!=null&&l(e,["usageMetadata"],c),e}f(aa,"generateContentResponseFromMldev");function la(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["candidates"]);if(o!=null){let u=o;Array.isArray(u)&&(u=u.map(p=>p)),l(e,["candidates"],u)}let i=s(n,["createTime"]);i!=null&&l(e,["createTime"],i);let r=s(n,["modelVersion"]);r!=null&&l(e,["modelVersion"],r);let a=s(n,["promptFeedback"]);a!=null&&l(e,["promptFeedback"],a);let c=s(n,["responseId"]);c!=null&&l(e,["responseId"],c);let d=s(n,["usageMetadata"]);return d!=null&&l(e,["usageMetadata"],d),e}f(la,"generateContentResponseFromVertex");function lf(n,e){let t={};if(s(n,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(s(n,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is not supported in Gemini API.");let o=s(n,["numberOfImages"]);e!==void 0&&o!=null&&l(e,["parameters","sampleCount"],o);let i=s(n,["aspectRatio"]);e!==void 0&&i!=null&&l(e,["parameters","aspectRatio"],i);let r=s(n,["guidanceScale"]);if(e!==void 0&&r!=null&&l(e,["parameters","guidanceScale"],r),s(n,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");let a=s(n,["safetyFilterLevel"]);e!==void 0&&a!=null&&l(e,["parameters","safetySetting"],a);let c=s(n,["personGeneration"]);e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c);let d=s(n,["includeSafetyAttributes"]);e!==void 0&&d!=null&&l(e,["parameters","includeSafetyAttributes"],d);let u=s(n,["includeRaiReason"]);e!==void 0&&u!=null&&l(e,["parameters","includeRaiReason"],u);let p=s(n,["language"]);e!==void 0&&p!=null&&l(e,["parameters","language"],p);let m=s(n,["outputMimeType"]);e!==void 0&&m!=null&&l(e,["parameters","outputOptions","mimeType"],m);let h=s(n,["outputCompressionQuality"]);if(e!==void 0&&h!=null&&l(e,["parameters","outputOptions","compressionQuality"],h),s(n,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is not supported in Gemini API.");if(s(n,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let g=s(n,["imageSize"]);if(e!==void 0&&g!=null&&l(e,["parameters","sampleImageSize"],g),s(n,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is not supported in Gemini API.");return t}f(lf,"generateImagesConfigToMldev");function cf(n,e){let t={},o=s(n,["outputGcsUri"]);e!==void 0&&o!=null&&l(e,["parameters","storageUri"],o);let i=s(n,["negativePrompt"]);e!==void 0&&i!=null&&l(e,["parameters","negativePrompt"],i);let r=s(n,["numberOfImages"]);e!==void 0&&r!=null&&l(e,["parameters","sampleCount"],r);let a=s(n,["aspectRatio"]);e!==void 0&&a!=null&&l(e,["parameters","aspectRatio"],a);let c=s(n,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=s(n,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let u=s(n,["safetyFilterLevel"]);e!==void 0&&u!=null&&l(e,["parameters","safetySetting"],u);let p=s(n,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let m=s(n,["includeSafetyAttributes"]);e!==void 0&&m!=null&&l(e,["parameters","includeSafetyAttributes"],m);let h=s(n,["includeRaiReason"]);e!==void 0&&h!=null&&l(e,["parameters","includeRaiReason"],h);let g=s(n,["language"]);e!==void 0&&g!=null&&l(e,["parameters","language"],g);let b=s(n,["outputMimeType"]);e!==void 0&&b!=null&&l(e,["parameters","outputOptions","mimeType"],b);let E=s(n,["outputCompressionQuality"]);e!==void 0&&E!=null&&l(e,["parameters","outputOptions","compressionQuality"],E);let I=s(n,["addWatermark"]);e!==void 0&&I!=null&&l(e,["parameters","addWatermark"],I);let v=s(n,["labels"]);e!==void 0&&v!=null&&l(e,["labels"],v);let w=s(n,["imageSize"]);e!==void 0&&w!=null&&l(e,["parameters","sampleImageSize"],w);let T=s(n,["enhancePrompt"]);return e!==void 0&&T!=null&&l(e,["parameters","enhancePrompt"],T),t}f(cf,"generateImagesConfigToVertex");function df(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["prompt"]);i!=null&&l(t,["instances[0]","prompt"],i);let r=s(e,["config"]);return r!=null&&lf(r,t),t}f(df,"generateImagesParametersToMldev");function uf(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["prompt"]);i!=null&&l(t,["instances[0]","prompt"],i);let r=s(e,["config"]);return r!=null&&cf(r,t),t}f(uf,"generateImagesParametersToVertex");function ff(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["predictions"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>Cf(a))),l(e,["generatedImages"],r)}let i=s(n,["positivePromptSafetyAttributes"]);return i!=null&&l(e,["positivePromptSafetyAttributes"],Ha(i)),e}f(ff,"generateImagesResponseFromMldev");function pf(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["predictions"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>Mn(a))),l(e,["generatedImages"],r)}let i=s(n,["positivePromptSafetyAttributes"]);return i!=null&&l(e,["positivePromptSafetyAttributes"],Va(i)),e}f(pf,"generateImagesResponseFromVertex");function mf(n,e){let t={},o=s(n,["numberOfVideos"]);if(e!==void 0&&o!=null&&l(e,["parameters","sampleCount"],o),s(n,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(s(n,["fps"])!==void 0)throw new Error("fps parameter is not supported in Gemini API.");let i=s(n,["durationSeconds"]);if(e!==void 0&&i!=null&&l(e,["parameters","durationSeconds"],i),s(n,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");let r=s(n,["aspectRatio"]);e!==void 0&&r!=null&&l(e,["parameters","aspectRatio"],r);let a=s(n,["resolution"]);e!==void 0&&a!=null&&l(e,["parameters","resolution"],a);let c=s(n,["personGeneration"]);if(e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c),s(n,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is not supported in Gemini API.");let d=s(n,["negativePrompt"]);e!==void 0&&d!=null&&l(e,["parameters","negativePrompt"],d);let u=s(n,["enhancePrompt"]);if(e!==void 0&&u!=null&&l(e,["parameters","enhancePrompt"],u),s(n,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is not supported in Gemini API.");let p=s(n,["lastFrame"]);e!==void 0&&p!=null&&l(e,["instances[0]","lastFrame"],Dn(p));let m=s(n,["referenceImages"]);if(e!==void 0&&m!=null){let h=m;Array.isArray(h)&&(h=h.map(g=>gp(g))),l(e,["instances[0]","referenceImages"],h)}if(s(n,["mask"])!==void 0)throw new Error("mask parameter is not supported in Gemini API.");if(s(n,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is not supported in Gemini API.");return t}f(mf,"generateVideosConfigToMldev");function hf(n,e){let t={},o=s(n,["numberOfVideos"]);e!==void 0&&o!=null&&l(e,["parameters","sampleCount"],o);let i=s(n,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let r=s(n,["fps"]);e!==void 0&&r!=null&&l(e,["parameters","fps"],r);let a=s(n,["durationSeconds"]);e!==void 0&&a!=null&&l(e,["parameters","durationSeconds"],a);let c=s(n,["seed"]);e!==void 0&&c!=null&&l(e,["parameters","seed"],c);let d=s(n,["aspectRatio"]);e!==void 0&&d!=null&&l(e,["parameters","aspectRatio"],d);let u=s(n,["resolution"]);e!==void 0&&u!=null&&l(e,["parameters","resolution"],u);let p=s(n,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let m=s(n,["pubsubTopic"]);e!==void 0&&m!=null&&l(e,["parameters","pubsubTopic"],m);let h=s(n,["negativePrompt"]);e!==void 0&&h!=null&&l(e,["parameters","negativePrompt"],h);let g=s(n,["enhancePrompt"]);e!==void 0&&g!=null&&l(e,["parameters","enhancePrompt"],g);let b=s(n,["generateAudio"]);e!==void 0&&b!=null&&l(e,["parameters","generateAudio"],b);let E=s(n,["lastFrame"]);e!==void 0&&E!=null&&l(e,["instances[0]","lastFrame"],Ce(E));let I=s(n,["referenceImages"]);if(e!==void 0&&I!=null){let T=I;Array.isArray(T)&&(T=T.map(_=>bp(_))),l(e,["instances[0]","referenceImages"],T)}let v=s(n,["mask"]);e!==void 0&&v!=null&&l(e,["instances[0]","mask"],hp(v));let w=s(n,["compressionQuality"]);return e!==void 0&&w!=null&&l(e,["parameters","compressionQuality"],w),t}f(hf,"generateVideosConfigToVertex");function gf(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(n,["done"]);i!=null&&l(e,["done"],i);let r=s(n,["error"]);r!=null&&l(e,["error"],r);let a=s(n,["response","generateVideoResponse"]);return a!=null&&l(e,["response"],If(a)),e}f(gf,"generateVideosOperationFromMldev");function bf(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(n,["done"]);i!=null&&l(e,["done"],i);let r=s(n,["error"]);r!=null&&l(e,["error"],r);let a=s(n,["response"]);return a!=null&&l(e,["response"],vf(a)),e}f(bf,"generateVideosOperationFromVertex");function yf(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["prompt"]);i!=null&&l(t,["instances[0]","prompt"],i);let r=s(e,["image"]);r!=null&&l(t,["instances[0]","image"],Dn(r));let a=s(e,["video"]);a!=null&&l(t,["instances[0]","video"],Oa(a));let c=s(e,["source"]);c!=null&&wf(c,t);let d=s(e,["config"]);return d!=null&&mf(d,t),t}f(yf,"generateVideosParametersToMldev");function Ef(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["prompt"]);i!=null&&l(t,["instances[0]","prompt"],i);let r=s(e,["image"]);r!=null&&l(t,["instances[0]","image"],Ce(r));let a=s(e,["video"]);a!=null&&l(t,["instances[0]","video"],za(a));let c=s(e,["source"]);c!=null&&Tf(c,t);let d=s(e,["config"]);return d!=null&&hf(d,t),t}f(Ef,"generateVideosParametersToVertex");function If(n){let e={},t=s(n,["generatedSamples"]);if(t!=null){let r=t;Array.isArray(r)&&(r=r.map(a=>Sf(a))),l(e,["generatedVideos"],r)}let o=s(n,["raiMediaFilteredCount"]);o!=null&&l(e,["raiMediaFilteredCount"],o);let i=s(n,["raiMediaFilteredReasons"]);return i!=null&&l(e,["raiMediaFilteredReasons"],i),e}f(If,"generateVideosResponseFromMldev");function vf(n){let e={},t=s(n,["videos"]);if(t!=null){let r=t;Array.isArray(r)&&(r=r.map(a=>Af(a))),l(e,["generatedVideos"],r)}let o=s(n,["raiMediaFilteredCount"]);o!=null&&l(e,["raiMediaFilteredCount"],o);let i=s(n,["raiMediaFilteredReasons"]);return i!=null&&l(e,["raiMediaFilteredReasons"],i),e}f(vf,"generateVideosResponseFromVertex");function wf(n,e){let t={},o=s(n,["prompt"]);e!==void 0&&o!=null&&l(e,["instances[0]","prompt"],o);let i=s(n,["image"]);e!==void 0&&i!=null&&l(e,["instances[0]","image"],Dn(i));let r=s(n,["video"]);return e!==void 0&&r!=null&&l(e,["instances[0]","video"],Oa(r)),t}f(wf,"generateVideosSourceToMldev");function Tf(n,e){let t={},o=s(n,["prompt"]);e!==void 0&&o!=null&&l(e,["instances[0]","prompt"],o);let i=s(n,["image"]);e!==void 0&&i!=null&&l(e,["instances[0]","image"],Ce(i));let r=s(n,["video"]);return e!==void 0&&r!=null&&l(e,["instances[0]","video"],za(r)),t}f(Tf,"generateVideosSourceToVertex");function Cf(n){let e={},t=s(n,["_self"]);t!=null&&l(e,["image"],Df(t));let o=s(n,["raiFilteredReason"]);o!=null&&l(e,["raiFilteredReason"],o);let i=s(n,["_self"]);return i!=null&&l(e,["safetyAttributes"],Ha(i)),e}f(Cf,"generatedImageFromMldev");function Mn(n){let e={},t=s(n,["_self"]);t!=null&&l(e,["image"],Fa(t));let o=s(n,["raiFilteredReason"]);o!=null&&l(e,["raiFilteredReason"],o);let i=s(n,["_self"]);i!=null&&l(e,["safetyAttributes"],Va(i));let r=s(n,["prompt"]);return r!=null&&l(e,["enhancedPrompt"],r),e}f(Mn,"generatedImageFromVertex");function _f(n){let e={},t=s(n,["_self"]);t!=null&&l(e,["mask"],Fa(t));let o=s(n,["labels"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>r)),l(e,["labels"],i)}return e}f(_f,"generatedImageMaskFromVertex");function Sf(n){let e={},t=s(n,["video"]);return t!=null&&l(e,["video"],pp(t)),e}f(Sf,"generatedVideoFromMldev");function Af(n){let e={},t=s(n,["_self"]);return t!=null&&l(e,["video"],mp(t)),e}f(Af,"generatedVideoFromVertex");function xf(n){let e={},t=s(n,["modelSelectionConfig"]);t!=null&&l(e,["modelConfig"],t);let o=s(n,["responseJsonSchema"]);o!=null&&l(e,["responseJsonSchema"],o);let i=s(n,["audioTimestamp"]);i!=null&&l(e,["audioTimestamp"],i);let r=s(n,["candidateCount"]);r!=null&&l(e,["candidateCount"],r);let a=s(n,["enableAffectiveDialog"]);a!=null&&l(e,["enableAffectiveDialog"],a);let c=s(n,["frequencyPenalty"]);c!=null&&l(e,["frequencyPenalty"],c);let d=s(n,["logprobs"]);d!=null&&l(e,["logprobs"],d);let u=s(n,["maxOutputTokens"]);u!=null&&l(e,["maxOutputTokens"],u);let p=s(n,["mediaResolution"]);p!=null&&l(e,["mediaResolution"],p);let m=s(n,["presencePenalty"]);m!=null&&l(e,["presencePenalty"],m);let h=s(n,["responseLogprobs"]);h!=null&&l(e,["responseLogprobs"],h);let g=s(n,["responseMimeType"]);g!=null&&l(e,["responseMimeType"],g);let b=s(n,["responseModalities"]);b!=null&&l(e,["responseModalities"],b);let E=s(n,["responseSchema"]);E!=null&&l(e,["responseSchema"],E);let I=s(n,["routingConfig"]);I!=null&&l(e,["routingConfig"],I);let v=s(n,["seed"]);v!=null&&l(e,["seed"],v);let w=s(n,["speechConfig"]);w!=null&&l(e,["speechConfig"],Ba(w));let T=s(n,["stopSequences"]);T!=null&&l(e,["stopSequences"],T);let _=s(n,["temperature"]);_!=null&&l(e,["temperature"],_);let A=s(n,["thinkingConfig"]);A!=null&&l(e,["thinkingConfig"],A);let R=s(n,["topK"]);R!=null&&l(e,["topK"],R);let N=s(n,["topP"]);if(N!=null&&l(e,["topP"],N),s(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}f(xf,"generationConfigToVertex");function Pf(n,e){let t={},o=s(e,["model"]);return o!=null&&l(t,["_url","name"],k(n,o)),t}f(Pf,"getModelParametersToMldev");function Nf(n,e){let t={},o=s(e,["model"]);return o!=null&&l(t,["_url","name"],k(n,o)),t}f(Nf,"getModelParametersToVertex");function $f(n){let e={};if(s(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=s(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}f($f,"googleMapsToMldev$1");function Gf(n){let e={};if(s(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(s(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=s(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}f(Gf,"googleSearchToMldev$1");function Rf(n){let e={},t=s(n,["aspectRatio"]);t!=null&&l(e,["aspectRatio"],t);let o=s(n,["imageSize"]);if(o!=null&&l(e,["imageSize"],o),s(n,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(s(n,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}f(Rf,"imageConfigToMldev");function Mf(n){let e={},t=s(n,["aspectRatio"]);t!=null&&l(e,["aspectRatio"],t);let o=s(n,["imageSize"]);o!=null&&l(e,["imageSize"],o);let i=s(n,["outputMimeType"]);i!=null&&l(e,["imageOutputOptions","mimeType"],i);let r=s(n,["outputCompressionQuality"]);return r!=null&&l(e,["imageOutputOptions","compressionQuality"],r),e}f(Mf,"imageConfigToVertex");function Df(n){let e={},t=s(n,["bytesBase64Encoded"]);t!=null&&l(e,["imageBytes"],He(t));let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(Df,"imageFromMldev");function Fa(n){let e={},t=s(n,["gcsUri"]);t!=null&&l(e,["gcsUri"],t);let o=s(n,["bytesBase64Encoded"]);o!=null&&l(e,["imageBytes"],He(o));let i=s(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}f(Fa,"imageFromVertex");function Dn(n){let e={};if(s(n,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");let t=s(n,["imageBytes"]);t!=null&&l(e,["bytesBase64Encoded"],He(t));let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(Dn,"imageToMldev");function Ce(n){let e={},t=s(n,["gcsUri"]);t!=null&&l(e,["gcsUri"],t);let o=s(n,["imageBytes"]);o!=null&&l(e,["bytesBase64Encoded"],He(o));let i=s(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}f(Ce,"imageToVertex");function kf(n,e,t){let o={},i=s(e,["pageSize"]);t!==void 0&&i!=null&&l(t,["_query","pageSize"],i);let r=s(e,["pageToken"]);t!==void 0&&r!=null&&l(t,["_query","pageToken"],r);let a=s(e,["filter"]);t!==void 0&&a!=null&&l(t,["_query","filter"],a);let c=s(e,["queryBase"]);return t!==void 0&&c!=null&&l(t,["_url","models_url"],$a(n,c)),o}f(kf,"listModelsConfigToMldev");function Lf(n,e,t){let o={},i=s(e,["pageSize"]);t!==void 0&&i!=null&&l(t,["_query","pageSize"],i);let r=s(e,["pageToken"]);t!==void 0&&r!=null&&l(t,["_query","pageToken"],r);let a=s(e,["filter"]);t!==void 0&&a!=null&&l(t,["_query","filter"],a);let c=s(e,["queryBase"]);return t!==void 0&&c!=null&&l(t,["_url","models_url"],$a(n,c)),o}f(Lf,"listModelsConfigToVertex");function Uf(n,e){let t={},o=s(e,["config"]);return o!=null&&kf(n,o,t),t}f(Uf,"listModelsParametersToMldev");function Ff(n,e){let t={},o=s(e,["config"]);return o!=null&&Lf(n,o,t),t}f(Ff,"listModelsParametersToVertex");function Hf(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(n,["_self"]);if(i!=null){let r=Ga(i);Array.isArray(r)&&(r=r.map(a=>Wo(a))),l(e,["models"],r)}return e}f(Hf,"listModelsResponseFromMldev");function Vf(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(n,["_self"]);if(i!=null){let r=Ga(i);Array.isArray(r)&&(r=r.map(a=>Ko(a))),l(e,["models"],r)}return e}f(Vf,"listModelsResponseFromVertex");function Bf(n){let e={},t=s(n,["maskMode"]);t!=null&&l(e,["maskMode"],t);let o=s(n,["segmentationClasses"]);o!=null&&l(e,["maskClasses"],o);let i=s(n,["maskDilation"]);return i!=null&&l(e,["dilation"],i),e}f(Bf,"maskReferenceConfigToVertex");function Wo(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["displayName"]);o!=null&&l(e,["displayName"],o);let i=s(n,["description"]);i!=null&&l(e,["description"],i);let r=s(n,["version"]);r!=null&&l(e,["version"],r);let a=s(n,["_self"]);a!=null&&l(e,["tunedModelInfo"],ip(a));let c=s(n,["inputTokenLimit"]);c!=null&&l(e,["inputTokenLimit"],c);let d=s(n,["outputTokenLimit"]);d!=null&&l(e,["outputTokenLimit"],d);let u=s(n,["supportedGenerationMethods"]);u!=null&&l(e,["supportedActions"],u);let p=s(n,["temperature"]);p!=null&&l(e,["temperature"],p);let m=s(n,["maxTemperature"]);m!=null&&l(e,["maxTemperature"],m);let h=s(n,["topP"]);h!=null&&l(e,["topP"],h);let g=s(n,["topK"]);g!=null&&l(e,["topK"],g);let b=s(n,["thinking"]);return b!=null&&l(e,["thinking"],b),e}f(Wo,"modelFromMldev");function Ko(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["displayName"]);o!=null&&l(e,["displayName"],o);let i=s(n,["description"]);i!=null&&l(e,["description"],i);let r=s(n,["versionId"]);r!=null&&l(e,["version"],r);let a=s(n,["deployedModels"]);if(a!=null){let m=a;Array.isArray(m)&&(m=m.map(h=>ef(h))),l(e,["endpoints"],m)}let c=s(n,["labels"]);c!=null&&l(e,["labels"],c);let d=s(n,["_self"]);d!=null&&l(e,["tunedModelInfo"],rp(d));let u=s(n,["defaultCheckpointId"]);u!=null&&l(e,["defaultCheckpointId"],u);let p=s(n,["checkpoints"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(h=>h)),l(e,["checkpoints"],m)}return e}f(Ko,"modelFromVertex");function qf(n){let e={},t=s(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let o=s(n,["codeExecutionResult"]);o!=null&&l(e,["codeExecutionResult"],o);let i=s(n,["executableCode"]);i!=null&&l(e,["executableCode"],i);let r=s(n,["fileData"]);r!=null&&l(e,["fileData"],tf(r));let a=s(n,["functionCall"]);a!=null&&l(e,["functionCall"],nf(a));let c=s(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=s(n,["inlineData"]);d!=null&&l(e,["inlineData"],Au(d));let u=s(n,["text"]);u!=null&&l(e,["text"],u);let p=s(n,["thought"]);p!=null&&l(e,["thought"],p);let m=s(n,["thoughtSignature"]);m!=null&&l(e,["thoughtSignature"],m);let h=s(n,["videoMetadata"]);return h!=null&&l(e,["videoMetadata"],h),e}f(qf,"partToMldev$1");function Of(n){let e={},t=s(n,["productImage"]);return t!=null&&l(e,["image"],Ce(t)),e}f(Of,"productImageToVertex");function zf(n,e){let t={},o=s(n,["numberOfImages"]);e!==void 0&&o!=null&&l(e,["parameters","sampleCount"],o);let i=s(n,["baseSteps"]);e!==void 0&&i!=null&&l(e,["parameters","baseSteps"],i);let r=s(n,["outputGcsUri"]);e!==void 0&&r!=null&&l(e,["parameters","storageUri"],r);let a=s(n,["seed"]);e!==void 0&&a!=null&&l(e,["parameters","seed"],a);let c=s(n,["safetyFilterLevel"]);e!==void 0&&c!=null&&l(e,["parameters","safetySetting"],c);let d=s(n,["personGeneration"]);e!==void 0&&d!=null&&l(e,["parameters","personGeneration"],d);let u=s(n,["addWatermark"]);e!==void 0&&u!=null&&l(e,["parameters","addWatermark"],u);let p=s(n,["outputMimeType"]);e!==void 0&&p!=null&&l(e,["parameters","outputOptions","mimeType"],p);let m=s(n,["outputCompressionQuality"]);e!==void 0&&m!=null&&l(e,["parameters","outputOptions","compressionQuality"],m);let h=s(n,["enhancePrompt"]);e!==void 0&&h!=null&&l(e,["parameters","enhancePrompt"],h);let g=s(n,["labels"]);return e!==void 0&&g!=null&&l(e,["labels"],g),t}f(zf,"recontextImageConfigToVertex");function Jf(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["source"]);i!=null&&Kf(i,t);let r=s(e,["config"]);return r!=null&&zf(r,t),t}f(Jf,"recontextImageParametersToVertex");function Wf(n){let e={},t=s(n,["predictions"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(i=>Mn(i))),l(e,["generatedImages"],o)}return e}f(Wf,"recontextImageResponseFromVertex");function Kf(n,e){let t={},o=s(n,["prompt"]);e!==void 0&&o!=null&&l(e,["instances[0]","prompt"],o);let i=s(n,["personImage"]);e!==void 0&&i!=null&&l(e,["instances[0]","personImage","image"],Ce(i));let r=s(n,["productImages"]);if(e!==void 0&&r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>Of(c))),l(e,["instances[0]","productImages"],a)}return t}f(Kf,"recontextImageSourceToVertex");function Xf(n){let e={},t=s(n,["referenceImage"]);t!=null&&l(e,["referenceImage"],Ce(t));let o=s(n,["referenceId"]);o!=null&&l(e,["referenceId"],o);let i=s(n,["referenceType"]);i!=null&&l(e,["referenceType"],i);let r=s(n,["maskImageConfig"]);r!=null&&l(e,["maskImageConfig"],Bf(r));let a=s(n,["controlImageConfig"]);a!=null&&l(e,["controlImageConfig"],Mu(a));let c=s(n,["styleImageConfig"]);c!=null&&l(e,["styleImageConfig"],c);let d=s(n,["subjectImageConfig"]);return d!=null&&l(e,["subjectImageConfig"],d),e}f(Xf,"referenceImageAPIInternalToVertex");function Ha(n){let e={},t=s(n,["safetyAttributes","categories"]);t!=null&&l(e,["categories"],t);let o=s(n,["safetyAttributes","scores"]);o!=null&&l(e,["scores"],o);let i=s(n,["contentType"]);return i!=null&&l(e,["contentType"],i),e}f(Ha,"safetyAttributesFromMldev");function Va(n){let e={},t=s(n,["safetyAttributes","categories"]);t!=null&&l(e,["categories"],t);let o=s(n,["safetyAttributes","scores"]);o!=null&&l(e,["scores"],o);let i=s(n,["contentType"]);return i!=null&&l(e,["contentType"],i),e}f(Va,"safetyAttributesFromVertex");function Yf(n){let e={},t=s(n,["category"]);if(t!=null&&l(e,["category"],t),s(n,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let o=s(n,["threshold"]);return o!=null&&l(e,["threshold"],o),e}f(Yf,"safetySettingToMldev");function Qf(n){let e={},t=s(n,["image"]);return t!=null&&l(e,["image"],Ce(t)),e}f(Qf,"scribbleImageToVertex");function Zf(n,e){let t={},o=s(n,["mode"]);e!==void 0&&o!=null&&l(e,["parameters","mode"],o);let i=s(n,["maxPredictions"]);e!==void 0&&i!=null&&l(e,["parameters","maxPredictions"],i);let r=s(n,["confidenceThreshold"]);e!==void 0&&r!=null&&l(e,["parameters","confidenceThreshold"],r);let a=s(n,["maskDilation"]);e!==void 0&&a!=null&&l(e,["parameters","maskDilation"],a);let c=s(n,["binaryColorThreshold"]);e!==void 0&&c!=null&&l(e,["parameters","binaryColorThreshold"],c);let d=s(n,["labels"]);return e!==void 0&&d!=null&&l(e,["labels"],d),t}f(Zf,"segmentImageConfigToVertex");function jf(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["source"]);i!=null&&tp(i,t);let r=s(e,["config"]);return r!=null&&Zf(r,t),t}f(jf,"segmentImageParametersToVertex");function ep(n){let e={},t=s(n,["predictions"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(i=>_f(i))),l(e,["generatedMasks"],o)}return e}f(ep,"segmentImageResponseFromVertex");function tp(n,e){let t={},o=s(n,["prompt"]);e!==void 0&&o!=null&&l(e,["instances[0]","prompt"],o);let i=s(n,["image"]);e!==void 0&&i!=null&&l(e,["instances[0]","image"],Ce(i));let r=s(n,["scribbleImage"]);return e!==void 0&&r!=null&&l(e,["instances[0]","scribble"],Qf(r)),t}f(tp,"segmentImageSourceToVertex");function Ba(n){let e={},t=s(n,["voiceConfig"]);t!=null&&l(e,["voiceConfig"],t);let o=s(n,["languageCode"]);if(o!=null&&l(e,["languageCode"],o),s(n,["multiSpeakerVoiceConfig"])!==void 0)throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");return e}f(Ba,"speechConfigToVertex");function np(n){let e={},t=s(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],of(t));let o=s(n,["retrievalConfig"]);return o!=null&&l(e,["retrievalConfig"],o),e}f(np,"toolConfigToMldev");function op(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let p=t;Array.isArray(p)&&(p=p.map(m=>m)),l(e,["functionDeclarations"],p)}if(s(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let o=s(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let i=s(n,["computerUse"]);i!=null&&l(e,["computerUse"],i);let r=s(n,["fileSearch"]);r!=null&&l(e,["fileSearch"],r);let a=s(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),s(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=s(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],$f(c));let d=s(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],Gf(d));let u=s(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}f(op,"toolToMldev$1");function qa(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let m=t;Array.isArray(m)&&(m=m.map(h=>rf(h))),l(e,["functionDeclarations"],m)}let o=s(n,["retrieval"]);o!=null&&l(e,["retrieval"],o);let i=s(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let r=s(n,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let a=s(n,["codeExecution"]);a!=null&&l(e,["codeExecution"],a);let c=s(n,["enterpriseWebSearch"]);c!=null&&l(e,["enterpriseWebSearch"],c);let d=s(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],d);let u=s(n,["googleSearch"]);u!=null&&l(e,["googleSearch"],u);let p=s(n,["urlContext"]);return p!=null&&l(e,["urlContext"],p),e}f(qa,"toolToVertex");function ip(n){let e={},t=s(n,["baseModel"]);t!=null&&l(e,["baseModel"],t);let o=s(n,["createTime"]);o!=null&&l(e,["createTime"],o);let i=s(n,["updateTime"]);return i!=null&&l(e,["updateTime"],i),e}f(ip,"tunedModelInfoFromMldev");function rp(n){let e={},t=s(n,["labels","google-vertex-llm-tuning-base-model-id"]);t!=null&&l(e,["baseModel"],t);let o=s(n,["createTime"]);o!=null&&l(e,["createTime"],o);let i=s(n,["updateTime"]);return i!=null&&l(e,["updateTime"],i),e}f(rp,"tunedModelInfoFromVertex");function sp(n,e){let t={},o=s(n,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let i=s(n,["description"]);e!==void 0&&i!=null&&l(e,["description"],i);let r=s(n,["defaultCheckpointId"]);return e!==void 0&&r!=null&&l(e,["defaultCheckpointId"],r),t}f(sp,"updateModelConfigToMldev");function ap(n,e){let t={},o=s(n,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let i=s(n,["description"]);e!==void 0&&i!=null&&l(e,["description"],i);let r=s(n,["defaultCheckpointId"]);return e!==void 0&&r!=null&&l(e,["defaultCheckpointId"],r),t}f(ap,"updateModelConfigToVertex");function lp(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","name"],k(n,o));let i=s(e,["config"]);return i!=null&&sp(i,t),t}f(lp,"updateModelParametersToMldev");function cp(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["config"]);return i!=null&&ap(i,t),t}f(cp,"updateModelParametersToVertex");function dp(n,e){let t={},o=s(n,["outputGcsUri"]);e!==void 0&&o!=null&&l(e,["parameters","storageUri"],o);let i=s(n,["safetyFilterLevel"]);e!==void 0&&i!=null&&l(e,["parameters","safetySetting"],i);let r=s(n,["personGeneration"]);e!==void 0&&r!=null&&l(e,["parameters","personGeneration"],r);let a=s(n,["includeRaiReason"]);e!==void 0&&a!=null&&l(e,["parameters","includeRaiReason"],a);let c=s(n,["outputMimeType"]);e!==void 0&&c!=null&&l(e,["parameters","outputOptions","mimeType"],c);let d=s(n,["outputCompressionQuality"]);e!==void 0&&d!=null&&l(e,["parameters","outputOptions","compressionQuality"],d);let u=s(n,["enhanceInputImage"]);e!==void 0&&u!=null&&l(e,["parameters","upscaleConfig","enhanceInputImage"],u);let p=s(n,["imagePreservationFactor"]);e!==void 0&&p!=null&&l(e,["parameters","upscaleConfig","imagePreservationFactor"],p);let m=s(n,["labels"]);e!==void 0&&m!=null&&l(e,["labels"],m);let h=s(n,["numberOfImages"]);e!==void 0&&h!=null&&l(e,["parameters","sampleCount"],h);let g=s(n,["mode"]);return e!==void 0&&g!=null&&l(e,["parameters","mode"],g),t}f(dp,"upscaleImageAPIConfigInternalToVertex");function up(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["_url","model"],k(n,o));let i=s(e,["image"]);i!=null&&l(t,["instances[0]","image"],Ce(i));let r=s(e,["upscaleFactor"]);r!=null&&l(t,["parameters","upscaleConfig","upscaleFactor"],r);let a=s(e,["config"]);return a!=null&&dp(a,t),t}f(up,"upscaleImageAPIParametersInternalToVertex");function fp(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>Mn(r))),l(e,["generatedImages"],i)}return e}f(fp,"upscaleImageResponseFromVertex");function pp(n){let e={},t=s(n,["uri"]);t!=null&&l(e,["uri"],t);let o=s(n,["encodedVideo"]);o!=null&&l(e,["videoBytes"],He(o));let i=s(n,["encoding"]);return i!=null&&l(e,["mimeType"],i),e}f(pp,"videoFromMldev");function mp(n){let e={},t=s(n,["gcsUri"]);t!=null&&l(e,["uri"],t);let o=s(n,["bytesBase64Encoded"]);o!=null&&l(e,["videoBytes"],He(o));let i=s(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}f(mp,"videoFromVertex");function hp(n){let e={},t=s(n,["image"]);t!=null&&l(e,["_self"],Ce(t));let o=s(n,["maskMode"]);return o!=null&&l(e,["maskMode"],o),e}f(hp,"videoGenerationMaskToVertex");function gp(n){let e={},t=s(n,["image"]);t!=null&&l(e,["image"],Dn(t));let o=s(n,["referenceType"]);return o!=null&&l(e,["referenceType"],o),e}f(gp,"videoGenerationReferenceImageToMldev");function bp(n){let e={},t=s(n,["image"]);t!=null&&l(e,["image"],Ce(t));let o=s(n,["referenceType"]);return o!=null&&l(e,["referenceType"],o),e}f(bp,"videoGenerationReferenceImageToVertex");function Oa(n){let e={},t=s(n,["uri"]);t!=null&&l(e,["uri"],t);let o=s(n,["videoBytes"]);o!=null&&l(e,["encodedVideo"],He(o));let i=s(n,["mimeType"]);return i!=null&&l(e,["encoding"],i),e}f(Oa,"videoToMldev");function za(n){let e={},t=s(n,["uri"]);t!=null&&l(e,["gcsUri"],t);let o=s(n,["videoBytes"]);o!=null&&l(e,["bytesBase64Encoded"],He(o));let i=s(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}f(za,"videoToVertex");function yp(n,e){let t={},o=s(n,["displayName"]);return e!==void 0&&o!=null&&l(e,["displayName"],o),t}f(yp,"createFileSearchStoreConfigToMldev");function Ep(n){let e={},t=s(n,["config"]);return t!=null&&yp(t,e),e}f(Ep,"createFileSearchStoreParametersToMldev");function Ip(n,e){let t={},o=s(n,["force"]);return e!==void 0&&o!=null&&l(e,["_query","force"],o),t}f(Ip,"deleteFileSearchStoreConfigToMldev");function vp(n){let e={},t=s(n,["name"]);t!=null&&l(e,["_url","name"],t);let o=s(n,["config"]);return o!=null&&Ip(o,e),e}f(vp,"deleteFileSearchStoreParametersToMldev");function wp(n){let e={},t=s(n,["name"]);return t!=null&&l(e,["_url","name"],t),e}f(wp,"getFileSearchStoreParametersToMldev");function Tp(n,e){let t={},o=s(n,["customMetadata"]);if(e!==void 0&&o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["customMetadata"],r)}let i=s(n,["chunkingConfig"]);return e!==void 0&&i!=null&&l(e,["chunkingConfig"],i),t}f(Tp,"importFileConfigToMldev");function Cp(n){let e={},t=s(n,["name"]);t!=null&&l(e,["name"],t);let o=s(n,["metadata"]);o!=null&&l(e,["metadata"],o);let i=s(n,["done"]);i!=null&&l(e,["done"],i);let r=s(n,["error"]);r!=null&&l(e,["error"],r);let a=s(n,["response"]);return a!=null&&l(e,["response"],Sp(a)),e}f(Cp,"importFileOperationFromMldev");function _p(n){let e={},t=s(n,["fileSearchStoreName"]);t!=null&&l(e,["_url","file_search_store_name"],t);let o=s(n,["fileName"]);o!=null&&l(e,["fileName"],o);let i=s(n,["config"]);return i!=null&&Tp(i,e),e}f(_p,"importFileParametersToMldev");function Sp(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["parent"]);o!=null&&l(e,["parent"],o);let i=s(n,["documentName"]);return i!=null&&l(e,["documentName"],i),e}f(Sp,"importFileResponseFromMldev");function Ap(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),t}f(Ap,"listFileSearchStoresConfigToMldev");function xp(n){let e={},t=s(n,["config"]);return t!=null&&Ap(t,e),e}f(xp,"listFileSearchStoresParametersToMldev");function Pp(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(n,["fileSearchStores"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["fileSearchStores"],r)}return e}f(Pp,"listFileSearchStoresResponseFromMldev");function Ja(n,e){let t={},o=s(n,["mimeType"]);e!==void 0&&o!=null&&l(e,["mimeType"],o);let i=s(n,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let r=s(n,["customMetadata"]);if(e!==void 0&&r!=null){let c=r;Array.isArray(c)&&(c=c.map(d=>d)),l(e,["customMetadata"],c)}let a=s(n,["chunkingConfig"]);return e!==void 0&&a!=null&&l(e,["chunkingConfig"],a),t}f(Ja,"uploadToFileSearchStoreConfigToMldev");function Np(n){let e={},t=s(n,["fileSearchStoreName"]);t!=null&&l(e,["_url","file_search_store_name"],t);let o=s(n,["config"]);return o!=null&&Ja(o,e),e}f(Np,"uploadToFileSearchStoreParametersToMldev");function $p(n){let e={},t=s(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}f($p,"uploadToFileSearchStoreResumableResponseFromMldev");var Gp="Content-Type",Rp="X-Server-Timeout",Mp="User-Agent",Xo="x-goog-api-client",Dp="1.33.0",kp=`google-genai-sdk/${Dp}`,Lp="v1beta1",Up="v1beta",Yo=class{static{f(this,"ApiClient")}constructor(e){var t,o;this.clientOptions=Object.assign(Object.assign({},e),{project:e.project,location:e.location,apiKey:e.apiKey,vertexai:e.vertexai});let i={};this.clientOptions.vertexai?(i.apiVersion=(t=this.clientOptions.apiVersion)!==null&&t!==void 0?t:Lp,i.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(i.apiVersion=(o=this.clientOptions.apiVersion)!==null&&o!==void 0?o:Up,i.baseUrl="https://generativelanguage.googleapis.com/"),i.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=i,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(i,e.httpOptions))}baseUrlFromProjectLocation(){return this.clientOptions.project&&this.clientOptions.location&&this.clientOptions.location!=="global"?`https://${this.clientOptions.location}-aiplatform.googleapis.com/`:"https://aiplatform.googleapis.com/"}normalizeAuthParameters(){if(this.clientOptions.project&&this.clientOptions.location){this.clientOptions.apiKey=void 0;return}this.clientOptions.project=void 0,this.clientOptions.location=void 0}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let o=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&o.push(e.apiVersion),o.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=this.getBaseUrl(),t=new URL(e);return t.protocol=t.protocol=="http:"?"ws":"wss",t.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}constructUrl(e,t,o){let i=[this.getRequestUrlInternal(t)];return o&&i.push(this.getBaseResourcePath()),e!==""&&i.push(e),new URL(`${i.join("/")}`)}shouldPrependVertexProjectPath(e){return!(this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let o=this.shouldPrependVertexProjectPath(e),i=this.constructUrl(e.path,t,o);if(e.queryParams)for(let[a,c]of Object.entries(e.queryParams))i.searchParams.append(a,String(c));let r={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else r.body=e.body;return r=await this.includeExtraHttpOptionsToRequestInit(r,t,i.toString(),e.abortSignal),this.unaryApiCall(i,r,e.httpMethod)}patchHttpOptions(e,t){let o=JSON.parse(JSON.stringify(e));for(let[i,r]of Object.entries(t))typeof r=="object"?o[i]=Object.assign(Object.assign({},o[i]),r):r!==void 0&&(o[i]=r);return o}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let o=this.shouldPrependVertexProjectPath(e),i=this.constructUrl(e.path,t,o);(!i.searchParams.has("alt")||i.searchParams.get("alt")!=="sse")&&i.searchParams.set("alt","sse");let r={};return r.body=e.body,r=await this.includeExtraHttpOptionsToRequestInit(r,t,i.toString(),e.abortSignal),this.streamApiCall(i,r,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,t,o,i){if(t&&t.timeout||i){let r=new AbortController,a=r.signal;if(t.timeout&&t?.timeout>0){let c=setTimeout(()=>r.abort(),t.timeout);c&&typeof c.unref=="function"&&c.unref()}i&&i.addEventListener("abort",()=>{r.abort()}),e.signal=a}return t&&t.extraBody!==null&&Fp(e,t.extraBody),e.headers=await this.getHeadersInternal(t,o),e}async unaryApiCall(e,t,o){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:o})).then(async i=>(await ca(i),new xt(i))).catch(i=>{throw i instanceof Error?i:new Error(JSON.stringify(i))})}async streamApiCall(e,t,o){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:o})).then(async i=>(await ca(i),this.processStreamResponse(i))).catch(i=>{throw i instanceof Error?i:new Error(JSON.stringify(i))})}processStreamResponse(e){return ve(this,arguments,f(function*(){var o;let i=(o=e?.body)===null||o===void 0?void 0:o.getReader(),r=new TextDecoder("utf-8");if(!i)throw new Error("Response body is empty");try{let a="",c="data:",d=[`
|
|
1172
1172
|
|
|
1173
1173
|
`,"\r\r",`\r
|
|
1174
1174
|
\r
|
|
1175
|
-
`];for(;;){let{done:u,value:p}=yield $(i.read());if(u){if(l.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let m=r.decode(p,{stream:!0});try{let b=JSON.parse(m);if("error"in b){let E=JSON.parse(JSON.stringify(b.error)),I=E.status,v=E.code,w=`got status: ${I}. ${JSON.stringify(b)}`;if(v>=400&&v<600)throw new bn({message:w,status:v})}}catch(b){if(b.name==="ApiError")throw b}l+=m;let h=-1,g=0;for(;;){h=-1,g=0;for(let I of d){let v=l.indexOf(I);v!==-1&&(h===-1||v<h)&&(h=v,g=I.length)}if(h===-1)break;let b=l.substring(0,h);l=l.substring(h+g);let E=b.trim();if(E.startsWith(c)){let I=E.substring(c.length).trim();try{let v=new Response(I,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield $(new xt(v))}catch(v){throw new Error(`exception parsing stream chunk ${I}. ${v}`)}}}}}finally{i.releaseLock()}},"processStreamResponse_1"))}async apiCall(e,t){return fetch(e,t).catch(o=>{throw new Error(`exception ${o} sending request`)})}getDefaultHeaders(){let e={},t=Mp+" "+this.clientOptions.userAgentExtra;return e[Rp]=t,e[Wo]=t,e[Np]="application/json",e}async getHeadersInternal(e,t){let o=new Headers;if(e&&e.headers){for(let[i,r]of Object.entries(e.headers))o.append(i,r);e.timeout&&e.timeout>0&&o.append($p,String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(o,t),o}getFileName(e){var t;let o="";return typeof e=="string"&&(o=e.replace(/[/\\]+$/,""),o=(t=o.split(/[/\\]/).pop())!==null&&t!==void 0?t:""),o}async uploadFile(e,t){var o;let i={};t!=null&&(i.mimeType=t.mimeType,i.name=t.name,i.displayName=t.displayName),i.name&&!i.name.startsWith("files/")&&(i.name=`files/${i.name}`);let r=this.clientOptions.uploader,l=await r.stat(e);i.sizeBytes=String(l.size);let c=(o=t?.mimeType)!==null&&o!==void 0?o:l.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");i.mimeType=c;let d={file:i},u=this.getFileName(e),p=_("upload/v1beta/files",d._url),m=await this.fetchUploadUrl(p,i.sizeBytes,i.mimeType,u,d,t?.httpOptions);return r.upload(e,m,this)}async uploadFileToFileSearchStore(e,t,o){var i;let r=this.clientOptions.uploader,l=await r.stat(t),c=String(l.size),d=(i=o?.mimeType)!==null&&i!==void 0?i:l.type;if(d===void 0||d==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let u=`upload/v1beta/${e}:uploadToFileSearchStore`,p=this.getFileName(t),m={};o!=null&&Oa(o,m);let h=await this.fetchUploadUrl(u,c,d,p,m,o?.httpOptions);return r.uploadToFileSearchStore(t,h,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,t,o,i,r,l){var c;let d={};l?d=l:d={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${o}`},i?{"X-Goog-Upload-File-Name":i}:{})};let u=await this.request({path:e,body:JSON.stringify(r),httpMethod:"POST",httpOptions:d});if(!u||!u?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let p=(c=u?.headers)===null||c===void 0?void 0:c["x-goog-upload-url"];if(p===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return p}};async function aa(n){var e;if(n===void 0)throw new Error("response is undefined");if(!n.ok){let t=n.status,o;!((e=n.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?o=await n.json():o={error:{message:await n.text(),code:n.status,status:n.statusText}};let i=JSON.stringify(o);throw t>=400&&t<600?new bn({message:i,status:t}):new Error(i)}}f(aa,"throwErrorIfNotOK");function kp(n,e){if(!e||Object.keys(e).length===0)return;if(n.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let t={};if(typeof n.body=="string"&&n.body.length>0)try{let r=JSON.parse(n.body);if(typeof r=="object"&&r!==null&&!Array.isArray(r))t=r;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function o(r,l){let c=Object.assign({},r);for(let d in l)if(Object.prototype.hasOwnProperty.call(l,d)){let u=l[d],p=c[d];u&&typeof u=="object"&&!Array.isArray(u)&&p&&typeof p=="object"&&!Array.isArray(p)?c[d]=o(p,u):(p&&u&&typeof p!=typeof u&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${d}". Original type: ${typeof p}, New type: ${typeof u}. Overwriting.`),c[d]=u)}return c}f(o,"deepMerge");let i=o(t,e);n.body=JSON.stringify(i)}f(kp,"includeExtraBodyToRequestInit");var Up="mcp_used/unknown",Fp=!1;function za(n){for(let e of n)if(Hp(e)||typeof e=="object"&&"inputSchema"in e)return!0;return Fp}f(za,"hasMcpToolUsage");function Ja(n){var e;let t=(e=n[Wo])!==null&&e!==void 0?e:"";n[Wo]=(t+` ${Up}`).trimStart()}f(Ja,"setMcpUsageHeader");function Hp(n){return n!==null&&typeof n=="object"&&n instanceof Xo}f(Hp,"isMcpCallableTool");function Vp(n){return Ie(this,arguments,f(function*(t,o=100){let i,r=0;for(;r<o;){let l=yield $(t.listTools({cursor:i}));for(let c of l.tools)yield yield $(c),r++;if(!l.nextCursor)break;i=l.nextCursor}},"listAllTools_1"))}f(Vp,"listAllTools");var Xo=class n{static{f(this,"McpCallableTool")}constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(e,t){return new n(e,t)}async initialize(){var e,t,o,i;if(this.mcpTools.length>0)return;let r={},l=[];for(let p of this.mcpClients)try{for(var c=!0,d=(t=void 0,ve(Vp(p))),u;u=await d.next(),e=u.done,!e;c=!0){i=u.value,c=!1;let m=i;l.push(m);let h=m.name;if(r[h])throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`);r[h]=p}}catch(m){t={error:m}}finally{try{!c&&!e&&(o=d.return)&&await o.call(d)}finally{if(t)throw t.error}}this.mcpTools=l,this.functionNameToMcpClient=r}async tool(){return await this.initialize(),_c(this.mcpTools,this.config)}async callTool(e){await this.initialize();let t=[];for(let o of e)if(o.name in this.functionNameToMcpClient){let i=this.functionNameToMcpClient[o.name],r;this.config.timeout&&(r={timeout:this.config.timeout});let l=await i.callTool({name:o.name,arguments:o.args},void 0,r);t.push({functionResponse:{name:o.name,response:l.isError?{error:l}:l}})}return t}};async function Bp(n,e,t){let o=new Lo,i;t.data instanceof Blob?i=JSON.parse(await t.data.text()):i=JSON.parse(t.data),Object.assign(o,i),e(o)}f(Bp,"handleWebSocketMessage$1");var Yo=class{static{f(this,"LiveMusic")}constructor(e,t,o){this.apiClient=e,this.auth=t,this.webSocketFactory=o}async connect(e){var t,o;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let i=this.apiClient.getWebsocketBaseUrl(),r=this.apiClient.getApiVersion(),l=Op(this.apiClient.getDefaultHeaders()),c=this.apiClient.getApiKey(),d=`${i}/ws/google.ai.generativelanguage.${r}.GenerativeService.BidiGenerateMusic?key=${c}`,u=f(()=>{},"onopenResolve"),p=new Promise(T=>{u=T}),m=e.callbacks,h=f(function(){u({})},"onopenAwaitedCallback"),g=this.apiClient,b={onopen:h,onmessage:f(T=>{Bp(g,m.onmessage,T)},"onmessage"),onerror:(t=m?.onerror)!==null&&t!==void 0?t:function(T){},onclose:(o=m?.onclose)!==null&&o!==void 0?o:function(T){}},E=this.webSocketFactory.create(d,qp(l),b);E.connect(),await p;let w={setup:{model:L(this.apiClient,e.model)}};return E.send(JSON.stringify(w)),new Qo(E,this.apiClient)}},Qo=class{static{f(this,"LiveMusicSession")}constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");let t=gu(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let t=hu(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){let t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(dt.PLAY)}pause(){this.sendPlaybackControl(dt.PAUSE)}stop(){this.sendPlaybackControl(dt.STOP)}resetContext(){this.sendPlaybackControl(dt.RESET_CONTEXT)}close(){this.conn.close()}};function qp(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}f(qp,"headersToMap$1");function Op(n){let e=new Headers;for(let[t,o]of Object.entries(n))e.append(t,o);return e}f(Op,"mapToHeaders$1");var zp="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function Jp(n,e,t){let o=new Do,i;t.data instanceof Blob?i=await t.data.text():t.data instanceof ArrayBuffer?i=new TextDecoder().decode(t.data):i=t.data;let r=JSON.parse(i);if(n.isVertexAI()){let l=Eu(r);Object.assign(o,l)}else Object.assign(o,r);e(o)}f(Jp,"handleWebSocketMessage");var Zo=class{static{f(this,"Live")}constructor(e,t,o){this.apiClient=e,this.auth=t,this.webSocketFactory=o,this.music=new Yo(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,o,i,r,l,c;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let d=this.apiClient.getWebsocketBaseUrl(),u=this.apiClient.getApiVersion(),p,m=this.apiClient.getHeaders();e.config&&e.config.tools&&za(e.config.tools)&&Ja(m);let h=Xp(m);if(this.apiClient.isVertexAI())p=`${d}/ws/google.cloud.aiplatform.${u}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(h,p);else{let x=this.apiClient.getApiKey(),D="BidiGenerateContent",J="key";x?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),u!=="v1alpha"&&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."),D="BidiGenerateContentConstrained",J="access_token"),p=`${d}/ws/google.ai.generativelanguage.${u}.GenerativeService.${D}?${J}=${x}`}let g=f(()=>{},"onopenResolve"),b=new Promise(x=>{g=x}),E=e.callbacks,I=f(function(){var x;(x=E?.onopen)===null||x===void 0||x.call(E),g({})},"onopenAwaitedCallback"),v=this.apiClient,w={onopen:I,onmessage:f(x=>{Jp(v,E.onmessage,x)},"onmessage"),onerror:(t=E?.onerror)!==null&&t!==void 0?t:function(x){},onclose:(o=E?.onclose)!==null&&o!==void 0?o:function(x){}},T=this.webSocketFactory.create(p,Kp(h),w);T.connect(),await b;let C=L(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&C.startsWith("publishers/")){let x=this.apiClient.getProject(),D=this.apiClient.getLocation();C=`projects/${x}/locations/${D}/`+C}let A={};this.apiClient.isVertexAI()&&((i=e.config)===null||i===void 0?void 0:i.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[tn.AUDIO]}:e.config.responseModalities=[tn.AUDIO]),!((r=e.config)===null||r===void 0)&&r.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");let G=(c=(l=e.config)===null||l===void 0?void 0:l.tools)!==null&&c!==void 0?c:[],N=[];for(let x of G)if(this.isCallableTool(x)){let D=x;N.push(await D.tool())}else N.push(x);N.length>0&&(e.config.tools=N);let H={model:C,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?A=mu(this.apiClient,H):A=pu(this.apiClient,H),delete A.config,T.send(JSON.stringify(A)),new jo(T,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},Wp={turnComplete:!0},jo=class{static{f(this,"Session")}constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(t.turns!==null&&t.turns!==void 0){let o=[];try{o=he(t.turns),e.isVertexAI()||(o=o.map(i=>Gn(i)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:o,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let o=[];if(t.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(t.functionResponses)?o=t.functionResponses:o=[t.functionResponses],o.length===0)throw new Error("functionResponses is required.");for(let r of o){if(typeof r!="object"||r===null||!("name"in r)||!("response"in r))throw new Error(`Could not parse function response, type '${typeof r}'.`);if(!e.isVertexAI()&&!("id"in r))throw new Error(zp)}return{toolResponse:{functionResponses:o}}}sendClientContent(e){e=Object.assign(Object.assign({},Wp),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};this.apiClient.isVertexAI()?t={realtimeInput:yu(e)}:t={realtimeInput:bu(e)},this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");let t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}close(){this.conn.close()}};function Kp(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}f(Kp,"headersToMap");function Xp(n){let e=new Headers;for(let[t,o]of Object.entries(n))e.append(t,o);return e}f(Xp,"mapToHeaders");var la=10;function ca(n){var e,t,o;if(!((e=n?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let i=!1;for(let l of(t=n?.tools)!==null&&t!==void 0?t:[])if(ft(l)){i=!0;break}if(!i)return!0;let r=(o=n?.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls;return r&&(r<0||!Number.isInteger(r))||r==0?(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:",r),!0):!1}f(ca,"shouldDisableAfc");function ft(n){return"callTool"in n&&typeof n.callTool=="function"}f(ft,"isCallableTool");function Yp(n){var e,t,o;return(o=(t=(e=n.config)===null||e===void 0?void 0:e.tools)===null||t===void 0?void 0:t.some(i=>ft(i)))!==null&&o!==void 0?o:!1}f(Yp,"hasCallableTools");function da(n){var e;let t=[];return!((e=n?.config)===null||e===void 0)&&e.tools&&n.config.tools.forEach((o,i)=>{if(ft(o))return;let r=o;r.functionDeclarations&&r.functionDeclarations.length>0&&t.push(i)}),t}f(da,"findAfcIncompatibleToolIndexes");function ua(n){var e;return!(!((e=n?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}f(ua,"shouldAppendAfcHistory");var ei=class extends we{static{f(this,"Models")}constructor(e){super(),this.apiClient=e,this.generateContent=async t=>{var o,i,r,l,c;let d=await this.processParamsMaybeAddMcpUsage(t);if(this.maybeMoveToResponseJsonSchem(t),!Yp(t)||ca(t.config))return await this.generateContentInternal(d);let u=da(t);if(u.length>0){let E=u.map(I=>`tools[${I}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${E}.`)}let p,m,h=he(d.contents),g=(r=(i=(o=d.config)===null||o===void 0?void 0:o.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&r!==void 0?r:la,b=0;for(;b<g&&(p=await this.generateContentInternal(d),!(!p.functionCalls||p.functionCalls.length===0));){let E=p.candidates[0].content,I=[];for(let v of(c=(l=t.config)===null||l===void 0?void 0:l.tools)!==null&&c!==void 0?c:[])if(ft(v)){let T=await v.callTool(p.functionCalls);I.push(...T)}b++,m={role:"user",parts:I},d.contents=he(d.contents),d.contents.push(E),d.contents.push(m),ua(d.config)&&(h.push(E),h.push(m))}return ua(d.config)&&(p.automaticFunctionCallingHistory=h),p},this.generateContentStream=async t=>{var o,i,r,l,c;if(this.maybeMoveToResponseJsonSchem(t),ca(t.config)){let m=await this.processParamsMaybeAddMcpUsage(t);return await this.generateContentStreamInternal(m)}let d=da(t);if(d.length>0){let m=d.map(h=>`tools[${h}]`).join(", ");throw new Error(`Incompatible tools found at ${m}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let u=(r=(i=(o=t?.config)===null||o===void 0?void 0:o.toolConfig)===null||i===void 0?void 0:i.functionCallingConfig)===null||r===void 0?void 0:r.streamFunctionCallArguments,p=(c=(l=t?.config)===null||l===void 0?void 0:l.automaticFunctionCalling)===null||c===void 0?void 0:c.disable;if(u&&!p)throw new 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(t)},this.generateImages=async t=>await this.generateImagesInternal(t).then(o=>{var i;let r,l=[];if(o?.generatedImages)for(let d of o.generatedImages)d&&d?.safetyAttributes&&((i=d?.safetyAttributes)===null||i===void 0?void 0:i.contentType)==="Positive Prompt"?r=d?.safetyAttributes:l.push(d);let c;return r?c={generatedImages:l,positivePromptSafetyAttributes:r,sdkHttpResponse:o.sdkHttpResponse}:c={generatedImages:l,sdkHttpResponse:o.sdkHttpResponse},c}),this.list=async t=>{var o;let l={config:Object.assign(Object.assign({},{queryBase:!0}),t?.config)};if(this.apiClient.isVertexAI()&&!l.config.queryBase){if(!((o=l.config)===null||o===void 0)&&o.filter)throw new Error("Filtering tuned models list for Vertex AI is not currently supported");l.config.filter="labels.tune-type:*"}return new Ge(Re.PAGED_ITEM_MODELS,c=>this.listInternal(c),await this.listInternal(l),l)},this.editImage=async t=>{let o={model:t.model,prompt:t.prompt,referenceImages:[],config:t.config};return t.referenceImages&&t.referenceImages&&(o.referenceImages=t.referenceImages.map(i=>i.toReferenceImageAPI())),await this.editImageInternal(o)},this.upscaleImage=async t=>{let o={numberOfImages:1,mode:"upscale"};t.config&&(o=Object.assign(Object.assign({},o),t.config));let i={model:t.model,image:t.image,upscaleFactor:t.upscaleFactor,config:o};return await this.upscaleImageInternal(i)},this.generateVideos=async t=>{var o,i,r,l,c,d;if((t.prompt||t.image||t.video)&&t.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return this.apiClient.isVertexAI()||(!((o=t.video)===null||o===void 0)&&o.uri&&(!((i=t.video)===null||i===void 0)&&i.videoBytes)?t.video={uri:t.video.uri,mimeType:t.video.mimeType}:!((l=(r=t.source)===null||r===void 0?void 0:r.video)===null||l===void 0)&&l.uri&&(!((d=(c=t.source)===null||c===void 0?void 0:c.video)===null||d===void 0)&&d.videoBytes)&&(t.source.video={uri:t.source.video.uri,mimeType:t.source.video.mimeType})),await this.generateVideosInternal(t)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var t,o,i;let r=(t=e.config)===null||t===void 0?void 0:t.tools;if(!r)return e;let l=await Promise.all(r.map(async d=>ft(d)?await d.tool():d)),c={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:l})};if(c.config.tools=l,e.config&&e.config.tools&&za(e.config.tools)){let d=(i=(o=e.config.httpOptions)===null||o===void 0?void 0:o.headers)!==null&&i!==void 0?i:{},u=Object.assign({},d);Object.keys(u).length===0&&(u=this.apiClient.getDefaultHeaders()),Ja(u),c.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:u})}return c}async initAfcToolsMap(e){var t,o,i;let r=new Map;for(let l of(o=(t=e.config)===null||t===void 0?void 0:t.tools)!==null&&o!==void 0?o:[])if(ft(l)){let c=l,d=await c.tool();for(let u of(i=d.functionDeclarations)!==null&&i!==void 0?i:[]){if(!u.name)throw new Error("Function declaration name is required.");if(r.has(u.name))throw new Error(`Duplicate tool declaration name: ${u.name}`);r.set(u.name,c)}}return r}async processAfcStream(e){var t,o,i;let r=(i=(o=(t=e.config)===null||t===void 0?void 0:t.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&i!==void 0?i:la,l=!1,c=0,d=await this.initAfcToolsMap(e);return function(u,p,m){return Ie(this,arguments,function*(){for(var h,g,b,E,I,v;c<r;){l&&(c++,l=!1);let A=yield $(u.processParamsMaybeAddMcpUsage(m)),G=yield $(u.generateContentStreamInternal(A)),N=[],H=[];try{for(var w=!0,T=(g=void 0,ve(G)),C;C=yield $(T.next()),h=C.done,!h;w=!0){E=C.value,w=!1;let x=E;if(yield yield $(x),x.candidates&&(!((I=x.candidates[0])===null||I===void 0)&&I.content)){H.push(x.candidates[0].content);for(let D of(v=x.candidates[0].content.parts)!==null&&v!==void 0?v:[])if(c<r&&D.functionCall){if(!D.functionCall.name)throw new Error("Function call name was not returned by the model.");if(p.has(D.functionCall.name)){let J=yield $(p.get(D.functionCall.name).callTool([D.functionCall]));N.push(...J)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${p.keys()}, mising tool: ${D.functionCall.name}`)}}}}catch(x){g={error:x}}finally{try{!w&&!h&&(b=T.return)&&(yield $(b.call(T)))}finally{if(g)throw g.error}}if(N.length>0){l=!0;let x=new je;x.candidates=[{content:{role:"user",parts:N}}],yield yield $(x);let D=[];D.push(...H),D.push({role:"user",parts:N});let J=he(m.contents).concat(D);m.contents=J}else break}})}(this,d,e)}async generateContentInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=ia(this.apiClient,e);return c=_("{model}:generateContent",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=sa(p),h=new je;return Object.assign(h,m),h})}else{let u=oa(this.apiClient,e);return c=_("{model}:generateContent",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=ra(p),h=new je;return Object.assign(h,m),h})}}async generateContentStreamInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=ia(this.apiClient,e);return c=_("{model}:streamGenerateContent?alt=sse",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.requestStream({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}),l.then(function(m){return Ie(this,arguments,function*(){var h,g,b,E;try{for(var I=!0,v=ve(m),w;w=yield $(v.next()),h=w.done,!h;I=!0){E=w.value,I=!1;let T=E,C=sa(yield $(T.json()));C.sdkHttpResponse={headers:T.headers};let A=new je;Object.assign(A,C),yield yield $(A)}}catch(T){g={error:T}}finally{try{!I&&!h&&(b=v.return)&&(yield $(b.call(v)))}finally{if(g)throw g.error}}})})}else{let u=oa(this.apiClient,e);return c=_("{model}:streamGenerateContent?alt=sse",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.requestStream({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}),l.then(function(m){return Ie(this,arguments,function*(){var h,g,b,E;try{for(var I=!0,v=ve(m),w;w=yield $(v.next()),h=w.done,!h;I=!0){E=w.value,I=!1;let T=E,C=ra(yield $(T.json()));C.sdkHttpResponse={headers:T.headers};let A=new je;Object.assign(A,C),yield yield $(A)}}catch(T){g={error:T}}finally{try{!I&&!h&&(b=v.return)&&(yield $(b.call(v)))}finally{if(g)throw g.error}}})})}}async embedContent(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=Xu(this.apiClient,e);return c=_("{model}:predict",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=Qu(p),h=new on;return Object.assign(h,m),h})}else{let u=Ku(this.apiClient,e);return c=_("{model}:batchEmbedContents",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=Yu(p),h=new on;return Object.assign(h,m),h})}}async generateImagesInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=cf(this.apiClient,e);return c=_("{model}:predict",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=uf(p),h=new rn;return Object.assign(h,m),h})}else{let u=lf(this.apiClient,e);return c=_("{model}:predict",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=df(p),h=new rn;return Object.assign(h,m),h})}}async editImageInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI()){let c=Ou(this.apiClient,e);return r=_("{model}:predict",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>{let u=zu(d),p=new To;return Object.assign(p,u),p})}else throw new Error("This method is only supported by the Vertex AI.")}async upscaleImageInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI()){let c=cp(this.apiClient,e);return r=_("{model}:predict",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>{let u=dp(d),p=new _o;return Object.assign(p,u),p})}else throw new Error("This method is only supported by the Vertex AI.")}async recontextImage(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI()){let c=Of(this.apiClient,e);return r=_("{model}:predict",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=zf(d),p=new Co;return Object.assign(p,u),p})}else throw new Error("This method is only supported by the Vertex AI.")}async segmentImage(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI()){let c=Qf(this.apiClient,e);return r=_("{model}:predict",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=Zf(d),p=new So;return Object.assign(p,u),p})}else throw new Error("This method is only supported by the Vertex AI.")}async get(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=xf(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),l.then(p=>Jo(p))}else{let u=Af(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),l.then(p=>zo(p))}}async listInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=kf(this.apiClient,e);return c=_("{models_url}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=Ff(p),h=new sn;return Object.assign(h,m),h})}else{let u=Lf(this.apiClient,e);return c=_("{models_url}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=Uf(p),h=new sn;return Object.assign(h,m),h})}}async update(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=ap(this.apiClient,e);return c=_("{model}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),l.then(p=>Jo(p))}else{let u=sp(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),l.then(p=>zo(p))}}async delete(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=Hu(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=Bu(p),h=new an;return Object.assign(h,m),h})}else{let u=Fu(this.apiClient,e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=Vu(p),h=new an;return Object.assign(h,m),h})}}async countTokens(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=Lu(this.apiClient,e);return c=_("{model}:countTokens",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=Uu(p),h=new ln;return Object.assign(h,m),h})}else{let u=Du(this.apiClient,e);return c=_("{model}:countTokens",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=ku(p),h=new ln;return Object.assign(h,m),h})}}async computeTokens(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI()){let c=xu(this.apiClient,e);return r=_("{model}:computeTokens",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>{let u=Pu(d),p=new Ao;return Object.assign(p,u),p})}else throw new Error("This method is only supported by the Vertex AI.")}async generateVideosInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=bf(this.apiClient,e);return c=_("{model}:predictLongRunning",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),l.then(p=>{let m=hf(p),h=new cn;return Object.assign(h,m),h})}else{let u=gf(this.apiClient,e);return c=_("{model}:predictLongRunning",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),l.then(p=>{let m=mf(p),h=new cn;return Object.assign(h,m),h})}}};var ti=class extends we{static{f(this,"Operations")}constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let t=e.operation,o=e.config;if(t.name===void 0||t.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=t.name.split("/operations/")[0],r;o&&"httpOptions"in o&&(r=o.httpOptions);let l=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:i,config:{httpOptions:r}});return t._fromAPIResponse({apiResponse:l,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:t.name,config:o});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async get(e){let t=e.operation,o=e.config;if(t.name===void 0||t.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=t.name.split("/operations/")[0],r;o&&"httpOptions"in o&&(r=o.httpOptions);let l=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:i,config:{httpOptions:r}});return t._fromAPIResponse({apiResponse:l,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:t.name,config:o});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=uc(e);return c=_("{operationName}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),l}else{let u=dc(e);return c=_("{operationName}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),l}}async fetchPredictVideosOperationInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI()){let c=oc(e);return r=_("{resourceName}:fetchPredictOperation",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i}else throw new Error("This method is only supported by the Vertex AI.")}};function Qp(n){let e={},t=s(n,["data"]);if(t!=null&&a(e,["data"],t),s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(Qp,"blobToMldev");function Zp(n){let e={},t=s(n,["parts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(r=>am(r))),a(e,["parts"],i)}let o=s(n,["role"]);return o!=null&&a(e,["role"],o),e}f(Zp,"contentToMldev");function jp(n,e,t){let o={},i=s(e,["expireTime"]);t!==void 0&&i!=null&&a(t,["expireTime"],i);let r=s(e,["newSessionExpireTime"]);t!==void 0&&r!=null&&a(t,["newSessionExpireTime"],r);let l=s(e,["uses"]);t!==void 0&&l!=null&&a(t,["uses"],l);let c=s(e,["liveConnectConstraints"]);t!==void 0&&c!=null&&a(t,["bidiGenerateContentSetup"],sm(n,c));let d=s(e,["lockAdditionalFields"]);return t!==void 0&&d!=null&&a(t,["fieldMask"],d),o}f(jp,"createAuthTokenConfigToMldev");function em(n,e){let t={},o=s(e,["config"]);return o!=null&&a(t,["config"],jp(n,o,t)),t}f(em,"createAuthTokenParametersToMldev");function tm(n){let e={};if(s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=s(n,["fileUri"]);t!=null&&a(e,["fileUri"],t);let o=s(n,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}f(tm,"fileDataToMldev");function nm(n){let e={},t=s(n,["id"]);t!=null&&a(e,["id"],t);let o=s(n,["args"]);o!=null&&a(e,["args"],o);let i=s(n,["name"]);if(i!=null&&a(e,["name"],i),s(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(s(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}f(nm,"functionCallToMldev");function om(n){let e={};if(s(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=s(n,["enableWidget"]);return t!=null&&a(e,["enableWidget"],t),e}f(om,"googleMapsToMldev");function im(n){let e={};if(s(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(s(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=s(n,["timeRangeFilter"]);return t!=null&&a(e,["timeRangeFilter"],t),e}f(im,"googleSearchToMldev");function rm(n,e){let t={},o=s(n,["generationConfig"]);e!==void 0&&o!=null&&a(e,["setup","generationConfig"],o);let i=s(n,["responseModalities"]);e!==void 0&&i!=null&&a(e,["setup","generationConfig","responseModalities"],i);let r=s(n,["temperature"]);e!==void 0&&r!=null&&a(e,["setup","generationConfig","temperature"],r);let l=s(n,["topP"]);e!==void 0&&l!=null&&a(e,["setup","generationConfig","topP"],l);let c=s(n,["topK"]);e!==void 0&&c!=null&&a(e,["setup","generationConfig","topK"],c);let d=s(n,["maxOutputTokens"]);e!==void 0&&d!=null&&a(e,["setup","generationConfig","maxOutputTokens"],d);let u=s(n,["mediaResolution"]);e!==void 0&&u!=null&&a(e,["setup","generationConfig","mediaResolution"],u);let p=s(n,["seed"]);e!==void 0&&p!=null&&a(e,["setup","generationConfig","seed"],p);let m=s(n,["speechConfig"]);e!==void 0&&m!=null&&a(e,["setup","generationConfig","speechConfig"],Ti(m));let h=s(n,["thinkingConfig"]);e!==void 0&&h!=null&&a(e,["setup","generationConfig","thinkingConfig"],h);let g=s(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&a(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=s(n,["systemInstruction"]);e!==void 0&&b!=null&&a(e,["setup","systemInstruction"],Zp(ie(b)));let E=s(n,["tools"]);if(e!==void 0&&E!=null){let G=gt(E);Array.isArray(G)&&(G=G.map(N=>cm(ht(N)))),a(e,["setup","tools"],G)}let I=s(n,["sessionResumption"]);e!==void 0&&I!=null&&a(e,["setup","sessionResumption"],lm(I));let v=s(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&a(e,["setup","inputAudioTranscription"],v);let w=s(n,["outputAudioTranscription"]);e!==void 0&&w!=null&&a(e,["setup","outputAudioTranscription"],w);let T=s(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&a(e,["setup","realtimeInputConfig"],T);let C=s(n,["contextWindowCompression"]);e!==void 0&&C!=null&&a(e,["setup","contextWindowCompression"],C);let A=s(n,["proactivity"]);if(e!==void 0&&A!=null&&a(e,["setup","proactivity"],A),s(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}f(rm,"liveConnectConfigToMldev");function sm(n,e){let t={},o=s(e,["model"]);o!=null&&a(t,["setup","model"],L(n,o));let i=s(e,["config"]);return i!=null&&a(t,["config"],rm(i,t)),t}f(sm,"liveConnectConstraintsToMldev");function am(n){let e={},t=s(n,["mediaResolution"]);t!=null&&a(e,["mediaResolution"],t);let o=s(n,["codeExecutionResult"]);o!=null&&a(e,["codeExecutionResult"],o);let i=s(n,["executableCode"]);i!=null&&a(e,["executableCode"],i);let r=s(n,["fileData"]);r!=null&&a(e,["fileData"],tm(r));let l=s(n,["functionCall"]);l!=null&&a(e,["functionCall"],nm(l));let c=s(n,["functionResponse"]);c!=null&&a(e,["functionResponse"],c);let d=s(n,["inlineData"]);d!=null&&a(e,["inlineData"],Qp(d));let u=s(n,["text"]);u!=null&&a(e,["text"],u);let p=s(n,["thought"]);p!=null&&a(e,["thought"],p);let m=s(n,["thoughtSignature"]);m!=null&&a(e,["thoughtSignature"],m);let h=s(n,["videoMetadata"]);return h!=null&&a(e,["videoMetadata"],h),e}f(am,"partToMldev");function lm(n){let e={},t=s(n,["handle"]);if(t!=null&&a(e,["handle"],t),s(n,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}f(lm,"sessionResumptionConfigToMldev");function cm(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let p=t;Array.isArray(p)&&(p=p.map(m=>m)),a(e,["functionDeclarations"],p)}if(s(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let o=s(n,["googleSearchRetrieval"]);o!=null&&a(e,["googleSearchRetrieval"],o);let i=s(n,["computerUse"]);i!=null&&a(e,["computerUse"],i);let r=s(n,["fileSearch"]);r!=null&&a(e,["fileSearch"],r);let l=s(n,["codeExecution"]);if(l!=null&&a(e,["codeExecution"],l),s(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=s(n,["googleMaps"]);c!=null&&a(e,["googleMaps"],om(c));let d=s(n,["googleSearch"]);d!=null&&a(e,["googleSearch"],im(d));let u=s(n,["urlContext"]);return u!=null&&a(e,["urlContext"],u),e}f(cm,"toolToMldev");function dm(n){let e=[];for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){let o=n[t];if(typeof o=="object"&&o!=null&&Object.keys(o).length>0){let i=Object.keys(o).map(r=>`${t}.${r}`);e.push(...i)}else e.push(t)}return e.join(",")}f(dm,"getFieldMasks");function um(n,e){let t=null,o=n.bidiGenerateContentSetup;if(typeof o=="object"&&o!==null&&"setup"in o){let r=o.setup;typeof r=="object"&&r!==null?(n.bidiGenerateContentSetup=r,t=r):delete n.bidiGenerateContentSetup}else o!==void 0&&delete n.bidiGenerateContentSetup;let i=n.fieldMask;if(t){let r=dm(t);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)r?n.fieldMask=r:delete n.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&i!==null&&Array.isArray(i)&&i.length>0){let l=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],c=[];i.length>0&&(c=i.map(u=>l.includes(u)?`generationConfig.${u}`:u));let d=[];r&&d.push(r),c.length>0&&d.push(...c),d.length>0?n.fieldMask=d.join(","):delete n.fieldMask}else delete n.fieldMask}else i!==null&&Array.isArray(i)&&i.length>0?n.fieldMask=i.join(","):delete n.fieldMask;return n}f(um,"convertBidiSetupToTokenSetup");var ni=class extends we{static{f(this,"Tokens")}constructor(e){super(),this.apiClient=e}async create(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let c=em(this.apiClient,e);r=_("auth_tokens",c._url),l=c._query,delete c.config,delete c._url,delete c._query;let d=um(c,e.config);return i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>u)}}};function fm(n,e){let t={},o=s(n,["force"]);return e!==void 0&&o!=null&&a(e,["_query","force"],o),t}f(fm,"deleteDocumentConfigToMldev");function pm(n){let e={},t=s(n,["name"]);t!=null&&a(e,["_url","name"],t);let o=s(n,["config"]);return o!=null&&fm(o,e),e}f(pm,"deleteDocumentParametersToMldev");function mm(n){let e={},t=s(n,["name"]);return t!=null&&a(e,["_url","name"],t),e}f(mm,"getDocumentParametersToMldev");function hm(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&a(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);return e!==void 0&&i!=null&&a(e,["_query","pageToken"],i),t}f(hm,"listDocumentsConfigToMldev");function gm(n){let e={},t=s(n,["parent"]);t!=null&&a(e,["_url","parent"],t);let o=s(n,["config"]);return o!=null&&hm(o,e),e}f(gm,"listDocumentsParametersToMldev");function bm(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&a(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&a(e,["nextPageToken"],o);let i=s(n,["documents"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(l=>l)),a(e,["documents"],r)}return e}f(bm,"listDocumentsResponseFromMldev");var oi=class extends we{static{f(this,"Documents")}constructor(e){super(),this.apiClient=e,this.list=async t=>new Ge(Re.PAGED_ITEM_DOCUMENTS,o=>this.listInternal({parent:t.parent,config:o.config}),await this.listInternal(t),t)}async get(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=mm(e);return r=_("{name}",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>d)}}async delete(e){var t,o;let i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let l=pm(e);i=_("{name}",l._url),r=l._query,delete l._url,delete l._query,await this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(l),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=gm(e);return r=_("{parent}/documents",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=bm(d),p=new xo;return Object.assign(p,u),p})}}};var ii=class extends we{static{f(this,"FileSearchStores")}constructor(e,t=new oi(e)){super(),this.apiClient=e,this.documents=t,this.list=async(o={})=>new Ge(Re.PAGED_ITEM_FILE_SEARCH_STORES,i=>this.listInternal(i),await this.listInternal(o),o)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Vertex AI does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async create(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=bp(e);return r=_("fileSearchStores",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>d)}}async get(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Ip(e);return r=_("{name}",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>d)}}async delete(e){var t,o;let i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let l=Ep(e);i=_("{name}",l._url),r=l._query,delete l._url,delete l._query,await this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(l),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Sp(e);return r=_("fileSearchStores",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=Ap(d),p=new Po;return Object.assign(p,u),p})}}async uploadToFileSearchStoreInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=xp(e);return r=_("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=Pp(d),p=new No;return Object.assign(p,u),p})}}async importFile(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Tp(e);return r=_("{file_search_store_name}:importFile",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=wp(d),p=new $o;return Object.assign(p,u),p})}}};var Wa=f(function(){let{crypto:n}=globalThis;if(n?.randomUUID)return Wa=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,o=>(+o^t()&15>>+o/4).toString(16))},"uuid4Internal"),ym=f(()=>Wa(),"uuid4");function ri(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}f(ri,"isAbortError");var si=f(n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)},"castToError");var ce=class extends Error{static{f(this,"GeminiNextGenAPIClientError")}},de=class n extends ce{static{f(this,"APIError")}constructor(e,t,o,i){super(`${n.makeMessage(e,t,o)}`),this.status=e,this.headers=i,this.error=t}static makeMessage(e,t,o){let i=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):o;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,t,o,i){if(!e||!i)return new pt({message:o,cause:si(t)});let r=t;return e===400?new En(e,r,o,i):e===401?new In(e,r,o,i):e===403?new vn(e,r,o,i):e===404?new wn(e,r,o,i):e===409?new Tn(e,r,o,i):e===422?new _n(e,r,o,i):e===429?new Cn(e,r,o,i):e>=500?new Sn(e,r,o,i):new n(e,r,o,i)}},Pt=class extends de{static{f(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},pt=class extends de{static{f(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},yn=class extends pt{static{f(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},En=class extends de{static{f(this,"BadRequestError")}},In=class extends de{static{f(this,"AuthenticationError")}},vn=class extends de{static{f(this,"PermissionDeniedError")}},wn=class extends de{static{f(this,"NotFoundError")}},Tn=class extends de{static{f(this,"ConflictError")}},_n=class extends de{static{f(this,"UnprocessableEntityError")}},Cn=class extends de{static{f(this,"RateLimitError")}},Sn=class extends de{static{f(this,"InternalServerError")}};var Em=/^[a-z][a-z0-9+.-]*:/i,Im=f(n=>Em.test(n),"isAbsoluteURL"),ai=f(n=>(ai=Array.isArray,ai(n)),"isArrayInternal"),vm=ai,wm=vm,fa=wm;function Tm(n){if(!n)return!0;for(let e in n)return!1;return!0}f(Tm,"isEmptyObj");function _m(n,e){return Object.prototype.hasOwnProperty.call(n,e)}f(_m,"hasOwn");var Cm=f((n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ce(`${n} must be an integer`);if(e<0)throw new ce(`${n} must be a positive integer`);return e},"validatePositiveInteger"),Sm=f(n=>{try{return JSON.parse(n)}catch{return}},"safeJSON");var Am=f(n=>new Promise(e=>setTimeout(e,n)),"sleep$1");var ct="0.0.1";function xm(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}f(xm,"getDetectedPlatform");var Pm=f(()=>{var n,e,t,o,i;let r=xm();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"X-Stainless-OS":ma(Deno.build.os),"X-Stainless-Arch":pa(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(e=(n=Deno.version)===null||n===void 0?void 0:n.deno)!==null&&e!==void 0?e:"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"X-Stainless-OS":ma((t=globalThis.process.platform)!==null&&t!==void 0?t:"unknown"),"X-Stainless-Arch":pa((o=globalThis.process.arch)!==null&&o!==void 0?o:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(i=globalThis.process.version)!==null&&i!==void 0?i:"unknown"};let l=Nm();return l?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${l.browser}`,"X-Stainless-Runtime-Version":l.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Nm(){if(typeof navigator>"u"||!navigator)return null;let n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of n){let o=t.exec(navigator.userAgent);if(o){let i=o[1]||0,r=o[2]||0,l=o[3]||0;return{browser:e,version:`${i}.${r}.${l}`}}}return null}f(Nm,"getBrowserInfo");var pa=f(n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown","normalizeArch"),ma=f(n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),"normalizePlatform"),Kt,$m=f(()=>Kt??(Kt=Pm()),"getPlatformHeaders");function Rm(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}f(Rm,"getDefaultFetch");function Ka(...n){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}f(Ka,"makeReadableStream");function Gm(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Ka({start(){},async pull(t){let{done:o,value:i}=await e.next();o?t.close():t.enqueue(i)},async cancel(){var t;await((t=e.return)===null||t===void 0?void 0:t.call(e))}})}f(Gm,"ReadableStreamFrom");function Xa(n){if(n[Symbol.asyncIterator])return n;let e=n.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}f(Xa,"ReadableStreamToAsyncIterable");async function Mm(n){var e,t;if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await((t=(e=n[Symbol.asyncIterator]()).return)===null||t===void 0?void 0:t.call(e));return}let o=n.getReader(),i=o.cancel();o.releaseLock(),await i}f(Mm,"CancelReadableStream");var Dm=f(({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var Ya=f(()=>{var n;if(typeof File>"u"){let{process:e}=globalThis,t=typeof((n=e?.versions)===null||n===void 0?void 0:n.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},"checkFileSupport");function yo(n,e,t){return Ya(),new File(n,e??"unknown_file",t)}f(yo,"makeFile");function Lm(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}f(Lm,"getName");var km=f(n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function","isAsyncIterable");var Qa=f(n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function","isBlobLike"),Um=f(n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Qa(n),"isFileLike"),Fm=f(n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function","isResponseLike");async function Hm(n,e,t){if(Ya(),n=await n,Um(n))return n instanceof File?n:yo([await n.arrayBuffer()],n.name);if(Fm(n)){let i=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),yo(await li(i),e,t)}let o=await li(n);if(e||(e=Lm(n)),!t?.type){let i=o.find(r=>typeof r=="object"&&"type"in r&&r.type);typeof i=="string"&&(t=Object.assign(Object.assign({},t),{type:i}))}return yo(o,e,t)}f(Hm,"toFile");async function li(n){var e,t,o,i,r;let l=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)l.push(n);else if(Qa(n))l.push(n instanceof Blob?n:await n.arrayBuffer());else if(km(n))try{for(var c=!0,d=ve(n),u;u=await d.next(),e=u.done,!e;c=!0){i=u.value,c=!1;let p=i;l.push(...await li(p))}}catch(p){t={error:p}}finally{try{!c&&!e&&(o=d.return)&&await o.call(d)}finally{if(t)throw t.error}}else{let p=(r=n?.constructor)===null||r===void 0?void 0:r.name;throw new Error(`Unexpected data type: ${typeof n}${p?`; constructor: ${p}`:""}${Vm(n)}`)}return l}f(li,"getBytes");function Vm(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}f(Vm,"propsForError");var An=class{static{f(this,"APIResource")}constructor(e){this._client=e}};An._key=[];function Za(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}f(Za,"encodeURIPath");var ha=Object.freeze(Object.create(null)),Bm=f((n=Za)=>f(function(t,...o){if(t.length===1)return t[0];let i=!1,r=[],l=t.reduce((p,m,h)=>{var g,b,E;/[?#]/.test(m)&&(i=!0);let I=o[h],v=(i?encodeURIComponent:n)(""+I);return h!==o.length&&(I==null||typeof I=="object"&&I.toString===((E=Object.getPrototypeOf((b=Object.getPrototypeOf((g=I.hasOwnProperty)!==null&&g!==void 0?g:ha))!==null&&b!==void 0?b:ha))===null||E===void 0?void 0:E.toString))&&(v=I+"",r.push({start:p.length+m.length,length:v.length,error:`Value of type ${Object.prototype.toString.call(I).slice(8,-1)} is not a valid path parameter`})),p+m+(h===o.length?"":v)},""),c=l.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=d.exec(c))!==null;)r.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(r.sort((p,m)=>p.start-m.start),r.length>0){let p=0,m=r.reduce((h,g)=>{let b=" ".repeat(g.start-p),E="^".repeat(g.length);return p=g.start+g.length,h+b+E},"");throw new ce(`Path parameters result in path with invalid segments:
|
|
1175
|
+
`];for(;;){let{done:u,value:p}=yield $(i.read());if(u){if(a.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let m=r.decode(p,{stream:!0});try{let b=JSON.parse(m);if("error"in b){let E=JSON.parse(JSON.stringify(b.error)),I=E.status,v=E.code,w=`got status: ${I}. ${JSON.stringify(b)}`;if(v>=400&&v<600)throw new bn({message:w,status:v})}}catch(b){if(b.name==="ApiError")throw b}a+=m;let h=-1,g=0;for(;;){h=-1,g=0;for(let I of d){let v=a.indexOf(I);v!==-1&&(h===-1||v<h)&&(h=v,g=I.length)}if(h===-1)break;let b=a.substring(0,h);a=a.substring(h+g);let E=b.trim();if(E.startsWith(c)){let I=E.substring(c.length).trim();try{let v=new Response(I,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield $(new xt(v))}catch(v){throw new Error(`exception parsing stream chunk ${I}. ${v}`)}}}}}finally{i.releaseLock()}},"processStreamResponse_1"))}async apiCall(e,t){return fetch(e,t).catch(o=>{throw new Error(`exception ${o} sending request`)})}getDefaultHeaders(){let e={},t=kp+" "+this.clientOptions.userAgentExtra;return e[Mp]=t,e[Xo]=t,e[Gp]="application/json",e}async getHeadersInternal(e,t){let o=new Headers;if(e&&e.headers){for(let[i,r]of Object.entries(e.headers))o.append(i,r);e.timeout&&e.timeout>0&&o.append(Rp,String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(o,t),o}getFileName(e){var t;let o="";return typeof e=="string"&&(o=e.replace(/[/\\]+$/,""),o=(t=o.split(/[/\\]/).pop())!==null&&t!==void 0?t:""),o}async uploadFile(e,t){var o;let i={};t!=null&&(i.mimeType=t.mimeType,i.name=t.name,i.displayName=t.displayName),i.name&&!i.name.startsWith("files/")&&(i.name=`files/${i.name}`);let r=this.clientOptions.uploader,a=await r.stat(e);i.sizeBytes=String(a.size);let c=(o=t?.mimeType)!==null&&o!==void 0?o:a.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");i.mimeType=c;let d={file:i},u=this.getFileName(e),p=C("upload/v1beta/files",d._url),m=await this.fetchUploadUrl(p,i.sizeBytes,i.mimeType,u,d,t?.httpOptions);return r.upload(e,m,this)}async uploadFileToFileSearchStore(e,t,o){var i;let r=this.clientOptions.uploader,a=await r.stat(t),c=String(a.size),d=(i=o?.mimeType)!==null&&i!==void 0?i:a.type;if(d===void 0||d==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let u=`upload/v1beta/${e}:uploadToFileSearchStore`,p=this.getFileName(t),m={};o!=null&&Ja(o,m);let h=await this.fetchUploadUrl(u,c,d,p,m,o?.httpOptions);return r.uploadToFileSearchStore(t,h,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,t,o,i,r,a){var c;let d={};a?d=a:d={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${o}`},i?{"X-Goog-Upload-File-Name":i}:{})};let u=await this.request({path:e,body:JSON.stringify(r),httpMethod:"POST",httpOptions:d});if(!u||!u?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let p=(c=u?.headers)===null||c===void 0?void 0:c["x-goog-upload-url"];if(p===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return p}};async function ca(n){var e;if(n===void 0)throw new Error("response is undefined");if(!n.ok){let t=n.status,o;!((e=n.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?o=await n.json():o={error:{message:await n.text(),code:n.status,status:n.statusText}};let i=JSON.stringify(o);throw t>=400&&t<600?new bn({message:i,status:t}):new Error(i)}}f(ca,"throwErrorIfNotOK");function Fp(n,e){if(!e||Object.keys(e).length===0)return;if(n.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let t={};if(typeof n.body=="string"&&n.body.length>0)try{let r=JSON.parse(n.body);if(typeof r=="object"&&r!==null&&!Array.isArray(r))t=r;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function o(r,a){let c=Object.assign({},r);for(let d in a)if(Object.prototype.hasOwnProperty.call(a,d)){let u=a[d],p=c[d];u&&typeof u=="object"&&!Array.isArray(u)&&p&&typeof p=="object"&&!Array.isArray(p)?c[d]=o(p,u):(p&&u&&typeof p!=typeof u&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${d}". Original type: ${typeof p}, New type: ${typeof u}. Overwriting.`),c[d]=u)}return c}f(o,"deepMerge");let i=o(t,e);n.body=JSON.stringify(i)}f(Fp,"includeExtraBodyToRequestInit");var Hp="mcp_used/unknown",Vp=!1;function Wa(n){for(let e of n)if(Bp(e)||typeof e=="object"&&"inputSchema"in e)return!0;return Vp}f(Wa,"hasMcpToolUsage");function Ka(n){var e;let t=(e=n[Xo])!==null&&e!==void 0?e:"";n[Xo]=(t+` ${Hp}`).trimStart()}f(Ka,"setMcpUsageHeader");function Bp(n){return n!==null&&typeof n=="object"&&n instanceof Qo}f(Bp,"isMcpCallableTool");function qp(n){return ve(this,arguments,f(function*(t,o=100){let i,r=0;for(;r<o;){let a=yield $(t.listTools({cursor:i}));for(let c of a.tools)yield yield $(c),r++;if(!a.nextCursor)break;i=a.nextCursor}},"listAllTools_1"))}f(qp,"listAllTools");var Qo=class n{static{f(this,"McpCallableTool")}constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(e,t){return new n(e,t)}async initialize(){var e,t,o,i;if(this.mcpTools.length>0)return;let r={},a=[];for(let p of this.mcpClients)try{for(var c=!0,d=(t=void 0,we(qp(p))),u;u=await d.next(),e=u.done,!e;c=!0){i=u.value,c=!1;let m=i;a.push(m);let h=m.name;if(r[h])throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`);r[h]=p}}catch(m){t={error:m}}finally{try{!c&&!e&&(o=d.return)&&await o.call(d)}finally{if(t)throw t.error}}this.mcpTools=a,this.functionNameToMcpClient=r}async tool(){return await this.initialize(),Sc(this.mcpTools,this.config)}async callTool(e){await this.initialize();let t=[];for(let o of e)if(o.name in this.functionNameToMcpClient){let i=this.functionNameToMcpClient[o.name],r;this.config.timeout&&(r={timeout:this.config.timeout});let a=await i.callTool({name:o.name,arguments:o.args},void 0,r);t.push({functionResponse:{name:o.name,response:a.isError?{error:a}:a}})}return t}};async function Op(n,e,t){let o=new Uo,i;t.data instanceof Blob?i=JSON.parse(await t.data.text()):i=JSON.parse(t.data),Object.assign(o,i),e(o)}f(Op,"handleWebSocketMessage$1");var Zo=class{static{f(this,"LiveMusic")}constructor(e,t,o){this.apiClient=e,this.auth=t,this.webSocketFactory=o}async connect(e){var t,o;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let i=this.apiClient.getWebsocketBaseUrl(),r=this.apiClient.getApiVersion(),a=Jp(this.apiClient.getDefaultHeaders()),c=this.apiClient.getApiKey(),d=`${i}/ws/google.ai.generativelanguage.${r}.GenerativeService.BidiGenerateMusic?key=${c}`,u=f(()=>{},"onopenResolve"),p=new Promise(T=>{u=T}),m=e.callbacks,h=f(function(){u({})},"onopenAwaitedCallback"),g=this.apiClient,b={onopen:h,onmessage:f(T=>{Op(g,m.onmessage,T)},"onmessage"),onerror:(t=m?.onerror)!==null&&t!==void 0?t:function(T){},onclose:(o=m?.onclose)!==null&&o!==void 0?o:function(T){}},E=this.webSocketFactory.create(d,zp(a),b);E.connect(),await p;let w={setup:{model:k(this.apiClient,e.model)}};return E.send(JSON.stringify(w)),new jo(E,this.apiClient)}},jo=class{static{f(this,"LiveMusicSession")}constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");let t=yu(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let t=bu(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){let t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(ut.PLAY)}pause(){this.sendPlaybackControl(ut.PAUSE)}stop(){this.sendPlaybackControl(ut.STOP)}resetContext(){this.sendPlaybackControl(ut.RESET_CONTEXT)}close(){this.conn.close()}};function zp(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}f(zp,"headersToMap$1");function Jp(n){let e=new Headers;for(let[t,o]of Object.entries(n))e.append(t,o);return e}f(Jp,"mapToHeaders$1");var Wp="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function Kp(n,e,t){let o=new Lo,i;t.data instanceof Blob?i=await t.data.text():t.data instanceof ArrayBuffer?i=new TextDecoder().decode(t.data):i=t.data;let r=JSON.parse(i);if(n.isVertexAI()){let a=vu(r);Object.assign(o,a)}else Object.assign(o,r);e(o)}f(Kp,"handleWebSocketMessage");var ei=class{static{f(this,"Live")}constructor(e,t,o){this.apiClient=e,this.auth=t,this.webSocketFactory=o,this.music=new Zo(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,o,i,r,a,c;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let d=this.apiClient.getWebsocketBaseUrl(),u=this.apiClient.getApiVersion(),p,m=this.apiClient.getHeaders();e.config&&e.config.tools&&Wa(e.config.tools)&&Ka(m);let h=Qp(m);if(this.apiClient.isVertexAI())p=`${d}/ws/google.cloud.aiplatform.${u}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(h,p);else{let x=this.apiClient.getApiKey(),D="BidiGenerateContent",J="key";x?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),u!=="v1alpha"&&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."),D="BidiGenerateContentConstrained",J="access_token"),p=`${d}/ws/google.ai.generativelanguage.${u}.GenerativeService.${D}?${J}=${x}`}let g=f(()=>{},"onopenResolve"),b=new Promise(x=>{g=x}),E=e.callbacks,I=f(function(){var x;(x=E?.onopen)===null||x===void 0||x.call(E),g({})},"onopenAwaitedCallback"),v=this.apiClient,w={onopen:I,onmessage:f(x=>{Kp(v,E.onmessage,x)},"onmessage"),onerror:(t=E?.onerror)!==null&&t!==void 0?t:function(x){},onclose:(o=E?.onclose)!==null&&o!==void 0?o:function(x){}},T=this.webSocketFactory.create(p,Yp(h),w);T.connect(),await b;let _=k(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&_.startsWith("publishers/")){let x=this.apiClient.getProject(),D=this.apiClient.getLocation();_=`projects/${x}/locations/${D}/`+_}let A={};this.apiClient.isVertexAI()&&((i=e.config)===null||i===void 0?void 0:i.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[tn.AUDIO]}:e.config.responseModalities=[tn.AUDIO]),!((r=e.config)===null||r===void 0)&&r.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");let R=(c=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&c!==void 0?c:[],N=[];for(let x of R)if(this.isCallableTool(x)){let D=x;N.push(await D.tool())}else N.push(x);N.length>0&&(e.config.tools=N);let H={model:_,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?A=gu(this.apiClient,H):A=hu(this.apiClient,H),delete A.config,T.send(JSON.stringify(A)),new ti(T,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},Xp={turnComplete:!0},ti=class{static{f(this,"Session")}constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(t.turns!==null&&t.turns!==void 0){let o=[];try{o=he(t.turns),e.isVertexAI()||(o=o.map(i=>Rn(i)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:o,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let o=[];if(t.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(t.functionResponses)?o=t.functionResponses:o=[t.functionResponses],o.length===0)throw new Error("functionResponses is required.");for(let r of o){if(typeof r!="object"||r===null||!("name"in r)||!("response"in r))throw new Error(`Could not parse function response, type '${typeof r}'.`);if(!e.isVertexAI()&&!("id"in r))throw new Error(Wp)}return{toolResponse:{functionResponses:o}}}sendClientContent(e){e=Object.assign(Object.assign({},Xp),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};this.apiClient.isVertexAI()?t={realtimeInput:Iu(e)}:t={realtimeInput:Eu(e)},this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");let t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}close(){this.conn.close()}};function Yp(n){let e={};return n.forEach((t,o)=>{e[o]=t}),e}f(Yp,"headersToMap");function Qp(n){let e=new Headers;for(let[t,o]of Object.entries(n))e.append(t,o);return e}f(Qp,"mapToHeaders");var da=10;function ua(n){var e,t,o;if(!((e=n?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let i=!1;for(let a of(t=n?.tools)!==null&&t!==void 0?t:[])if(pt(a)){i=!0;break}if(!i)return!0;let r=(o=n?.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls;return r&&(r<0||!Number.isInteger(r))||r==0?(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:",r),!0):!1}f(ua,"shouldDisableAfc");function pt(n){return"callTool"in n&&typeof n.callTool=="function"}f(pt,"isCallableTool");function Zp(n){var e,t,o;return(o=(t=(e=n.config)===null||e===void 0?void 0:e.tools)===null||t===void 0?void 0:t.some(i=>pt(i)))!==null&&o!==void 0?o:!1}f(Zp,"hasCallableTools");function fa(n){var e;let t=[];return!((e=n?.config)===null||e===void 0)&&e.tools&&n.config.tools.forEach((o,i)=>{if(pt(o))return;let r=o;r.functionDeclarations&&r.functionDeclarations.length>0&&t.push(i)}),t}f(fa,"findAfcIncompatibleToolIndexes");function pa(n){var e;return!(!((e=n?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}f(pa,"shouldAppendAfcHistory");var ni=class extends Te{static{f(this,"Models")}constructor(e){super(),this.apiClient=e,this.generateContent=async t=>{var o,i,r,a,c;let d=await this.processParamsMaybeAddMcpUsage(t);if(this.maybeMoveToResponseJsonSchem(t),!Zp(t)||ua(t.config))return await this.generateContentInternal(d);let u=fa(t);if(u.length>0){let E=u.map(I=>`tools[${I}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${E}.`)}let p,m,h=he(d.contents),g=(r=(i=(o=d.config)===null||o===void 0?void 0:o.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&r!==void 0?r:da,b=0;for(;b<g&&(p=await this.generateContentInternal(d),!(!p.functionCalls||p.functionCalls.length===0));){let E=p.candidates[0].content,I=[];for(let v of(c=(a=t.config)===null||a===void 0?void 0:a.tools)!==null&&c!==void 0?c:[])if(pt(v)){let T=await v.callTool(p.functionCalls);I.push(...T)}b++,m={role:"user",parts:I},d.contents=he(d.contents),d.contents.push(E),d.contents.push(m),pa(d.config)&&(h.push(E),h.push(m))}return pa(d.config)&&(p.automaticFunctionCallingHistory=h),p},this.generateContentStream=async t=>{var o,i,r,a,c;if(this.maybeMoveToResponseJsonSchem(t),ua(t.config)){let m=await this.processParamsMaybeAddMcpUsage(t);return await this.generateContentStreamInternal(m)}let d=fa(t);if(d.length>0){let m=d.map(h=>`tools[${h}]`).join(", ");throw new Error(`Incompatible tools found at ${m}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let u=(r=(i=(o=t?.config)===null||o===void 0?void 0:o.toolConfig)===null||i===void 0?void 0:i.functionCallingConfig)===null||r===void 0?void 0:r.streamFunctionCallArguments,p=(c=(a=t?.config)===null||a===void 0?void 0:a.automaticFunctionCalling)===null||c===void 0?void 0:c.disable;if(u&&!p)throw new 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(t)},this.generateImages=async t=>await this.generateImagesInternal(t).then(o=>{var i;let r,a=[];if(o?.generatedImages)for(let d of o.generatedImages)d&&d?.safetyAttributes&&((i=d?.safetyAttributes)===null||i===void 0?void 0:i.contentType)==="Positive Prompt"?r=d?.safetyAttributes:a.push(d);let c;return r?c={generatedImages:a,positivePromptSafetyAttributes:r,sdkHttpResponse:o.sdkHttpResponse}:c={generatedImages:a,sdkHttpResponse:o.sdkHttpResponse},c}),this.list=async t=>{var o;let a={config:Object.assign(Object.assign({},{queryBase:!0}),t?.config)};if(this.apiClient.isVertexAI()&&!a.config.queryBase){if(!((o=a.config)===null||o===void 0)&&o.filter)throw new Error("Filtering tuned models list for Vertex AI is not currently supported");a.config.filter="labels.tune-type:*"}return new Me(Re.PAGED_ITEM_MODELS,c=>this.listInternal(c),await this.listInternal(a),a)},this.editImage=async t=>{let o={model:t.model,prompt:t.prompt,referenceImages:[],config:t.config};return t.referenceImages&&t.referenceImages&&(o.referenceImages=t.referenceImages.map(i=>i.toReferenceImageAPI())),await this.editImageInternal(o)},this.upscaleImage=async t=>{let o={numberOfImages:1,mode:"upscale"};t.config&&(o=Object.assign(Object.assign({},o),t.config));let i={model:t.model,image:t.image,upscaleFactor:t.upscaleFactor,config:o};return await this.upscaleImageInternal(i)},this.generateVideos=async t=>{var o,i,r,a,c,d;if((t.prompt||t.image||t.video)&&t.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return this.apiClient.isVertexAI()||(!((o=t.video)===null||o===void 0)&&o.uri&&(!((i=t.video)===null||i===void 0)&&i.videoBytes)?t.video={uri:t.video.uri,mimeType:t.video.mimeType}:!((a=(r=t.source)===null||r===void 0?void 0:r.video)===null||a===void 0)&&a.uri&&(!((d=(c=t.source)===null||c===void 0?void 0:c.video)===null||d===void 0)&&d.videoBytes)&&(t.source.video={uri:t.source.video.uri,mimeType:t.source.video.mimeType})),await this.generateVideosInternal(t)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var t,o,i;let r=(t=e.config)===null||t===void 0?void 0:t.tools;if(!r)return e;let a=await Promise.all(r.map(async d=>pt(d)?await d.tool():d)),c={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:a})};if(c.config.tools=a,e.config&&e.config.tools&&Wa(e.config.tools)){let d=(i=(o=e.config.httpOptions)===null||o===void 0?void 0:o.headers)!==null&&i!==void 0?i:{},u=Object.assign({},d);Object.keys(u).length===0&&(u=this.apiClient.getDefaultHeaders()),Ka(u),c.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:u})}return c}async initAfcToolsMap(e){var t,o,i;let r=new Map;for(let a of(o=(t=e.config)===null||t===void 0?void 0:t.tools)!==null&&o!==void 0?o:[])if(pt(a)){let c=a,d=await c.tool();for(let u of(i=d.functionDeclarations)!==null&&i!==void 0?i:[]){if(!u.name)throw new Error("Function declaration name is required.");if(r.has(u.name))throw new Error(`Duplicate tool declaration name: ${u.name}`);r.set(u.name,c)}}return r}async processAfcStream(e){var t,o,i;let r=(i=(o=(t=e.config)===null||t===void 0?void 0:t.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&i!==void 0?i:da,a=!1,c=0,d=await this.initAfcToolsMap(e);return function(u,p,m){return ve(this,arguments,function*(){for(var h,g,b,E,I,v;c<r;){a&&(c++,a=!1);let A=yield $(u.processParamsMaybeAddMcpUsage(m)),R=yield $(u.generateContentStreamInternal(A)),N=[],H=[];try{for(var w=!0,T=(g=void 0,we(R)),_;_=yield $(T.next()),h=_.done,!h;w=!0){E=_.value,w=!1;let x=E;if(yield yield $(x),x.candidates&&(!((I=x.candidates[0])===null||I===void 0)&&I.content)){H.push(x.candidates[0].content);for(let D of(v=x.candidates[0].content.parts)!==null&&v!==void 0?v:[])if(c<r&&D.functionCall){if(!D.functionCall.name)throw new Error("Function call name was not returned by the model.");if(p.has(D.functionCall.name)){let J=yield $(p.get(D.functionCall.name).callTool([D.functionCall]));N.push(...J)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${p.keys()}, mising tool: ${D.functionCall.name}`)}}}}catch(x){g={error:x}}finally{try{!w&&!h&&(b=T.return)&&(yield $(b.call(T)))}finally{if(g)throw g.error}}if(N.length>0){a=!0;let x=new je;x.candidates=[{content:{role:"user",parts:N}}],yield yield $(x);let D=[];D.push(...H),D.push({role:"user",parts:N});let J=he(m.contents).concat(D);m.contents=J}else break}})}(this,d,e)}async generateContentInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=sa(this.apiClient,e);return c=C("{model}:generateContent",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=la(p),h=new je;return Object.assign(h,m),h})}else{let u=ra(this.apiClient,e);return c=C("{model}:generateContent",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=aa(p),h=new je;return Object.assign(h,m),h})}}async generateContentStreamInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=sa(this.apiClient,e);return c=C("{model}:streamGenerateContent?alt=sse",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.requestStream({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}),a.then(function(m){return ve(this,arguments,function*(){var h,g,b,E;try{for(var I=!0,v=we(m),w;w=yield $(v.next()),h=w.done,!h;I=!0){E=w.value,I=!1;let T=E,_=la(yield $(T.json()));_.sdkHttpResponse={headers:T.headers};let A=new je;Object.assign(A,_),yield yield $(A)}}catch(T){g={error:T}}finally{try{!I&&!h&&(b=v.return)&&(yield $(b.call(v)))}finally{if(g)throw g.error}}})})}else{let u=ra(this.apiClient,e);return c=C("{model}:streamGenerateContent?alt=sse",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.requestStream({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}),a.then(function(m){return ve(this,arguments,function*(){var h,g,b,E;try{for(var I=!0,v=we(m),w;w=yield $(v.next()),h=w.done,!h;I=!0){E=w.value,I=!1;let T=E,_=aa(yield $(T.json()));_.sdkHttpResponse={headers:T.headers};let A=new je;Object.assign(A,_),yield yield $(A)}}catch(T){g={error:T}}finally{try{!I&&!h&&(b=v.return)&&(yield $(b.call(v)))}finally{if(g)throw g.error}}})})}}async embedContent(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Qu(this.apiClient,e);return c=C("{model}:predict",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=ju(p),h=new on;return Object.assign(h,m),h})}else{let u=Yu(this.apiClient,e);return c=C("{model}:batchEmbedContents",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=Zu(p),h=new on;return Object.assign(h,m),h})}}async generateImagesInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=uf(this.apiClient,e);return c=C("{model}:predict",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=pf(p),h=new rn;return Object.assign(h,m),h})}else{let u=df(this.apiClient,e);return c=C("{model}:predict",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=ff(p),h=new rn;return Object.assign(h,m),h})}}async editImageInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let c=Ju(this.apiClient,e);return r=C("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>{let u=Wu(d),p=new _o;return Object.assign(p,u),p})}else throw new Error("This method is only supported by the Vertex AI.")}async upscaleImageInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let c=up(this.apiClient,e);return r=C("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>{let u=fp(d),p=new So;return Object.assign(p,u),p})}else throw new Error("This method is only supported by the Vertex AI.")}async recontextImage(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let c=Jf(this.apiClient,e);return r=C("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=Wf(d),p=new Ao;return Object.assign(p,u),p})}else throw new Error("This method is only supported by the Vertex AI.")}async segmentImage(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let c=jf(this.apiClient,e);return r=C("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=ep(d),p=new xo;return Object.assign(p,u),p})}else throw new Error("This method is only supported by the Vertex AI.")}async get(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Nf(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),a.then(p=>Ko(p))}else{let u=Pf(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),a.then(p=>Wo(p))}}async listInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Ff(this.apiClient,e);return c=C("{models_url}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=Vf(p),h=new sn;return Object.assign(h,m),h})}else{let u=Uf(this.apiClient,e);return c=C("{models_url}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=Hf(p),h=new sn;return Object.assign(h,m),h})}}async update(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=cp(this.apiClient,e);return c=C("{model}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),a.then(p=>Ko(p))}else{let u=lp(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),a.then(p=>Wo(p))}}async delete(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Bu(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=Ou(p),h=new an;return Object.assign(h,m),h})}else{let u=Vu(this.apiClient,e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=qu(p),h=new an;return Object.assign(h,m),h})}}async countTokens(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Uu(this.apiClient,e);return c=C("{model}:countTokens",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=Hu(p),h=new ln;return Object.assign(h,m),h})}else{let u=Lu(this.apiClient,e);return c=C("{model}:countTokens",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=Fu(p),h=new ln;return Object.assign(h,m),h})}}async computeTokens(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let c=Nu(this.apiClient,e);return r=C("{model}:computeTokens",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>{let u=$u(d),p=new Po;return Object.assign(p,u),p})}else throw new Error("This method is only supported by the Vertex AI.")}async generateVideosInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Ef(this.apiClient,e);return c=C("{model}:predictLongRunning",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),a.then(p=>{let m=bf(p),h=new cn;return Object.assign(h,m),h})}else{let u=yf(this.apiClient,e);return c=C("{model}:predictLongRunning",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),a.then(p=>{let m=gf(p),h=new cn;return Object.assign(h,m),h})}}};var oi=class extends Te{static{f(this,"Operations")}constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let t=e.operation,o=e.config;if(t.name===void 0||t.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=t.name.split("/operations/")[0],r;o&&"httpOptions"in o&&(r=o.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:i,config:{httpOptions:r}});return t._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:t.name,config:o});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async get(e){let t=e.operation,o=e.config;if(t.name===void 0||t.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let i=t.name.split("/operations/")[0],r;o&&"httpOptions"in o&&(r=o.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:i,config:{httpOptions:r}});return t._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let i=await this.getVideosOperationInternal({operationName:t.name,config:o});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=pc(e);return c=C("{operationName}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),a}else{let u=fc(e);return c=C("{operationName}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json()),a}}async fetchPredictVideosOperationInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let c=rc(e);return r=C("{resourceName}:fetchPredictOperation",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i}else throw new Error("This method is only supported by the Vertex AI.")}};function jp(n){let e={},t=s(n,["data"]);if(t!=null&&l(e,["data"],t),s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(jp,"blobToMldev");function em(n){let e={},t=s(n,["parts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(r=>cm(r))),l(e,["parts"],i)}let o=s(n,["role"]);return o!=null&&l(e,["role"],o),e}f(em,"contentToMldev");function tm(n,e,t){let o={},i=s(e,["expireTime"]);t!==void 0&&i!=null&&l(t,["expireTime"],i);let r=s(e,["newSessionExpireTime"]);t!==void 0&&r!=null&&l(t,["newSessionExpireTime"],r);let a=s(e,["uses"]);t!==void 0&&a!=null&&l(t,["uses"],a);let c=s(e,["liveConnectConstraints"]);t!==void 0&&c!=null&&l(t,["bidiGenerateContentSetup"],lm(n,c));let d=s(e,["lockAdditionalFields"]);return t!==void 0&&d!=null&&l(t,["fieldMask"],d),o}f(tm,"createAuthTokenConfigToMldev");function nm(n,e){let t={},o=s(e,["config"]);return o!=null&&l(t,["config"],tm(n,o,t)),t}f(nm,"createAuthTokenParametersToMldev");function om(n){let e={};if(s(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=s(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let o=s(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}f(om,"fileDataToMldev");function im(n){let e={},t=s(n,["id"]);t!=null&&l(e,["id"],t);let o=s(n,["args"]);o!=null&&l(e,["args"],o);let i=s(n,["name"]);if(i!=null&&l(e,["name"],i),s(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(s(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}f(im,"functionCallToMldev");function rm(n){let e={};if(s(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=s(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}f(rm,"googleMapsToMldev");function sm(n){let e={};if(s(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(s(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=s(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}f(sm,"googleSearchToMldev");function am(n,e){let t={},o=s(n,["generationConfig"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig"],o);let i=s(n,["responseModalities"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig","responseModalities"],i);let r=s(n,["temperature"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig","temperature"],r);let a=s(n,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let c=s(n,["topK"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","topK"],c);let d=s(n,["maxOutputTokens"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","maxOutputTokens"],d);let u=s(n,["mediaResolution"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","mediaResolution"],u);let p=s(n,["seed"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","seed"],p);let m=s(n,["speechConfig"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","speechConfig"],_i(m));let h=s(n,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let g=s(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=s(n,["systemInstruction"]);e!==void 0&&b!=null&&l(e,["setup","systemInstruction"],em(re(b)));let E=s(n,["tools"]);if(e!==void 0&&E!=null){let R=bt(E);Array.isArray(R)&&(R=R.map(N=>um(gt(N)))),l(e,["setup","tools"],R)}let I=s(n,["sessionResumption"]);e!==void 0&&I!=null&&l(e,["setup","sessionResumption"],dm(I));let v=s(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&l(e,["setup","inputAudioTranscription"],v);let w=s(n,["outputAudioTranscription"]);e!==void 0&&w!=null&&l(e,["setup","outputAudioTranscription"],w);let T=s(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&l(e,["setup","realtimeInputConfig"],T);let _=s(n,["contextWindowCompression"]);e!==void 0&&_!=null&&l(e,["setup","contextWindowCompression"],_);let A=s(n,["proactivity"]);if(e!==void 0&&A!=null&&l(e,["setup","proactivity"],A),s(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}f(am,"liveConnectConfigToMldev");function lm(n,e){let t={},o=s(e,["model"]);o!=null&&l(t,["setup","model"],k(n,o));let i=s(e,["config"]);return i!=null&&l(t,["config"],am(i,t)),t}f(lm,"liveConnectConstraintsToMldev");function cm(n){let e={},t=s(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let o=s(n,["codeExecutionResult"]);o!=null&&l(e,["codeExecutionResult"],o);let i=s(n,["executableCode"]);i!=null&&l(e,["executableCode"],i);let r=s(n,["fileData"]);r!=null&&l(e,["fileData"],om(r));let a=s(n,["functionCall"]);a!=null&&l(e,["functionCall"],im(a));let c=s(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=s(n,["inlineData"]);d!=null&&l(e,["inlineData"],jp(d));let u=s(n,["text"]);u!=null&&l(e,["text"],u);let p=s(n,["thought"]);p!=null&&l(e,["thought"],p);let m=s(n,["thoughtSignature"]);m!=null&&l(e,["thoughtSignature"],m);let h=s(n,["videoMetadata"]);return h!=null&&l(e,["videoMetadata"],h),e}f(cm,"partToMldev");function dm(n){let e={},t=s(n,["handle"]);if(t!=null&&l(e,["handle"],t),s(n,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}f(dm,"sessionResumptionConfigToMldev");function um(n){let e={},t=s(n,["functionDeclarations"]);if(t!=null){let p=t;Array.isArray(p)&&(p=p.map(m=>m)),l(e,["functionDeclarations"],p)}if(s(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let o=s(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let i=s(n,["computerUse"]);i!=null&&l(e,["computerUse"],i);let r=s(n,["fileSearch"]);r!=null&&l(e,["fileSearch"],r);let a=s(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),s(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=s(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],rm(c));let d=s(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],sm(d));let u=s(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}f(um,"toolToMldev");function fm(n){let e=[];for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){let o=n[t];if(typeof o=="object"&&o!=null&&Object.keys(o).length>0){let i=Object.keys(o).map(r=>`${t}.${r}`);e.push(...i)}else e.push(t)}return e.join(",")}f(fm,"getFieldMasks");function pm(n,e){let t=null,o=n.bidiGenerateContentSetup;if(typeof o=="object"&&o!==null&&"setup"in o){let r=o.setup;typeof r=="object"&&r!==null?(n.bidiGenerateContentSetup=r,t=r):delete n.bidiGenerateContentSetup}else o!==void 0&&delete n.bidiGenerateContentSetup;let i=n.fieldMask;if(t){let r=fm(t);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)r?n.fieldMask=r:delete n.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&i!==null&&Array.isArray(i)&&i.length>0){let a=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],c=[];i.length>0&&(c=i.map(u=>a.includes(u)?`generationConfig.${u}`:u));let d=[];r&&d.push(r),c.length>0&&d.push(...c),d.length>0?n.fieldMask=d.join(","):delete n.fieldMask}else delete n.fieldMask}else i!==null&&Array.isArray(i)&&i.length>0?n.fieldMask=i.join(","):delete n.fieldMask;return n}f(pm,"convertBidiSetupToTokenSetup");var ii=class extends Te{static{f(this,"Tokens")}constructor(e){super(),this.apiClient=e}async create(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let c=nm(this.apiClient,e);r=C("auth_tokens",c._url),a=c._query,delete c.config,delete c._url,delete c._query;let d=pm(c,e.config);return i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>u)}}};function mm(n,e){let t={},o=s(n,["force"]);return e!==void 0&&o!=null&&l(e,["_query","force"],o),t}f(mm,"deleteDocumentConfigToMldev");function hm(n){let e={},t=s(n,["name"]);t!=null&&l(e,["_url","name"],t);let o=s(n,["config"]);return o!=null&&mm(o,e),e}f(hm,"deleteDocumentParametersToMldev");function gm(n){let e={},t=s(n,["name"]);return t!=null&&l(e,["_url","name"],t),e}f(gm,"getDocumentParametersToMldev");function bm(n,e){let t={},o=s(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let i=s(n,["pageToken"]);return e!==void 0&&i!=null&&l(e,["_query","pageToken"],i),t}f(bm,"listDocumentsConfigToMldev");function ym(n){let e={},t=s(n,["parent"]);t!=null&&l(e,["_url","parent"],t);let o=s(n,["config"]);return o!=null&&bm(o,e),e}f(ym,"listDocumentsParametersToMldev");function Em(n){let e={},t=s(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let o=s(n,["nextPageToken"]);o!=null&&l(e,["nextPageToken"],o);let i=s(n,["documents"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["documents"],r)}return e}f(Em,"listDocumentsResponseFromMldev");var ri=class extends Te{static{f(this,"Documents")}constructor(e){super(),this.apiClient=e,this.list=async t=>new Me(Re.PAGED_ITEM_DOCUMENTS,o=>this.listInternal({parent:t.parent,config:o.config}),await this.listInternal(t),t)}async get(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=gm(e);return r=C("{name}",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>d)}}async delete(e){var t,o;let i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=hm(e);i=C("{name}",a._url),r=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=ym(e);return r=C("{parent}/documents",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=Em(d),p=new No;return Object.assign(p,u),p})}}};var si=class extends Te{static{f(this,"FileSearchStores")}constructor(e,t=new ri(e)){super(),this.apiClient=e,this.documents=t,this.list=async(o={})=>new Me(Re.PAGED_ITEM_FILE_SEARCH_STORES,i=>this.listInternal(i),await this.listInternal(o),o)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Vertex AI does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async create(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Ep(e);return r=C("fileSearchStores",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>d)}}async get(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=wp(e);return r=C("{name}",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>d)}}async delete(e){var t,o;let i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=vp(e);i=C("{name}",a._url),r=a._query,delete a._url,delete a._query,await this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=xp(e);return r=C("fileSearchStores",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=Pp(d),p=new $o;return Object.assign(p,u),p})}}async uploadToFileSearchStoreInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Np(e);return r=C("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=$p(d),p=new Go;return Object.assign(p,u),p})}}async importFile(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=_p(e);return r=C("{file_search_store_name}:importFile",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),i.then(d=>{let u=Cp(d),p=new Ro;return Object.assign(p,u),p})}}};var Xa=f(function(){let{crypto:n}=globalThis;if(n?.randomUUID)return Xa=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,o=>(+o^t()&15>>+o/4).toString(16))},"uuid4Internal"),Im=f(()=>Xa(),"uuid4");function ai(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}f(ai,"isAbortError");var li=f(n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)},"castToError");var de=class extends Error{static{f(this,"GeminiNextGenAPIClientError")}},ue=class n extends de{static{f(this,"APIError")}constructor(e,t,o,i){super(`${n.makeMessage(e,t,o)}`),this.status=e,this.headers=i,this.error=t}static makeMessage(e,t,o){let i=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):o;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,t,o,i){if(!e||!i)return new mt({message:o,cause:li(t)});let r=t;return e===400?new En(e,r,o,i):e===401?new In(e,r,o,i):e===403?new vn(e,r,o,i):e===404?new wn(e,r,o,i):e===409?new Tn(e,r,o,i):e===422?new Cn(e,r,o,i):e===429?new _n(e,r,o,i):e>=500?new Sn(e,r,o,i):new n(e,r,o,i)}},Pt=class extends ue{static{f(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},mt=class extends ue{static{f(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},yn=class extends mt{static{f(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},En=class extends ue{static{f(this,"BadRequestError")}},In=class extends ue{static{f(this,"AuthenticationError")}},vn=class extends ue{static{f(this,"PermissionDeniedError")}},wn=class extends ue{static{f(this,"NotFoundError")}},Tn=class extends ue{static{f(this,"ConflictError")}},Cn=class extends ue{static{f(this,"UnprocessableEntityError")}},_n=class extends ue{static{f(this,"RateLimitError")}},Sn=class extends ue{static{f(this,"InternalServerError")}};var vm=/^[a-z][a-z0-9+.-]*:/i,wm=f(n=>vm.test(n),"isAbsoluteURL"),ci=f(n=>(ci=Array.isArray,ci(n)),"isArrayInternal"),Tm=ci,Cm=Tm,ma=Cm;function _m(n){if(!n)return!0;for(let e in n)return!1;return!0}f(_m,"isEmptyObj");function Sm(n,e){return Object.prototype.hasOwnProperty.call(n,e)}f(Sm,"hasOwn");var Am=f((n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new de(`${n} must be an integer`);if(e<0)throw new de(`${n} must be a positive integer`);return e},"validatePositiveInteger"),xm=f(n=>{try{return JSON.parse(n)}catch{return}},"safeJSON");var Pm=f(n=>new Promise(e=>setTimeout(e,n)),"sleep$1");var dt="0.0.1";function Nm(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}f(Nm,"getDetectedPlatform");var $m=f(()=>{var n,e,t,o,i;let r=Nm();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":ga(Deno.build.os),"X-Stainless-Arch":ha(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(e=(n=Deno.version)===null||n===void 0?void 0:n.deno)!==null&&e!==void 0?e:"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":ga((t=globalThis.process.platform)!==null&&t!==void 0?t:"unknown"),"X-Stainless-Arch":ha((o=globalThis.process.arch)!==null&&o!==void 0?o:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(i=globalThis.process.version)!==null&&i!==void 0?i:"unknown"};let a=Gm();return a?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${a.browser}`,"X-Stainless-Runtime-Version":a.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Gm(){if(typeof navigator>"u"||!navigator)return null;let n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of n){let o=t.exec(navigator.userAgent);if(o){let i=o[1]||0,r=o[2]||0,a=o[3]||0;return{browser:e,version:`${i}.${r}.${a}`}}}return null}f(Gm,"getBrowserInfo");var ha=f(n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown","normalizeArch"),ga=f(n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),"normalizePlatform"),Kt,Rm=f(()=>Kt??(Kt=$m()),"getPlatformHeaders");function Mm(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}f(Mm,"getDefaultFetch");function Ya(...n){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}f(Ya,"makeReadableStream");function Dm(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Ya({start(){},async pull(t){let{done:o,value:i}=await e.next();o?t.close():t.enqueue(i)},async cancel(){var t;await((t=e.return)===null||t===void 0?void 0:t.call(e))}})}f(Dm,"ReadableStreamFrom");function Qa(n){if(n[Symbol.asyncIterator])return n;let e=n.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}f(Qa,"ReadableStreamToAsyncIterable");async function km(n){var e,t;if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await((t=(e=n[Symbol.asyncIterator]()).return)===null||t===void 0?void 0:t.call(e));return}let o=n.getReader(),i=o.cancel();o.releaseLock(),await i}f(km,"CancelReadableStream");var Lm=f(({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var Za=f(()=>{var n;if(typeof File>"u"){let{process:e}=globalThis,t=typeof((n=e?.versions)===null||n===void 0?void 0:n.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},"checkFileSupport");function Io(n,e,t){return Za(),new File(n,e??"unknown_file",t)}f(Io,"makeFile");function Um(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}f(Um,"getName");var Fm=f(n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function","isAsyncIterable");var ja=f(n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function","isBlobLike"),Hm=f(n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&ja(n),"isFileLike"),Vm=f(n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function","isResponseLike");async function Bm(n,e,t){if(Za(),n=await n,Hm(n))return n instanceof File?n:Io([await n.arrayBuffer()],n.name);if(Vm(n)){let i=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),Io(await di(i),e,t)}let o=await di(n);if(e||(e=Um(n)),!t?.type){let i=o.find(r=>typeof r=="object"&&"type"in r&&r.type);typeof i=="string"&&(t=Object.assign(Object.assign({},t),{type:i}))}return Io(o,e,t)}f(Bm,"toFile");async function di(n){var e,t,o,i,r;let a=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)a.push(n);else if(ja(n))a.push(n instanceof Blob?n:await n.arrayBuffer());else if(Fm(n))try{for(var c=!0,d=we(n),u;u=await d.next(),e=u.done,!e;c=!0){i=u.value,c=!1;let p=i;a.push(...await di(p))}}catch(p){t={error:p}}finally{try{!c&&!e&&(o=d.return)&&await o.call(d)}finally{if(t)throw t.error}}else{let p=(r=n?.constructor)===null||r===void 0?void 0:r.name;throw new Error(`Unexpected data type: ${typeof n}${p?`; constructor: ${p}`:""}${qm(n)}`)}return a}f(di,"getBytes");function qm(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}f(qm,"propsForError");var An=class{static{f(this,"APIResource")}constructor(e){this._client=e}};An._key=[];function el(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}f(el,"encodeURIPath");var ba=Object.freeze(Object.create(null)),Om=f((n=el)=>f(function(t,...o){if(t.length===1)return t[0];let i=!1,r=[],a=t.reduce((p,m,h)=>{var g,b,E;/[?#]/.test(m)&&(i=!0);let I=o[h],v=(i?encodeURIComponent:n)(""+I);return h!==o.length&&(I==null||typeof I=="object"&&I.toString===((E=Object.getPrototypeOf((b=Object.getPrototypeOf((g=I.hasOwnProperty)!==null&&g!==void 0?g:ba))!==null&&b!==void 0?b:ba))===null||E===void 0?void 0:E.toString))&&(v=I+"",r.push({start:p.length+m.length,length:v.length,error:`Value of type ${Object.prototype.toString.call(I).slice(8,-1)} is not a valid path parameter`})),p+m+(h===o.length?"":v)},""),c=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=d.exec(c))!==null;)r.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(r.sort((p,m)=>p.start-m.start),r.length>0){let p=0,m=r.reduce((h,g)=>{let b=" ".repeat(g.start-p),E="^".repeat(g.length);return p=g.start+g.length,h+b+E},"");throw new de(`Path parameters result in path with invalid segments:
|
|
1176
1176
|
${r.map(h=>h.error).join(`
|
|
1177
1177
|
`)}
|
|
1178
|
-
${
|
|
1179
|
-
${m}`)}return
|
|
1180
|
-
`):[]}};
|
|
1181
|
-
`,"\r"]);
|
|
1182
|
-
`);o.enqueue(
|
|
1183
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],r}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,o,i]=Xm(e,":");return i.startsWith(" ")&&(i=i.substring(1)),t==="event"?this.event=i:t==="data"&&this.data.push(i),null}};function Xm(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}f(Xm,"partition");async function Ym(n,e){let{response:t,requestLogID:o,retryOfRequestLogID:i,startTime:r}=e,l=await(async()=>{var c;if(e.options.stream)return ae(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):ci.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let d=t.headers.get("content-type"),u=(c=d?.split(";")[0])===null||c===void 0?void 0:c.trim();return u?.includes("application/json")||u?.endsWith("+json")?await t.json():await t.text()})();return ae(n).debug(`[${o}] response parsed`,Ze({retryOfRequestLogID:i,url:t.url,status:t.status,body:l,durationMs:Date.now()-r})),l}f(Ym,"defaultParseResponse");var ui=class n extends Promise{static{f(this,"APIPromise")}constructor(e,t,o=Ym){super(i=>{i(null)}),this.responsePromise=t,this.parseResponse=o,this.client=e}_thenUnwrap(e){return new n(this.client,this.responsePromise,async(t,o)=>e(await this.parseResponse(t,o),o))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};var ja=Symbol("brand.privateNullableHeaders");function*Qm(n){if(!n)return;if(ja in n){let{values:o,nulls:i}=n;yield*o.entries();for(let r of i)yield[r,null];return}let e=!1,t;n instanceof Headers?t=n.entries():fa(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let o of t){let i=o[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let r=fa(o[1])?o[1]:[o[1]],l=!1;for(let c of r)c!==void 0&&(e&&!l&&(l=!0,yield[i,null]),yield[i,c])}}f(Qm,"iterateHeaders");var Eo=f(n=>{let e=new Headers,t=new Set;for(let o of n){let i=new Set;for(let[r,l]of Qm(o)){let c=r.toLowerCase();i.has(c)||(e.delete(r),i.add(c)),l===null?(e.delete(r),t.add(c)):(e.append(r,l),t.delete(c))}}return{[ja]:!0,values:e,nulls:t}},"buildHeaders");var Io=f(n=>{var e,t,o,i,r,l;if(typeof globalThis.process<"u")return(o=(t=(e=globalThis.process.env)===null||e===void 0?void 0:e[n])===null||t===void 0?void 0:t.trim())!==null&&o!==void 0?o:void 0;if(typeof globalThis.Deno<"u")return(l=(r=(i=globalThis.Deno.env)===null||i===void 0?void 0:i.get)===null||r===void 0?void 0:r.call(i,n))===null||l===void 0?void 0:l.trim()},"readEnv");var el,$n=class n{static{f(this,"BaseGeminiNextGenAPIClient")}constructor(e){var t,o,i,r,l,c,d,u=e===void 0?{}:e,{baseURL:p=Io("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:m=(t=Io("GEMINI_API_KEY"))!==null&&t!==void 0?t:null,apiVersion:h="v1beta"}=u,g=gn(u,["baseURL","apiKey","apiVersion"]);let b=Object.assign(Object.assign({apiKey:m,apiVersion:h},g),{baseURL:p||"https://generativelanguage.googleapis.com"});this.baseURL=b.baseURL,this.timeout=(o=b.timeout)!==null&&o!==void 0?o:n.DEFAULT_TIMEOUT,this.logger=(i=b.logger)!==null&&i!==void 0?i:console;let E="warn";this.logLevel=E,this.logLevel=(l=(r=ba(b.logLevel,"ClientOptions.logLevel",this))!==null&&r!==void 0?r:ba(Io("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&l!==void 0?l:E,this.fetchOptions=b.fetchOptions,this.maxRetries=(c=b.maxRetries)!==null&&c!==void 0?c:2,this.fetch=(d=b.fetch)!==null&&d!==void 0?d:Rm(),this.encoder=Dm,this._options=b,this.apiKey=m,this.apiVersion=h}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-goog-api-key"))&&!t.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){if(this.apiKey!=null)return Eo([{"x-goog-api-key":this.apiKey}])}stringifyQuery(e){return Object.entries(e).filter(([t,o])=>typeof o<"u").map(([t,o])=>{if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(o)}`;if(o===null)return`${encodeURIComponent(t)}=`;throw new ce(`Cannot stringify type ${typeof o}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${ct}`}defaultIdempotencyKey(){return`stainless-node-retry-${ym()}`}makeStatusError(e,t,o,i){return de.generate(e,t,o,i)}buildURL(e,t,o){let i=!this.baseURLOverridden()&&o||this.baseURL,r=Im(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),l=this.defaultQuery();return Tm(l)||(t=Object.assign(Object.assign({},l),t)),typeof t=="object"&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:o}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,o){return this.request(Promise.resolve(o).then(i=>Object.assign({method:e,path:t},i)))}request(e,t=null){return new ui(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,o){var i,r,l;let c=await e,d=(i=c.maxRetries)!==null&&i!==void 0?i:this.maxRetries;t==null&&(t=d),await this.prepareOptions(c);let{req:u,url:p,timeout:m}=await this.buildRequest(c,{retryCount:d-t});await this.prepareRequest(u,{url:p,options:c});let h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=o===void 0?"":`, retryOf: ${o}`,b=Date.now();if(ae(this).debug(`[${h}] sending request`,Ze({retryOfRequestLogID:o,method:c.method,url:p,options:c,headers:u.headers})),!((r=c.signal)===null||r===void 0)&&r.aborted)throw new Pt;let E=new AbortController,I=await this.fetchWithTimeout(p,u,m,E).catch(si),v=Date.now();if(I instanceof globalThis.Error){let T=`retrying, ${t} attempts remaining`;if(!((l=c.signal)===null||l===void 0)&&l.aborted)throw new Pt;let C=ri(I)||/timed? ?out/i.test(String(I)+("cause"in I?String(I.cause):""));if(t)return ae(this).info(`[${h}] connection ${C?"timed out":"failed"} - ${T}`),ae(this).debug(`[${h}] connection ${C?"timed out":"failed"} (${T})`,Ze({retryOfRequestLogID:o,url:p,durationMs:v-b,message:I.message})),this.retryRequest(c,t,o??h);throw ae(this).info(`[${h}] connection ${C?"timed out":"failed"} - error; no more retries left`),ae(this).debug(`[${h}] connection ${C?"timed out":"failed"} (error; no more retries left)`,Ze({retryOfRequestLogID:o,url:p,durationMs:v-b,message:I.message})),C?new yn:new pt({cause:I})}let w=`[${h}${g}] ${u.method} ${p} ${I.ok?"succeeded":"failed"} with status ${I.status} in ${v-b}ms`;if(!I.ok){let T=await this.shouldRetry(I);if(t&&T){let x=`retrying, ${t} attempts remaining`;return await Mm(I.body),ae(this).info(`${w} - ${x}`),ae(this).debug(`[${h}] response error (${x})`,Ze({retryOfRequestLogID:o,url:I.url,status:I.status,headers:I.headers,durationMs:v-b})),this.retryRequest(c,t,o??h,I.headers)}let C=T?"error; no more retries left":"error; not retryable";ae(this).info(`${w} - ${C}`);let A=await I.text().catch(x=>si(x).message),G=Sm(A),N=G?void 0:A;throw ae(this).debug(`[${h}] response error (${C})`,Ze({retryOfRequestLogID:o,url:I.url,status:I.status,headers:I.headers,message:N,durationMs:Date.now()-b})),this.makeStatusError(I.status,G,N,I.headers)}return ae(this).info(w),ae(this).debug(`[${h}] response start`,Ze({retryOfRequestLogID:o,url:I.url,status:I.status,headers:I.headers,durationMs:v-b})),{response:I,options:c,controller:E,requestLogID:h,retryOfRequestLogID:o,startTime:b}}async fetchWithTimeout(e,t,o,i){let r=t||{},{signal:l,method:c}=r,d=gn(r,["signal","method"]);l&&l.addEventListener("abort",()=>i.abort());let u=setTimeout(()=>i.abort(),o),p=globalThis.ReadableStream&&d.body instanceof globalThis.ReadableStream||typeof d.body=="object"&&d.body!==null&&Symbol.asyncIterator in d.body,m=Object.assign(Object.assign(Object.assign({signal:i.signal},p?{duplex:"half"}:{}),{method:"GET"}),d);c&&(m.method=c.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,o,i){var r;let l,c=i?.get("retry-after-ms");if(c){let u=parseFloat(c);Number.isNaN(u)||(l=u)}let d=i?.get("retry-after");if(d&&!l){let u=parseFloat(d);Number.isNaN(u)?l=Date.parse(d)-Date.now():l=u*1e3}if(!(l&&0<=l&&l<60*1e3)){let u=(r=e.maxRetries)!==null&&r!==void 0?r:this.maxRetries;l=this.calculateDefaultRetryTimeoutMillis(t,u)}return await Am(l),this.makeRequest(e,t-1,o)}calculateDefaultRetryTimeoutMillis(e,t){let r=t-e,l=Math.min(.5*Math.pow(2,r),8),c=1-Math.random()*.25;return l*c*1e3}async buildRequest(e,{retryCount:t=0}={}){var o,i,r;let l=Object.assign({},e),{method:c,path:d,query:u,defaultBaseURL:p}=l,m=this.buildURL(d,u,p);"timeout"in l&&Cm("timeout",l.timeout),l.timeout=(o=l.timeout)!==null&&o!==void 0?o:this.timeout;let{bodyHeaders:h,body:g}=this.buildBody({options:l}),b=await this.buildHeaders({options:e,method:c,bodyHeaders:h,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:c,headers:b},l.signal&&{signal:l.signal}),globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"}),g&&{body:g}),(i=this.fetchOptions)!==null&&i!==void 0?i:{}),(r=l.fetchOptions)!==null&&r!==void 0?r:{}),url:m,timeout:l.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:o,retryCount:i}){let r={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);let l=Eo([r,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),$m()),await this.authHeaders(e),this._options.defaultHeaders,o,e.headers]);return this.validateHeaders(l),l.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let o=Eo([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&o.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Gm(e)}:this.encoder({body:e,headers:o})}};$n.DEFAULT_TIMEOUT=6e4;var Y=class extends $n{static{f(this,"GeminiNextGenAPIClient")}constructor(){super(...arguments),this.interactions=new Pn(this)}};el=Y;Y.GeminiNextGenAPIClient=el;Y.GeminiNextGenAPIClientError=ce;Y.APIError=de;Y.APIConnectionError=pt;Y.APIConnectionTimeoutError=yn;Y.APIUserAbortError=Pt;Y.NotFoundError=wn;Y.ConflictError=Tn;Y.RateLimitError=Cn;Y.BadRequestError=En;Y.AuthenticationError=In;Y.InternalServerError=Sn;Y.PermissionDeniedError=vn;Y.UnprocessableEntityError=_n;Y.toFile=Hm;Y.Interactions=Pn;function Zm(n,e){let t={},o=s(n,["name"]);return o!=null&&a(t,["_url","name"],o),t}f(Zm,"cancelTuningJobParametersToMldev");function jm(n,e){let t={},o=s(n,["name"]);return o!=null&&a(t,["_url","name"],o),t}f(jm,"cancelTuningJobParametersToVertex");function eh(n,e){let t={},o=s(n,["sdkHttpResponse"]);return o!=null&&a(t,["sdkHttpResponse"],o),t}f(eh,"cancelTuningJobResponseFromMldev");function th(n,e){let t={},o=s(n,["sdkHttpResponse"]);return o!=null&&a(t,["sdkHttpResponse"],o),t}f(th,"cancelTuningJobResponseFromVertex");function nh(n,e,t){let o={};if(s(n,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is not supported in Gemini API.");let i=s(n,["tunedModelDisplayName"]);if(e!==void 0&&i!=null&&a(e,["displayName"],i),s(n,["description"])!==void 0)throw new Error("description parameter is not supported in Gemini API.");let r=s(n,["epochCount"]);e!==void 0&&r!=null&&a(e,["tuningTask","hyperparameters","epochCount"],r);let l=s(n,["learningRateMultiplier"]);if(l!=null&&a(o,["tuningTask","hyperparameters","learningRateMultiplier"],l),s(n,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(s(n,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(s(n,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is not supported in Gemini API.");let c=s(n,["batchSize"]);e!==void 0&&c!=null&&a(e,["tuningTask","hyperparameters","batchSize"],c);let d=s(n,["learningRate"]);if(e!==void 0&&d!=null&&a(e,["tuningTask","hyperparameters","learningRate"],d),s(n,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");if(s(n,["beta"])!==void 0)throw new Error("beta parameter is not supported in Gemini API.");return o}f(nh,"createTuningJobConfigToMldev");function oh(n,e,t){let o={},i=s(t,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let g=s(n,["validationDataset"]);e!==void 0&&g!=null&&a(e,["supervisedTuningSpec"],Ea(g))}else if(i==="PREFERENCE_TUNING"){let g=s(n,["validationDataset"]);e!==void 0&&g!=null&&a(e,["preferenceOptimizationSpec"],Ea(g))}let r=s(n,["tunedModelDisplayName"]);e!==void 0&&r!=null&&a(e,["tunedModelDisplayName"],r);let l=s(n,["description"]);e!==void 0&&l!=null&&a(e,["description"],l);let c=s(t,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let g=s(n,["epochCount"]);e!==void 0&&g!=null&&a(e,["supervisedTuningSpec","hyperParameters","epochCount"],g)}else if(c==="PREFERENCE_TUNING"){let g=s(n,["epochCount"]);e!==void 0&&g!=null&&a(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],g)}let d=s(t,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let g=s(n,["learningRateMultiplier"]);e!==void 0&&g!=null&&a(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],g)}else if(d==="PREFERENCE_TUNING"){let g=s(n,["learningRateMultiplier"]);e!==void 0&&g!=null&&a(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],g)}let u=s(t,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let g=s(n,["exportLastCheckpointOnly"]);e!==void 0&&g!=null&&a(e,["supervisedTuningSpec","exportLastCheckpointOnly"],g)}else if(u==="PREFERENCE_TUNING"){let g=s(n,["exportLastCheckpointOnly"]);e!==void 0&&g!=null&&a(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],g)}let p=s(t,["config","method"]);if(p===void 0&&(p="SUPERVISED_FINE_TUNING"),p==="SUPERVISED_FINE_TUNING"){let g=s(n,["adapterSize"]);e!==void 0&&g!=null&&a(e,["supervisedTuningSpec","hyperParameters","adapterSize"],g)}else if(p==="PREFERENCE_TUNING"){let g=s(n,["adapterSize"]);e!==void 0&&g!=null&&a(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],g)}if(s(n,["batchSize"])!==void 0)throw new Error("batchSize parameter is not supported in Vertex AI.");if(s(n,["learningRate"])!==void 0)throw new Error("learningRate parameter is not supported in Vertex AI.");let m=s(n,["labels"]);e!==void 0&&m!=null&&a(e,["labels"],m);let h=s(n,["beta"]);return e!==void 0&&h!=null&&a(e,["preferenceOptimizationSpec","hyperParameters","beta"],h),o}f(oh,"createTuningJobConfigToVertex");function ih(n,e){let t={},o=s(n,["baseModel"]);o!=null&&a(t,["baseModel"],o);let i=s(n,["preTunedModel"]);i!=null&&a(t,["preTunedModel"],i);let r=s(n,["trainingDataset"]);r!=null&&hh(r);let l=s(n,["config"]);return l!=null&&nh(l,t),t}f(ih,"createTuningJobParametersPrivateToMldev");function rh(n,e){let t={},o=s(n,["baseModel"]);o!=null&&a(t,["baseModel"],o);let i=s(n,["preTunedModel"]);i!=null&&a(t,["preTunedModel"],i);let r=s(n,["trainingDataset"]);r!=null&&gh(r,t,e);let l=s(n,["config"]);return l!=null&&oh(l,t,e),t}f(rh,"createTuningJobParametersPrivateToVertex");function sh(n,e){let t={},o=s(n,["name"]);return o!=null&&a(t,["_url","name"],o),t}f(sh,"getTuningJobParametersToMldev");function ah(n,e){let t={},o=s(n,["name"]);return o!=null&&a(t,["_url","name"],o),t}f(ah,"getTuningJobParametersToVertex");function lh(n,e,t){let o={},i=s(n,["pageSize"]);e!==void 0&&i!=null&&a(e,["_query","pageSize"],i);let r=s(n,["pageToken"]);e!==void 0&&r!=null&&a(e,["_query","pageToken"],r);let l=s(n,["filter"]);return e!==void 0&&l!=null&&a(e,["_query","filter"],l),o}f(lh,"listTuningJobsConfigToMldev");function ch(n,e,t){let o={},i=s(n,["pageSize"]);e!==void 0&&i!=null&&a(e,["_query","pageSize"],i);let r=s(n,["pageToken"]);e!==void 0&&r!=null&&a(e,["_query","pageToken"],r);let l=s(n,["filter"]);return e!==void 0&&l!=null&&a(e,["_query","filter"],l),o}f(ch,"listTuningJobsConfigToVertex");function dh(n,e){let t={},o=s(n,["config"]);return o!=null&&lh(o,t),t}f(dh,"listTuningJobsParametersToMldev");function uh(n,e){let t={},o=s(n,["config"]);return o!=null&&ch(o,t),t}f(uh,"listTuningJobsParametersToVertex");function fh(n,e){let t={},o=s(n,["sdkHttpResponse"]);o!=null&&a(t,["sdkHttpResponse"],o);let i=s(n,["nextPageToken"]);i!=null&&a(t,["nextPageToken"],i);let r=s(n,["tunedModels"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(c=>tl(c))),a(t,["tuningJobs"],l)}return t}f(fh,"listTuningJobsResponseFromMldev");function ph(n,e){let t={},o=s(n,["sdkHttpResponse"]);o!=null&&a(t,["sdkHttpResponse"],o);let i=s(n,["nextPageToken"]);i!=null&&a(t,["nextPageToken"],i);let r=s(n,["tuningJobs"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(c=>fi(c))),a(t,["tuningJobs"],l)}return t}f(ph,"listTuningJobsResponseFromVertex");function mh(n,e){let t={},o=s(n,["name"]);o!=null&&a(t,["model"],o);let i=s(n,["name"]);return i!=null&&a(t,["endpoint"],i),t}f(mh,"tunedModelFromMldev");function hh(n,e){let t={};if(s(n,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(s(n,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");let o=s(n,["examples"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>r)),a(t,["examples","examples"],i)}return t}f(hh,"tuningDatasetToMldev");function gh(n,e,t){let o={},i=s(t,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let l=s(n,["gcsUri"]);e!==void 0&&l!=null&&a(e,["supervisedTuningSpec","trainingDatasetUri"],l)}else if(i==="PREFERENCE_TUNING"){let l=s(n,["gcsUri"]);e!==void 0&&l!=null&&a(e,["preferenceOptimizationSpec","trainingDatasetUri"],l)}let r=s(t,["config","method"]);if(r===void 0&&(r="SUPERVISED_FINE_TUNING"),r==="SUPERVISED_FINE_TUNING"){let l=s(n,["vertexDatasetResource"]);e!==void 0&&l!=null&&a(e,["supervisedTuningSpec","trainingDatasetUri"],l)}else if(r==="PREFERENCE_TUNING"){let l=s(n,["vertexDatasetResource"]);e!==void 0&&l!=null&&a(e,["preferenceOptimizationSpec","trainingDatasetUri"],l)}if(s(n,["examples"])!==void 0)throw new Error("examples parameter is not supported in Vertex AI.");return o}f(gh,"tuningDatasetToVertex");function tl(n,e){let t={},o=s(n,["sdkHttpResponse"]);o!=null&&a(t,["sdkHttpResponse"],o);let i=s(n,["name"]);i!=null&&a(t,["name"],i);let r=s(n,["state"]);r!=null&&a(t,["state"],Aa(r));let l=s(n,["createTime"]);l!=null&&a(t,["createTime"],l);let c=s(n,["tuningTask","startTime"]);c!=null&&a(t,["startTime"],c);let d=s(n,["tuningTask","completeTime"]);d!=null&&a(t,["endTime"],d);let u=s(n,["updateTime"]);u!=null&&a(t,["updateTime"],u);let p=s(n,["description"]);p!=null&&a(t,["description"],p);let m=s(n,["baseModel"]);m!=null&&a(t,["baseModel"],m);let h=s(n,["_self"]);return h!=null&&a(t,["tunedModel"],mh(h)),t}f(tl,"tuningJobFromMldev");function fi(n,e){let t={},o=s(n,["sdkHttpResponse"]);o!=null&&a(t,["sdkHttpResponse"],o);let i=s(n,["name"]);i!=null&&a(t,["name"],i);let r=s(n,["state"]);r!=null&&a(t,["state"],Aa(r));let l=s(n,["createTime"]);l!=null&&a(t,["createTime"],l);let c=s(n,["startTime"]);c!=null&&a(t,["startTime"],c);let d=s(n,["endTime"]);d!=null&&a(t,["endTime"],d);let u=s(n,["updateTime"]);u!=null&&a(t,["updateTime"],u);let p=s(n,["error"]);p!=null&&a(t,["error"],p);let m=s(n,["description"]);m!=null&&a(t,["description"],m);let h=s(n,["baseModel"]);h!=null&&a(t,["baseModel"],h);let g=s(n,["tunedModel"]);g!=null&&a(t,["tunedModel"],g);let b=s(n,["preTunedModel"]);b!=null&&a(t,["preTunedModel"],b);let E=s(n,["supervisedTuningSpec"]);E!=null&&a(t,["supervisedTuningSpec"],E);let I=s(n,["preferenceOptimizationSpec"]);I!=null&&a(t,["preferenceOptimizationSpec"],I);let v=s(n,["tuningDataStats"]);v!=null&&a(t,["tuningDataStats"],v);let w=s(n,["encryptionSpec"]);w!=null&&a(t,["encryptionSpec"],w);let T=s(n,["partnerModelTuningSpec"]);T!=null&&a(t,["partnerModelTuningSpec"],T);let C=s(n,["customBaseModel"]);C!=null&&a(t,["customBaseModel"],C);let A=s(n,["experiment"]);A!=null&&a(t,["experiment"],A);let G=s(n,["labels"]);G!=null&&a(t,["labels"],G);let N=s(n,["outputUri"]);N!=null&&a(t,["outputUri"],N);let H=s(n,["pipelineJob"]);H!=null&&a(t,["pipelineJob"],H);let x=s(n,["serviceAccount"]);x!=null&&a(t,["serviceAccount"],x);let D=s(n,["tunedModelDisplayName"]);D!=null&&a(t,["tunedModelDisplayName"],D);let J=s(n,["veoTuningSpec"]);return J!=null&&a(t,["veoTuningSpec"],J),t}f(fi,"tuningJobFromVertex");function bh(n,e){let t={},o=s(n,["sdkHttpResponse"]);o!=null&&a(t,["sdkHttpResponse"],o);let i=s(n,["name"]);i!=null&&a(t,["name"],i);let r=s(n,["metadata"]);r!=null&&a(t,["metadata"],r);let l=s(n,["done"]);l!=null&&a(t,["done"],l);let c=s(n,["error"]);return c!=null&&a(t,["error"],c),t}f(bh,"tuningOperationFromMldev");function Ea(n,e){let t={},o=s(n,["gcsUri"]);o!=null&&a(t,["validationDatasetUri"],o);let i=s(n,["vertexDatasetResource"]);return i!=null&&a(t,["validationDatasetUri"],i),t}f(Ea,"tuningValidationDatasetToVertex");var pi=class extends we{static{f(this,"Tunings")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Ge(Re.PAGED_ITEM_TUNING_JOBS,o=>this.listInternal(o),await this.listInternal(t),t),this.get=async t=>await this.getInternal(t),this.tune=async t=>{var o;if(this.apiClient.isVertexAI())if(t.baseModel.startsWith("projects/")){let i={tunedModelName:t.baseModel};!((o=t.config)===null||o===void 0)&&o.preTunedModelCheckpointId&&(i.checkpointId=t.config.preTunedModelCheckpointId);let r=Object.assign(Object.assign({},t),{preTunedModel:i});return r.baseModel=void 0,await this.tuneInternal(r)}else{let i=Object.assign({},t);return await this.tuneInternal(i)}else{let i=Object.assign({},t),r=await this.tuneMldevInternal(i),l="";return r.metadata!==void 0&&r.metadata.tunedModel!==void 0?l=r.metadata.tunedModel:r.name!==void 0&&r.name.includes("/operations/")&&(l=r.name.split("/operations/")[0]),{name:l,state:wo.JOB_STATE_QUEUED}}}}async getInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=ah(e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>fi(p))}else{let u=sh(e);return c=_("{name}",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>tl(p))}}async listInternal(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=uh(e);return c=_("tuningJobs",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=ph(p),h=new dn;return Object.assign(h,m),h})}else{let u=dh(e);return c=_("tunedModels",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=fh(p),h=new dn;return Object.assign(h,m),h})}}async cancel(e){var t,o,i,r;let l,c="",d={};if(this.apiClient.isVertexAI()){let u=jm(e);return c=_("{name}:cancel",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=th(p),h=new un;return Object.assign(h,m),h})}else{let u=Zm(e);return c=_("{name}:cancel",u._url),d=u._query,delete u._url,delete u._query,l=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),l.then(p=>{let m=eh(p),h=new un;return Object.assign(h,m),h})}}async tuneInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI()){let c=rh(e,e);return r=_("tuningJobs",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>fi(d))}else throw new Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(e){var t,o;let i,r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=ih(e);return r=_("tunedModels",c._url),l=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>bh(d))}}};var mi=class{static{f(this,"BrowserDownloader")}async download(e,t){throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.")}},yh=1024*1024*8,Eh=3,Ih=1e3,vh=2,Rn="x-goog-upload-status";async function wh(n,e,t){var o;let i=await nl(n,e,t),r=await i?.json();if(((o=i?.headers)===null||o===void 0?void 0:o[Rn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return r.file}f(wh,"uploadBlob");async function Th(n,e,t){var o;let i=await nl(n,e,t),r=await i?.json();if(((o=i?.headers)===null||o===void 0?void 0:o[Rn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let l=va(r),c=new ko;return Object.assign(c,l),c}f(Th,"uploadBlobToFileSearchStore");async function nl(n,e,t){var o,i;let r=0,l=0,c=new xt(new Response),d="upload";for(r=n.size;l<r;){let u=Math.min(yh,r-l),p=n.slice(l,l+u);l+u>=r&&(d+=", finalize");let m=0,h=Ih;for(;m<Eh&&(c=await t.request({path:"",body:p,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:e,headers:{"X-Goog-Upload-Command":d,"X-Goog-Upload-Offset":String(l),"Content-Length":String(u)}}}),!(!((o=c?.headers)===null||o===void 0)&&o[Rn]));)m++,await Ch(h),h=h*vh;if(l+=u,((i=c?.headers)===null||i===void 0?void 0:i[Rn])!=="active")break;if(r<=l)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return c}f(nl,"uploadBlobInternal");async function _h(n){return{size:n.size,type:n.type}}f(_h,"getBlobStat");function Ch(n){return new Promise(e=>setTimeout(e,n))}f(Ch,"sleep");var hi=class{static{f(this,"BrowserUploader")}async upload(e,t,o){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await wh(e,t,o)}async uploadToFileSearchStore(e,t,o){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await Th(e,t,o)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await _h(e)}};var gi=class{static{f(this,"BrowserWebSocketFactory")}create(e,t,o){return new bi(e,t,o)}},bi=class{static{f(this,"BrowserWebSocket")}constructor(e,t,o){this.url=e,this.headers=t,this.callbacks=o}connect(){this.ws=new WebSocket(this.url),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(e){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};var Ia="x-goog-api-key",yi=class{static{f(this,"WebAuth")}constructor(e){this.apiKey=e}async addAuthHeaders(e,t){if(e.get(Ia)===null){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");if(!this.apiKey)throw new Error("API key is missing. Please provide a valid API key.");e.append(Ia,this.apiKey)}}};var Sh="gl-node/",Nt=class{static{f(this,"GoogleGenAI")}get interactions(){if(this._interactions!==void 0)return this._interactions;if(console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions."),this.vertexai)throw new Error("This version of the GenAI SDK does not support Vertex AI API for interactions.");let e=this.httpOptions;e?.extraBody&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.");let t=new Y({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:e?.timeout});return this._interactions=t.interactions,this._interactions}constructor(e){var t;if(e.apiKey==null)throw new Error("An API Key must be set when running in a browser");if(e.project||e.location)throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.");this.vertexai=(t=e.vertexai)!==null&&t!==void 0?t:!1,this.apiKey=e.apiKey;let o=tc(e.httpOptions,e.vertexai,void 0,void 0);o&&(e.httpOptions?e.httpOptions.baseUrl=o:e.httpOptions={baseUrl:o}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let i=new yi(this.apiKey);this.apiClient=new Ko({auth:i,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:Sh+"web",uploader:new hi,downloader:new mi}),this.models=new ei(this.apiClient),this.live=new Zo(this.apiClient,i,new gi),this.batches=new Ho(this.apiClient),this.chats=new Bo(this.models,this.apiClient),this.caches=new Vo(this.apiClient),this.files=new Oo(this.apiClient),this.operations=new ti(this.apiClient),this.authTokens=new ni(this.apiClient),this.tunings=new pi(this.apiClient),this.fileSearchStores=new ii(this.apiClient)}};var et=V||!0,ol=new Map,il=[];function tt(){let n=`[${tt.name}]`;try{return et&&console.log(`${n} starting... (I: a5cf5821b42e1c71182dd61431977e25)`),ol}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{et&&console.log(`${n} complete.`)}}f(tt,"getAllFunctionInfos");function Ci(){let n=`[${Ci.name}]`;try{return et&&console.log(`${n} starting... (I: 82c9a8fc91d8121fb843af32e76c2e25)`),il}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{et&&console.log(`${n} complete.`)}}f(Ci,"getDeprecatedFunctionInfoNames");function Ah({functionInfos:n}){let e=`[${Ah.name}]`;try{et&&console.log(`${e} starting... (I: 14fee8e27384a040494542182031ae25)`),n.size===0&&console.warn(`${e} empty functionInfos? (W: 97fcb8fc47689bc418893c09a16a2525)`);for(let[t,o]of n)il.includes(t)?et&&console.log(`${e} functionInfo.nameOrId (${t}) is deprecated. Skipping add. (I: 3256eadf54f8087088a704798e2fd825)`):ol.set(t,o)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{et&&console.log(`${e} complete.`)}}f(Ah,"registerFunctionInfos");var ue=V;function $t(n){switch(n){case X.HUMAN:return"user";case X.AI:return"model";case X.FUNCTION:return"user";case X.HARDCODED:return"user";case X.UNKNOWN:return"user";default:throw new Error(`(UNEXPECTED) src is not a valid TextSource? src: ${n} (E: 9d954fe0bc49cf4572a65b19b6173925)`)}}f($t,"textSourceToGeminiRole");function rl(n){return n.api==="gemini"}f(rl,"isPromptInfoGemini");function Si({systemPromptEntries:n}){let e=`[${Si.name}]`;try{if(ue&&console.log(`${e} starting... (I: 18693a97427939699285ef8c1a9cc425)`),n.length===0)return;n.every(o=>o.src===X.HUMAN)||ue&&console.warn(`${e} not every system entry's src is human. We're still going to say that these are "user" origin in Gemini API. (W: 7115e2be876498ecb1e153c79a86e125)`);let t={role:"user",parts:n.filter(o=>!!o.content.parts).flatMap(o=>o.content.parts)};return ue&&console.log(`${e} sysInstructionContent: ${M(t)} (I: 011e5b865c23eb0b640df3f464ac2525)`),t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{ue&&console.log(`${e} complete.`)}}f(Si,"systemPromptEntriesToSystemInstructionContent");function Ai({ibGib:n}){let e=`[${Ai.name}]`;try{if(ue&&console.log(`${e} starting... (I: 986d3edcd4f3aaf1d7eb0f8b59206b25)`),!n)return ue&&console.warn(`${e} ibGib falsy. (W: a70390e8bc3f420a92d3a84f4c78f12a)`),!1;if(!Ye({ibGib:n}))return ue&&console.log(`${e} not a comment ibgib (I: 6a62c4f6e13776616855c4f237a5206b)`),!1;if(!n.data)return ue&&console.log(`${e} ibGib.data falsy (I: 69eb86975640475395bb74944141a46d)`),!1;let{text:t}=n.data;return t?t.includes(Jt)?(ue&&console.log(`${e} has tag. returning true. (I: 6d76b27d558d44f696582f41af561f29)`),!0):(ue&&console.log(`${e} no indicator found. returning false. (I: 815f181a0a08058362f76b08a8964674)`),!1):(ue&&console.log(`${e} text falsy (I: e348e38c841b4443b3f09e75c0215b24)`),!1)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{ue&&console.log(`${e} complete.`)}}f(Ai,"isFunctionCallRequestComment");function xi({functionInfoIbGib:n}){let e=`[${xi.name}]`;try{if(ue&&console.log(`${e} starting... (I: 1a2b3c4d5e6f7a8b)`),!n)throw new Error(`${e} functionInfoIbGib parameter is required. (E: 9c8f7a3b2d1e4a5b6c7d8e9f)`);if(!n.data)throw new Error(`${e} functionInfoIbGib.data is required. (E: 2b3c4d5e6f7a8b1c2d3e4f5a)`);let{fnName:t,fnArgs:o,fnResult:i}=n.data;if(!t)throw new Error(`${e} functionInfoIbGib.data.fnName is required. (E: 6f7a8b1c2d3e4f5a6b7c8d9e)`);return{call:{functionCall:{name:t,args:o??{}}},response:{functionResponse:{name:t,response:{value:i}}}}}catch(t){throw console.error(`${e} Error: ${y(t)}`),t}finally{ue&&console.log(`${e} complete.`)}}f(xi,"getFunctionCallAndResponseParts");var Rt=V,Ln="function_info",sl="function_info";function al({data:n}){let e=`[${al.name}]`,{model:t,api:o,agentId:i,timestamp:r}=n;if(!t)throw new Error(`${e} data.model falsy (E: 6f47a28c0a8a45d794149c83e8f27e25)`);if(!o)throw new Error(`${e} data.api falsy (E: a0a812508a952a87c619d38084b7e325)`);if(!i)throw new Error(`${e} data.agentId falsy (E: ac35c1592c458e2c0e5908f6a9a3e525)`);let l=ze(r);if([t,o,i,l].some(d=>d.includes(" ")))throw new Error("invalid data. ib must not contain spaces (E: 36a56e4685163848458be06f51d4ad25)");return[sl,l,t,o,i].join(" ")}f(al,"getFunctionInfoIb");async function kn(n){let e=`[${kn.name}]`;try{Rt&&console.log(`${e} starting... (I: f4c9f0810a4d877f676297f6e6a96825)`);let{fnRawRequest:t,api:o,model:i,agentId:r,fnName:l,fnArgs:c,fnResult:d,fnComplete:u,parseErrorMsg:p,execErrorMsg:m,repromptWithResult:h,saveInSpace:g,metaspace:b,space:E}=n,I=new Date,v={name:i,timestamp:Lt(I),timestampMs:I.getMilliseconds(),agentId:r,api:o,model:i,fnRawRequest:t,fnName:l,fnArgs:c,fnResult:d,fnComplete:u,repromptWithResult:h};p&&(v.parseErrorMsg=p),m&&(v.execErrorMsg=m);let w=al({data:v}),T=await ne.firstGen({ib:w,parentIbGib:ne.primitive({ib:sl}),data:v,nCounter:!0,dna:!0,tjp:{uuid:!0}});if(Rt&&console.log(`${e} created functionInfoIbGib (I: e50d2e17f43312d4f4739899306bb725)`),g){if(!b)throw new Error(`${e} metaspace must be provided if saveInSpace is set to true (E: e74b76b00124d5874a6c5404e794b725)`);if(!E)throw new Error(`${e} space must be provided if saveInSpace is set to true (E: f3d5f1695a52707114117f72d932a025)`);await b.persistTransformResult({resTransform:T,space:E}),Rt&&console.log(`${e} persisted resFunctionInfo (${S({ibGib:T.newIbGib})}) to space ${E.data?.uuid} (I: aa98e877d3b34e0d2a3b7711f8f27e25)`),await b.registerNewIbGib({ibGib:T.newIbGib,space:E}),Rt&&console.log(`${e} registered new function info ibgib (${S({ibGib:T.newIbGib})}) with metaspace (I: aa98e877d3b34e0d2a3b7711f8f27e25)`)}return T}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Rt&&console.log(`${e} complete.`)}}f(kn,"createFunctionInfoIbGib");var R=V,Un=class n extends _r{static{f(this,"AgentWitness_V1")}lc=`[${n.name}]`;availableFunctions=new Map;commentIbGibs_system=[];commentIbGibs_chat=[];_metaspace;fnGetAPIKey=f(()=>Promise.reject("not implemented. you need to set this after initializing the agent. (E: a14cbe903d08821126bbbb1d063d9825)"),"fnGetAPIKey");get name(){return this.data?.name??""}get uuid(){return this.data?.uuid??""}_genAI;transientDecompressionPromptText;fnOutputText=f(e=>{console.log(`${this.lc}[fnOutputText] this hack does nothing by default. set this to do something when text is returned by the model LLM. textResponse: ${e} (W: 3007e5d69dafdd7e42157fa7370d7f25)`)},"fnOutputText");ibGibProxy;constructor(e,t){super(e,t),this.instanceId=nt({count:32})}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{R&&console.log(`${e} starting... (I: 641e211473fc54d5a9ebb4ea44944d25)`);let t=await super.validateThis();return this.data?(this.data?.subSpaceId||t.push("agent.data.subSpaceId falsy (E: d4ea57fd6b1c5cbc1e18a084de2f7725)"),this.data?.subSpaceId.match(Dt)||t.push(`agent.data.subSpaceId must match regexp: ${Dt}. (E: f381eff533aa3f4713316f93f7f1dc25)`),this.data.name?this.data.name.match(st)||t.push(`agent name must match regexp: ${st}`):t.push("agent name falsy (E: 1351325107e5ac5ea6b7b789b73de125)"),this.data.description&&(this.data.description.match(so)||t.push(`agent description must match regexp: ${so}`))):t.push("this.data falsy (E: f5f151e11b12cad814b37ecad7c74a25)"),t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{R&&console.log(`${e} starting... (I: ce38519ac4bef52844a558fe31cda825)`),await super.initialize(),this._metaspace=await me();let t=new Ue;if(await t.initialized,!t.contextUpdated$)throw new Error("(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: e8840870af18091e6e4d52490ddca825)");if(t.contextUpdated$.subscribe($e({next:f(async o=>{let i=`${e}[ibGibProxy.contextUpdated$][next]`;R&&console.log(`${i} nextIbGib: ${M(o)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleContextUpdated()},"next"),error:f(async o=>{debugger;console.error(`${e}[ibGibProxy.contextUpdated$][error] what up? ${y(o)}`)},"error")})),this.ib&&this.gib&&this.data){let o=this.toIbGibDto();await this.loadIbGibDto(o);let i=await this._metaspace.getLocalUserSpace({localSpaceId:o.data?.superSpaceId});if(!i)throw new Error(`couldn't get local space with agent.data.superSpaceId (${o.data?.superSpaceId})? (E: 0fc1b8a8ffa26f39d8a15218ec818725)`);await this.ibGibProxy?.setWrappedIbGib({ibGib:o,space:i})}else R&&console.log(`${e} agent is "empty". not loading dto at this time, caller is responsible for calling loadIbGibDto (I: 06dba19d74d5695fe7d1957889283725)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{if(!this.ibGibProxy)throw new Error("(UNEXPECTED) this.ibGibProxy falsy but we're within handleContextUpdated handler? (E: a88fa85e8f27bd7f72c207389ebfbc25)");if(!this.ibGibProxy.ibGib)throw new Error("(UNEXPECTED) this.ibGibProxy.ibGib falsy but we're within the handleContextUpdated handler? (E: ca60b8f0a60a3e3d652c3018102d1825)");debugger;if(!this.gib){debugger;console.error(`${e} not sure if error, but this.gib is falsy when we get a new context down the pipeline? (E: 8501d8aee4db7b8461587f38f0bbb125)`)}if(S({ibGib:this})!==S({ibGib:this.ibGibProxy.ibGib})){let t=this.ibGibProxy.ibGib.data.n??0,o=this.data?.n??0;if(t<=o){debugger;console.error(`${e} issue with "new" proxy context and the current this.data.n with different addresses. divergent timelines? (E: 15c698eb4488cbae2db0e778fec15825)`)}await this.loadIbGibDto(this.ibGibProxy.ibGib),await W(200)}else console.error(`${e} ibgibProxy new context is no different than current. this is NOT necessarily an error, I just want to see this when it happens. nothing is being done here, we're just not loading the "new" ibgib dto. (E: eff668b2e858ded448366d58e4dd6825)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}}async getSubSpace(){let e=`[${this.getSubSpace.name}]`;try{R&&console.log(`${e} starting... (I: a2ec2c5e8f5fdf95c8c571b2b1b9e925)`);let{_metaspace:t}=this;if(!t)throw new Error("(UNEXPECTED) this.metaspace falsy? after init this.metaspace is expected to be set. (E: 4519a8feaf4489389be679598f274425)");let o=await t.getLocalUserSpace({localSpaceId:this.data.subSpaceId});if(!o){let i=await this.validateThis();if(i.length>0)throw new Error(`this agent has validation errors: ${i} (E: 9a0c6125cf89789ddb1610cf5a752225)`);if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 06e30e1d53fd4935333c7cf7e10db425)");o=await t.createLocalSpaceAndUpdateBootstrap({allowCancel:!1,zeroSpace:t.zeroSpace,spaceName:this.name+this.uuid.substring(0,5),createBootstrap:!1})}if(!o)throw new Error("(UNEXPECTED) space still falsy after creating locally? (E: 037ef1e6f54a675d0367227fdae16525)");return o}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async getSuperSpace(){let e=`[${this.getSuperSpace.name}]`;try{R&&console.log(`${e} starting... (I: 55fba9bcaf9539cc2219e03cda200525)`);let{_metaspace:t}=this;if(!t)throw new Error("(UNEXPECTED) this.metaspace falsy? after init this.metaspace is expected to be set. (E: 107f670c99832c573a7e5de18d58c325)");if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: a4341b8753678fcba7877b6319769b25)");if(!this.data.superSpaceId)throw new Error("(UNEXPECTED) this.data.superSpaceId falsy? (E: 0429fe44df5b56bf2ac67d38cde56325)");let o=await t.getLocalUserSpace({localSpaceId:this.data.superSpaceId});if(!o)throw new Error(`(UNEXPECTED) superSpace falsy? this.data.superSpaceId: ${this.data.superSpaceId} (E: fd9435212e8b87e4b60034bf9e797f25)`);return o}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{R&&console.log(`${e} complete.`)}}_activeContext=void 0;async setActiveContext(e){let t=`${this.lc}[${this.setActiveContext.name}]`;try{R&&console.log(`${t} starting... (I: genuuid)`);let{contextIbGib:o,loggingInfo:i}=e;if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: ab5377fda6bc324638722d9832bab925)");if(!o)throw new Error("(UNEXPECTED) contextIbGib falsy? (E: 694525e512cfdd12c14e1213dbaab925)");if(!o.data)throw new Error("(UNEXPECTED) contextIbGib.data falsy? (E: f337252a23c822bcbd76144540050825)");let r=S({ibGib:o}),l=re({ibGib:o});if(!l)throw new Error(`(UNEXPECTED) contextTjpAddr falsy? contextIbGib (${r}) is expected to be a living ibgib with a tjp address (i.e. a timeline). This means it should have a rel8ns.tjp or data.isTjp should be truthy. (E: d756d1e862d2cccfed4a5807737e9a25)`);if(this.data?.["@currentContextTjpAddr"]===l?R&&console.log(`${t} this.data.@currentContextTjpAddr already set to the same addr. (I: 9f0d58ec65eee3ca2aec528f1328c325)`):await this.mut8Self({dataToAddOrPatch:{"@currentContextTjpAddr":l}}),!this._activeContext){let c=new Ue;await c.initialized;let d=`${t}[contextUpdated]`;if(!c.contextUpdated$)throw new Error("(UNEXPECTED) proxy.contextUpdated$ falsy? (E: 868c5e3bf025baa6d1ae727ab1160c25)");c.contextUpdated$.subscribe($e({next:f(async p=>{console.log(`${d}[next] nextIbGib: ${M(p)}`)},"next"),complete:f(async()=>{debugger;throw new Error(`${d}[complete] (UNEXPECTED) agent active context subscription complete? i honestly don't know if this hits. (E: 786d26ab23e4313db7ae2e08c70a7425)`)},"complete"),error:f(async p=>{debugger;console.error(`${d}[error] ${y(p)}`)},"error")}));let u=`${t}[newContextChild]`;if(!c.newContextChild$)throw new Error("(UNEXPECTED) proxy.newContextChild$ falsy? (E: 123cf5624c3d2a6308aafc0c41f8a925)");c.newContextChild$.subscribe($e({next:f(async p=>{if(console.log(`${u}[next] newChild: ${M(p)}`),!p.data)throw new Error("newChild.data falsy? (E: a654134a2695c176971b0cd1426ced25)");if(Ye({ibGib:p})){let m=this.commentIbGibs_chat.map(I=>re({ibGib:I})??S({ibGib:I})),h=re({ibGib:p})??S({ibGib:p});if(m.includes(h)){console.log(`${t} already did this comment (${h}) (I: bce18642bb9babeb553e6188d7ae2825)`);return}let{safeIbCommentMetadataText:g}=Ke({ib:p.ib}),{textSrc:b}=Gt({addlMetadataText:g??"",ifError:"warn"}),E=p.data.text.startsWith("system: ");await this.addTexts({infos:[{textSrc:b??X.UNKNOWN,commentIbGib:p,isSystem:E}]}),b===X.HUMAN&&(E?console.log(`${t} system prompt has been modified. (I: d21c26f0a3fa12e2a874925882f39825)`):await this.doPrompt())}else console.warn(`${u} non-comment newChild. probably not a warning proper, but at this stage I'm only expecting comments ignoring... (W: e664834af4791ddcde19bfd4f7063e25)`)},"next"),complete:f(async()=>{debugger;throw new Error(`${u}[complete] (UNEXPECTED) agent active context subscription complete? i honestly don't know if this hits. (E: 88202d1f7554330d3dfca0237c2d6525)`)},"complete"),error:f(async p=>{debugger;console.error(`${u}[error] ${y(p)}`)},"error")})),this._activeContext=c}if(!this._activeContext)throw new Error("(UNEXPECTED) this._activeContext still falsy after we just initialized it? (E: 584f2f672b9ae7c979dde693eafb7a25)");await this._activeContext.setWrappedIbGib({ibGib:o})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{R&&console.log(`${t} complete.`)}}async updateName({name:e}){let t=`${this.lc}[${this.updateName.name}]`;try{if(R&&console.log(`${t} starting... (I: genuuid)`),e===this.name){console.warn(`${t} agent (${this.uuid}) already is named ${e}. returning early... (W: genuuid)`);return}else if(st.test(e))await this.mut8Self({dataToAddOrPatch:{name:e}});else throw new Error(`invalid name ${e}. must match regexp: ${st.source} (E: 507a2bfc0aaa60bd7bb608d253239e25)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{R&&console.log(`${t} complete.`)}}async updateAvailableFunctions({availableFunctions:e}){let t=`${this.lc}[${this.updateAvailableFunctions.name}]`;try{R&&console.log(`${t} starting... (I: 68f1bfa343925a657f8c0545b191c725)`);let o=[];for(let i of e)if(!this.availableFunctions.has(i.nameOrId)){let r=tt().get(i.nameOrId);if(r)o.push(r);else{console.error(`(UNEXPECTED) ${i} function not registered with getAllFunctionInfos()? skipping adding this function to the agent... (E: e860fe13c02677b274ac0e7df2587a25)`);continue}}o.length>0&&(console.log(`${t} adding newly found functions to agent: ${o.map(i=>i.nameOrId)}. (I: ab2b0ae6a62b3ced6a5f1e2e8cec4f25)`),await this.addAvailableFunctions(o))}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{R&&console.log(`${t} complete.`)}}async mut8Self({dataToAddOrPatch:e}){let t=`${this.lc}[${this.mut8Self.name}]`;try{R&&console.log(`${t} starting... (I: f4618832a0fe07ff8c89cea889d20725)`);let o=this._metaspace;if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: genuuid)");let i=await o.getLocalUserSpace({lock:!1,localSpaceId:this.data.superSpaceId});if(!i)throw new Error(`couldn't get local superSpace given by this.data.superSpaceId (${this.data.superSpaceId}) (E: genuuid)`);let{tjpGib:r}=K({gib:this.gib});if(!r)throw new Error(`(UNEXPECTED) this.gib (${this.gib}) has no tjpGib? (E: 75b8dcb82b58d3b0db40b39149023e25)`);await Ht({fn:f(async()=>{let l=xe();await l.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1});let c=await Ji({type:"mut8",src:this.toIbGibDto(),dataToAddOrPatch:e,dna:!0,nCounter:!0});await o.persistTransformResult({resTransform:c,space:i});let d=c.newIbGib;await this.loadIbGibDto(d),await l.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!0}),await o.registerNewIbGib({ibGib:d,space:i}),await Pi({newAgentIbGib:d,metaspace:o,space:i,type:this.data.type})},"fn"),scope:r,secondsValid:60,maxDelayMs:100,maxLockAttempts:Number.MAX_SAFE_INTEGER,space:i,callerInstanceId:this.instanceId})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{R&&console.log(`${t} complete.`)}}getAvailableFunctions(){return Array.from(this.availableFunctions.values())}getComments_System(){return[...this.commentIbGibs_system]}getComments_Chat(){return[...this.commentIbGibs_chat]}async addAvailableFunctions(e){let t=`[${this.addAvailableFunctions.name}]`;try{if(R&&console.log(`${t} starting... (I: 273525464ec540fc9cba565e608db925)`),!e)throw new Error("(UNEXPECTED) functionInfos falsy? (E: 19cf2b7c9ee1115f0a3f7f62fbf77825)");if(e.length===0){console.warn(`${t} functionInfos.length === 0? why is this being called with no functions? returning early without doing anything. (W: 86c6dc4fad3c1ddcac697d5636b1eb25)`);return}await xe().updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1}),e.forEach(i=>{this.availableFunctions.has(i.nameOrId)&&console.warn(`${t} this.availableFunctions already has an entry for ${i.nameOrId}. replacing anyway. (W: ef2372a27be67174cb3605eac2c85c25)`),this.availableFunctions.set(i.nameOrId,i)}),await this.mut8Self({dataToAddOrPatch:{availableFunctionNameOrIds:Array.from(this.availableFunctions.keys())}})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{R&&console.log(`${t} complete.`)}}async doPrompt(){let e=`[${this.doPrompt.name}]`;try{if(R&&console.log(`${e} starting... (I: e7f1a7845cdf1bdce1f12d74c71a6425)`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 3c528e2376a2f2600b347b2c183a5225)");let t=await this.composePromptInfo();R&&console.log(`${e} promptTextInfo: ${M(t)} (I: b769b5f2a47623a99f78210994d90525)`);let o=await this.callTextAPI(t);if(R&&console.log(`${e} api result:`,o,"(I: e4d2c767eb3d6e38d83123d684a07425)"),"text"in o)await this.doPrompt_text(o.text);else{let{functionCalls:i}=o;await this.doPrompt_functionCalls({functionCalls:i})}}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async doPrompt_text(e){let t=`${this.lc}[${this.doPrompt_text.name}]`;try{R&&console.log(`${t} starting... (I: a2b9c21f3b2b058d355d16421e2b4425)`),e||="[no text returned from the model]",this.fnOutputText?this.fnOutputText(e):console.log(`${t} no fnOutputText set. Text Response: ${e} (I: 5936517474b10b214257781a24b10425)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{R&&console.log(`${t} complete.`)}}async doPrompt_functionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls.name}]`;try{if(R&&console.log(`${t} starting... (I: a4f1b581517a9c2a9187e9f8f3519925)`),e.length===0)throw new Error("(UNEXPECTED) functionCalls.length is zero? (E: 6434b8515a435a59b331452b563f4425)");let o=await this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({functionCalls:e});if(await this.doPrompt_functionCalls_addFunctionCallRequestComment({functionInfoIbGibs:o}),o.some(r=>!!r.data?.repromptWithResult&&r.data.fnName!=="tellUser")){let r=await this.doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt({functionInfoIbGibs:o});r.length>0?(console.log(`${t} transientDecompressionPromptText: ${r} (I: 11c11d544b7c8f8f8e7e5f7c1a9e3625)`),this.transientDecompressionPromptText=r,await this.rePrompt()):console.warn(`${t} (UNEXPECTED) there is no decompression text? (W: 6ce5da95c1c89a7ec48a00fbc1d11825)`)}else R&&console.log(`${t} no repromptWithResult. returning early. (I: 9c0113c958c7404534291f6700325925)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{R&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls.name}]`;try{if(R&&console.log(`${t} starting... (I: adc094bc98cb076a4aaf729f70adce25)`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: d071328283b2cf880ff0ccd499c22b25)");if(!this.data.uuid)throw new Error("(UNEXPECTED) this.data.uuid falsy? (E: 8acd2f793e4b5a368dbcf1d8d1e6e825)");let o=this._metaspace;if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: acf8a69e853eb8663f1dd0f79a823e25)");let i=[];for(let r of e)try{R&&console.log(`${t} processing functionCall: ${r} (I: a0c0b22b3c6b6c4b674a5a9c8c8b9e25)`);let l,c,d,u,p,m="";try{if(c=JSON.parse(r),m=c?.name??"",!m)throw new Error("functionName (functionCallParsedObj.name) falsy (E: e2397d675863a12b7609495b0007a025)");if(R&&console.log(`${t} functionCallParsedObj:`,M(c),"(I: 750f097243b85644d111971e0f929c25)"),u=tt().get(c.name),!u)throw new Error(`no APIFunctionInfo found that matches functionName (${m}) (E: 9d36b6472ec5cdf95e4f498292449925)`);p=c.args,R&&console.log(`${t} valid params (I: a4d5c13c79a2405c8d20464b42083325)`)}catch(h){d=`${t} invalid functionCallParsedObj. error: ${y(h)}. functionCallStr: ${r}. (E: 1687a24c5a3667d34689a09f8f753125)`,console.error(d),c=void 0}if(u){R&&console.log(`${t} found functionInfo: ${u.nameOrId} (I: 837c7a8200689a0b2314b73057812b25)`);let h,g=!1,b;try{R&&console.log(`${t} calling function impl for ${u.nameOrId} (I: b145d08186782089c18564305f0f1125)`),h=await u.fnViaCmd(p),g=!0,R&&console.log(`${t} functionImpl complete for ${u.nameOrId}. result:`,M(h),"(I: e19d476f489261263165914750472d25)")}catch(I){b=`${t} could not call functionImpl for ${u.nameOrId}: ${y(I)} (E: 9c0e97f29a9290f9d57637b7053f0c25)`,console.error(b)}l=(await kn({api:this.data.api,model:this.data.model,agentId:this.data.uuid,fnRawRequest:r,fnName:m,fnArgs:c.args,repromptWithResult:c.args?.repromptWithResult??!1,fnResult:h,fnComplete:g,execErrorMsg:b,parseErrorMsg:void 0,saveInSpace:!0,metaspace:o,space:await this.getSuperSpace()})).newIbGib}else l=(await kn({api:this.data.api,model:this.data.model,agentId:this.data.uuid,fnRawRequest:r,fnName:m,fnArgs:c.args,repromptWithResult:c.args?.repromptWithResult??!1,fnResult:void 0,fnComplete:void 0,execErrorMsg:void 0,parseErrorMsg:d,saveInSpace:!0,metaspace:o,space:await this.getSuperSpace()})).newIbGib;if(!l)throw new Error("(UNEXPECTED) functionInfoIbGib falsy? we should have guaranteed to create one at this point. (E: 97c4ce12c7372adfeebfd45181b73f25)");i.push(l)}catch(l){throw console.error(`${t} ${y(l)}`),l}finally{R&&console.log(`${t} complete.`)}if(i.length===0)throw new Error("(UNEXPECTED) functionInfoIbGibs.length === 0? We expect at least one to be created (E: a8f81c56377cdbdeb468af6b21879825)");return i}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{R&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_addFunctionCallRequestComment({functionInfoIbGibs:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_addFunctionCallRequestComment.name}]`;try{R&&console.log(`${t} starting... (I: 5000adac5e8c4a7158a720c38f56b325)`);let o=this._metaspace;if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: d7275731461d8d0526af3088553ae525)");let i=await this.getSuperSpace(),r=at({tagText:Jt,contentText:e.map(p=>S({ibGib:p})).join(`
|
|
1184
|
-
`),randomIdLength:4}),
|
|
1185
|
-
`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{R&&console.log(`${t} complete.`)}}repromptCount=0;repromptMax=12;async rePrompt(){let e=`${this.lc}[${this.rePrompt.name}]`;try{R&&console.log(`${e} starting... (I: b6af34214acf07f9ca8c1d03c0011525)`),this.repromptCount<this.repromptMax?(this.repromptCount++,await this.doPrompt()):(console.log(`${e} already reached repromptMax (${this.repromptMax}). reprompt aborting. $(I: dacefb501dab2a1ee173ce8558657725)`),this.repromptCount=0)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async witness(e){if(e.ib===Ut&&e.gib===Ft)return this.getComments_Chat().length>0&&await this.doPrompt(),It;throw new Error(`arg (${M(e)}) not implemented. only expect ${It} right now to trigger doPrompt. (E: 24da0ad7333b6bbb359d1be425db3c25)`)}};var k=V,Ve=class n extends Un{static{f(this,"AgentWitnessGemini_V1")}lc=`[${n.name}]`;async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{k&&console.log(`${e} starting... (I: 641e211473fc54d5a9ebb4ea44944d25)`);let t=await super.validateThis();return this.data&&console.warn(`${e} do more validation on this concrete class. (W: fb778a84ccca2ebcefd2ca7845543825)`),t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{k&&console.log(`${e} complete.`)}}parseAddlMetadataString({ib:e}){let t=`${this.lc}[${this.parseAddlMetadataString.name}]`;try{throw k&&console.log(`${t} starting... (I: 080daf4b73f8bb52c70bf0a8f329be25)`),new Error("not implemented...i've just converted agent witness to a full witness with context and this was the only abstract method required. wasn't being used previously? so i'm not sure why this is here. (E: 129e816d3698f3867ec54c34fcc9a225)")}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{k&&console.log(`${t} complete.`)}}async addTexts(e){let t=`${this.lc}[${this.addTexts.name}]`;try{let o=xe();await o.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1});let i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: fd92a81901a83e2698ab2c3d4e702f25)");if(e.infos.length===0)return console.warn(`${t} opts.infos.length === 0. So we've called addTexts but with an empty array? returning early. (W: 0d42cd3b26aec45874d0e65450b37d25)`),[];let r=[],l=[],c=[],d=await this.getSuperSpace();for(let m of e.infos){let{textSrc:h,isSystem:g}=m,{text:b,commentIbGib:E}=m;if(b&&E)throw new Error("(UNEXPECTED) both text and commentIbGib provided? (E: a3fd590db1a5efc301f3c7e66b322f25)");if(!b&&!E)throw new Error("(UNEXPECTED) both text and commentIbGib falsy? one or the other is required (E: e08c7c694a17319085adfb75914b2725)");let I=yt({textSrc:h});if(E)k&&console.log(`${t} adding existing commentIbGib (I: 72a3f7aafde92f65b168d27605f94625)`);else{if(k&&console.log(`${t} creating new commentIbGib for text (I: 72a3f7aafde92f65b168d27605f94625)`),!b)throw new Error("(UNEXPECTED) text falsy still? at this point it should be guaranteed (E: b2deec458f35f22298ccb664d0685125)");E=(await Xe({text:b,addlMetadataText:I,saveInSpace:!0,space:d})).newIbGib,await i.registerNewIbGib({ibGib:E,space:d})}if(!E)throw new Error("(UNEXPECTED) commentIbGib still falsy? we should have just created one if it didn't exist (E: 9370b19aa207234db185cd74b57be525)");let v=await Vn({ibGib:E});if(v.length>0)throw new Error(`validation errors with trying to add a commentIbGib. errors: ${v} (E: beee1893050f9bcf9842c66831595225)`);r.push(E),g?l.push(E):c.push(E)}let u=[];l.length>0&&u.push({rel8nName:"system",ibGibs:l}),c.length>0&&u.push({rel8nName:"chat",ibGibs:c});let p=await Tr({timeline:this.toIbGibDto(),rel8nInfos:u,timelineIndexInfo:{rel8nName:Qe,type:this.data.type},metaspace:i,space:d});return await this.loadIbGibDto(p),await o.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!0}),r}catch(o){throw console.error(`${t} ${y(o)}`),o}}async composePromptInfo(){let e=`${this.lc}[${this.composePromptInfo.name}]`;try{if(k&&console.log(`${e} starting... (I: 155774d4811b038034342d5750174325)`),!this._metaspace)throw new Error("this.metaspace falsy (E: 7232a3a1b4348d460ed1375b32677125)");let t=[];for(let p of this.commentIbGibs_system){let m=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:p});t.push(...m)}let o=this.data?.["@currentContextTjpAddr"]??q;if(o!==q&&t.push({src:X.HARDCODED,content:{role:$t(X.HARDCODED),parts:[{text:ll({currentContextTjpAddr:o})}]}}),this.commentIbGibs_chat.length===0)throw new Error("(UNEXPECTED) this.commentIbGibs_chat.length === 0? why are we composing prompt info? We are assumed at this point to have added at least one comment ibgib to this agent. (E: a4e3d840946ab8e6dc3fde3e25d6b225)");let i=[],r=this.commentIbGibs_chat.length>1?this.commentIbGibs_chat.slice(0,-1):[];for(let p of r){let m=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:p});i.push(...m)}let l,c=this.commentIbGibs_chat.at(-1),d=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:c});if(d.length===1)l=d.at(0);else if(d.length===2)i.push(d.at(0)),l=d.at(1);else throw new Error("(UNEXPECTED) chatPromptCurrent_rawarray.length !== 1 or 2? We expect at this point either a regular text part or a FCR comment which creates two entries. (E: cd59f978479c20e496da4b0eb86c7d25)");let u={api:"gemini",systemPromptEntries:t,chatPromptHistoryParts:i,chatPromptCurrent:l};return k&&console.log(`${e} resPromptInfo:`,M(u),"(I: 8f17a8c45b9a91e20a5c5064d9114a25)"),u}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{k&&console.log(`${e} complete.`)}}async callTextAPI(e){let t=`${this.lc}[${this.callTextAPI.name}]`;try{if(k&&console.log(`${t} starting... (I: 27885f5b14682646542e9658417b2f25)`),!rl(e))throw new Error("(UNEXPECTED) info.api !== gemini? we are in the gemini concrete class where this is assumed. (E: 9223647ec96fb3f4eaee32c3fc15d925)");if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 09224b6688fdac884ce88f196b68a425)");let{api:o,model:i}=this.data;if(o!=="gemini")throw new Error(`api not supported: ${o} (E: 7e5c7c17988a666a86e72299630c7f25)`);k&&console.log(`${t} calling gemini api with model: ${i} (I: 6208942a419e9041bb037384135a0c25)`);let r=await this.fnGetAPIKey();if(!r)return console.error(`${t} apiKey falsy. did you set this.fnGetAPIKey (E: d964596b1538c0327209a92e97a54d25)`),{text:"no api key entered so no LLM chat happening. enter a gemini api key and donate/invest!"};this._genAI??=new Nt({apiKey:r});let l=Array.from(this.availableFunctions.values()).map(w=>({name:w.nameOrId,description:w.schema?.description,parameters:w.schema?.parameters}));l.some(w=>w.parameters==="undefined")&&console.error(`${t} (UNEXPECTED) function schema parameters not defined for all APIFunctionInfo values. (E: ae7227cdd65c0ab4513c7b282a1e4825)`),k&&(console.log(`${t} Gemini functionDeclarations:`),console.dir(l));let{systemPromptEntries:c,chatPromptHistoryParts:d,chatPromptCurrent:u}=e,p=te(u);k&&console.log(`chatPromptCurrent_final (before decompression): ${M(p)} (I: bbd4c7b9f3225afe9da1761918d0ac25)`),k&&console.warn(`${t} skipping decompression for the moment. if we add decompression text when the last comment is a function response part, then we'll error out. Need to rethink compression/decompression with the new function call/response workflow. (W: 7478439f9bbbde30a1eab3c5189ea625)`);let m,h=f(async w=>{if(!this._genAI)throw new Error("(UNEXPECTED) this._genAI falsy? (E: 503a0d9e3f729de7653ee3565b017b25)");let T=d.map(H=>H.content),C={model:w,history:T,config:{systemInstruction:Si({systemPromptEntries:c}),tools:[{functionDeclarations:l}],toolConfig:{functionCallingConfig:{mode:e.overrideFunctionCallingMode??nn.ANY}}}},A=this._genAI.chats.create(C),G={message:u.content.parts};return await A.sendMessage(G)},"fnGoModel"),g=0,b=i;do{g++;try{m=await h(b);break}catch(w){let T=w.message,C=w.status??"[STATUS?]";T.includes(`${503}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${lt}) for this next call. error (${w.status}): ${y(w)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=lt):T.includes(`${429}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${lt}) for this next call. error (${w.status}): ${y(w)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=lt):console.error(`${t}[fnGoModel][${b}] error trying to get result from model. error (${w.status}): ${y(w)} (E: a67d595c8ed313d458369d4d0b3e7f25)`)}await W(2e3)}while(!m&&g<go);if(!m)throw new Error("couldn't get result from model (E: ede013a53f875d99a96a2e257c7e7125)");let E=m,I=[],v=E.candidates?.[0]?.content?.parts||[];for(let w of v)w.functionCall&&I.push(w.functionCall);if(!I||I.length===0){if(k&&console.warn(`${t} no function calls in response, returning text. (W: 3a4b8c940983b9e28e3f04c01a09bb25)`),!E.text)throw new Error("response generated no function calls and no response.text (E: 6123b8cacfb834105ad3160cfc4ef825)");return{text:E.text}}return k&&(console.log(`${t} Gemini function calls:`),console.dir(I)),{functionCalls:I.map(w=>JSON.stringify(w,null,2))}}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{k&&console.log(`${t} complete.`)}}async createPromptInfoEntriesFromGeminiComment({commentIbGib:e}){let t=`[${this.createPromptInfoEntriesFromGeminiComment.name}]`;try{k&&console.log(`${t} starting... (I: 826a9d6b120d96532afbe1f7a22e8d25)`);let o=await Vn({ibGib:e});if(o.length>0)throw new Error(`validation errors with commentIbGib. Cannot create a prompt info entry. errors: ${o} (E: beee1893050f9bcf9842c66831595225)`);let{safeIbCommentMetadataText:i}=Ke({ib:e.ib});if(!i)throw new Error("(UNEXPECTED) addlMetaDataText falsy? we just validated the comment ibgib, so there should be the expected shape of the comment.ib. (E: facf5801f9ba158b1526dd09d0e1b325)");let{textSrc:r,timestampInTicks:l,errorMsg:c,other:d}=Gt({addlMetadataText:i,ifError:"warn"});if(c)throw new Error("(UNEXPECTED) errorMsg is truthy after parse addl metadata from comment.ib? we just validated the comment ibgib, so there should be the expected shape of the comment.ib. (? (E: 7fd7fac50851916f39ceccbe93446425)");if(!e.data)throw new Error("(UNEXPECTED) commentIbGib.data falsy? (E: 8ce54d28219237feddf8f25b5846cc25)");if(!e.data.text)throw new Error("(UNEXPECTED) commentIbGib.data.text falsy? (E: 8556fc95c401d1b5441454fceb8f2f25)");if(Ai({ibGib:e})){let p=await this.getFunctionInfoIbGibs({fcrCommentIbGib:e}),m=[],h=[];for(let E of p){let{call:I,response:v}=xi({functionInfoIbGib:E});if(!I)throw new Error("(UNEXPECTED) call falsy? (E: 5c8f3bd6de3b300e1c105b9603bb7b25)");if(!v)throw new Error("(UNEXPECTED) response falsy? (E: d0388c838975c93126c1a6d64f781d25)");if(I.functionCall.name!==v.functionResponse.name)throw new Error("(UNEXPECTED) functionCall.name !== functionResponse.name? (E: e49f0d60093354db2b6ad17fdf86d425)");m.push(I),h.push(v)}let g={src:X.AI,content:{role:$t("ai"),parts:m}},b={src:X.FUNCTION,content:{role:$t(X.FUNCTION),parts:h}};return[g,b]}else return[{src:r,content:{role:$t(r),parts:[{text:e.data.text}]}}]}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{k&&console.log(`${t} complete.`)}}async promptOneOff(e){let t=`${this.lc}[${this.promptOneOff.name}]`;try{k&&console.log(`${t} starting... (I: genuuid)`);let{text:o,systemInstructions:i}=e;if(!o)throw new Error("(UNEXPECTED) opts.text falsy? (E: genuuid)");if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: genuuid)");let{api:r,model:l}=this.data;if(r!=="gemini")throw new Error(`api not supported: ${r} (E: genuuid)`);k&&console.log(`${t} calling gemini api with model: ${l} (I: genuuid)`);let c=await this.fnGetAPIKey();if(!c){console.error(`${t} apiKey falsy. did you set this.fnGetAPIKey (E: genuuid)`);return}this._genAI??=new Nt({apiKey:c});let d=f(async b=>{if(!this._genAI)throw new Error("(UNEXPECTED) this._genAI falsy? (E: fbe235713d48f0d8e87cd0b88ec54825)");let E={model:b,config:{systemInstruction:i}},v=await this._genAI.chats.create(E).sendMessage({message:o});if(v.text)return v.text;throw new Error("response.text empty/falsy, potentially blocked by safety settings (E: a21a78c9471f27a42c07d1c859187825)")},"fnGoModel"),u,p=0,m=[];e.modelOverrides&&e.modelOverrides.length>0?m.push(...e.modelOverrides):m.push(l),e.modelBackupOverrides&&e.modelBackupOverrides.length>0?m.push(...e.modelBackupOverrides):m.push(lt);let h=0,g=1;do{p++,g++;let b=m[h];try{u=await d(b);break}catch(E){if(E instanceof Error){let I=E.message,v=E.status??"[STATUS?]";if(I.includes(`${503}`))if(h===m.length-1)console.error(`${t}[fnGoModel][${b}] error trying to get result from model: GEMINI_ERROR_STATUS_MODEL_OVERLOADED ${503}. we are already using the final backup model in our modelsToTry, so SOL here. will try again... error (${v}): ${y(E)} (E: 9bb63cb520b8bd3bb85d2ca20715c825)`);else{h++;let w=m[h];console.error(`${t}[fnGoModel][${b}] error trying to get result from model: GEMINI_ERROR_STATUS_MODEL_OVERLOADED ${503}. will try using the next model (${w}) for this next call. error (${v}): ${y(E)} (E: b07a041bb97ea95b03cd6f9856f01525)`)}else if(I.includes(`${429}`))if(h===m.length-1)console.error(`${t}[fnGoModel][${b}] error trying to get result from model: GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED ${429}. we are already using the final backup model, so SOL here. will try again... error (${v}): ${y(E)} (E: d280c441aa37579bb2cfd29038202525)`);else{h++;let w=m[h];console.error(`${t}[fnGoModel][${b}] error trying to get result from model: GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED ${429}. will try using the next model (${w}) for this next call. error (${v}): ${y(E)} (E: a9869883fc72bf156f1691183e27ee25)`)}else console.error(`${t}[fnGoModel][${b}] error trying to get result from model. error (${v}): ${y(E)} (E: a67d595c8ed313d458369d4d0b3e7f25)`)}else console.error(`${t}[fnGoModel][${b}] (UNEXPECTED) error is not instanceof Error? The expected error from the @google/genai lib is supposed to be an instance of Error according to Gemini migration AI. (E: 15df95701e78b35f783d250801092825)`)}p>1&&await W(g*1e3)}while(!u&&p<go);return u}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{k&&console.log(`${t} complete.`)}}async getFunctionInfoIbGibs({fcrCommentIbGib:e}){let t=`[${this.getFunctionInfoIbGibs.name}]`;try{k&&console.log(`${t} starting... (I: 976a684b7ae58cda523b17fc0c62e325)`);let o=[];if(!e)throw new Error(`${t} fcrCommentIbGib is falsy. (E: a01c80f415ab8737a81b7b2a2f479f25)`);if(!e.data)throw new Error(`${t} fcrCommentIbGib.data is falsy. (E: a03bc3662a8d6f69c1c077605727a025)`);let i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) this.metaspace falsy. (E: 997d071847c5d7e80692f48191244e25)");let r=await this.getSuperSpace();if(!r)throw new Error("(UNEXPECTED) superSpace falsy? (E: dd1600f15e1e659c01f73991656a3325)");let l=e.rel8ns?.[Ln]??[];if(l.length===0)return k&&console.warn(`${t} no functionInfoAddrs (I: 5f8965e92c305689c11677a1148b7425)`),[];k&&console.log(`${t} functionInfoAddrs: ${l} (I: e7b1f5a4576c493326b913e48a505e25)`);let c=await i.get({addrs:l,space:r});if(!c.success||!c.ibGibs||c.ibGibs.length!==l.length)throw new Error(`${t} could not retrieve function info ibgibs. errorMsg: ${c.errorMsg??"unknown error (E: 164246a6661d49f2b21d1b6769139625)"} (E: 0736d824876e420f91c089925191d425)`);return o=c.ibGibs,k&&console.log(`${t} resFunctionInfoIbGibs: ${M(o.map(d=>S({ibGib:d})))} (I: a5661b5c449608f0e8d773135a599a25)`),o}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{k&&console.log(`${t} complete.`)}}async loadIbGibDto(e){let t=`[${this.loadIbGibDto.name}]`;try{if(k&&console.log(`${t} starting... (I: cb0b1e9e22fce321ca9a26e7a5d4c825)`),await super.loadIbGibDto(e),!this.data)throw new Error("(UNEXPECTED) this.data falsy after load dto? (E: 77aecd066b0bbbd0c66e2658519bdb25)");let o=this._metaspace;if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: e5762b1e3f77f84ca338641edc011225)");let i=await this.getSuperSpace(),r=f(async()=>{this.availableFunctions=new Map;for(let d of this.data.availableFunctionNameOrIds){if(!d)throw new Error("(UNEXPECTED) nameOrId falsy, driven by this.data.availableFunctionNameOrIds? somehow a falsy nameOrId saved? (E: 7b63f177624de2415e1569e96ef8d125)");let u=tt().get(d);u?this.availableFunctions.set(d,u):Ci().includes(d)?k&&console.log(`${t} function nameOrId (${d}) found as deprecated. not adding to available functions on agent. (I: 983864ad5cd8af915fb135580e455425)`):console.error(`no function info in getAllFunctionInfos() found corresponding to nameOrId (${d}) and this was not found in getDeprecatedFunctionInfoNames(). this is logged here but we're not throwing. (E: db0da9880cf1e414c3f1078d3e9f0b25)`)}let l=this.rel8ns?.system??[];if(l.length>0){let d=await o.get({addrs:l,space:i});if(!d.success||d.errorMsg)throw new Error(`couldn't get system comments. error: ${y(d.errorMsg??"unknown error (E: c0b4d7aab724bcf58e88ffd496de8825)")} (E: 7925d4b5ec3a8f7a648c109941c38a25)`);if((d.ibGibs??[]).length!==l.length)throw new Error("(UNEXPECTED) (resGet_systemComments.ibGibs ?? []).length !== rel8dAddrs_system.length, but resGet.success truthy and resGet.errorMsg falsy? (E: 2055553b602e6c2fe49e956a1e423f25)");this.commentIbGibs_system=d.ibGibs}let c=this.rel8ns?.chat??[];if(c.length>0){let d=await o.get({addrs:c,space:i});if(!d.success||d.errorMsg)throw new Error(`couldn't get chat comments. error: ${y(d.errorMsg??"unknown error (E: c0b4d7aab724bcf58e88ffd496de8825)")} (E: 7925d4b5ec3a8f7a648c109941c38a25)`);if((d.ibGibs??[]).length!==c.length)throw new Error("(UNEXPECTED) (resGet_chatComments.ibGibs ?? []).length !== rel8dAddrs_chat.length, but resGet.success truthy and resGet.errorMsg falsy? (E: 2055553b602e6c2fe49e956a1e423f25)");this.commentIbGibs_chat=d.ibGibs}},"fn");await Ht({scope:"prune",secondsValid:60,maxDelayMs:100,maxLockAttempts:1800,space:i,callerInstanceId:ze(),fn:r})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{k&&console.log(`${t} complete.`)}}};setTimeout(()=>{xe().registerFactory({classname:Ve.name,fnDtoToAgentWitness:f(async e=>e.data?e.data.classname?e.data.classname===Ve.name?{applies:!0,agent:await Ni({agentIbGib:e})}:{applies:!1}:{applies:!1}:{applies:!1},"fnDtoToAgentWitness")})});function ll({currentContextTjpAddr:n}){let e=`[${ll.name}]`;try{k&&console.log(`${e} starting... (I: 7edafbba277d57eae51af325cf7eb225)`);let t=K({ibGibAddr:n});return`Your current context ibGibAddr is ${n}
|
|
1186
|
-
It is very important that you use THIS context address. THIS context address takes precedence over previous contexts in your system chat history, because those chats may be from previous sessions per the user's POV. If there are any doubts, like if you're saying something and the user is not responding, then this may be the reason. You should call the function to get your context to be sure you are talking in the right one.`}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{
|
|
1187
|
-
`)}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{Z&&console.log(`${o} complete.`)}}f(at,"taggifyForPrompt");function yt({textSrc:n,other:e}){let t=`[${yt.name}]`;return e?[n,ze(),e].join("_"):[n,ze()].join("_")}f(yt,"getAddlMetadataTextForAgentText");function Gt({addlMetadataText:n,ifError:e="warn"}){let t=`[${yt.name}]`;try{Z&&console.log(`${t} starting... (I: 89b8b19a8d785b945fe0f816df762d25)`);let[o,i,...r]=n.split("_");if(!o)throw new Error("addlMetadataText.textSrc falsy (E: 40bbec4269c1688ab1390fa5d5440325)");if(!Wr(o))throw new Error(`addlMetadataText.textSrc (${o}) is unexpected value. Expected one of ${ao} (E: 02bae41275a39210e5737548747bd825)`);if(!i)throw new Error("addlMetadataText.timestampInTicks falsy (E: 03cbbc7515a1cff1fc7c12e3947c6825)");let l=Number.parseInt(i);if(Number.isNaN(l))throw new Error(`invalid timestampInTicks (${i}): value should be an integer but parse is NaN (E: 9d31e3563d972c02553ce18a19a19b25)`);return{textSrc:o,timestampInTicks:l,other:r.length>0?r:void 0}}catch(o){let i=`${t} ${y(o)}`;switch(e){case"ignore":return{textSrc:X.UNKNOWN,timestampInTicks:0,errorMsg:y(o)};case"warn":return console.warn(`${t} ${i} (W: 3e1f4a98ad6461c9bd96462841c31b25)`),{textSrc:X.UNKNOWN,timestampInTicks:0,errorMsg:y(o)};default:throw console.error(`${t} ${i} (E: 6396ed44947c52adf85788e1adc22825)`),new Error(i)}}finally{Z&&console.log(`${t} complete.`)}}f(Gt,"parseAddlMetadataTextForAgentText");function mo({data:n}){let e=`[${mo.name}]`,{name:t,uuid:o,type:i}=n;if(!t)throw new Error(`${e} data.name falsy (E: 4c172c5b8a110ae26479b8c4006f3225)`);if(!o)throw new Error(`${e} data.uuid falsy (E: 67d2c79ac39e70e5ecfd1745e1fd3525)`);if(!i)throw new Error(`${e} data.type falsy (E: 53bf1f9a145a16be81296437682a7a25)`);if([t,o,i].some(l=>l.includes(" ")))throw new Error("invalid data. ib must not contain spaces in name, uuid, type. (E: 36a56e4685163848458be06f51d4ad25)");return[rt,t,o,i].join(" ")}f(mo,"getAgentIb");function Yr({ib:n}){let[e,t,o,i]=n.split(" ");if(e!==rt)throw new Error(`invalid ib. first term expected to e an atom: ${rt} (E: 3c01d42035d2e32c4bfd5c1bf363f725)`);if(!t)throw new Error("invalid ib. name falsy in agent ib (E: 8b494c544f05b8ef9c866078b761a725)");if(!o)throw new Error("invalid ib. uuid falsy in agent ib (E: aba195db3ddcb000324ebed15351b725)");if(!i)throw new Error("invalid ib. type falsy in agent ib (E: 8c814772394ae76342f95e885570c325)");return{atom:e,name:t,uuid:o,type:i}}f(Yr,"parseAgentIb");async function Vn({ibGib:n}){let e=`[${Vn.name}]`;try{Z&&console.log(`${e} starting... (I: f9a733a5a05b7f7494836d86a79e2d25)`);let t=await ot({ibGib:n})??[];if(!Ye({ibGib:n}))return t.push(`${e} not a comment ibgib (E: 08676d94c698c6e42e6c35e94a58f125)`),t;let{safeIbCommentMetadataText:o}=Ke({ib:n.ib});if(o){let i=Gt({addlMetadataText:o,ifError:"warn"});i.errorMsg&&t.push(`${e} could not parse addlMetadataText: ${i.errorMsg} (E: e178265c33e5e94947a02c1f9d6a7425)`)}else t.push(`${e} addlMetadataText falsy. this implies something is incorrect with the comment's ib, as we expect agent comments to have certain metadata (e.g. textSrc). See AgentWitness_V1 (and data interface) for more info. (E: 7c3c41c973a67256c432604666106b25)`);return t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Z&&console.log(`${e} complete.`)}}f(Vn,"validateAgentWitnessCommentIbGib");var qn="settings",xh="general",Ph="text-editor",Nh="projects",$h="projects-explorer",Rh="projects-dropdown",Gh="project",Mh="minigame",Dh="chronologys",Lh="identity-manager",ee={general:xh,textEditor:Ph,projects:Nh,projectsExplorer:$h,projectsDropdown:Rh,project:Gh,minigame:Mh,chronologys:Dh,identityManager:Lh},kh=Object.values(ee);var Ri={type:ee.general,editor:void 0,readonly:!0,viewer:"ibgib-raw-viewer"},Gi={type:ee.textEditor,wrap:"wrap"},Uh={type:ee.project,openChildTjpAddrs:[],activeChildTjpAddr:void 0,lensMode:"raw"},Fh={type:ee.minigame},Hh={type:ee.chronologys,openChildTjpAddrs:[],activeChildTjpAddr:void 0},Vh={type:ee.identityManager,openChildTjpAddrs:[],activeChildTjpAddr:void 0},cl={sections:{},children:{}};var qe=V;async function Mi({ibGib:n}){let e=`[${Mi.name}]`;try{qe&&console.log(`${e} starting... (I: 57ac4c0a3448bc5e98ecf5bfb02ce825)`);let{ib:t}=F({ibGib:n}),o=t.split(" ").at(0);if(!o)throw new Error("(UNEXPECTED) atom falsy? we split the ib by spaces (space-delimiter). this makes no sense. (E: 6a9ea640ae38823aeefc6ec82a05d625)");return`${qn}_${o}`}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{qe&&console.log(`${e} complete.`)}}f(Mi,"getSettingsScope");async function pe({settingsType:n,useCase:e}){let t=`[${pe.name}]`;try{if(qe&&console.log(`${t} starting... (I: f13dff111048421cad5453f821487825)`),e.includes("_"))throw new Error("(UNEXPECTED) settingsType.includes('_')? should be kebab-cased or camelCased (E: 8f75e89b9378819ab882cc1870f1e825)");if(n.includes("_"))throw new Error("(UNEXPECTED) settingsType.includes('_')? should be kebab-cased or camelCased (E: 1d316b0808287c12689d1e882648b825)");return[n,e].join("_")}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{qe&&console.log(`${t} complete.`)}}f(pe,"getSectionName");async function On({sectionName:n,settingsIbGib:e}){let t=`[${On.name}]`;try{if(qe&&console.log(`${t} starting... (I: 266554b13f6ce6daa85c882f04805825)`),!e.data)throw new Error("(UNEXPECTED) settingsIbGib.data falsy? (E: dd3708f0515fb0b4d4024f4d336a3625)");if(!e.data.sections)throw new Error("(UNEXPECTED) settingsIbGib.data.sections falsy? what was the settingsIbGib even created for? (E: 31f85898a1c854e13440e278a79ceb25)");return(e.data.sections??{})[n]}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{qe&&console.log(`${t} complete.`)}}f(On,"getSettingsSection");function dl({scope:n}){let e=`[${dl.name}]`;try{return n.includes(" ")&&(console.warn(`${e} scope includes one or more spaces. These will be converted to double underscores. (W: 75a53c623d3110b5e874e5789b414325)`),n=n.replace(/ /g,"__")),`${qn} ${n}`}catch(t){throw console.error(`${e} ${y(t)}`),t}}f(dl,"getSettingsIb");async function Di({scope:n,metaspace:e,space:t,saveInSpace:o}){let i=`[${Di.name}]`;try{let r=dl({scope:n}),l=await ul(),d=await ne.firstGen({parentIbGib:ne.primitive({ib:qn}),ib:r,data:l,rel8ns:void 0,dna:!0,nCounter:!0,tjp:{timestamp:!0,uuid:!0}});if(o){if(!e)throw new Error("metaspace falsy but saveInSpace is true (E: f91adfe38d78e6e4f8bca278fce37925)");await e.persistTransformResult({resTransform:d,space:t}),await e.registerNewIbGib({ibGib:d.newIbGib,space:t})}return d}catch(r){throw console.error(`${i} ${y(r)}`),r}}f(Di,"createSettings");async function ul(){let n=`[${ul.name}]`;try{qe&&console.log(`${n} starting... (I: 3d7cc3f242cc88ad28dafaf85d646a25)`);let e=te(cl),t=await pe({settingsType:"general",useCase:"default"}),o=await pe({settingsType:"general",useCase:"current"});e.sections[t]=te(Ri),e.sections[o]=te(Ri);let i=await pe({settingsType:"text-editor",useCase:"default"}),r=await pe({settingsType:"text-editor",useCase:"current"});return e.sections[i]=te(Gi),e.sections[r]=te(Gi),e}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{qe&&console.log(`${n} complete.`)}}f(ul,"getDefaultSettingsData");var P=V,ge=class n{static{f(this,"IbGibDynamicComponentMetaBase")}lc=`[${n.name}]`;componentName="";routeRegExp=void 0;fnHandleRoute=void 0;fnGetMetaspace;bootstrapPromise;constructor({fnGetMetaspace:e,bootstrapPromise:t}){this.fnGetMetaspace=e,this.bootstrapPromise=t}},Oe=class n extends HTMLElement{static{f(this,"IbGibDynamicComponentInstanceBase")}lc=`[${n.name}]`;elements;createdPromise;settings;get agent(){return this.agents.at(0)}agents=[];get ib(){let{ib:e}=F({ibGibAddr:this.ibGibAddr??q});return e}get gib(){let{gib:e}=F({ibGibAddr:this.ibGibAddr??q});return e}ibGibAddr=q;ibGibProxy;get ibGib(){let e=this.ibGibAddr??q,{ib:t,gib:o}=F({ibGibAddr:e});return this.ibGibAddr&&!vt({gib:o})?this.ibGibProxy?.ibGib:ne.primitive({ib:t})}get tjpAddr(){return this.ibGib?re({ibGib:this.ibGib,defaultIfNone:"incomingAddr"}):void 0}meta;html;css;static get observedAttributes(){return["ibGibAddr"]}_instanceId;get instanceId(){return this._instanceId}agentsInitialized;connectedCount=0;_isBusy=!1;get isBusy(){return this._isBusy}showBusy({isBusy:e,title:t,msg:o,localOnly:i,animationEmoji:r}){let l=`${this.lc}[${this.showBusy.name}]`;try{this._isBusy=e,i?this.dispatchEvent(new CustomEvent(wt,{detail:{isBusy:e,title:t,msg:o,animationEmoji:r},bubbles:!0,composed:!0})):window.dispatchEvent(new CustomEvent(wt,{detail:{isBusy:e,title:t,msg:o,animationEmoji:r}}))}catch(c){throw console.error(`${l} ${y(c)}`),c}}async getMetaspace(){let e=`${this.lc}[${this.getMetaspace.name}]`;try{if(P&&console.log(`${e} starting... (I: 956418cf932823bc767ccc6a0fd2b325)`),!this.meta)throw new Error("(UNEXPECTED) this.meta falsy? (E: dd2bfae6c0e84b1d58c72e2922b51325)");return await this.meta.fnGetMetaspace()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}constructor(){super(),this._instanceId=nt({count:8})}async initialize(e){let{ibGibAddr:t,meta:o,html:i,css:r}=e,l=`${this.lc}[${this.initialize.name}]`;try{P&&console.log(`${l} starting... (I: c9b94131bc2f0d20e1397c214dad6725)`),this.ibGibAddr=t,this.meta=o,this.html=i,this.css=r,this.attachShadow({mode:"open"}),await this.meta.bootstrapPromise}catch(c){throw console.error(`${l} ${y(c)}`),c}finally{P&&console.log(`${l} complete.`)}}async initAgents(){let e=`${this.lc}[${this.initAgents.name}]`;P&&console.log(`${e} does nothing in base class (I: 0b31a650b942619a0e36a1a7f763e825)`)}async connectedCallback(){let e=`${this.lc}[${this.connectedCallback.name}]`;try{P&&console.log(`${e} starting... (I: 01bbbf69f1c75b03a29e7a85ebd2c725)`),this.connectedCount++,this.connectedCount===1?await this.connectedCallback_initComponent():await this.connectedCallback_reconnectComponent()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async connectedCallback_initComponent(){let e=`${this.lc}[${this.connectedCallback_initComponent.name}]`;try{if(P&&console.log(`${e} starting... (I: bc4af3f6751d841f51bad19e334efa25)`),!this.html)throw new Error("(UNEXPECTED) this.html is falsy? (E: a0a0ab7c8f987d78058dd7cad09a5125)");let t=document.createElement("template");if(t.innerHTML=this.css?`
|
|
1178
|
+
${a}
|
|
1179
|
+
${m}`)}return a},"path"),"createPathTagFunction"),Xt=Om(el);var xn=class extends An{static{f(this,"BaseInteractions")}create(e,t){var o;let{api_version:i=this._client.apiVersion}=e,r=gn(e,["api_version"]);if("model"in r&&"agent_config"in r)throw new de("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in r&&"generation_config"in r)throw new de("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(Xt`/${i}/interactions`,Object.assign(Object.assign({body:r},t),{stream:(o=e.stream)!==null&&o!==void 0?o:!1}))}delete(e,t={},o){let{api_version:i=this._client.apiVersion}=t??{};return this._client.delete(Xt`/${i}/interactions/${e}`,o)}cancel(e,t={},o){let{api_version:i=this._client.apiVersion}=t??{};return this._client.post(Xt`/${i}/interactions/${e}/cancel`,o)}get(e,t={},o){var i;let r=t??{},{api_version:a=this._client.apiVersion}=r,c=gn(r,["api_version"]);return this._client.get(Xt`/${a}/interactions/${e}`,Object.assign(Object.assign({query:c},o),{stream:(i=t?.stream)!==null&&i!==void 0?i:!1}))}};xn._key=Object.freeze(["interactions"]);var Pn=class extends xn{static{f(this,"Interactions")}};function zm(n){let e=0;for(let i of n)e+=i.length;let t=new Uint8Array(e),o=0;for(let i of n)t.set(i,o),o+=i.length;return t}f(zm,"concatBytes");var Yt;function Si(n){let e;return(Yt??(e=new globalThis.TextEncoder,Yt=e.encode.bind(e)))(n)}f(Si,"encodeUTF8");var Qt;function ya(n){let e;return(Qt??(e=new globalThis.TextDecoder,Qt=e.decode.bind(e)))(n)}f(ya,"decodeUTF8");var ht=class{static{f(this,"LineDecoder")}constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Si(e):e;this.buffer=zm([this.buffer,t]);let o=[],i;for(;(i=Jm(this.buffer,this.carriageReturnIndex))!=null;){if(i.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=i.index;continue}if(this.carriageReturnIndex!=null&&(i.index!==this.carriageReturnIndex+1||i.carriage)){o.push(ya(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null;continue}let r=this.carriageReturnIndex!==null?i.preceding-1:i.preceding,a=ya(this.buffer.subarray(0,r));o.push(a),this.buffer=this.buffer.subarray(i.index),this.carriageReturnIndex=null}return o}flush(){return this.buffer.length?this.decode(`
|
|
1180
|
+
`):[]}};ht.NEWLINE_CHARS=new Set([`
|
|
1181
|
+
`,"\r"]);ht.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Jm(n,e){for(let i=e??0;i<n.length;i++){if(n[i]===10)return{preceding:i,index:i+1,carriage:!1};if(n[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}f(Jm,"findNewlineIndex");function Wm(n){for(let o=0;o<n.length-1;o++){if(n[o]===10&&n[o+1]===10||n[o]===13&&n[o+1]===13)return o+2;if(n[o]===13&&n[o+1]===10&&o+3<n.length&&n[o+2]===13&&n[o+3]===10)return o+4}return-1}f(Wm,"findDoubleNewlineIndex");var Nn={off:0,error:200,warn:300,info:400,debug:500},Ea=f((n,e,t)=>{if(n){if(Sm(Nn,n))return n;ae(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Nn))}`)}},"parseLogLevel");function At(){}f(At,"noop");function Zt(n,e,t){return!e||Nn[n]>Nn[t]?At:e[n].bind(e)}f(Zt,"makeLogFn");var Km={error:At,warn:At,info:At,debug:At},Ia=new WeakMap;function ae(n){var e;let t=n.logger,o=(e=n.logLevel)!==null&&e!==void 0?e:"off";if(!t)return Km;let i=Ia.get(t);if(i&&i[0]===o)return i[1];let r={error:Zt("error",t,o),warn:Zt("warn",t,o),info:Zt("info",t,o),debug:Zt("debug",t,o)};return Ia.set(t,[o,r]),r}f(ae,"loggerFor");var Ze=f(n=>(n.options&&(n.options=Object.assign({},n.options),delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-goog-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n),"formatRequestDetails");var ui=class n{static{f(this,"Stream")}constructor(e,t,o){this.iterator=e,this.controller=t,this.client=o}static fromSSEResponse(e,t,o){let i=!1,r=o?ae(o):console;function a(){return ve(this,arguments,f(function*(){var d,u,p,m;if(i)throw new de("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let h=!1;try{try{for(var g=!0,b=we(Xm(e,t)),E;E=yield $(b.next()),d=E.done,!d;g=!0){m=E.value,g=!1;let I=m;if(!h)if(I.data.startsWith("[DONE]")){h=!0;continue}else try{yield yield $(JSON.parse(I.data))}catch(v){throw r.error("Could not parse message into JSON:",I.data),r.error("From chunk:",I.raw),v}}}catch(I){u={error:I}}finally{try{!g&&!d&&(p=b.return)&&(yield $(p.call(b)))}finally{if(u)throw u.error}}h=!0}catch(I){if(ai(I))return yield $(void 0);throw I}finally{h||t.abort()}},"iterator_1"))}return f(a,"iterator"),new n(a,t,o)}static fromReadableStream(e,t,o){let i=!1;function r(){return ve(this,arguments,f(function*(){var d,u,p,m;let h=new ht,g=Qa(e);try{for(var b=!0,E=we(g),I;I=yield $(E.next()),d=I.done,!d;b=!0){m=I.value,b=!1;let v=m;for(let w of h.decode(v))yield yield $(w)}}catch(v){u={error:v}}finally{try{!b&&!d&&(p=E.return)&&(yield $(p.call(E)))}finally{if(u)throw u.error}}for(let v of h.flush())yield yield $(v)},"iterLines_1"))}f(r,"iterLines");function a(){return ve(this,arguments,f(function*(){var d,u,p,m;if(i)throw new de("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let h=!1;try{try{for(var g=!0,b=we(r()),E;E=yield $(b.next()),d=E.done,!d;g=!0){m=E.value,g=!1;let I=m;h||I&&(yield yield $(JSON.parse(I)))}}catch(I){u={error:I}}finally{try{!g&&!d&&(p=b.return)&&(yield $(p.call(b)))}finally{if(u)throw u.error}}h=!0}catch(I){if(ai(I))return yield $(void 0);throw I}finally{h||t.abort()}},"iterator_2"))}return f(a,"iterator"),new n(a,t,o)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],o=this.iterator(),i=f(r=>({next:f(()=>{if(r.length===0){let a=o.next();e.push(a),t.push(a)}return r.shift()},"next")}),"teeIterator");return[new n(()=>i(e),this.controller,this.client),new n(()=>i(t),this.controller,this.client)]}toReadableStream(){let e=this,t;return Ya({async start(){t=e[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:r}=await t.next();if(r)return o.close();let a=Si(JSON.stringify(i)+`
|
|
1182
|
+
`);o.enqueue(a)}catch(i){o.error(i)}},async cancel(){var o;await((o=t.return)===null||o===void 0?void 0:o.call(t))}})}};function Xm(n,e){return ve(this,arguments,f(function*(){var o,i,r,a;if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new de("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new de("Attempted to iterate over a response with no body");let c=new fi,d=new ht,u=Qa(n.body);try{for(var p=!0,m=we(Ym(u)),h;h=yield $(m.next()),o=h.done,!o;p=!0){a=h.value,p=!1;let g=a;for(let b of d.decode(g)){let E=c.decode(b);E&&(yield yield $(E))}}}catch(g){i={error:g}}finally{try{!p&&!o&&(r=m.return)&&(yield $(r.call(m)))}finally{if(i)throw i.error}}for(let g of d.flush()){let b=c.decode(g);b&&(yield yield $(b))}},"_iterSSEMessages_1"))}f(Xm,"_iterSSEMessages");function Ym(n){return ve(this,arguments,f(function*(){var t,o,i,r;let a=new Uint8Array;try{for(var c=!0,d=we(n),u;u=yield $(d.next()),t=u.done,!t;c=!0){r=u.value,c=!1;let p=r;if(p==null)continue;let m=p instanceof ArrayBuffer?new Uint8Array(p):typeof p=="string"?Si(p):p,h=new Uint8Array(a.length+m.length);h.set(a),h.set(m,a.length),a=h;let g;for(;(g=Wm(a))!==-1;)yield yield $(a.slice(0,g)),a=a.slice(g)}}catch(p){o={error:p}}finally{try{!c&&!t&&(i=d.return)&&(yield $(i.call(d)))}finally{if(o)throw o.error}}a.length>0&&(yield yield $(a))},"iterSSEChunks_1"))}f(Ym,"iterSSEChunks");var fi=class{static{f(this,"SSEDecoder")}constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let r={event:this.event,data:this.data.join(`
|
|
1183
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],r}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,o,i]=Qm(e,":");return i.startsWith(" ")&&(i=i.substring(1)),t==="event"?this.event=i:t==="data"&&this.data.push(i),null}};function Qm(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}f(Qm,"partition");async function Zm(n,e){let{response:t,requestLogID:o,retryOfRequestLogID:i,startTime:r}=e,a=await(async()=>{var c;if(e.options.stream)return ae(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):ui.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let d=t.headers.get("content-type"),u=(c=d?.split(";")[0])===null||c===void 0?void 0:c.trim();return u?.includes("application/json")||u?.endsWith("+json")?await t.json():await t.text()})();return ae(n).debug(`[${o}] response parsed`,Ze({retryOfRequestLogID:i,url:t.url,status:t.status,body:a,durationMs:Date.now()-r})),a}f(Zm,"defaultParseResponse");var pi=class n extends Promise{static{f(this,"APIPromise")}constructor(e,t,o=Zm){super(i=>{i(null)}),this.responsePromise=t,this.parseResponse=o,this.client=e}_thenUnwrap(e){return new n(this.client,this.responsePromise,async(t,o)=>e(await this.parseResponse(t,o),o))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};var tl=Symbol("brand.privateNullableHeaders");function*jm(n){if(!n)return;if(tl in n){let{values:o,nulls:i}=n;yield*o.entries();for(let r of i)yield[r,null];return}let e=!1,t;n instanceof Headers?t=n.entries():ma(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let o of t){let i=o[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let r=ma(o[1])?o[1]:[o[1]],a=!1;for(let c of r)c!==void 0&&(e&&!a&&(a=!0,yield[i,null]),yield[i,c])}}f(jm,"iterateHeaders");var vo=f(n=>{let e=new Headers,t=new Set;for(let o of n){let i=new Set;for(let[r,a]of jm(o)){let c=r.toLowerCase();i.has(c)||(e.delete(r),i.add(c)),a===null?(e.delete(r),t.add(c)):(e.append(r,a),t.delete(c))}}return{[tl]:!0,values:e,nulls:t}},"buildHeaders");var wo=f(n=>{var e,t,o,i,r,a;if(typeof globalThis.process<"u")return(o=(t=(e=globalThis.process.env)===null||e===void 0?void 0:e[n])===null||t===void 0?void 0:t.trim())!==null&&o!==void 0?o:void 0;if(typeof globalThis.Deno<"u")return(a=(r=(i=globalThis.Deno.env)===null||i===void 0?void 0:i.get)===null||r===void 0?void 0:r.call(i,n))===null||a===void 0?void 0:a.trim()},"readEnv");var nl,$n=class n{static{f(this,"BaseGeminiNextGenAPIClient")}constructor(e){var t,o,i,r,a,c,d,u=e===void 0?{}:e,{baseURL:p=wo("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:m=(t=wo("GEMINI_API_KEY"))!==null&&t!==void 0?t:null,apiVersion:h="v1beta"}=u,g=gn(u,["baseURL","apiKey","apiVersion"]);let b=Object.assign(Object.assign({apiKey:m,apiVersion:h},g),{baseURL:p||"https://generativelanguage.googleapis.com"});this.baseURL=b.baseURL,this.timeout=(o=b.timeout)!==null&&o!==void 0?o:n.DEFAULT_TIMEOUT,this.logger=(i=b.logger)!==null&&i!==void 0?i:console;let E="warn";this.logLevel=E,this.logLevel=(a=(r=Ea(b.logLevel,"ClientOptions.logLevel",this))!==null&&r!==void 0?r:Ea(wo("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&a!==void 0?a:E,this.fetchOptions=b.fetchOptions,this.maxRetries=(c=b.maxRetries)!==null&&c!==void 0?c:2,this.fetch=(d=b.fetch)!==null&&d!==void 0?d:Mm(),this.encoder=Lm,this._options=b,this.apiKey=m,this.apiVersion=h}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-goog-api-key"))&&!t.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){if(this.apiKey!=null)return vo([{"x-goog-api-key":this.apiKey}])}stringifyQuery(e){return Object.entries(e).filter(([t,o])=>typeof o<"u").map(([t,o])=>{if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(o)}`;if(o===null)return`${encodeURIComponent(t)}=`;throw new de(`Cannot stringify type ${typeof o}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${dt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Im()}`}makeStatusError(e,t,o,i){return ue.generate(e,t,o,i)}buildURL(e,t,o){let i=!this.baseURLOverridden()&&o||this.baseURL,r=wm(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return _m(a)||(t=Object.assign(Object.assign({},a),t)),typeof t=="object"&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:o}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,o){return this.request(Promise.resolve(o).then(i=>Object.assign({method:e,path:t},i)))}request(e,t=null){return new pi(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,o){var i,r,a;let c=await e,d=(i=c.maxRetries)!==null&&i!==void 0?i:this.maxRetries;t==null&&(t=d),await this.prepareOptions(c);let{req:u,url:p,timeout:m}=await this.buildRequest(c,{retryCount:d-t});await this.prepareRequest(u,{url:p,options:c});let h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=o===void 0?"":`, retryOf: ${o}`,b=Date.now();if(ae(this).debug(`[${h}] sending request`,Ze({retryOfRequestLogID:o,method:c.method,url:p,options:c,headers:u.headers})),!((r=c.signal)===null||r===void 0)&&r.aborted)throw new Pt;let E=new AbortController,I=await this.fetchWithTimeout(p,u,m,E).catch(li),v=Date.now();if(I instanceof globalThis.Error){let T=`retrying, ${t} attempts remaining`;if(!((a=c.signal)===null||a===void 0)&&a.aborted)throw new Pt;let _=ai(I)||/timed? ?out/i.test(String(I)+("cause"in I?String(I.cause):""));if(t)return ae(this).info(`[${h}] connection ${_?"timed out":"failed"} - ${T}`),ae(this).debug(`[${h}] connection ${_?"timed out":"failed"} (${T})`,Ze({retryOfRequestLogID:o,url:p,durationMs:v-b,message:I.message})),this.retryRequest(c,t,o??h);throw ae(this).info(`[${h}] connection ${_?"timed out":"failed"} - error; no more retries left`),ae(this).debug(`[${h}] connection ${_?"timed out":"failed"} (error; no more retries left)`,Ze({retryOfRequestLogID:o,url:p,durationMs:v-b,message:I.message})),_?new yn:new mt({cause:I})}let w=`[${h}${g}] ${u.method} ${p} ${I.ok?"succeeded":"failed"} with status ${I.status} in ${v-b}ms`;if(!I.ok){let T=await this.shouldRetry(I);if(t&&T){let x=`retrying, ${t} attempts remaining`;return await km(I.body),ae(this).info(`${w} - ${x}`),ae(this).debug(`[${h}] response error (${x})`,Ze({retryOfRequestLogID:o,url:I.url,status:I.status,headers:I.headers,durationMs:v-b})),this.retryRequest(c,t,o??h,I.headers)}let _=T?"error; no more retries left":"error; not retryable";ae(this).info(`${w} - ${_}`);let A=await I.text().catch(x=>li(x).message),R=xm(A),N=R?void 0:A;throw ae(this).debug(`[${h}] response error (${_})`,Ze({retryOfRequestLogID:o,url:I.url,status:I.status,headers:I.headers,message:N,durationMs:Date.now()-b})),this.makeStatusError(I.status,R,N,I.headers)}return ae(this).info(w),ae(this).debug(`[${h}] response start`,Ze({retryOfRequestLogID:o,url:I.url,status:I.status,headers:I.headers,durationMs:v-b})),{response:I,options:c,controller:E,requestLogID:h,retryOfRequestLogID:o,startTime:b}}async fetchWithTimeout(e,t,o,i){let r=t||{},{signal:a,method:c}=r,d=gn(r,["signal","method"]);a&&a.addEventListener("abort",()=>i.abort());let u=setTimeout(()=>i.abort(),o),p=globalThis.ReadableStream&&d.body instanceof globalThis.ReadableStream||typeof d.body=="object"&&d.body!==null&&Symbol.asyncIterator in d.body,m=Object.assign(Object.assign(Object.assign({signal:i.signal},p?{duplex:"half"}:{}),{method:"GET"}),d);c&&(m.method=c.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,o,i){var r;let a,c=i?.get("retry-after-ms");if(c){let u=parseFloat(c);Number.isNaN(u)||(a=u)}let d=i?.get("retry-after");if(d&&!a){let u=parseFloat(d);Number.isNaN(u)?a=Date.parse(d)-Date.now():a=u*1e3}if(!(a&&0<=a&&a<60*1e3)){let u=(r=e.maxRetries)!==null&&r!==void 0?r:this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,u)}return await Pm(a),this.makeRequest(e,t-1,o)}calculateDefaultRetryTimeoutMillis(e,t){let r=t-e,a=Math.min(.5*Math.pow(2,r),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){var o,i,r;let a=Object.assign({},e),{method:c,path:d,query:u,defaultBaseURL:p}=a,m=this.buildURL(d,u,p);"timeout"in a&&Am("timeout",a.timeout),a.timeout=(o=a.timeout)!==null&&o!==void 0?o:this.timeout;let{bodyHeaders:h,body:g}=this.buildBody({options:a}),b=await this.buildHeaders({options:e,method:c,bodyHeaders:h,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:c,headers:b},a.signal&&{signal:a.signal}),globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"}),g&&{body:g}),(i=this.fetchOptions)!==null&&i!==void 0?i:{}),(r=a.fetchOptions)!==null&&r!==void 0?r:{}),url:m,timeout:a.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:o,retryCount:i}){let r={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);let a=vo([r,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),Rm()),await this.authHeaders(e),this._options.defaultHeaders,o,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let o=vo([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&o.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Dm(e)}:this.encoder({body:e,headers:o})}};$n.DEFAULT_TIMEOUT=6e4;var Y=class extends $n{static{f(this,"GeminiNextGenAPIClient")}constructor(){super(...arguments),this.interactions=new Pn(this)}};nl=Y;Y.GeminiNextGenAPIClient=nl;Y.GeminiNextGenAPIClientError=de;Y.APIError=ue;Y.APIConnectionError=mt;Y.APIConnectionTimeoutError=yn;Y.APIUserAbortError=Pt;Y.NotFoundError=wn;Y.ConflictError=Tn;Y.RateLimitError=_n;Y.BadRequestError=En;Y.AuthenticationError=In;Y.InternalServerError=Sn;Y.PermissionDeniedError=vn;Y.UnprocessableEntityError=Cn;Y.toFile=Bm;Y.Interactions=Pn;function eh(n,e){let t={},o=s(n,["name"]);return o!=null&&l(t,["_url","name"],o),t}f(eh,"cancelTuningJobParametersToMldev");function th(n,e){let t={},o=s(n,["name"]);return o!=null&&l(t,["_url","name"],o),t}f(th,"cancelTuningJobParametersToVertex");function nh(n,e){let t={},o=s(n,["sdkHttpResponse"]);return o!=null&&l(t,["sdkHttpResponse"],o),t}f(nh,"cancelTuningJobResponseFromMldev");function oh(n,e){let t={},o=s(n,["sdkHttpResponse"]);return o!=null&&l(t,["sdkHttpResponse"],o),t}f(oh,"cancelTuningJobResponseFromVertex");function ih(n,e,t){let o={};if(s(n,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is not supported in Gemini API.");let i=s(n,["tunedModelDisplayName"]);if(e!==void 0&&i!=null&&l(e,["displayName"],i),s(n,["description"])!==void 0)throw new Error("description parameter is not supported in Gemini API.");let r=s(n,["epochCount"]);e!==void 0&&r!=null&&l(e,["tuningTask","hyperparameters","epochCount"],r);let a=s(n,["learningRateMultiplier"]);if(a!=null&&l(o,["tuningTask","hyperparameters","learningRateMultiplier"],a),s(n,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(s(n,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(s(n,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is not supported in Gemini API.");let c=s(n,["batchSize"]);e!==void 0&&c!=null&&l(e,["tuningTask","hyperparameters","batchSize"],c);let d=s(n,["learningRate"]);if(e!==void 0&&d!=null&&l(e,["tuningTask","hyperparameters","learningRate"],d),s(n,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");if(s(n,["beta"])!==void 0)throw new Error("beta parameter is not supported in Gemini API.");return o}f(ih,"createTuningJobConfigToMldev");function rh(n,e,t){let o={},i=s(t,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let g=s(n,["validationDataset"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec"],va(g))}else if(i==="PREFERENCE_TUNING"){let g=s(n,["validationDataset"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec"],va(g))}let r=s(n,["tunedModelDisplayName"]);e!==void 0&&r!=null&&l(e,["tunedModelDisplayName"],r);let a=s(n,["description"]);e!==void 0&&a!=null&&l(e,["description"],a);let c=s(t,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let g=s(n,["epochCount"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","epochCount"],g)}else if(c==="PREFERENCE_TUNING"){let g=s(n,["epochCount"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],g)}let d=s(t,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let g=s(n,["learningRateMultiplier"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],g)}else if(d==="PREFERENCE_TUNING"){let g=s(n,["learningRateMultiplier"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],g)}let u=s(t,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let g=s(n,["exportLastCheckpointOnly"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","exportLastCheckpointOnly"],g)}else if(u==="PREFERENCE_TUNING"){let g=s(n,["exportLastCheckpointOnly"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],g)}let p=s(t,["config","method"]);if(p===void 0&&(p="SUPERVISED_FINE_TUNING"),p==="SUPERVISED_FINE_TUNING"){let g=s(n,["adapterSize"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","adapterSize"],g)}else if(p==="PREFERENCE_TUNING"){let g=s(n,["adapterSize"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],g)}if(s(n,["batchSize"])!==void 0)throw new Error("batchSize parameter is not supported in Vertex AI.");if(s(n,["learningRate"])!==void 0)throw new Error("learningRate parameter is not supported in Vertex AI.");let m=s(n,["labels"]);e!==void 0&&m!=null&&l(e,["labels"],m);let h=s(n,["beta"]);return e!==void 0&&h!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","beta"],h),o}f(rh,"createTuningJobConfigToVertex");function sh(n,e){let t={},o=s(n,["baseModel"]);o!=null&&l(t,["baseModel"],o);let i=s(n,["preTunedModel"]);i!=null&&l(t,["preTunedModel"],i);let r=s(n,["trainingDataset"]);r!=null&&bh(r);let a=s(n,["config"]);return a!=null&&ih(a,t),t}f(sh,"createTuningJobParametersPrivateToMldev");function ah(n,e){let t={},o=s(n,["baseModel"]);o!=null&&l(t,["baseModel"],o);let i=s(n,["preTunedModel"]);i!=null&&l(t,["preTunedModel"],i);let r=s(n,["trainingDataset"]);r!=null&&yh(r,t,e);let a=s(n,["config"]);return a!=null&&rh(a,t,e),t}f(ah,"createTuningJobParametersPrivateToVertex");function lh(n,e){let t={},o=s(n,["name"]);return o!=null&&l(t,["_url","name"],o),t}f(lh,"getTuningJobParametersToMldev");function ch(n,e){let t={},o=s(n,["name"]);return o!=null&&l(t,["_url","name"],o),t}f(ch,"getTuningJobParametersToVertex");function dh(n,e,t){let o={},i=s(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let r=s(n,["pageToken"]);e!==void 0&&r!=null&&l(e,["_query","pageToken"],r);let a=s(n,["filter"]);return e!==void 0&&a!=null&&l(e,["_query","filter"],a),o}f(dh,"listTuningJobsConfigToMldev");function uh(n,e,t){let o={},i=s(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let r=s(n,["pageToken"]);e!==void 0&&r!=null&&l(e,["_query","pageToken"],r);let a=s(n,["filter"]);return e!==void 0&&a!=null&&l(e,["_query","filter"],a),o}f(uh,"listTuningJobsConfigToVertex");function fh(n,e){let t={},o=s(n,["config"]);return o!=null&&dh(o,t),t}f(fh,"listTuningJobsParametersToMldev");function ph(n,e){let t={},o=s(n,["config"]);return o!=null&&uh(o,t),t}f(ph,"listTuningJobsParametersToVertex");function mh(n,e){let t={},o=s(n,["sdkHttpResponse"]);o!=null&&l(t,["sdkHttpResponse"],o);let i=s(n,["nextPageToken"]);i!=null&&l(t,["nextPageToken"],i);let r=s(n,["tunedModels"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>ol(c))),l(t,["tuningJobs"],a)}return t}f(mh,"listTuningJobsResponseFromMldev");function hh(n,e){let t={},o=s(n,["sdkHttpResponse"]);o!=null&&l(t,["sdkHttpResponse"],o);let i=s(n,["nextPageToken"]);i!=null&&l(t,["nextPageToken"],i);let r=s(n,["tuningJobs"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>mi(c))),l(t,["tuningJobs"],a)}return t}f(hh,"listTuningJobsResponseFromVertex");function gh(n,e){let t={},o=s(n,["name"]);o!=null&&l(t,["model"],o);let i=s(n,["name"]);return i!=null&&l(t,["endpoint"],i),t}f(gh,"tunedModelFromMldev");function bh(n,e){let t={};if(s(n,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(s(n,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");let o=s(n,["examples"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(r=>r)),l(t,["examples","examples"],i)}return t}f(bh,"tuningDatasetToMldev");function yh(n,e,t){let o={},i=s(t,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){let a=s(n,["gcsUri"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(i==="PREFERENCE_TUNING"){let a=s(n,["gcsUri"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}let r=s(t,["config","method"]);if(r===void 0&&(r="SUPERVISED_FINE_TUNING"),r==="SUPERVISED_FINE_TUNING"){let a=s(n,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(r==="PREFERENCE_TUNING"){let a=s(n,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}if(s(n,["examples"])!==void 0)throw new Error("examples parameter is not supported in Vertex AI.");return o}f(yh,"tuningDatasetToVertex");function ol(n,e){let t={},o=s(n,["sdkHttpResponse"]);o!=null&&l(t,["sdkHttpResponse"],o);let i=s(n,["name"]);i!=null&&l(t,["name"],i);let r=s(n,["state"]);r!=null&&l(t,["state"],Pa(r));let a=s(n,["createTime"]);a!=null&&l(t,["createTime"],a);let c=s(n,["tuningTask","startTime"]);c!=null&&l(t,["startTime"],c);let d=s(n,["tuningTask","completeTime"]);d!=null&&l(t,["endTime"],d);let u=s(n,["updateTime"]);u!=null&&l(t,["updateTime"],u);let p=s(n,["description"]);p!=null&&l(t,["description"],p);let m=s(n,["baseModel"]);m!=null&&l(t,["baseModel"],m);let h=s(n,["_self"]);return h!=null&&l(t,["tunedModel"],gh(h)),t}f(ol,"tuningJobFromMldev");function mi(n,e){let t={},o=s(n,["sdkHttpResponse"]);o!=null&&l(t,["sdkHttpResponse"],o);let i=s(n,["name"]);i!=null&&l(t,["name"],i);let r=s(n,["state"]);r!=null&&l(t,["state"],Pa(r));let a=s(n,["createTime"]);a!=null&&l(t,["createTime"],a);let c=s(n,["startTime"]);c!=null&&l(t,["startTime"],c);let d=s(n,["endTime"]);d!=null&&l(t,["endTime"],d);let u=s(n,["updateTime"]);u!=null&&l(t,["updateTime"],u);let p=s(n,["error"]);p!=null&&l(t,["error"],p);let m=s(n,["description"]);m!=null&&l(t,["description"],m);let h=s(n,["baseModel"]);h!=null&&l(t,["baseModel"],h);let g=s(n,["tunedModel"]);g!=null&&l(t,["tunedModel"],g);let b=s(n,["preTunedModel"]);b!=null&&l(t,["preTunedModel"],b);let E=s(n,["supervisedTuningSpec"]);E!=null&&l(t,["supervisedTuningSpec"],E);let I=s(n,["preferenceOptimizationSpec"]);I!=null&&l(t,["preferenceOptimizationSpec"],I);let v=s(n,["tuningDataStats"]);v!=null&&l(t,["tuningDataStats"],v);let w=s(n,["encryptionSpec"]);w!=null&&l(t,["encryptionSpec"],w);let T=s(n,["partnerModelTuningSpec"]);T!=null&&l(t,["partnerModelTuningSpec"],T);let _=s(n,["customBaseModel"]);_!=null&&l(t,["customBaseModel"],_);let A=s(n,["experiment"]);A!=null&&l(t,["experiment"],A);let R=s(n,["labels"]);R!=null&&l(t,["labels"],R);let N=s(n,["outputUri"]);N!=null&&l(t,["outputUri"],N);let H=s(n,["pipelineJob"]);H!=null&&l(t,["pipelineJob"],H);let x=s(n,["serviceAccount"]);x!=null&&l(t,["serviceAccount"],x);let D=s(n,["tunedModelDisplayName"]);D!=null&&l(t,["tunedModelDisplayName"],D);let J=s(n,["veoTuningSpec"]);return J!=null&&l(t,["veoTuningSpec"],J),t}f(mi,"tuningJobFromVertex");function Eh(n,e){let t={},o=s(n,["sdkHttpResponse"]);o!=null&&l(t,["sdkHttpResponse"],o);let i=s(n,["name"]);i!=null&&l(t,["name"],i);let r=s(n,["metadata"]);r!=null&&l(t,["metadata"],r);let a=s(n,["done"]);a!=null&&l(t,["done"],a);let c=s(n,["error"]);return c!=null&&l(t,["error"],c),t}f(Eh,"tuningOperationFromMldev");function va(n,e){let t={},o=s(n,["gcsUri"]);o!=null&&l(t,["validationDatasetUri"],o);let i=s(n,["vertexDatasetResource"]);return i!=null&&l(t,["validationDatasetUri"],i),t}f(va,"tuningValidationDatasetToVertex");var hi=class extends Te{static{f(this,"Tunings")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new Me(Re.PAGED_ITEM_TUNING_JOBS,o=>this.listInternal(o),await this.listInternal(t),t),this.get=async t=>await this.getInternal(t),this.tune=async t=>{var o;if(this.apiClient.isVertexAI())if(t.baseModel.startsWith("projects/")){let i={tunedModelName:t.baseModel};!((o=t.config)===null||o===void 0)&&o.preTunedModelCheckpointId&&(i.checkpointId=t.config.preTunedModelCheckpointId);let r=Object.assign(Object.assign({},t),{preTunedModel:i});return r.baseModel=void 0,await this.tuneInternal(r)}else{let i=Object.assign({},t);return await this.tuneInternal(i)}else{let i=Object.assign({},t),r=await this.tuneMldevInternal(i),a="";return r.metadata!==void 0&&r.metadata.tunedModel!==void 0?a=r.metadata.tunedModel:r.name!==void 0&&r.name.includes("/operations/")&&(a=r.name.split("/operations/")[0]),{name:a,state:Co.JOB_STATE_QUEUED}}}}async getInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=ch(e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>mi(p))}else{let u=lh(e);return c=C("{name}",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>ol(p))}}async listInternal(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=ph(e);return c=C("tuningJobs",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=hh(p),h=new dn;return Object.assign(h,m),h})}else{let u=fh(e);return c=C("tunedModels",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=mh(p),h=new dn;return Object.assign(h,m),h})}}async cancel(e){var t,o,i,r;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=th(e);return c=C("{name}:cancel",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=oh(p),h=new un;return Object.assign(h,m),h})}else{let u=eh(e);return c=C("{name}:cancel",u._url),d=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:c,queryParams:d,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(p=>p.json().then(m=>{let h=m;return h.sdkHttpResponse={headers:p.headers},h})),a.then(p=>{let m=nh(p),h=new un;return Object.assign(h,m),h})}}async tuneInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI()){let c=ah(e,e);return r=C("tuningJobs",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>mi(d))}else throw new Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(e){var t,o;let i,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=sh(e);return r=C("tunedModels",c._url),a=c._query,delete c._url,delete c._query,i=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json().then(u=>{let p=u;return p.sdkHttpResponse={headers:d.headers},p})),i.then(d=>Eh(d))}}};var gi=class{static{f(this,"BrowserDownloader")}async download(e,t){throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.")}},Ih=1024*1024*8,vh=3,wh=1e3,Th=2,Gn="x-goog-upload-status";async function Ch(n,e,t){var o;let i=await il(n,e,t),r=await i?.json();if(((o=i?.headers)===null||o===void 0?void 0:o[Gn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return r.file}f(Ch,"uploadBlob");async function _h(n,e,t){var o;let i=await il(n,e,t),r=await i?.json();if(((o=i?.headers)===null||o===void 0?void 0:o[Gn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let a=Ta(r),c=new Fo;return Object.assign(c,a),c}f(_h,"uploadBlobToFileSearchStore");async function il(n,e,t){var o,i;let r=0,a=0,c=new xt(new Response),d="upload";for(r=n.size;a<r;){let u=Math.min(Ih,r-a),p=n.slice(a,a+u);a+u>=r&&(d+=", finalize");let m=0,h=wh;for(;m<vh&&(c=await t.request({path:"",body:p,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:e,headers:{"X-Goog-Upload-Command":d,"X-Goog-Upload-Offset":String(a),"Content-Length":String(u)}}}),!(!((o=c?.headers)===null||o===void 0)&&o[Gn]));)m++,await Ah(h),h=h*Th;if(a+=u,((i=c?.headers)===null||i===void 0?void 0:i[Gn])!=="active")break;if(r<=a)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return c}f(il,"uploadBlobInternal");async function Sh(n){return{size:n.size,type:n.type}}f(Sh,"getBlobStat");function Ah(n){return new Promise(e=>setTimeout(e,n))}f(Ah,"sleep");var bi=class{static{f(this,"BrowserUploader")}async upload(e,t,o){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await Ch(e,t,o)}async uploadToFileSearchStore(e,t,o){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await _h(e,t,o)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await Sh(e)}};var yi=class{static{f(this,"BrowserWebSocketFactory")}create(e,t,o){return new Ei(e,t,o)}},Ei=class{static{f(this,"BrowserWebSocket")}constructor(e,t,o){this.url=e,this.headers=t,this.callbacks=o}connect(){this.ws=new WebSocket(this.url),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(e){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};var wa="x-goog-api-key",Ii=class{static{f(this,"WebAuth")}constructor(e){this.apiKey=e}async addAuthHeaders(e,t){if(e.get(wa)===null){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");if(!this.apiKey)throw new Error("API key is missing. Please provide a valid API key.");e.append(wa,this.apiKey)}}};var xh="gl-node/",Nt=class{static{f(this,"GoogleGenAI")}get interactions(){if(this._interactions!==void 0)return this._interactions;if(console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions."),this.vertexai)throw new Error("This version of the GenAI SDK does not support Vertex AI API for interactions.");let e=this.httpOptions;e?.extraBody&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.");let t=new Y({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:e?.timeout});return this._interactions=t.interactions,this._interactions}constructor(e){var t;if(e.apiKey==null)throw new Error("An API Key must be set when running in a browser");if(e.project||e.location)throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.");this.vertexai=(t=e.vertexai)!==null&&t!==void 0?t:!1,this.apiKey=e.apiKey;let o=oc(e.httpOptions,e.vertexai,void 0,void 0);o&&(e.httpOptions?e.httpOptions.baseUrl=o:e.httpOptions={baseUrl:o}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let i=new Ii(this.apiKey);this.apiClient=new Yo({auth:i,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:xh+"web",uploader:new bi,downloader:new gi}),this.models=new ni(this.apiClient),this.live=new ei(this.apiClient,i,new yi),this.batches=new Bo(this.apiClient),this.chats=new Oo(this.models,this.apiClient),this.caches=new qo(this.apiClient),this.files=new Jo(this.apiClient),this.operations=new oi(this.apiClient),this.authTokens=new ii(this.apiClient),this.tunings=new hi(this.apiClient),this.fileSearchStores=new si(this.apiClient)}};var et=V||!0,rl=new Map,sl=[];function tt(){let n=`[${tt.name}]`;try{return et&&console.log(`${n} starting... (I: a5cf5821b42e1c71182dd61431977e25)`),rl}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{et&&console.log(`${n} complete.`)}}f(tt,"getAllFunctionInfos");function Ai(){let n=`[${Ai.name}]`;try{return et&&console.log(`${n} starting... (I: 82c9a8fc91d8121fb843af32e76c2e25)`),sl}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{et&&console.log(`${n} complete.`)}}f(Ai,"getDeprecatedFunctionInfoNames");function Ph({functionInfos:n}){let e=`[${Ph.name}]`;try{et&&console.log(`${e} starting... (I: 14fee8e27384a040494542182031ae25)`),n.size===0&&console.warn(`${e} empty functionInfos? (W: 97fcb8fc47689bc418893c09a16a2525)`);for(let[t,o]of n)sl.includes(t)?et&&console.log(`${e} functionInfo.nameOrId (${t}) is deprecated. Skipping add. (I: 3256eadf54f8087088a704798e2fd825)`):rl.set(t,o)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{et&&console.log(`${e} complete.`)}}f(Ph,"registerFunctionInfos");var fe=V;function $t(n){switch(n){case X.HUMAN:return"user";case X.AI:return"model";case X.FUNCTION:return"user";case X.HARDCODED:return"user";case X.UNKNOWN:return"user";default:throw new Error(`(UNEXPECTED) src is not a valid TextSource? src: ${n} (E: 9d954fe0bc49cf4572a65b19b6173925)`)}}f($t,"textSourceToGeminiRole");function al(n){return n.api==="gemini"}f(al,"isPromptInfoGemini");function xi({systemPromptEntries:n}){let e=`[${xi.name}]`;try{if(fe&&console.log(`${e} starting... (I: 18693a97427939699285ef8c1a9cc425)`),n.length===0)return;n.every(o=>o.src===X.HUMAN)||fe&&console.warn(`${e} not every system entry's src is human. We're still going to say that these are "user" origin in Gemini API. (W: 7115e2be876498ecb1e153c79a86e125)`);let t={role:"user",parts:n.filter(o=>!!o.content.parts).flatMap(o=>o.content.parts)};return fe&&console.log(`${e} sysInstructionContent: ${M(t)} (I: 011e5b865c23eb0b640df3f464ac2525)`),t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{fe&&console.log(`${e} complete.`)}}f(xi,"systemPromptEntriesToSystemInstructionContent");function Pi({ibGib:n}){let e=`[${Pi.name}]`;try{if(fe&&console.log(`${e} starting... (I: 986d3edcd4f3aaf1d7eb0f8b59206b25)`),!n)return fe&&console.warn(`${e} ibGib falsy. (W: a70390e8bc3f420a92d3a84f4c78f12a)`),!1;if(!Ye({ibGib:n}))return fe&&console.log(`${e} not a comment ibgib (I: 6a62c4f6e13776616855c4f237a5206b)`),!1;if(!n.data)return fe&&console.log(`${e} ibGib.data falsy (I: 69eb86975640475395bb74944141a46d)`),!1;let{text:t}=n.data;return t?t.includes(Jt)?(fe&&console.log(`${e} has tag. returning true. (I: 6d76b27d558d44f696582f41af561f29)`),!0):(fe&&console.log(`${e} no indicator found. returning false. (I: 815f181a0a08058362f76b08a8964674)`),!1):(fe&&console.log(`${e} text falsy (I: e348e38c841b4443b3f09e75c0215b24)`),!1)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{fe&&console.log(`${e} complete.`)}}f(Pi,"isFunctionCallRequestComment");function Ni({functionInfoIbGib:n}){let e=`[${Ni.name}]`;try{if(fe&&console.log(`${e} starting... (I: 1a2b3c4d5e6f7a8b)`),!n)throw new Error(`${e} functionInfoIbGib parameter is required. (E: 9c8f7a3b2d1e4a5b6c7d8e9f)`);if(!n.data)throw new Error(`${e} functionInfoIbGib.data is required. (E: 2b3c4d5e6f7a8b1c2d3e4f5a)`);let{fnName:t,fnArgs:o,fnResult:i}=n.data;if(!t)throw new Error(`${e} functionInfoIbGib.data.fnName is required. (E: 6f7a8b1c2d3e4f5a6b7c8d9e)`);return{call:{functionCall:{name:t,args:o??{}}},response:{functionResponse:{name:t,response:{value:i}}}}}catch(t){throw console.error(`${e} Error: ${y(t)}`),t}finally{fe&&console.log(`${e} complete.`)}}f(Ni,"getFunctionCallAndResponseParts");var Gt=V,kn="function_info",ll="function_info";function cl({data:n}){let e=`[${cl.name}]`,{model:t,api:o,agentId:i,timestamp:r}=n;if(!t)throw new Error(`${e} data.model falsy (E: 6f47a28c0a8a45d794149c83e8f27e25)`);if(!o)throw new Error(`${e} data.api falsy (E: a0a812508a952a87c619d38084b7e325)`);if(!i)throw new Error(`${e} data.agentId falsy (E: ac35c1592c458e2c0e5908f6a9a3e525)`);let a=ze(r);if([t,o,i,a].some(d=>d.includes(" ")))throw new Error("invalid data. ib must not contain spaces (E: 36a56e4685163848458be06f51d4ad25)");return[ll,a,t,o,i].join(" ")}f(cl,"getFunctionInfoIb");async function Ln(n){let e=`[${Ln.name}]`;try{Gt&&console.log(`${e} starting... (I: f4c9f0810a4d877f676297f6e6a96825)`);let{fnRawRequest:t,api:o,model:i,agentId:r,fnName:a,fnArgs:c,fnResult:d,fnComplete:u,parseErrorMsg:p,execErrorMsg:m,repromptWithResult:h,saveInSpace:g,metaspace:b,space:E}=n,I=new Date,v={name:i,timestamp:kt(I),timestampMs:I.getMilliseconds(),agentId:r,api:o,model:i,fnRawRequest:t,fnName:a,fnArgs:c,fnResult:d,fnComplete:u,repromptWithResult:h};p&&(v.parseErrorMsg=p),m&&(v.execErrorMsg=m);let w=cl({data:v}),T=await ne.firstGen({ib:w,parentIbGib:ne.primitive({ib:ll}),data:v,nCounter:!0,dna:!0,tjp:{uuid:!0}});if(Gt&&console.log(`${e} created functionInfoIbGib (I: e50d2e17f43312d4f4739899306bb725)`),g){if(!b)throw new Error(`${e} metaspace must be provided if saveInSpace is set to true (E: e74b76b00124d5874a6c5404e794b725)`);if(!E)throw new Error(`${e} space must be provided if saveInSpace is set to true (E: f3d5f1695a52707114117f72d932a025)`);await b.persistTransformResult({resTransform:T,space:E}),Gt&&console.log(`${e} persisted resFunctionInfo (${S({ibGib:T.newIbGib})}) to space ${E.data?.uuid} (I: aa98e877d3b34e0d2a3b7711f8f27e25)`),await b.registerNewIbGib({ibGib:T.newIbGib,space:E}),Gt&&console.log(`${e} registered new function info ibgib (${S({ibGib:T.newIbGib})}) with metaspace (I: aa98e877d3b34e0d2a3b7711f8f27e25)`)}return T}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Gt&&console.log(`${e} complete.`)}}f(Ln,"createFunctionInfoIbGib");var G=V,Un=class n extends Sr{static{f(this,"AgentWitness_V1")}lc=`[${n.name}]`;availableFunctions=new Map;commentIbGibs_system=[];commentIbGibs_chat=[];_metaspace;fnGetAPIKey=f(()=>Promise.reject("not implemented. you need to set this after initializing the agent. (E: a14cbe903d08821126bbbb1d063d9825)"),"fnGetAPIKey");get name(){return this.data?.name??""}get uuid(){return this.data?.uuid??""}_genAI;transientDecompressionPromptText;fnOutputText=f(e=>{console.log(`${this.lc}[fnOutputText] this hack does nothing by default. set this to do something when text is returned by the model LLM. textResponse: ${e} (W: 3007e5d69dafdd7e42157fa7370d7f25)`)},"fnOutputText");ibGibProxy;constructor(e,t){super(e,t),this.instanceId=nt({count:32})}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{G&&console.log(`${e} starting... (I: 641e211473fc54d5a9ebb4ea44944d25)`);let t=await super.validateThis();return this.data?(this.data?.subSpaceId||t.push("agent.data.subSpaceId falsy (E: d4ea57fd6b1c5cbc1e18a084de2f7725)"),this.data?.subSpaceId.match(Dt)||t.push(`agent.data.subSpaceId must match regexp: ${Dt}. (E: f381eff533aa3f4713316f93f7f1dc25)`),this.data.name?this.data.name.match(at)||t.push(`agent name must match regexp: ${at}`):t.push("agent name falsy (E: 1351325107e5ac5ea6b7b789b73de125)"),this.data.description&&(this.data.description.match(lo)||t.push(`agent description must match regexp: ${lo}`))):t.push("this.data falsy (E: f5f151e11b12cad814b37ecad7c74a25)"),t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{G&&console.log(`${e} starting... (I: ce38519ac4bef52844a558fe31cda825)`),await super.initialize(),this._metaspace=await me();let t=new Ue;if(await t.initialized,!t.contextUpdated$)throw new Error("(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: e8840870af18091e6e4d52490ddca825)");if(t.contextUpdated$.subscribe($e({next:f(async o=>{let i=`${e}[ibGibProxy.contextUpdated$][next]`;G&&console.log(`${i} nextIbGib: ${M(o)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleContextUpdated()},"next"),error:f(async o=>{debugger;console.error(`${e}[ibGibProxy.contextUpdated$][error] what up? ${y(o)}`)},"error")})),this.ib&&this.gib&&this.data){let o=this.toIbGibDto();await this.loadIbGibDto(o);let i=await this._metaspace.getLocalUserSpace({localSpaceId:o.data?.superSpaceId});if(!i)throw new Error(`couldn't get local space with agent.data.superSpaceId (${o.data?.superSpaceId})? (E: 0fc1b8a8ffa26f39d8a15218ec818725)`);await this.ibGibProxy?.setWrappedIbGib({ibGib:o,space:i})}else G&&console.log(`${e} agent is "empty". not loading dto at this time, caller is responsible for calling loadIbGibDto (I: 06dba19d74d5695fe7d1957889283725)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{if(!this.ibGibProxy)throw new Error("(UNEXPECTED) this.ibGibProxy falsy but we're within handleContextUpdated handler? (E: a88fa85e8f27bd7f72c207389ebfbc25)");if(!this.ibGibProxy.ibGib)throw new Error("(UNEXPECTED) this.ibGibProxy.ibGib falsy but we're within the handleContextUpdated handler? (E: ca60b8f0a60a3e3d652c3018102d1825)");debugger;if(!this.gib){debugger;console.error(`${e} not sure if error, but this.gib is falsy when we get a new context down the pipeline? (E: 8501d8aee4db7b8461587f38f0bbb125)`)}if(S({ibGib:this})!==S({ibGib:this.ibGibProxy.ibGib})){let t=this.ibGibProxy.ibGib.data.n??0,o=this.data?.n??0;if(t<=o){debugger;console.error(`${e} issue with "new" proxy context and the current this.data.n with different addresses. divergent timelines? (E: 15c698eb4488cbae2db0e778fec15825)`)}await this.loadIbGibDto(this.ibGibProxy.ibGib),await W(200)}else console.error(`${e} ibgibProxy new context is no different than current. this is NOT necessarily an error, I just want to see this when it happens. nothing is being done here, we're just not loading the "new" ibgib dto. (E: eff668b2e858ded448366d58e4dd6825)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}}async getSubSpace(){let e=`[${this.getSubSpace.name}]`;try{G&&console.log(`${e} starting... (I: a2ec2c5e8f5fdf95c8c571b2b1b9e925)`);let{_metaspace:t}=this;if(!t)throw new Error("(UNEXPECTED) this.metaspace falsy? after init this.metaspace is expected to be set. (E: 4519a8feaf4489389be679598f274425)");let o=await t.getLocalUserSpace({localSpaceId:this.data.subSpaceId});if(!o){let i=await this.validateThis();if(i.length>0)throw new Error(`this agent has validation errors: ${i} (E: 9a0c6125cf89789ddb1610cf5a752225)`);if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 06e30e1d53fd4935333c7cf7e10db425)");o=await t.createLocalSpaceAndUpdateBootstrap({allowCancel:!1,zeroSpace:t.zeroSpace,spaceName:this.name+this.uuid.substring(0,5),createBootstrap:!1})}if(!o)throw new Error("(UNEXPECTED) space still falsy after creating locally? (E: 037ef1e6f54a675d0367227fdae16525)");return o}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}}async getSuperSpace(){let e=`[${this.getSuperSpace.name}]`;try{G&&console.log(`${e} starting... (I: 55fba9bcaf9539cc2219e03cda200525)`);let{_metaspace:t}=this;if(!t)throw new Error("(UNEXPECTED) this.metaspace falsy? after init this.metaspace is expected to be set. (E: 107f670c99832c573a7e5de18d58c325)");if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: a4341b8753678fcba7877b6319769b25)");if(!this.data.superSpaceId)throw new Error("(UNEXPECTED) this.data.superSpaceId falsy? (E: 0429fe44df5b56bf2ac67d38cde56325)");let o=await t.getLocalUserSpace({localSpaceId:this.data.superSpaceId});if(!o)throw new Error(`(UNEXPECTED) superSpace falsy? this.data.superSpaceId: ${this.data.superSpaceId} (E: fd9435212e8b87e4b60034bf9e797f25)`);return o}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}}_activeContext=void 0;async setActiveContext(e){let t=`${this.lc}[${this.setActiveContext.name}]`;try{G&&console.log(`${t} starting... (I: genuuid)`);let{contextIbGib:o,loggingInfo:i}=e;if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: ab5377fda6bc324638722d9832bab925)");if(!o)throw new Error("(UNEXPECTED) contextIbGib falsy? (E: 694525e512cfdd12c14e1213dbaab925)");if(!o.data)throw new Error("(UNEXPECTED) contextIbGib.data falsy? (E: f337252a23c822bcbd76144540050825)");let r=S({ibGib:o}),a=se({ibGib:o});if(!a)throw new Error(`(UNEXPECTED) contextTjpAddr falsy? contextIbGib (${r}) is expected to be a living ibgib with a tjp address (i.e. a timeline). This means it should have a rel8ns.tjp or data.isTjp should be truthy. (E: d756d1e862d2cccfed4a5807737e9a25)`);if(this.data?.["@currentContextTjpAddr"]===a?G&&console.log(`${t} this.data.@currentContextTjpAddr already set to the same addr. (I: 9f0d58ec65eee3ca2aec528f1328c325)`):await this.mut8Self({dataToAddOrPatch:{"@currentContextTjpAddr":a}}),!this._activeContext){let c=new Ue;await c.initialized;let d=`${t}[contextUpdated]`;if(!c.contextUpdated$)throw new Error("(UNEXPECTED) proxy.contextUpdated$ falsy? (E: 868c5e3bf025baa6d1ae727ab1160c25)");c.contextUpdated$.subscribe($e({next:f(async p=>{console.log(`${d}[next] nextIbGib: ${M(p)}`)},"next"),complete:f(async()=>{debugger;throw new Error(`${d}[complete] (UNEXPECTED) agent active context subscription complete? i honestly don't know if this hits. (E: 786d26ab23e4313db7ae2e08c70a7425)`)},"complete"),error:f(async p=>{debugger;console.error(`${d}[error] ${y(p)}`)},"error")}));let u=`${t}[newContextChild]`;if(!c.newContextChild$)throw new Error("(UNEXPECTED) proxy.newContextChild$ falsy? (E: 123cf5624c3d2a6308aafc0c41f8a925)");c.newContextChild$.subscribe($e({next:f(async p=>{if(console.log(`${u}[next] newChild: ${M(p)}`),!p.data)throw new Error("newChild.data falsy? (E: a654134a2695c176971b0cd1426ced25)");if(Ye({ibGib:p})){let m=this.commentIbGibs_chat.map(I=>se({ibGib:I})??S({ibGib:I})),h=se({ibGib:p})??S({ibGib:p});if(m.includes(h)){console.log(`${t} already did this comment (${h}) (I: bce18642bb9babeb553e6188d7ae2825)`);return}let{safeIbCommentMetadataText:g}=Ke({ib:p.ib}),{textSrc:b}=Rt({addlMetadataText:g??"",ifError:"warn"}),E=p.data.text.startsWith("system: ");await this.addTexts({infos:[{textSrc:b??X.UNKNOWN,commentIbGib:p,isSystem:E}]}),b===X.HUMAN&&(E?console.log(`${t} system prompt has been modified. (I: d21c26f0a3fa12e2a874925882f39825)`):await this.doPrompt())}else console.warn(`${u} non-comment newChild. probably not a warning proper, but at this stage I'm only expecting comments ignoring... (W: e664834af4791ddcde19bfd4f7063e25)`)},"next"),complete:f(async()=>{debugger;throw new Error(`${u}[complete] (UNEXPECTED) agent active context subscription complete? i honestly don't know if this hits. (E: 88202d1f7554330d3dfca0237c2d6525)`)},"complete"),error:f(async p=>{debugger;console.error(`${u}[error] ${y(p)}`)},"error")})),this._activeContext=c}if(!this._activeContext)throw new Error("(UNEXPECTED) this._activeContext still falsy after we just initialized it? (E: 584f2f672b9ae7c979dde693eafb7a25)");await this._activeContext.setWrappedIbGib({ibGib:o})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{G&&console.log(`${t} complete.`)}}async updateName({name:e}){let t=`${this.lc}[${this.updateName.name}]`;try{if(G&&console.log(`${t} starting... (I: genuuid)`),e===this.name){console.warn(`${t} agent (${this.uuid}) already is named ${e}. returning early... (W: genuuid)`);return}else if(at.test(e))await this.mut8Self({dataToAddOrPatch:{name:e}});else throw new Error(`invalid name ${e}. must match regexp: ${at.source} (E: 507a2bfc0aaa60bd7bb608d253239e25)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{G&&console.log(`${t} complete.`)}}async updateAvailableFunctions({availableFunctions:e}){let t=`${this.lc}[${this.updateAvailableFunctions.name}]`;try{G&&console.log(`${t} starting... (I: 68f1bfa343925a657f8c0545b191c725)`);let o=[];for(let i of e)if(!this.availableFunctions.has(i.nameOrId)){let r=tt().get(i.nameOrId);if(r)o.push(r);else{console.error(`(UNEXPECTED) ${i} function not registered with getAllFunctionInfos()? skipping adding this function to the agent... (E: e860fe13c02677b274ac0e7df2587a25)`);continue}}o.length>0&&(console.log(`${t} adding newly found functions to agent: ${o.map(i=>i.nameOrId)}. (I: ab2b0ae6a62b3ced6a5f1e2e8cec4f25)`),await this.addAvailableFunctions(o))}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{G&&console.log(`${t} complete.`)}}async mut8Self({dataToAddOrPatch:e}){let t=`${this.lc}[${this.mut8Self.name}]`;try{G&&console.log(`${t} starting... (I: f4618832a0fe07ff8c89cea889d20725)`);let o=this._metaspace;if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: genuuid)");let i=await o.getLocalUserSpace({lock:!1,localSpaceId:this.data.superSpaceId});if(!i)throw new Error(`couldn't get local superSpace given by this.data.superSpaceId (${this.data.superSpaceId}) (E: genuuid)`);let{tjpGib:r}=K({gib:this.gib});if(!r)throw new Error(`(UNEXPECTED) this.gib (${this.gib}) has no tjpGib? (E: 75b8dcb82b58d3b0db40b39149023e25)`);await Ht({fn:f(async()=>{let a=xe();await a.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1});let c=await Ki({type:"mut8",src:this.toIbGibDto(),dataToAddOrPatch:e,dna:!0,nCounter:!0});await o.persistTransformResult({resTransform:c,space:i});let d=c.newIbGib;await this.loadIbGibDto(d),await a.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!0}),await o.registerNewIbGib({ibGib:d,space:i}),await $i({newAgentIbGib:d,metaspace:o,space:i,type:this.data.type})},"fn"),scope:r,secondsValid:60,maxDelayMs:100,maxLockAttempts:Number.MAX_SAFE_INTEGER,space:i,callerInstanceId:this.instanceId})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{G&&console.log(`${t} complete.`)}}getAvailableFunctions(){return Array.from(this.availableFunctions.values())}getComments_System(){return[...this.commentIbGibs_system]}getComments_Chat(){return[...this.commentIbGibs_chat]}async addAvailableFunctions(e){let t=`[${this.addAvailableFunctions.name}]`;try{if(G&&console.log(`${t} starting... (I: 273525464ec540fc9cba565e608db925)`),!e)throw new Error("(UNEXPECTED) functionInfos falsy? (E: 19cf2b7c9ee1115f0a3f7f62fbf77825)");if(e.length===0){console.warn(`${t} functionInfos.length === 0? why is this being called with no functions? returning early without doing anything. (W: 86c6dc4fad3c1ddcac697d5636b1eb25)`);return}await xe().updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1}),e.forEach(i=>{this.availableFunctions.has(i.nameOrId)&&console.warn(`${t} this.availableFunctions already has an entry for ${i.nameOrId}. replacing anyway. (W: ef2372a27be67174cb3605eac2c85c25)`),this.availableFunctions.set(i.nameOrId,i)}),await this.mut8Self({dataToAddOrPatch:{availableFunctionNameOrIds:Array.from(this.availableFunctions.keys())}})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{G&&console.log(`${t} complete.`)}}async doPrompt(){let e=`[${this.doPrompt.name}]`;try{if(G&&console.log(`${e} starting... (I: e7f1a7845cdf1bdce1f12d74c71a6425)`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 3c528e2376a2f2600b347b2c183a5225)");let t=await this.composePromptInfo();G&&console.log(`${e} promptTextInfo: ${M(t)} (I: b769b5f2a47623a99f78210994d90525)`);let o=await this.callTextAPI(t);if(G&&console.log(`${e} api result:`,o,"(I: e4d2c767eb3d6e38d83123d684a07425)"),"text"in o)await this.doPrompt_text(o.text);else{let{functionCalls:i}=o;await this.doPrompt_functionCalls({functionCalls:i})}}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}}async doPrompt_text(e){let t=`${this.lc}[${this.doPrompt_text.name}]`;try{G&&console.log(`${t} starting... (I: a2b9c21f3b2b058d355d16421e2b4425)`),e||="[no text returned from the model]",this.fnOutputText?this.fnOutputText(e):console.log(`${t} no fnOutputText set. Text Response: ${e} (I: 5936517474b10b214257781a24b10425)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{G&&console.log(`${t} complete.`)}}async doPrompt_functionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls.name}]`;try{if(G&&console.log(`${t} starting... (I: a4f1b581517a9c2a9187e9f8f3519925)`),e.length===0)throw new Error("(UNEXPECTED) functionCalls.length is zero? (E: 6434b8515a435a59b331452b563f4425)");let o=await this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({functionCalls:e});if(await this.doPrompt_functionCalls_addFunctionCallRequestComment({functionInfoIbGibs:o}),o.some(r=>!!r.data?.repromptWithResult&&r.data.fnName!=="tellUser")){let r=await this.doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt({functionInfoIbGibs:o});r.length>0?(console.log(`${t} transientDecompressionPromptText: ${r} (I: 11c11d544b7c8f8f8e7e5f7c1a9e3625)`),this.transientDecompressionPromptText=r,await this.rePrompt()):console.warn(`${t} (UNEXPECTED) there is no decompression text? (W: 6ce5da95c1c89a7ec48a00fbc1d11825)`)}else G&&console.log(`${t} no repromptWithResult. returning early. (I: 9c0113c958c7404534291f6700325925)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{G&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls.name}]`;try{if(G&&console.log(`${t} starting... (I: adc094bc98cb076a4aaf729f70adce25)`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: d071328283b2cf880ff0ccd499c22b25)");if(!this.data.uuid)throw new Error("(UNEXPECTED) this.data.uuid falsy? (E: 8acd2f793e4b5a368dbcf1d8d1e6e825)");let o=this._metaspace;if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: acf8a69e853eb8663f1dd0f79a823e25)");let i=[];for(let r of e)try{G&&console.log(`${t} processing functionCall: ${r} (I: a0c0b22b3c6b6c4b674a5a9c8c8b9e25)`);let a,c,d,u,p,m="";try{if(c=JSON.parse(r),m=c?.name??"",!m)throw new Error("functionName (functionCallParsedObj.name) falsy (E: e2397d675863a12b7609495b0007a025)");if(G&&console.log(`${t} functionCallParsedObj:`,M(c),"(I: 750f097243b85644d111971e0f929c25)"),u=tt().get(c.name),!u)throw new Error(`no APIFunctionInfo found that matches functionName (${m}) (E: 9d36b6472ec5cdf95e4f498292449925)`);p=c.args,G&&console.log(`${t} valid params (I: a4d5c13c79a2405c8d20464b42083325)`)}catch(h){d=`${t} invalid functionCallParsedObj. error: ${y(h)}. functionCallStr: ${r}. (E: 1687a24c5a3667d34689a09f8f753125)`,console.error(d),c=void 0}if(u){G&&console.log(`${t} found functionInfo: ${u.nameOrId} (I: 837c7a8200689a0b2314b73057812b25)`);let h,g=!1,b;try{G&&console.log(`${t} calling function impl for ${u.nameOrId} (I: b145d08186782089c18564305f0f1125)`),h=await u.fnViaCmd(p),g=!0,G&&console.log(`${t} functionImpl complete for ${u.nameOrId}. result:`,M(h),"(I: e19d476f489261263165914750472d25)")}catch(I){b=`${t} could not call functionImpl for ${u.nameOrId}: ${y(I)} (E: 9c0e97f29a9290f9d57637b7053f0c25)`,console.error(b)}a=(await Ln({api:this.data.api,model:this.data.model,agentId:this.data.uuid,fnRawRequest:r,fnName:m,fnArgs:c.args,repromptWithResult:c.args?.repromptWithResult??!1,fnResult:h,fnComplete:g,execErrorMsg:b,parseErrorMsg:void 0,saveInSpace:!0,metaspace:o,space:await this.getSuperSpace()})).newIbGib}else a=(await Ln({api:this.data.api,model:this.data.model,agentId:this.data.uuid,fnRawRequest:r,fnName:m,fnArgs:c.args,repromptWithResult:c.args?.repromptWithResult??!1,fnResult:void 0,fnComplete:void 0,execErrorMsg:void 0,parseErrorMsg:d,saveInSpace:!0,metaspace:o,space:await this.getSuperSpace()})).newIbGib;if(!a)throw new Error("(UNEXPECTED) functionInfoIbGib falsy? we should have guaranteed to create one at this point. (E: 97c4ce12c7372adfeebfd45181b73f25)");i.push(a)}catch(a){throw console.error(`${t} ${y(a)}`),a}finally{G&&console.log(`${t} complete.`)}if(i.length===0)throw new Error("(UNEXPECTED) functionInfoIbGibs.length === 0? We expect at least one to be created (E: a8f81c56377cdbdeb468af6b21879825)");return i}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{G&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_addFunctionCallRequestComment({functionInfoIbGibs:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_addFunctionCallRequestComment.name}]`;try{G&&console.log(`${t} starting... (I: 5000adac5e8c4a7158a720c38f56b325)`);let o=this._metaspace;if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: d7275731461d8d0526af3088553ae525)");let i=await this.getSuperSpace(),r=lt({tagText:Jt,contentText:e.map(p=>S({ibGib:p})).join(`
|
|
1184
|
+
`),randomIdLength:4}),a=Et({textSrc:"ai",other:"functionCallRequest"}),c=await Xe({text:r,addlMetadataText:a,saveInSpace:!0,space:i}),d=await Je({type:"rel8",src:c.newIbGib,rel8nsToAddByAddr:{[kn]:e.map(p=>S({ibGib:p}))},dna:!0,nCounter:!0}),u=d.newIbGib;await o.persistTransformResult({resTransform:d,space:i}),await o.registerNewIbGib({ibGib:u,space:i}),await this.addTexts({infos:[{textSrc:"ai",commentIbGib:u}]})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{G&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt({functionInfoIbGibs:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt.name}]`;try{G&&console.log(`${t} starting... (I: c245f78f6c78a98d62375a9f14b3d625)`);let o=[];for(let i of e)try{let r=S({ibGib:i});if(!i.data)throw new Error(`(UNEXPECTED) !functionInfoIbGib.data? functionInfoAddr: ${r} (E: 7815e4854513c26b889517a9bd7e0d25)`);let{fnRawRequest:a,fnComplete:c,fnResult:d}=i.data,p=lt({tagText:r,contentText:M({fnRawRequest:a,fnComplete:c,fnResult:d}),randomIdLength:void 0});o.push(p)}catch(r){console.error(`${t} could not call functionImpl: ${y(r)} (E: 2a3b8b37e146c524b67119e3a74e3d25)`)}return o.join(`
|
|
1185
|
+
`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{G&&console.log(`${t} complete.`)}}repromptCount=0;repromptMax=12;async rePrompt(){let e=`${this.lc}[${this.rePrompt.name}]`;try{G&&console.log(`${e} starting... (I: b6af34214acf07f9ca8c1d03c0011525)`),this.repromptCount<this.repromptMax?(this.repromptCount++,await this.doPrompt()):(console.log(`${e} already reached repromptMax (${this.repromptMax}). reprompt aborting. $(I: dacefb501dab2a1ee173ce8558657725)`),this.repromptCount=0)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}}async witness(e){if(e.ib===Ut&&e.gib===Ft)return this.getComments_Chat().length>0&&await this.doPrompt(),vt;throw new Error(`arg (${M(e)}) not implemented. only expect ${vt} right now to trigger doPrompt. (E: 24da0ad7333b6bbb359d1be425db3c25)`)}};var L=V,Ve=class n extends Un{static{f(this,"AgentWitnessGemini_V1")}lc=`[${n.name}]`;async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{L&&console.log(`${e} starting... (I: 641e211473fc54d5a9ebb4ea44944d25)`);let t=await super.validateThis();return this.data&&console.warn(`${e} do more validation on this concrete class. (W: fb778a84ccca2ebcefd2ca7845543825)`),t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{L&&console.log(`${e} complete.`)}}parseAddlMetadataString({ib:e}){let t=`${this.lc}[${this.parseAddlMetadataString.name}]`;try{throw L&&console.log(`${t} starting... (I: 080daf4b73f8bb52c70bf0a8f329be25)`),new Error("not implemented...i've just converted agent witness to a full witness with context and this was the only abstract method required. wasn't being used previously? so i'm not sure why this is here. (E: 129e816d3698f3867ec54c34fcc9a225)")}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{L&&console.log(`${t} complete.`)}}async addTexts(e){let t=`${this.lc}[${this.addTexts.name}]`;try{let o=xe();await o.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1});let i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: fd92a81901a83e2698ab2c3d4e702f25)");if(e.infos.length===0)return console.warn(`${t} opts.infos.length === 0. So we've called addTexts but with an empty array? returning early. (W: 0d42cd3b26aec45874d0e65450b37d25)`),[];let r=[],a=[],c=[],d=await this.getSuperSpace();for(let m of e.infos){let{textSrc:h,isSystem:g}=m,{text:b,commentIbGib:E}=m;if(b&&E)throw new Error("(UNEXPECTED) both text and commentIbGib provided? (E: a3fd590db1a5efc301f3c7e66b322f25)");if(!b&&!E)throw new Error("(UNEXPECTED) both text and commentIbGib falsy? one or the other is required (E: e08c7c694a17319085adfb75914b2725)");let I=Et({textSrc:h});if(E)L&&console.log(`${t} adding existing commentIbGib (I: 72a3f7aafde92f65b168d27605f94625)`);else{if(L&&console.log(`${t} creating new commentIbGib for text (I: 72a3f7aafde92f65b168d27605f94625)`),!b)throw new Error("(UNEXPECTED) text falsy still? at this point it should be guaranteed (E: b2deec458f35f22298ccb664d0685125)");E=(await Xe({text:b,addlMetadataText:I,saveInSpace:!0,space:d})).newIbGib,await i.registerNewIbGib({ibGib:E,space:d})}if(!E)throw new Error("(UNEXPECTED) commentIbGib still falsy? we should have just created one if it didn't exist (E: 9370b19aa207234db185cd74b57be525)");let v=await Vn({ibGib:E});if(v.length>0)throw new Error(`validation errors with trying to add a commentIbGib. errors: ${v} (E: beee1893050f9bcf9842c66831595225)`);r.push(E),g?a.push(E):c.push(E)}let u=[];a.length>0&&u.push({rel8nName:"system",ibGibs:a}),c.length>0&&u.push({rel8nName:"chat",ibGibs:c});let p=await _r({timeline:this.toIbGibDto(),rel8nInfos:u,timelineIndexInfo:{rel8nName:Qe,type:this.data.type},metaspace:i,space:d});return await this.loadIbGibDto(p),await o.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!0}),r}catch(o){throw console.error(`${t} ${y(o)}`),o}}async composePromptInfo(){let e=`${this.lc}[${this.composePromptInfo.name}]`;try{if(L&&console.log(`${e} starting... (I: 155774d4811b038034342d5750174325)`),!this._metaspace)throw new Error("this.metaspace falsy (E: 7232a3a1b4348d460ed1375b32677125)");let t=[];for(let p of this.commentIbGibs_system){let m=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:p});t.push(...m)}let o=this.data?.["@currentContextTjpAddr"]??z;if(o!==z&&t.push({src:X.HARDCODED,content:{role:$t(X.HARDCODED),parts:[{text:dl({currentContextTjpAddr:o})}]}}),this.commentIbGibs_chat.length===0)throw new Error("(UNEXPECTED) this.commentIbGibs_chat.length === 0? why are we composing prompt info? We are assumed at this point to have added at least one comment ibgib to this agent. (E: a4e3d840946ab8e6dc3fde3e25d6b225)");let i=[],r=this.commentIbGibs_chat.length>1?this.commentIbGibs_chat.slice(0,-1):[];for(let p of r){let m=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:p});i.push(...m)}let a,c=this.commentIbGibs_chat.at(-1),d=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:c});if(d.length===1)a=d.at(0);else if(d.length===2)i.push(d.at(0)),a=d.at(1);else throw new Error("(UNEXPECTED) chatPromptCurrent_rawarray.length !== 1 or 2? We expect at this point either a regular text part or a FCR comment which creates two entries. (E: cd59f978479c20e496da4b0eb86c7d25)");let u={api:"gemini",systemPromptEntries:t,chatPromptHistoryParts:i,chatPromptCurrent:a};return L&&console.log(`${e} resPromptInfo:`,M(u),"(I: 8f17a8c45b9a91e20a5c5064d9114a25)"),u}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{L&&console.log(`${e} complete.`)}}async callTextAPI(e){let t=`${this.lc}[${this.callTextAPI.name}]`;try{if(L&&console.log(`${t} starting... (I: 27885f5b14682646542e9658417b2f25)`),!al(e))throw new Error("(UNEXPECTED) info.api !== gemini? we are in the gemini concrete class where this is assumed. (E: 9223647ec96fb3f4eaee32c3fc15d925)");if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 09224b6688fdac884ce88f196b68a425)");let{api:o,model:i}=this.data;if(o!=="gemini")throw new Error(`api not supported: ${o} (E: 7e5c7c17988a666a86e72299630c7f25)`);L&&console.log(`${t} calling gemini api with model: ${i} (I: 6208942a419e9041bb037384135a0c25)`);let r=await this.fnGetAPIKey();if(!r)return console.error(`${t} apiKey falsy. did you set this.fnGetAPIKey (E: d964596b1538c0327209a92e97a54d25)`),{text:"no api key entered so no LLM chat happening. enter a gemini api key and donate/invest!"};this._genAI??=new Nt({apiKey:r});let a=Array.from(this.availableFunctions.values()).map(w=>({name:w.nameOrId,description:w.schema?.description,parameters:w.schema?.parameters}));a.some(w=>w.parameters==="undefined")&&console.error(`${t} (UNEXPECTED) function schema parameters not defined for all APIFunctionInfo values. (E: ae7227cdd65c0ab4513c7b282a1e4825)`),L&&(console.log(`${t} Gemini functionDeclarations:`),console.dir(a));let{systemPromptEntries:c,chatPromptHistoryParts:d,chatPromptCurrent:u}=e,p=te(u);L&&console.log(`chatPromptCurrent_final (before decompression): ${M(p)} (I: bbd4c7b9f3225afe9da1761918d0ac25)`),L&&console.warn(`${t} skipping decompression for the moment. if we add decompression text when the last comment is a function response part, then we'll error out. Need to rethink compression/decompression with the new function call/response workflow. (W: 7478439f9bbbde30a1eab3c5189ea625)`);let m,h=f(async w=>{if(!this._genAI)throw new Error("(UNEXPECTED) this._genAI falsy? (E: 503a0d9e3f729de7653ee3565b017b25)");let T=d.map(H=>H.content),_={model:w,history:T,config:{systemInstruction:xi({systemPromptEntries:c}),tools:[{functionDeclarations:a}],toolConfig:{functionCallingConfig:{mode:e.overrideFunctionCallingMode??nn.ANY}}}},A=this._genAI.chats.create(_),R={message:u.content.parts};return await A.sendMessage(R)},"fnGoModel"),g=0,b=i;do{g++;try{m=await h(b);break}catch(w){let T=w.message,_=w.status??"[STATUS?]";T.includes(`${503}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${ct}) for this next call. error (${w.status}): ${y(w)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=ct):T.includes(`${429}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${ct}) for this next call. error (${w.status}): ${y(w)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=ct):console.error(`${t}[fnGoModel][${b}] error trying to get result from model. error (${w.status}): ${y(w)} (E: a67d595c8ed313d458369d4d0b3e7f25)`)}await W(2e3)}while(!m&&g<yo);if(!m)throw new Error("couldn't get result from model (E: ede013a53f875d99a96a2e257c7e7125)");let E=m,I=[],v=E.candidates?.[0]?.content?.parts||[];for(let w of v)w.functionCall&&I.push(w.functionCall);if(!I||I.length===0){if(L&&console.warn(`${t} no function calls in response, returning text. (W: 3a4b8c940983b9e28e3f04c01a09bb25)`),!E.text)throw new Error("response generated no function calls and no response.text (E: 6123b8cacfb834105ad3160cfc4ef825)");return{text:E.text}}return L&&(console.log(`${t} Gemini function calls:`),console.dir(I)),{functionCalls:I.map(w=>JSON.stringify(w,null,2))}}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{L&&console.log(`${t} complete.`)}}async createPromptInfoEntriesFromGeminiComment({commentIbGib:e}){let t=`[${this.createPromptInfoEntriesFromGeminiComment.name}]`;try{L&&console.log(`${t} starting... (I: 826a9d6b120d96532afbe1f7a22e8d25)`);let o=await Vn({ibGib:e});if(o.length>0)throw new Error(`validation errors with commentIbGib. Cannot create a prompt info entry. errors: ${o} (E: beee1893050f9bcf9842c66831595225)`);let{safeIbCommentMetadataText:i}=Ke({ib:e.ib});if(!i)throw new Error("(UNEXPECTED) addlMetaDataText falsy? we just validated the comment ibgib, so there should be the expected shape of the comment.ib. (E: facf5801f9ba158b1526dd09d0e1b325)");let{textSrc:r,timestampInTicks:a,errorMsg:c,other:d}=Rt({addlMetadataText:i,ifError:"warn"});if(c)throw new Error("(UNEXPECTED) errorMsg is truthy after parse addl metadata from comment.ib? we just validated the comment ibgib, so there should be the expected shape of the comment.ib. (? (E: 7fd7fac50851916f39ceccbe93446425)");if(!e.data)throw new Error("(UNEXPECTED) commentIbGib.data falsy? (E: 8ce54d28219237feddf8f25b5846cc25)");if(!e.data.text)throw new Error("(UNEXPECTED) commentIbGib.data.text falsy? (E: 8556fc95c401d1b5441454fceb8f2f25)");if(Pi({ibGib:e})){let p=await this.getFunctionInfoIbGibs({fcrCommentIbGib:e}),m=[],h=[];for(let E of p){let{call:I,response:v}=Ni({functionInfoIbGib:E});if(!I)throw new Error("(UNEXPECTED) call falsy? (E: 5c8f3bd6de3b300e1c105b9603bb7b25)");if(!v)throw new Error("(UNEXPECTED) response falsy? (E: d0388c838975c93126c1a6d64f781d25)");if(I.functionCall.name!==v.functionResponse.name)throw new Error("(UNEXPECTED) functionCall.name !== functionResponse.name? (E: e49f0d60093354db2b6ad17fdf86d425)");m.push(I),h.push(v)}let g={src:X.AI,content:{role:$t("ai"),parts:m}},b={src:X.FUNCTION,content:{role:$t(X.FUNCTION),parts:h}};return[g,b]}else return[{src:r,content:{role:$t(r),parts:[{text:e.data.text}]}}]}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{L&&console.log(`${t} complete.`)}}async promptOneOff(e){let t=`${this.lc}[${this.promptOneOff.name}]`;try{L&&console.log(`${t} starting... (I: genuuid)`);let{text:o,systemInstructions:i}=e;if(!o)throw new Error("(UNEXPECTED) opts.text falsy? (E: genuuid)");if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: genuuid)");let{api:r,model:a}=this.data;if(r!=="gemini")throw new Error(`api not supported: ${r} (E: genuuid)`);L&&console.log(`${t} calling gemini api with model: ${a} (I: genuuid)`);let c=await this.fnGetAPIKey();if(!c){console.error(`${t} apiKey falsy. did you set this.fnGetAPIKey (E: genuuid)`);return}this._genAI??=new Nt({apiKey:c});let d=f(async b=>{if(!this._genAI)throw new Error("(UNEXPECTED) this._genAI falsy? (E: fbe235713d48f0d8e87cd0b88ec54825)");let E={model:b,config:{systemInstruction:i}},v=await this._genAI.chats.create(E).sendMessage({message:o});if(v.text)return v.text;throw new Error("response.text empty/falsy, potentially blocked by safety settings (E: a21a78c9471f27a42c07d1c859187825)")},"fnGoModel"),u,p=0,m=[];e.modelOverrides&&e.modelOverrides.length>0?m.push(...e.modelOverrides):m.push(a),e.modelBackupOverrides&&e.modelBackupOverrides.length>0?m.push(...e.modelBackupOverrides):m.push(ct);let h=0,g=1;do{p++,g++;let b=m[h];try{u=await d(b);break}catch(E){if(E instanceof Error){let I=E.message,v=E.status??"[STATUS?]";if(I.includes(`${503}`))if(h===m.length-1)console.error(`${t}[fnGoModel][${b}] error trying to get result from model: GEMINI_ERROR_STATUS_MODEL_OVERLOADED ${503}. we are already using the final backup model in our modelsToTry, so SOL here. will try again... error (${v}): ${y(E)} (E: 9bb63cb520b8bd3bb85d2ca20715c825)`);else{h++;let w=m[h];console.error(`${t}[fnGoModel][${b}] error trying to get result from model: GEMINI_ERROR_STATUS_MODEL_OVERLOADED ${503}. will try using the next model (${w}) for this next call. error (${v}): ${y(E)} (E: b07a041bb97ea95b03cd6f9856f01525)`)}else if(I.includes(`${429}`))if(h===m.length-1)console.error(`${t}[fnGoModel][${b}] error trying to get result from model: GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED ${429}. we are already using the final backup model, so SOL here. will try again... error (${v}): ${y(E)} (E: d280c441aa37579bb2cfd29038202525)`);else{h++;let w=m[h];console.error(`${t}[fnGoModel][${b}] error trying to get result from model: GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED ${429}. will try using the next model (${w}) for this next call. error (${v}): ${y(E)} (E: a9869883fc72bf156f1691183e27ee25)`)}else console.error(`${t}[fnGoModel][${b}] error trying to get result from model. error (${v}): ${y(E)} (E: a67d595c8ed313d458369d4d0b3e7f25)`)}else console.error(`${t}[fnGoModel][${b}] (UNEXPECTED) error is not instanceof Error? The expected error from the @google/genai lib is supposed to be an instance of Error according to Gemini migration AI. (E: 15df95701e78b35f783d250801092825)`)}p>1&&await W(g*1e3)}while(!u&&p<yo);return u}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{L&&console.log(`${t} complete.`)}}async getFunctionInfoIbGibs({fcrCommentIbGib:e}){let t=`[${this.getFunctionInfoIbGibs.name}]`;try{L&&console.log(`${t} starting... (I: 976a684b7ae58cda523b17fc0c62e325)`);let o=[];if(!e)throw new Error(`${t} fcrCommentIbGib is falsy. (E: a01c80f415ab8737a81b7b2a2f479f25)`);if(!e.data)throw new Error(`${t} fcrCommentIbGib.data is falsy. (E: a03bc3662a8d6f69c1c077605727a025)`);let i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) this.metaspace falsy. (E: 997d071847c5d7e80692f48191244e25)");let r=await this.getSuperSpace();if(!r)throw new Error("(UNEXPECTED) superSpace falsy? (E: dd1600f15e1e659c01f73991656a3325)");let a=e.rel8ns?.[kn]??[];if(a.length===0)return L&&console.warn(`${t} no functionInfoAddrs (I: 5f8965e92c305689c11677a1148b7425)`),[];L&&console.log(`${t} functionInfoAddrs: ${a} (I: e7b1f5a4576c493326b913e48a505e25)`);let c=await i.get({addrs:a,space:r});if(!c.success||!c.ibGibs||c.ibGibs.length!==a.length)throw new Error(`${t} could not retrieve function info ibgibs. errorMsg: ${c.errorMsg??"unknown error (E: 164246a6661d49f2b21d1b6769139625)"} (E: 0736d824876e420f91c089925191d425)`);return o=c.ibGibs,L&&console.log(`${t} resFunctionInfoIbGibs: ${M(o.map(d=>S({ibGib:d})))} (I: a5661b5c449608f0e8d773135a599a25)`),o}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{L&&console.log(`${t} complete.`)}}async loadIbGibDto(e){let t=`[${this.loadIbGibDto.name}]`;try{if(L&&console.log(`${t} starting... (I: cb0b1e9e22fce321ca9a26e7a5d4c825)`),await super.loadIbGibDto(e),!this.data)throw new Error("(UNEXPECTED) this.data falsy after load dto? (E: 77aecd066b0bbbd0c66e2658519bdb25)");let o=this._metaspace;if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: e5762b1e3f77f84ca338641edc011225)");let i=await this.getSuperSpace(),r=f(async()=>{this.availableFunctions=new Map;for(let d of this.data.availableFunctionNameOrIds){if(!d)throw new Error("(UNEXPECTED) nameOrId falsy, driven by this.data.availableFunctionNameOrIds? somehow a falsy nameOrId saved? (E: 7b63f177624de2415e1569e96ef8d125)");let u=tt().get(d);u?this.availableFunctions.set(d,u):Ai().includes(d)?L&&console.log(`${t} function nameOrId (${d}) found as deprecated. not adding to available functions on agent. (I: 983864ad5cd8af915fb135580e455425)`):console.error(`no function info in getAllFunctionInfos() found corresponding to nameOrId (${d}) and this was not found in getDeprecatedFunctionInfoNames(). this is logged here but we're not throwing. (E: db0da9880cf1e414c3f1078d3e9f0b25)`)}let a=this.rel8ns?.system??[];if(a.length>0){let d=await o.get({addrs:a,space:i});if(!d.success||d.errorMsg)throw new Error(`couldn't get system comments. error: ${y(d.errorMsg??"unknown error (E: c0b4d7aab724bcf58e88ffd496de8825)")} (E: 7925d4b5ec3a8f7a648c109941c38a25)`);if((d.ibGibs??[]).length!==a.length)throw new Error("(UNEXPECTED) (resGet_systemComments.ibGibs ?? []).length !== rel8dAddrs_system.length, but resGet.success truthy and resGet.errorMsg falsy? (E: 2055553b602e6c2fe49e956a1e423f25)");this.commentIbGibs_system=d.ibGibs}let c=this.rel8ns?.chat??[];if(c.length>0){let d=await o.get({addrs:c,space:i});if(!d.success||d.errorMsg)throw new Error(`couldn't get chat comments. error: ${y(d.errorMsg??"unknown error (E: c0b4d7aab724bcf58e88ffd496de8825)")} (E: 7925d4b5ec3a8f7a648c109941c38a25)`);if((d.ibGibs??[]).length!==c.length)throw new Error("(UNEXPECTED) (resGet_chatComments.ibGibs ?? []).length !== rel8dAddrs_chat.length, but resGet.success truthy and resGet.errorMsg falsy? (E: 2055553b602e6c2fe49e956a1e423f25)");this.commentIbGibs_chat=d.ibGibs}},"fn");await Ht({scope:"prune",secondsValid:60,maxDelayMs:100,maxLockAttempts:1800,space:i,callerInstanceId:ze(),fn:r})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{L&&console.log(`${t} complete.`)}}};setTimeout(()=>{xe().registerFactory({classname:Ve.name,fnDtoToAgentWitness:f(async e=>e.data?e.data.classname?e.data.classname===Ve.name?{applies:!0,agent:await Gi({agentIbGib:e})}:{applies:!1}:{applies:!1}:{applies:!1},"fnDtoToAgentWitness")})});function dl({currentContextTjpAddr:n}){let e=`[${dl.name}]`;try{L&&console.log(`${e} starting... (I: 7edafbba277d57eae51af325cf7eb225)`);let t=K({ibGibAddr:n});return`Your current context ibGibAddr is ${n}
|
|
1186
|
+
It is very important that you use THIS context address. THIS context address takes precedence over previous contexts in your system chat history, because those chats may be from previous sessions per the user's POV. If there are any doubts, like if you're saying something and the user is not responding, then this may be the reason. You should call the function to get your context to be sure you are talking in the right one.`}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{L&&console.log(`${e} complete.`)}}f(dl,"getTextPartForCurrentContextTjpAddr");var Be=V,Bn=class n{static{f(this,"CreateConcreteAgentWitnessFactory_Gemini")}lc=`[${n.name}]`;arg;constructor(e){this.arg=e}async createInitialData(e){let t=`${this.lc}[${this.createInitialData.name}]`;try{Be&&console.log(`${t} starting... (I: f4c8ac488804666077cfc2237972d625)`);let{name:o,api:i,model:r,type:a,availableFunctions:c}=this.arg;if(!r)throw new Error("(UNEXPECTED) model falsy? (E: ee7286c772a37fa86236c85f96233625)");if(!e.data)throw new Error("(UNEXPECTED) superSpace.data falsy? (E: 858d5950b9ef7a0175482a51caaf9c25)");if(!e.data.uuid)throw new Error("(UNEXPECTED) superSpace.data.uuid falsy? (E: 08867535db1b254d73c050bd5086e525)");let d=te(es);return o&&(d.name=o),d.uuid=await zi(),d.superSpaceId=e.data.uuid,d.api=i,d.model=r,d.type=a,d.availableFunctionNameOrIds=c.map(u=>u.nameOrId),d.classname=Ve.name,d}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{Be&&console.log(`${t} complete.`)}}async createInitialRel8ns(){let e=`${this.lc}[${this.createInitialRel8ns.name}]`;try{return Be&&console.log(`${e} starting... (I: 2d4933ea3761bd7df701d8d306fb2825)`),Eo?te(Eo):void 0}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Be&&console.log(`${e} complete.`)}}async createWitness(){let e=`[${this.createWitness.name}]`;try{Be&&console.log(`${e} starting... (I: 36709dfa0c398d63d64c4f6ba9055625)`);let{api:t,model:o}=this.arg;if(t==="gemini"){let i=new Ve;return await i.initialized,i}else throw new Error(`(UNEXPECTED) unknown api: ${t}? only 'gemini' currently implemented (E: 2d1cb22ce787c6c42d4532c260320125)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Be&&console.log(`${e} complete.`)}}};async function Gi({agentIbGib:n}){let e=`[${Gi.name}]`;try{Be&&console.log(`${e} starting... (I: 5a4efefba9e4bdfb942afbe7919fff25)`);let t=new Ve;return await t.initialized,await t.loadIbGibDto(n),t.fnGetAPIKey=async()=>await br({dbName:hr(),storeName:await mr(),key:await gr()})??"",t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Be&&console.log(`${e} complete.`)}}f(Gi,"agentIbGibDtoToWitness");var Z=V;async function mo({metaspace:n,space:e,createIfNone:t}){let o=`[${mo.name}]`;try{if(Z&&console.log(`${o} starting... (I: ad1594767abce66ca80fea8c8d89f325)`),e??=await n.getLocalUserSpace({lock:!1}),!e)throw new Error("(UNEXPECTED) space falsy after getting local user space? (E: bc68d97d46dcf1d15dd74edba200b725)");let i=await ur({metaspace:n,space:e});if(!i.rel8ns)throw new Error("(UNEXPECTED) tagsIbGib.rel8ns falsy? (E: dc50e8d218fe5e30bbaec7f37d484525)");let a=(i.rel8ns[Qi]??[]).filter(u=>{let{ib:p}=F({ibGibAddr:u});return p===sr}),c,d;if(a.length===0){if(t){Z&&console.log(`${o} creating new agents tag... (I: 47f4f4fa89f1a1bba960e0a6ff5f5225)`);let{newTagIbGib:u}=await n.createTagIbGib({text:or,icon:ir,description:rr,space:e});return d=u,Z&&console.log(`${o} creating new agents tag complete. (I: 5f41d644f2b692348377f918057cf225)`),u}}else a.length===1?(c=a.at(0),Z&&console.log(`${o} exactly one agent tag addr found (${c}) in space (${e.ib}) (I: 7ef995963313c966216097760d0cdb25)`)):(c=a.at(0),console.error(`${o} more than one agent tag found in space (${e.ib})? Well, we're returning just the first one (${c}), but really we've not coded for this edge/future case. (E: 52a4e2e49d3c0d644df483119b46f125)`));if(c){let u=await n.get({addrs:[c],space:e});if(u.success&&u.ibGibs?.length===1)return d=u.ibGibs.at(0),d;throw new Error(`couldn't get agentTagAddr (${c}) in space (${e.ib}) (E: 53d9cdb7b769014a2de15871484cc325)`)}else throw new Error(`agentTagAddr not found, so there ain't no agents tag, and createIfNone was ${t}. (E: 54cb3164a118105f187e936613ff4625)`)}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{Z&&console.log(`${o} complete.`)}}f(mo,"getTag_Agents");async function Wt({metaspace:n,type:e,spaceId:t,space:o}){let i=`[${Wt.name}]`;try{if(Z&&console.log(`${i} starting... (I: 41037d1926051c4b051769069f518f25)`),o??=await n.getLocalUserSpace({localSpaceId:t,lock:!1}),!o)throw new Error(`couldn't get local user space by id (${t}) (E: fe96076e79fb227c0ae2de077eb5e225)`);if(!await n.getSpecialIbGib({type:e,initialize:!0,dontWarnIfNotExist:!0,lock:!1,space:o}))throw new Error("(UNEXPECTED) couldn't initialize/get agents special ibgib? (E: 1abe0e2543711744adbdb7026b242e25)");let a=await n.getSpecialRel8dIbGibs({rel8nName:Qe,type:e,space:o})??[],c=[];for(let d of a){if(d.data?.api!=="gemini")throw new Error("(UNEXPECTED) agentIbGib.data.api !== gemini? only gemini is implemented right now. (E: 7348fe8c68565bcf88a4052458f42d25)");let u=xe(),p=await u.getLatestAgent({id:d.data.uuid});if(!p){if(p=await u.getAgentWitnessFromDto({dto:d}),!p){debugger;throw new Error(`(UNEXPECTED) couldn't get actual agent witness from agent dto? have we registered classname (${d.data?.classname}) and factory fn with agents service? (E: bcbfdf6446793ac34d6f6118e050d325)`)}await u.updateOrSetLatestAgent({agent:p,throwIfNewerFound:!1})}c.push(p)}return c}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{Z&&console.log(`${i} complete.`)}}f(Wt,"getAgents");async function $i({metaspace:n,type:e,space:t,newAgentIbGib:o}){await f(async()=>{let r=`[${$i.name}]`;try{if(Z&&console.log(`${r} starting... (I: bf6ff6bf4132eaa943eaa3af1ee17225)`),!o.data)throw new Error("(UNEXPECTED) newAgentIbGib.data falsy? (E: 26e03d0a8e286ac3a13b678a50c87a25)");if(!o.data.uuid)throw new Error("(UNEXPECTED) newAgentIbGib.data.uuid falsy? (E: 31b753e01275272484ea93e3dfe53225)");let c=await xe().getLatestAgent({id:o.data.uuid});if(c&&c.data.n>o.data.n){debugger;throw new Error(`latestInMemory.data!.n! > newAgentIbGib.data.n! ... in plain english, this means that there is a more recent (higher n) agent with the given agent's id (${o.data.uuid}) already in existence, but the caller is trying to update the special ibgib index with the older agent. (E: 5c0c028075736f22072c55e20a0c7e25)`)}let d=S({ibGib:o});await Ge({type:o.data.type,rel8nInfos:[{rel8nName:Qe,ibGibs:[oe({ibGib:o})]}],metaspace:n,space:t})}catch(a){throw console.error(`${r} ${y(a)}`),a}finally{Z&&console.log(`${r} complete.`)}},"fn")()}f($i,"updateAgentIndex");async function Ri({ibGib:n,metaspace:e,space:t}){let o=`[${Ri.name}]`;try{if(Z&&console.log(`${o} starting...`),!n)throw new Error("ibGib required (E: 753a0aa13e4e5ea20d7f6bb92d963625)");let i=await Bt({ibGib:n,metaspace:e,space:t,scope:"agent",skipGetLatest:!1});if(!i){console.warn(`${o} couldn't find agent for domain ibGib (${n.ib}) (W: 9536a8e67fe83ddc819c476f5a50c825)`);return}let r=se({ibGib:n,defaultIfNone:"incomingAddr"}),a=S({ibGib:i}),d=await xe().getAgentByAddr({agentAddr:a,metaspace:e,spaceId:t.data.uuid});return Z&&console.log(d?`${o} complete. Found agent ${S({ibGib:d})} for domain ${r}`:`${o} complete. No agent found for ibgib tjp ${r}`),d}catch(i){throw console.error(`${o} ${y(i)}`),i}}f(Ri,"getAgentForDomainIbGib");function ho(n){let e=`[${ho.name}]`;try{Z&&console.log(`${e} starting... (I: 2a9899514ac6e478eb55819a57fd9725)`);let{api:t}=n;switch(t){case"gemini":return new Bn(n);default:throw new Error(`(UNEXPECTED) api: ${t}? only 'gemini' currently implemented? (E: 071fedab181fda80666858c14ea73625)`)}}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Z&&console.log(`${e} complete.`)}}f(ho,"getConcreteAgentFactory");function lt({tagText:n,contentText:e,randomIdLength:t}){let o=`[${lt.name}]`;try{Z&&console.log(`${o} starting... (I: 94104ec059c89d4ba458d96580791d25)`);let i=t?`${n}|${nt({count:t})}`:n;return[`[${i} begin]`,e,`[${i} end]`].join(`
|
|
1187
|
+
`)}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{Z&&console.log(`${o} complete.`)}}f(lt,"taggifyForPrompt");function Et({textSrc:n,other:e}){let t=`[${Et.name}]`;return e?[n,ze(),e].join("_"):[n,ze()].join("_")}f(Et,"getAddlMetadataTextForAgentText");function Rt({addlMetadataText:n,ifError:e="warn"}){let t=`[${Et.name}]`;try{Z&&console.log(`${t} starting... (I: 89b8b19a8d785b945fe0f816df762d25)`);let[o,i,...r]=n.split("_");if(!o)throw new Error("addlMetadataText.textSrc falsy (E: 40bbec4269c1688ab1390fa5d5440325)");if(!Xr(o))throw new Error(`addlMetadataText.textSrc (${o}) is unexpected value. Expected one of ${co} (E: 02bae41275a39210e5737548747bd825)`);if(!i)throw new Error("addlMetadataText.timestampInTicks falsy (E: 03cbbc7515a1cff1fc7c12e3947c6825)");let a=Number.parseInt(i);if(Number.isNaN(a))throw new Error(`invalid timestampInTicks (${i}): value should be an integer but parse is NaN (E: 9d31e3563d972c02553ce18a19a19b25)`);return{textSrc:o,timestampInTicks:a,other:r.length>0?r:void 0}}catch(o){let i=`${t} ${y(o)}`;switch(e){case"ignore":return{textSrc:X.UNKNOWN,timestampInTicks:0,errorMsg:y(o)};case"warn":return console.warn(`${t} ${i} (W: 3e1f4a98ad6461c9bd96462841c31b25)`),{textSrc:X.UNKNOWN,timestampInTicks:0,errorMsg:y(o)};default:throw console.error(`${t} ${i} (E: 6396ed44947c52adf85788e1adc22825)`),new Error(i)}}finally{Z&&console.log(`${t} complete.`)}}f(Rt,"parseAddlMetadataTextForAgentText");function go({data:n}){let e=`[${go.name}]`,{name:t,uuid:o,type:i}=n;if(!t)throw new Error(`${e} data.name falsy (E: 4c172c5b8a110ae26479b8c4006f3225)`);if(!o)throw new Error(`${e} data.uuid falsy (E: 67d2c79ac39e70e5ecfd1745e1fd3525)`);if(!i)throw new Error(`${e} data.type falsy (E: 53bf1f9a145a16be81296437682a7a25)`);if([t,o,i].some(a=>a.includes(" ")))throw new Error("invalid data. ib must not contain spaces in name, uuid, type. (E: 36a56e4685163848458be06f51d4ad25)");return[st,t,o,i].join(" ")}f(go,"getAgentIb");function Zr({ib:n}){let[e,t,o,i]=n.split(" ");if(e!==st)throw new Error(`invalid ib. first term expected to e an atom: ${st} (E: 3c01d42035d2e32c4bfd5c1bf363f725)`);if(!t)throw new Error("invalid ib. name falsy in agent ib (E: 8b494c544f05b8ef9c866078b761a725)");if(!o)throw new Error("invalid ib. uuid falsy in agent ib (E: aba195db3ddcb000324ebed15351b725)");if(!i)throw new Error("invalid ib. type falsy in agent ib (E: 8c814772394ae76342f95e885570c325)");return{atom:e,name:t,uuid:o,type:i}}f(Zr,"parseAgentIb");async function Vn({ibGib:n}){let e=`[${Vn.name}]`;try{Z&&console.log(`${e} starting... (I: f9a733a5a05b7f7494836d86a79e2d25)`);let t=await ot({ibGib:n})??[];if(!Ye({ibGib:n}))return t.push(`${e} not a comment ibgib (E: 08676d94c698c6e42e6c35e94a58f125)`),t;let{safeIbCommentMetadataText:o}=Ke({ib:n.ib});if(o){let i=Rt({addlMetadataText:o,ifError:"warn"});i.errorMsg&&t.push(`${e} could not parse addlMetadataText: ${i.errorMsg} (E: e178265c33e5e94947a02c1f9d6a7425)`)}else t.push(`${e} addlMetadataText falsy. this implies something is incorrect with the comment's ib, as we expect agent comments to have certain metadata (e.g. textSrc). See AgentWitness_V1 (and data interface) for more info. (E: 7c3c41c973a67256c432604666106b25)`);return t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Z&&console.log(`${e} complete.`)}}f(Vn,"validateAgentWitnessCommentIbGib");var qn="settings",Nh="general",$h="text-editor",Gh="projects",Rh="projects-explorer",Mh="projects-dropdown",Dh="project",kh="minigame",Lh="chronologys",Uh="identity-manager",ee={general:Nh,textEditor:$h,projects:Gh,projectsExplorer:Rh,projectsDropdown:Mh,project:Dh,minigame:kh,chronologys:Lh,identityManager:Uh},Fh=Object.values(ee);var Mi={type:ee.general,editor:void 0,readonly:!0,viewer:"ibgib-raw-viewer"},Di={type:ee.textEditor,wrap:"wrap"},Hh={type:ee.project,openChildTjpAddrs:[],activeChildTjpAddr:void 0,lensMode:"raw"},Vh={type:ee.minigame},Bh={type:ee.chronologys,openChildTjpAddrs:[],activeChildTjpAddr:void 0},qh={type:ee.identityManager,openChildTjpAddrs:[],activeChildTjpAddr:void 0},ul={sections:{},children:{}};var qe=V;async function ki({ibGib:n}){let e=`[${ki.name}]`;try{qe&&console.log(`${e} starting... (I: 57ac4c0a3448bc5e98ecf5bfb02ce825)`);let{ib:t}=F({ibGib:n}),o=t.split(" ").at(0);if(!o)throw new Error("(UNEXPECTED) atom falsy? we split the ib by spaces (space-delimiter). this makes no sense. (E: 6a9ea640ae38823aeefc6ec82a05d625)");return`${qn}_${o}`}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{qe&&console.log(`${e} complete.`)}}f(ki,"getSettingsScope");async function pe({settingsType:n,useCase:e}){let t=`[${pe.name}]`;try{if(qe&&console.log(`${t} starting... (I: f13dff111048421cad5453f821487825)`),e.includes("_"))throw new Error("(UNEXPECTED) settingsType.includes('_')? should be kebab-cased or camelCased (E: 8f75e89b9378819ab882cc1870f1e825)");if(n.includes("_"))throw new Error("(UNEXPECTED) settingsType.includes('_')? should be kebab-cased or camelCased (E: 1d316b0808287c12689d1e882648b825)");return[n,e].join("_")}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{qe&&console.log(`${t} complete.`)}}f(pe,"getSectionName");async function On({sectionName:n,settingsIbGib:e}){let t=`[${On.name}]`;try{if(qe&&console.log(`${t} starting... (I: 266554b13f6ce6daa85c882f04805825)`),!e.data)throw new Error("(UNEXPECTED) settingsIbGib.data falsy? (E: dd3708f0515fb0b4d4024f4d336a3625)");if(!e.data.sections)throw new Error("(UNEXPECTED) settingsIbGib.data.sections falsy? what was the settingsIbGib even created for? (E: 31f85898a1c854e13440e278a79ceb25)");return(e.data.sections??{})[n]}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{qe&&console.log(`${t} complete.`)}}f(On,"getSettingsSection");function fl({scope:n}){let e=`[${fl.name}]`;try{return n.includes(" ")&&(console.warn(`${e} scope includes one or more spaces. These will be converted to double underscores. (W: 75a53c623d3110b5e874e5789b414325)`),n=n.replace(/ /g,"__")),`${qn} ${n}`}catch(t){throw console.error(`${e} ${y(t)}`),t}}f(fl,"getSettingsIb");async function Li({scope:n,metaspace:e,space:t,saveInSpace:o}){let i=`[${Li.name}]`;try{let r=fl({scope:n}),a=await pl(),d=await ne.firstGen({parentIbGib:ne.primitive({ib:qn}),ib:r,data:a,rel8ns:void 0,dna:!0,nCounter:!0,tjp:{timestamp:!0,uuid:!0}});if(o){if(!e)throw new Error("metaspace falsy but saveInSpace is true (E: f91adfe38d78e6e4f8bca278fce37925)");await e.persistTransformResult({resTransform:d,space:t}),await e.registerNewIbGib({ibGib:d.newIbGib,space:t})}return d}catch(r){throw console.error(`${i} ${y(r)}`),r}}f(Li,"createSettings");async function pl(){let n=`[${pl.name}]`;try{qe&&console.log(`${n} starting... (I: 3d7cc3f242cc88ad28dafaf85d646a25)`);let e=te(ul),t=await pe({settingsType:"general",useCase:"default"}),o=await pe({settingsType:"general",useCase:"current"});e.sections[t]=te(Mi),e.sections[o]=te(Mi);let i=await pe({settingsType:"text-editor",useCase:"default"}),r=await pe({settingsType:"text-editor",useCase:"current"});return e.sections[i]=te(Di),e.sections[r]=te(Di),e}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{qe&&console.log(`${n} complete.`)}}f(pl,"getDefaultSettingsData");var P=V,ge=class n{static{f(this,"IbGibDynamicComponentMetaBase")}lc=`[${n.name}]`;componentName="";routeRegExp=void 0;fnHandleRoute=void 0;fnGetMetaspace;bootstrapPromise;constructor({fnGetMetaspace:e,bootstrapPromise:t}){this.fnGetMetaspace=e,this.bootstrapPromise=t}},Oe=class n extends HTMLElement{static{f(this,"IbGibDynamicComponentInstanceBase")}lc=`[${n.name}]`;elements;createdPromise;settings;get agent(){return this.agents.at(0)}agents=[];get ib(){let{ib:e}=F({ibGibAddr:this.ibGibAddr??z});return e}get gib(){let{gib:e}=F({ibGibAddr:this.ibGibAddr??z});return e}ibGibAddr=z;ibGibProxy;get ibGib(){let e=this.ibGibAddr??z,{ib:t,gib:o}=F({ibGibAddr:e});return this.ibGibAddr&&!wt({gib:o})?this.ibGibProxy?.ibGib:ne.primitive({ib:t})}get tjpAddr(){return this.ibGib?se({ibGib:this.ibGib,defaultIfNone:"incomingAddr"}):void 0}meta;html;css;static get observedAttributes(){return["ibGibAddr"]}_instanceId;get instanceId(){return this._instanceId}agentsInitialized;connectedCount=0;_isBusy=!1;get isBusy(){return this._isBusy}showBusy({isBusy:e,title:t,msg:o,localOnly:i,animationEmoji:r}){let a=`${this.lc}[${this.showBusy.name}]`;try{this._isBusy=e,i?this.dispatchEvent(new CustomEvent(Tt,{detail:{isBusy:e,title:t,msg:o,animationEmoji:r},bubbles:!0,composed:!0})):window.dispatchEvent(new CustomEvent(Tt,{detail:{isBusy:e,title:t,msg:o,animationEmoji:r}}))}catch(c){throw console.error(`${a} ${y(c)}`),c}}async getMetaspace(){let e=`${this.lc}[${this.getMetaspace.name}]`;try{if(P&&console.log(`${e} starting... (I: 956418cf932823bc767ccc6a0fd2b325)`),!this.meta)throw new Error("(UNEXPECTED) this.meta falsy? (E: dd2bfae6c0e84b1d58c72e2922b51325)");return await this.meta.fnGetMetaspace()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}constructor(){super(),this._instanceId=nt({count:8})}async initialize(e){let{ibGibAddr:t,meta:o,html:i,css:r}=e,a=`${this.lc}[${this.initialize.name}]`;try{P&&console.log(`${a} starting... (I: c9b94131bc2f0d20e1397c214dad6725)`),this.ibGibAddr=t,this.meta=o,this.html=i,this.css=r,this.attachShadow({mode:"open"}),await this.meta.bootstrapPromise}catch(c){throw console.error(`${a} ${y(c)}`),c}finally{P&&console.log(`${a} complete.`)}}async initAgents(){let e=`${this.lc}[${this.initAgents.name}]`;P&&console.log(`${e} does nothing in base class (I: 0b31a650b942619a0e36a1a7f763e825)`)}async connectedCallback(){let e=`${this.lc}[${this.connectedCallback.name}]`;try{P&&console.log(`${e} starting... (I: 01bbbf69f1c75b03a29e7a85ebd2c725)`),this.connectedCount++,this.connectedCount===1?await this.connectedCallback_initComponent():await this.connectedCallback_reconnectComponent()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async connectedCallback_initComponent(){let e=`${this.lc}[${this.connectedCallback_initComponent.name}]`;try{if(P&&console.log(`${e} starting... (I: bc4af3f6751d841f51bad19e334efa25)`),!this.html)throw new Error("(UNEXPECTED) this.html is falsy? (E: a0a0ab7c8f987d78058dd7cad09a5125)");let t=document.createElement("template");if(t.innerHTML=this.css?`
|
|
1188
1188
|
<style>
|
|
1189
1189
|
${this.css.join(`
|
|
1190
1190
|
`)}
|
|
1191
1191
|
</style>
|
|
1192
1192
|
${this.html}
|
|
1193
|
-
`:this.html,!this.shadowRoot)throw new Error("(UNEXPECTED) this.shadowRoot is falsy? (E: 1a3cf77d87767aaff37d31657ee73f25)");this.shadowRoot.appendChild(t.content),this.createdPromise=this.created(),await this.createdPromise}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async connectedCallback_reconnectComponent(){let e=`${this.lc}[${this.connectedCallback_reconnectComponent.name}]`;try{P&&console.log(`${e} starting... (I: 7fccefbeff68c0dda15642ebaa1eb525)`),console.log(`${e} does nothing in base class (I: 724bc670d4ccb0fde2b2fa49830cd425)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async disconnectedCallback(){let e=`${this.lc}[${this.disconnectedCallback.name}]`;try{P&&console.log(`${e} starting... (I: 6f3b25c23fb874b1ac513e8f0d1f4e25)`),await this.disconnected()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async attributeChangedCallback(e,t,o){let i=`${this.lc}[attributeChangedCallback]`;P&&console.log(`${i} starting... (I: 33cd68579171582166d25d8898640f25): ${e} ${t} => ${o}`),console.warn(`${i} nothing done in base class atow (W: 9eb93eb8fde7c0058c79cea841936a25)`)}async destroy(){let e=`${this.lc}[${this.destroy.name}]`;try{P&&console.log(`${e} starting... (I: 536989c9491b544105b6d01a688fbb25)`),await this.destroyed()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async destroyed(){let e=`${this.lc}[${this.destroyed.name}]`;try{P&&console.log(`${e} starting... (I: f34f3ca04b06b1e00ebe04df22331125)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}return P&&console.log(`${e} does nothing in the base class. (I: d9437f962e0aec40d69ad6159e7b5725)`),Promise.resolve()}async loadIbGib(e){let t=`${this.lc}[${this.loadIbGib.name}]`;try{P&&console.log(`${t} starting... (I: 4dcb1b7a3d86f3415ca7224c07126925)`);let o=e?.getLatest??!1;if(this.ibGib){console.warn(`${t} this.ibGib already loaded. idempotently returning early without doing anything. (W: 15498d346a32e884acec108cb3c8ee25)`);return}if(
|
|
1194
|
-
agent.data: ${M(
|
|
1195
|
-
ibGib.data: ${se({ibGib:this.ibGib})} (W: cb22e8b064d8c2d7b3b2c488ed169225)`),this.agents=[r]}else if(e)console.warn(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${S({ibGib:this.ibGib})}) (W: e4219903462baab438a23c786d714825)`);else throw new Error(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${S({ibGib:this.ibGib})}) (E: 7182d1aa070b9578c78a5b8b401d8425)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{P&&console.log(`${t} complete.`)}}async getSettings({settingsType:e,useCase:t}){let o=`${this.lc}[${this.getSettings.name}]`;try{if(P&&console.log(`${o} starting... (I: 00c8dbedd2e8a8b988cc45f4186efd25)`),!this.settings)throw new Error("(UNEXPECTED) this.settings falsy? shouldn't this be initialized by now? (E: ceae480e28fab1da38b8def8b1060d25 (E: dc7d984c1c64293a3c3e0628dedadb25)");if(!this.settings.ibGib)throw new Error("(UNEXPECTED) this.settings.ibGib falsy? shouldn't this be initialized by now? especially since this.settings is truthy? (E: faef6878abaf00a4a6a6f6b85ce8c825)");let i=await On({sectionName:await pe({settingsType:e,useCase:t}),settingsIbGib:this.settings.ibGib});return i||P&&console.log(`${o} settingsSection does not exist. returning undefined. (I: 0462d83f5ae8049708274b88e9b0d825)`),i}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{P&&console.log(`${o} complete.`)}}async updateSettings({settingsType:e,useCase:t,newSectionInfo:o}){let i=`${this.lc}[${this.updateSettings.name}]`;try{P&&console.log(`${i} starting... (I: 80ce98cf386e0c04d30e8b15ac0f2925)`);let r=await pe({settingsType:e,useCase:t}),l=await it({timeline:this.settings.ibGib,metaspace:await this.getMetaspace(),mut8Opts:{dataToAddOrPatch:{sections:{[r]:o}}}});await W(100)}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{P&&console.log(`${i} complete.`)}}async getCurrentSettings({settingsType:e}){let t=`${this.lc}[${this.getCurrentSettings.name}]`;try{if(P&&console.log(`${t} starting... (I: da0baee73e386089a8c059f83cc43825)`),!this.settings)return;let o=await pe({settingsType:e,useCase:"current"});return On({sectionName:o,settingsIbGib:this.settings.ibGib})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{P&&console.log(`${t} complete.`)}}async initSettings(){let e=`${this.lc}[${this.initSettings.name}]`;try{if(P&&console.log(`${e} starting... (I: acfee8787d32a6075442e2887a386a25)`),!this.ibGib)throw new Error("(UNEXPECTED) this.ibGib falsy? (E: 8ce2e73bea87b9330b131778a3981825)");let t=await this.getMetaspace(),o=await t.getLocalUserSpace({lock:!1});if(!o)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: f77ce7269a6f0d7ad8978349b4c6cd25)");if(vt({ibGib:this.ibGib})){console.error(`${e} this.ibGib is primitive, so what are we initializing settings for? (W: 9915089019b81c6935b32ae877095825)`);return}let i=await Mi({ibGib:this.ibGib}),r=await Bt({scope:i,ibGib:this.ibGib,metaspace:t,space:o});if(r||(r=(await Di({scope:i,metaspace:t,space:o,saveInSpace:!0})).newIbGib,await eo({scope:i,domainIbGib:this.ibGib,localIbGib:r,metaspace:t,space:o})),!r)throw new Error("(UNEXPECTED) settings falsy still? should be initialized. (E: a179adcbbab800cff849b8aa95fbe425)");let l=new Ue;if(await l.setWrappedIbGib({ibGib:r,space:o}),this.settings=l,!await this.getCurrentSettings({settingsType:ee.general}))throw new Error("(UNEXPECTED) no current general settings? the settings should have been updated with this upon creation. (E: d10fd8d42b58d917180293a713009825)")}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async exportIbGib({ibGib:e,compress:t}){let o=`${this.lc}[${this.exportIbGib.name}]`;try{P&&console.log(`${o} starting... (I: 623d9463d919683be81f749821a95825)`);let i=await this.getMetaspace();if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: 3d15dbd074ac0c15b834a788d0b57d25)");if(vt({ibGib:e}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let r=await i.getLocalUserSpace({lock:!1});if(!r)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: 7bb735be58282f1bd7abe5d9ffabb525)");await ur({ibGib:e,compress:t,metaspace:i,space:r})}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{P&&console.log(`${o} complete.`)}}async importIbGib({exportIbGibJsonString:e,rel8nName:t,force:o,skipRegisterTimelines:i,divergentTimelineStrategy:r}){let l=`${this.lc}[${this.importIbGib.name}]`;try{let c=await this.getMetaspace(),d=await c.getLocalUserSpace({lock:!1});if(!d)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: 947c983e57a91aa00c8c185320354325)");let[u,p]=await dr({exportIbGibJsonString:e,metaspace:c});if(!u.data)throw new Error("(UNEXPECTED) rawExportIbGib.data falsy? this is assumed validated at this point. (E: 6bc4e84db08e3c6228b2c40c2ea50825)");let m=u.data.contextIbGibAddr,h=!1;if(!o){let g=await c.get({addr:m,space:d});g.success&&(g.ibGibs??[]).length===1&&(console.log(`${l} export's ibGib addr (${m}) already exists in the space, so we're skipping doing any physical importing of the export's graph. (I: 429b5bdcd0585c697869f568c4673825)`),h=!0)}if(!h){jn;let g=[],b=[];Object.values(p).forEach(N=>{zi({ibGib:N})?g.push(N):b.push(N)});let E=await c.put({ibGibs:g,isDna:!0,space:d,force:o});if(!E.success||E.errorMsg)throw new Error(`there was an error putting the export's dna ibgibs into the space (${d.ib}). error: ${E.errorMsg||"[unknown error (E: 7c7ef8d5281399b1d8f3fbeefba1b825)]"} (E: ce3e8b982208afc4889164ba20a31825)`);let{mapWithTjp_YesDna:I,mapWithTjp_NoDna:v,mapWithoutTjps:w}=jn({ibGibs:b}),T=await c.put({ibGibs:Object.values(w),space:d,force:o});if(!T.success||T.errorMsg)throw new Error(`there was an error putting the export's non-dna stone ibgibs (no-tjp) into the space (${d.ib}). error: ${T.errorMsg||"[unknown error (E: dc17f8ee7aed5c445f8b827f274b0825)]"} (E: 9561364961e89c132818f6784a607825)`);let C={...I,...v},A=Object.values(C),G=await c.put({ibGibs:A,space:d,force:o});if(!G.success||G.errorMsg)throw new Error(`there was an error putting the export's timeline ibgibs into the space (${d.ib}). error: ${G.errorMsg||"[unknown error (E: be4a28961574765798c8d3686ae89c25)]"} (E: 066796a23da3c9f748558fd25bfdf525)`);if(!i){let N=er({ibGibs:A}),H=Object.values(N);for(let x of H){let D=x.at(-1);if(!D)throw new Error("(UNEXPECTED) latestInTimeline falsy? this would mean that we had an empty timeline, and this doesn't make sense... (E: 3bec09e79768cc39d8029f4fe3af9825)");let J=await c.getLatestAddr({ibGib:D,space:d});!1||await c.registerNewIbGib({ibGib:D,space:d})}}}throw new Error("not implemented (E: 66c308e420e848c8d7cd01c8fddf8425)")}catch(c){throw console.error(`${l} ${y(c)}`),c}finally{P&&console.log(`${l} complete.`)}}},Mt=class extends Oe{static{f(this,"IbGibDynamicComponentInstanceBase_Parent")}childInfos=[];get activeChildInfo(){return this.childInfos.find(e=>e.active)}async activateIbGib({addr:e,ibGib:t}){let o=`${this.lc}[${this.activateIbGib.name}]`;try{let h=function(g){let b=F({ibGibAddr:g.addr}).gib;return(K({gib:b}).tjpGib??b)===m};var i=h;for(f(h,"tabInfoSharesTjpGib"),P&&console.log(`${o} starting... (I: 05015d78983488496dcca4fa36718725)`);!this.createdPromise;)await W(50);if(await this.createdPromise,!this.elements)throw new Error("(UNEXPECTED) this.elements falsy? (E: fa221c138f211ee93c717c9dd0cf3225)");let{contentEl:r}=this.elements;if(!t&&!e)throw new Error("(UNEXPECTED) both ibGib and addr falsy? (E: 529fb88738cdacb10aea87b8450f2525)");if(t&&e&&S({ibGib:t})!==e)throw new Error("(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: c99a94d8744e3a720cdbc094d53c4e25)");e??=S({ibGib:t});let l=await le(),c=await this.getLoadedChildInfo({addr:e,ibGib:t});if(c.active){console.log(`${o} same tab already active. returning early. childInfo.addr: ${c.addr} (user just clicked on the same tab) (I: e67c0d02f3143c49c7a20c82d0730225)`);return}let d=this.activeChildInfo;d&&(d.childBtnEl.classList.remove("active"),d.active=!1,r.innerHTML=""),c.childBtnEl.classList.add("active"),c.childBtnEl.scrollIntoView({behavior:"smooth"}),c.active=!0;let u=F({ibGibAddr:e}).gib,m=K({gib:u}).tjpGib??u;if(this.childInfos.some(g=>h(g))||this.childInfos.push(c),!c.component)throw new Error("(UNEXPECTED) childInfo.component falsy? should be populated by this point in code (E: 77abfd1e8cd395605d46716bd087fb25)");await l.inject({parentEl:r,componentToInject:c.component})}catch(r){throw console.error(`${o} ${y(r)}`),r}finally{P&&console.log(`${o} complete.`)}}},zn=class n extends Mt{static{f(this,"IbGibDynamicComponentInstanceBase_ParentOfTabs")}lc=`[${n.name}]`;get isBusy(){return this._reloadingTabs}_reloadingTabs=!1;get reloadingTabs(){return this._reloadingTabs}set reloadingTabs(e){let t=e!==this._reloadingTabs;this._reloadingTabs=e,t&&this.renderUI_busy()}async closeTab({ibGib:e}){let t=`${this.lc}[${this.closeTab.name}]`;try{P&&console.log(`${t} starting... (I: e0d5f8ed67b8a7f43822fa3843fd4525)`);let o=S({ibGib:e}),i=re({ibGib:e,defaultIfNone:"incomingAddr"});if(!i)throw new Error(`(UNEXPECTED) tjpAddr false after incomingAddr default? ibGib: ${M(e)} (E: 707988b4d22a27c1287aa5a815d88825)`);let r=await this.getLoadedChildInfo({addr:o,ibGib:e}),l=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(!l)throw new Error(`(UNEXPECTED) settings_current falsy for this project? this.ibGib: ${M(this.ibGib)} (E: ecea08dcacd198bb38cc44a860cc6825)`);if(!l.openChildTjpAddrs.includes(i))throw new Error(`${t} (UNEXPECTED) projectSettings didn't have the tjpAddr (${i})? projectSettings: ${M(l)} (E: genuuid)`);let c=l.openChildTjpAddrs.filter(g=>g!==i),d;if(l.activeChildTjpAddr===i)if(c.length>0){let g=l.openChildTjpAddrs.indexOf(i)-1;g<0&&(g=0),d=l.openChildTjpAddrs.at(g)}else d=this.tjpAddr,c.push(this.tjpAddr);let u=await pe({settingsType:this.settingsType,useCase:"current"}),p={...l,openChildTjpAddrs:c},m=await this.getMetaspace(),h=await it({timeline:this.settings.ibGib,metaspace:m,mut8Opts:{dataToAddOrPatch:{sections:{[u]:p}}}});r.active&&await this.activateIbGib({addr:d}),this.childInfos=this.childInfos.filter(g=>g.addr!==r.addr),await this.removeTabBtn({tabInfo:r})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{P&&console.log(`${t} complete.`)}}async reopenOldTabs(){let e=`${this.lc}[${this.reopenOldTabs.name}]`;try{P&&console.log(`${e} starting... (I: 195e7d34b3f8b761aa78dd384011f825)`);let t=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(!t)throw new Error("(UNEXPECTED) settings falsy? these should be initialized before now. (E: 2003ab77e01448d638216fc82aff5f25)");this.reloadingTabs=!0,await this.renderUI_busy();let o;try{for(let i of t.openChildTjpAddrs)o=i,await this.activateIbGib({addr:i})}catch(i){throw console.error(`${e} error during activating child ibGib tabs. childTjpAddr: ${o??"[unset?]"} (E: 0396b2e24d08f42ac94510bb718a1725)`),i}finally{this.reloadingTabs=!1}await this.activateIbGib({addr:t.activeChildTjpAddr})}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}},Jn=class extends Oe{static{f(this,"IbGibFormInstanceBase")}setLoading(e,t="#btn-submit, #btn-generate",o){if(!this.shadowRoot)return;let i=this.shadowRoot.querySelector(t);if(i)if(i.disabled=e,e)i.setAttribute("data-loading","true"),o&&(i.setAttribute("data-original-text",i.textContent||""),i.textContent=o);else{i.removeAttribute("data-loading");let r=i.getAttribute("data-original-text");r!==null&&(i.textContent=r,i.removeAttribute("data-original-text"))}}setStatus(e,t,o="status-area",i="status-text"){if(!this.shadowRoot)return;let r=this.shadowRoot.getElementById(o),l=this.shadowRoot.getElementById(i);l&&(l.textContent=e,l.className=`status-msg ${t}`),r&&(e?r.classList.remove("hidden"):r.classList.add("hidden"))}dispatchShellMessage(e,t){this.dispatchEvent(new CustomEvent(ar,{detail:{message:e,level:t,source:this.tagName.toLowerCase()},bubbles:!0,composed:!0}))}validateForm(e="form"){if(!this.shadowRoot)return!0;let t=this.shadowRoot.querySelector(e);if(t)return t.checkValidity();let o=this.shadowRoot.querySelectorAll("input, select, textarea"),i=!0;for(let r of Array.from(o)){let l=r;if(!l.checkValidity()){i=!1,l.reportValidity();break}}return i}validateInputPattern({input:e,pattern:t,errorMessage:o,required:i=!0}){if(!e)return!0;let r=e.value.trim();if(!r&&!i)return e.classList.remove("invalid"),e.setCustomValidity(""),!0;let l=t.test(r);return l?(e.classList.remove("invalid"),e.setCustomValidity("")):(e.classList.add("invalid"),e.setCustomValidity(o),e.reportValidity()),l}showBusy({isBusy:e,title:t,msg:o,localOnly:i,submitBtnSelector:r,loadingText:l,animationEmoji:c}){let d=`${this.lc}[${this.showBusy.name}]`;try{this.setLoading(e,r,l),this.toggleAllInputsDisabled(e),super.showBusy({isBusy:e,title:t,msg:o,localOnly:i,animationEmoji:c})}catch(u){throw console.error(`${d} ${y(u)}`),u}}toggleAllInputsDisabled(e){if(!this.shadowRoot)return;this.shadowRoot.querySelectorAll("input, select, textarea, button").forEach(o=>{o.id==="btn-submit"||o.id==="btn-generate"||(o.disabled=e)})}};var fl="ibgib-keystone-creator",Wn=class extends ge{static{f(this,"KeystoneCreatorComponentMeta")}lc="[KeystoneCreatorComponentMeta]";routeRegExp=new RegExp(`^${fl}$`);componentName=fl;constructor(){super(Ce()),customElements.get(this.componentName)||customElements.define(this.componentName,Li)}async createInstance({path:e,ibGibAddr:t}){let o=`${this.lc}[${this.createInstance.name}]`,i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:Mr,css:[Ae,Gr]}),i}},Li=class extends Jn{static{f(this,"KeystoneCreatorComponentInstance")}lc="[KeystoneCreatorComponentInstance]";hasExistingIdentities=!1;constructor(){super()}async initialize(e){await super.initialize(e)}async created(){this.elements={},this.elements.containerEl=this.shadowRoot.getElementById("container"),this.elements.titleEl=this.shadowRoot.getElementById("title"),this.elements.btnGenerateEl=this.shadowRoot.getElementById("btn-generate"),this.elements.resultAreaEl=this.shadowRoot.getElementById("result-area"),this.elements.keystoneAddrEl=this.shadowRoot.getElementById("keystone-addr"),this.elements.inputUsername=this.shadowRoot.getElementById("input-username"),this.elements.inputDescription=this.shadowRoot.getElementById("input-description"),this.elements.inputSecret=this.shadowRoot.getElementById("input-secret"),this.elements.checkboxMakeActive=this.shadowRoot.getElementById("checkbox-make-active"),this.elements.statusArea=this.shadowRoot.getElementById("status-area"),this.elements.statusText=this.shadowRoot.getElementById("status-text"),this.elements.contentEl=this.elements.containerEl,this.initHandlers(),this.ibGibAddr&&!this.ibGib&&await this.loadIbGib(),await this.checkExistingIdentities(),await this.renderUI()}async checkExistingIdentities(){let e=`${this.lc}[checkExistingIdentities]`;try{let o=await me(),i=await o.getLocalUserSpace({});if(i){let l=(await o.getSpecialIbGib({type:"keystones",space:i,initialize:!0}))?.rel8ns?.keystone??[];this.hasExistingIdentities=l.length>0}}catch(o){console.warn(`${e} Error checking existing identities: ${y(o)}`),this.hasExistingIdentities=!1}let t=this.elements.checkboxMakeActive;t&&(this.hasExistingIdentities?(t.disabled=!1,t.title=""):(t.checked=!0,t.disabled=!0,t.title="At least one active identity is required."))}async disconnected(){}initHandlers(){this.elements.btnGenerateEl.addEventListener("click",()=>this.handleGenerate()),this.elements.inputUsername.addEventListener("input",()=>{this.elements.inputUsername.classList.remove("invalid")}),this.elements.inputDescription.addEventListener("input",()=>{this.elements.inputDescription.classList.remove("invalid")}),this.elements.inputSecret.addEventListener("input",()=>{this.elements.inputSecret.classList.remove("invalid")})}async handleGenerate(){let e=`${this.lc}[${this.handleGenerate.name}]`;try{console.log(`${e} [NAG][ibgib-paradigm] starting genesis orchestration...`);let t=500;if(this.setStatus("Initializing genesis...","info"),Q("Starting local genesis orchestration..."),!this.validateInputPattern({input:this.elements.inputUsername,pattern:gr,errorMessage:"Username must be 1-63 characters (alphanumeric, underscores, hyphens, dots).",required:!0})){this.setStatus("Invalid username. Must be 1-63 characters (alphanumeric, _, -, .).","error"),Q("\u2717 Invalid username.");return}let o=this.elements.inputUsername.value.trim();if(!this.validateInputPattern({input:this.elements.inputDescription,pattern:br,errorMessage:"Description must be 0-128 characters and consist of English characters and common punctuation.",required:!1})){this.setStatus("Invalid description. Alphanumeric + common punctuation, max 128 chars.","error"),Q("\u2717 Invalid description.");return}let i=this.elements.inputDescription.value.trim(),r=this.elements.inputSecret.value;if(r)this.elements.inputSecret.classList.remove("invalid");else{this.elements.inputSecret.classList.add("invalid"),this.setStatus("Please enter a master secret.","error"),Q("\u2717 Please enter a master secret.");return}this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Preparing configuration and policy options...",animationEmoji:"\u2699\uFE0F",submitBtnSelector:"#btn-generate",loadingText:"Generating..."});let l=Ct.buildKeystone("domain").withUsername(o).withDescription(i).withDetails({client:"space-gib-web",role:"domain-identity"}),c=await l.compileConfigs(),d=await me(),u=await d.getLocalUserSpace({});if(!u)throw new Error("No default space found in metaspace.");this.showBusy({isBusy:!0,title:"Generating Identity...",msg:`Performing cryptographic local genesis...
|
|
1196
|
-
(This runs compute-heavy Key Derivation Functions)`,animationEmoji:"\u{1F5DD}\uFE0F"});let p=new
|
|
1197
|
-
`),animationEmoji:"\u{1F504}"});let
|
|
1198
|
-
Updating local identity indexes and scope settings...`,animationEmoji:"\u{1F4BE}"}),await W(t),await
|
|
1193
|
+
`:this.html,!this.shadowRoot)throw new Error("(UNEXPECTED) this.shadowRoot is falsy? (E: 1a3cf77d87767aaff37d31657ee73f25)");this.shadowRoot.appendChild(t.content),this.createdPromise=this.created(),await this.createdPromise}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async connectedCallback_reconnectComponent(){let e=`${this.lc}[${this.connectedCallback_reconnectComponent.name}]`;try{P&&console.log(`${e} starting... (I: 7fccefbeff68c0dda15642ebaa1eb525)`),console.log(`${e} does nothing in base class (I: 724bc670d4ccb0fde2b2fa49830cd425)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async disconnectedCallback(){let e=`${this.lc}[${this.disconnectedCallback.name}]`;try{P&&console.log(`${e} starting... (I: 6f3b25c23fb874b1ac513e8f0d1f4e25)`),await this.disconnected()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async attributeChangedCallback(e,t,o){let i=`${this.lc}[attributeChangedCallback]`;P&&console.log(`${i} starting... (I: 33cd68579171582166d25d8898640f25): ${e} ${t} => ${o}`),console.warn(`${i} nothing done in base class atow (W: 9eb93eb8fde7c0058c79cea841936a25)`)}async destroy(){let e=`${this.lc}[${this.destroy.name}]`;try{P&&console.log(`${e} starting... (I: 536989c9491b544105b6d01a688fbb25)`),await this.destroyed()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async destroyed(){let e=`${this.lc}[${this.destroyed.name}]`;try{P&&console.log(`${e} starting... (I: f34f3ca04b06b1e00ebe04df22331125)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}return P&&console.log(`${e} does nothing in the base class. (I: d9437f962e0aec40d69ad6159e7b5725)`),Promise.resolve()}async loadIbGib(e){let t=`${this.lc}[${this.loadIbGib.name}]`;try{P&&console.log(`${t} starting... (I: 4dcb1b7a3d86f3415ca7224c07126925)`);let o=e?.getLatest??!1;if(this.ibGib){console.warn(`${t} this.ibGib already loaded. idempotently returning early without doing anything. (W: 15498d346a32e884acec108cb3c8ee25)`);return}if(wt({gib:F({ibGibAddr:this.ibGibAddr??z}).gib})){P&&console.log(`${t} component loading primitive ibgib (I: 3349796ef6139c1e718c8626c7935625)`);return}let i=await this.getMetaspace(),r=await i.getLocalUserSpace({lock:!1});if(!r)throw new Error("(UNEXPECTED) local user space falsy? (E: bb093b7e9781064e8db9a4390b63bb25)");if(o){let m=await i.getLatestAddr({addr:this.ibGibAddr,space:r});m&&m!==this.ibGibAddr&&(this.ibGibAddr=m)}let a=await i.get({addrs:[this.ibGibAddr],space:r});if(!a.success||a.ibGibs?.length!==1)throw new Error(`couldn't get ibGib (${this.ibGibAddr}) in space (${r?.ib??"undefined"}) (E: 59c3461bebf3e0065df72bd1bd8dc125)`);let c=a.ibGibs.at(0),d=new Ue;if(await d.initialized,!d.contextUpdated$)throw new Error("(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: 351dfc898d2c3da2d7928079cec14925)");if(d.contextUpdated$.subscribe($e({next:f(async m=>{let h=`${t}[ibGibProxy.contextUpdated$][next]`;P&&console.log(`${h} nextIbGib: ${M(m)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleContextUpdated()},"next"),error:f(async m=>{debugger;console.error(`${t}[ibGibProxy.contextUpdated$][error] what up? ${y(m)}`)},"error")})),!d.newContextChild$)throw new Error("(UNEXPECTED) ibGibProxy.newContextChild$ falsy? (E: 2cbde5ab402cc6d81259c74d68bca725)");d.newContextChild$.subscribe($e({next:f(async m=>{let h=`${t}[ibGibProxy.contextUpdated$][next]`;P&&console.log(`${h} childIbGib: ${M(m)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleNewContextChild({childIbGib:m})},"next"),error:f(async m=>{debugger;console.error(`${t}[ibGibProxy.contextUpdated$][error] what up? ${y(m)}`)},"error")}));let u=await d.witness(r),p=await d.witness(c);this.ibGibProxy=d,this.ibGibAddr=S({ibGib:d.ibGib})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{P&&console.log(`${t} complete.`)}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{let{ibGib:t}=this;this.ibGibAddr=t?S({ibGib:t}):z,P&&console.log(`${e} context updated. this.ibGibAddr (I: 64e5876f58cc54b5af777c94f13a4325)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}}async handleNewContextChild({childIbGib:e}){let t=`${this.lc}[${this.handleNewContextChild.name}]`;try{P&&console.log(`${t} child added to contextcontext updated. childIbGib: ${M(e)} (I: 07d02c9182c6629cbbacd39fd0ff7f25)`),console.log(S({ibGib:e}))}catch(o){throw console.error(`${t} ${y(o)}`),o}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;try{if(P&&console.log(`${e} starting... (I: 7e5704afe17fb937c8473e7801f56e25)`),this.ibGib){let{punctiliarColor:t,punctiliarColorTranslucent:o,punctiliarColorContrast:i,tjpColor:r,tjpColorTranslucent:a,tjpColorContrast:c,errorMsg:d}=qt({ibGib:this.ibGib,translucentAlpha:10});d?console.error(`${e} ${d} (E: 65e0d330d029c1fe39f3d6280dda3725)`):(this.style.setProperty("--ibgib-color",t),this.style.setProperty("--ibgib-color-translucent",o),this.style.setProperty("--ibgib-color-contrast",i),this.style.setProperty("--tjp-color",r??t),this.style.setProperty("--tjp-color-translucent",a??o),this.style.setProperty("--tjp-color-contrast",c??"lime"))}await this.renderUI_busy()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async renderUI_busy(){}async loadAgentsCoupledToIbGib({dontThrowIfNone:e}={}){let t=`${this.lc}[${this.loadAgentsCoupledToIbGib.name}]`;try{let o=await this.getMetaspace(),i=await o.getLocalUserSpace({lock:!1});if(!i)throw new Error("(UNEXPECTED) space falsy? we couldn't get the default local user space? (E: 06f5be2eec8abaa54d42ad982a155925)");if(!this.ibGib)throw new Error("(UNEXPECTED) this.ibGib falsy? (E: 9b24c4b4aa491a21b58fde9185eb9325)");let r=await Ri({ibGib:this.ibGib,metaspace:o,space:i});if(r){let a=r.data.n;await r.setActiveContext({contextIbGib:this.ibGib,loggingInfo:this.lc}),await W(32);let c=r.data.n;a!==c&&console.warn(`${t} setting active context for agent changed agent.data.n.
|
|
1194
|
+
agent.data: ${M(oe({ibGib:r}))}
|
|
1195
|
+
ibGib.data: ${oe({ibGib:this.ibGib})} (W: cb22e8b064d8c2d7b3b2c488ed169225)`),this.agents=[r]}else if(e)console.warn(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${S({ibGib:this.ibGib})}) (W: e4219903462baab438a23c786d714825)`);else throw new Error(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${S({ibGib:this.ibGib})}) (E: 7182d1aa070b9578c78a5b8b401d8425)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{P&&console.log(`${t} complete.`)}}async getSettings({settingsType:e,useCase:t}){let o=`${this.lc}[${this.getSettings.name}]`;try{if(P&&console.log(`${o} starting... (I: 00c8dbedd2e8a8b988cc45f4186efd25)`),!this.settings)throw new Error("(UNEXPECTED) this.settings falsy? shouldn't this be initialized by now? (E: ceae480e28fab1da38b8def8b1060d25 (E: dc7d984c1c64293a3c3e0628dedadb25)");if(!this.settings.ibGib)throw new Error("(UNEXPECTED) this.settings.ibGib falsy? shouldn't this be initialized by now? especially since this.settings is truthy? (E: faef6878abaf00a4a6a6f6b85ce8c825)");let i=await On({sectionName:await pe({settingsType:e,useCase:t}),settingsIbGib:this.settings.ibGib});return i||P&&console.log(`${o} settingsSection does not exist. returning undefined. (I: 0462d83f5ae8049708274b88e9b0d825)`),i}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{P&&console.log(`${o} complete.`)}}async updateSettings({settingsType:e,useCase:t,newSectionInfo:o}){let i=`${this.lc}[${this.updateSettings.name}]`;try{P&&console.log(`${i} starting... (I: 80ce98cf386e0c04d30e8b15ac0f2925)`);let r=await pe({settingsType:e,useCase:t}),a=await it({timeline:this.settings.ibGib,metaspace:await this.getMetaspace(),mut8Opts:{dataToAddOrPatch:{sections:{[r]:o}}}});await W(100)}catch(r){throw console.error(`${i} ${y(r)}`),r}finally{P&&console.log(`${i} complete.`)}}async getCurrentSettings({settingsType:e}){let t=`${this.lc}[${this.getCurrentSettings.name}]`;try{if(P&&console.log(`${t} starting... (I: da0baee73e386089a8c059f83cc43825)`),!this.settings)return;let o=await pe({settingsType:e,useCase:"current"});return On({sectionName:o,settingsIbGib:this.settings.ibGib})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{P&&console.log(`${t} complete.`)}}async initSettings(){let e=`${this.lc}[${this.initSettings.name}]`;try{if(P&&console.log(`${e} starting... (I: acfee8787d32a6075442e2887a386a25)`),!this.ibGib)throw new Error("(UNEXPECTED) this.ibGib falsy? (E: 8ce2e73bea87b9330b131778a3981825)");let t=await this.getMetaspace(),o=await t.getLocalUserSpace({lock:!1});if(!o)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: f77ce7269a6f0d7ad8978349b4c6cd25)");if(wt({ibGib:this.ibGib})){console.error(`${e} this.ibGib is primitive, so what are we initializing settings for? (W: 9915089019b81c6935b32ae877095825)`);return}let i=await ki({ibGib:this.ibGib}),r=await Bt({scope:i,ibGib:this.ibGib,metaspace:t,space:o});if(r||(r=(await Li({scope:i,metaspace:t,space:o,saveInSpace:!0})).newIbGib,await to({scope:i,domainIbGib:this.ibGib,localIbGib:r,metaspace:t,space:o})),!r)throw new Error("(UNEXPECTED) settings falsy still? should be initialized. (E: a179adcbbab800cff849b8aa95fbe425)");let a=new Ue;if(await a.setWrappedIbGib({ibGib:r,space:o}),this.settings=a,!await this.getCurrentSettings({settingsType:ee.general}))throw new Error("(UNEXPECTED) no current general settings? the settings should have been updated with this upon creation. (E: d10fd8d42b58d917180293a713009825)")}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}async exportIbGib({ibGib:e,compress:t}){let o=`${this.lc}[${this.exportIbGib.name}]`;try{P&&console.log(`${o} starting... (I: 623d9463d919683be81f749821a95825)`);let i=await this.getMetaspace();if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: 3d15dbd074ac0c15b834a788d0b57d25)");if(wt({ibGib:e}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let r=await i.getLocalUserSpace({lock:!1});if(!r)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: 7bb735be58282f1bd7abe5d9ffabb525)");await pr({ibGib:e,compress:t,metaspace:i,space:r})}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{P&&console.log(`${o} complete.`)}}async importIbGib({exportIbGibJsonString:e,rel8nName:t,force:o,skipRegisterTimelines:i,divergentTimelineStrategy:r}){let a=`${this.lc}[${this.importIbGib.name}]`;try{let c=await this.getMetaspace(),d=await c.getLocalUserSpace({lock:!1});if(!d)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: 947c983e57a91aa00c8c185320354325)");let[u,p]=await fr({exportIbGibJsonString:e,metaspace:c});if(!u.data)throw new Error("(UNEXPECTED) rawExportIbGib.data falsy? this is assumed validated at this point. (E: 6bc4e84db08e3c6228b2c40c2ea50825)");let m=u.data.contextIbGibAddr,h=!1;if(!o){let g=await c.get({addr:m,space:d});g.success&&(g.ibGibs??[]).length===1&&(console.log(`${a} export's ibGib addr (${m}) already exists in the space, so we're skipping doing any physical importing of the export's graph. (I: 429b5bdcd0585c697869f568c4673825)`),h=!0)}if(!h){eo;let g=[],b=[];Object.values(p).forEach(N=>{Wi({ibGib:N})?g.push(N):b.push(N)});let E=await c.put({ibGibs:g,isDna:!0,space:d,force:o});if(!E.success||E.errorMsg)throw new Error(`there was an error putting the export's dna ibgibs into the space (${d.ib}). error: ${E.errorMsg||"[unknown error (E: 7c7ef8d5281399b1d8f3fbeefba1b825)]"} (E: ce3e8b982208afc4889164ba20a31825)`);let{mapWithTjp_YesDna:I,mapWithTjp_NoDna:v,mapWithoutTjps:w}=eo({ibGibs:b}),T=await c.put({ibGibs:Object.values(w),space:d,force:o});if(!T.success||T.errorMsg)throw new Error(`there was an error putting the export's non-dna stone ibgibs (no-tjp) into the space (${d.ib}). error: ${T.errorMsg||"[unknown error (E: dc17f8ee7aed5c445f8b827f274b0825)]"} (E: 9561364961e89c132818f6784a607825)`);let _={...I,...v},A=Object.values(_),R=await c.put({ibGibs:A,space:d,force:o});if(!R.success||R.errorMsg)throw new Error(`there was an error putting the export's timeline ibgibs into the space (${d.ib}). error: ${R.errorMsg||"[unknown error (E: be4a28961574765798c8d3686ae89c25)]"} (E: 066796a23da3c9f748558fd25bfdf525)`);if(!i){let N=nr({ibGibs:A}),H=Object.values(N);for(let x of H){let D=x.at(-1);if(!D)throw new Error("(UNEXPECTED) latestInTimeline falsy? this would mean that we had an empty timeline, and this doesn't make sense... (E: 3bec09e79768cc39d8029f4fe3af9825)");let J=await c.getLatestAddr({ibGib:D,space:d});!1||await c.registerNewIbGib({ibGib:D,space:d})}}}throw new Error("not implemented (E: 66c308e420e848c8d7cd01c8fddf8425)")}catch(c){throw console.error(`${a} ${y(c)}`),c}finally{P&&console.log(`${a} complete.`)}}},Mt=class extends Oe{static{f(this,"IbGibDynamicComponentInstanceBase_Parent")}childInfos=[];get activeChildInfo(){return this.childInfos.find(e=>e.active)}async activateIbGib({addr:e,ibGib:t}){let o=`${this.lc}[${this.activateIbGib.name}]`;try{let h=function(g){let b=F({ibGibAddr:g.addr}).gib;return(K({gib:b}).tjpGib??b)===m};var i=h;for(f(h,"tabInfoSharesTjpGib"),P&&console.log(`${o} starting... (I: 05015d78983488496dcca4fa36718725)`);!this.createdPromise;)await W(50);if(await this.createdPromise,!this.elements)throw new Error("(UNEXPECTED) this.elements falsy? (E: fa221c138f211ee93c717c9dd0cf3225)");let{contentEl:r}=this.elements;if(!t&&!e)throw new Error("(UNEXPECTED) both ibGib and addr falsy? (E: 529fb88738cdacb10aea87b8450f2525)");if(t&&e&&S({ibGib:t})!==e)throw new Error("(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: c99a94d8744e3a720cdbc094d53c4e25)");e??=S({ibGib:t});let a=await ce(),c=await this.getLoadedChildInfo({addr:e,ibGib:t});if(c.active){console.log(`${o} same tab already active. returning early. childInfo.addr: ${c.addr} (user just clicked on the same tab) (I: e67c0d02f3143c49c7a20c82d0730225)`);return}let d=this.activeChildInfo;d&&(d.childBtnEl.classList.remove("active"),d.active=!1,r.innerHTML=""),c.childBtnEl.classList.add("active"),c.childBtnEl.scrollIntoView({behavior:"smooth"}),c.active=!0;let u=F({ibGibAddr:e}).gib,m=K({gib:u}).tjpGib??u;if(this.childInfos.some(g=>h(g))||this.childInfos.push(c),!c.component)throw new Error("(UNEXPECTED) childInfo.component falsy? should be populated by this point in code (E: 77abfd1e8cd395605d46716bd087fb25)");await a.inject({parentEl:r,componentToInject:c.component})}catch(r){throw console.error(`${o} ${y(r)}`),r}finally{P&&console.log(`${o} complete.`)}}},zn=class n extends Mt{static{f(this,"IbGibDynamicComponentInstanceBase_ParentOfTabs")}lc=`[${n.name}]`;get isBusy(){return this._reloadingTabs}_reloadingTabs=!1;get reloadingTabs(){return this._reloadingTabs}set reloadingTabs(e){let t=e!==this._reloadingTabs;this._reloadingTabs=e,t&&this.renderUI_busy()}async closeTab({ibGib:e}){let t=`${this.lc}[${this.closeTab.name}]`;try{P&&console.log(`${t} starting... (I: e0d5f8ed67b8a7f43822fa3843fd4525)`);let o=S({ibGib:e}),i=se({ibGib:e,defaultIfNone:"incomingAddr"});if(!i)throw new Error(`(UNEXPECTED) tjpAddr false after incomingAddr default? ibGib: ${M(e)} (E: 707988b4d22a27c1287aa5a815d88825)`);let r=await this.getLoadedChildInfo({addr:o,ibGib:e}),a=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(!a)throw new Error(`(UNEXPECTED) settings_current falsy for this project? this.ibGib: ${M(this.ibGib)} (E: ecea08dcacd198bb38cc44a860cc6825)`);if(!a.openChildTjpAddrs.includes(i))throw new Error(`${t} (UNEXPECTED) projectSettings didn't have the tjpAddr (${i})? projectSettings: ${M(a)} (E: genuuid)`);let c=a.openChildTjpAddrs.filter(g=>g!==i),d;if(a.activeChildTjpAddr===i)if(c.length>0){let g=a.openChildTjpAddrs.indexOf(i)-1;g<0&&(g=0),d=a.openChildTjpAddrs.at(g)}else d=this.tjpAddr,c.push(this.tjpAddr);let u=await pe({settingsType:this.settingsType,useCase:"current"}),p={...a,openChildTjpAddrs:c},m=await this.getMetaspace(),h=await it({timeline:this.settings.ibGib,metaspace:m,mut8Opts:{dataToAddOrPatch:{sections:{[u]:p}}}});r.active&&await this.activateIbGib({addr:d}),this.childInfos=this.childInfos.filter(g=>g.addr!==r.addr),await this.removeTabBtn({tabInfo:r})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{P&&console.log(`${t} complete.`)}}async reopenOldTabs(){let e=`${this.lc}[${this.reopenOldTabs.name}]`;try{P&&console.log(`${e} starting... (I: 195e7d34b3f8b761aa78dd384011f825)`);let t=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(!t)throw new Error("(UNEXPECTED) settings falsy? these should be initialized before now. (E: 2003ab77e01448d638216fc82aff5f25)");this.reloadingTabs=!0,await this.renderUI_busy();let o;try{for(let i of t.openChildTjpAddrs)o=i,await this.activateIbGib({addr:i})}catch(i){throw console.error(`${e} error during activating child ibGib tabs. childTjpAddr: ${o??"[unset?]"} (E: 0396b2e24d08f42ac94510bb718a1725)`),i}finally{this.reloadingTabs=!1}await this.activateIbGib({addr:t.activeChildTjpAddr})}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{P&&console.log(`${e} complete.`)}}},Jn=class extends Oe{static{f(this,"IbGibFormInstanceBase")}setLoading(e,t="#btn-submit, #btn-generate",o){if(!this.shadowRoot)return;let i=this.shadowRoot.querySelector(t);if(i)if(i.disabled=e,e)i.setAttribute("data-loading","true"),o&&(i.setAttribute("data-original-text",i.textContent||""),i.textContent=o);else{i.removeAttribute("data-loading");let r=i.getAttribute("data-original-text");r!==null&&(i.textContent=r,i.removeAttribute("data-original-text"))}}setStatus(e,t,o="status-area",i="status-text"){if(!this.shadowRoot)return;let r=this.shadowRoot.getElementById(o),a=this.shadowRoot.getElementById(i);a&&(a.textContent=e,a.className=`status-msg ${t}`),r&&(e?r.classList.remove("hidden"):r.classList.add("hidden"))}dispatchShellMessage(e,t){this.dispatchEvent(new CustomEvent(cr,{detail:{message:e,level:t,source:this.tagName.toLowerCase()},bubbles:!0,composed:!0}))}validateForm(e="form"){if(!this.shadowRoot)return!0;let t=this.shadowRoot.querySelector(e);if(t)return t.checkValidity();let o=this.shadowRoot.querySelectorAll("input, select, textarea"),i=!0;for(let r of Array.from(o)){let a=r;if(!a.checkValidity()){i=!1,a.reportValidity();break}}return i}validateInputPattern({input:e,pattern:t,errorMessage:o,required:i=!0}){if(!e)return!0;let r=e.value.trim();if(!r&&!i)return e.classList.remove("invalid"),e.setCustomValidity(""),!0;let a=t.test(r);return a?(e.classList.remove("invalid"),e.setCustomValidity("")):(e.classList.add("invalid"),e.setCustomValidity(o),e.reportValidity()),a}showBusy({isBusy:e,title:t,msg:o,localOnly:i,submitBtnSelector:r,loadingText:a,animationEmoji:c}){let d=`${this.lc}[${this.showBusy.name}]`;try{this.setLoading(e,r,a),this.toggleAllInputsDisabled(e),super.showBusy({isBusy:e,title:t,msg:o,localOnly:i,animationEmoji:c})}catch(u){throw console.error(`${d} ${y(u)}`),u}}toggleAllInputsDisabled(e){if(!this.shadowRoot)return;this.shadowRoot.querySelectorAll("input, select, textarea, button").forEach(o=>{o.id==="btn-submit"||o.id==="btn-generate"||(o.disabled=e)})}};var ml="ibgib-keystone-creator",Wn=class extends ge{static{f(this,"KeystoneCreatorComponentMeta")}lc="[KeystoneCreatorComponentMeta]";routeRegExp=new RegExp(`^${ml}$`);componentName=ml;constructor(){super(Se()),customElements.get(this.componentName)||customElements.define(this.componentName,Ui)}async createInstance({path:e,ibGibAddr:t}){let o=`${this.lc}[${this.createInstance.name}]`,i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:kr,css:[Ae,Dr]}),i}},Ui=class extends Jn{static{f(this,"KeystoneCreatorComponentInstance")}lc="[KeystoneCreatorComponentInstance]";hasExistingIdentities=!1;constructor(){super()}async initialize(e){await super.initialize(e)}async created(){this.elements={},this.elements.containerEl=this.shadowRoot.getElementById("container"),this.elements.titleEl=this.shadowRoot.getElementById("title"),this.elements.btnGenerateEl=this.shadowRoot.getElementById("btn-generate"),this.elements.resultAreaEl=this.shadowRoot.getElementById("result-area"),this.elements.keystoneAddrEl=this.shadowRoot.getElementById("keystone-addr"),this.elements.inputUsername=this.shadowRoot.getElementById("input-username"),this.elements.inputDescription=this.shadowRoot.getElementById("input-description"),this.elements.inputSecret=this.shadowRoot.getElementById("input-secret"),this.elements.checkboxMakeActive=this.shadowRoot.getElementById("checkbox-make-active"),this.elements.statusArea=this.shadowRoot.getElementById("status-area"),this.elements.statusText=this.shadowRoot.getElementById("status-text"),this.elements.contentEl=this.elements.containerEl,this.initHandlers(),this.ibGibAddr&&!this.ibGib&&await this.loadIbGib(),await this.checkExistingIdentities(),await this.renderUI()}async checkExistingIdentities(){let e=`${this.lc}[checkExistingIdentities]`;try{let o=await me(),i=await o.getLocalUserSpace({});if(i){let a=(await o.getSpecialIbGib({type:"keystones",space:i,initialize:!0}))?.rel8ns?.keystone??[];this.hasExistingIdentities=a.length>0}}catch(o){console.warn(`${e} Error checking existing identities: ${y(o)}`),this.hasExistingIdentities=!1}let t=this.elements.checkboxMakeActive;t&&(this.hasExistingIdentities?(t.disabled=!1,t.title=""):(t.checked=!0,t.disabled=!0,t.title="At least one active identity is required."))}async disconnected(){}initHandlers(){this.elements.btnGenerateEl.addEventListener("click",()=>this.handleGenerate()),this.elements.inputUsername.addEventListener("input",()=>{this.elements.inputUsername.classList.remove("invalid")}),this.elements.inputDescription.addEventListener("input",()=>{this.elements.inputDescription.classList.remove("invalid")}),this.elements.inputSecret.addEventListener("input",()=>{this.elements.inputSecret.classList.remove("invalid")})}async handleGenerate(){let e=`${this.lc}[${this.handleGenerate.name}]`;try{console.log(`${e} [NAG][ibgib-paradigm] starting genesis orchestration...`);let t=500;if(this.setStatus("Initializing genesis...","info"),Q("Starting local genesis orchestration..."),!this.validateInputPattern({input:this.elements.inputUsername,pattern:yr,errorMessage:"Username must be 1-63 characters (alphanumeric, underscores, hyphens, dots).",required:!0})){this.setStatus("Invalid username. Must be 1-63 characters (alphanumeric, _, -, .).","error"),Q("\u2717 Invalid username.");return}let o=this.elements.inputUsername.value.trim();if(!this.validateInputPattern({input:this.elements.inputDescription,pattern:Er,errorMessage:"Description must be 0-128 characters and consist of English characters and common punctuation.",required:!1})){this.setStatus("Invalid description. Alphanumeric + common punctuation, max 128 chars.","error"),Q("\u2717 Invalid description.");return}let i=this.elements.inputDescription.value.trim(),r=this.elements.inputSecret.value;if(r)this.elements.inputSecret.classList.remove("invalid");else{this.elements.inputSecret.classList.add("invalid"),this.setStatus("Please enter a master secret.","error"),Q("\u2717 Please enter a master secret.");return}this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Preparing configuration and policy options...",animationEmoji:"\u2699\uFE0F",submitBtnSelector:"#btn-generate",loadingText:"Generating..."});let a=_t.buildKeystone("domain").withUsername(o).withDescription(i).withDetails({client:"space-gib-web",role:"domain-identity"}),c=await a.compileConfigs(),d=await me(),u=await d.getLocalUserSpace({});if(!u)throw new Error("No default space found in metaspace.");this.showBusy({isBusy:!0,title:"Generating Identity...",msg:`Performing cryptographic local genesis...
|
|
1196
|
+
(This runs compute-heavy Key Derivation Functions)`,animationEmoji:"\u{1F5DD}\uFE0F"});let p=new ye,m=await p.genesis({masterSecret:r,configs:c,metaspace:d,space:u,frameDetails:a.getFrameDetails(),isPrimary:!0}),h=S({ibGib:m});console.log(`${e} [NAG][ibgib-paradigm] local genesis complete: ${h}`),await W(t),this.setStatus("Local genesis complete. Creating sync delegate...","info"),Q(`\u2713 Local genesis complete: ${h}`),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Generating cryptographic sync delegate keys...",animationEmoji:"\u{1F511}"});let g=await wr({masterSecret:r}),b=_t.buildKeystone("sync").withUsername(`${o}-sync`).withDescription(`Sync Delegate for ${o}`).withDetails({client:"space-gib-web",role:"sync-delegate"}),E=await b.compileConfigs(),I=await p.genesis({masterSecret:g,configs:E,metaspace:d,space:u,frameDetails:b.getFrameDetails()}),v=S({ibGib:I});console.log(`${e} sync delegate genesis complete: ${v}`),await W(t),this.setStatus("Registering delegate on parent...","info"),this.showBusy({isBusy:!0,title:"Registering Delegate...",msg:"Evolving domain identity to register delegate...",animationEmoji:"\u{1F4DD}"});let w=await p.registerDelegate({parentKeystone:m,delegateKeystone:I,masterSecret:r,metaspace:d,space:u,allowedVerbs:[Ir,vr]}),T=S({ibGib:w});console.log(`${e} delegate registered. evolved parent address: ${T}`),await W(t),Q("Posting genesis keystone to server..."),this.setStatus("Syncing genesis to server...","info"),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:["Posting genesis keystone to server sync node...","(may take awhile, depending on strength of keystone...)"].join(`
|
|
1197
|
+
`),animationEmoji:"\u{1F504}"});let _=await rt.postGenesisKeystone(m);if(!_.success){this.setStatus(`Sync failed: ${_.message}`,"error"),Q(`\u2717 Server rejected genesis keystone: ${_.message}`);return}this.setStatus("Syncing delegate registration to server...","info"),this.showBusy({isBusy:!0,title:"Syncing Delegate...",msg:"Posting evolved domain identity and sync delegate to server...",animationEmoji:"\u{1F504}"});let A=await rt.putEvolveKeystone(h,w,[I]);if(!A.success){this.setStatus(`Delegate registration sync failed: ${A.message}`,"error"),Q(`\u2717 Server rejected delegate registration: ${A.message}`);return}this.showBusy({isBusy:!0,title:"Registering Identity...",msg:`Server sync succeeded!
|
|
1198
|
+
Updating local identity indexes and scope settings...`,animationEmoji:"\u{1F4BE}"}),await W(t),await Ge({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[oe({ibGib:w}),oe({ibGib:I})]}],metaspace:d,space:u}),window.dev_domainI=w,window.dev_domainIMasterSecret=r,window.dev_syncDelegate=I,window.dev_syncDelegateSecret=g,this.elements.checkboxMakeActive?.checked&&window.dispatchEvent(new CustomEvent(ke,{detail:{activeIdentityAddr:T},bubbles:!0,composed:!0})),this.elements.keystoneAddrEl.textContent=T,this.elements.statusArea.classList.remove("hidden"),this.setStatus("Keystone successfully created and synced!","success"),await W(t),Q("\u2713 Keystone successfully created and synced!")}catch(t){let o=y(t);console.error(`${e} ${o}`),this.setStatus(`Error: ${o}`,"error"),Q(`\u2717 Error: ${o}`)}finally{this.showBusy({isBusy:!1,submitBtnSelector:"#btn-generate"})}}async renderUI(){}async handleContextUpdated(){await this.renderUI()}};var hl=`:host {
|
|
1199
1199
|
display: block;
|
|
1200
1200
|
width: 100%;
|
|
1201
1201
|
max-width: 100%;
|
|
@@ -1365,7 +1365,7 @@ h2 {
|
|
|
1365
1365
|
|
|
1366
1366
|
.close-tab-button:hover {
|
|
1367
1367
|
color: var(--clr-danger, #ff5555) !important;
|
|
1368
|
-
}`;var
|
|
1368
|
+
}`;var gl=`<div id="container" class="component-container">
|
|
1369
1369
|
<header id="identity-manager-header">
|
|
1370
1370
|
<h2 id="title">Identity Manager</h2>
|
|
1371
1371
|
<div class="tabs-row">
|
|
@@ -1383,8 +1383,8 @@ h2 {
|
|
|
1383
1383
|
<button id="btn-create-placeholder" class="action-btn">Create/Load Identity</button>
|
|
1384
1384
|
</div>
|
|
1385
1385
|
</div>
|
|
1386
|
-
</div>`;var hl="ibgib-identity-manager",Kn=class extends ge{static{f(this,"IdentityManagerComponentMeta")}lc="[IdentityManagerComponentMeta]";routeRegExp=new RegExp(`^${hl}$`);componentName=hl;constructor(){super(Ce()),customElements.get(this.componentName)||customElements.define(this.componentName,ki)}async createInstance({path:e,ibGibAddr:t}){let o=`${this.lc}[${this.createInstance.name}]`,i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:ml,css:[Ae,pl]}),i}},ki=class extends zn{static{f(this,"IdentityManagerComponentInstance")}lc="[IdentityManagerComponentInstance]";globalActiveAddr=null;_onIdentityChanged=null;keystoneCache=new Map;metaspace;get settingsType(){return ee.identityManager}constructor(){super()}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let o=z(O).metaspace;if(!o)return{username:"",description:"",isPrimary:!1,n:0};let i=await o.getLocalUserSpace({lock:!1});if(!i)return{username:"",description:"",isPrimary:!1,n:0};try{let l=await new Se().getKeystoneCommonInfo({addr:e,metaspace:o,space:i});if(l){let c={username:l.name,description:l.description,isPrimary:l.isPrimary,n:l.n};return this.keystoneCache.set(e,c),c}}catch(r){console.warn(`Error getting details for keystone ${e}: ${y(r)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async initialize(e){this.metaspace||(this.metaspace=await me({delayIntervalMs:50})),e.ibGibAddr=await this.metaspace.getLatestAddr({addr:e.ibGibAddr})??e.ibGibAddr,await super.initialize(e)}async created(){this.elements={};let e=this.shadowRoot;this.elements.containerEl=e.getElementById("container"),this.elements.titleEl=e.getElementById("title"),this.elements.tabsListEl=e.getElementById("identity-tabs"),this.elements.btnAddIdentityEl=e.getElementById("btn-add-identity"),this.elements.noIdentityPlaceholderEl=e.getElementById("no-identity-placeholder"),this.elements.btnCreatePlaceholderEl=e.getElementById("btn-create-placeholder"),this.elements.contentEl=e.getElementById("identity-manager-content"),this.initHandlers(),this._onIdentityChanged=t=>{this.globalActiveAddr=t.detail?.activeIdentityAddr||null,this.renderUI()},window.addEventListener(Le,this._onIdentityChanged),this.addEventListener("ibgib-view-keystone-details",async t=>{let o=t.detail?.addr;o&&await this.activateIbGib({addr:o})}),this.ibGibAddr===q||!this.ibGib?await this.loadKeystonesIndex():await this.initSettings(),await this.renderUI(),this.restoreOrInitTabs()}async restoreOrInitTabs(){let e=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(e){let t=(e.openChildTjpAddrs??[]).filter(o=>{if(!o||o==="^"||o==="gib")return!1;let{gib:i}=F({ibGibAddr:o});return!!i&&i!=="gib"&&i!=="^"});if(t.length!==(e.openChildTjpAddrs??[]).length){e.openChildTjpAddrs=t;let o=z(O).metaspace;if(o){let i=await pe({settingsType:this.settingsType,useCase:"current"});await it({timeline:this.settings.ibGib,metaspace:o,mut8Opts:{dataToAddOrPatch:{sections:{[i]:e}}}})}}}!e||(e.openChildTjpAddrs??[]).length===0?await this.loadDefaultPrimaryIdentityTabs():await this.reopenOldTabs()}async disconnected(){this._onIdentityChanged&&window.removeEventListener(Le,this._onIdentityChanged)}async loadKeystonesIndex(){let e=`${this.lc}[loadKeystonesIndex]`;try{let t=z(O).metaspace;if(!t)return;let o=await t.getLocalUserSpace({lock:!1});if(!o)return;let i=await t.getSpecialIbGib({type:"keystones",space:o,initialize:!0});i&&(this.ibGibAddr=S({ibGib:i}),await this.loadIbGib(),await this.initSettings())}catch(t){console.error(`${e} ${y(t)}`)}}initHandlers(){this.elements.btnAddIdentityEl.addEventListener("click",()=>this.handleAddNewIdentityFlow()),this.elements.btnCreatePlaceholderEl.addEventListener("click",()=>this.handleAddNewIdentityFlow()),this.elements.tabsListEl.addEventListener("wheel",e=>{e.deltaY!==0&&(e.preventDefault(),this.elements.tabsListEl.scrollBy({left:e.deltaY,behavior:"smooth"}))},{passive:!1})}async handleAddNewIdentityFlow(){let e=`${this.lc}[${this.handleAddNewIdentityFlow.name}]`;Q(`${e} Triggering identity creation/import flow...`);try{let o=await(await le()).getComponentInstance({path:"ibgib-keystone-creator",ibGibAddr:q,useRegExpPrefilter:!0});if(o){this.elements.noIdentityPlaceholderEl.classList.add("hidden");let i=this.elements.contentEl.querySelector("ibgib-keystone-creator");i&&i.remove();let r=this.activeChildInfo;r&&(r.childBtnEl.classList.remove("active"),r.active=!1),this.elements.contentEl.innerHTML="",this.elements.contentEl.appendChild(o),Q(`${e} Mounted ibgib-keystone-creator successfully.`)}else throw new Error("Could not find meta for ibgib-keystone-creator")}catch(t){console.error(`${e} ${y(t)}`)}}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{if(!this.settings){this.globalActiveAddr=null;return}let o=(await this.getSettings({settingsType:ee.general,useCase:"current"}))?.activeIdentityAddr,r=(this.ibGib?.rel8ns?.keystone??[]).map(async d=>{let u=await this.getKeystoneDetails(d);return{addr:d,isPrimary:u?.isPrimary??!1}}),c=(await Promise.all(r)).filter(d=>d.isPrimary).map(d=>d.addr);o&&c.includes(o)?this.globalActiveAddr=o:c.length>0?this.globalActiveAddr=c[0]:this.globalActiveAddr=null}catch(t){console.error(`${e} ${y(t)}`),this.globalActiveAddr=null}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;if(!this.elements)return;if(await this.resolveActiveIdentity(),(this.ibGib?.rel8ns?.keystone??[]).length===0&&this.childInfos.length===0){this.elements.noIdentityPlaceholderEl.classList.remove("hidden"),this.elements.contentEl.innerHTML="";return}this.elements.noIdentityPlaceholderEl.classList.add("hidden");for(let o of this.childInfos){let i=o.childBtnEl;i.className=`tab-btn ${o.active?"active":""} ${o.addr===this.globalActiveAddr?"global-active":""}`}}async loadDefaultPrimaryIdentityTabs(){let t=(this.ibGib?.rel8ns?.keystone??[]).filter(l=>{if(!l||l==="^"||l==="gib")return!1;let{gib:c}=F({ibGibAddr:l});return!!c&&c!=="gib"&&c!=="^"}).map(async l=>{let c=await this.getKeystoneDetails(l);return{addr:l,isPrimary:c?.isPrimary??!1}}),i=(await Promise.all(t)).filter(l=>l.isPrimary).map(l=>l.addr);if(i.length===0){this.elements.noIdentityPlaceholderEl.classList.remove("hidden");return}this.elements.noIdentityPlaceholderEl.classList.add("hidden"),this.reloadingTabs=!0;try{for(let l of i)await this.activateIbGib({addr:l})}finally{this.reloadingTabs=!1}let r=i.includes(this.globalActiveAddr||"")?this.globalActiveAddr:i[0];await this.activateIbGib({addr:r})}async activateIbGib({addr:e,ibGib:t}){let o=`${this.lc}[activateIbGib]`;try{if(!this.metaspace)throw new Error("(UNEXPECTED) this.metaspace falsy? (E: f9e0e9a1427899eba8e469c18d7ae826)");if(await super.activateIbGib({addr:e,ibGib:t}),!this.activeChildInfo)throw new Error("(UNEXPECTED) activeChildInfo falsy after activateIbGib? (E: d76bd8bc300f3fdc486d50c8b2644826)");if(t??=this.activeChildInfo.component?.ibGib,!t)throw new Error("(UNEXPECTED) ibGib falsy? (E: 5b6ec745dd32fd2128635728e3f35e26)");if(!t.ib.startsWith(to))throw new Error(`ibGib.ib (${t.ib}) does not start with keystone atom (${to}) (E: e0df410381c8e569eb6da996e79b6826)`);if(this.elements.noIdentityPlaceholderEl.classList.add("hidden"),!this.reloadingTabs){let i=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(i){let r=!1,l=re({ibGib:this.activeChildInfo.component?.ibGib||t,defaultIfNone:"incomingAddr"});if(l&&(i.openChildTjpAddrs.includes(l)||(i.openChildTjpAddrs.push(l),r=!0),i.activeChildTjpAddr!==l&&(i.activeChildTjpAddr=l,r=!0)),r){let c=z(O).metaspace;if(c){let d=await pe({settingsType:this.settingsType,useCase:"current"});await it({timeline:this.settings.ibGib,metaspace:c,mut8Opts:{dataToAddOrPatch:{sections:{[d]:i}}}})}}}}await this.renderUI()}catch(i){console.error(`${o} ${y(i)}`)}}async getLoadedChildInfo({addr:e,ibGib:t}){let o=`${this.lc}[getLoadedChildInfo]`;try{if(!e)throw new Error("(UNEXPECTED) addr falsy?");if(e==="^"||e==="gib"||F({ibGibAddr:e}).gib==="^")throw new Error(`Cannot load child info for primitive address ${e}`);let i=K({ibGibAddr:e}).tjpGib??F({ibGibAddr:e}).gib,r=f(async()=>{let u=await(await le()).getComponentInstance({path:"ibgib-keystone-scrubber",ibGibAddr:e,useRegExpPrefilter:!0});if(!u)throw new Error("(UNEXPECTED) detailsComponent falsy?");return u},"fnCreateAndLoadChildComponent"),l,c=this.childInfos.filter(d=>(K({ibGibAddr:d.addr}).tjpGib??F({ibGibAddr:d.addr}).gib)===i);if(c.length>0){if(c.length!==1)throw new Error("(UNEXPECTED) filtered.length !== 1?");l=c[0],l.component||(l.component=await r())}else{let d=await r(),u=0;for(;!d.ibGib;)if(await W(100),u++,u>50){debugger;throw new Error("(UNEXPECTED) detailsComponent.ibGib falsy? didn't load? (E: de50689834124914f770520f1eccb826)")}t=d.ibGib,e=S({ibGib:t});let p=await this.addChild({addr:e,ibGib:t});l={addr:e,childBtnEl:p,component:d,active:!1},this.childInfos.push(l)}return l}catch(i){throw console.error(`${o} ${y(i)}`),i}}async addChild({addr:e,ibGib:t}){let o=`${this.lc}[addChild]`;try{if(e??=S({ibGib:t}),e==="^"||e==="gib"||F({ibGibAddr:e}).gib==="^")throw new Error(`Cannot add child tab for primitive address ${e}`);if(!this.elements)throw new Error("(UNEXPECTED) this.elements falsy?");let{tabsListEl:i}=this.elements;e??=S({ibGib:t});let r=document.createElement("button");if(r.className="tab-btn",r.id=`identity-tab-button-${e}`,await this.updateTabTitleAndText({span:r,ibGib:t,addr:e}),!(await this.getKeystoneDetails(e)).isPrimary){let c=document.createElement("span");c.className="close-tab-button",c.textContent=" \xD7",c.style.marginLeft="0.5rem",c.style.cursor="pointer",r.appendChild(c),c.addEventListener("click",async d=>{d.stopPropagation(),await this.closeTab({ibGib:t})})}return i.appendChild(r),r.addEventListener("click",async c=>{await this.activateIbGib({addr:e})}),r}catch(i){throw console.error(`${o} ${y(i)}`),i}}async updateTabTitleAndText({span:e,ibGib:t,addr:o}){let i=await this.getKeystoneDetails(o),r=i.username,l=16;if(r)r.length>l&&(r=r.substring(0,l-3)+"..."),e.textContent=r;else{let d=o;d.length>12&&(d=d.substring(0,5)+"..."+d.substring(d.length-4)),e.textContent=d}let c=[];if(i.username&&c.push(`User: ${i.username}`),i.description){let d=i.description.length>100?i.description.substring(0,97)+"...":i.description;c.push(`Desc: ${d}`)}c.push(`Addr: ${o}`),e.title=c.join(`
|
|
1387
|
-
`)}async removeTabBtn({tabInfo:e}){this.elements.tabsListEl.removeChild(e.childBtnEl)}};var
|
|
1386
|
+
</div>`;var bl="ibgib-identity-manager",Kn=class extends ge{static{f(this,"IdentityManagerComponentMeta")}lc="[IdentityManagerComponentMeta]";routeRegExp=new RegExp(`^${bl}$`);componentName=bl;constructor(){super(Se()),customElements.get(this.componentName)||customElements.define(this.componentName,Fi)}async createInstance({path:e,ibGibAddr:t}){let o=`${this.lc}[${this.createInstance.name}]`,i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:gl,css:[Ae,hl]}),i}},Fi=class extends zn{static{f(this,"IdentityManagerComponentInstance")}lc="[IdentityManagerComponentInstance]";globalActiveAddr=null;_onIdentityChanged=null;keystoneCache=new Map;metaspace;get settingsType(){return ee.identityManager}constructor(){super()}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let o=O(q).metaspace;if(!o)return{username:"",description:"",isPrimary:!1,n:0};let i=await o.getLocalUserSpace({lock:!1});if(!i)return{username:"",description:"",isPrimary:!1,n:0};try{let a=await new ye().getKeystoneCommonInfo({addr:e,metaspace:o,space:i});if(a){let c={username:a.name,description:a.description,isPrimary:a.isPrimary,n:a.n};return this.keystoneCache.set(e,c),c}}catch(r){console.warn(`Error getting details for keystone ${e}: ${y(r)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async initialize(e){this.metaspace||(this.metaspace=await me({delayIntervalMs:50})),e.ibGibAddr=await this.metaspace.getLatestAddr({addr:e.ibGibAddr})??e.ibGibAddr,await super.initialize(e)}async created(){this.elements={};let e=this.shadowRoot;this.elements.containerEl=e.getElementById("container"),this.elements.titleEl=e.getElementById("title"),this.elements.tabsListEl=e.getElementById("identity-tabs"),this.elements.btnAddIdentityEl=e.getElementById("btn-add-identity"),this.elements.noIdentityPlaceholderEl=e.getElementById("no-identity-placeholder"),this.elements.btnCreatePlaceholderEl=e.getElementById("btn-create-placeholder"),this.elements.contentEl=e.getElementById("identity-manager-content"),this.initHandlers(),this._onIdentityChanged=t=>{this.globalActiveAddr=t.detail?.activeIdentityAddr||null,this.renderUI()},window.addEventListener(Le,this._onIdentityChanged),this.addEventListener("ibgib-view-keystone-details",async t=>{let o=t.detail?.addr;o&&await this.activateIbGib({addr:o})}),this.ibGibAddr===z||!this.ibGib?await this.loadKeystonesIndex():await this.initSettings(),await this.renderUI(),this.restoreOrInitTabs()}async restoreOrInitTabs(){let e=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(e){let t=(e.openChildTjpAddrs??[]).filter(o=>{if(!o||o==="^"||o==="gib")return!1;let{gib:i}=F({ibGibAddr:o});return!!i&&i!=="gib"&&i!=="^"});if(t.length!==(e.openChildTjpAddrs??[]).length){e.openChildTjpAddrs=t;let o=O(q).metaspace;if(o){let i=await pe({settingsType:this.settingsType,useCase:"current"});await it({timeline:this.settings.ibGib,metaspace:o,mut8Opts:{dataToAddOrPatch:{sections:{[i]:e}}}})}}}!e||(e.openChildTjpAddrs??[]).length===0?await this.loadDefaultPrimaryIdentityTabs():await this.reopenOldTabs()}async disconnected(){this._onIdentityChanged&&window.removeEventListener(Le,this._onIdentityChanged)}async loadKeystonesIndex(){let e=`${this.lc}[loadKeystonesIndex]`;try{let t=O(q).metaspace;if(!t)return;let o=await t.getLocalUserSpace({lock:!1});if(!o)return;let i=await t.getSpecialIbGib({type:"keystones",space:o,initialize:!0});i&&(this.ibGibAddr=S({ibGib:i}),await this.loadIbGib(),await this.initSettings())}catch(t){console.error(`${e} ${y(t)}`)}}initHandlers(){this.elements.btnAddIdentityEl.addEventListener("click",()=>this.handleAddNewIdentityFlow()),this.elements.btnCreatePlaceholderEl.addEventListener("click",()=>this.handleAddNewIdentityFlow()),this.elements.tabsListEl.addEventListener("wheel",e=>{e.deltaY!==0&&(e.preventDefault(),this.elements.tabsListEl.scrollBy({left:e.deltaY,behavior:"smooth"}))},{passive:!1})}async handleAddNewIdentityFlow(){let e=`${this.lc}[${this.handleAddNewIdentityFlow.name}]`;Q(`${e} Triggering identity creation/import flow...`);try{let o=await(await ce()).getComponentInstance({path:"ibgib-keystone-creator",ibGibAddr:z,useRegExpPrefilter:!0});if(o){this.elements.noIdentityPlaceholderEl.classList.add("hidden");let i=this.elements.contentEl.querySelector("ibgib-keystone-creator");i&&i.remove();let r=this.activeChildInfo;r&&(r.childBtnEl.classList.remove("active"),r.active=!1),this.elements.contentEl.innerHTML="",this.elements.contentEl.appendChild(o),Q(`${e} Mounted ibgib-keystone-creator successfully.`)}else throw new Error("Could not find meta for ibgib-keystone-creator")}catch(t){console.error(`${e} ${y(t)}`)}}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{if(!this.settings){this.globalActiveAddr=null;return}let o=(await this.getSettings({settingsType:ee.general,useCase:"current"}))?.activeIdentityAddr,r=(this.ibGib?.rel8ns?.keystone??[]).map(async d=>{let u=await this.getKeystoneDetails(d);return{addr:d,isPrimary:u?.isPrimary??!1}}),c=(await Promise.all(r)).filter(d=>d.isPrimary).map(d=>d.addr);o&&c.includes(o)?this.globalActiveAddr=o:c.length>0?this.globalActiveAddr=c[0]:this.globalActiveAddr=null}catch(t){console.error(`${e} ${y(t)}`),this.globalActiveAddr=null}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;if(!this.elements)return;if(await this.resolveActiveIdentity(),(this.ibGib?.rel8ns?.keystone??[]).length===0&&this.childInfos.length===0){this.elements.noIdentityPlaceholderEl.classList.remove("hidden"),this.elements.contentEl.innerHTML="";return}this.elements.noIdentityPlaceholderEl.classList.add("hidden");for(let o of this.childInfos){let i=o.childBtnEl;i.className=`tab-btn ${o.active?"active":""} ${o.addr===this.globalActiveAddr?"global-active":""}`}}async loadDefaultPrimaryIdentityTabs(){let t=(this.ibGib?.rel8ns?.keystone??[]).filter(a=>{if(!a||a==="^"||a==="gib")return!1;let{gib:c}=F({ibGibAddr:a});return!!c&&c!=="gib"&&c!=="^"}).map(async a=>{let c=await this.getKeystoneDetails(a);return{addr:a,isPrimary:c?.isPrimary??!1}}),i=(await Promise.all(t)).filter(a=>a.isPrimary).map(a=>a.addr);if(i.length===0){this.elements.noIdentityPlaceholderEl.classList.remove("hidden");return}this.elements.noIdentityPlaceholderEl.classList.add("hidden"),this.reloadingTabs=!0;try{for(let a of i)await this.activateIbGib({addr:a})}finally{this.reloadingTabs=!1}let r=i.includes(this.globalActiveAddr||"")?this.globalActiveAddr:i[0];await this.activateIbGib({addr:r})}async activateIbGib({addr:e,ibGib:t}){let o=`${this.lc}[activateIbGib]`;try{if(!this.metaspace)throw new Error("(UNEXPECTED) this.metaspace falsy? (E: f9e0e9a1427899eba8e469c18d7ae826)");if(await super.activateIbGib({addr:e,ibGib:t}),!this.activeChildInfo)throw new Error("(UNEXPECTED) activeChildInfo falsy after activateIbGib? (E: d76bd8bc300f3fdc486d50c8b2644826)");if(t??=this.activeChildInfo.component?.ibGib,!t)throw new Error("(UNEXPECTED) ibGib falsy? (E: 5b6ec745dd32fd2128635728e3f35e26)");if(!t.ib.startsWith(oo))throw new Error(`ibGib.ib (${t.ib}) does not start with keystone atom (${oo}) (E: e0df410381c8e569eb6da996e79b6826)`);if(this.elements.noIdentityPlaceholderEl.classList.add("hidden"),!this.reloadingTabs){let i=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(i){let r=!1,a=se({ibGib:this.activeChildInfo.component?.ibGib||t,defaultIfNone:"incomingAddr"});if(a&&(i.openChildTjpAddrs.includes(a)||(i.openChildTjpAddrs.push(a),r=!0),i.activeChildTjpAddr!==a&&(i.activeChildTjpAddr=a,r=!0)),r){let c=O(q).metaspace;if(c){let d=await pe({settingsType:this.settingsType,useCase:"current"});await it({timeline:this.settings.ibGib,metaspace:c,mut8Opts:{dataToAddOrPatch:{sections:{[d]:i}}}})}}}}await this.renderUI()}catch(i){console.error(`${o} ${y(i)}`)}}async getLoadedChildInfo({addr:e,ibGib:t}){let o=`${this.lc}[getLoadedChildInfo]`;try{if(!e)throw new Error("(UNEXPECTED) addr falsy?");if(e==="^"||e==="gib"||F({ibGibAddr:e}).gib==="^")throw new Error(`Cannot load child info for primitive address ${e}`);let i=K({ibGibAddr:e}).tjpGib??F({ibGibAddr:e}).gib,r=f(async()=>{let u=await(await ce()).getComponentInstance({path:"ibgib-keystone-scrubber",ibGibAddr:e,useRegExpPrefilter:!0});if(!u)throw new Error("(UNEXPECTED) detailsComponent falsy?");return u},"fnCreateAndLoadChildComponent"),a,c=this.childInfos.filter(d=>(K({ibGibAddr:d.addr}).tjpGib??F({ibGibAddr:d.addr}).gib)===i);if(c.length>0){if(c.length!==1)throw new Error("(UNEXPECTED) filtered.length !== 1?");a=c[0],a.component||(a.component=await r())}else{let d=await r(),u=0;for(;!d.ibGib;)if(await W(100),u++,u>50){debugger;throw new Error("(UNEXPECTED) detailsComponent.ibGib falsy? didn't load? (E: de50689834124914f770520f1eccb826)")}t=d.ibGib,e=S({ibGib:t});let p=await this.addChild({addr:e,ibGib:t});a={addr:e,childBtnEl:p,component:d,active:!1},this.childInfos.push(a)}return a}catch(i){throw console.error(`${o} ${y(i)}`),i}}async addChild({addr:e,ibGib:t}){let o=`${this.lc}[addChild]`;try{if(e??=S({ibGib:t}),e==="^"||e==="gib"||F({ibGibAddr:e}).gib==="^")throw new Error(`Cannot add child tab for primitive address ${e}`);if(!this.elements)throw new Error("(UNEXPECTED) this.elements falsy?");let{tabsListEl:i}=this.elements;e??=S({ibGib:t});let r=document.createElement("button");if(r.className="tab-btn",r.id=`identity-tab-button-${e}`,await this.updateTabTitleAndText({span:r,ibGib:t,addr:e}),!(await this.getKeystoneDetails(e)).isPrimary){let c=document.createElement("span");c.className="close-tab-button",c.textContent=" \xD7",c.style.marginLeft="0.5rem",c.style.cursor="pointer",r.appendChild(c),c.addEventListener("click",async d=>{d.stopPropagation(),await this.closeTab({ibGib:t})})}return i.appendChild(r),r.addEventListener("click",async c=>{await this.activateIbGib({addr:e})}),r}catch(i){throw console.error(`${o} ${y(i)}`),i}}async updateTabTitleAndText({span:e,ibGib:t,addr:o}){let i=await this.getKeystoneDetails(o),r=i.username,a=16;if(r)r.length>a&&(r=r.substring(0,a-3)+"..."),e.textContent=r;else{let d=o;d.length>12&&(d=d.substring(0,5)+"..."+d.substring(d.length-4)),e.textContent=d}let c=[];if(i.username&&c.push(`User: ${i.username}`),i.description){let d=i.description.length>100?i.description.substring(0,97)+"...":i.description;c.push(`Desc: ${d}`)}c.push(`Addr: ${o}`),e.title=c.join(`
|
|
1387
|
+
`)}async removeTabBtn({tabInfo:e}){this.elements.tabsListEl.removeChild(e.childBtnEl)}};var yl=`:host {
|
|
1388
1388
|
display: inline-block;
|
|
1389
1389
|
vertical-align: middle;
|
|
1390
1390
|
}
|
|
@@ -1496,7 +1496,7 @@ h2 {
|
|
|
1496
1496
|
color: var(--clr-accent, #50fa7b);
|
|
1497
1497
|
transform: rotate(45deg);
|
|
1498
1498
|
}
|
|
1499
|
-
`;var
|
|
1499
|
+
`;var El=`<div id="container" class="header-widget-container">
|
|
1500
1500
|
<!-- Active Identity Pill -->
|
|
1501
1501
|
<div id="active-identity-pill" class="identity-pill hidden">
|
|
1502
1502
|
<div id="identity-avatar" class="avatar-circle">-</div>
|
|
@@ -1506,8 +1506,8 @@ h2 {
|
|
|
1506
1506
|
|
|
1507
1507
|
<!-- Fallback Action Button -->
|
|
1508
1508
|
<button id="btn-create-identity" class="action-btn hidden" title="No active identity. Click to manage.">No Active Identity</button>
|
|
1509
|
-
</div>`;var
|
|
1510
|
-
`)}else this.elements.activeIdentityPillEl.classList.add("hidden"),this.elements.btnCreateIdentityEl.classList.remove("hidden")}async handleRequestIdentityChange(e){let t=`${this.lc}[handleRequestIdentityChange]`,o=e.detail?.activeIdentityAddr;if(o){Q(`${t} Request to change active identity to: ${o}`);try{if(!this.settings)return;let i=await this.getSettings({settingsType:ee.general,useCase:"current"})??{type:"general"};i.activeIdentityAddr=o,await this.updateSettings({settingsType:ee.general,useCase:"current",newSectionInfo:i}),await this.resolveActiveIdentity(),await this.renderUI(),window.dispatchEvent(new CustomEvent(Le,{detail:{activeIdentityAddr:o},bubbles:!0,composed:!0})),Q(`${t} Successfully changed active identity settings to: ${o}`)}catch(i){console.error(`${t} Failed to switch active identity: ${y(i)}`)}}}async handleContextUpdated(){await this.renderUI()}};var
|
|
1509
|
+
</div>`;var Il="ibgib-identity-header",Xn=class extends ge{static{f(this,"IdentityHeaderComponentMeta")}lc="[IdentityHeaderComponentMeta]";routeRegExp=new RegExp(`^${Il}$`);componentName=Il;constructor(){super(Se()),customElements.get(this.componentName)||customElements.define(this.componentName,Hi)}async createInstance({path:e,ibGibAddr:t}){let o=document.createElement(this.componentName);return await o.initialize({ibGibAddr:t,meta:this,html:El,css:[Ae,yl]}),o}},Hi=class extends Oe{static{f(this,"IdentityHeaderComponentInstance")}lc="[IdentityHeaderComponentInstance]";activeAddr=null;_onRequestIdentityChange=null;keystoneCache=new Map;constructor(){super()}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let o=O(q).metaspace;if(!o)return{username:"",description:"",isPrimary:!1};let i=await o.getLocalUserSpace({lock:!1});if(!i)return{username:"",description:"",isPrimary:!1};try{let a=await new ye().getKeystoneCommonInfo({addr:e,metaspace:o,space:i});if(a){let c={username:a.name,description:a.description,isPrimary:a.isPrimary};return this.keystoneCache.set(e,c),c}}catch(r){console.warn(`Error getting details for keystone ${e}: ${y(r)}`)}return{username:"",description:"",isPrimary:!1}}async initialize(e){await super.initialize(e)}async created(){this.elements={};let e=this.shadowRoot;this.elements.containerEl=e.getElementById("container"),this.elements.activeIdentityPillEl=e.getElementById("active-identity-pill"),this.elements.identitySelectorEl=e.getElementById("identity-selector"),this.elements.btnManageIdentitiesEl=e.getElementById("btn-manage-identities"),this.elements.btnCreateIdentityEl=e.getElementById("btn-create-identity"),this.elements.identityAvatarEl=e.getElementById("identity-avatar"),this.elements.contentEl=this.elements.containerEl,this.initHandlers(),this._onRequestIdentityChange=t=>this.handleRequestIdentityChange(t),window.addEventListener(ke,this._onRequestIdentityChange),this.ibGibAddr===z||!this.ibGib?await this.loadKeystonesIndex():await this.initSettings(),await this.renderUI()}async loadKeystonesIndex(){let e=`${this.lc}[loadKeystonesIndex]`;try{let t=O(q).metaspace;if(!t)return;let o=await t.getLocalUserSpace({lock:!1});if(!o)return;let i=await t.getSpecialIbGib({type:"keystones",space:o,initialize:!0});i&&(this.ibGibAddr=S({ibGib:i}),await this.loadIbGib(),await this.initSettings())}catch(t){console.error(`${e} ${y(t)}`)}}async disconnected(){this._onRequestIdentityChange&&window.removeEventListener(ke,this._onRequestIdentityChange)}initHandlers(){this.elements.btnCreateIdentityEl.addEventListener("click",()=>this.navigateToManager()),this.elements.btnManageIdentitiesEl.addEventListener("click",e=>{e.stopPropagation(),this.navigateToManager()}),this.elements.identitySelectorEl.addEventListener("click",e=>{e.stopPropagation()}),this.elements.identitySelectorEl.addEventListener("change",()=>{let e=this.elements.identitySelectorEl.value;e&&window.dispatchEvent(new CustomEvent(ke,{detail:{activeIdentityAddr:e},bubbles:!0,composed:!0}))})}navigateToManager(){vl().showIdentityManager()}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{if(!this.settings){this.activeAddr=null;let u=O(q);u.identity=void 0;return}let o=(await this.getSettings({settingsType:ee.general,useCase:"current"}))?.activeIdentityAddr,r=(this.ibGib?.rel8ns?.keystone??[]).map(async u=>{let p=await this.getKeystoneDetails(u);return{addr:u,isPrimary:p?.isPrimary??!1}}),c=(await Promise.all(r)).filter(u=>u.isPrimary).map(u=>u.addr);o&&c.includes(o)?this.activeAddr=o:c.length>0?this.activeAddr=c[0]:this.activeAddr=null;let d=O(q);if(this.activeAddr){let u=d.metaspace;if(u){let p=await u.getLocalUserSpace({lock:!1});if(p){let m=await u.get({addr:this.activeAddr,space:p});if(m.success&&m.ibGibs&&m.ibGibs.length>0){let h=m.ibGibs[0],g,b=h.data?.delegates;if(b){for(let E of Object.values(b))if(E.allowedVerbs?.includes("sync^gib")||!E.allowedVerbs&&E.delegateTjpAddr){let I=await u.getLatestAddr({addr:E.delegateTjpAddr,space:p});if(I){let v=await u.get({addr:I,space:p});if(v.success&&v.ibGibs&&v.ibGibs.length>0){g=v.ibGibs[0];break}}}}d.identity={resolved:!0,authenticated:!0,domainIdentity:h,syncDelegateIdentity:g}}}}}else d.identity={resolved:!1,authenticated:!1}}catch(t){console.error(`${e} ${y(t)}`),this.activeAddr=null;let o=O(q);o.identity=void 0}}async renderUI(){if(!this.elements)return;await this.resolveActiveIdentity();let t=(this.ibGib?.rel8ns?.keystone??[]).map(async r=>{let a=await this.getKeystoneDetails(r);return{addr:r,isPrimary:a?.isPrimary??!1}}),i=(await Promise.all(t)).filter(r=>r.isPrimary).map(r=>r.addr);if(this.activeAddr&&i.length>0){this.elements.activeIdentityPillEl.classList.remove("hidden"),this.elements.btnCreateIdentityEl.classList.add("hidden");let r=this.activeAddr;this.elements.identitySelectorEl.innerHTML="";for(let h of i){let g=document.createElement("option");g.value=h;let b=h;b.length>14&&(b=b.substring(0,7)+"..."+b.substring(b.length-5)),g.textContent=b,this.getKeystoneDetails(h).then(E=>{if(E.username){let I=E.username;I.length>14&&(I=I.substring(0,11)+"..."),g.textContent=I}}).catch(E=>{}),this.elements.identitySelectorEl.appendChild(g)}this.elements.identitySelectorEl.value=r,this.elements.identityAvatarEl.textContent="-",this.elements.identityAvatarEl.style.backgroundColor="var(--clr-accent)",this.elements.identityAvatarEl.style.color="#11111b";let a=await this.getKeystoneDetails(r),c="-";if(a.username)c=a.username.charAt(0).toUpperCase();else{let h=r.match(/[a-zA-Z]/);c=h?h[0].toUpperCase():"I"}if(!this.elements)throw new Error("(UNEXPECTED) this.elements falsy? (E: fd6bfa87c968a38c4860588818c3cd26)");this.elements.identityAvatarEl.textContent=c;let d=qt({ibGibAddr:r}),u=d.tjpColor||d.punctiliarColor,p=d.tjpColorContrast||d.punctiliarColorContrast;this.elements.identityAvatarEl.style.backgroundColor=u,this.elements.identityAvatarEl.style.color=p;let m=[];if(a.username&&m.push(`User: ${a.username}`),a.description){let h=a.description.length>100?a.description.substring(0,97)+"...":a.description;m.push(`Desc: ${h}`)}m.push(`Addr: ${r}`),this.elements.activeIdentityPillEl.title=m.join(`
|
|
1510
|
+
`)}else this.elements.activeIdentityPillEl.classList.add("hidden"),this.elements.btnCreateIdentityEl.classList.remove("hidden")}async handleRequestIdentityChange(e){let t=`${this.lc}[handleRequestIdentityChange]`,o=e.detail?.activeIdentityAddr;if(o){Q(`${t} Request to change active identity to: ${o}`);try{if(!this.settings)return;let i=await this.getSettings({settingsType:ee.general,useCase:"current"})??{type:"general"};i.activeIdentityAddr=o,await this.updateSettings({settingsType:ee.general,useCase:"current",newSectionInfo:i}),await this.resolveActiveIdentity(),await this.renderUI(),window.dispatchEvent(new CustomEvent(Le,{detail:{activeIdentityAddr:o},bubbles:!0,composed:!0})),Q(`${t} Successfully changed active identity settings to: ${o}`)}catch(i){console.error(`${t} Failed to switch active identity: ${y(i)}`)}}}async handleContextUpdated(){await this.renderUI()}};var wl=`:host {
|
|
1511
1511
|
display: block;
|
|
1512
1512
|
width: 100%;
|
|
1513
1513
|
max-width: 100%;
|
|
@@ -1942,44 +1942,141 @@ h2 {
|
|
|
1942
1942
|
}
|
|
1943
1943
|
}
|
|
1944
1944
|
|
|
1945
|
-
|
|
1945
|
+
/* Grouped Toggle Switch for Identity Providers */
|
|
1946
|
+
.sso-toggle-group {
|
|
1946
1947
|
display: flex;
|
|
1947
|
-
gap:
|
|
1948
|
+
gap: 1.5rem;
|
|
1948
1949
|
margin-top: 1rem;
|
|
1949
1950
|
flex-wrap: wrap;
|
|
1950
1951
|
}
|
|
1951
1952
|
|
|
1952
|
-
.sso-
|
|
1953
|
+
.sso-toggle-card {
|
|
1953
1954
|
flex: 1;
|
|
1954
|
-
min-width:
|
|
1955
|
-
|
|
1956
|
-
|
|
1955
|
+
min-width: 180px;
|
|
1956
|
+
max-width: 240px;
|
|
1957
|
+
height: 180px;
|
|
1958
|
+
background: rgba(255, 255, 255, 0.02);
|
|
1959
|
+
border: 1px solid rgba(255, 255, 255, 0.06);
|
|
1960
|
+
border-radius: var(--radius-md, 8px);
|
|
1961
|
+
display: flex;
|
|
1962
|
+
flex-direction: column;
|
|
1963
|
+
justify-content: space-between;
|
|
1957
1964
|
align-items: center;
|
|
1958
|
-
|
|
1959
|
-
|
|
1965
|
+
cursor: pointer;
|
|
1966
|
+
overflow: hidden;
|
|
1967
|
+
position: relative;
|
|
1968
|
+
user-select: none;
|
|
1969
|
+
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
.sso-toggle-card:hover {
|
|
1973
|
+
background: rgba(255, 255, 255, 0.04);
|
|
1974
|
+
border-color: rgba(255, 255, 255, 0.12);
|
|
1975
|
+
transform: translateY(-2px);
|
|
1976
|
+
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
.sso-toggle-card:focus-visible {
|
|
1980
|
+
outline: 2px solid var(--clr-accent, #50fa7b);
|
|
1981
|
+
outline-offset: 2px;
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
/* Status Indicator bars: Top (Green/Active) and Bottom (Red/Faded) */
|
|
1985
|
+
.toggle-status-indicator {
|
|
1986
|
+
width: 100%;
|
|
1987
|
+
height: 6px;
|
|
1988
|
+
transition: all 0.25s ease-in-out;
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
.toggle-status-indicator.top {
|
|
1992
|
+
background: transparent;
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
.toggle-status-indicator.bottom {
|
|
1996
|
+
background: transparent;
|
|
1997
|
+
}
|
|
1998
|
+
|
|
1999
|
+
/* Middle Content Wrapper */
|
|
2000
|
+
.toggle-content {
|
|
2001
|
+
display: flex;
|
|
2002
|
+
flex-direction: column;
|
|
2003
|
+
align-items: center;
|
|
2004
|
+
justify-content: center;
|
|
2005
|
+
gap: 0.6rem;
|
|
2006
|
+
padding: 1rem;
|
|
2007
|
+
text-align: center;
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
.sso-icon {
|
|
2011
|
+
width: 2.25rem;
|
|
2012
|
+
height: 2.25rem;
|
|
2013
|
+
transition: transform 0.25s cubic-bezier(0.4, 0, 0.2, 1);
|
|
2014
|
+
}
|
|
2015
|
+
|
|
2016
|
+
.sso-toggle-card:hover .sso-icon {
|
|
2017
|
+
transform: scale(1.1);
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
.provider-label {
|
|
2021
|
+
font-size: 0.95rem;
|
|
1960
2022
|
font-weight: 600;
|
|
2023
|
+
color: var(--clr-text-primary, #ffffff);
|
|
1961
2024
|
}
|
|
1962
2025
|
|
|
1963
|
-
.
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
2026
|
+
.toggle-state-text {
|
|
2027
|
+
font-size: 0.75rem;
|
|
2028
|
+
font-weight: 500;
|
|
2029
|
+
text-transform: uppercase;
|
|
2030
|
+
letter-spacing: 0.05em;
|
|
2031
|
+
color: var(--clr-text-secondary, #8fa08f);
|
|
2032
|
+
transition: color 0.25s ease-in-out;
|
|
1967
2033
|
}
|
|
1968
2034
|
|
|
1969
|
-
|
|
1970
|
-
|
|
2035
|
+
/* Linked (Active State) styles */
|
|
2036
|
+
.sso-toggle-card.linked {
|
|
2037
|
+
background: rgba(80, 250, 123, 0.02);
|
|
2038
|
+
border-color: rgba(80, 250, 123, 0.2);
|
|
2039
|
+
box-shadow: 0 4px 16px rgba(80, 250, 123, 0.04);
|
|
1971
2040
|
}
|
|
1972
2041
|
|
|
1973
|
-
.sso-
|
|
1974
|
-
background:
|
|
1975
|
-
border-color:
|
|
1976
|
-
color: #ffffff;
|
|
2042
|
+
.sso-toggle-card.linked:hover {
|
|
2043
|
+
background: rgba(80, 250, 123, 0.04);
|
|
2044
|
+
border-color: rgba(80, 250, 123, 0.35);
|
|
1977
2045
|
}
|
|
1978
2046
|
|
|
1979
|
-
.sso-
|
|
1980
|
-
background: #
|
|
2047
|
+
.sso-toggle-card.linked .toggle-status-indicator.top {
|
|
2048
|
+
background: var(--clr-accent, #50fa7b);
|
|
2049
|
+
box-shadow: 0 2px 10px rgba(80, 250, 123, 0.5);
|
|
1981
2050
|
}
|
|
1982
|
-
|
|
2051
|
+
|
|
2052
|
+
.sso-toggle-card.linked .toggle-state-text {
|
|
2053
|
+
color: var(--clr-accent, #50fa7b);
|
|
2054
|
+
font-weight: bold;
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
/* Unlinked (Inactive/Faded State) styles */
|
|
2058
|
+
.sso-toggle-card.unlinked {
|
|
2059
|
+
opacity: 0.75;
|
|
2060
|
+
}
|
|
2061
|
+
|
|
2062
|
+
.sso-toggle-card.unlinked:hover {
|
|
2063
|
+
opacity: 1.0;
|
|
2064
|
+
}
|
|
2065
|
+
|
|
2066
|
+
.sso-toggle-card.unlinked .toggle-status-indicator.bottom {
|
|
2067
|
+
background: rgba(255, 85, 85, 0.4);
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
.sso-toggle-card.unlinked .toggle-state-text {
|
|
2071
|
+
color: var(--clr-text-secondary, #8fa08f);
|
|
2072
|
+
}
|
|
2073
|
+
|
|
2074
|
+
/* Historical/Disabled state */
|
|
2075
|
+
.sso-toggle-card.disabled {
|
|
2076
|
+
pointer-events: none;
|
|
2077
|
+
opacity: 0.4;
|
|
2078
|
+
}
|
|
2079
|
+
`;var Tl=`<div id="container" class="component-container">
|
|
1983
2080
|
<div id="historical-warning-banner" class="warning-banner hidden">
|
|
1984
2081
|
<span>\u26A0\uFE0F Viewing Historical Frame (Past State)</span>
|
|
1985
2082
|
</div>
|
|
@@ -2057,11 +2154,39 @@ h2 {
|
|
|
2057
2154
|
|
|
2058
2155
|
<!-- SSO Identity Linking Card -->
|
|
2059
2156
|
<div id="sso-link-card" class="card hidden">
|
|
2060
|
-
<h3>
|
|
2061
|
-
<p class="description">
|
|
2062
|
-
<div class="sso-
|
|
2063
|
-
|
|
2064
|
-
<
|
|
2157
|
+
<h3>Identity Providers</h3>
|
|
2158
|
+
<p class="description">Securely link or unlink external OAuth2 providers to delegate sync access to this identity.</p>
|
|
2159
|
+
<div class="sso-toggle-group">
|
|
2160
|
+
<!-- Google Card Toggle -->
|
|
2161
|
+
<div id="btn-link-google" class="sso-toggle-card google" role="button" tabindex="0">
|
|
2162
|
+
<div class="toggle-status-indicator top"></div>
|
|
2163
|
+
<div class="toggle-content">
|
|
2164
|
+
<!-- Custom Google SVG Icon -->
|
|
2165
|
+
<svg class="sso-icon" viewBox="0 0 24 24">
|
|
2166
|
+
<path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
|
|
2167
|
+
<path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
|
|
2168
|
+
<path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z"/>
|
|
2169
|
+
<path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"/>
|
|
2170
|
+
</svg>
|
|
2171
|
+
<span class="provider-label">Google</span>
|
|
2172
|
+
<span class="toggle-state-text">Unlinked</span>
|
|
2173
|
+
</div>
|
|
2174
|
+
<div class="toggle-status-indicator bottom"></div>
|
|
2175
|
+
</div>
|
|
2176
|
+
|
|
2177
|
+
<!-- GitHub Card Toggle -->
|
|
2178
|
+
<div id="btn-link-github" class="sso-toggle-card github" role="button" tabindex="0">
|
|
2179
|
+
<div class="toggle-status-indicator top"></div>
|
|
2180
|
+
<div class="toggle-content">
|
|
2181
|
+
<!-- Custom GitHub SVG Icon -->
|
|
2182
|
+
<svg class="sso-icon" viewBox="0 0 24 24" fill="currentColor">
|
|
2183
|
+
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/>
|
|
2184
|
+
</svg>
|
|
2185
|
+
<span class="provider-label">GitHub</span>
|
|
2186
|
+
<span class="toggle-state-text">Unlinked</span>
|
|
2187
|
+
</div>
|
|
2188
|
+
<div class="toggle-status-indicator bottom"></div>
|
|
2189
|
+
</div>
|
|
2065
2190
|
</div>
|
|
2066
2191
|
<div id="sso-status-msg" class="status-msg hidden"></div>
|
|
2067
2192
|
</div>
|
|
@@ -2078,7 +2203,7 @@ h2 {
|
|
|
2078
2203
|
</div>
|
|
2079
2204
|
</div>
|
|
2080
2205
|
</div>
|
|
2081
|
-
`;var fe=Vt||!0,wl="ibgib-keystone-details",Yn=class extends ge{static{f(this,"KeystoneDetailsComponentMeta")}lc="[KeystoneDetailsComponentMeta]";routeRegExp=new RegExp(`^${wl}$`);componentName=wl;constructor(){super(Ce()),customElements.get(this.componentName)||customElements.define(this.componentName,Fi)}async createInstance({path:e,ibGibAddr:t}){let o=`${this.lc}[${this.createInstance.name}]`,i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:vl,css:[Ae,Il]}),i}},Fi=class extends Oe{static{f(this,"KeystoneDetailsComponentInstance")}lc="[KeystoneDetailsComponentInstance]";staticIbGib;get ibGib(){return this.staticIbGib}globalActiveAddr=null;isHistoricalFrame=!1;_onIdentityChanged=null;keystoneCache=new Map;constructor(){super()}async initialize(e){let t=`${this.lc}[${this.initialize.name}]`;try{fe&&console.log(`${t} starting... (I: 4c9328643a18e56b56e57292c87bd226)`),await super.initialize(e),await this.loadIbGib({getLatest:!1})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{fe&&console.log(`${t} complete.`)}}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let o=z(O).metaspace;if(!o)return{username:"",description:"",isPrimary:!1,n:0};let i=await o.getLocalUserSpace({lock:!1});if(!i)return{username:"",description:"",isPrimary:!1,n:0};try{let l=await new Se().getKeystoneCommonInfo({addr:e,metaspace:o,space:i});if(l){let c={username:l.name,description:l.description,isPrimary:l.isPrimary,n:l.n};return this.keystoneCache.set(e,c),c}}catch(r){console.warn(`Error getting details for keystone ${e}: ${y(r)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async created(){let e=`${this.lc}[${this.created.name}]`;try{fe&&console.log(`${e} starting... (I: 0b2c6debcdac9db9b7928aa8695ed826)`),this.elements={};let t=this.shadowRoot;this.elements.identityDetailsViewEl=t.getElementById("identity-details-view"),this.elements.identityAddrEl=t.getElementById("identity-addr"),this.elements.identityGenEl=t.getElementById("identity-gen"),this.elements.identityTimestampEl=t.getElementById("identity-timestamp"),this.elements.identityUuidEl=t.getElementById("identity-uuid"),this.elements.identityNameEl=t.getElementById("identity-name"),this.elements.identityDescriptionEl=t.getElementById("identity-description"),this.elements.identityFrameDetailsEl=t.getElementById("identity-frame-details"),this.elements.identityAggrDetailsEl=t.getElementById("identity-aggr-details"),this.elements.poolsContainerEl=t.getElementById("pools-container"),this.elements.btnVerifyChainEl=t.getElementById("btn-verify-chain"),this.elements.btnSetActiveEl=t.getElementById("btn-set-active"),this.elements.verificationStatusEl=t.getElementById("verification-status"),this.elements.rawAccordionHeaderEl=t.getElementById("raw-accordion-header"),this.elements.rawAccordionContentEl=t.getElementById("raw-accordion-content"),this.elements.rawKeystoneJsonEl=t.getElementById("raw-keystone-json"),this.elements.delegatesCardEl=t.getElementById("delegates-card"),this.elements.delegatesListEl=t.getElementById("delegates-list"),this.elements.containerEl=t.getElementById("container"),this.elements.historicalWarningBannerEl=t.getElementById("historical-warning-banner"),this.elements.ssoLinkCardEl=t.getElementById("sso-link-card"),this.elements.btnLinkGoogleEl=t.getElementById("btn-link-google"),this.elements.btnLinkGithubEl=t.getElementById("btn-link-github"),this.elements.ssoStatusMsgEl=t.getElementById("sso-status-msg"),this.elements.contentEl=t.getElementById("identity-details-view"),this.initHandlers(),this._onIdentityChanged=o=>{this.globalActiveAddr=o.detail?.activeIdentityAddr||null,this.updateActiveButtonState()},window.addEventListener(Le,this._onIdentityChanged),await this.resolveActiveIdentity(),await this.loadIbGib({getLatest:!1})}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{fe&&console.log(`${e} complete.`)}}async disconnected(){this._onIdentityChanged&&window.removeEventListener(Le,this._onIdentityChanged)}initHandlers(){this.elements.rawAccordionHeaderEl.addEventListener("click",()=>this.toggleAccordion()),this.elements.btnVerifyChainEl.addEventListener("click",()=>this.handleVerifyIdentityChain()),this.elements.btnSetActiveEl.addEventListener("click",()=>this.handleSetActiveIdentity()),this.elements.btnLinkGoogleEl.addEventListener("click",()=>this.handleSSOLink("google")),this.elements.btnLinkGithubEl.addEventListener("click",()=>this.handleSSOLink("github"))}toggleAccordion(){let e=this.elements.rawAccordionHeaderEl,t=this.elements.rawAccordionContentEl;e.classList.toggle("expanded"),t.classList.toggle("expanded")}async handleVerifyIdentityChain(){let e=`${this.lc}[${this.handleVerifyIdentityChain.name}]`;Q(`${e} Verifying identity keystone timeline...`),this.setVerificationStatus("Verification request sent...","info");try{this.setVerificationStatus("Verification complete. Root Keystone is verified (Genesis phase 1).","success")}catch(t){this.setVerificationStatus(`Verification failed: ${y(t)}`,"error")}}async handleSetActiveIdentity(){this.ibGibAddr&&window.dispatchEvent(new CustomEvent(De,{detail:{activeIdentityAddr:this.ibGibAddr},bubbles:!0,composed:!0}))}setVerificationStatus(e,t){let o=this.elements.verificationStatusEl;o.textContent=e,o.className=`status-msg ${t}`,o.classList.remove("hidden")}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{let t=z(O).identity?.domainIdentity;this.globalActiveAddr=t?S({ibGib:t}):null}catch(t){console.error(`${e} ${y(t)}`),this.globalActiveAddr=null}}async loadIbGib(e){let t=`${this.lc}[${this.loadIbGib.name}]`;try{if(fe&&console.log(`${t} starting... (I: f0f7e8d52cbdc37bec844b2875996e26)`),!this.ibGibAddr)return;let o=z(O).metaspace;if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: a9864dbbaefc1082ce7bd228ebd67c26)");let i=await o.getLocalUserSpace({lock:!1});if(!i)throw new Error("(UNEXPECTED) space falsy and we couldn't get default local user space from metaspace? (E: fa298edcecbda889cfd7b228fbd57c26)");let r=await o.get({addrs:[this.ibGibAddr],space:i});if(r.success&&r.ibGibs&&r.ibGibs.length===1)this.staticIbGib=r.ibGibs[0];else{let c=r.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find address ${this.ibGibAddr}. addrsNotFound: ${c}? resGet.errorMsg: ${r.errorMsg} (E: e0e5c9b7de2837bc902fa88390cd9f26)`)}await this.updateFrameDetailsView()}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{fe&&console.log(`${t} complete.`)}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;try{fe&&console.log(`${e} starting... (I: c8aa086352d8079708e00f78b6ac0826)`),await super.renderUI()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{fe&&console.log(`${e} complete.`)}}updateActiveButtonState(){if(!this.elements)return;let e=K({ibGibAddr:this.ibGibAddr}).tjpGib??F({ibGibAddr:this.ibGibAddr}).gib,t=this.globalActiveAddr?K({ibGibAddr:this.globalActiveAddr}).tjpGib??F({ibGibAddr:this.globalActiveAddr}).gib:null,o=!!(this.globalActiveAddr&&e===t);o?(this.elements.btnSetActiveEl.textContent="Active Identity",this.elements.btnSetActiveEl.classList.add("active-primary")):(this.elements.btnSetActiveEl.textContent="Set as Active Identity",this.elements.btnSetActiveEl.classList.remove("active-primary")),this.isHistoricalFrame?(this.elements.btnSetActiveEl.disabled=!0,this.elements.btnVerifyChainEl.disabled=!0):(this.elements.btnVerifyChainEl.disabled=!1,this.elements.btnSetActiveEl.disabled=o)}async updateFrameDetailsView(){let e=`${this.lc}[${this.updateFrameDetailsView.name}]`;try{if(fe&&console.log(`${e} starting... (I: 1fa9e66d2e78fb100874573e2db71d26)`),!this.elements)return;let t=this.ibGib;if(!t){this.clearActiveDetails();return}let o=this.ibGibAddr;this.elements.identityAddrEl.textContent=o,this.elements.identityGenEl.textContent=t.data?.n!==void 0?String(t.data.n):"0 (Genesis)";let i=t.data?.timestamp,r="N/A";if(i){let h=parseInt(i);isNaN(h)?r=new Date(i).toLocaleString():r=new Date(h).toLocaleString()}this.elements.identityTimestampEl.textContent=r,this.elements.identityUuidEl.textContent=t.data?.uuid||"N/A";let l=t.data?.frameDetails;this.elements.identityFrameDetailsEl.textContent=l?M(l):"{}";let c=!1,d=z(O).metaspace;if(d){let h=await d.getLocalUserSpace({lock:!1});if(h){try{let g=await d.getLatestAddr({addr:this.ibGibAddr,space:h});g&&g!==this.ibGibAddr&&(c=!0)}catch(g){console.warn(`${e} Error checking latest address: ${y(g)}`)}try{let b=await new Se().getAggregateDetails({latestKeystone:t,metaspace:d,space:h});this.elements.identityAggrDetailsEl.textContent=b?M(b):"{}",this.elements.identityNameEl.textContent=b?.username||b?.profile?.name||b?.name||"-",this.elements.identityDescriptionEl.textContent=b?.description||b?.profile?.description||"-"}catch(g){console.warn(`${e} Error aggregating details: ${y(g)}`),this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-"}}else this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-"}else this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-";this.isHistoricalFrame=c;let u=this.elements.historicalWarningBannerEl,p=this.elements.containerEl;u&&p&&(c?(u.classList.remove("hidden"),p.classList.add("is-historical")):(u.classList.add("hidden"),p.classList.remove("is-historical"))),this.elements.rawKeystoneJsonEl.textContent=M(t),this.renderChallengePools(t.data?.challengePools||[]),(await this.getKeystoneDetails(this.ibGibAddr)).isPrimary?(this.elements.delegatesCardEl.classList.remove("hidden"),await this.renderDelegates(t.data?.delegates),this.elements.ssoLinkCardEl.classList.remove("hidden")):(this.elements.delegatesCardEl.classList.add("hidden"),this.elements.ssoLinkCardEl.classList.add("hidden")),this.updateActiveButtonState()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{fe&&console.log(`${e} complete.`)}}clearActiveDetails(){this.elements&&(this.isHistoricalFrame=!1,this.elements.historicalWarningBannerEl&&this.elements.historicalWarningBannerEl.classList.add("hidden"),this.elements.containerEl&&this.elements.containerEl.classList.remove("is-historical"),this.elements.identityGenEl.textContent="-",this.elements.identityTimestampEl.textContent="-",this.elements.identityUuidEl.textContent="-",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-",this.elements.identityFrameDetailsEl.textContent="{}",this.elements.identityAggrDetailsEl.textContent="{}",this.elements.poolsContainerEl.innerHTML="",this.elements.delegatesListEl&&(this.elements.delegatesListEl.innerHTML=""))}renderChallengePools(e){if(!this.elements)return;let t=this.elements.poolsContainerEl;if(t.innerHTML="",!e||e.length===0){t.innerHTML='<p class="description">No challenge pools found in this keystone.</p>';return}for(let o of e){let i=document.createElement("div");i.className="pool-card";let r=o.config||{},l=r.behavior||{},c=r.allowedVerbs||[],d=o.challenges?Object.keys(o.challenges).length:0,u=!!o.isForeign,p=o.challenges||{},m=Object.entries(p).map(([h,g])=>{let b=g.hash&&g.hash.length>20?g.hash.substring(0,10)+"..."+g.hash.substring(g.hash.length-8):g.hash||"N/A";return`
|
|
2206
|
+
`;function Yn({keystone:n,providerId:e}){if(!n?.data?.challengePools)return!1;let t=`custodian-manage-${e}`;return n.data.challengePools.some(o=>o.id===t)}f(Yn,"isSsoProviderLinked");var le=Vt||!0,Cl="ibgib-keystone-details",Qn=class extends ge{static{f(this,"KeystoneDetailsComponentMeta")}lc="[KeystoneDetailsComponentMeta]";routeRegExp=new RegExp(`^${Cl}$`);componentName=Cl;constructor(){super(Se()),customElements.get(this.componentName)||customElements.define(this.componentName,Vi)}async createInstance({path:e,ibGibAddr:t}){let o=`${this.lc}[${this.createInstance.name}]`,i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:Tl,css:[Ae,wl]}),i}},Vi=class extends Oe{static{f(this,"KeystoneDetailsComponentInstance")}lc="[KeystoneDetailsComponentInstance]";staticIbGib;get ibGib(){return this.staticIbGib}globalActiveAddr=null;isHistoricalFrame=!1;_onIdentityChanged=null;keystoneCache=new Map;constructor(){super()}async initialize(e){let t=`${this.lc}[${this.initialize.name}]`;try{le&&console.log(`${t} starting... (I: 4c9328643a18e56b56e57292c87bd226)`),await super.initialize(e),await this.loadIbGib({getLatest:!1})}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{le&&console.log(`${t} complete.`)}}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let o=O(q).metaspace;if(!o)return{username:"",description:"",isPrimary:!1,n:0};let i=await o.getLocalUserSpace({lock:!1});if(!i)return{username:"",description:"",isPrimary:!1,n:0};try{let a=await new ye().getKeystoneCommonInfo({addr:e,metaspace:o,space:i});if(a){let c={username:a.name,description:a.description,isPrimary:a.isPrimary,n:a.n};return this.keystoneCache.set(e,c),c}}catch(r){console.warn(`Error getting details for keystone ${e}: ${y(r)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async created(){let e=`${this.lc}[${this.created.name}]`;try{le&&console.log(`${e} starting... (I: 0b2c6debcdac9db9b7928aa8695ed826)`),this.elements={};let t=this.shadowRoot;this.elements.identityDetailsViewEl=t.getElementById("identity-details-view"),this.elements.identityAddrEl=t.getElementById("identity-addr"),this.elements.identityGenEl=t.getElementById("identity-gen"),this.elements.identityTimestampEl=t.getElementById("identity-timestamp"),this.elements.identityUuidEl=t.getElementById("identity-uuid"),this.elements.identityNameEl=t.getElementById("identity-name"),this.elements.identityDescriptionEl=t.getElementById("identity-description"),this.elements.identityFrameDetailsEl=t.getElementById("identity-frame-details"),this.elements.identityAggrDetailsEl=t.getElementById("identity-aggr-details"),this.elements.poolsContainerEl=t.getElementById("pools-container"),this.elements.btnVerifyChainEl=t.getElementById("btn-verify-chain"),this.elements.btnSetActiveEl=t.getElementById("btn-set-active"),this.elements.verificationStatusEl=t.getElementById("verification-status"),this.elements.rawAccordionHeaderEl=t.getElementById("raw-accordion-header"),this.elements.rawAccordionContentEl=t.getElementById("raw-accordion-content"),this.elements.rawKeystoneJsonEl=t.getElementById("raw-keystone-json"),this.elements.delegatesCardEl=t.getElementById("delegates-card"),this.elements.delegatesListEl=t.getElementById("delegates-list"),this.elements.containerEl=t.getElementById("container"),this.elements.historicalWarningBannerEl=t.getElementById("historical-warning-banner"),this.elements.ssoLinkCardEl=t.getElementById("sso-link-card"),this.elements.btnLinkGoogleEl=t.getElementById("btn-link-google"),this.elements.btnLinkGithubEl=t.getElementById("btn-link-github"),this.elements.ssoStatusMsgEl=t.getElementById("sso-status-msg"),this.elements.contentEl=t.getElementById("identity-details-view"),this.initHandlers(),this._onIdentityChanged=o=>{this.globalActiveAddr=o.detail?.activeIdentityAddr||null,this.updateActiveButtonState()},window.addEventListener(Le,this._onIdentityChanged),await this.resolveActiveIdentity(),await this.loadIbGib({getLatest:!1})}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{le&&console.log(`${e} complete.`)}}async disconnected(){this._onIdentityChanged&&window.removeEventListener(Le,this._onIdentityChanged)}initHandlers(){this.elements.rawAccordionHeaderEl.addEventListener("click",()=>this.toggleAccordion()),this.elements.btnVerifyChainEl.addEventListener("click",()=>this.handleVerifyIdentityChain()),this.elements.btnSetActiveEl.addEventListener("click",()=>this.handleSetActiveIdentity()),this.elements.btnLinkGoogleEl.addEventListener("click",()=>this.handleSSOClick("google")),this.elements.btnLinkGithubEl.addEventListener("click",()=>this.handleSSOClick("github"))}toggleAccordion(){let e=this.elements.rawAccordionHeaderEl,t=this.elements.rawAccordionContentEl;e.classList.toggle("expanded"),t.classList.toggle("expanded")}async handleVerifyIdentityChain(){let e=`${this.lc}[${this.handleVerifyIdentityChain.name}]`;Q(`${e} Verifying identity keystone timeline...`),this.setVerificationStatus("Verification request sent...","info");try{this.setVerificationStatus("Verification complete. Root Keystone is verified (Genesis phase 1).","success")}catch(t){this.setVerificationStatus(`Verification failed: ${y(t)}`,"error")}}async handleSetActiveIdentity(){this.ibGibAddr&&window.dispatchEvent(new CustomEvent(ke,{detail:{activeIdentityAddr:this.ibGibAddr},bubbles:!0,composed:!0}))}setVerificationStatus(e,t){let o=this.elements.verificationStatusEl;o.textContent=e,o.className=`status-msg ${t}`,o.classList.remove("hidden")}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{let t=O(q).identity?.domainIdentity;this.globalActiveAddr=t?S({ibGib:t}):null}catch(t){console.error(`${e} ${y(t)}`),this.globalActiveAddr=null}}async loadIbGib(e){let t=`${this.lc}[${this.loadIbGib.name}]`;try{if(le&&console.log(`${t} starting... (I: f0f7e8d52cbdc37bec844b2875996e26)`),!this.ibGibAddr)return;let o=O(q).metaspace;if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: a9864dbbaefc1082ce7bd228ebd67c26)");let i=await o.getLocalUserSpace({lock:!1});if(!i)throw new Error("(UNEXPECTED) space falsy and we couldn't get default local user space from metaspace? (E: fa298edcecbda889cfd7b228fbd57c26)");let r=await o.get({addrs:[this.ibGibAddr],space:i});if(r.success&&r.ibGibs&&r.ibGibs.length===1)this.staticIbGib=r.ibGibs[0];else{let c=r.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find address ${this.ibGibAddr}. addrsNotFound: ${c}? resGet.errorMsg: ${r.errorMsg} (E: e0e5c9b7de2837bc902fa88390cd9f26)`)}await this.updateFrameDetailsView()}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{le&&console.log(`${t} complete.`)}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;try{le&&console.log(`${e} starting... (I: c8aa086352d8079708e00f78b6ac0826)`),await super.renderUI()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{le&&console.log(`${e} complete.`)}}updateActiveButtonState(){if(!this.elements)return;let e=K({ibGibAddr:this.ibGibAddr}).tjpGib??F({ibGibAddr:this.ibGibAddr}).gib,t=this.globalActiveAddr?K({ibGibAddr:this.globalActiveAddr}).tjpGib??F({ibGibAddr:this.globalActiveAddr}).gib:null,o=!!(this.globalActiveAddr&&e===t);if(o?(this.elements.btnSetActiveEl.textContent="Active Identity",this.elements.btnSetActiveEl.classList.add("active-primary")):(this.elements.btnSetActiveEl.textContent="Set as Active Identity",this.elements.btnSetActiveEl.classList.remove("active-primary")),this.isHistoricalFrame)this.elements.btnSetActiveEl.disabled=!0,this.elements.btnVerifyChainEl.disabled=!0,this.elements.btnLinkGoogleEl.classList.add("disabled"),this.elements.btnLinkGithubEl.classList.add("disabled");else{this.elements.btnVerifyChainEl.disabled=!1,this.elements.btnSetActiveEl.disabled=o,this.elements.btnLinkGoogleEl.classList.remove("disabled"),this.elements.btnLinkGithubEl.classList.remove("disabled");let i=Yn({keystone:this.ibGib,providerId:"google"}),r=Yn({keystone:this.ibGib,providerId:"github"}),a=this.elements.btnLinkGoogleEl,c=a.querySelector(".toggle-state-text");i?(a.classList.remove("unlinked"),a.classList.add("linked"),c.textContent="Google Linked \u2705"):(a.classList.remove("linked"),a.classList.add("unlinked"),c.textContent="Unlinked");let d=this.elements.btnLinkGithubEl,u=d.querySelector(".toggle-state-text");r?(d.classList.remove("unlinked"),d.classList.add("linked"),u.textContent="GitHub Linked \u2705"):(d.classList.remove("linked"),d.classList.add("unlinked"),u.textContent="Unlinked")}}async updateFrameDetailsView(){let e=`${this.lc}[${this.updateFrameDetailsView.name}]`;try{if(le&&console.log(`${e} starting... (I: 1fa9e66d2e78fb100874573e2db71d26)`),!this.elements)return;let t=this.ibGib;if(!t){this.clearActiveDetails();return}let o=this.ibGibAddr;this.elements.identityAddrEl.textContent=o,this.elements.identityGenEl.textContent=t.data?.n!==void 0?String(t.data.n):"0 (Genesis)";let i=t.data?.timestamp,r="N/A";if(i){let h=parseInt(i);isNaN(h)?r=new Date(i).toLocaleString():r=new Date(h).toLocaleString()}this.elements.identityTimestampEl.textContent=r,this.elements.identityUuidEl.textContent=t.data?.uuid||"N/A";let a=t.data?.frameDetails;this.elements.identityFrameDetailsEl.textContent=a?M(a):"{}";let c=!1,d=O(q).metaspace;if(d){let h=await d.getLocalUserSpace({lock:!1});if(h){try{let g=await d.getLatestAddr({addr:this.ibGibAddr,space:h});g&&g!==this.ibGibAddr&&(c=!0)}catch(g){console.warn(`${e} Error checking latest address: ${y(g)}`)}try{let b=await new ye().getAggregateDetails({latestKeystone:t,metaspace:d,space:h});this.elements.identityAggrDetailsEl.textContent=b?M(b):"{}",this.elements.identityNameEl.textContent=b?.username||b?.profile?.name||b?.name||"-",this.elements.identityDescriptionEl.textContent=b?.description||b?.profile?.description||"-"}catch(g){console.warn(`${e} Error aggregating details: ${y(g)}`),this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-"}}else this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-"}else this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-";this.isHistoricalFrame=c;let u=this.elements.historicalWarningBannerEl,p=this.elements.containerEl;u&&p&&(c?(u.classList.remove("hidden"),p.classList.add("is-historical")):(u.classList.add("hidden"),p.classList.remove("is-historical"))),this.elements.rawKeystoneJsonEl.textContent=M(t),this.renderChallengePools(t.data?.challengePools||[]),(await this.getKeystoneDetails(this.ibGibAddr)).isPrimary?(this.elements.delegatesCardEl.classList.remove("hidden"),await this.renderDelegates(t.data?.delegates),this.elements.ssoLinkCardEl.classList.remove("hidden")):(this.elements.delegatesCardEl.classList.add("hidden"),this.elements.ssoLinkCardEl.classList.add("hidden")),this.updateActiveButtonState()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{le&&console.log(`${e} complete.`)}}clearActiveDetails(){this.elements&&(this.isHistoricalFrame=!1,this.elements.historicalWarningBannerEl&&this.elements.historicalWarningBannerEl.classList.add("hidden"),this.elements.containerEl&&this.elements.containerEl.classList.remove("is-historical"),this.elements.identityGenEl.textContent="-",this.elements.identityTimestampEl.textContent="-",this.elements.identityUuidEl.textContent="-",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-",this.elements.identityFrameDetailsEl.textContent="{}",this.elements.identityAggrDetailsEl.textContent="{}",this.elements.poolsContainerEl.innerHTML="",this.elements.delegatesListEl&&(this.elements.delegatesListEl.innerHTML=""))}renderChallengePools(e){if(!this.elements)return;let t=this.elements.poolsContainerEl;if(t.innerHTML="",!e||e.length===0){t.innerHTML='<p class="description">No challenge pools found in this keystone.</p>';return}for(let o of e){let i=document.createElement("div");i.className="pool-card";let r=o.config||{},a=r.behavior||{},c=r.allowedVerbs||[],d=o.challenges?Object.keys(o.challenges).length:0,u=!!o.isForeign,p=o.challenges||{},m=Object.entries(p).map(([h,g])=>{let b=g.hash&&g.hash.length>20?g.hash.substring(0,10)+"..."+g.hash.substring(g.hash.length-8):g.hash||"N/A";return`
|
|
2082
2207
|
<div class="pool-challenge-item">
|
|
2083
2208
|
<span class="challenge-id">${h}</span>
|
|
2084
2209
|
<span class="challenge-hash" title="${g.hash||""}">${b}</span>
|
|
@@ -2095,7 +2220,7 @@ h2 {
|
|
|
2095
2220
|
</div>
|
|
2096
2221
|
<div class="pool-field">
|
|
2097
2222
|
<label>FIFO / Random cost</label>
|
|
2098
|
-
<span>FIFO: ${
|
|
2223
|
+
<span>FIFO: ${a.selectSequentially??0}, Rand: ${a.selectRandomly??0}</span>
|
|
2099
2224
|
</div>
|
|
2100
2225
|
</div>
|
|
2101
2226
|
|
|
@@ -2112,9 +2237,9 @@ h2 {
|
|
|
2112
2237
|
No registered delegates.
|
|
2113
2238
|
</td>
|
|
2114
2239
|
</tr>
|
|
2115
|
-
`;return}for(let[o,i]of Object.entries(e)){let r=document.createElement("tr"),
|
|
2240
|
+
`;return}for(let[o,i]of Object.entries(e)){let r=document.createElement("tr"),a=document.createElement("td");a.textContent="Loading...";let c=document.createElement("td");c.textContent=o,c.title=o;let d=document.createElement("td");d.textContent=i.allowedVerbs?i.allowedVerbs.join(", "):"-",d.title=d.textContent;let u=document.createElement("td"),p=document.createElement("button");p.className="action-btn secondary small",p.textContent="View Details",p.addEventListener("click",()=>{i.delegateAddr&&this.dispatchEvent(new CustomEvent("ibgib-view-keystone-details",{detail:{addr:i.delegateAddr},bubbles:!0,composed:!0}))}),u.appendChild(p),r.appendChild(a),r.appendChild(c),r.appendChild(d),r.appendChild(u),t.appendChild(r),i.delegateAddr?this.getKeystoneDetails(i.delegateAddr).then(m=>{let h=[];m.username&&h.push(m.username),m.description&&h.push(m.description),a.textContent=h.join(" / ")||"Unnamed Delegate",a.title=`Addr: ${i.delegateAddr}
|
|
2116
2241
|
`+h.join(`
|
|
2117
|
-
`)}).catch(m=>{
|
|
2242
|
+
`)}).catch(m=>{a.textContent="Unknown Delegate"}):a.textContent="No Address"}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{le&&console.log(`${e} starting... (I: 243a88c1d4689c779bbbf2a4abd5da26)`),console.warn(`${e} this component currently designed expecting that this does not hit (W: 95dc018b87027287e860de0826146826)`),await super.handleContextUpdated()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{le&&console.log(`${e} complete.`)}}async handleNewContextChild({childIbGib:e}){let t=`${this.lc}[${this.handleNewContextChild.name}]`;try{le&&console.log(`${t} starting... (I: b04dc63842f871658840233485659726)`),await super.handleNewContextChild({childIbGib:e}),console.warn(`${t} this component currently designed expecting that this does not hit (W: 95dc018b87027287e860de0826146826)`)}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{le&&console.log(`${t} complete.`)}}async handleSSOLink(e){let t=`${this.lc}[${this.handleSSOLink.name}]`;this.setSSOStatus(`Linking ${e}...`,"info");try{let o=await fetch("/api/identity/sso/config");if(!o.ok)throw new Error(`Failed to fetch SSO config from server: ${o.statusText}`);let i=await o.json();if(!i.success||!i.providers)throw new Error(`SSO configuration fetch failed: ${i.message||"unknown error"}`);let r=i.providers.find(g=>g.providerId===e);if(!r)throw new Error(`SSO provider '${e}' is not configured on the server.`);let a=(Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,32),c={providerId:e,parentTjpAddr:this.ibGibAddr,userNonce:a},d=btoa(JSON.stringify(c)),u=`${r.authUrl}?client_id=${r.clientId}&redirect_uri=${encodeURIComponent(r.redirectUri)}&response_type=code&scope=${encodeURIComponent(r.scope)}&state=${encodeURIComponent(d)}`,p=window.open(u,"sso-oauth-popup","width=600,height=700,status=yes,toolbar=no,menubar=no,location=yes");if(!p)throw new Error("Popup blocked by browser. Please enable popups for this site.");let m,h=f(async g=>{if(g.origin!==window.location.origin)return;let b=g.data;b&&b.type==="sso-oauth-callback"&&(window.removeEventListener("message",h),clearInterval(m),await this.handleSSOLinkCallback(b.code,c,r.redirectUri))},"messageListener");window.addEventListener("message",h),m=setInterval(()=>{if(p.closed){clearInterval(m),window.removeEventListener("message",h);let g=this.elements.ssoStatusMsgEl;g.textContent&&g.textContent.startsWith("Linking")&&this.setSSOStatus("Linking cancelled (window closed).","error")}},500)}catch(o){console.error(`${t} SSO link initiation failed: ${y(o)}`),this.setSSOStatus(`Link failed: ${y(o)}`,"error")}}setSSOStatus(e,t){let o=this.elements.ssoStatusMsgEl;o.textContent=e,o.className=`status-msg ${t}`,o.classList.remove("hidden")}async handleSSOLinkCallback(e,t,o){let i=`${this.lc}[${this.handleSSOLinkCallback.name}]`;this.setSSOStatus("Retrieving challenge pool configuration from server...","info");try{let r=await fetch("/api/identity/sso/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,providerId:t.providerId,parentTjpAddr:t.parentTjpAddr,userNonce:t.userNonce,redirectUri:o})});if(!r.ok){let v=await r.json().catch(()=>({}));throw new Error(`Server link exchange failed: ${v.message||r.statusText}`)}let a=await r.json();if(!a.success||!a.custodianPool)throw new Error(`Failed to retrieve custodian challenge pool: ${a.message||"unknown error"}`);let c=a.custodianPool,d=new ye,u,p=!1,m=0,h=8;for(;m<h&&!p;){try{let v=m===0?"Link successful! Enter your local Master Secret (Passphrase) to sign and register the custodian pool":`Incorrect passphrase. Please try again (${h-m} tries remaining):`;u=await no({msg:v,confirm:!1})}catch{le&&console.log(`${i}[promptForSecret] user cancelled (I: 911ff1fb0234949228481968e9087626)`),u=void 0;break}if(!u)break;p=await d.verifySigningSecret({keystoneIbGib:this.ibGib,signingSecret:u,poolId:"manage"}),p||m++}if(!p){this.setSSOStatus("Link cancelled or failed (incorrect passphrase).","error");return}this.setSSOStatus("Evolving identity locally and generating cryptographic signatures...","info");let g=O(q).metaspace;if(!g)throw new Error("Metaspace not found");let b=await g.getLocalUserSpace({lock:!1});if(!b)throw new Error("Local space not found");let E=await d.addPools({latestKeystone:this.ibGib,masterSecret:u,newPools:[c],metaspace:g,space:b});this.setSSOStatus("Publishing evolved identity keystone to server...","info");let I=await rt.putEvolveKeystone(t.parentTjpAddr,E,[]);if(!I.success)throw new Error(`Server synchronization rejected: ${I.message}`);await Ge({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[oe({ibGib:E})]}],metaspace:g,space:b}),this.setSSOStatus(`Successfully linked with ${t.providerId}!`,"success"),await this.loadIbGib({getLatest:!1})}catch(r){console.error(`${i} SSO callback processing failed: ${y(r)}`),this.setSSOStatus(`Link failed: ${y(r)}`,"error")}}async handleSSOClick(e){Yn({keystone:this.ibGib,providerId:e})?await this.handleSSOUnlink(e):await this.handleSSOLink(e)}async handleSSOUnlink(e){let t=`${this.lc}[${this.handleSSOUnlink.name}]`;this.setSSOStatus(`Unlinking ${e}...`,"info");try{let o=new ye,i,r=!1,a=0,c=8;for(;a<c&&!r;){try{let g=a===0?`Are you sure you want to unlink your ${e} account? If so, enter your local Master Secret (Passphrase) to authorize. Otherwise, click Cancel.`:`Incorrect passphrase. Please try again (${c-a} tries remaining):`;i=await no({msg:g,confirm:!1})}catch{i=void 0;break}if(!i)break;r=await o.verifySigningSecret({keystoneIbGib:this.ibGib,signingSecret:i,poolId:"manage"}),r||a++}if(!r){this.setSSOStatus("Unlink cancelled or failed (incorrect passphrase).","error");return}this.setSSOStatus("Evolving identity locally and removing custodian pool...","info");let d=O(q).metaspace;if(!d)throw new Error("Metaspace not found");let u=await d.getLocalUserSpace({lock:!1});if(!u)throw new Error("Local space not found");let p=`custodian-manage-${e}`,m=await o.removePools({latestKeystone:this.ibGib,masterSecret:i,poolIds:[p],metaspace:d,space:u});this.setSSOStatus("Publishing evolved identity keystone to server...","info");let h=await rt.putEvolveKeystone(S({ibGib:this.ibGib}),m,[]);if(!h.success)throw new Error(`Server synchronization rejected: ${h.message}`);await Ge({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[oe({ibGib:m})]}],metaspace:d,space:u}),this.setSSOStatus(`Successfully unlinked ${e}!`,"success"),await this.loadIbGib({getLatest:!1})}catch(o){console.error(`${t} SSO unlink failed: ${y(o)}`),this.setSSOStatus(`Unlink failed: ${y(o)}`,"error")}}};var _l=`:host {
|
|
2118
2243
|
display: block;
|
|
2119
2244
|
width: 100%;
|
|
2120
2245
|
max-width: 100%;
|
|
@@ -2160,7 +2285,7 @@ h2 {
|
|
|
2160
2285
|
flex-direction: column;
|
|
2161
2286
|
gap: 1.5rem;
|
|
2162
2287
|
}
|
|
2163
|
-
`;var
|
|
2288
|
+
`;var Sl=`<div id="container" class="scrubber-container">
|
|
2164
2289
|
<div class="scrubber-nav">
|
|
2165
2290
|
<button id="btn-scrub-first" class="action-btn scrubber-btn" title="First Frame"><<</button>
|
|
2166
2291
|
<button id="btn-scrub-prev10" class="action-btn scrubber-btn" title="Back 10 Frames">-10</button>
|
|
@@ -2175,7 +2300,7 @@ h2 {
|
|
|
2175
2300
|
<!-- Details component for the active frame will be injected here -->
|
|
2176
2301
|
</div>
|
|
2177
2302
|
</div>
|
|
2178
|
-
`;var be=Vt||!0,Cl="ibgib-keystone-scrubber",Qn=class extends ge{static{f(this,"KeystoneScrubberComponentMeta")}lc="[KeystoneScrubberComponentMeta]";routeRegExp=new RegExp(`^${Cl}$`);componentName=Cl;constructor(){super(Ce()),customElements.get(this.componentName)||customElements.define(this.componentName,Hi)}async createInstance({path:e,ibGibAddr:t}){let o=`${this.lc}[${this.createInstance.name}]`,i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:_l,css:[Ae,Tl]}),i}},Hi=class n extends Mt{static{f(this,"KeystoneScrubberComponentInstance")}lc="[KeystoneScrubberComponentInstance]";history=[];currentFrameIndex=-1;lastLoadedHistoryAddr=null;constructor(){console.log("yes this is being updated! I am just wondering if I am seeing old code in the browser, i.e., if refresh is happening or just getting cache (I: 6599db11c1086062b8f5e86db89cba26)");let e=`${n.name}[ctor]`;be&&console.log(`${e} (I: 3adca837d5c898d8e839d23c59538126)`),super()}async initialize(e){let t=`${this.lc}[${this.initialize.name}]`;try{be&&console.log(`${t} starting... (I: 75eecfc01af7f3fa9897932ec5457526)`),await super.initialize(e),await this.loadIbGib()}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{be&&console.log(`${t} complete.`)}}async created(){let e=`${this.lc}[${this.created.name}]`;try{be&&console.log(`${e} starting... (I: bc16e6212928658ed8034c75b6279526)`),this.elements={};let t=this.shadowRoot;this.elements.containerEl=t.getElementById("container"),this.elements.btnScrubFirstEl=t.getElementById("btn-scrub-first"),this.elements.btnScrubPrev10El=t.getElementById("btn-scrub-prev10"),this.elements.btnScrubPrevEl=t.getElementById("btn-scrub-prev"),this.elements.scrubberStatusEl=t.getElementById("scrubber-status"),this.elements.btnScrubNextEl=t.getElementById("btn-scrub-next"),this.elements.btnScrubNext10El=t.getElementById("btn-scrub-next10"),this.elements.btnScrubLatestEl=t.getElementById("btn-scrub-latest"),this.elements.contentEl=t.getElementById("keystone-scrubber-content"),this.initHandlers(),this.loadHistoryData().catch(o=>console.error(`${this.lc} loadHistoryData error: ${y(o)}`))}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{be&&console.log(`${e} complete.`)}}async disconnected(){}initHandlers(){this.elements.btnScrubFirstEl.addEventListener("click",()=>this.scrubFirst()),this.elements.btnScrubPrev10El.addEventListener("click",()=>this.scrubPrev10()),this.elements.btnScrubPrevEl.addEventListener("click",()=>this.scrubPrev()),this.elements.btnScrubNextEl.addEventListener("click",()=>this.scrubNext()),this.elements.btnScrubNext10El.addEventListener("click",()=>this.scrubNext10()),this.elements.btnScrubLatestEl.addEventListener("click",()=>this.scrubLatest())}async loadIbGib(){let e=`${this.lc}[${this.loadIbGib.name}]`;try{if(be&&console.log(`${e} starting... (I: a4a9181bbb58a22cc71c8745a91ec426)`),!this.ibGibAddr)return;await super.loadIbGib(),await this.loadHistoryData()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{be&&console.log(`${e} complete.`)}}async activateIbGib({addr:e,ibGib:t}){let o=`${this.lc}[activateIbGib]`;try{if(be&&console.log(`${o} starting... (I: 890a8cb88f72c918a8bcf82c8af63e26)`),!e)return;let i=await this.getLoadedChildInfo({addr:e,ibGib:t}),r=this.activeChildInfo;r&&(r.active=!1),i.active=!0,await(await le()).inject({parentEl:this.elements.contentEl,componentToInject:i.component})}catch(i){console.error(`${o} ${y(i)}`)}}async loadHistoryData(){!this.ibGibAddr||!this.elements||(this.ibGibAddr!==this.lastLoadedHistoryAddr&&(await this.loadHistory(this.ibGibAddr),this.lastLoadedHistoryAddr=this.ibGibAddr),await this.scrubTo(this.history.length-1))}async loadHistory(e){let t=`${this.lc}[loadHistory]`;this.history=[],this.currentFrameIndex=-1;let o=z(O).metaspace;if(!o)return;let i=await o.getLocalUserSpace({lock:!1});if(!i)return;let r=e,l=[];for(;r;){let c=await o.get({addr:r,space:i});if(!c.success||!c.ibGibs||c.ibGibs.length===0){console.warn(`${t} Could not find frame at ${r}`);break}let d=c.ibGibs[0];if(l.push(r),d.data?.n===0)break;let u=d.rel8ns?.past;r=u&&u.length>0?u[u.length-1]:void 0}this.history=l.reverse(),this.currentFrameIndex=this.history.length-1}async scrubTo(e){if(this.history.length===0)return;this.currentFrameIndex=Math.max(0,Math.min(e,this.history.length-1)),this.updateScrubberUI();let t=this.history[this.currentFrameIndex];await this.activateIbGib({addr:t})}scrubFirst(){this.scrubTo(0)}scrubPrev10(){this.scrubTo(this.currentFrameIndex-10)}scrubPrev(){this.scrubTo(this.currentFrameIndex-1)}scrubNext(){this.scrubTo(this.currentFrameIndex+1)}scrubNext10(){this.scrubTo(this.currentFrameIndex+10)}scrubLatest(){this.scrubTo(this.history.length-1)}updateScrubberUI(){this.elements&&(this.elements.scrubberStatusEl.textContent=`Frame ${this.currentFrameIndex+1} / ${this.history.length}`,this.elements.btnScrubFirstEl.disabled=this.currentFrameIndex===0,this.elements.btnScrubPrev10El.disabled=this.currentFrameIndex===0,this.elements.btnScrubPrevEl.disabled=this.currentFrameIndex===0,this.elements.btnScrubNextEl.disabled=this.currentFrameIndex===this.history.length-1,this.elements.btnScrubNext10El.disabled=this.currentFrameIndex===this.history.length-1,this.elements.btnScrubLatestEl.disabled=this.currentFrameIndex===this.history.length-1)}async getLoadedChildInfo({addr:e,ibGib:t}){let o=`${this.lc}[${this.getLoadedChildInfo.name}]`;try{if(be&&console.log(`${o} starting... (I: 9eea188f6b55f04b483fbda8a110f826)`),!e)throw new Error("(UNEXPECTED) addr falsy?");let i=K({ibGibAddr:e}).tjpGib??F({ibGibAddr:e}).gib,r=f(async()=>{let u=await(await le()).getComponentInstance({path:"ibgib-keystone-details",ibGibAddr:e,useRegExpPrefilter:!0});if(!u)throw new Error("(UNEXPECTED) detailsComponent falsy?");return u},"fnCreateAndLoadChildComponent"),l,c=this.childInfos.filter(d=>d.addr===e);if(c.length>0){if(c.length!==1)throw new Error("(UNEXPECTED) filtered.length !== 1?");l=c[0],l.component||(l.component=await r())}else{let d=await r();t=d.ibGib??t;let u=await this.addChild({addr:e,ibGib:t});l={addr:e,childBtnEl:u,component:d,active:!1},this.childInfos.push(l)}return l}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{be&&console.log(`${o} complete.`)}}async addChild({addr:e,ibGib:t}){let o=`${this.lc}[${this.addChild.name}]`;try{be&&console.log(`${o} starting... (I: 824f98b6f9a2c922f8b3a9f67ad63e26)`);let i=document.createElement("div");return i.style.display="none",i}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{be&&console.log(`${o} complete.`)}}};var Vi=class{static{f(this,"SpaceGibShellService")}lc="[SpaceGibShellService]";initialized;leftPanelState="collapsed";rightPanelState="collapsed";isResizingLeft=!1;isResizingRight=!1;isResizingFooter=!1;constructor(){this.initialized=this.initialize()}async initialize(){this.initElements(),this.initEventHandlers(),await this.registerComponents()}initElements(){let e=`${this.lc}[${this.initElements.name}]`;try{this.updateCssVariables()}catch(t){console.error(`${e} ${y(t)}`)}}initEventHandlers(){let e=`${this.lc}[${this.initEventHandlers.name}]`;try{let t=document.getElementById(Nr);t&&t.addEventListener("click",()=>this.toggleLeftPanel());let o=document.getElementById($r);o&&o.addEventListener("click",()=>this.toggleRightPanel());let i=document.getElementById(Ar);i&&(i.addEventListener("mousedown",()=>{this.leftPanelState==="expanded"&&(this.isResizingLeft=!0)}),i.addEventListener("dblclick",()=>this.toggleLeftPanel()));let r=document.getElementById(xr);r&&(r.addEventListener("mousedown",()=>{this.rightPanelState==="expanded"&&(this.isResizingRight=!0)}),r.addEventListener("dblclick",()=>this.toggleRightPanel()));let l=document.getElementById(Pr);l&&l.addEventListener("mousedown",()=>this.isResizingFooter=!0),window.addEventListener("mousemove",p=>this.handleMouseMove(p)),window.addEventListener("mouseup",()=>this.handleMouseUp());let c=document.getElementById(Rr);c&&c.addEventListener("click",()=>this.showIdentityManager());let d,u=!1;window.addEventListener(wt,p=>{let{isBusy:m,title:h,msg:g,animationEmoji:b}=p.detail;m?(u=!0,d?d.update({title:h,msg:g,animationEmoji:b}):lr({title:h||"Processing...",msg:g||"Please do not navigate away or refresh.",isBusy:!0,animationEmoji:b}).then(E=>{u?d=E:E.close()}).catch(E=>{console.error(`${e}[showFullscreenDialog] ${y(E)}`)})):(u=!1,d&&(d.close(),d=void 0))})}catch(t){console.error(`${e} ${y(t)}`)}}async showIdentityManager(){let e=`${this.lc}[${this.showIdentityManager.name}]`;try{let o=await(await le()).getComponentInstance({path:"ibgib-identity-manager",ibGibAddr:q,useRegExpPrefilter:!0}),i=document.getElementById(io);i&&o&&(i.innerHTML="",i.appendChild(o))}catch(t){console.error(`${e} ${y(t)}`)}}async showKeystoneCreator(){let e=`${this.lc}[${this.showKeystoneCreator.name}]`;try{let o=await(await le()).getComponentInstance({path:"ibgib-keystone-creator",ibGibAddr:q,useRegExpPrefilter:!0}),i=document.getElementById(io);i&&o&&(i.innerHTML="",i.appendChild(o))}catch(t){console.error(`${e} ${y(t)}`)}}toggleLeftPanel(){this.leftPanelState=this.leftPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(Cr);e&&(this.leftPanelState==="collapsed"?e.classList.add("collapsed"):e.classList.remove("collapsed"))}toggleRightPanel(){this.rightPanelState=this.rightPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(Sr);e&&(this.rightPanelState==="collapsed"?e.classList.add("collapsed"):e.classList.remove("collapsed"))}handleMouseMove(e){if(!(!this.isResizingLeft&&!this.isResizingRight&&!this.isResizingFooter)){if(e.preventDefault(),this.isResizingLeft){let t=Math.max(100,Math.min(e.clientX,600));document.documentElement.style.setProperty("--left-panel-width",`${t}px`)}if(this.isResizingRight){let t=Math.max(100,Math.min(window.innerWidth-e.clientX,600));document.documentElement.style.setProperty("--right-panel-width",`${t}px`)}if(this.isResizingFooter){let t=Math.max(24,Math.min(window.innerHeight-e.clientY,400));document.documentElement.style.setProperty("--footer-panel-height",`${t}px`)}}}handleMouseUp(){this.isResizingLeft=!1,this.isResizingRight=!1,this.isResizingFooter=!1}updateCssVariables(){}async registerComponents(){let e=`${this.lc}[${this.registerComponents.name}]`;try{let t=[new Wn,new Kn,new Xn,new Yn,new Qn],o=await le();for(let i of t)o.registerComponentMeta(i)}catch(t){throw console.error(`${e} ${y(t)}`),t}}async onEngineReady(){let e=`${this.lc}[${this.onEngineReady.name}]`;try{await this.initialized,console.log(`${e} SpaceGib Shell Service is ready.`);let t=document.getElementById("status-section");t&&(t.style.display="none");let i=await(await le()).getComponentInstance({path:"ibgib-identity-header",ibGibAddr:q,useRegExpPrefilter:!0}),r=document.getElementById("identity-header-container");r&&i&&(r.innerHTML="",r.appendChild(i)),window.dispatchEvent(new CustomEvent(sr,{detail:{timestamp:Date.now()}}))}catch(t){console.error(`${e} ${y(t)}`)}}};function El(){let n="[getSpaceGibShellSvc]",e=z(O);return e.spaceGibShellSvc||(typeof console<"u"&&console.log(`${n} initializing SpaceGibShellService singleton on globalThis... (I: genuuid)`),e.spaceGibShellSvc=new Vi),e.spaceGibShellSvc}f(El,"getSpaceGibShellSvc");export{Ot as a,qr as b,Xe as c,Ye as d,zt as e,Ue as f,lb as g,cb as h,X as i,db as j,xe as k,tt as l,Ah as m,yt as n,qn as o,El as p};
|
|
2303
|
+
`;var be=Vt||!0,Al="ibgib-keystone-scrubber",Zn=class extends ge{static{f(this,"KeystoneScrubberComponentMeta")}lc="[KeystoneScrubberComponentMeta]";routeRegExp=new RegExp(`^${Al}$`);componentName=Al;constructor(){super(Se()),customElements.get(this.componentName)||customElements.define(this.componentName,Bi)}async createInstance({path:e,ibGibAddr:t}){let o=`${this.lc}[${this.createInstance.name}]`,i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:Sl,css:[Ae,_l]}),i}},Bi=class n extends Mt{static{f(this,"KeystoneScrubberComponentInstance")}lc="[KeystoneScrubberComponentInstance]";history=[];currentFrameIndex=-1;lastLoadedHistoryAddr=null;constructor(){console.log("yes this is being updated! I am just wondering if I am seeing old code in the browser, i.e., if refresh is happening or just getting cache (I: 6599db11c1086062b8f5e86db89cba26)");let e=`${n.name}[ctor]`;be&&console.log(`${e} (I: 3adca837d5c898d8e839d23c59538126)`),super()}async initialize(e){let t=`${this.lc}[${this.initialize.name}]`;try{be&&console.log(`${t} starting... (I: 75eecfc01af7f3fa9897932ec5457526)`),await super.initialize(e),await this.loadIbGib()}catch(o){throw console.error(`${t} ${y(o)}`),o}finally{be&&console.log(`${t} complete.`)}}async created(){let e=`${this.lc}[${this.created.name}]`;try{be&&console.log(`${e} starting... (I: bc16e6212928658ed8034c75b6279526)`),this.elements={};let t=this.shadowRoot;this.elements.containerEl=t.getElementById("container"),this.elements.btnScrubFirstEl=t.getElementById("btn-scrub-first"),this.elements.btnScrubPrev10El=t.getElementById("btn-scrub-prev10"),this.elements.btnScrubPrevEl=t.getElementById("btn-scrub-prev"),this.elements.scrubberStatusEl=t.getElementById("scrubber-status"),this.elements.btnScrubNextEl=t.getElementById("btn-scrub-next"),this.elements.btnScrubNext10El=t.getElementById("btn-scrub-next10"),this.elements.btnScrubLatestEl=t.getElementById("btn-scrub-latest"),this.elements.contentEl=t.getElementById("keystone-scrubber-content"),this.initHandlers(),this.loadHistoryData().catch(o=>console.error(`${this.lc} loadHistoryData error: ${y(o)}`))}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{be&&console.log(`${e} complete.`)}}async disconnected(){}initHandlers(){this.elements.btnScrubFirstEl.addEventListener("click",()=>this.scrubFirst()),this.elements.btnScrubPrev10El.addEventListener("click",()=>this.scrubPrev10()),this.elements.btnScrubPrevEl.addEventListener("click",()=>this.scrubPrev()),this.elements.btnScrubNextEl.addEventListener("click",()=>this.scrubNext()),this.elements.btnScrubNext10El.addEventListener("click",()=>this.scrubNext10()),this.elements.btnScrubLatestEl.addEventListener("click",()=>this.scrubLatest())}async loadIbGib(){let e=`${this.lc}[${this.loadIbGib.name}]`;try{if(be&&console.log(`${e} starting... (I: a4a9181bbb58a22cc71c8745a91ec426)`),!this.ibGibAddr)return;await super.loadIbGib(),await this.loadHistoryData()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{be&&console.log(`${e} complete.`)}}async activateIbGib({addr:e,ibGib:t}){let o=`${this.lc}[activateIbGib]`;try{if(be&&console.log(`${o} starting... (I: 890a8cb88f72c918a8bcf82c8af63e26)`),!e)return;let i=await this.getLoadedChildInfo({addr:e,ibGib:t}),r=this.activeChildInfo;r&&(r.active=!1),i.active=!0,await(await ce()).inject({parentEl:this.elements.contentEl,componentToInject:i.component})}catch(i){console.error(`${o} ${y(i)}`)}}async loadHistoryData(){!this.ibGibAddr||!this.elements||(this.ibGibAddr!==this.lastLoadedHistoryAddr&&(await this.loadHistory(this.ibGibAddr),this.lastLoadedHistoryAddr=this.ibGibAddr),await this.scrubTo(this.history.length-1))}async loadHistory(e){let t=`${this.lc}[loadHistory]`;this.history=[],this.currentFrameIndex=-1;let o=O(q).metaspace;if(!o)return;let i=await o.getLocalUserSpace({lock:!1});if(!i)return;let r=e,a=[];for(;r;){let c=await o.get({addr:r,space:i});if(!c.success||!c.ibGibs||c.ibGibs.length===0){console.warn(`${t} Could not find frame at ${r}`);break}let d=c.ibGibs[0];if(a.push(r),d.data?.n===0)break;let u=d.rel8ns?.past;r=u&&u.length>0?u[u.length-1]:void 0}this.history=a.reverse(),this.currentFrameIndex=this.history.length-1}async scrubTo(e){if(this.history.length===0)return;this.currentFrameIndex=Math.max(0,Math.min(e,this.history.length-1)),this.updateScrubberUI();let t=this.history[this.currentFrameIndex];await this.activateIbGib({addr:t})}scrubFirst(){this.scrubTo(0)}scrubPrev10(){this.scrubTo(this.currentFrameIndex-10)}scrubPrev(){this.scrubTo(this.currentFrameIndex-1)}scrubNext(){this.scrubTo(this.currentFrameIndex+1)}scrubNext10(){this.scrubTo(this.currentFrameIndex+10)}scrubLatest(){this.scrubTo(this.history.length-1)}updateScrubberUI(){this.elements&&(this.elements.scrubberStatusEl.textContent=`Frame ${this.currentFrameIndex+1} / ${this.history.length}`,this.elements.btnScrubFirstEl.disabled=this.currentFrameIndex===0,this.elements.btnScrubPrev10El.disabled=this.currentFrameIndex===0,this.elements.btnScrubPrevEl.disabled=this.currentFrameIndex===0,this.elements.btnScrubNextEl.disabled=this.currentFrameIndex===this.history.length-1,this.elements.btnScrubNext10El.disabled=this.currentFrameIndex===this.history.length-1,this.elements.btnScrubLatestEl.disabled=this.currentFrameIndex===this.history.length-1)}async getLoadedChildInfo({addr:e,ibGib:t}){let o=`${this.lc}[${this.getLoadedChildInfo.name}]`;try{if(be&&console.log(`${o} starting... (I: 9eea188f6b55f04b483fbda8a110f826)`),!e)throw new Error("(UNEXPECTED) addr falsy?");let i=K({ibGibAddr:e}).tjpGib??F({ibGibAddr:e}).gib,r=f(async()=>{let u=await(await ce()).getComponentInstance({path:"ibgib-keystone-details",ibGibAddr:e,useRegExpPrefilter:!0});if(!u)throw new Error("(UNEXPECTED) detailsComponent falsy?");return u},"fnCreateAndLoadChildComponent"),a,c=this.childInfos.filter(d=>d.addr===e);if(c.length>0){if(c.length!==1)throw new Error("(UNEXPECTED) filtered.length !== 1?");a=c[0],a.component||(a.component=await r())}else{let d=await r();t=d.ibGib??t;let u=await this.addChild({addr:e,ibGib:t});a={addr:e,childBtnEl:u,component:d,active:!1},this.childInfos.push(a)}return a}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{be&&console.log(`${o} complete.`)}}async addChild({addr:e,ibGib:t}){let o=`${this.lc}[${this.addChild.name}]`;try{be&&console.log(`${o} starting... (I: 824f98b6f9a2c922f8b3a9f67ad63e26)`);let i=document.createElement("div");return i.style.display="none",i}catch(i){throw console.error(`${o} ${y(i)}`),i}finally{be&&console.log(`${o} complete.`)}}};var qi=class{static{f(this,"SpaceGibShellService")}lc="[SpaceGibShellService]";initialized;leftPanelState="collapsed";rightPanelState="collapsed";isResizingLeft=!1;isResizingRight=!1;isResizingFooter=!1;constructor(){this.initialized=this.initialize()}async initialize(){this.initElements(),this.initEventHandlers(),await this.registerComponents()}initElements(){let e=`${this.lc}[${this.initElements.name}]`;try{this.updateCssVariables()}catch(t){console.error(`${e} ${y(t)}`)}}initEventHandlers(){let e=`${this.lc}[${this.initEventHandlers.name}]`;try{let t=document.getElementById(Gr);t&&t.addEventListener("click",()=>this.toggleLeftPanel());let o=document.getElementById(Rr);o&&o.addEventListener("click",()=>this.toggleRightPanel());let i=document.getElementById(Pr);i&&(i.addEventListener("mousedown",()=>{this.leftPanelState==="expanded"&&(this.isResizingLeft=!0)}),i.addEventListener("dblclick",()=>this.toggleLeftPanel()));let r=document.getElementById(Nr);r&&(r.addEventListener("mousedown",()=>{this.rightPanelState==="expanded"&&(this.isResizingRight=!0)}),r.addEventListener("dblclick",()=>this.toggleRightPanel()));let a=document.getElementById($r);a&&a.addEventListener("mousedown",()=>this.isResizingFooter=!0),window.addEventListener("mousemove",p=>this.handleMouseMove(p)),window.addEventListener("mouseup",()=>this.handleMouseUp());let c=document.getElementById(Mr);c&&c.addEventListener("click",()=>this.showIdentityManager());let d,u=!1;window.addEventListener(Tt,p=>{let{isBusy:m,title:h,msg:g,animationEmoji:b}=p.detail;m?(u=!0,d?d.update({title:h,msg:g,animationEmoji:b}):dr({title:h||"Processing...",msg:g||"Please do not navigate away or refresh.",isBusy:!0,animationEmoji:b}).then(E=>{u?d=E:E.close()}).catch(E=>{console.error(`${e}[showFullscreenDialog] ${y(E)}`)})):(u=!1,d&&(d.close(),d=void 0))})}catch(t){console.error(`${e} ${y(t)}`)}}async showIdentityManager(){let e=`${this.lc}[${this.showIdentityManager.name}]`;try{let o=await(await ce()).getComponentInstance({path:"ibgib-identity-manager",ibGibAddr:z,useRegExpPrefilter:!0}),i=document.getElementById(so);i&&o&&(i.innerHTML="",i.appendChild(o))}catch(t){console.error(`${e} ${y(t)}`)}}async showKeystoneCreator(){let e=`${this.lc}[${this.showKeystoneCreator.name}]`;try{let o=await(await ce()).getComponentInstance({path:"ibgib-keystone-creator",ibGibAddr:z,useRegExpPrefilter:!0}),i=document.getElementById(so);i&&o&&(i.innerHTML="",i.appendChild(o))}catch(t){console.error(`${e} ${y(t)}`)}}toggleLeftPanel(){this.leftPanelState=this.leftPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(Ar);e&&(this.leftPanelState==="collapsed"?e.classList.add("collapsed"):e.classList.remove("collapsed"))}toggleRightPanel(){this.rightPanelState=this.rightPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(xr);e&&(this.rightPanelState==="collapsed"?e.classList.add("collapsed"):e.classList.remove("collapsed"))}handleMouseMove(e){if(!(!this.isResizingLeft&&!this.isResizingRight&&!this.isResizingFooter)){if(e.preventDefault(),this.isResizingLeft){let t=Math.max(100,Math.min(e.clientX,600));document.documentElement.style.setProperty("--left-panel-width",`${t}px`)}if(this.isResizingRight){let t=Math.max(100,Math.min(window.innerWidth-e.clientX,600));document.documentElement.style.setProperty("--right-panel-width",`${t}px`)}if(this.isResizingFooter){let t=Math.max(24,Math.min(window.innerHeight-e.clientY,400));document.documentElement.style.setProperty("--footer-panel-height",`${t}px`)}}}handleMouseUp(){this.isResizingLeft=!1,this.isResizingRight=!1,this.isResizingFooter=!1}updateCssVariables(){}async registerComponents(){let e=`${this.lc}[${this.registerComponents.name}]`;try{let t=[new Wn,new Kn,new Xn,new Qn,new Zn],o=await ce();for(let i of t)o.registerComponentMeta(i)}catch(t){throw console.error(`${e} ${y(t)}`),t}}async onEngineReady(){let e=`${this.lc}[${this.onEngineReady.name}]`;try{await this.initialized,console.log(`${e} SpaceGib Shell Service is ready.`);let t=document.getElementById("status-section");t&&(t.style.display="none");let i=await(await ce()).getComponentInstance({path:"ibgib-identity-header",ibGibAddr:z,useRegExpPrefilter:!0}),r=document.getElementById("identity-header-container");r&&i&&(r.innerHTML="",r.appendChild(i)),window.dispatchEvent(new CustomEvent(lr,{detail:{timestamp:Date.now()}}))}catch(t){console.error(`${e} ${y(t)}`)}}};function vl(){let n="[getSpaceGibShellSvc]",e=O(q);return e.spaceGibShellSvc||(typeof console<"u"&&console.log(`${n} initializing SpaceGibShellService singleton on globalThis... (I: genuuid)`),e.spaceGibShellSvc=new qi),e.spaceGibShellSvc}f(vl,"getSpaceGibShellSvc");export{Ot as a,zr as b,Xe as c,Ye as d,zt as e,Ue as f,db as g,ub as h,X as i,fb as j,xe as k,tt as l,Ph as m,Et as n,qn as o,vl as p};
|
|
2179
2304
|
/*! Bundled license information:
|
|
2180
2305
|
|
|
2181
2306
|
@google/genai/dist/web/index.mjs:
|
|
@@ -2213,4 +2338,4 @@ h2 {
|
|
|
2213
2338
|
* SPDX-License-Identifier: Apache-2.0
|
|
2214
2339
|
*)
|
|
2215
2340
|
*/
|
|
2216
|
-
//# sourceMappingURL=chunk-
|
|
2341
|
+
//# sourceMappingURL=chunk-DBHMHCGD.mjs.map
|