@ibgib/space-gib 0.0.13 → 0.0.16
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 +25 -23
- package/dist/client/bootstrap.mjs.map +2 -2
- package/dist/client/chunk-6BYQ5JSY.mjs +19 -0
- package/dist/client/chunk-6BYQ5JSY.mjs.map +7 -0
- package/dist/client/{chunk-WJHRARK6.mjs → chunk-QPR6ILY2.mjs} +285 -107
- package/dist/client/{chunk-WJHRARK6.mjs.map → chunk-QPR6ILY2.mjs.map} +4 -4
- package/dist/client/index.mjs +13 -13
- package/dist/client/index.mjs.map +4 -4
- package/dist/client/script.mjs +1 -1
- package/dist/server/server.mjs +3567 -1658
- package/dist/server/server.mjs.map +4 -4
- package/package.json +6 -6
- package/src/client/AUTO-GENERATED-version.mts +1 -1
- package/src/client/bootstrap.mts +4 -0
- package/src/client/ui/shell/space-gib-shell-service.mts +17 -16
- package/src/server/server.mts +6 -0
- package/dist/client/chunk-ROJZUPPE.mjs +0 -19
- package/dist/client/chunk-ROJZUPPE.mjs.map +0 -7
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as
|
|
1
|
+
import{$b as Ls,A as xt,Ab as $t,Ac as Vs,Ba as ys,Bb as Ns,Bc as en,C as W,Cb as $s,Cc as tn,D as ps,Db as Xt,E as Xe,Eb as gi,F as dt,Gb as M,H as hs,Hb as Yt,Hc as nn,I as ms,J as re,Jc as Ei,Kc as Z,Lb as Qt,Ma as Wt,Mb as Ps,Nb as Rs,Nc as qs,Ob as Gs,Pb as Pt,Qb as Ms,Rb as ks,Sb as Ds,Va as Es,Vb as Zt,Wa as ws,X as gs,Xa as vs,Y as bs,a as p,b as Ot,c as ds,d as se,e as zt,eb as mi,ec as Us,f as lt,fb as Ye,fc as ue,g as Fe,gc as ut,h as U,hb as X,i as O,ib as z,j as y,l as We,lc as J,mb as K,n as St,o as ct,ob as Is,oc as Fs,p as Kt,pb as Ts,pc as Me,q as Jt,qb as Cs,r as At,rb as _s,sb as Ss,u as Q,ub as As,uc as Bs,v as us,vb as xs,vc as bi,w as A,wb as Nt,x as H,xb as ne,yb as Pe,yc as yi,z as fs,zb as ve,zc as jt}from"./chunk-6BYQ5JSY.mjs";var Ce=K,wi=class n{static{p(this,"IbGibComponentService")}lc=`[${n.name}]`;_registeredComponentsMeta=[];initialized;constructor(){this.initialized=this.initialize()}async initialize(){let e=`[${this.initialize.name}]`;try{Ce&&console.log(`${e} starting... (I: 1cf04e8d768f4b5c55e7c3861e2d2225)`),console.log(`${e} does nothing atow (I: 65bb46c88c82b637ad928b8bf1a07225)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Ce&&console.log(`${e} complete.`)}}registerComponentMeta(e){this._registeredComponentsMeta.push(e),Ce&&console.log(`${this.lc}[registerComponentMeta] component meta registered: ${e.constructor.name} (I: 88ddcbd0c8caa2342af0e7348f171225)`)}unregisterComponentMeta(e){this._registeredComponentsMeta=this._registeredComponentsMeta.filter(t=>t!==e),Ce&&console.log(`${this.lc}[unregisterComponentMeta] component meta unregistered: ${e.constructor.name} (I: 4e84b5274de688248984896a90f5cc25)`)}async getComponentInstance({useRegExpPrefilter:e,path:t,ibGibAddr:i}){let o=`${this.lc}[${this.getComponentInstance.name}]`;try{Ce&&console.log(`${o} starting... (I: 684ef316cbdb4a3b1fdc96096c273b25)`);let s,a=Rt.getRegisteredComponentsMeta(),c=e?a.filter(d=>{let u=d.routeRegExp?d.routeRegExp.test(t):!1;return Ce&&console.log(`${o} ${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:i}):!0){s=await d.createInstance({path:t,ibGibAddr:i});break}return s}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{Ce&&console.log(`${o} complete.`)}}async inject({parentEl:e,componentToInject:t}){let i=`${this.lc}[${this.inject.name}]`;try{if(Ce&&console.log(`${i} starting... (I: 6844cf07eaf8a5b1b106784f7db17125)`),!e)throw new Error(`${i} parentEl required. (E: 6f4eb2d682856ef47d173b970ec3c825)`);if(!t)throw new Error(`${i} componentToInject required. (E: decf0b51ad49257ce44fecbcf84c3a25)`);if(!t.meta)throw new Error(`${i} componentToInject.meta required. (E: f8827c0602ca7b0e030d0b3e2c4a4825)`);if(!t.meta.componentName)throw new Error(`${i} componentToInject.meta.componentName required. (E: 5dcae244ae32690f7b73ce27a32a3c25)`);e.innerHTML="",e.appendChild(t),e.classList.remove("fade-out")}catch(o){console.error(`${i} ${y(o)}`),e.innerHTML=`<p class="error">Error loading component for route. error:</p><br /><br /><p>${o.message}</p>`}finally{Ce&&console.log(`${i} complete.`)}}getRegisteredComponentsMeta(){return[...this._registeredComponentsMeta]}},Rt;async function ae(){let n=`[${ae.name}]`;try{return Ce&&console.log(`${n} starting... (I: 853694c88223381339103a3765129925)`),Rt||(Rt=new wi,await Rt.initialized),Rt}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{Ce&&console.log(`${n} complete.`)}}p(ae,"getComponentSvc");var Hs="left-panel";var Os="right-panel";var zs="left-resizer",Ks="right-resizer",Js="footer-resizer",Ws="btn-left-panel-toggle",Xs="btn-right-panel-toggle",Ys="btn-create-keystone",on="center-panel-content";var Ii=class{static{p(this,"KeystoneSyncService")}lc="[KeystoneSyncService]";dispatchUpdateAvailableEvent(e){typeof window<"u"&&window.dispatchEvent(new CustomEvent($t,{detail:e,bubbles:!0,composed:!0}))}async checkForKeystoneUpdate({activePrimaryAddr:e,metaspace:t,space:i}){let o=`${this.lc}[${this.checkForKeystoneUpdate.name}]`;try{if(t||(t=await M()),!t)throw new Error("Metaspace not available.");if(i||(i=await t.getLocalUserSpace({lock:!1})),!i)throw new Error("Local user space not available.");let s=await t.getLatestAddr({addr:e,space:i})||e,a=await t.get({addrs:[s],space:i}),c=a.success&&a.ibGibs&&a.ibGibs.length>0?a.ibGibs[0]:void 0,d=c?.data?.n??0,{ib:u}=H({ibGibAddr:e}),f=W({ibGibAddr:e}),h=f.tjpGib?`${u}^${f.tjpGib}`:e,m=(c?X({ibGib:c}):void 0)||h,g=await J().getKeystoneGraph(m);if(!g.success||!g.graph){let P={hasUpdate:!1,serverN:d,localN:d,serverLatestAddr:s,graph:{}};return this.dispatchUpdateAvailableEvent({activePrimaryAddr:e,hasUpdate:P.hasUpdate,serverN:P.serverN,localN:P.localN,serverLatestAddr:P.serverLatestAddr}),P}let b=g.graph,E=Object.values(b),w=Ye({ibGibs:E}),v=w[m]||w[e]||w[Object.keys(w)[0]]||[];if(v.length===0){let P={hasUpdate:!1,serverN:d,localN:d,serverLatestAddr:s,graph:b};return this.dispatchUpdateAvailableEvent({activePrimaryAddr:e,hasUpdate:P.hasUpdate,serverN:P.serverN,localN:P.localN,serverLatestAddr:P.serverLatestAddr}),P}let I=[...v].sort((P,$)=>(P.data?.n??0)-($.data?.n??0)),T=I[I.length-1],C=T.data?.n??0,N=A({ibGib:T}),x={hasUpdate:C>d,serverN:C,localN:d,serverLatestAddr:N,graph:b};return this.dispatchUpdateAvailableEvent({activePrimaryAddr:e,hasUpdate:x.hasUpdate,serverN:x.serverN,localN:x.localN,serverLatestAddr:x.serverLatestAddr}),x}catch(s){console.error(`${o} ${y(s)}`);let a={hasUpdate:!1,serverN:0,localN:0,serverLatestAddr:e,graph:{}};return this.dispatchUpdateAvailableEvent({activePrimaryAddr:e,hasUpdate:!1,serverN:0,localN:0,serverLatestAddr:e}),a}}async updateActiveKeystone({activePrimaryAddr:e,metaspace:t,space:i}){let o=`${this.lc}[${this.updateActiveKeystone.name}]`;try{if(t||(t=await M()),!t)throw new Error("Metaspace not available.");if(i||(i=await t.getLocalUserSpace({lock:!1})),!i)throw new Error("Local user space not available.");let s=await this.checkForKeystoneUpdate({activePrimaryAddr:e,metaspace:t,space:i});if(s.hasUpdate&&Object.keys(s.graph).length>0){let d=Object.values(s.graph);await t.put({ibGibs:d,space:i});let u=Ye({ibGibs:d});for(let b of Object.keys(u)){let w=[...u[b]].sort((v,I)=>(v.data?.n??0)-(I.data?.n??0));for(let v of w)await t.registerNewIbGib({ibGib:v,space:i})}let f=W({ibGibAddr:e}).tjpGib??e,m=[...u[f]||u[e]||u[Object.keys(u)[0]]].sort((b,E)=>(b.data?.n??0)-(E.data?.n??0)),g=m[m.length-1];if(g)return await ue({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[z({ibGib:g})]}],metaspace:t,space:i}),g}let a=await t.getLatestAddr({addr:e,space:i})||e,c=await t.get({addrs:[a],space:i});return c.success&&c.ibGibs&&c.ibGibs.length>0?c.ibGibs[0]:void 0}catch(s){throw console.error(`${o} ${y(s)}`),s}}},vi;function Qe(){return vi||(vi=new Ii),vi}p(Qe,"getKeystoneSyncService");var Qs=`:host {
|
|
2
2
|
display: inline-block;
|
|
3
3
|
vertical-align: middle;
|
|
4
4
|
position: relative;
|
|
@@ -315,7 +315,7 @@ import{A as Ct,Ab as St,Ac as Xt,Ba as ds,Bb as vs,Bc as Yt,C as z,Cb as Is,D as
|
|
|
315
315
|
display: none !important;
|
|
316
316
|
}
|
|
317
317
|
|
|
318
|
-
`;var
|
|
318
|
+
`;var Zs=`<div id="container" class="header-widget-container">
|
|
319
319
|
<!-- Single top control button -->
|
|
320
320
|
<button id="btn-identity-pill" class="identity-pill-btn" title="Identity Menu">
|
|
321
321
|
<!-- Authenticated State Content -->
|
|
@@ -386,7 +386,7 @@ import{A as Ct,Ab as St,Ac as Xt,Ba as ds,Bb as vs,Bc as Yt,C as z,Cb as Is,D as
|
|
|
386
386
|
<button id="btn-sync-modal-close" class="modal-close-btn hidden">Done</button>
|
|
387
387
|
</div>
|
|
388
388
|
</div>
|
|
389
|
-
</div>`;var
|
|
389
|
+
</div>`;var me=`/* =========================================================================
|
|
390
390
|
@ibgib/web-gib \u2014 Common Web Component Stylesheet
|
|
391
391
|
Shared Shadow DOM styles for buttons, tabs, inputs, cards, and status tags.
|
|
392
392
|
========================================================================= */
|
|
@@ -656,42 +656,42 @@ import{A as Ct,Ab as St,Ac as Xt,Ba as ds,Bb as vs,Bc as Yt,C as z,Cb as Is,D as
|
|
|
656
656
|
word-break: break-all;
|
|
657
657
|
color: var(--clr-accent);
|
|
658
658
|
}
|
|
659
|
-
`;var
|
|
660
|
-
`)}`);let s=
|
|
661
|
-
`)}`);let a=await
|
|
662
|
-
`)}`):this.data?.allowPrimitiveArgs||z({gib:e.gib}).isPrimitive&&i.push('arg is primitive (i.e. gib === "gib") and witness.data.allowPrimitiveArgs is falsy. (E: d0aa3d7ad4f54b01bd0023300d15ecd9)'),i}catch(i){throw console.error(`${t} ${i.message}`),i}}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(i){throw console.error(`${e} ${i.message}`),i}return t}persistOptsAndResultIbGibs({arg:e,result:t}){let i=`${this.lc}[${this.persistOptsAndResultIbGibs.name}]`;return console.warn(`${i} not implemented in this base class. Override this in descendent class. (W: 087514e851704322a4ec8069a73ce944)`),Promise.resolve()}};var zs="___whitespace___";var Se=!1;function Ks({commentText:n,addlMetadataText:e}){let t=`[${Ks.name}]`;try{if(!n)throw new Error("commentText required. (E: 22fdfd0aa0524a18b63a9405b312c99e)");let i=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 o=It({text:e,length:128});if(!o)throw new Error("(UNEXPECTED) addlMetadataText contains no safe characters? (E: dd03c578ada2836b05c94a4aa1785222)");return`comment ${i} ${o}`}else return`comment ${i}`}catch(i){throw console.error(`${t} ${i.message}`),i}}p(Ks,"getCommentIb");function Ye({ib:n}){let e=`${Ye.name}]`;try{if(Se&&console.log(`${e} starting... (I: 1a16f5e3134599eeb585eae77ee6af22)`),!n)throw new Error("ib required (E: d89f8c4df46b970585c82bc89c1c6322)");let[t,i,o]=n.split(" ");for(;i.includes("__qm__");)i=i.replace("__qm__","?");return{safeIbCommentText:i,safeIbCommentMetadataText:o}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Se&&console.log(`${e} complete.`)}}p(Ye,"parseCommentIb");async function Qe({text:n,addlMetadataText:e,saveInSpace:t,space:i,dontTrimText:o}){let s=`[${Qe.name}]`;Se&&console.log(`${s} starting...`);try{if(!n)throw new Error("text required (E: 3e3d0f555e1a83771a6548eb10943522)");if(o||(n=n.trim()),!n)throw new Error("text cannot be only whitespace when dontTrimText is falsy. (E: d6db3537b9834294836aeb70987c908e)");let a={text:n,textTimestamp:Ft()},c={parentIbGib:oe.primitive({ib:"comment"}),ib:Ks({commentText:n.trim()||zs,addlMetadataText:e}),data:a,dna:!0,tjp:{uuid:!0,timestamp:!0},nCounter:!0};Se&&console.log(`${s} opts: ${L(c)}`);let d=await oe.firstGen(c);if(t){if(!i)throw new Error("space required if saveInSpace is truthy (E: 40f69f22f21b4279a83cb746cb4b0da1)");await ds({resTransform:d,space:i})}return d}catch(a){throw console.error(`${s} ${a.message}`),a}}p(Qe,"createCommentIbGib");function Ze({ibGib:n}){let e=`[${Ze.name}]`;try{if(Se&&console.log(`${e} starting...`),!n)throw new Error("ibGib required (E: f204dac30ae548b0a049f1c4d8048502)");let{ib:t,data:i,rel8ns:o}=n;if(!o)return Se&&console.log(`${e} rel8ns falsy, NOT a comment (I: 6e145eb2d0ba46629746215a3b655fd5)`),!1;let s=o.ancestor||[];return s&&s.includes("comment^gib")?(Se&&console.log(`${e} descends from comment^gib, YES is a comment (I: 1a8557780e2e4c1580d5a2585567762b)`),!0):i?i.text&&t?.includes("comment")?(Se&&console.log(`${e} has text, and ib has 'comment', YES is a comment (I: 3aa03bcd639d4ec7abd7ead917eda3d8)`),!0):(Se&&console.log(`${e} reached end, doesn't have comment qualities. NOT a comment. (I: cfa529f27f9d490abd476c924ef77087)`),!1):(Se&&console.log(`${e} data falsy, NOT a comment (I: 30b20ff6785f432f98489f11efe24299)`),!1)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Se&&console.log(`${e} complete.`)}}p(Ze,"isComment");var B=!1,en=class n extends jt{static{p(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{B&&console.log(`${e} starting... (I: f0e65ab0f80046a59668ddfbf9f47a4a5)`),await super.initialize()}catch(t){console.error(`${e} ${y(t)}`)}finally{B&&console.log(`${e} complete.`)}}async loadNewerSelfIfAvailable(){let e=`${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;try{if(B&&console.log(`${e} starting... (I: 94755c3131f4dfa12d20fa38e2926522)`),this.metaspace){let t=C({ibGib:this}),i=await this.metaspace.getLatestAddr({ibGib:this});if(i&&i!==t){let o=await this.metaspace.get({addr:i});if(!o||!o?.success||(o?.ibGibs??[]).length===0)throw new Error("could not get newer ibgib in timeline (E: 15fa346c8ac17edb96e4b0870104c122)");await this.loadIbGibDto(o.ibGibs[0]);let s=await this.validateThis();if(s?.length>0)throw new Error(`validationErrors when loading newer version: ${L(s)} (E: 0d9f0684a1ff6af44e20a57130e3ac22)`)}}else console.warn(`${e} this.metaspace undefined (W: 44cc5bf1b14b4695b8de4c589787be06)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{B&&console.log(`${e} complete.`)}}async rel8To({ibGibs:e,rel8nName:t,linked:i,metaspace:o}){let s=`${this.lc}[${this.rel8To.name}]`;try{if(B&&console.log(`${s} 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(o=o??this.metaspace,!o)throw new Error("either metaspace or this.metaspace required (E: b5f9453ddb394a2b76dec74c7304df22)");let d=(this.rel8ns?this.rel8ns[t]??[]:[]).map(b=>z({ibGibAddr:b}).tjpGib),u=e.filter(b=>{let E=z({ibGibAddr:C({ibGib:b})}).tjpGib;return!d.includes(E)});if(u.length===0){B&&console.log(`${s} already rel8d to all incoming ibGib(s) via tjp. (I: 5e9d94a98ba262f146c0c0b765157922)`);return}let f=u.map(b=>C({ibGib:b})),h=await Je({src:this.toIbGibDto(),rel8nsToAddByAddr:{[t]:f},linkedRel8ns:i?["past","ancestor",t]:["past","ancestor"],dna:!0,nCounter:!0}),m=h.newIbGib,g=await rt({ibGib:m});if(g?.length??!1)throw new Error(`new this ibgib would have validation errors. aborting. newThisValidationErrors: ${g.join("|")} (E: eb816a27156c246c121ef55e37d59322)`);await o.persistTransformResult({resTransform:h}),await this.loadIbGibDto(m),await o.registerNewIbGib({ibGib:m})}catch(a){throw console.error(`${s} ${y(a)}`),a}finally{B&&console.log(`${s} complete.`)}}async rel8ToContextIbGib({ibGibToRel8:e,ibGibAddrToRel8:t,contextIbGib:i,rel8nNames:o}){let s=`${this.lc}[${this.rel8ToContextIbGib.name}]`;try{if(!e&&!t)throw new Error("ibGibToRel8 or ibGibAddrToRel8 required (E: 3ee14659fd22355a5ba0e537a477be22)");if(!i)throw new Error("contextIbGib required (E: 85f27c7cbf713704c21084c141cd8822)");if(!this.metaspace)throw new Error("this.metaspace required (E: 6a38c4274bdefc8d44cafd2d6faaa222)");if((o??[]).length===0){if(!this.data?.defaultRel8nName)throw new Error("either rel8nNames or this.data.defaultRel8nName required (E: a14ab4b3e479d9274c61bc5a30bc2222)");o=[this.data.defaultRel8nName]}let a={};t=t||C({ibGib:e}),o.forEach(u=>{a[u]=[t]});let c=await Je({src:i,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(`${s} ${y(a)}`),a}}async createCommentAndRel8ToContextIbGib({text:e,contextIbGib:t,rel8nName:i}){let o=`${this.lc}[${this.createCommentAndRel8ToContextIbGib.name}]`;try{if(B&&console.log(`${o} starting... (I: c3a005f7d323468a5b4e1b2710901d22)`),!this.metaspace)throw new Error("this.metaspace required (E: 5dbb1a7f0ff5469b8ce3cb1be175e521)");let s=await this.metaspace.getLocalUserSpace({lock:!0}),a=await Qe({text:e,addlMetadataText:this.getAddlMetadata(),saveInSpace:!0,space:s});s=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:i})}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{B&&console.log(`${o} complete.`)}}getThisAtom(){return It({text:this.data?.classname??"this",length:16})}getAddlMetadata(){let e=`${this.lc}[${this.getAddlMetadata.name}]`;try{if(B&&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 i=this.data.classname?.replace(/[_]/mg,"")||void 0,o=this.data.name?.slice(0,8).replace(/[__]/mg,"")||void 0,s=this.data.uuid?.slice(0,8)||void 0,a=`${t}_${i}_${o}_${s}`;return B&&console.log(`${e} addlMetadataText: ${a} (I: 53c0044671dc99fb75635367d2e63c22)`),a}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{B&&console.log(`${e} complete.`)}}async getContextIbGibFromArgOrAddr({arg:e,addr:t,latest:i}){let o=`${this.lc}[${this.getContextIbGibFromArgOrAddr.name}]`;try{B&&console.log(`${o} starting... (I: c13f7cb92133984048f606075efb8a22)`);let s;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)");s=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)`);s=a.ibGibs[0]}if(i){let a=await this.metaspace.getLatestAddr({ibGib:s});if(a!==C({ibGib:s})){let c=await this.metaspace.get({addr:a});if(c.success&&c.ibGibs?.length===1)s=c.ibGibs[0];else throw new Error(`unable to get resLatestAddr (${a}) (E: ce1e1297743e9a16c8f082321e52a122)`)}}return s}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{B&&console.log(`${o} complete.`)}}async initializeContext({arg:e,contextIbGib:t,rel8nName:i}){let o=`${this.lc}[${this.initializeContext.name}]`;try{if(B&&console.log(`${o} starting... (I: d93429c85b0a494388f66fba3eece922)`),!this.metaspace)throw new Error("this.metaspace (metaspace) required. set this before using this witness. (E: 67db388a0223bf813b40accd9941ad23)");e&&t&&console.warn(`${o} both arg and contextIbGib provided. using raw contextIbGib (W: d6d723ad7fb942079833c40647aecd22)`);let s=t??await this.getContextIbGibFromArgOrAddr({arg:e,latest:!1});if(this._currentWorkingContextIbGib){let d=Q({ibGib:this._currentWorkingContextIbGib}),u=Q({ibGib:s});if(d===u){B&&console.warn(`${o} initializing context but it's the same timeline (${d}). (W: 7609f8f51172443183e0c93ad52bfe56)`);return}else await this.finalizeContext({arg:e})}let a=p(()=>{this._currentWorkingContextIbGib_PriorChildrenAddrs=[...this._currentWorkingContextIbGib?.rel8ns?.comment??[],...this._currentWorkingContextIbGib?.rel8ns?.pic??[],...this._currentWorkingContextIbGib?.rel8ns?.link??[]]},"updatePriorChildren");this._currentWorkingContextIbGib=t?await this.getContextIbGibFromArgOrAddr({addr:C({ibGib:t}),latest:!0}):await this.getContextIbGibFromArgOrAddr({arg:e,latest:!0}),a();let c=Q({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(Ge({next:p(async d=>{let u=`${o}[latestObs.next]`;if(d.tjpAddr!==c)return;let f=C({ibGib:this._currentWorkingContextIbGib});if(d.latestAddr!==f){if(B&&console.warn(`${u} checking if new context is actually new...damn getLatestAddr maybe not working in ionic space... argh (W: 3d1a12154dfafb9c96d07e6f75f7a322)`),d.latestIbGib){let h=d.latestIbGib.data?.n??-1,m=this._currentWorkingContextIbGib?.data?.n??-2;if(h<=m){console.warn(`${u} latestN is not really the latest. latestN_Supposedly: ${h}, currentN: ${m}. (tjpGib: ${d.tjpAddr}) (W: 6792c9a596c44c03b262614ae79a715e)`);return}}B&&console.log(`${u} update to context.
|
|
659
|
+
`;var Gt=!1,sn=class n{static{p(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(Gt||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 z({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return Gt&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=se(e.ib),this.gib=se(e.gib),e.data?this.data=se(e.data):delete this.data,e.rel8ns?this.rel8ns=se(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(i){throw console.error(`${t} ${i.message}`),i}finally{Gt&&console.log(`${t} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{await this.initialized,this.gib||(this.gib=await us(this.toIbGibDto()));let i=await this.validateThis();if(i?.length>0){for(let a of i)console.error(`${t} ${a}`);throw new Error("internal witness validation failed. See `WitnessBase_V1.validateThis` (E: 2b5f73cadbfa416ba189346f3c31cd0c)")}let o=await this.validateWitnessArg(e);if(o?.length>0){for(let a of o)console.error(`${t} ${a}`);throw new Error("arg validation failed. See `WitnessBase_V1.validateWitnessArg` (E: 51531a1d928a485e8ffc277145ec44e9)")}(Gt||this.trace)&&console.log(`${t} addr: ${A(e)}`),Gt&&console.log(`${t} addr: ${A(e)} (I: f4cf13a44c4e4fc3903f14018e616c64)`);let s=await this.witnessImpl(e);return this.data?.persistOptsAndResultIbGibs&&await this.persistOptsAndResultIbGibs({arg:e,result:s}),s}catch(i){if(console.error(`${t} ${i.message||"unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)"}`),this.catchAllErrors)return;throw i}}async validateWitnessArg(e){let t=`${this.lc}[${this.validateWitnessArg.name}]`;try{let i=[];e||i.push("arg required (E: a222db3b668e4bb09cfd82e75c07bfa6)");let o=hs({ib:e?.ib});(o?.length??!1)&&i.push(`invalid arg.ib (E: 2ae362ef274d4c3bb9716800f2106d28) errors: ${o.join(`
|
|
660
|
+
`)}`);let s=ms({gib:e?.gib});(s?.length??!1)&&i.push(`invalid arg.gib (E: 73be275058084d768a39299337f2ce34) errors: ${s.join(`
|
|
661
|
+
`)}`);let a=await dt({ibGib:e});return a?.length??!1?i.push(`arg ibgib invalid intrinsically (E: 73be275058084d768a39299337f2ce34) errors: ${a.join(`
|
|
662
|
+
`)}`):this.data?.allowPrimitiveArgs||W({gib:e.gib}).isPrimitive&&i.push('arg is primitive (i.e. gib === "gib") and witness.data.allowPrimitiveArgs is falsy. (E: d0aa3d7ad4f54b01bd0023300d15ecd9)'),i}catch(i){throw console.error(`${t} ${i.message}`),i}}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(i){throw console.error(`${e} ${i.message}`),i}return t}persistOptsAndResultIbGibs({arg:e,result:t}){let i=`${this.lc}[${this.persistOptsAndResultIbGibs.name}]`;return console.warn(`${i} not implemented in this base class. Override this in descendent class. (W: 087514e851704322a4ec8069a73ce944)`),Promise.resolve()}};var js="___whitespace___";var _e=!1;function er({commentText:n,addlMetadataText:e}){let t=`[${er.name}]`;try{if(!n)throw new Error("commentText required. (E: 22fdfd0aa0524a18b63a9405b312c99e)");let i=St({text:n,length:20,replaceMap:{"?":"__qm__"}});if(e){e.length>128&&console.warn(`${t} addlMetadataText (${e.length}) is too long. Max length: ${128}`);let o=St({text:e,length:128});if(!o)throw new Error("(UNEXPECTED) addlMetadataText contains no safe characters? (E: dd03c578ada2836b05c94a4aa1785222)");return`comment ${i} ${o}`}else return`comment ${i}`}catch(i){throw console.error(`${t} ${i.message}`),i}}p(er,"getCommentIb");function je({ib:n}){let e=`${je.name}]`;try{if(_e&&console.log(`${e} starting... (I: 1a16f5e3134599eeb585eae77ee6af22)`),!n)throw new Error("ib required (E: d89f8c4df46b970585c82bc89c1c6322)");let[t,i,o]=n.split(" ");for(;i.includes("__qm__");)i=i.replace("__qm__","?");return{safeIbCommentText:i,safeIbCommentMetadataText:o}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{_e&&console.log(`${e} complete.`)}}p(je,"parseCommentIb");async function et({text:n,addlMetadataText:e,saveInSpace:t,space:i,dontTrimText:o}){let s=`[${et.name}]`;_e&&console.log(`${s} starting...`);try{if(!n)throw new Error("text required (E: 3e3d0f555e1a83771a6548eb10943522)");if(o||(n=n.trim()),!n)throw new Error("text cannot be only whitespace when dontTrimText is falsy. (E: d6db3537b9834294836aeb70987c908e)");let a={text:n,textTimestamp:zt()},c={parentIbGib:re.primitive({ib:"comment"}),ib:er({commentText:n.trim()||js,addlMetadataText:e}),data:a,dna:!0,tjp:{uuid:!0,timestamp:!0},nCounter:!0};_e&&console.log(`${s} opts: ${U(c)}`);let d=await re.firstGen(c);if(t){if(!i)throw new Error("space required if saveInSpace is truthy (E: 40f69f22f21b4279a83cb746cb4b0da1)");await ys({resTransform:d,space:i})}return d}catch(a){throw console.error(`${s} ${a.message}`),a}}p(et,"createCommentIbGib");function tt({ibGib:n}){let e=`[${tt.name}]`;try{if(_e&&console.log(`${e} starting...`),!n)throw new Error("ibGib required (E: f204dac30ae548b0a049f1c4d8048502)");let{ib:t,data:i,rel8ns:o}=n;if(!o)return _e&&console.log(`${e} rel8ns falsy, NOT a comment (I: 6e145eb2d0ba46629746215a3b655fd5)`),!1;let s=o.ancestor||[];return s&&s.includes("comment^gib")?(_e&&console.log(`${e} descends from comment^gib, YES is a comment (I: 1a8557780e2e4c1580d5a2585567762b)`),!0):i?i.text&&t?.includes("comment")?(_e&&console.log(`${e} has text, and ib has 'comment', YES is a comment (I: 3aa03bcd639d4ec7abd7ead917eda3d8)`),!0):(_e&&console.log(`${e} reached end, doesn't have comment qualities. NOT a comment. (I: cfa529f27f9d490abd476c924ef77087)`),!1):(_e&&console.log(`${e} data falsy, NOT a comment (I: 30b20ff6785f432f98489f11efe24299)`),!1)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{_e&&console.log(`${e} complete.`)}}p(tt,"isComment");var q=!1,rn=class n extends sn{static{p(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{q&&console.log(`${e} starting... (I: f0e65ab0f80046a59668ddfbf9f47a4a5)`),await super.initialize()}catch(t){console.error(`${e} ${y(t)}`)}finally{q&&console.log(`${e} complete.`)}}async loadNewerSelfIfAvailable(){let e=`${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;try{if(q&&console.log(`${e} starting... (I: 94755c3131f4dfa12d20fa38e2926522)`),this.metaspace){let t=A({ibGib:this}),i=await this.metaspace.getLatestAddr({ibGib:this});if(i&&i!==t){let o=await this.metaspace.get({addr:i});if(!o||!o?.success||(o?.ibGibs??[]).length===0)throw new Error("could not get newer ibgib in timeline (E: 15fa346c8ac17edb96e4b0870104c122)");await this.loadIbGibDto(o.ibGibs[0]);let s=await this.validateThis();if(s?.length>0)throw new Error(`validationErrors when loading newer version: ${U(s)} (E: 0d9f0684a1ff6af44e20a57130e3ac22)`)}}else console.warn(`${e} this.metaspace undefined (W: 44cc5bf1b14b4695b8de4c589787be06)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{q&&console.log(`${e} complete.`)}}async rel8To({ibGibs:e,rel8nName:t,linked:i,metaspace:o}){let s=`${this.lc}[${this.rel8To.name}]`;try{if(q&&console.log(`${s} 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(o=o??this.metaspace,!o)throw new Error("either metaspace or this.metaspace required (E: b5f9453ddb394a2b76dec74c7304df22)");let d=(this.rel8ns?this.rel8ns[t]??[]:[]).map(b=>W({ibGibAddr:b}).tjpGib),u=e.filter(b=>{let E=W({ibGibAddr:A({ibGib:b})}).tjpGib;return!d.includes(E)});if(u.length===0){q&&console.log(`${s} already rel8d to all incoming ibGib(s) via tjp. (I: 5e9d94a98ba262f146c0c0b765157922)`);return}let f=u.map(b=>A({ibGib:b})),h=await Xe({src:this.toIbGibDto(),rel8nsToAddByAddr:{[t]:f},linkedRel8ns:i?["past","ancestor",t]:["past","ancestor"],dna:!0,nCounter:!0}),m=h.newIbGib,g=await dt({ibGib:m});if(g?.length??!1)throw new Error(`new this ibgib would have validation errors. aborting. newThisValidationErrors: ${g.join("|")} (E: eb816a27156c246c121ef55e37d59322)`);await o.persistTransformResult({resTransform:h}),await this.loadIbGibDto(m),await o.registerNewIbGib({ibGib:m})}catch(a){throw console.error(`${s} ${y(a)}`),a}finally{q&&console.log(`${s} complete.`)}}async rel8ToContextIbGib({ibGibToRel8:e,ibGibAddrToRel8:t,contextIbGib:i,rel8nNames:o}){let s=`${this.lc}[${this.rel8ToContextIbGib.name}]`;try{if(!e&&!t)throw new Error("ibGibToRel8 or ibGibAddrToRel8 required (E: 3ee14659fd22355a5ba0e537a477be22)");if(!i)throw new Error("contextIbGib required (E: 85f27c7cbf713704c21084c141cd8822)");if(!this.metaspace)throw new Error("this.metaspace required (E: 6a38c4274bdefc8d44cafd2d6faaa222)");if((o??[]).length===0){if(!this.data?.defaultRel8nName)throw new Error("either rel8nNames or this.data.defaultRel8nName required (E: a14ab4b3e479d9274c61bc5a30bc2222)");o=[this.data.defaultRel8nName]}let a={};t=t||A({ibGib:e}),o.forEach(u=>{a[u]=[t]});let c=await Xe({src:i,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(`${s} ${y(a)}`),a}}async createCommentAndRel8ToContextIbGib({text:e,contextIbGib:t,rel8nName:i}){let o=`${this.lc}[${this.createCommentAndRel8ToContextIbGib.name}]`;try{if(q&&console.log(`${o} starting... (I: c3a005f7d323468a5b4e1b2710901d22)`),!this.metaspace)throw new Error("this.metaspace required (E: 5dbb1a7f0ff5469b8ce3cb1be175e521)");let s=await this.metaspace.getLocalUserSpace({lock:!0}),a=await et({text:e,addlMetadataText:this.getAddlMetadata(),saveInSpace:!0,space:s});s=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:i})}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{q&&console.log(`${o} complete.`)}}getThisAtom(){return St({text:this.data?.classname??"this",length:16})}getAddlMetadata(){let e=`${this.lc}[${this.getAddlMetadata.name}]`;try{if(q&&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 i=this.data.classname?.replace(/[_]/mg,"")||void 0,o=this.data.name?.slice(0,8).replace(/[__]/mg,"")||void 0,s=this.data.uuid?.slice(0,8)||void 0,a=`${t}_${i}_${o}_${s}`;return q&&console.log(`${e} addlMetadataText: ${a} (I: 53c0044671dc99fb75635367d2e63c22)`),a}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{q&&console.log(`${e} complete.`)}}async getContextIbGibFromArgOrAddr({arg:e,addr:t,latest:i}){let o=`${this.lc}[${this.getContextIbGibFromArgOrAddr.name}]`;try{q&&console.log(`${o} starting... (I: c13f7cb92133984048f606075efb8a22)`);let s;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)");s=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)`);s=a.ibGibs[0]}if(i){let a=await this.metaspace.getLatestAddr({ibGib:s});if(a!==A({ibGib:s})){let c=await this.metaspace.get({addr:a});if(c.success&&c.ibGibs?.length===1)s=c.ibGibs[0];else throw new Error(`unable to get resLatestAddr (${a}) (E: ce1e1297743e9a16c8f082321e52a122)`)}}return s}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{q&&console.log(`${o} complete.`)}}async initializeContext({arg:e,contextIbGib:t,rel8nName:i}){let o=`${this.lc}[${this.initializeContext.name}]`;try{if(q&&console.log(`${o} starting... (I: d93429c85b0a494388f66fba3eece922)`),!this.metaspace)throw new Error("this.metaspace (metaspace) required. set this before using this witness. (E: 67db388a0223bf813b40accd9941ad23)");e&&t&&console.warn(`${o} both arg and contextIbGib provided. using raw contextIbGib (W: d6d723ad7fb942079833c40647aecd22)`);let s=t??await this.getContextIbGibFromArgOrAddr({arg:e,latest:!1});if(this._currentWorkingContextIbGib){let d=X({ibGib:this._currentWorkingContextIbGib}),u=X({ibGib:s});if(d===u){q&&console.warn(`${o} initializing context but it's the same timeline (${d}). (W: 7609f8f51172443183e0c93ad52bfe56)`);return}else await this.finalizeContext({arg:e})}let a=p(()=>{this._currentWorkingContextIbGib_PriorChildrenAddrs=[...this._currentWorkingContextIbGib?.rel8ns?.comment??[],...this._currentWorkingContextIbGib?.rel8ns?.pic??[],...this._currentWorkingContextIbGib?.rel8ns?.link??[]]},"updatePriorChildren");this._currentWorkingContextIbGib=t?await this.getContextIbGibFromArgOrAddr({addr:A({ibGib:t}),latest:!0}):await this.getContextIbGibFromArgOrAddr({arg:e,latest:!0}),a();let c=X({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(Me({next:p(async d=>{let u=`${o}[latestObs.next]`;if(d.tjpAddr!==c)return;let f=A({ibGib:this._currentWorkingContextIbGib});if(d.latestAddr!==f){if(q&&console.warn(`${u} checking if new context is actually new...damn getLatestAddr maybe not working in ionic space... argh (W: 3d1a12154dfafb9c96d07e6f75f7a322)`),d.latestIbGib){let h=d.latestIbGib.data?.n??-1,m=this._currentWorkingContextIbGib?.data?.n??-2;if(h<=m){console.warn(`${u} latestN is not really the latest. latestN_Supposedly: ${h}, currentN: ${m}. (tjpGib: ${d.tjpAddr}) (W: 6792c9a596c44c03b262614ae79a715e)`);return}}q&&console.log(`${u} update to context.
|
|
663
663
|
currentAddr: ${f}
|
|
664
|
-
latestAddr: ${d.latestAddr} (I: d0adcc392e6e974c9917730ebad51322)`),this._currentWorkingContextIbGib=d.latestIbGib??await this.getContextIbGibFromArgOrAddr({addr:d.latestAddr,latest:!1}),this._updatingContext?B&&console.log(`${u} already updating context (I: f856f9414627ab00418dccd285b55822)`):(await this.handleContextUpdate({update:d}),a())}},"next"),error:p(async d=>{let u=`${o}[latestObs.error]`;console.error(`${u} this.metaspace.latestObs error: ${$s({err:d})}. (E: 99df4c42195d46d0a9dbfb06ac45ae00)`)},"error")})),i&&await this.rel8To({ibGibs:[this._currentWorkingContextIbGib],rel8nName:i})}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{B&&console.log(`${o} complete.`)}}async finalizeContext({arg:e}){let t=`${this.lc}[${this.finalizeContext.name}]`;try{B&&console.log(`${t} starting... (I: dd53dfc745864dd19fde5f209ceb82c8)`);let i=0,o=100;for(;this._updatingContext&&i<o;)await H(100),i++,i%10===0&&console.log(`${t} already updating context and taking a litle while... waiting still. tries: ${i}/${o} (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(i){throw console.error(`${t} ${y(i)}`),i}finally{this._updatingContext=!1,B&&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 H(1e3);this._updatingContext=!0;try{if(B&&console.log(`${t} starting... (I: 3eeaa40cad49094f125f9f5cd6ff6e22)`),B&&(console.log(`${t} update: (I: ad0abae7de472e3b4d3891ea0b937322)`),console.table(e)),!e.latestIbGib){debugger;throw new Error("(UNEXPECTED) update.latestIbGib falsy? (E: e18a048d7e95757238396ddd84748f22)")}let i=e.latestIbGib,o=await this.getNewChildrenIbGibs({newContext:i});if(o.length===1){let s=o[0];await this.handleNewContextChild({newChild:s})}else if(o.length>1){console.warn(`${t} (UNEXPECTED) multiple new children in context update. iterating through each one. (W: 02d82a8f755f418d95fa30f0f52ad58e)`);for(let s of o)await this.handleNewContextChild({newChild:s})}else{B&&console.log(`${t} no new children in context update. returning early... (I: 31397b04965351ab29bb3f78cb709122)`);return}}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{this._updatingContext=!1,B&&console.log(`${t} complete.`)}}async getNewChildrenIbGibs({newContext:e}){let t=`${this.lc}[${this.getNewChildrenIbGibs.name}]`;try{B&&console.log(`${t} starting... (I: 1b3d1cf908489087fa3b281f55b9a522)`);let o=[...e.rel8ns?.comment??[],...e.rel8ns?.pic??[],...e.rel8ns?.link??[]].filter(u=>!this._currentWorkingContextIbGib_PriorChildrenAddrs.includes(u));if(o.length===0)return B&&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 s=await this.metaspace.getLocalUserSpace({});if(!s)throw new Error("couldn't get local user space? (E: f118f75e5852fc22bba3a6495beec723)");let a=await ps({addrs:o,space:s}),c=Object.values(a?.data?.latestAddrsMap??{});if(!a?.data?.success||c.length!==o.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!==o.length)throw new Error(`failed to get newChildren with addrs: ${o.join("|")}. Error: ${d.errorMsg??"unknown error 5737bd0996d5445b8bd80975bedc0d57"} (E: 05722e11350ec6ffffdb5c7d0caa2922)`);return d.ibGibs}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{B&&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(i){throw console.error(`${t} ${y(i)}`),i}}};var ae=J,Ue=class extends en{static{p(this,"LiveProxyIbGib")}lc="";ib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.ib:Vt;gib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.gib:Ht;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{ae&&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{ae&&console.log(`${e} complete.`)}}async loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{ae&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{ae&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;return ae&&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{ae&&console.log(`${e} starting... (I: 1bd72217a5f334effc63f8d51e7b2225)`),await super.initialize(),this._contextUpdated$=await fi(),this.contextUpdated$=this._contextUpdated$.asObservable(),this._newContextChild$=await fi(),this.newContextChild$=this._newContextChild$.asObservable()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{ae&&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(ae&&console.log(`${t} starting...`),us({ib:e.ib})){if(!e.data)throw new Error("arg has space ib but arg.data is falsy (E: b2af9226c067d5e72f117fa36e239525)");let i=e.data.uuid;return this.spaceId=i,ae&&console.log(`${t} spaceId set to the ${i} (I: 018724a5431ba421b71fad36924c5a25)`),oe.primitive({ib:`spaceId set to ${i}`})}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 i=await this.metaspace?.getLocalUserSpace({localSpaceId:this.spaceId});return await this.setWrappedIbGib({ibGib:e,space:i}),Tt}}catch(i){throw console.error(`${t} ${i.message}`),i}finally{ae&&console.log(`${t} complete.`)}}_contextUpdated$;contextUpdated$;_newContextChild$;newContextChild$;async handleContextUpdate({update:e}){let t=`${this.lc}[${this.handleContextUpdate.name}]`;try{if(ae&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{ae&&console.log(`${t} complete.`)}}async setWrappedIbGib({ibGib:e,ibGibAddr:t,space:i}){let o=`${this.lc}[${this.setWrappedIbGib.name}]`;try{if(ae&&console.log(`${o} starting... (I: a4b0acda259c121801aa701534320125)`),this.metaspace||(this.metaspace=await D()),!e){if(!t)throw new Error("(UNEXPECTED) both ibGib AND ibGibAddr falsy? (E: 6fac98ba2d4cfdec2b7ee974dec74625)");if(i??=await this.metaspace.getLocalUserSpace({lock:!1}),!i)throw new Error("(UNEXPECTED) space falsy? no space provided and couldn't get default local user space? (E: e14d1b7a6586f99453fc571396d4df25)");let s=await this.metaspace.get({addrs:[t],space:i});if(!s.success||s.ibGibs?.length!==1)throw new Error(`${o} failed to get ibGib(?) (${t}). space.ib: ${i.ib} (E: b38f0a25d92e44c0aa5cc3b038a43c6c)`);e=s.ibGibs.at(0)}await this.initializeContext({contextIbGib:e,rel8nName:""})}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{ae&&console.log(`${o} complete.`)}}async handleNewContextChild({newChild:e}){let t=`[${this.handleNewContextChild.name}]`;try{if(ae&&console.log(`${t} starting... (I: 7e9b6b7a4bb2726e9c717f230dfe1925)`),!this._newContextChild$)throw new Error("(UNEXPECTED) this._contextUpdated$ falsy? (E: a184df090502bed9649f8df88bd4c125)");await this._newContextChild$.next(e)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{ae&&console.log(`${t} complete.`)}}};var lt="witness_agent",ct=/^[a-zA-Z0-9_\-.]{1,32}$/,yi=/.{1,255}/,Js="",Ws="Manco",Xs="This is a generic, unspecified agent.";var tn="List of function info ibgib addresses. These contain info on both the requests you made and the resultant values.",je="agent",Ib={type:"string",description:"unique identifier for the agent. Should be provided to the agent in system instructions upon creation."},Tb={type:"string",description:"type of the agent that governs basic responsibilities. Should be provided to the agent in system instructions upon creation."};var Jl="hardcoded",Wl="human",Xl="ai",Yl="function",Ql="unknown",X={HARDCODED:Jl,HUMAN:Wl,AI:Xl,FUNCTION:Yl,UNKNOWN:Ql},Ei=Object.freeze(Object.values(X));function Ys(n){return!!n&&Ei.includes(n)}p(Ys,"isTextSource");var Cb={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: ${ct.source}`},Qs="primaryagent";var Zs=!1;async function wi({ibGib:n,addr:e,tagIbGib:t,metaspace:i,space:o}){let s=`[${wi.name}]`;try{if(Zs&&console.log(`${s} starting... (I: b1fd25ec28bce8f1916b4ab55f48a724)`),!e&&!n)throw new Error("either addr or ibGib required (E: 3d580f8ecc251a0c81c7ea8bc3d38524)");if(e??=C({ibGib:n}),e!==C({ibGib:n}))throw new Error(`addr (${e}) differs from incoming ibGib's addr (${C({ibGib:n})}). (E: f2c14234a78c917fb9f587beaee89324)`);let a=await i.getLatestAddr({ibGib:t,space:o});if(a!==C({ibGib:t})){let f=await i.get({addr:a,space:o});if(!f.success||f.ibGibs?.length!==1)throw new Error(`could not get latest tag (${a}) from space (${o.ib}). error: ${f.errorMsg??"[unknown error (E: a4e31c98398b417db8f617f98a5f2741)]"} (E: 73c085d81efdab0e7b8939222ec07524)`);t=f.ibGibs.at(0)}let c={[cs]:[e]},d=await Je({src:t,rel8nsToAddByAddr:c,dna:!0,nCounter:!0}),u=d.newIbGib;return await i.persistTransformResult({resTransform:d,space:o}),await i.registerNewIbGib({ibGib:u,space:o}),u}catch(a){throw console.error(`${s} ${y(a)}`),a}finally{Zs&&console.log(`${s} complete.`)}}p(wi,"rel8ToTag");var te=J,Ii=class n{static{p(this,"AgentsService_V1")}lc=`[${n.name}]`;latestAgents=new Map;factoryFns={};constructor(){}async getAgentById(e){let t=`${this.lc}[${this.getAgentById.name}]`;try{let{agentId:i,agentType:o,spaceId:s}=e;te&&console.log(`${t} starting... (I: 0c4214b4614a43bd2825978e54aee325)`);let a=this.latestAgents.get(i);if(!a){let c=await D();a=(await nn({metaspace:c,type:o,spaceId:s})).find(u=>u.data.uuid===i)}return a||console.warn(`${t} couldn't find any agent by id. opts: ${L(e)} (W: 70cf51ecbe68dfdcfe1e9995a7468f25)`),a}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{te&&console.log(`${t} complete.`)}}async updateOrSetLatestAgent({agent:e,throwIfNewerFound:t}){let i=`${this.lc}[${this.updateOrSetLatestAgent.name}]`;try{if(te&&console.log(`${i} 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 o=await this.getLatestAgent({id:e.data.uuid});if(o){if(!o.data)throw new Error("(UNEXPECTED) existing.data falsy? should have thrown on previous set function call? (E: f3cbae9922ea9849ada25db2eea40825)");if(o.data.n===e.data.n){if(o.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.
|
|
665
|
-
existing: ${
|
|
666
|
-
new: ${L(K({ibGib:e}))} (E: 5e079b566ff3533acdb2d01359f08625)`),await o.loadIbGibDto(e.toIbGibDto()),this.latestAgents.set(e.data.uuid,e);return}else if(o.data.n>e.data.n){let s="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(`${i} ${s} (E: bb2cc3ce8cfa88b80fb62149b0e70225)`);console.warn(`${i} ${s} (W: caaf66deb4e6fd8e2eb9261685dc0325)`);return}else{await o.loadIbGibDto(e.toIbGibDto()),this.latestAgents.set(e.data.uuid,e);return}}else{this.latestAgents.set(e.data.uuid,e);return}}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{te&&console.log(`${i} complete.`)}}getLatestAgent({id:e}){let t=`${this.lc}[${this.getLatestAgent.name}]`;try{return te&&console.log(`${t} starting... (I: 8e85b55057760b712a913a92e88ead25)`),Promise.resolve(this.latestAgents.get(e))}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{te&&console.log(`${t} complete.`)}}registerFactory({classname:e,fnDtoToAgentWitness:t}){this.factoryFns[e]=t}async getAgentWitnessFromDto({dto:e,classname:t}){let i=`${this.lc}[${this.getAgentWitnessFromDto.name}]`;try{if(te&&console.log(`${i} starting... (I: 718837d4ee3d590177f3425b99106225)`),!e.data)throw new Error("dto.data falsy (E: fad89dd4c787b687a657c13968946925)");let o;if(t??=e.data.classname,t){let s=this.factoryFns[t],a=await s(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)");o=a.agent}else throw new Error(`classname (${t}) factory function found and attempted, but result says applied: false. (E: 751a2502c9a7e2d61c76c8ae2f7fb125)`)}else{let s=Object.keys(this.factoryFns);for(let a of s){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)");o=d.agent;break}}}return o}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{te&&console.log(`${i} complete.`)}}async getAgentByAddr({agentAddr:e,spaceId:t,metaspace:i}){let o=`${this.lc}[${this.getAgentByAddr.name}]`;try{if(te&&console.log(`${o} starting... (I: 42dfecbe6d6b5a3a7d392af5a66cc625)`),!e)throw new Error(`${o} agentAddr is required. (E: 389351659a2e08fa179ceede16925a25)`);let{ib:s}=q({ibGibAddr:e}),{uuid:a,type:c}=js({ib:s});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 te&&console.log(`${o} agent found already in agents svc so didn't need to go get it from the space. (I: ec6abaf3badd8e301d79a7476845bc25)`),d;i??=await D();let u=await i.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 f=await i.get({addrs:[e],space:u});if(!f.success||!f.ibGibs||f.ibGibs.length===0){te&&console.log(`${o} Agent ibGib not found in space (${t}) at address ${e}. (I: 29c5c7994fb3ed388b28a81a9ed68325)`);return}let h=f.ibGibs[0],m=await this.getAgentWitnessFromDto({dto:h});if(!m){debugger;throw new Error(`${o} Couldn't get actual agent witness from agent dto (${e}). Have we registered classname (${h.data?.classname}) and factory fn with agents service? (E: e6e9da6c91d14bd7acb5c571c8de1a25)`)}return await this.updateOrSetLatestAgent({agent:m,throwIfNewerFound:!0}),te&&console.log(`${o} Cached agent witness with id ${a}. (I: b862f63147a3fac3c6e6210d5ab87c25)`),te&&console.log(`${o} complete. Retrieved and cached agent witness for address ${e}.`),m}catch(s){throw console.error(`${o} ${y(s)}`),s}}async createNewAgent(e){let t=`[${this.createNewAgent.name}]`;try{te&&console.log(`${t} starting... (I: a3e07b54bb7bf45f7739eff2d738c825)`);let{metaspace:i,superSpace:o,name:s,availableFunctions:a,initialSystemText:c,initialChatText:d,fnGetAPIKey:u,addToAgentsTag:f,type:h}=e;if(o??=await i.getLocalUserSpace({}),!o)throw new Error("(UNEXPECTED) superSpace falsy? (E: ceb60d96ff25b6d6aaa5aa69a7a51d25)");if(!o.data)throw new Error("(UNEXPECTED) superSpace.data falsy? (E: 56b4ec127f8559da96e6f70c7cb13825)");let m=Ci(e),g=await m.createInitialData(o);if(!g.uuid)throw new Error("(UNEXPECTED) data.uuid falsy? (E: 4e4f6fcf89d1e3775971ad843a083725)");let b=await i.createLocalSpaceAndUpdateBootstrap({allowCancel:!1,zeroSpace:i.zeroSpace,spaceName:s+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 m.createInitialRel8ns(),w=await oe.firstGen({ib:_i({data:g}),parentIbGib:oe.primitive({ib:lt}),data:g,rel8ns:E,nCounter:!0,dna:!0,tjp:{timestamp:!0}});await i.persistTransformResult({resTransform:w});let v=w.newIbGib,I=await m.createWitness();if(I.fnGetAPIKey=u,await I.loadIbGibDto(v),f){let S=await Ti({metaspace:i,space:o}),N=await wi({ibGib:v,metaspace:i,space:o,tagIbGib:S})}await de({type:h,rel8nInfos:[{rel8nName:je,ibGibs:[v]}],metaspace:i,space:o}),a.length>0&&await I.addAvailableFunctions(a);let T=[];return T.push({textSrc:"hardcoded",text:dt({tagText:ys,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 I.addTexts({infos:T}),this.latestAgents.set(I.data.uuid,I),I}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{te&&console.log(`${t} complete.`)}}getAgents(e){let t=`${this.lc}[${this.getAgents.name}]`;try{return te&&console.log(`${t} starting... (I: 4663f125c3a21fa3ecccc2c5a38d1225)`),nn(e)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{te&&console.log(`${t} complete.`)}}},vi;function Re(){return vi||(vi=new Ii),vi}p(Re,"getAgentsSvc");var Zl="gemini-3.1-pro-preview",jl="gemini-3-flash-preview",ec="gemini-3.1-flash-lite-preview",tc="gemini-3.1-flash-live-preview",nc="gemini-2.5-pro",ic="gemini-2.5-flash",oc="gemini-2.5-flash-lite",sc="gemini-2.5-flash-preview-tts",rc="gemini-2.0-flash",ac="gemini-2.0-flash-lite",Si={GEMINI_3_1_PRO_PREVIEW:Zl,GEMINI_3_FLASH_PREVIEW:jl,GEMINI_3_1_FLASH_LITE_PREVIEW:ec,GEMINI_3_1_FLASH_LIVE_PREVIEW:tc,GEMINI_2_5_PRO:nc,GEMINI_2_5_FLASH:ic,GEMINI_2_5_FLASH_LITE:oc,GEMINI_2_5_FLASH_PREVIEW_TTS:sc,GEMINI_2_0_FLASH:rc,GEMINI_2_0_FLASH_LITE:ac},Kb=Object.freeze(Object.values(Si));var er=Si.GEMINI_2_5_FLASH,ut=Si.GEMINI_2_5_FLASH_LITE,Ai=5;var tr={version:"1",uuid:Js,name:Ws,description:Xs,classname:"AgentWitness_V1",icon:"happy",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1,subSpaceId:"",superSpaceId:"",availableFunctionNameOrIds:[],model:er,api:"gemini",type:Qs,"@currentContextTjpAddr":W},xi=void 0;var lc,cc;function dc(){return{geminiUrl:lc,vertexUrl:cc}}p(dc,"getDefaultBaseUrls");function uc(n,e,t,i){var o,s;if(!n?.baseUrl){let a=dc();return e?(o=a.vertexUrl)!==null&&o!==void 0?o:t:(s=a.geminiUrl)!==null&&s!==void 0?s:i}return n.baseUrl}p(uc,"getBaseUrl");var Ne=class{static{p(this,"BaseModule")}};function _(n,e){let t=/\{([^}]+)\}/g;return n.replace(t,(i,o)=>{if(Object.prototype.hasOwnProperty.call(e,o)){let s=e[o];return s!=null?String(s):""}else throw new Error(`Key '${o}' not found in valueMap.`)})}p(_,"formatMap");function l(n,e,t){for(let s=0;s<e.length-1;s++){let a=e[s];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 f=d[u];l(f,e.slice(s+1),t[u])}else for(let u of d)l(u,e.slice(s+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(s+1),t);return}(!n[a]||typeof n[a]!="object")&&(n[a]={}),n=n[a]}let i=e[e.length-1],o=n[i];if(o!==void 0){if(!t||typeof t=="object"&&Object.keys(t).length===0||t===o)return;if(typeof o=="object"&&typeof t=="object"&&o!==null&&t!==null)Object.assign(o,t);else throw new Error(`Cannot set value for an existing key. Key: ${i}`)}else i==="_self"&&typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.assign(n,t):n[i]=t}p(l,"setValueByPath");function r(n,e,t=void 0){try{if(e.length===1&&e[0]==="_self")return n;for(let i=0;i<e.length;i++){if(typeof n!="object"||n===null)return t;let o=e[i];if(o.endsWith("[]")){let s=o.slice(0,-2);if(s in n){let a=n[s];return Array.isArray(a)?a.map(c=>r(c,e.slice(i+1),t)):t}else return t}else n=n[o]}return n}catch(i){if(i instanceof TypeError)return t;throw i}}p(r,"getValueByPath");function fc(n,e){for(let[t,i]of Object.entries(e)){let o=t.split("."),s=i.split("."),a=new Set,c=-1;for(let d=0;d<o.length;d++)if(o[d]==="*"){c=d;break}if(c!==-1&&s.length>c)for(let d=c;d<s.length;d++){let u=s[d];u!=="*"&&!u.endsWith("[]")&&!u.endsWith("[0]")&&a.add(u)}Ri(n,o,s,0,a)}}p(fc,"moveValueByPath");function Ri(n,e,t,i,o){if(i>=e.length||typeof n!="object"||n===null)return;let s=e[i];if(s.endsWith("[]")){let a=s.slice(0,-2),c=n;if(a in c&&Array.isArray(c[a]))for(let d of c[a])Ri(d,e,t,i+1,o)}else if(s==="*"){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let a=n,c=Object.keys(a).filter(u=>!u.startsWith("_")&&!o.has(u)),d={};for(let u of c)d[u]=a[u];for(let[u,f]of Object.entries(d)){let h=[];for(let m of t.slice(i))m==="*"?h.push(u):h.push(m);l(a,h,f)}for(let u of c)delete a[u]}}else{let a=n;s in a&&Ri(a[s],e,t,i+1,o)}}p(Ri,"_moveValueRecursive");function Po(n){if(typeof n!="string")throw new Error("fromImageBytes must be a string");return n}p(Po,"tBytes$1");function pc(n){let e={},t=r(n,["operationName"]);t!=null&&l(e,["operationName"],t);let i=r(n,["resourceName"]);return i!=null&&l(e,["_url","resourceName"],i),e}p(pc,"fetchPredictOperationParametersToVertex");function hc(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response","generateVideoResponse"]);return a!=null&&l(e,["response"],gc(a)),e}p(hc,"generateVideosOperationFromMldev$1");function mc(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response"]);return a!=null&&l(e,["response"],bc(a)),e}p(mc,"generateVideosOperationFromVertex$1");function gc(n){let e={},t=r(n,["generatedSamples"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>yc(a))),l(e,["generatedVideos"],s)}let i=r(n,["raiMediaFilteredCount"]);i!=null&&l(e,["raiMediaFilteredCount"],i);let o=r(n,["raiMediaFilteredReasons"]);return o!=null&&l(e,["raiMediaFilteredReasons"],o),e}p(gc,"generateVideosResponseFromMldev$1");function bc(n){let e={},t=r(n,["videos"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>Ec(a))),l(e,["generatedVideos"],s)}let i=r(n,["raiMediaFilteredCount"]);i!=null&&l(e,["raiMediaFilteredCount"],i);let o=r(n,["raiMediaFilteredReasons"]);return o!=null&&l(e,["raiMediaFilteredReasons"],o),e}p(bc,"generateVideosResponseFromVertex$1");function yc(n){let e={},t=r(n,["video"]);return t!=null&&l(e,["video"],_c(t)),e}p(yc,"generatedVideoFromMldev$1");function Ec(n){let e={},t=r(n,["_self"]);return t!=null&&l(e,["video"],Sc(t)),e}p(Ec,"generatedVideoFromVertex$1");function wc(n){let e={},t=r(n,["operationName"]);return t!=null&&l(e,["_url","operationName"],t),e}p(wc,"getOperationParametersToMldev");function vc(n){let e={},t=r(n,["operationName"]);return t!=null&&l(e,["_url","operationName"],t),e}p(vc,"getOperationParametersToVertex");function Ic(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response"]);return a!=null&&l(e,["response"],Tc(a)),e}p(Ic,"importFileOperationFromMldev$1");function Tc(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["parent"]);i!=null&&l(e,["parent"],i);let o=r(n,["documentName"]);return o!=null&&l(e,["documentName"],o),e}p(Tc,"importFileResponseFromMldev$1");function Ca(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response"]);return a!=null&&l(e,["response"],Cc(a)),e}p(Ca,"uploadToFileSearchStoreOperationFromMldev");function Cc(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["parent"]);i!=null&&l(e,["parent"],i);let o=r(n,["documentName"]);return o!=null&&l(e,["documentName"],o),e}p(Cc,"uploadToFileSearchStoreResponseFromMldev");function _c(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["encodedVideo"]);i!=null&&l(e,["videoBytes"],Po(i));let o=r(n,["encoding"]);return o!=null&&l(e,["mimeType"],o),e}p(_c,"videoFromMldev$1");function Sc(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["uri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["videoBytes"],Po(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(Sc,"videoFromVertex$1");var nr;(function(n){n.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",n.OUTCOME_OK="OUTCOME_OK",n.OUTCOME_FAILED="OUTCOME_FAILED",n.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(nr||(nr={}));var ir;(function(n){n.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",n.PYTHON="PYTHON"})(ir||(ir={}));var or;(function(n){n.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",n.SILENT="SILENT",n.WHEN_IDLE="WHEN_IDLE",n.INTERRUPT="INTERRUPT"})(or||(or={}));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 sr;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(sr||(sr={}));var rr;(function(n){n.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",n.SIMPLE_SEARCH="SIMPLE_SEARCH",n.ELASTIC_SEARCH="ELASTIC_SEARCH"})(rr||(rr={}));var ar;(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"})(ar||(ar={}));var lr;(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"})(lr||(lr={}));var cr;(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"})(cr||(cr={}));var dr;(function(n){n.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",n.LOW="LOW",n.HIGH="HIGH"})(dr||(dr={}));var ur;(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"})(ur||(ur={}));var fr;(function(n){n.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",n.SEVERITY="SEVERITY",n.PROBABILITY="PROBABILITY"})(fr||(fr={}));var pr;(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"})(pr||(pr={}));var hr;(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"})(hr||(hr={}));var mr;(function(n){n.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",n.NEGLIGIBLE="NEGLIGIBLE",n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH"})(mr||(mr={}));var gr;(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"})(gr||(gr={}));var br;(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"})(br||(br={}));var yr;(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"})(yr||(yr={}));var Er;(function(n){n.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",n.ON_DEMAND="ON_DEMAND",n.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(Er||(Er={}));var un;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.AUDIO="AUDIO"})(un||(un={}));var wr;(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"})(wr||(wr={}));var vr;(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"})(vr||(vr={}));var Ir;(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"})(Ir||(Ir={}));var Gi;(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"})(Gi||(Gi={}));var Tr;(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"})(Tr||(Tr={}));var Cr;(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"})(Cr||(Cr={}));var _r;(function(n){n.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",n.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",n.BALANCED="BALANCED",n.PRIORITIZE_COST="PRIORITIZE_COST"})(_r||(_r={}));var Sr;(function(n){n.UNSPECIFIED="UNSPECIFIED",n.BLOCKING="BLOCKING",n.NON_BLOCKING="NON_BLOCKING"})(Sr||(Sr={}));var Ar;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(Ar||(Ar={}));var xr;(function(n){n.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",n.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(xr||(xr={}));var fn;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.AUTO="AUTO",n.ANY="ANY",n.NONE="NONE",n.VALIDATED="VALIDATED"})(fn||(fn={}));var Nr;(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"})(Nr||(Nr={}));var $r;(function(n){n.DONT_ALLOW="DONT_ALLOW",n.ALLOW_ADULT="ALLOW_ADULT",n.ALLOW_ALL="ALLOW_ALL"})($r||($r={}));var Pr;(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"})(Pr||(Pr={}));var Rr;(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"})(Rr||(Rr={}));var Gr;(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"})(Gr||(Gr={}));var Mr;(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"})(Mr||(Mr={}));var Dr;(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"})(Dr||(Dr={}));var kr;(function(n){n.FOREGROUND="FOREGROUND",n.BACKGROUND="BACKGROUND",n.PROMPT="PROMPT",n.SEMANTIC="SEMANTIC",n.INTERACTIVE="INTERACTIVE"})(kr||(kr={}));var Lr;(function(n){n.ASSET="ASSET",n.STYLE="STYLE"})(Lr||(Lr={}));var Ur;(function(n){n.INSERT="INSERT",n.REMOVE="REMOVE",n.REMOVE_STATIC="REMOVE_STATIC",n.OUTPAINT="OUTPAINT"})(Ur||(Ur={}));var Fr;(function(n){n.OPTIMIZED="OPTIMIZED",n.LOSSLESS="LOSSLESS"})(Fr||(Fr={}));var Br;(function(n){n.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",n.PREFERENCE_TUNING="PREFERENCE_TUNING"})(Br||(Br={}));var Vr;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.STATE_PENDING="STATE_PENDING",n.STATE_ACTIVE="STATE_ACTIVE",n.STATE_FAILED="STATE_FAILED"})(Vr||(Vr={}));var Hr;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.PROCESSING="PROCESSING",n.ACTIVE="ACTIVE",n.FAILED="FAILED"})(Hr||(Hr={}));var qr;(function(n){n.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",n.UPLOADED="UPLOADED",n.GENERATED="GENERATED"})(qr||(qr={}));var Or;(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"})(Or||(Or={}));var zr;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.VIDEO="VIDEO",n.AUDIO="AUDIO",n.DOCUMENT="DOCUMENT"})(zr||(zr={}));var Kr;(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"})(Kr||(Kr={}));var Jr;(function(n){n.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",n.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",n.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(Jr||(Jr={}));var Wr;(function(n){n.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",n.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",n.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(Wr||(Wr={}));var Xr;(function(n){n.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",n.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",n.NO_INTERRUPTION="NO_INTERRUPTION"})(Xr||(Xr={}));var Yr;(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"})(Yr||(Yr={}));var Qr;(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"})(Qr||(Qr={}));var Zr;(function(n){n.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",n.QUALITY="QUALITY",n.DIVERSITY="DIVERSITY",n.VOCALIZATION="VOCALIZATION"})(Zr||(Zr={}));var pt;(function(n){n.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",n.PLAY="PLAY",n.PAUSE="PAUSE",n.STOP="STOP",n.RESET_CONTEXT="RESET_CONTEXT"})(pt||(pt={}));var $t=class{static{p(this,"HttpResponse")}constructor(e){let t={};for(let i of e.headers.entries())t[i[0]]=i[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}};var tt=class{static{p(this,"GenerateContentResponse")}get text(){var e,t,i,o,s,a,c,d;if(((o=(i=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.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="",f=!1,h=[];for(let m of(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[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(m))g!=="text"&&g!=="thought"&&g!=="thoughtSignature"&&(b!==null||b!==void 0)&&h.push(g);if(typeof m.text=="string"){if(typeof m.thought=="boolean"&&m.thought)continue;f=!0,u+=m.text}}return h.length>0&&console.warn(`there are non-text parts ${h} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),f?u:void 0}get data(){var e,t,i,o,s,a,c,d;if(((o=(i=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.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="",f=[];for(let h of(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)!==null&&d!==void 0?d:[]){for(let[m,g]of Object.entries(h))m!=="inlineData"&&(g!==null||g!==void 0)&&f.push(m);h.inlineData&&typeof h.inlineData.data=="string"&&(u+=atob(h.inlineData.data))}return f.length>0&&console.warn(`there are non-data parts ${f} 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,i,o,s,a,c,d;if(((o=(i=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.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=(s=this.candidates)===null||s===void 0?void 0:s[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(f=>f.functionCall).map(f=>f.functionCall).filter(f=>f!==void 0);if(u?.length!==0)return u}get executableCode(){var e,t,i,o,s,a,c,d,u;if(((o=(i=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.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 f=(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[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(h=>h.executableCode).map(h=>h.executableCode).filter(h=>h!==void 0);if(f?.length!==0)return(u=f?.[0])===null||u===void 0?void 0:u.code}get codeExecutionResult(){var e,t,i,o,s,a,c,d,u;if(((o=(i=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.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 f=(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[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(h=>h.codeExecutionResult).map(h=>h.codeExecutionResult).filter(h=>h!==void 0);if(f?.length!==0)return(u=f?.[0])===null||u===void 0?void 0:u.output}},pn=class{static{p(this,"EmbedContentResponse")}},hn=class{static{p(this,"GenerateImagesResponse")}},Mi=class{static{p(this,"EditImageResponse")}},Di=class{static{p(this,"UpscaleImageResponse")}},ki=class{static{p(this,"RecontextImageResponse")}},Li=class{static{p(this,"SegmentImageResponse")}},mn=class{static{p(this,"ListModelsResponse")}},gn=class{static{p(this,"DeleteModelResponse")}},bn=class{static{p(this,"CountTokensResponse")}},Ui=class{static{p(this,"ComputeTokensResponse")}};var yn=class n{static{p(this,"GenerateVideosOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,o,s=e;return t?o=mc(s):o=hc(s),Object.assign(i,o),i}},En=class{static{p(this,"ListTuningJobsResponse")}},wn=class{static{p(this,"CancelTuningJobResponse")}},vn=class{static{p(this,"DeleteCachedContentResponse")}},In=class{static{p(this,"ListCachedContentsResponse")}},Fi=class{static{p(this,"ListDocumentsResponse")}},Bi=class{static{p(this,"ListFileSearchStoresResponse")}},Vi=class{static{p(this,"UploadToFileSearchStoreResumableResponse")}};var Hi=class n{static{p(this,"ImportFileOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,s=Ic(e);return Object.assign(i,s),i}},qi=class{static{p(this,"ListFilesResponse")}},Oi=class{static{p(this,"CreateFileResponse")}},zi=class{static{p(this,"DeleteFileResponse")}};var Tn=class{static{p(this,"ListBatchJobsResponse")}};var Ki=class{static{p(this,"LiveServerMessage")}get text(){var e,t,i;let o="",s=!1,a=[];for(let c of(i=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&i!==void 0?i:[]){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;s=!0,o+=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.`),s?o:void 0}get data(){var e,t,i;let o="",s=[];for(let a of(i=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&i!==void 0?i:[]){for(let[c,d]of Object.entries(a))c!=="inlineData"&&d!==null&&s.push(c);a.inlineData&&typeof a.inlineData.data=="string"&&(o+=atob(a.inlineData.data))}return s.length>0&&console.warn(`there are non-data parts ${s} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),o.length>0?btoa(o):void 0}};var Ji=class{static{p(this,"LiveMusicServerMessage")}get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var Wi=class n{static{p(this,"UploadToFileSearchStoreOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,s=Ca(e);return Object.assign(i,s),i}};function U(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}`}p(U,"tModel");function _a(n,e){let t=U(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:""}p(_a,"tCachesModel");function Sa(n){return Array.isArray(n)?n.map(e=>Cn(e)):[Cn(n)]}p(Sa,"tBlobs");function Cn(n){if(typeof n=="object"&&n!==null)return n;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof n}`)}p(Cn,"tBlob");function Aa(n){let e=Cn(n);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}p(Aa,"tImageBlob");function xa(n){let e=Cn(n);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}p(xa,"tAudioBlob");function jr(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}`)}p(jr,"tPart");function Na(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("PartListUnion is required");return Array.isArray(n)?n.map(e=>jr(e)):[jr(n)]}p(Na,"tParts");function Xi(n){return n!=null&&typeof n=="object"&&"parts"in n&&Array.isArray(n.parts)}p(Xi,"_isContent");function ea(n){return n!=null&&typeof n=="object"&&"functionCall"in n}p(ea,"_isFunctionCallPart");function ta(n){return n!=null&&typeof n=="object"&&"functionResponse"in n}p(ta,"_isFunctionResponsePart");function le(n){if(n==null)throw new Error("ContentUnion is required");return Xi(n)?n:{role:"user",parts:Na(n)}}p(le,"tContent");function Ro(n,e){if(!e)return[];if(n.isVertexAI()&&Array.isArray(e))return e.flatMap(t=>{let i=le(t);return i.parts&&i.parts.length>0&&i.parts[0].text!==void 0?[i.parts[0].text]:[]});if(n.isVertexAI()){let t=le(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=>le(t)):[le(e)]}p(Ro,"tContentsForEmbed");function Ie(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("contents are required");if(!Array.isArray(n)){if(ea(n)||ta(n))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[le(n)]}let e=[],t=[],i=Xi(n[0]);for(let o of n){let s=Xi(o);if(s!=i)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(s)e.push(o);else{if(ea(o)||ta(o))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(o)}}return i||e.push({role:"user",parts:Na(t)}),e}p(Ie,"tContents");function Ac(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(i=>i!=="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 i of t)e.anyOf.push({type:Object.values(Fe).includes(i.toUpperCase())?i.toUpperCase():Fe.TYPE_UNSPECIFIED})}}p(Ac,"flattenTypeArrayToAnyOf");function ht(n){let e={},t=["items"],i=["anyOf"],o=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=n.anyOf;s!=null&&s.length==2&&(s[0].type==="null"?(e.nullable=!0,n=s[1]):s[1].type==="null"&&(e.nullable=!0,n=s[0])),n.type instanceof Array&&Ac(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]=ht(c);else if(i.includes(a)){let d=[];for(let u of c){if(u.type=="null"){e.nullable=!0;continue}d.push(ht(u))}e[a]=d}else if(o.includes(a)){let d={};for(let[u,f]of Object.entries(c))d[u]=ht(f);e[a]=d}else{if(a==="additionalProperties")continue;e[a]=c}return e}p(ht,"processJsonSchema");function Go(n){return ht(n)}p(Go,"tSchema");function Mo(n){if(typeof n=="object")return n;if(typeof n=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:n}}};throw new Error(`Unsupported speechConfig type: ${typeof n}`)}p(Mo,"tSpeechConfig");function Do(n){if("multiSpeakerVoiceConfig"in n)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return n}p(Do,"tLiveSpeechConfig");function yt(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=ht(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=ht(e.response));return n}p(yt,"tTool");function Et(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}p(Et,"tTools");function xc(n,e,t,i=1){let o=!e.startsWith(`${t}/`)&&e.split("/").length===i;return n.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${n.getProject()}/${e}`:e.startsWith(`${t}/`)?`projects/${n.getProject()}/locations/${n.getLocation()}/${e}`:o?`projects/${n.getProject()}/locations/${n.getLocation()}/${t}/${e}`:e:o?`${t}/${e}`:e}p(xc,"resourceName");function ke(n,e){if(typeof e!="string")throw new Error("name must be a string");return xc(n,e,"cachedContents")}p(ke,"tCachedContentName");function $a(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}}p($a,"tTuningJobStatus");function Be(n){return Po(n)}p(Be,"tBytes");function Nc(n){return n!=null&&typeof n=="object"&&"name"in n}p(Nc,"_isFile");function $c(n){return n!=null&&typeof n=="object"&&"video"in n}p($c,"isGeneratedVideo");function Pc(n){return n!=null&&typeof n=="object"&&"uri"in n}p(Pc,"isVideo");function Pa(n){var e;let t;if(Nc(n)&&(t=n.name),!(Pc(n)&&(t=n.uri,t===void 0))&&!($c(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 o=t.split("files/")[1].match(/[a-z0-9]+/);if(o===null)throw new Error(`Could not extract file name from URI ${t}`);t=o[0]}else t.startsWith("files/")&&(t=t.split("files/")[1]);return t}}p(Pa,"tFileName");function Ra(n,e){let t;return n.isVertexAI()?t=e?"publishers/google/models":"models":t=e?"models":"tunedModels",t}p(Ra,"tModelsUrl");function Ga(n){for(let e of["models","tunedModels","publisherModels"])if(Rc(n,e))return n[e];return[]}p(Ga,"tExtractModels");function Rc(n,e){return n!==null&&typeof n=="object"&&e in n}p(Rc,"hasField");function Gc(n,e={}){let t=n,i={name:t.name,description:t.description,parametersJsonSchema:t.inputSchema};return t.outputSchema&&(i.responseJsonSchema=t.outputSchema),e.behavior&&(i.behavior=e.behavior),{functionDeclarations:[i]}}p(Gc,"mcpToGeminiTool");function Mc(n,e={}){let t=[],i=new Set;for(let o of n){let s=o.name;if(i.has(s))throw new Error(`Duplicate function name ${s} found in MCP tools. Please ensure function names are unique.`);i.add(s);let a=Gc(o,e);a.functionDeclarations&&t.push(...a.functionDeclarations)}return{functionDeclarations:t}}p(Mc,"mcpToolsToGeminiTool");function Ma(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 i=[t.gcsUri,t.bigqueryUri].filter(Boolean).length,o=[t.inlinedRequests,t.fileName].filter(Boolean).length;if(n.isVertexAI()){if(o>0||i!==1)throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(i>0||o!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return t}p(Ma,"tBatchJobSource");function Dc(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}`)}p(Dc,"tBatchJobDestination");function Da(n){if(typeof n!="object"||n===null)return{};let e=n,t=e.inlinedResponses;if(typeof t!="object"||t===null)return n;let o=t.inlinedResponses;if(!Array.isArray(o)||o.length===0)return n;let s=!1;for(let a of o){if(typeof a!="object"||a===null)continue;let d=a.response;if(typeof d!="object"||d===null)continue;if(d.embedding!==void 0){s=!0;break}}return s&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),n}p(Da,"tRecvBatchJobDestination");function wt(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}.`)}p(wt,"tBatchJobName");function ka(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}p(ka,"tJobState");function kc(n){let e={},t=r(n,["responsesFile"]);t!=null&&l(e,["fileName"],t);let i=r(n,["inlinedResponses","inlinedResponses"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>gd(a))),l(e,["inlinedResponses"],s)}let o=r(n,["inlinedEmbedContentResponses","inlinedResponses"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["inlinedEmbedContentResponses"],s)}return e}p(kc,"batchJobDestinationFromMldev");function Lc(n){let e={},t=r(n,["predictionsFormat"]);t!=null&&l(e,["format"],t);let i=r(n,["gcsDestination","outputUriPrefix"]);i!=null&&l(e,["gcsUri"],i);let o=r(n,["bigqueryDestination","outputUri"]);return o!=null&&l(e,["bigqueryUri"],o),e}p(Lc,"batchJobDestinationFromVertex");function Uc(n){let e={},t=r(n,["format"]);t!=null&&l(e,["predictionsFormat"],t);let i=r(n,["gcsUri"]);i!=null&&l(e,["gcsDestination","outputUriPrefix"],i);let o=r(n,["bigqueryUri"]);if(o!=null&&l(e,["bigqueryDestination","outputUri"],o),r(n,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(r(n,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is not supported in Vertex AI.");if(r(n,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");return e}p(Uc,"batchJobDestinationToVertex");function cn(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata","displayName"]);i!=null&&l(e,["displayName"],i);let o=r(n,["metadata","state"]);o!=null&&l(e,["state"],ka(o));let s=r(n,["metadata","createTime"]);s!=null&&l(e,["createTime"],s);let a=r(n,["metadata","endTime"]);a!=null&&l(e,["endTime"],a);let c=r(n,["metadata","updateTime"]);c!=null&&l(e,["updateTime"],c);let d=r(n,["metadata","model"]);d!=null&&l(e,["model"],d);let u=r(n,["metadata","output"]);return u!=null&&l(e,["dest"],kc(Da(u))),e}p(cn,"batchJobFromMldev");function Yi(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["displayName"]);i!=null&&l(e,["displayName"],i);let o=r(n,["state"]);o!=null&&l(e,["state"],ka(o));let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["createTime"]);a!=null&&l(e,["createTime"],a);let c=r(n,["startTime"]);c!=null&&l(e,["startTime"],c);let d=r(n,["endTime"]);d!=null&&l(e,["endTime"],d);let u=r(n,["updateTime"]);u!=null&&l(e,["updateTime"],u);let f=r(n,["model"]);f!=null&&l(e,["model"],f);let h=r(n,["inputConfig"]);h!=null&&l(e,["src"],Fc(h));let m=r(n,["outputConfig"]);m!=null&&l(e,["dest"],Lc(Da(m)));let g=r(n,["completionStats"]);return g!=null&&l(e,["completionStats"],g),e}p(Yi,"batchJobFromVertex");function Fc(n){let e={},t=r(n,["instancesFormat"]);t!=null&&l(e,["format"],t);let i=r(n,["gcsSource","uris"]);i!=null&&l(e,["gcsUri"],i);let o=r(n,["bigquerySource","inputUri"]);return o!=null&&l(e,["bigqueryUri"],o),e}p(Fc,"batchJobSourceFromVertex");function Bc(n,e){let t={};if(r(e,["format"])!==void 0)throw new Error("format parameter is not supported in Gemini API.");if(r(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(r(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is not supported in Gemini API.");let i=r(e,["fileName"]);i!=null&&l(t,["fileName"],i);let o=r(e,["inlinedRequests"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>md(n,a))),l(t,["requests","requests"],s)}return t}p(Bc,"batchJobSourceToMldev");function Vc(n){let e={},t=r(n,["format"]);t!=null&&l(e,["instancesFormat"],t);let i=r(n,["gcsUri"]);i!=null&&l(e,["gcsSource","uris"],i);let o=r(n,["bigqueryUri"]);if(o!=null&&l(e,["bigquerySource","inputUri"],o),r(n,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(r(n,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is not supported in Vertex AI.");return e}p(Vc,"batchJobSourceToVertex");function Hc(n){let e={},t=r(n,["data"]);if(t!=null&&l(e,["data"],t),r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(Hc,"blobToMldev$4");function qc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],wt(n,i)),t}p(qc,"cancelBatchJobParametersToMldev");function Oc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],wt(n,i)),t}p(Oc,"cancelBatchJobParametersToVertex");function zc(n){let e={},t=r(n,["content"]);t!=null&&l(e,["content"],t);let i=r(n,["citationMetadata"]);i!=null&&l(e,["citationMetadata"],Kc(i));let o=r(n,["tokenCount"]);o!=null&&l(e,["tokenCount"],o);let s=r(n,["finishReason"]);s!=null&&l(e,["finishReason"],s);let a=r(n,["avgLogprobs"]);a!=null&&l(e,["avgLogprobs"],a);let c=r(n,["groundingMetadata"]);c!=null&&l(e,["groundingMetadata"],c);let d=r(n,["index"]);d!=null&&l(e,["index"],d);let u=r(n,["logprobsResult"]);u!=null&&l(e,["logprobsResult"],u);let f=r(n,["safetyRatings"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(g=>g)),l(e,["safetyRatings"],m)}let h=r(n,["urlContextMetadata"]);return h!=null&&l(e,["urlContextMetadata"],h),e}p(zc,"candidateFromMldev$1");function Kc(n){let e={},t=r(n,["citationSources"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>o)),l(e,["citations"],i)}return e}p(Kc,"citationMetadataFromMldev$1");function La(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>Td(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(La,"contentToMldev$4");function Jc(n,e){let t={},i=r(n,["displayName"]);if(e!==void 0&&i!=null&&l(e,["batch","displayName"],i),r(n,["dest"])!==void 0)throw new Error("dest parameter is not supported in Gemini API.");return t}p(Jc,"createBatchJobConfigToMldev");function Wc(n,e){let t={},i=r(n,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=r(n,["dest"]);return e!==void 0&&o!=null&&l(e,["outputConfig"],Uc(Dc(o))),t}p(Wc,"createBatchJobConfigToVertex");function na(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["src"]);o!=null&&l(t,["batch","inputConfig"],Bc(n,Ma(n,o)));let s=r(e,["config"]);return s!=null&&Jc(s,t),t}p(na,"createBatchJobParametersToMldev");function Xc(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],U(n,i));let o=r(e,["src"]);o!=null&&l(t,["inputConfig"],Vc(Ma(n,o)));let s=r(e,["config"]);return s!=null&&Wc(s,t),t}p(Xc,"createBatchJobParametersToVertex");function Yc(n,e){let t={},i=r(n,["displayName"]);return e!==void 0&&i!=null&&l(e,["batch","displayName"],i),t}p(Yc,"createEmbeddingsBatchJobConfigToMldev");function Qc(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["src"]);o!=null&&l(t,["batch","inputConfig"],od(n,o));let s=r(e,["config"]);return s!=null&&Yc(s,t),t}p(Qc,"createEmbeddingsBatchJobParametersToMldev");function Zc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],wt(n,i)),t}p(Zc,"deleteBatchJobParametersToMldev");function jc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],wt(n,i)),t}p(jc,"deleteBatchJobParametersToVertex");function ed(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["name"]);i!=null&&l(e,["name"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);return s!=null&&l(e,["error"],s),e}p(ed,"deleteResourceJobFromMldev");function td(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["name"]);i!=null&&l(e,["name"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);return s!=null&&l(e,["error"],s),e}p(td,"deleteResourceJobFromVertex");function nd(n,e){let t={},i=r(e,["contents"]);if(i!=null){let s=Ro(n,i);Array.isArray(s)&&(s=s.map(a=>a)),l(t,["requests[]","request","content"],s)}let o=r(e,["config"]);return o!=null&&(l(t,["_self"],id(o,t)),fc(t,{"requests[].*":"requests[].request.*"})),t}p(nd,"embedContentBatchToMldev");function id(n,e){let t={},i=r(n,["taskType"]);e!==void 0&&i!=null&&l(e,["requests[]","taskType"],i);let o=r(n,["title"]);e!==void 0&&o!=null&&l(e,["requests[]","title"],o);let s=r(n,["outputDimensionality"]);if(e!==void 0&&s!=null&&l(e,["requests[]","outputDimensionality"],s),r(n,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(r(n,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return t}p(id,"embedContentConfigToMldev$1");function od(n,e){let t={},i=r(e,["fileName"]);i!=null&&l(t,["file_name"],i);let o=r(e,["inlinedRequests"]);return o!=null&&l(t,["requests"],nd(n,o)),t}p(od,"embeddingsBatchJobSourceToMldev");function sd(n){let e={};if(r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=r(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(sd,"fileDataToMldev$4");function rd(n){let e={},t=r(n,["id"]);t!=null&&l(e,["id"],t);let i=r(n,["args"]);i!=null&&l(e,["args"],i);let o=r(n,["name"]);if(o!=null&&l(e,["name"],o),r(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(r(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}p(rd,"functionCallToMldev$4");function ad(n){let e={},t=r(n,["mode"]);t!=null&&l(e,["mode"],t);let i=r(n,["allowedFunctionNames"]);if(i!=null&&l(e,["allowedFunctionNames"],i),r(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}p(ad,"functionCallingConfigToMldev$2");function ld(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],La(le(o)));let s=r(e,["temperature"]);s!=null&&l(i,["temperature"],s);let a=r(e,["topP"]);a!=null&&l(i,["topP"],a);let c=r(e,["topK"]);c!=null&&l(i,["topK"],c);let d=r(e,["candidateCount"]);d!=null&&l(i,["candidateCount"],d);let u=r(e,["maxOutputTokens"]);u!=null&&l(i,["maxOutputTokens"],u);let f=r(e,["stopSequences"]);f!=null&&l(i,["stopSequences"],f);let h=r(e,["responseLogprobs"]);h!=null&&l(i,["responseLogprobs"],h);let m=r(e,["logprobs"]);m!=null&&l(i,["logprobs"],m);let g=r(e,["presencePenalty"]);g!=null&&l(i,["presencePenalty"],g);let b=r(e,["frequencyPenalty"]);b!=null&&l(i,["frequencyPenalty"],b);let E=r(e,["seed"]);E!=null&&l(i,["seed"],E);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],Go(v));let I=r(e,["responseJsonSchema"]);if(I!=null&&l(i,["responseJsonSchema"],I),r(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(r(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");let T=r(e,["safetySettings"]);if(t!==void 0&&T!=null){let V=T;Array.isArray(V)&&(V=V.map(we=>Cd(we))),l(t,["safetySettings"],V)}let S=r(e,["tools"]);if(t!==void 0&&S!=null){let V=Et(S);Array.isArray(V)&&(V=V.map(we=>Sd(yt(we)))),l(t,["tools"],V)}let N=r(e,["toolConfig"]);if(t!==void 0&&N!=null&&l(t,["toolConfig"],_d(N)),r(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let $=r(e,["cachedContent"]);t!==void 0&&$!=null&&l(t,["cachedContent"],ke(n,$));let A=r(e,["responseModalities"]);A!=null&&l(i,["responseModalities"],A);let P=r(e,["mediaResolution"]);P!=null&&l(i,["mediaResolution"],P);let x=r(e,["speechConfig"]);if(x!=null&&l(i,["speechConfig"],Mo(x)),r(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let k=r(e,["thinkingConfig"]);k!=null&&l(i,["thinkingConfig"],k);let O=r(e,["imageConfig"]);O!=null&&l(i,["imageConfig"],hd(O));let j=r(e,["enableEnhancedCivicAnswers"]);return j!=null&&l(i,["enableEnhancedCivicAnswers"],j),i}p(ld,"generateContentConfigToMldev$1");function cd(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["candidates"]);if(i!=null){let d=i;Array.isArray(d)&&(d=d.map(u=>zc(u))),l(e,["candidates"],d)}let o=r(n,["modelVersion"]);o!=null&&l(e,["modelVersion"],o);let s=r(n,["promptFeedback"]);s!=null&&l(e,["promptFeedback"],s);let a=r(n,["responseId"]);a!=null&&l(e,["responseId"],a);let c=r(n,["usageMetadata"]);return c!=null&&l(e,["usageMetadata"],c),e}p(cd,"generateContentResponseFromMldev$1");function dd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],wt(n,i)),t}p(dd,"getBatchJobParametersToMldev");function ud(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],wt(n,i)),t}p(ud,"getBatchJobParametersToVertex");function fd(n){let e={};if(r(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=r(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}p(fd,"googleMapsToMldev$4");function pd(n){let e={};if(r(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(r(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=r(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}p(pd,"googleSearchToMldev$4");function hd(n){let e={},t=r(n,["aspectRatio"]);t!=null&&l(e,["aspectRatio"],t);let i=r(n,["imageSize"]);if(i!=null&&l(e,["imageSize"],i),r(n,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(r(n,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}p(hd,"imageConfigToMldev$1");function md(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["request","model"],U(n,i));let o=r(e,["contents"]);if(o!=null){let c=Ie(o);Array.isArray(c)&&(c=c.map(d=>La(d))),l(t,["request","contents"],c)}let s=r(e,["metadata"]);s!=null&&l(t,["metadata"],s);let a=r(e,["config"]);return a!=null&&l(t,["request","generationConfig"],ld(n,a,r(t,["request"],{}))),t}p(md,"inlinedRequestToMldev");function gd(n){let e={},t=r(n,["response"]);t!=null&&l(e,["response"],cd(t));let i=r(n,["error"]);return i!=null&&l(e,["error"],i),e}p(gd,"inlinedResponseFromMldev");function bd(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);if(e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),r(n,["filter"])!==void 0)throw new Error("filter parameter is not supported in Gemini API.");return t}p(bd,"listBatchJobsConfigToMldev");function yd(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);e!==void 0&&o!=null&&l(e,["_query","pageToken"],o);let s=r(n,["filter"]);return e!==void 0&&s!=null&&l(e,["_query","filter"],s),t}p(yd,"listBatchJobsConfigToVertex");function Ed(n){let e={},t=r(n,["config"]);return t!=null&&bd(t,e),e}p(Ed,"listBatchJobsParametersToMldev");function wd(n){let e={},t=r(n,["config"]);return t!=null&&yd(t,e),e}p(wd,"listBatchJobsParametersToVertex");function vd(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["operations"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>cn(a))),l(e,["batchJobs"],s)}return e}p(vd,"listBatchJobsResponseFromMldev");function Id(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["batchPredictionJobs"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>Yi(a))),l(e,["batchJobs"],s)}return e}p(Id,"listBatchJobsResponseFromVertex");function Td(n){let e={},t=r(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let i=r(n,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=r(n,["executableCode"]);o!=null&&l(e,["executableCode"],o);let s=r(n,["fileData"]);s!=null&&l(e,["fileData"],sd(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],rd(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],Hc(d));let u=r(n,["text"]);u!=null&&l(e,["text"],u);let f=r(n,["thought"]);f!=null&&l(e,["thought"],f);let h=r(n,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=r(n,["videoMetadata"]);return m!=null&&l(e,["videoMetadata"],m),e}p(Td,"partToMldev$4");function Cd(n){let e={},t=r(n,["category"]);if(t!=null&&l(e,["category"],t),r(n,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let i=r(n,["threshold"]);return i!=null&&l(e,["threshold"],i),e}p(Cd,"safetySettingToMldev$1");function _d(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],ad(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(_d,"toolConfigToMldev$2");function Sd(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let f=t;Array.isArray(f)&&(f=f.map(h=>h)),l(e,["functionDeclarations"],f)}if(r(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let i=r(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let o=r(n,["computerUse"]);o!=null&&l(e,["computerUse"],o);let s=r(n,["fileSearch"]);s!=null&&l(e,["fileSearch"],s);let a=r(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),r(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],fd(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],pd(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Sd,"toolToMldev$4");var Me;(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"})(Me||(Me={}));var De=class{static{p(this,"Pager")}constructor(e,t,i,o){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,i,o)}init(e,t,i){var o,s;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=t?.sdkHttpResponse,this.idxInternal=0;let a={config:{}};!i||Object.keys(i).length===0?a={config:{}}:typeof i=="object"?a=Object.assign({},i):a=i,a.config&&(a.config.pageToken=t.nextPageToken),this.paramsInternal=a,this.pageInternalSize=(s=(o=a.config)===null||o===void 0?void 0:o.pageSize)!==null&&s!==void 0?s: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:p(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:p(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 Qi=class extends Ne{static{p(this,"Batches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new De(Me.PAGED_ITEM_BATCH_JOBS,i=>this.listInternal(i),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=na(this.apiClient,e),i=t._url,o=_("{model}:batchGenerateContent",i),c=t.batch.inputConfig.requests,d=c.requests,u=[];for(let f of d){let h=Object.assign({},f);if(h.systemInstruction){let m=h.systemInstruction;delete h.systemInstruction;let g=h.request;g.systemInstruction=m,h.request=g}u.push(h)}return c.requests=u,delete t.config,delete t._url,delete t._query,{path:o,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 i=t?Object.assign({},t):{},o=Date.now().toString();if(i.displayName||(i.displayName=`genaiBatchJob_${o}`),i.dest===void 0){let s=this.getGcsUri(e),a=this.getBigqueryUri(e);if(s)s.endsWith(".jsonl")?i.dest=`${s.slice(0,-6)}/dest`:i.dest=`${s}_dest_${o}`;else if(a)i.dest=`${a}_dest_${o}`;else throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.")}return i}async createInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Xc(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>Yi(f))}else{let u=na(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>cn(f))}}async createEmbeddingsInternal(e){var t,i;let o,s="",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 s=_("{model}:asyncBatchEmbedContent",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>cn(d))}}async get(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=ud(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>Yi(f))}else{let u=dd(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>cn(f))}}async cancel(e){var t,i,o,s;let a="",c={};if(this.apiClient.isVertexAI()){let d=Oc(this.apiClient,e);a=_("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:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}else{let d=qc(this.apiClient,e);a=_("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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal})}}async listInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=wd(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Id(f),m=new Tn;return Object.assign(m,h),m})}else{let u=Ed(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=vd(f),m=new Tn;return Object.assign(m,h),m})}}async delete(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=jc(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>td(f))}else{let u=Zc(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>ed(f))}}};function Ad(n){let e={},t=r(n,["data"]);if(t!=null&&l(e,["data"],t),r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(Ad,"blobToMldev$3");function ia(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>Yd(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(ia,"contentToMldev$3");function xd(n,e){let t={},i=r(n,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=r(n,["expireTime"]);e!==void 0&&o!=null&&l(e,["expireTime"],o);let s=r(n,["displayName"]);e!==void 0&&s!=null&&l(e,["displayName"],s);let a=r(n,["contents"]);if(e!==void 0&&a!=null){let f=Ie(a);Array.isArray(f)&&(f=f.map(h=>ia(h))),l(e,["contents"],f)}let c=r(n,["systemInstruction"]);e!==void 0&&c!=null&&l(e,["systemInstruction"],ia(le(c)));let d=r(n,["tools"]);if(e!==void 0&&d!=null){let f=d;Array.isArray(f)&&(f=f.map(h=>Zd(h))),l(e,["tools"],f)}let u=r(n,["toolConfig"]);if(e!==void 0&&u!=null&&l(e,["toolConfig"],Qd(u)),r(n,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return t}p(xd,"createCachedContentConfigToMldev");function Nd(n,e){let t={},i=r(n,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=r(n,["expireTime"]);e!==void 0&&o!=null&&l(e,["expireTime"],o);let s=r(n,["displayName"]);e!==void 0&&s!=null&&l(e,["displayName"],s);let a=r(n,["contents"]);if(e!==void 0&&a!=null){let h=Ie(a);Array.isArray(h)&&(h=h.map(m=>m)),l(e,["contents"],h)}let c=r(n,["systemInstruction"]);e!==void 0&&c!=null&&l(e,["systemInstruction"],le(c));let d=r(n,["tools"]);if(e!==void 0&&d!=null){let h=d;Array.isArray(h)&&(h=h.map(m=>jd(m))),l(e,["tools"],h)}let u=r(n,["toolConfig"]);e!==void 0&&u!=null&&l(e,["toolConfig"],u);let f=r(n,["kmsKeyName"]);return e!==void 0&&f!=null&&l(e,["encryption_spec","kmsKeyName"],f),t}p(Nd,"createCachedContentConfigToVertex");function $d(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],_a(n,i));let o=r(e,["config"]);return o!=null&&xd(o,t),t}p($d,"createCachedContentParametersToMldev");function Pd(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],_a(n,i));let o=r(e,["config"]);return o!=null&&Nd(o,t),t}p(Pd,"createCachedContentParametersToVertex");function Rd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],ke(n,i)),t}p(Rd,"deleteCachedContentParametersToMldev");function Gd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],ke(n,i)),t}p(Gd,"deleteCachedContentParametersToVertex");function Md(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Md,"deleteCachedContentResponseFromMldev");function Dd(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Dd,"deleteCachedContentResponseFromVertex");function kd(n){let e={};if(r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=r(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(kd,"fileDataToMldev$3");function Ld(n){let e={},t=r(n,["id"]);t!=null&&l(e,["id"],t);let i=r(n,["args"]);i!=null&&l(e,["args"],i);let o=r(n,["name"]);if(o!=null&&l(e,["name"],o),r(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(r(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}p(Ld,"functionCallToMldev$3");function Ud(n){let e={},t=r(n,["mode"]);t!=null&&l(e,["mode"],t);let i=r(n,["allowedFunctionNames"]);if(i!=null&&l(e,["allowedFunctionNames"],i),r(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}p(Ud,"functionCallingConfigToMldev$1");function Fd(n){let e={};if(r(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=r(n,["description"]);t!=null&&l(e,["description"],t);let i=r(n,["name"]);i!=null&&l(e,["name"],i);let o=r(n,["parameters"]);o!=null&&l(e,["parameters"],o);let s=r(n,["parametersJsonSchema"]);s!=null&&l(e,["parametersJsonSchema"],s);let a=r(n,["response"]);a!=null&&l(e,["response"],a);let c=r(n,["responseJsonSchema"]);return c!=null&&l(e,["responseJsonSchema"],c),e}p(Fd,"functionDeclarationToVertex$2");function Bd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],ke(n,i)),t}p(Bd,"getCachedContentParametersToMldev");function Vd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],ke(n,i)),t}p(Vd,"getCachedContentParametersToVertex");function Hd(n){let e={};if(r(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=r(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}p(Hd,"googleMapsToMldev$3");function qd(n){let e={};if(r(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(r(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=r(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}p(qd,"googleSearchToMldev$3");function Od(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),t}p(Od,"listCachedContentsConfigToMldev");function zd(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),t}p(zd,"listCachedContentsConfigToVertex");function Kd(n){let e={},t=r(n,["config"]);return t!=null&&Od(t,e),e}p(Kd,"listCachedContentsParametersToMldev");function Jd(n){let e={},t=r(n,["config"]);return t!=null&&zd(t,e),e}p(Jd,"listCachedContentsParametersToVertex");function Wd(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["cachedContents"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["cachedContents"],s)}return e}p(Wd,"listCachedContentsResponseFromMldev");function Xd(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["cachedContents"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["cachedContents"],s)}return e}p(Xd,"listCachedContentsResponseFromVertex");function Yd(n){let e={},t=r(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let i=r(n,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=r(n,["executableCode"]);o!=null&&l(e,["executableCode"],o);let s=r(n,["fileData"]);s!=null&&l(e,["fileData"],kd(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],Ld(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],Ad(d));let u=r(n,["text"]);u!=null&&l(e,["text"],u);let f=r(n,["thought"]);f!=null&&l(e,["thought"],f);let h=r(n,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=r(n,["videoMetadata"]);return m!=null&&l(e,["videoMetadata"],m),e}p(Yd,"partToMldev$3");function Qd(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],Ud(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(Qd,"toolConfigToMldev$1");function Zd(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let f=t;Array.isArray(f)&&(f=f.map(h=>h)),l(e,["functionDeclarations"],f)}if(r(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let i=r(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let o=r(n,["computerUse"]);o!=null&&l(e,["computerUse"],o);let s=r(n,["fileSearch"]);s!=null&&l(e,["fileSearch"],s);let a=r(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),r(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],Hd(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],qd(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Zd,"toolToMldev$3");function jd(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>Fd(m))),l(e,["functionDeclarations"],h)}let i=r(n,["retrieval"]);i!=null&&l(e,["retrieval"],i);let o=r(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let s=r(n,["computerUse"]);if(s!=null&&l(e,["computerUse"],s),r(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let a=r(n,["codeExecution"]);a!=null&&l(e,["codeExecution"],a);let c=r(n,["enterpriseWebSearch"]);c!=null&&l(e,["enterpriseWebSearch"],c);let d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],d);let u=r(n,["googleSearch"]);u!=null&&l(e,["googleSearch"],u);let f=r(n,["urlContext"]);return f!=null&&l(e,["urlContext"],f),e}p(jd,"toolToVertex$2");function eu(n,e){let t={},i=r(n,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=r(n,["expireTime"]);return e!==void 0&&o!=null&&l(e,["expireTime"],o),t}p(eu,"updateCachedContentConfigToMldev");function tu(n,e){let t={},i=r(n,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=r(n,["expireTime"]);return e!==void 0&&o!=null&&l(e,["expireTime"],o),t}p(tu,"updateCachedContentConfigToVertex");function nu(n,e){let t={},i=r(e,["name"]);i!=null&&l(t,["_url","name"],ke(n,i));let o=r(e,["config"]);return o!=null&&eu(o,t),t}p(nu,"updateCachedContentParametersToMldev");function iu(n,e){let t={},i=r(e,["name"]);i!=null&&l(t,["_url","name"],ke(n,i));let o=r(e,["config"]);return o!=null&&tu(o,t),t}p(iu,"updateCachedContentParametersToVertex");var Zi=class extends Ne{static{p(this,"Caches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new De(Me.PAGED_ITEM_CACHED_CONTENTS,i=>this.listInternal(i),await this.listInternal(t),t)}async create(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Pd(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let u=$d(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async get(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Vd(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let u=Bd(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async delete(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Gd(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Dd(f),m=new vn;return Object.assign(m,h),m})}else{let u=Rd(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Md(f),m=new vn;return Object.assign(m,h),m})}}async update(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=iu(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let u=nu(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async listInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Jd(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Xd(f),m=new In;return Object.assign(m,h),m})}else{let u=Kd(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Wd(f),m=new In;return Object.assign(m,h),m})}}};function _n(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,i=Object.getOwnPropertySymbols(n);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(n,i[o])&&(t[i[o]]=n[i[o]]);return t}p(_n,"__rest");function oa(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:p(function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}},"next")};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}p(oa,"__values");function G(n){return this instanceof G?(this.v=n,this):new G(n)}p(G,"__await");function Ae(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",a),o[Symbol.asyncIterator]=function(){return this},o;function a(g){return function(b){return Promise.resolve(b).then(g,h)}}function c(g,b){i[g]&&(o[g]=function(E){return new Promise(function(w,v){s.push([g,E,w,v])>1||d(g,E)})},b&&(o[g]=b(o[g])))}function d(g,b){try{u(i[g](b))}catch(E){m(s[0][3],E)}}function u(g){g.value instanceof G?Promise.resolve(g.value.v).then(f,h):m(s[0][2],g)}function f(g){d("next",g)}function h(g){d("throw",g)}function m(g,b){g(b),s.shift(),s.length&&d(s[0][0],s[0][1])}}p(Ae,"__asyncGenerator");function xe(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={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(a){return new Promise(function(c,d){a=n[s](a),o(c,d,a.done,a.value)})}}function o(s,a,c,d){Promise.resolve(d).then(function(u){s({value:u,done:c})},a)}}p(xe,"__asyncValues");function ou(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:Ua(t)}p(ou,"isValidResponse");function Ua(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}p(Ua,"isValidContent");function su(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}.`)}}p(su,"validateHistory");function sa(n){if(n===void 0||n.length===0)return[];let e=[],t=n.length,i=0;for(;i<t;)if(n[i].role==="user")e.push(n[i]),i++;else{let o=[],s=!0;for(;i<t&&n[i].role==="model";)o.push(n[i]),s&&!Ua(n[i])&&(s=!1),i++;s?e.push(...o):e.pop()}return e}p(sa,"extractCuratedHistory");var ji=class{static{p(this,"Chats")}constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new eo(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},eo=class{static{p(this,"Chat")}constructor(e,t,i,o={},s=[]){this.apiClient=e,this.modelsModule=t,this.model=i,this.config=o,this.history=s,this.sendPromise=Promise.resolve(),su(s)}async sendMessage(e){var t;await this.sendPromise;let i=le(e.message),o=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(i),config:(t=e.config)!==null&&t!==void 0?t:this.config});return this.sendPromise=(async()=>{var s,a,c;let d=await o,u=(a=(s=d.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content,f=d.automaticFunctionCallingHistory,h=this.getHistory(!0).length,m=[];f!=null&&(m=(c=f.slice(h))!==null&&c!==void 0?c:[]);let g=u?[u]:[];this.recordHistory(i,g,m)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),o}async sendMessageStream(e){var t;await this.sendPromise;let i=le(e.message),o=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(i),config:(t=e.config)!==null&&t!==void 0?t:this.config});this.sendPromise=o.then(()=>{}).catch(()=>{});let s=await o;return this.processStreamResponse(s,i)}getHistory(e=!1){let t=e?sa(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return Ae(this,arguments,p(function*(){var o,s,a,c,d,u;let f=[];try{for(var h=!0,m=xe(e),g;g=yield G(m.next()),o=g.done,!o;h=!0){c=g.value,h=!1;let b=c;if(ou(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&&f.push(E)}yield yield G(b)}}catch(b){s={error:b}}finally{try{!h&&!o&&(a=m.return)&&(yield G(a.call(m)))}finally{if(s)throw s.error}}this.recordHistory(t,f)},"processStreamResponse_1"))}recordHistory(e,t,i){let o=[];t.length>0&&t.every(s=>s.role!==void 0)?o=t:o.push({role:"model",parts:[]}),i&&i.length>0?this.history.push(...sa(i)):this.history.push(e),this.history.push(...o)}};var Sn=class n extends Error{static{p(this,"ApiError")}constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,n.prototype)}};function ru(n){let e={},t=r(n,["file"]);return t!=null&&l(e,["file"],t),e}p(ru,"createFileParametersToMldev");function au(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(au,"createFileResponseFromMldev");function lu(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","file"],Pa(t)),e}p(lu,"deleteFileParametersToMldev");function cu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(cu,"deleteFileResponseFromMldev");function du(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","file"],Pa(t)),e}p(du,"getFileParametersToMldev");function uu(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),t}p(uu,"listFilesConfigToMldev");function fu(n){let e={},t=r(n,["config"]);return t!=null&&uu(t,e),e}p(fu,"listFilesParametersToMldev");function pu(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["files"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["files"],s)}return e}p(pu,"listFilesResponseFromMldev");var to=class extends Ne{static{p(this,"Files")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new De(Me.PAGED_ITEM_FILES,i=>this.listInternal(i),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,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=fu(e);return s=_("files",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>{let u=pu(d),f=new qi;return Object.assign(f,u),f})}}async createInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=ru(e);return s=_("upload/v1beta/files",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=au(d),f=new Oi;return Object.assign(f,u),f})}}async get(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=du(e);return s=_("files/{file}",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>d)}}async delete(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=lu(e);return s=_("files/{file}",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>{let u=cu(d),f=new zi;return Object.assign(f,u),f})}}};function dn(n){let e={},t=r(n,["data"]);if(t!=null&&l(e,["data"],t),r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(dn,"blobToMldev$2");function hu(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>$u(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(hu,"contentToMldev$2");function mu(n){let e={};if(r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=r(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(mu,"fileDataToMldev$2");function gu(n){let e={},t=r(n,["id"]);t!=null&&l(e,["id"],t);let i=r(n,["args"]);i!=null&&l(e,["args"],i);let o=r(n,["name"]);if(o!=null&&l(e,["name"],o),r(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(r(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}p(gu,"functionCallToMldev$2");function bu(n){let e={};if(r(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=r(n,["description"]);t!=null&&l(e,["description"],t);let i=r(n,["name"]);i!=null&&l(e,["name"],i);let o=r(n,["parameters"]);o!=null&&l(e,["parameters"],o);let s=r(n,["parametersJsonSchema"]);s!=null&&l(e,["parametersJsonSchema"],s);let a=r(n,["response"]);a!=null&&l(e,["response"],a);let c=r(n,["responseJsonSchema"]);return c!=null&&l(e,["responseJsonSchema"],c),e}p(bu,"functionDeclarationToVertex$1");function yu(n){let e={},t=r(n,["modelSelectionConfig"]);t!=null&&l(e,["modelConfig"],t);let i=r(n,["responseJsonSchema"]);i!=null&&l(e,["responseJsonSchema"],i);let o=r(n,["audioTimestamp"]);o!=null&&l(e,["audioTimestamp"],o);let s=r(n,["candidateCount"]);s!=null&&l(e,["candidateCount"],s);let a=r(n,["enableAffectiveDialog"]);a!=null&&l(e,["enableAffectiveDialog"],a);let c=r(n,["frequencyPenalty"]);c!=null&&l(e,["frequencyPenalty"],c);let d=r(n,["logprobs"]);d!=null&&l(e,["logprobs"],d);let u=r(n,["maxOutputTokens"]);u!=null&&l(e,["maxOutputTokens"],u);let f=r(n,["mediaResolution"]);f!=null&&l(e,["mediaResolution"],f);let h=r(n,["presencePenalty"]);h!=null&&l(e,["presencePenalty"],h);let m=r(n,["responseLogprobs"]);m!=null&&l(e,["responseLogprobs"],m);let g=r(n,["responseMimeType"]);g!=null&&l(e,["responseMimeType"],g);let b=r(n,["responseModalities"]);b!=null&&l(e,["responseModalities"],b);let E=r(n,["responseSchema"]);E!=null&&l(e,["responseSchema"],E);let w=r(n,["routingConfig"]);w!=null&&l(e,["routingConfig"],w);let v=r(n,["seed"]);v!=null&&l(e,["seed"],v);let I=r(n,["speechConfig"]);I!=null&&l(e,["speechConfig"],Fa(I));let T=r(n,["stopSequences"]);T!=null&&l(e,["stopSequences"],T);let S=r(n,["temperature"]);S!=null&&l(e,["temperature"],S);let N=r(n,["thinkingConfig"]);N!=null&&l(e,["thinkingConfig"],N);let $=r(n,["topK"]);$!=null&&l(e,["topK"],$);let A=r(n,["topP"]);if(A!=null&&l(e,["topP"],A),r(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}p(yu,"generationConfigToVertex$1");function Eu(n){let e={};if(r(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=r(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}p(Eu,"googleMapsToMldev$2");function wu(n){let e={};if(r(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(r(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=r(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}p(wu,"googleSearchToMldev$2");function vu(n,e){let t={},i=r(n,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],i);let o=r(n,["responseModalities"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","responseModalities"],o);let s=r(n,["temperature"]);e!==void 0&&s!=null&&l(e,["setup","generationConfig","temperature"],s);let a=r(n,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let c=r(n,["topK"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","topK"],c);let d=r(n,["maxOutputTokens"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","maxOutputTokens"],d);let u=r(n,["mediaResolution"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","mediaResolution"],u);let f=r(n,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let h=r(n,["speechConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","speechConfig"],Do(h));let m=r(n,["thinkingConfig"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","thinkingConfig"],m);let g=r(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=r(n,["systemInstruction"]);e!==void 0&&b!=null&&l(e,["setup","systemInstruction"],hu(le(b)));let E=r(n,["tools"]);if(e!==void 0&&E!=null){let $=Et(E);Array.isArray($)&&($=$.map(A=>Ru(yt(A)))),l(e,["setup","tools"],$)}let w=r(n,["sessionResumption"]);e!==void 0&&w!=null&&l(e,["setup","sessionResumption"],Pu(w));let v=r(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&l(e,["setup","inputAudioTranscription"],v);let I=r(n,["outputAudioTranscription"]);e!==void 0&&I!=null&&l(e,["setup","outputAudioTranscription"],I);let T=r(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&l(e,["setup","realtimeInputConfig"],T);let S=r(n,["contextWindowCompression"]);e!==void 0&&S!=null&&l(e,["setup","contextWindowCompression"],S);let N=r(n,["proactivity"]);if(e!==void 0&&N!=null&&l(e,["setup","proactivity"],N),r(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}p(vu,"liveConnectConfigToMldev$1");function Iu(n,e){let t={},i=r(n,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],yu(i));let o=r(n,["responseModalities"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","responseModalities"],o);let s=r(n,["temperature"]);e!==void 0&&s!=null&&l(e,["setup","generationConfig","temperature"],s);let a=r(n,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let c=r(n,["topK"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","topK"],c);let d=r(n,["maxOutputTokens"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","maxOutputTokens"],d);let u=r(n,["mediaResolution"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","mediaResolution"],u);let f=r(n,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let h=r(n,["speechConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","speechConfig"],Fa(Do(h)));let m=r(n,["thinkingConfig"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","thinkingConfig"],m);let g=r(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=r(n,["systemInstruction"]);e!==void 0&&b!=null&&l(e,["setup","systemInstruction"],le(b));let E=r(n,["tools"]);if(e!==void 0&&E!=null){let A=Et(E);Array.isArray(A)&&(A=A.map(P=>Gu(yt(P)))),l(e,["setup","tools"],A)}let w=r(n,["sessionResumption"]);e!==void 0&&w!=null&&l(e,["setup","sessionResumption"],w);let v=r(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&l(e,["setup","inputAudioTranscription"],v);let I=r(n,["outputAudioTranscription"]);e!==void 0&&I!=null&&l(e,["setup","outputAudioTranscription"],I);let T=r(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&l(e,["setup","realtimeInputConfig"],T);let S=r(n,["contextWindowCompression"]);e!==void 0&&S!=null&&l(e,["setup","contextWindowCompression"],S);let N=r(n,["proactivity"]);e!==void 0&&N!=null&&l(e,["setup","proactivity"],N);let $=r(n,["explicitVadSignal"]);return e!==void 0&&$!=null&&l(e,["setup","explicitVadSignal"],$),t}p(Iu,"liveConnectConfigToVertex");function Tu(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],U(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],vu(o,t)),t}p(Tu,"liveConnectParametersToMldev");function Cu(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],U(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],Iu(o,t)),t}p(Cu,"liveConnectParametersToVertex");function _u(n){let e={},t=r(n,["musicGenerationConfig"]);return t!=null&&l(e,["musicGenerationConfig"],t),e}p(_u,"liveMusicSetConfigParametersToMldev");function Su(n){let e={},t=r(n,["weightedPrompts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>o)),l(e,["weightedPrompts"],i)}return e}p(Su,"liveMusicSetWeightedPromptsParametersToMldev");function Au(n){let e={},t=r(n,["media"]);if(t!=null){let u=Sa(t);Array.isArray(u)&&(u=u.map(f=>dn(f))),l(e,["mediaChunks"],u)}let i=r(n,["audio"]);i!=null&&l(e,["audio"],dn(xa(i)));let o=r(n,["audioStreamEnd"]);o!=null&&l(e,["audioStreamEnd"],o);let s=r(n,["video"]);s!=null&&l(e,["video"],dn(Aa(s)));let a=r(n,["text"]);a!=null&&l(e,["text"],a);let c=r(n,["activityStart"]);c!=null&&l(e,["activityStart"],c);let d=r(n,["activityEnd"]);return d!=null&&l(e,["activityEnd"],d),e}p(Au,"liveSendRealtimeInputParametersToMldev");function xu(n){let e={},t=r(n,["media"]);if(t!=null){let u=Sa(t);Array.isArray(u)&&(u=u.map(f=>f)),l(e,["mediaChunks"],u)}let i=r(n,["audio"]);i!=null&&l(e,["audio"],xa(i));let o=r(n,["audioStreamEnd"]);o!=null&&l(e,["audioStreamEnd"],o);let s=r(n,["video"]);s!=null&&l(e,["video"],Aa(s));let a=r(n,["text"]);a!=null&&l(e,["text"],a);let c=r(n,["activityStart"]);c!=null&&l(e,["activityStart"],c);let d=r(n,["activityEnd"]);return d!=null&&l(e,["activityEnd"],d),e}p(xu,"liveSendRealtimeInputParametersToVertex");function Nu(n){let e={},t=r(n,["setupComplete"]);t!=null&&l(e,["setupComplete"],t);let i=r(n,["serverContent"]);i!=null&&l(e,["serverContent"],i);let o=r(n,["toolCall"]);o!=null&&l(e,["toolCall"],o);let s=r(n,["toolCallCancellation"]);s!=null&&l(e,["toolCallCancellation"],s);let a=r(n,["usageMetadata"]);a!=null&&l(e,["usageMetadata"],Mu(a));let c=r(n,["goAway"]);c!=null&&l(e,["goAway"],c);let d=r(n,["sessionResumptionUpdate"]);d!=null&&l(e,["sessionResumptionUpdate"],d);let u=r(n,["voiceActivityDetectionSignal"]);return u!=null&&l(e,["voiceActivityDetectionSignal"],u),e}p(Nu,"liveServerMessageFromVertex");function $u(n){let e={},t=r(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let i=r(n,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=r(n,["executableCode"]);o!=null&&l(e,["executableCode"],o);let s=r(n,["fileData"]);s!=null&&l(e,["fileData"],mu(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],gu(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],dn(d));let u=r(n,["text"]);u!=null&&l(e,["text"],u);let f=r(n,["thought"]);f!=null&&l(e,["thought"],f);let h=r(n,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=r(n,["videoMetadata"]);return m!=null&&l(e,["videoMetadata"],m),e}p($u,"partToMldev$2");function Pu(n){let e={},t=r(n,["handle"]);if(t!=null&&l(e,["handle"],t),r(n,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}p(Pu,"sessionResumptionConfigToMldev$1");function Fa(n){let e={},t=r(n,["voiceConfig"]);t!=null&&l(e,["voiceConfig"],t);let i=r(n,["languageCode"]);if(i!=null&&l(e,["languageCode"],i),r(n,["multiSpeakerVoiceConfig"])!==void 0)throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");return e}p(Fa,"speechConfigToVertex$1");function Ru(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let f=t;Array.isArray(f)&&(f=f.map(h=>h)),l(e,["functionDeclarations"],f)}if(r(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let i=r(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let o=r(n,["computerUse"]);o!=null&&l(e,["computerUse"],o);let s=r(n,["fileSearch"]);s!=null&&l(e,["fileSearch"],s);let a=r(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),r(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],Eu(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],wu(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Ru,"toolToMldev$2");function Gu(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>bu(m))),l(e,["functionDeclarations"],h)}let i=r(n,["retrieval"]);i!=null&&l(e,["retrieval"],i);let o=r(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let s=r(n,["computerUse"]);if(s!=null&&l(e,["computerUse"],s),r(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let a=r(n,["codeExecution"]);a!=null&&l(e,["codeExecution"],a);let c=r(n,["enterpriseWebSearch"]);c!=null&&l(e,["enterpriseWebSearch"],c);let d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],d);let u=r(n,["googleSearch"]);u!=null&&l(e,["googleSearch"],u);let f=r(n,["urlContext"]);return f!=null&&l(e,["urlContext"],f),e}p(Gu,"toolToVertex$1");function Mu(n){let e={},t=r(n,["promptTokenCount"]);t!=null&&l(e,["promptTokenCount"],t);let i=r(n,["cachedContentTokenCount"]);i!=null&&l(e,["cachedContentTokenCount"],i);let o=r(n,["candidatesTokenCount"]);o!=null&&l(e,["responseTokenCount"],o);let s=r(n,["toolUsePromptTokenCount"]);s!=null&&l(e,["toolUsePromptTokenCount"],s);let a=r(n,["thoughtsTokenCount"]);a!=null&&l(e,["thoughtsTokenCount"],a);let c=r(n,["totalTokenCount"]);c!=null&&l(e,["totalTokenCount"],c);let d=r(n,["promptTokensDetails"]);if(d!=null){let g=d;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["promptTokensDetails"],g)}let u=r(n,["cacheTokensDetails"]);if(u!=null){let g=u;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["cacheTokensDetails"],g)}let f=r(n,["candidatesTokensDetails"]);if(f!=null){let g=f;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["responseTokensDetails"],g)}let h=r(n,["toolUsePromptTokensDetails"]);if(h!=null){let g=h;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["toolUsePromptTokensDetails"],g)}let m=r(n,["trafficType"]);return m!=null&&l(e,["trafficType"],m),e}p(Mu,"usageMetadataFromVertex");function Du(n){let e={},t=r(n,["data"]);if(t!=null&&l(e,["data"],t),r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(Du,"blobToMldev$1");function ku(n){let e={},t=r(n,["content"]);t!=null&&l(e,["content"],t);let i=r(n,["citationMetadata"]);i!=null&&l(e,["citationMetadata"],Lu(i));let o=r(n,["tokenCount"]);o!=null&&l(e,["tokenCount"],o);let s=r(n,["finishReason"]);s!=null&&l(e,["finishReason"],s);let a=r(n,["avgLogprobs"]);a!=null&&l(e,["avgLogprobs"],a);let c=r(n,["groundingMetadata"]);c!=null&&l(e,["groundingMetadata"],c);let d=r(n,["index"]);d!=null&&l(e,["index"],d);let u=r(n,["logprobsResult"]);u!=null&&l(e,["logprobsResult"],u);let f=r(n,["safetyRatings"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(g=>g)),l(e,["safetyRatings"],m)}let h=r(n,["urlContextMetadata"]);return h!=null&&l(e,["urlContextMetadata"],h),e}p(ku,"candidateFromMldev");function Lu(n){let e={},t=r(n,["citationSources"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>o)),l(e,["citations"],i)}return e}p(Lu,"citationMetadataFromMldev");function Uu(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["contents"]);if(o!=null){let s=Ie(o);Array.isArray(s)&&(s=s.map(a=>a)),l(t,["contents"],s)}return t}p(Uu,"computeTokensParametersToVertex");function Fu(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["tokensInfo"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>s)),l(e,["tokensInfo"],o)}return e}p(Fu,"computeTokensResponseFromVertex");function Bu(n){let e={},t=r(n,["values"]);t!=null&&l(e,["values"],t);let i=r(n,["statistics"]);return i!=null&&l(e,["statistics"],Vu(i)),e}p(Bu,"contentEmbeddingFromVertex");function Vu(n){let e={},t=r(n,["truncated"]);t!=null&&l(e,["truncated"],t);let i=r(n,["token_count"]);return i!=null&&l(e,["tokenCount"],i),e}p(Vu,"contentEmbeddingStatisticsFromVertex");function Hn(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>Qf(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(Hn,"contentToMldev$1");function Hu(n){let e={},t=r(n,["controlType"]);t!=null&&l(e,["controlType"],t);let i=r(n,["enableControlImageComputation"]);return i!=null&&l(e,["computeControl"],i),e}p(Hu,"controlReferenceConfigToVertex");function qu(n){let e={};if(r(n,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is not supported in Gemini API.");if(r(n,["tools"])!==void 0)throw new Error("tools parameter is not supported in Gemini API.");if(r(n,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is not supported in Gemini API.");return e}p(qu,"countTokensConfigToMldev");function Ou(n,e){let t={},i=r(n,["systemInstruction"]);e!==void 0&&i!=null&&l(e,["systemInstruction"],le(i));let o=r(n,["tools"]);if(e!==void 0&&o!=null){let a=o;Array.isArray(a)&&(a=a.map(c=>Oa(c))),l(e,["tools"],a)}let s=r(n,["generationConfig"]);return e!==void 0&&s!=null&&l(e,["generationConfig"],kf(s)),t}p(Ou,"countTokensConfigToVertex");function zu(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["contents"]);if(o!=null){let a=Ie(o);Array.isArray(a)&&(a=a.map(c=>Hn(c))),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&qu(s),t}p(zu,"countTokensParametersToMldev");function Ku(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["contents"]);if(o!=null){let a=Ie(o);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&Ou(s,t),t}p(Ku,"countTokensParametersToVertex");function Ju(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["totalTokens"]);i!=null&&l(e,["totalTokens"],i);let o=r(n,["cachedContentTokenCount"]);return o!=null&&l(e,["cachedContentTokenCount"],o),e}p(Ju,"countTokensResponseFromMldev");function Wu(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["totalTokens"]);return i!=null&&l(e,["totalTokens"],i),e}p(Wu,"countTokensResponseFromVertex");function Xu(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],U(n,i)),t}p(Xu,"deleteModelParametersToMldev");function Yu(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],U(n,i)),t}p(Yu,"deleteModelParametersToVertex");function Qu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Qu,"deleteModelResponseFromMldev");function Zu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Zu,"deleteModelResponseFromVertex");function ju(n,e){let t={},i=r(n,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=r(n,["negativePrompt"]);e!==void 0&&o!=null&&l(e,["parameters","negativePrompt"],o);let s=r(n,["numberOfImages"]);e!==void 0&&s!=null&&l(e,["parameters","sampleCount"],s);let a=r(n,["aspectRatio"]);e!==void 0&&a!=null&&l(e,["parameters","aspectRatio"],a);let c=r(n,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=r(n,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let u=r(n,["safetyFilterLevel"]);e!==void 0&&u!=null&&l(e,["parameters","safetySetting"],u);let f=r(n,["personGeneration"]);e!==void 0&&f!=null&&l(e,["parameters","personGeneration"],f);let h=r(n,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let m=r(n,["includeRaiReason"]);e!==void 0&&m!=null&&l(e,["parameters","includeRaiReason"],m);let g=r(n,["language"]);e!==void 0&&g!=null&&l(e,["parameters","language"],g);let b=r(n,["outputMimeType"]);e!==void 0&&b!=null&&l(e,["parameters","outputOptions","mimeType"],b);let E=r(n,["outputCompressionQuality"]);e!==void 0&&E!=null&&l(e,["parameters","outputOptions","compressionQuality"],E);let w=r(n,["addWatermark"]);e!==void 0&&w!=null&&l(e,["parameters","addWatermark"],w);let v=r(n,["labels"]);e!==void 0&&v!=null&&l(e,["labels"],v);let I=r(n,["editMode"]);e!==void 0&&I!=null&&l(e,["parameters","editMode"],I);let T=r(n,["baseSteps"]);return e!==void 0&&T!=null&&l(e,["parameters","editConfig","baseSteps"],T),t}p(ju,"editImageConfigToVertex");function ef(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["referenceImages"]);if(s!=null){let c=s;Array.isArray(c)&&(c=c.map(d=>ip(d))),l(t,["instances[0]","referenceImages"],c)}let a=r(e,["config"]);return a!=null&&ju(a,t),t}p(ef,"editImageParametersInternalToVertex");function tf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>qn(s))),l(e,["generatedImages"],o)}return e}p(tf,"editImageResponseFromVertex");function nf(n,e){let t={},i=r(n,["taskType"]);e!==void 0&&i!=null&&l(e,["requests[]","taskType"],i);let o=r(n,["title"]);e!==void 0&&o!=null&&l(e,["requests[]","title"],o);let s=r(n,["outputDimensionality"]);if(e!==void 0&&s!=null&&l(e,["requests[]","outputDimensionality"],s),r(n,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(r(n,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return t}p(nf,"embedContentConfigToMldev");function of(n,e){let t={},i=r(n,["taskType"]);e!==void 0&&i!=null&&l(e,["instances[]","task_type"],i);let o=r(n,["title"]);e!==void 0&&o!=null&&l(e,["instances[]","title"],o);let s=r(n,["outputDimensionality"]);e!==void 0&&s!=null&&l(e,["parameters","outputDimensionality"],s);let a=r(n,["mimeType"]);e!==void 0&&a!=null&&l(e,["instances[]","mimeType"],a);let c=r(n,["autoTruncate"]);return e!==void 0&&c!=null&&l(e,["parameters","autoTruncate"],c),t}p(of,"embedContentConfigToVertex");function sf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["contents"]);if(o!=null){let c=Ro(n,o);Array.isArray(c)&&(c=c.map(d=>d)),l(t,["requests[]","content"],c)}let s=r(e,["config"]);s!=null&&nf(s,t);let a=r(e,["model"]);return a!==void 0&&l(t,["requests[]","model"],U(n,a)),t}p(sf,"embedContentParametersToMldev");function rf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["contents"]);if(o!=null){let a=Ro(n,o);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["instances[]","content"],a)}let s=r(e,["config"]);return s!=null&&of(s,t),t}p(rf,"embedContentParametersToVertex");function af(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["embeddings"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["embeddings"],s)}let o=r(n,["metadata"]);return o!=null&&l(e,["metadata"],o),e}p(af,"embedContentResponseFromMldev");function lf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["predictions[]","embeddings"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>Bu(a))),l(e,["embeddings"],s)}let o=r(n,["metadata"]);return o!=null&&l(e,["metadata"],o),e}p(lf,"embedContentResponseFromVertex");function cf(n){let e={},t=r(n,["endpoint"]);t!=null&&l(e,["name"],t);let i=r(n,["deployedModelId"]);return i!=null&&l(e,["deployedModelId"],i),e}p(cf,"endpointFromVertex");function df(n){let e={};if(r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=r(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(df,"fileDataToMldev$1");function uf(n){let e={},t=r(n,["id"]);t!=null&&l(e,["id"],t);let i=r(n,["args"]);i!=null&&l(e,["args"],i);let o=r(n,["name"]);if(o!=null&&l(e,["name"],o),r(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(r(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}p(uf,"functionCallToMldev$1");function ff(n){let e={},t=r(n,["mode"]);t!=null&&l(e,["mode"],t);let i=r(n,["allowedFunctionNames"]);if(i!=null&&l(e,["allowedFunctionNames"],i),r(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}p(ff,"functionCallingConfigToMldev");function pf(n){let e={};if(r(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=r(n,["description"]);t!=null&&l(e,["description"],t);let i=r(n,["name"]);i!=null&&l(e,["name"],i);let o=r(n,["parameters"]);o!=null&&l(e,["parameters"],o);let s=r(n,["parametersJsonSchema"]);s!=null&&l(e,["parametersJsonSchema"],s);let a=r(n,["response"]);a!=null&&l(e,["response"],a);let c=r(n,["responseJsonSchema"]);return c!=null&&l(e,["responseJsonSchema"],c),e}p(pf,"functionDeclarationToVertex");function hf(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],Hn(le(o)));let s=r(e,["temperature"]);s!=null&&l(i,["temperature"],s);let a=r(e,["topP"]);a!=null&&l(i,["topP"],a);let c=r(e,["topK"]);c!=null&&l(i,["topK"],c);let d=r(e,["candidateCount"]);d!=null&&l(i,["candidateCount"],d);let u=r(e,["maxOutputTokens"]);u!=null&&l(i,["maxOutputTokens"],u);let f=r(e,["stopSequences"]);f!=null&&l(i,["stopSequences"],f);let h=r(e,["responseLogprobs"]);h!=null&&l(i,["responseLogprobs"],h);let m=r(e,["logprobs"]);m!=null&&l(i,["logprobs"],m);let g=r(e,["presencePenalty"]);g!=null&&l(i,["presencePenalty"],g);let b=r(e,["frequencyPenalty"]);b!=null&&l(i,["frequencyPenalty"],b);let E=r(e,["seed"]);E!=null&&l(i,["seed"],E);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],Go(v));let I=r(e,["responseJsonSchema"]);if(I!=null&&l(i,["responseJsonSchema"],I),r(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(r(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");let T=r(e,["safetySettings"]);if(t!==void 0&&T!=null){let V=T;Array.isArray(V)&&(V=V.map(we=>op(we))),l(t,["safetySettings"],V)}let S=r(e,["tools"]);if(t!==void 0&&S!=null){let V=Et(S);Array.isArray(V)&&(V=V.map(we=>up(yt(we)))),l(t,["tools"],V)}let N=r(e,["toolConfig"]);if(t!==void 0&&N!=null&&l(t,["toolConfig"],dp(N)),r(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let $=r(e,["cachedContent"]);t!==void 0&&$!=null&&l(t,["cachedContent"],ke(n,$));let A=r(e,["responseModalities"]);A!=null&&l(i,["responseModalities"],A);let P=r(e,["mediaResolution"]);P!=null&&l(i,["mediaResolution"],P);let x=r(e,["speechConfig"]);if(x!=null&&l(i,["speechConfig"],Mo(x)),r(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let k=r(e,["thinkingConfig"]);k!=null&&l(i,["thinkingConfig"],k);let O=r(e,["imageConfig"]);O!=null&&l(i,["imageConfig"],Vf(O));let j=r(e,["enableEnhancedCivicAnswers"]);return j!=null&&l(i,["enableEnhancedCivicAnswers"],j),i}p(hf,"generateContentConfigToMldev");function mf(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],le(o));let s=r(e,["temperature"]);s!=null&&l(i,["temperature"],s);let a=r(e,["topP"]);a!=null&&l(i,["topP"],a);let c=r(e,["topK"]);c!=null&&l(i,["topK"],c);let d=r(e,["candidateCount"]);d!=null&&l(i,["candidateCount"],d);let u=r(e,["maxOutputTokens"]);u!=null&&l(i,["maxOutputTokens"],u);let f=r(e,["stopSequences"]);f!=null&&l(i,["stopSequences"],f);let h=r(e,["responseLogprobs"]);h!=null&&l(i,["responseLogprobs"],h);let m=r(e,["logprobs"]);m!=null&&l(i,["logprobs"],m);let g=r(e,["presencePenalty"]);g!=null&&l(i,["presencePenalty"],g);let b=r(e,["frequencyPenalty"]);b!=null&&l(i,["frequencyPenalty"],b);let E=r(e,["seed"]);E!=null&&l(i,["seed"],E);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],Go(v));let I=r(e,["responseJsonSchema"]);I!=null&&l(i,["responseJsonSchema"],I);let T=r(e,["routingConfig"]);T!=null&&l(i,["routingConfig"],T);let S=r(e,["modelSelectionConfig"]);S!=null&&l(i,["modelConfig"],S);let N=r(e,["safetySettings"]);if(t!==void 0&&N!=null){let Ce=N;Array.isArray(Ce)&&(Ce=Ce.map(ci=>ci)),l(t,["safetySettings"],Ce)}let $=r(e,["tools"]);if(t!==void 0&&$!=null){let Ce=Et($);Array.isArray(Ce)&&(Ce=Ce.map(ci=>Oa(yt(ci)))),l(t,["tools"],Ce)}let A=r(e,["toolConfig"]);t!==void 0&&A!=null&&l(t,["toolConfig"],A);let P=r(e,["labels"]);t!==void 0&&P!=null&&l(t,["labels"],P);let x=r(e,["cachedContent"]);t!==void 0&&x!=null&&l(t,["cachedContent"],ke(n,x));let k=r(e,["responseModalities"]);k!=null&&l(i,["responseModalities"],k);let O=r(e,["mediaResolution"]);O!=null&&l(i,["mediaResolution"],O);let j=r(e,["speechConfig"]);j!=null&&l(i,["speechConfig"],qa(Mo(j)));let V=r(e,["audioTimestamp"]);V!=null&&l(i,["audioTimestamp"],V);let we=r(e,["thinkingConfig"]);we!=null&&l(i,["thinkingConfig"],we);let Lt=r(e,["imageConfig"]);if(Lt!=null&&l(i,["imageConfig"],Hf(Lt)),r(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return i}p(mf,"generateContentConfigToVertex");function ra(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["contents"]);if(o!=null){let a=Ie(o);Array.isArray(a)&&(a=a.map(c=>Hn(c))),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&l(t,["generationConfig"],hf(n,s,t)),t}p(ra,"generateContentParametersToMldev");function aa(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["contents"]);if(o!=null){let a=Ie(o);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&l(t,["generationConfig"],mf(n,s,t)),t}p(aa,"generateContentParametersToVertex");function la(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["candidates"]);if(i!=null){let d=i;Array.isArray(d)&&(d=d.map(u=>ku(u))),l(e,["candidates"],d)}let o=r(n,["modelVersion"]);o!=null&&l(e,["modelVersion"],o);let s=r(n,["promptFeedback"]);s!=null&&l(e,["promptFeedback"],s);let a=r(n,["responseId"]);a!=null&&l(e,["responseId"],a);let c=r(n,["usageMetadata"]);return c!=null&&l(e,["usageMetadata"],c),e}p(la,"generateContentResponseFromMldev");function ca(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["candidates"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(f=>f)),l(e,["candidates"],u)}let o=r(n,["createTime"]);o!=null&&l(e,["createTime"],o);let s=r(n,["modelVersion"]);s!=null&&l(e,["modelVersion"],s);let a=r(n,["promptFeedback"]);a!=null&&l(e,["promptFeedback"],a);let c=r(n,["responseId"]);c!=null&&l(e,["responseId"],c);let d=r(n,["usageMetadata"]);return d!=null&&l(e,["usageMetadata"],d),e}p(ca,"generateContentResponseFromVertex");function gf(n,e){let t={};if(r(n,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(r(n,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is not supported in Gemini API.");let i=r(n,["numberOfImages"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=r(n,["aspectRatio"]);e!==void 0&&o!=null&&l(e,["parameters","aspectRatio"],o);let s=r(n,["guidanceScale"]);if(e!==void 0&&s!=null&&l(e,["parameters","guidanceScale"],s),r(n,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");let a=r(n,["safetyFilterLevel"]);e!==void 0&&a!=null&&l(e,["parameters","safetySetting"],a);let c=r(n,["personGeneration"]);e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c);let d=r(n,["includeSafetyAttributes"]);e!==void 0&&d!=null&&l(e,["parameters","includeSafetyAttributes"],d);let u=r(n,["includeRaiReason"]);e!==void 0&&u!=null&&l(e,["parameters","includeRaiReason"],u);let f=r(n,["language"]);e!==void 0&&f!=null&&l(e,["parameters","language"],f);let h=r(n,["outputMimeType"]);e!==void 0&&h!=null&&l(e,["parameters","outputOptions","mimeType"],h);let m=r(n,["outputCompressionQuality"]);if(e!==void 0&&m!=null&&l(e,["parameters","outputOptions","compressionQuality"],m),r(n,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is not supported in Gemini API.");if(r(n,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let g=r(n,["imageSize"]);if(e!==void 0&&g!=null&&l(e,["parameters","sampleImageSize"],g),r(n,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is not supported in Gemini API.");return t}p(gf,"generateImagesConfigToMldev");function bf(n,e){let t={},i=r(n,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=r(n,["negativePrompt"]);e!==void 0&&o!=null&&l(e,["parameters","negativePrompt"],o);let s=r(n,["numberOfImages"]);e!==void 0&&s!=null&&l(e,["parameters","sampleCount"],s);let a=r(n,["aspectRatio"]);e!==void 0&&a!=null&&l(e,["parameters","aspectRatio"],a);let c=r(n,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=r(n,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let u=r(n,["safetyFilterLevel"]);e!==void 0&&u!=null&&l(e,["parameters","safetySetting"],u);let f=r(n,["personGeneration"]);e!==void 0&&f!=null&&l(e,["parameters","personGeneration"],f);let h=r(n,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let m=r(n,["includeRaiReason"]);e!==void 0&&m!=null&&l(e,["parameters","includeRaiReason"],m);let g=r(n,["language"]);e!==void 0&&g!=null&&l(e,["parameters","language"],g);let b=r(n,["outputMimeType"]);e!==void 0&&b!=null&&l(e,["parameters","outputOptions","mimeType"],b);let E=r(n,["outputCompressionQuality"]);e!==void 0&&E!=null&&l(e,["parameters","outputOptions","compressionQuality"],E);let w=r(n,["addWatermark"]);e!==void 0&&w!=null&&l(e,["parameters","addWatermark"],w);let v=r(n,["labels"]);e!==void 0&&v!=null&&l(e,["labels"],v);let I=r(n,["imageSize"]);e!==void 0&&I!=null&&l(e,["parameters","sampleImageSize"],I);let T=r(n,["enhancePrompt"]);return e!==void 0&&T!=null&&l(e,["parameters","enhancePrompt"],T),t}p(bf,"generateImagesConfigToVertex");function yf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["config"]);return s!=null&&gf(s,t),t}p(yf,"generateImagesParametersToMldev");function Ef(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["config"]);return s!=null&&bf(s,t),t}p(Ef,"generateImagesParametersToVertex");function wf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>Rf(a))),l(e,["generatedImages"],s)}let o=r(n,["positivePromptSafetyAttributes"]);return o!=null&&l(e,["positivePromptSafetyAttributes"],Va(o)),e}p(wf,"generateImagesResponseFromMldev");function vf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>qn(a))),l(e,["generatedImages"],s)}let o=r(n,["positivePromptSafetyAttributes"]);return o!=null&&l(e,["positivePromptSafetyAttributes"],Ha(o)),e}p(vf,"generateImagesResponseFromVertex");function If(n,e){let t={},i=r(n,["numberOfVideos"]);if(e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i),r(n,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(r(n,["fps"])!==void 0)throw new Error("fps parameter is not supported in Gemini API.");let o=r(n,["durationSeconds"]);if(e!==void 0&&o!=null&&l(e,["parameters","durationSeconds"],o),r(n,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");let s=r(n,["aspectRatio"]);e!==void 0&&s!=null&&l(e,["parameters","aspectRatio"],s);let a=r(n,["resolution"]);e!==void 0&&a!=null&&l(e,["parameters","resolution"],a);let c=r(n,["personGeneration"]);if(e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c),r(n,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is not supported in Gemini API.");let d=r(n,["negativePrompt"]);e!==void 0&&d!=null&&l(e,["parameters","negativePrompt"],d);let u=r(n,["enhancePrompt"]);if(e!==void 0&&u!=null&&l(e,["parameters","enhancePrompt"],u),r(n,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is not supported in Gemini API.");let f=r(n,["lastFrame"]);e!==void 0&&f!=null&&l(e,["instances[0]","lastFrame"],On(f));let h=r(n,["referenceImages"]);if(e!==void 0&&h!=null){let m=h;Array.isArray(m)&&(m=m.map(g=>Cp(g))),l(e,["instances[0]","referenceImages"],m)}if(r(n,["mask"])!==void 0)throw new Error("mask parameter is not supported in Gemini API.");if(r(n,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is not supported in Gemini API.");return t}p(If,"generateVideosConfigToMldev");function Tf(n,e){let t={},i=r(n,["numberOfVideos"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=r(n,["outputGcsUri"]);e!==void 0&&o!=null&&l(e,["parameters","storageUri"],o);let s=r(n,["fps"]);e!==void 0&&s!=null&&l(e,["parameters","fps"],s);let a=r(n,["durationSeconds"]);e!==void 0&&a!=null&&l(e,["parameters","durationSeconds"],a);let c=r(n,["seed"]);e!==void 0&&c!=null&&l(e,["parameters","seed"],c);let d=r(n,["aspectRatio"]);e!==void 0&&d!=null&&l(e,["parameters","aspectRatio"],d);let u=r(n,["resolution"]);e!==void 0&&u!=null&&l(e,["parameters","resolution"],u);let f=r(n,["personGeneration"]);e!==void 0&&f!=null&&l(e,["parameters","personGeneration"],f);let h=r(n,["pubsubTopic"]);e!==void 0&&h!=null&&l(e,["parameters","pubsubTopic"],h);let m=r(n,["negativePrompt"]);e!==void 0&&m!=null&&l(e,["parameters","negativePrompt"],m);let g=r(n,["enhancePrompt"]);e!==void 0&&g!=null&&l(e,["parameters","enhancePrompt"],g);let b=r(n,["generateAudio"]);e!==void 0&&b!=null&&l(e,["parameters","generateAudio"],b);let E=r(n,["lastFrame"]);e!==void 0&&E!=null&&l(e,["instances[0]","lastFrame"],$e(E));let w=r(n,["referenceImages"]);if(e!==void 0&&w!=null){let T=w;Array.isArray(T)&&(T=T.map(S=>_p(S))),l(e,["instances[0]","referenceImages"],T)}let v=r(n,["mask"]);e!==void 0&&v!=null&&l(e,["instances[0]","mask"],Tp(v));let I=r(n,["compressionQuality"]);return e!==void 0&&I!=null&&l(e,["parameters","compressionQuality"],I),t}p(Tf,"generateVideosConfigToVertex");function Cf(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response","generateVideoResponse"]);return a!=null&&l(e,["response"],xf(a)),e}p(Cf,"generateVideosOperationFromMldev");function _f(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response"]);return a!=null&&l(e,["response"],Nf(a)),e}p(_f,"generateVideosOperationFromVertex");function Sf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["image"]);s!=null&&l(t,["instances[0]","image"],On(s));let a=r(e,["video"]);a!=null&&l(t,["instances[0]","video"],za(a));let c=r(e,["source"]);c!=null&&$f(c,t);let d=r(e,["config"]);return d!=null&&If(d,t),t}p(Sf,"generateVideosParametersToMldev");function Af(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["image"]);s!=null&&l(t,["instances[0]","image"],$e(s));let a=r(e,["video"]);a!=null&&l(t,["instances[0]","video"],Ka(a));let c=r(e,["source"]);c!=null&&Pf(c,t);let d=r(e,["config"]);return d!=null&&Tf(d,t),t}p(Af,"generateVideosParametersToVertex");function xf(n){let e={},t=r(n,["generatedSamples"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>Mf(a))),l(e,["generatedVideos"],s)}let i=r(n,["raiMediaFilteredCount"]);i!=null&&l(e,["raiMediaFilteredCount"],i);let o=r(n,["raiMediaFilteredReasons"]);return o!=null&&l(e,["raiMediaFilteredReasons"],o),e}p(xf,"generateVideosResponseFromMldev");function Nf(n){let e={},t=r(n,["videos"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>Df(a))),l(e,["generatedVideos"],s)}let i=r(n,["raiMediaFilteredCount"]);i!=null&&l(e,["raiMediaFilteredCount"],i);let o=r(n,["raiMediaFilteredReasons"]);return o!=null&&l(e,["raiMediaFilteredReasons"],o),e}p(Nf,"generateVideosResponseFromVertex");function $f(n,e){let t={},i=r(n,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=r(n,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],On(o));let s=r(n,["video"]);return e!==void 0&&s!=null&&l(e,["instances[0]","video"],za(s)),t}p($f,"generateVideosSourceToMldev");function Pf(n,e){let t={},i=r(n,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=r(n,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],$e(o));let s=r(n,["video"]);return e!==void 0&&s!=null&&l(e,["instances[0]","video"],Ka(s)),t}p(Pf,"generateVideosSourceToVertex");function Rf(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["image"],qf(t));let i=r(n,["raiFilteredReason"]);i!=null&&l(e,["raiFilteredReason"],i);let o=r(n,["_self"]);return o!=null&&l(e,["safetyAttributes"],Va(o)),e}p(Rf,"generatedImageFromMldev");function qn(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["image"],Ba(t));let i=r(n,["raiFilteredReason"]);i!=null&&l(e,["raiFilteredReason"],i);let o=r(n,["_self"]);o!=null&&l(e,["safetyAttributes"],Ha(o));let s=r(n,["prompt"]);return s!=null&&l(e,["enhancedPrompt"],s),e}p(qn,"generatedImageFromVertex");function Gf(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["mask"],Ba(t));let i=r(n,["labels"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>s)),l(e,["labels"],o)}return e}p(Gf,"generatedImageMaskFromVertex");function Mf(n){let e={},t=r(n,["video"]);return t!=null&&l(e,["video"],vp(t)),e}p(Mf,"generatedVideoFromMldev");function Df(n){let e={},t=r(n,["_self"]);return t!=null&&l(e,["video"],Ip(t)),e}p(Df,"generatedVideoFromVertex");function kf(n){let e={},t=r(n,["modelSelectionConfig"]);t!=null&&l(e,["modelConfig"],t);let i=r(n,["responseJsonSchema"]);i!=null&&l(e,["responseJsonSchema"],i);let o=r(n,["audioTimestamp"]);o!=null&&l(e,["audioTimestamp"],o);let s=r(n,["candidateCount"]);s!=null&&l(e,["candidateCount"],s);let a=r(n,["enableAffectiveDialog"]);a!=null&&l(e,["enableAffectiveDialog"],a);let c=r(n,["frequencyPenalty"]);c!=null&&l(e,["frequencyPenalty"],c);let d=r(n,["logprobs"]);d!=null&&l(e,["logprobs"],d);let u=r(n,["maxOutputTokens"]);u!=null&&l(e,["maxOutputTokens"],u);let f=r(n,["mediaResolution"]);f!=null&&l(e,["mediaResolution"],f);let h=r(n,["presencePenalty"]);h!=null&&l(e,["presencePenalty"],h);let m=r(n,["responseLogprobs"]);m!=null&&l(e,["responseLogprobs"],m);let g=r(n,["responseMimeType"]);g!=null&&l(e,["responseMimeType"],g);let b=r(n,["responseModalities"]);b!=null&&l(e,["responseModalities"],b);let E=r(n,["responseSchema"]);E!=null&&l(e,["responseSchema"],E);let w=r(n,["routingConfig"]);w!=null&&l(e,["routingConfig"],w);let v=r(n,["seed"]);v!=null&&l(e,["seed"],v);let I=r(n,["speechConfig"]);I!=null&&l(e,["speechConfig"],qa(I));let T=r(n,["stopSequences"]);T!=null&&l(e,["stopSequences"],T);let S=r(n,["temperature"]);S!=null&&l(e,["temperature"],S);let N=r(n,["thinkingConfig"]);N!=null&&l(e,["thinkingConfig"],N);let $=r(n,["topK"]);$!=null&&l(e,["topK"],$);let A=r(n,["topP"]);if(A!=null&&l(e,["topP"],A),r(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}p(kf,"generationConfigToVertex");function Lf(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],U(n,i)),t}p(Lf,"getModelParametersToMldev");function Uf(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],U(n,i)),t}p(Uf,"getModelParametersToVertex");function Ff(n){let e={};if(r(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=r(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}p(Ff,"googleMapsToMldev$1");function Bf(n){let e={};if(r(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(r(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=r(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}p(Bf,"googleSearchToMldev$1");function Vf(n){let e={},t=r(n,["aspectRatio"]);t!=null&&l(e,["aspectRatio"],t);let i=r(n,["imageSize"]);if(i!=null&&l(e,["imageSize"],i),r(n,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(r(n,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}p(Vf,"imageConfigToMldev");function Hf(n){let e={},t=r(n,["aspectRatio"]);t!=null&&l(e,["aspectRatio"],t);let i=r(n,["imageSize"]);i!=null&&l(e,["imageSize"],i);let o=r(n,["outputMimeType"]);o!=null&&l(e,["imageOutputOptions","mimeType"],o);let s=r(n,["outputCompressionQuality"]);return s!=null&&l(e,["imageOutputOptions","compressionQuality"],s),e}p(Hf,"imageConfigToVertex");function qf(n){let e={},t=r(n,["bytesBase64Encoded"]);t!=null&&l(e,["imageBytes"],Be(t));let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(qf,"imageFromMldev");function Ba(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["imageBytes"],Be(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(Ba,"imageFromVertex");function On(n){let e={};if(r(n,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");let t=r(n,["imageBytes"]);t!=null&&l(e,["bytesBase64Encoded"],Be(t));let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(On,"imageToMldev");function $e(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["imageBytes"]);i!=null&&l(e,["bytesBase64Encoded"],Be(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p($e,"imageToVertex");function Of(n,e,t){let i={},o=r(e,["pageSize"]);t!==void 0&&o!=null&&l(t,["_query","pageSize"],o);let s=r(e,["pageToken"]);t!==void 0&&s!=null&&l(t,["_query","pageToken"],s);let a=r(e,["filter"]);t!==void 0&&a!=null&&l(t,["_query","filter"],a);let c=r(e,["queryBase"]);return t!==void 0&&c!=null&&l(t,["_url","models_url"],Ra(n,c)),i}p(Of,"listModelsConfigToMldev");function zf(n,e,t){let i={},o=r(e,["pageSize"]);t!==void 0&&o!=null&&l(t,["_query","pageSize"],o);let s=r(e,["pageToken"]);t!==void 0&&s!=null&&l(t,["_query","pageToken"],s);let a=r(e,["filter"]);t!==void 0&&a!=null&&l(t,["_query","filter"],a);let c=r(e,["queryBase"]);return t!==void 0&&c!=null&&l(t,["_url","models_url"],Ra(n,c)),i}p(zf,"listModelsConfigToVertex");function Kf(n,e){let t={},i=r(e,["config"]);return i!=null&&Of(n,i,t),t}p(Kf,"listModelsParametersToMldev");function Jf(n,e){let t={},i=r(e,["config"]);return i!=null&&zf(n,i,t),t}p(Jf,"listModelsParametersToVertex");function Wf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["_self"]);if(o!=null){let s=Ga(o);Array.isArray(s)&&(s=s.map(a=>no(a))),l(e,["models"],s)}return e}p(Wf,"listModelsResponseFromMldev");function Xf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["_self"]);if(o!=null){let s=Ga(o);Array.isArray(s)&&(s=s.map(a=>io(a))),l(e,["models"],s)}return e}p(Xf,"listModelsResponseFromVertex");function Yf(n){let e={},t=r(n,["maskMode"]);t!=null&&l(e,["maskMode"],t);let i=r(n,["segmentationClasses"]);i!=null&&l(e,["maskClasses"],i);let o=r(n,["maskDilation"]);return o!=null&&l(e,["dilation"],o),e}p(Yf,"maskReferenceConfigToVertex");function no(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["displayName"]);i!=null&&l(e,["displayName"],i);let o=r(n,["description"]);o!=null&&l(e,["description"],o);let s=r(n,["version"]);s!=null&&l(e,["version"],s);let a=r(n,["_self"]);a!=null&&l(e,["tunedModelInfo"],fp(a));let c=r(n,["inputTokenLimit"]);c!=null&&l(e,["inputTokenLimit"],c);let d=r(n,["outputTokenLimit"]);d!=null&&l(e,["outputTokenLimit"],d);let u=r(n,["supportedGenerationMethods"]);u!=null&&l(e,["supportedActions"],u);let f=r(n,["temperature"]);f!=null&&l(e,["temperature"],f);let h=r(n,["maxTemperature"]);h!=null&&l(e,["maxTemperature"],h);let m=r(n,["topP"]);m!=null&&l(e,["topP"],m);let g=r(n,["topK"]);g!=null&&l(e,["topK"],g);let b=r(n,["thinking"]);return b!=null&&l(e,["thinking"],b),e}p(no,"modelFromMldev");function io(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["displayName"]);i!=null&&l(e,["displayName"],i);let o=r(n,["description"]);o!=null&&l(e,["description"],o);let s=r(n,["versionId"]);s!=null&&l(e,["version"],s);let a=r(n,["deployedModels"]);if(a!=null){let h=a;Array.isArray(h)&&(h=h.map(m=>cf(m))),l(e,["endpoints"],h)}let c=r(n,["labels"]);c!=null&&l(e,["labels"],c);let d=r(n,["_self"]);d!=null&&l(e,["tunedModelInfo"],pp(d));let u=r(n,["defaultCheckpointId"]);u!=null&&l(e,["defaultCheckpointId"],u);let f=r(n,["checkpoints"]);if(f!=null){let h=f;Array.isArray(h)&&(h=h.map(m=>m)),l(e,["checkpoints"],h)}return e}p(io,"modelFromVertex");function Qf(n){let e={},t=r(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let i=r(n,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=r(n,["executableCode"]);o!=null&&l(e,["executableCode"],o);let s=r(n,["fileData"]);s!=null&&l(e,["fileData"],df(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],uf(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],Du(d));let u=r(n,["text"]);u!=null&&l(e,["text"],u);let f=r(n,["thought"]);f!=null&&l(e,["thought"],f);let h=r(n,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=r(n,["videoMetadata"]);return m!=null&&l(e,["videoMetadata"],m),e}p(Qf,"partToMldev$1");function Zf(n){let e={},t=r(n,["productImage"]);return t!=null&&l(e,["image"],$e(t)),e}p(Zf,"productImageToVertex");function jf(n,e){let t={},i=r(n,["numberOfImages"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=r(n,["baseSteps"]);e!==void 0&&o!=null&&l(e,["parameters","baseSteps"],o);let s=r(n,["outputGcsUri"]);e!==void 0&&s!=null&&l(e,["parameters","storageUri"],s);let a=r(n,["seed"]);e!==void 0&&a!=null&&l(e,["parameters","seed"],a);let c=r(n,["safetyFilterLevel"]);e!==void 0&&c!=null&&l(e,["parameters","safetySetting"],c);let d=r(n,["personGeneration"]);e!==void 0&&d!=null&&l(e,["parameters","personGeneration"],d);let u=r(n,["addWatermark"]);e!==void 0&&u!=null&&l(e,["parameters","addWatermark"],u);let f=r(n,["outputMimeType"]);e!==void 0&&f!=null&&l(e,["parameters","outputOptions","mimeType"],f);let h=r(n,["outputCompressionQuality"]);e!==void 0&&h!=null&&l(e,["parameters","outputOptions","compressionQuality"],h);let m=r(n,["enhancePrompt"]);e!==void 0&&m!=null&&l(e,["parameters","enhancePrompt"],m);let g=r(n,["labels"]);return e!==void 0&&g!=null&&l(e,["labels"],g),t}p(jf,"recontextImageConfigToVertex");function ep(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["source"]);o!=null&&np(o,t);let s=r(e,["config"]);return s!=null&&jf(s,t),t}p(ep,"recontextImageParametersToVertex");function tp(n){let e={},t=r(n,["predictions"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>qn(o))),l(e,["generatedImages"],i)}return e}p(tp,"recontextImageResponseFromVertex");function np(n,e){let t={},i=r(n,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=r(n,["personImage"]);e!==void 0&&o!=null&&l(e,["instances[0]","personImage","image"],$e(o));let s=r(n,["productImages"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>Zf(c))),l(e,["instances[0]","productImages"],a)}return t}p(np,"recontextImageSourceToVertex");function ip(n){let e={},t=r(n,["referenceImage"]);t!=null&&l(e,["referenceImage"],$e(t));let i=r(n,["referenceId"]);i!=null&&l(e,["referenceId"],i);let o=r(n,["referenceType"]);o!=null&&l(e,["referenceType"],o);let s=r(n,["maskImageConfig"]);s!=null&&l(e,["maskImageConfig"],Yf(s));let a=r(n,["controlImageConfig"]);a!=null&&l(e,["controlImageConfig"],Hu(a));let c=r(n,["styleImageConfig"]);c!=null&&l(e,["styleImageConfig"],c);let d=r(n,["subjectImageConfig"]);return d!=null&&l(e,["subjectImageConfig"],d),e}p(ip,"referenceImageAPIInternalToVertex");function Va(n){let e={},t=r(n,["safetyAttributes","categories"]);t!=null&&l(e,["categories"],t);let i=r(n,["safetyAttributes","scores"]);i!=null&&l(e,["scores"],i);let o=r(n,["contentType"]);return o!=null&&l(e,["contentType"],o),e}p(Va,"safetyAttributesFromMldev");function Ha(n){let e={},t=r(n,["safetyAttributes","categories"]);t!=null&&l(e,["categories"],t);let i=r(n,["safetyAttributes","scores"]);i!=null&&l(e,["scores"],i);let o=r(n,["contentType"]);return o!=null&&l(e,["contentType"],o),e}p(Ha,"safetyAttributesFromVertex");function op(n){let e={},t=r(n,["category"]);if(t!=null&&l(e,["category"],t),r(n,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let i=r(n,["threshold"]);return i!=null&&l(e,["threshold"],i),e}p(op,"safetySettingToMldev");function sp(n){let e={},t=r(n,["image"]);return t!=null&&l(e,["image"],$e(t)),e}p(sp,"scribbleImageToVertex");function rp(n,e){let t={},i=r(n,["mode"]);e!==void 0&&i!=null&&l(e,["parameters","mode"],i);let o=r(n,["maxPredictions"]);e!==void 0&&o!=null&&l(e,["parameters","maxPredictions"],o);let s=r(n,["confidenceThreshold"]);e!==void 0&&s!=null&&l(e,["parameters","confidenceThreshold"],s);let a=r(n,["maskDilation"]);e!==void 0&&a!=null&&l(e,["parameters","maskDilation"],a);let c=r(n,["binaryColorThreshold"]);e!==void 0&&c!=null&&l(e,["parameters","binaryColorThreshold"],c);let d=r(n,["labels"]);return e!==void 0&&d!=null&&l(e,["labels"],d),t}p(rp,"segmentImageConfigToVertex");function ap(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["source"]);o!=null&&cp(o,t);let s=r(e,["config"]);return s!=null&&rp(s,t),t}p(ap,"segmentImageParametersToVertex");function lp(n){let e={},t=r(n,["predictions"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>Gf(o))),l(e,["generatedMasks"],i)}return e}p(lp,"segmentImageResponseFromVertex");function cp(n,e){let t={},i=r(n,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=r(n,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],$e(o));let s=r(n,["scribbleImage"]);return e!==void 0&&s!=null&&l(e,["instances[0]","scribble"],sp(s)),t}p(cp,"segmentImageSourceToVertex");function qa(n){let e={},t=r(n,["voiceConfig"]);t!=null&&l(e,["voiceConfig"],t);let i=r(n,["languageCode"]);if(i!=null&&l(e,["languageCode"],i),r(n,["multiSpeakerVoiceConfig"])!==void 0)throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");return e}p(qa,"speechConfigToVertex");function dp(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],ff(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(dp,"toolConfigToMldev");function up(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let f=t;Array.isArray(f)&&(f=f.map(h=>h)),l(e,["functionDeclarations"],f)}if(r(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let i=r(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let o=r(n,["computerUse"]);o!=null&&l(e,["computerUse"],o);let s=r(n,["fileSearch"]);s!=null&&l(e,["fileSearch"],s);let a=r(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),r(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],Ff(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],Bf(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(up,"toolToMldev$1");function Oa(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>pf(m))),l(e,["functionDeclarations"],h)}let i=r(n,["retrieval"]);i!=null&&l(e,["retrieval"],i);let o=r(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let s=r(n,["computerUse"]);if(s!=null&&l(e,["computerUse"],s),r(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let a=r(n,["codeExecution"]);a!=null&&l(e,["codeExecution"],a);let c=r(n,["enterpriseWebSearch"]);c!=null&&l(e,["enterpriseWebSearch"],c);let d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],d);let u=r(n,["googleSearch"]);u!=null&&l(e,["googleSearch"],u);let f=r(n,["urlContext"]);return f!=null&&l(e,["urlContext"],f),e}p(Oa,"toolToVertex");function fp(n){let e={},t=r(n,["baseModel"]);t!=null&&l(e,["baseModel"],t);let i=r(n,["createTime"]);i!=null&&l(e,["createTime"],i);let o=r(n,["updateTime"]);return o!=null&&l(e,["updateTime"],o),e}p(fp,"tunedModelInfoFromMldev");function pp(n){let e={},t=r(n,["labels","google-vertex-llm-tuning-base-model-id"]);t!=null&&l(e,["baseModel"],t);let i=r(n,["createTime"]);i!=null&&l(e,["createTime"],i);let o=r(n,["updateTime"]);return o!=null&&l(e,["updateTime"],o),e}p(pp,"tunedModelInfoFromVertex");function hp(n,e){let t={},i=r(n,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=r(n,["description"]);e!==void 0&&o!=null&&l(e,["description"],o);let s=r(n,["defaultCheckpointId"]);return e!==void 0&&s!=null&&l(e,["defaultCheckpointId"],s),t}p(hp,"updateModelConfigToMldev");function mp(n,e){let t={},i=r(n,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=r(n,["description"]);e!==void 0&&o!=null&&l(e,["description"],o);let s=r(n,["defaultCheckpointId"]);return e!==void 0&&s!=null&&l(e,["defaultCheckpointId"],s),t}p(mp,"updateModelConfigToVertex");function gp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","name"],U(n,i));let o=r(e,["config"]);return o!=null&&hp(o,t),t}p(gp,"updateModelParametersToMldev");function bp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["config"]);return o!=null&&mp(o,t),t}p(bp,"updateModelParametersToVertex");function yp(n,e){let t={},i=r(n,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=r(n,["safetyFilterLevel"]);e!==void 0&&o!=null&&l(e,["parameters","safetySetting"],o);let s=r(n,["personGeneration"]);e!==void 0&&s!=null&&l(e,["parameters","personGeneration"],s);let a=r(n,["includeRaiReason"]);e!==void 0&&a!=null&&l(e,["parameters","includeRaiReason"],a);let c=r(n,["outputMimeType"]);e!==void 0&&c!=null&&l(e,["parameters","outputOptions","mimeType"],c);let d=r(n,["outputCompressionQuality"]);e!==void 0&&d!=null&&l(e,["parameters","outputOptions","compressionQuality"],d);let u=r(n,["enhanceInputImage"]);e!==void 0&&u!=null&&l(e,["parameters","upscaleConfig","enhanceInputImage"],u);let f=r(n,["imagePreservationFactor"]);e!==void 0&&f!=null&&l(e,["parameters","upscaleConfig","imagePreservationFactor"],f);let h=r(n,["labels"]);e!==void 0&&h!=null&&l(e,["labels"],h);let m=r(n,["numberOfImages"]);e!==void 0&&m!=null&&l(e,["parameters","sampleCount"],m);let g=r(n,["mode"]);return e!==void 0&&g!=null&&l(e,["parameters","mode"],g),t}p(yp,"upscaleImageAPIConfigInternalToVertex");function Ep(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],U(n,i));let o=r(e,["image"]);o!=null&&l(t,["instances[0]","image"],$e(o));let s=r(e,["upscaleFactor"]);s!=null&&l(t,["parameters","upscaleConfig","upscaleFactor"],s);let a=r(e,["config"]);return a!=null&&yp(a,t),t}p(Ep,"upscaleImageAPIParametersInternalToVertex");function wp(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>qn(s))),l(e,["generatedImages"],o)}return e}p(wp,"upscaleImageResponseFromVertex");function vp(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["encodedVideo"]);i!=null&&l(e,["videoBytes"],Be(i));let o=r(n,["encoding"]);return o!=null&&l(e,["mimeType"],o),e}p(vp,"videoFromMldev");function Ip(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["uri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["videoBytes"],Be(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(Ip,"videoFromVertex");function Tp(n){let e={},t=r(n,["image"]);t!=null&&l(e,["_self"],$e(t));let i=r(n,["maskMode"]);return i!=null&&l(e,["maskMode"],i),e}p(Tp,"videoGenerationMaskToVertex");function Cp(n){let e={},t=r(n,["image"]);t!=null&&l(e,["image"],On(t));let i=r(n,["referenceType"]);return i!=null&&l(e,["referenceType"],i),e}p(Cp,"videoGenerationReferenceImageToMldev");function _p(n){let e={},t=r(n,["image"]);t!=null&&l(e,["image"],$e(t));let i=r(n,["referenceType"]);return i!=null&&l(e,["referenceType"],i),e}p(_p,"videoGenerationReferenceImageToVertex");function za(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["videoBytes"]);i!=null&&l(e,["encodedVideo"],Be(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["encoding"],o),e}p(za,"videoToMldev");function Ka(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["videoBytes"]);i!=null&&l(e,["bytesBase64Encoded"],Be(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(Ka,"videoToVertex");function Sp(n,e){let t={},i=r(n,["displayName"]);return e!==void 0&&i!=null&&l(e,["displayName"],i),t}p(Sp,"createFileSearchStoreConfigToMldev");function Ap(n){let e={},t=r(n,["config"]);return t!=null&&Sp(t,e),e}p(Ap,"createFileSearchStoreParametersToMldev");function xp(n,e){let t={},i=r(n,["force"]);return e!==void 0&&i!=null&&l(e,["_query","force"],i),t}p(xp,"deleteFileSearchStoreConfigToMldev");function Np(n){let e={},t=r(n,["name"]);t!=null&&l(e,["_url","name"],t);let i=r(n,["config"]);return i!=null&&xp(i,e),e}p(Np,"deleteFileSearchStoreParametersToMldev");function $p(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","name"],t),e}p($p,"getFileSearchStoreParametersToMldev");function Pp(n,e){let t={},i=r(n,["customMetadata"]);if(e!==void 0&&i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["customMetadata"],s)}let o=r(n,["chunkingConfig"]);return e!==void 0&&o!=null&&l(e,["chunkingConfig"],o),t}p(Pp,"importFileConfigToMldev");function Rp(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response"]);return a!=null&&l(e,["response"],Mp(a)),e}p(Rp,"importFileOperationFromMldev");function Gp(n){let e={},t=r(n,["fileSearchStoreName"]);t!=null&&l(e,["_url","file_search_store_name"],t);let i=r(n,["fileName"]);i!=null&&l(e,["fileName"],i);let o=r(n,["config"]);return o!=null&&Pp(o,e),e}p(Gp,"importFileParametersToMldev");function Mp(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["parent"]);i!=null&&l(e,["parent"],i);let o=r(n,["documentName"]);return o!=null&&l(e,["documentName"],o),e}p(Mp,"importFileResponseFromMldev");function Dp(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),t}p(Dp,"listFileSearchStoresConfigToMldev");function kp(n){let e={},t=r(n,["config"]);return t!=null&&Dp(t,e),e}p(kp,"listFileSearchStoresParametersToMldev");function Lp(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["fileSearchStores"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["fileSearchStores"],s)}return e}p(Lp,"listFileSearchStoresResponseFromMldev");function Ja(n,e){let t={},i=r(n,["mimeType"]);e!==void 0&&i!=null&&l(e,["mimeType"],i);let o=r(n,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let s=r(n,["customMetadata"]);if(e!==void 0&&s!=null){let c=s;Array.isArray(c)&&(c=c.map(d=>d)),l(e,["customMetadata"],c)}let a=r(n,["chunkingConfig"]);return e!==void 0&&a!=null&&l(e,["chunkingConfig"],a),t}p(Ja,"uploadToFileSearchStoreConfigToMldev");function Up(n){let e={},t=r(n,["fileSearchStoreName"]);t!=null&&l(e,["_url","file_search_store_name"],t);let i=r(n,["config"]);return i!=null&&Ja(i,e),e}p(Up,"uploadToFileSearchStoreParametersToMldev");function Fp(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Fp,"uploadToFileSearchStoreResumableResponseFromMldev");var Bp="Content-Type",Vp="X-Server-Timeout",Hp="User-Agent",oo="x-goog-api-client",qp="1.33.0",Op=`google-genai-sdk/${qp}`,zp="v1beta1",Kp="v1beta",so=class{static{p(this,"ApiClient")}constructor(e){var t,i;this.clientOptions=Object.assign(Object.assign({},e),{project:e.project,location:e.location,apiKey:e.apiKey,vertexai:e.vertexai});let o={};this.clientOptions.vertexai?(o.apiVersion=(t=this.clientOptions.apiVersion)!==null&&t!==void 0?t:zp,o.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(o.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:Kp,o.baseUrl="https://generativelanguage.googleapis.com/"),o.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=o,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(o,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 i=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&i.push(e.apiVersion),i.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,i){let o=[this.getRequestUrlInternal(t)];return i&&o.push(this.getBaseResourcePath()),e!==""&&o.push(e),new URL(`${o.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 i=this.shouldPrependVertexProjectPath(e),o=this.constructUrl(e.path,t,i);if(e.queryParams)for(let[a,c]of Object.entries(e.queryParams))o.searchParams.append(a,String(c));let s={};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 s.body=e.body;return s=await this.includeExtraHttpOptionsToRequestInit(s,t,o.toString(),e.abortSignal),this.unaryApiCall(o,s,e.httpMethod)}patchHttpOptions(e,t){let i=JSON.parse(JSON.stringify(e));for(let[o,s]of Object.entries(t))typeof s=="object"?i[o]=Object.assign(Object.assign({},i[o]),s):s!==void 0&&(i[o]=s);return i}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let i=this.shouldPrependVertexProjectPath(e),o=this.constructUrl(e.path,t,i);(!o.searchParams.has("alt")||o.searchParams.get("alt")!=="sse")&&o.searchParams.set("alt","sse");let s={};return s.body=e.body,s=await this.includeExtraHttpOptionsToRequestInit(s,t,o.toString(),e.abortSignal),this.streamApiCall(o,s,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,t,i,o){if(t&&t.timeout||o){let s=new AbortController,a=s.signal;if(t.timeout&&t?.timeout>0){let c=setTimeout(()=>s.abort(),t.timeout);c&&typeof c.unref=="function"&&c.unref()}o&&o.addEventListener("abort",()=>{s.abort()}),e.signal=a}return t&&t.extraBody!==null&&Jp(e,t.extraBody),e.headers=await this.getHeadersInternal(t,i),e}async unaryApiCall(e,t,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:i})).then(async o=>(await da(o),new $t(o))).catch(o=>{throw o instanceof Error?o:new Error(JSON.stringify(o))})}async streamApiCall(e,t,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:i})).then(async o=>(await da(o),this.processStreamResponse(o))).catch(o=>{throw o instanceof Error?o:new Error(JSON.stringify(o))})}processStreamResponse(e){return Ae(this,arguments,p(function*(){var i;let o=(i=e?.body)===null||i===void 0?void 0:i.getReader(),s=new TextDecoder("utf-8");if(!o)throw new Error("Response body is empty");try{let a="",c="data:",d=[`
|
|
664
|
+
latestAddr: ${d.latestAddr} (I: d0adcc392e6e974c9917730ebad51322)`),this._currentWorkingContextIbGib=d.latestIbGib??await this.getContextIbGibFromArgOrAddr({addr:d.latestAddr,latest:!1}),this._updatingContext?q&&console.log(`${u} already updating context (I: f856f9414627ab00418dccd285b55822)`):(await this.handleContextUpdate({update:d}),a())}},"next"),error:p(async d=>{let u=`${o}[latestObs.error]`;console.error(`${u} this.metaspace.latestObs error: ${Fs({err:d})}. (E: 99df4c42195d46d0a9dbfb06ac45ae00)`)},"error")})),i&&await this.rel8To({ibGibs:[this._currentWorkingContextIbGib],rel8nName:i})}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{q&&console.log(`${o} complete.`)}}async finalizeContext({arg:e}){let t=`${this.lc}[${this.finalizeContext.name}]`;try{q&&console.log(`${t} starting... (I: dd53dfc745864dd19fde5f209ceb82c8)`);let i=0,o=100;for(;this._updatingContext&&i<o;)await O(100),i++,i%10===0&&console.log(`${t} already updating context and taking a litle while... waiting still. tries: ${i}/${o} (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(i){throw console.error(`${t} ${y(i)}`),i}finally{this._updatingContext=!1,q&&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 O(1e3);this._updatingContext=!0;try{if(q&&console.log(`${t} starting... (I: 3eeaa40cad49094f125f9f5cd6ff6e22)`),q&&(console.log(`${t} update: (I: ad0abae7de472e3b4d3891ea0b937322)`),console.table(e)),!e.latestIbGib){debugger;throw new Error("(UNEXPECTED) update.latestIbGib falsy? (E: e18a048d7e95757238396ddd84748f22)")}let i=e.latestIbGib,o=await this.getNewChildrenIbGibs({newContext:i});if(o.length===1){let s=o[0];await this.handleNewContextChild({newChild:s})}else if(o.length>1){console.warn(`${t} (UNEXPECTED) multiple new children in context update. iterating through each one. (W: 02d82a8f755f418d95fa30f0f52ad58e)`);for(let s of o)await this.handleNewContextChild({newChild:s})}else{q&&console.log(`${t} no new children in context update. returning early... (I: 31397b04965351ab29bb3f78cb709122)`);return}}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{this._updatingContext=!1,q&&console.log(`${t} complete.`)}}async getNewChildrenIbGibs({newContext:e}){let t=`${this.lc}[${this.getNewChildrenIbGibs.name}]`;try{q&&console.log(`${t} starting... (I: 1b3d1cf908489087fa3b281f55b9a522)`);let o=[...e.rel8ns?.comment??[],...e.rel8ns?.pic??[],...e.rel8ns?.link??[]].filter(u=>!this._currentWorkingContextIbGib_PriorChildrenAddrs.includes(u));if(o.length===0)return q&&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 s=await this.metaspace.getLocalUserSpace({});if(!s)throw new Error("couldn't get local user space? (E: f118f75e5852fc22bba3a6495beec723)");let a=await vs({addrs:o,space:s}),c=Object.values(a?.data?.latestAddrsMap??{});if(!a?.data?.success||c.length!==o.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!==o.length)throw new Error(`failed to get newChildren with addrs: ${o.join("|")}. Error: ${d.errorMsg??"unknown error 5737bd0996d5445b8bd80975bedc0d57"} (E: 05722e11350ec6ffffdb5c7d0caa2922)`);return d.ibGibs}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{q&&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(i){throw console.error(`${t} ${y(i)}`),i}}};var le=K,Be=class extends rn{static{p(this,"LiveProxyIbGib")}lc="";ib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.ib:Kt;gib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.gib:Jt;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{le&&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{le&&console.log(`${e} complete.`)}}async loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{le&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{le&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;return le&&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{le&&console.log(`${e} starting... (I: 1bd72217a5f334effc63f8d51e7b2225)`),await super.initialize(),this._contextUpdated$=await bi(),this.contextUpdated$=this._contextUpdated$.asObservable(),this._newContextChild$=await bi(),this.newContextChild$=this._newContextChild$.asObservable()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{le&&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(le&&console.log(`${t} starting...`),Es({ib:e.ib})){if(!e.data)throw new Error("arg has space ib but arg.data is falsy (E: b2af9226c067d5e72f117fa36e239525)");let i=e.data.uuid;return this.spaceId=i,le&&console.log(`${t} spaceId set to the ${i} (I: 018724a5431ba421b71fad36924c5a25)`),re.primitive({ib:`spaceId set to ${i}`})}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 i=await this.metaspace?.getLocalUserSpace({localSpaceId:this.spaceId});return await this.setWrappedIbGib({ibGib:e,space:i}),At}}catch(i){throw console.error(`${t} ${i.message}`),i}finally{le&&console.log(`${t} complete.`)}}_contextUpdated$;contextUpdated$;_newContextChild$;newContextChild$;async handleContextUpdate({update:e}){let t=`${this.lc}[${this.handleContextUpdate.name}]`;try{if(le&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{le&&console.log(`${t} complete.`)}}async setWrappedIbGib({ibGib:e,ibGibAddr:t,space:i}){let o=`${this.lc}[${this.setWrappedIbGib.name}]`;try{if(le&&console.log(`${o} starting... (I: a4b0acda259c121801aa701534320125)`),this.metaspace||(this.metaspace=await M()),!e){if(!t)throw new Error("(UNEXPECTED) both ibGib AND ibGibAddr falsy? (E: 6fac98ba2d4cfdec2b7ee974dec74625)");if(i??=await this.metaspace.getLocalUserSpace({lock:!1}),!i)throw new Error("(UNEXPECTED) space falsy? no space provided and couldn't get default local user space? (E: e14d1b7a6586f99453fc571396d4df25)");let s=await this.metaspace.get({addrs:[t],space:i});if(!s.success||s.ibGibs?.length!==1)throw new Error(`${o} failed to get ibGib(?) (${t}). space.ib: ${i.ib} (E: b38f0a25d92e44c0aa5cc3b038a43c6c)`);e=s.ibGibs.at(0)}await this.initializeContext({contextIbGib:e,rel8nName:""})}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{le&&console.log(`${o} complete.`)}}async handleNewContextChild({newChild:e}){let t=`[${this.handleNewContextChild.name}]`;try{if(le&&console.log(`${t} starting... (I: 7e9b6b7a4bb2726e9c717f230dfe1925)`),!this._newContextChild$)throw new Error("(UNEXPECTED) this._contextUpdated$ falsy? (E: a184df090502bed9649f8df88bd4c125)");await this._newContextChild$.next(e)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{le&&console.log(`${t} complete.`)}}};var ft="witness_agent",pt=/^[a-zA-Z0-9_\-.]{1,32}$/,Ci=/.{1,255}/,tr="",nr="Manco",ir="This is a generic, unspecified agent.";var an="List of function info ibgib addresses. These contain info on both the requests you made and the resultant values.",nt="agent",Pb={type:"string",description:"unique identifier for the agent. Should be provided to the agent in system instructions upon creation."},Rb={type:"string",description:"type of the agent that governs basic responsibilities. Should be provided to the agent in system instructions upon creation."};var tc="hardcoded",nc="human",ic="ai",oc="function",sc="unknown",j={HARDCODED:tc,HUMAN:nc,AI:ic,FUNCTION:oc,UNKNOWN:sc},_i=Object.freeze(Object.values(j));function or(n){return!!n&&_i.includes(n)}p(or,"isTextSource");var Gb={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: ${pt.source}`},sr="primaryagent";var rr=!1;async function Si({ibGib:n,addr:e,tagIbGib:t,metaspace:i,space:o}){let s=`[${Si.name}]`;try{if(rr&&console.log(`${s} starting... (I: b1fd25ec28bce8f1916b4ab55f48a724)`),!e&&!n)throw new Error("either addr or ibGib required (E: 3d580f8ecc251a0c81c7ea8bc3d38524)");if(e??=A({ibGib:n}),e!==A({ibGib:n}))throw new Error(`addr (${e}) differs from incoming ibGib's addr (${A({ibGib:n})}). (E: f2c14234a78c917fb9f587beaee89324)`);let a=await i.getLatestAddr({ibGib:t,space:o});if(a!==A({ibGib:t})){let f=await i.get({addr:a,space:o});if(!f.success||f.ibGibs?.length!==1)throw new Error(`could not get latest tag (${a}) from space (${o.ib}). error: ${f.errorMsg??"[unknown error (E: a4e31c98398b417db8f617f98a5f2741)]"} (E: 73c085d81efdab0e7b8939222ec07524)`);t=f.ibGibs.at(0)}let c={[bs]:[e]},d=await Xe({src:t,rel8nsToAddByAddr:c,dna:!0,nCounter:!0}),u=d.newIbGib;return await i.persistTransformResult({resTransform:d,space:o}),await i.registerNewIbGib({ibGib:u,space:o}),u}catch(a){throw console.error(`${s} ${y(a)}`),a}finally{rr&&console.log(`${s} complete.`)}}p(Si,"rel8ToTag");var ie=K,xi=class n{static{p(this,"AgentsService_V1")}lc=`[${n.name}]`;latestAgents=new Map;factoryFns={};constructor(){}async getAgentById(e){let t=`${this.lc}[${this.getAgentById.name}]`;try{let{agentId:i,agentType:o,spaceId:s}=e;ie&&console.log(`${t} starting... (I: 0c4214b4614a43bd2825978e54aee325)`);let a=this.latestAgents.get(i);if(!a){let c=await M();a=(await ln({metaspace:c,type:o,spaceId:s})).find(u=>u.data.uuid===i)}return a||console.warn(`${t} couldn't find any agent by id. opts: ${U(e)} (W: 70cf51ecbe68dfdcfe1e9995a7468f25)`),a}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{ie&&console.log(`${t} complete.`)}}async updateOrSetLatestAgent({agent:e,throwIfNewerFound:t}){let i=`${this.lc}[${this.updateOrSetLatestAgent.name}]`;try{if(ie&&console.log(`${i} 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 o=await this.getLatestAgent({id:e.data.uuid});if(o){if(!o.data)throw new Error("(UNEXPECTED) existing.data falsy? should have thrown on previous set function call? (E: f3cbae9922ea9849ada25db2eea40825)");if(o.data.n===e.data.n){if(o.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.
|
|
665
|
+
existing: ${U(z({ibGib:o}))}
|
|
666
|
+
new: ${U(z({ibGib:e}))} (E: 5e079b566ff3533acdb2d01359f08625)`),await o.loadIbGibDto(e.toIbGibDto()),this.latestAgents.set(e.data.uuid,e);return}else if(o.data.n>e.data.n){let s="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(`${i} ${s} (E: bb2cc3ce8cfa88b80fb62149b0e70225)`);console.warn(`${i} ${s} (W: caaf66deb4e6fd8e2eb9261685dc0325)`);return}else{await o.loadIbGibDto(e.toIbGibDto()),this.latestAgents.set(e.data.uuid,e);return}}else{this.latestAgents.set(e.data.uuid,e);return}}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{ie&&console.log(`${i} complete.`)}}getLatestAgent({id:e}){let t=`${this.lc}[${this.getLatestAgent.name}]`;try{return ie&&console.log(`${t} starting... (I: 8e85b55057760b712a913a92e88ead25)`),Promise.resolve(this.latestAgents.get(e))}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{ie&&console.log(`${t} complete.`)}}registerFactory({classname:e,fnDtoToAgentWitness:t}){this.factoryFns[e]=t}async getAgentWitnessFromDto({dto:e,classname:t}){let i=`${this.lc}[${this.getAgentWitnessFromDto.name}]`;try{if(ie&&console.log(`${i} starting... (I: 718837d4ee3d590177f3425b99106225)`),!e.data)throw new Error("dto.data falsy (E: fad89dd4c787b687a657c13968946925)");let o;if(t??=e.data.classname,t){let s=this.factoryFns[t],a=await s(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)");o=a.agent}else throw new Error(`classname (${t}) factory function found and attempted, but result says applied: false. (E: 751a2502c9a7e2d61c76c8ae2f7fb125)`)}else{let s=Object.keys(this.factoryFns);for(let a of s){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)");o=d.agent;break}}}return o}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{ie&&console.log(`${i} complete.`)}}async getAgentByAddr({agentAddr:e,spaceId:t,metaspace:i}){let o=`${this.lc}[${this.getAgentByAddr.name}]`;try{if(ie&&console.log(`${o} starting... (I: 42dfecbe6d6b5a3a7d392af5a66cc625)`),!e)throw new Error(`${o} agentAddr is required. (E: 389351659a2e08fa179ceede16925a25)`);let{ib:s}=H({ibGibAddr:e}),{uuid:a,type:c}=ar({ib:s});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 ie&&console.log(`${o} agent found already in agents svc so didn't need to go get it from the space. (I: ec6abaf3badd8e301d79a7476845bc25)`),d;i??=await M();let u=await i.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 f=await i.get({addrs:[e],space:u});if(!f.success||!f.ibGibs||f.ibGibs.length===0){ie&&console.log(`${o} Agent ibGib not found in space (${t}) at address ${e}. (I: 29c5c7994fb3ed388b28a81a9ed68325)`);return}let h=f.ibGibs[0],m=await this.getAgentWitnessFromDto({dto:h});if(!m){debugger;throw new Error(`${o} Couldn't get actual agent witness from agent dto (${e}). Have we registered classname (${h.data?.classname}) and factory fn with agents service? (E: e6e9da6c91d14bd7acb5c571c8de1a25)`)}return await this.updateOrSetLatestAgent({agent:m,throwIfNewerFound:!0}),ie&&console.log(`${o} Cached agent witness with id ${a}. (I: b862f63147a3fac3c6e6210d5ab87c25)`),ie&&console.log(`${o} complete. Retrieved and cached agent witness for address ${e}.`),m}catch(s){throw console.error(`${o} ${y(s)}`),s}}async createNewAgent(e){let t=`[${this.createNewAgent.name}]`;try{ie&&console.log(`${t} starting... (I: a3e07b54bb7bf45f7739eff2d738c825)`);let{metaspace:i,superSpace:o,name:s,availableFunctions:a,initialSystemText:c,initialChatText:d,fnGetAPIKey:u,addToAgentsTag:f,type:h}=e;if(o??=await i.getLocalUserSpace({}),!o)throw new Error("(UNEXPECTED) superSpace falsy? (E: ceb60d96ff25b6d6aaa5aa69a7a51d25)");if(!o.data)throw new Error("(UNEXPECTED) superSpace.data falsy? (E: 56b4ec127f8559da96e6f70c7cb13825)");let m=$i(e),g=await m.createInitialData(o);if(!g.uuid)throw new Error("(UNEXPECTED) data.uuid falsy? (E: 4e4f6fcf89d1e3775971ad843a083725)");let b=await i.createLocalSpaceAndUpdateBootstrap({allowCancel:!1,zeroSpace:i.zeroSpace,spaceName:s+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 m.createInitialRel8ns(),w=await re.firstGen({ib:Pi({data:g}),parentIbGib:re.primitive({ib:ft}),data:g,rel8ns:E,nCounter:!0,dna:!0,tjp:{timestamp:!0}});await i.persistTransformResult({resTransform:w});let v=w.newIbGib,I=await m.createWitness();if(I.fnGetAPIKey=u,await I.loadIbGibDto(v),f){let C=await Ni({metaspace:i,space:o}),N=await Si({ibGib:v,metaspace:i,space:o,tagIbGib:C})}await ue({type:h,rel8nInfos:[{rel8nName:nt,ibGibs:[v]}],metaspace:i,space:o}),a.length>0&&await I.addAvailableFunctions(a);let T=[];return T.push({textSrc:"hardcoded",text:ht({tagText:Ss,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 I.addTexts({infos:T}),this.latestAgents.set(I.data.uuid,I),I}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{ie&&console.log(`${t} complete.`)}}getAgents(e){let t=`${this.lc}[${this.getAgents.name}]`;try{return ie&&console.log(`${t} starting... (I: 4663f125c3a21fa3ecccc2c5a38d1225)`),ln(e)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{ie&&console.log(`${t} complete.`)}}},Ai;function Re(){return Ai||(Ai=new xi),Ai}p(Re,"getAgentsSvc");var rc="gemini-3.1-pro-preview",ac="gemini-3-flash-preview",lc="gemini-3.1-flash-lite-preview",cc="gemini-3.1-flash-live-preview",dc="gemini-2.5-pro",uc="gemini-2.5-flash",fc="gemini-2.5-flash-lite",pc="gemini-2.5-flash-preview-tts",hc="gemini-2.0-flash",mc="gemini-2.0-flash-lite",Ri={GEMINI_3_1_PRO_PREVIEW:rc,GEMINI_3_FLASH_PREVIEW:ac,GEMINI_3_1_FLASH_LITE_PREVIEW:lc,GEMINI_3_1_FLASH_LIVE_PREVIEW:cc,GEMINI_2_5_PRO:dc,GEMINI_2_5_FLASH:uc,GEMINI_2_5_FLASH_LITE:fc,GEMINI_2_5_FLASH_PREVIEW_TTS:pc,GEMINI_2_0_FLASH:hc,GEMINI_2_0_FLASH_LITE:mc},ty=Object.freeze(Object.values(Ri));var lr=Ri.GEMINI_2_5_FLASH,mt=Ri.GEMINI_2_5_FLASH_LITE,Gi=5;var cr={version:"1",uuid:tr,name:nr,description:ir,classname:"AgentWitness_V1",icon:"happy",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1,subSpaceId:"",superSpaceId:"",availableFunctionNameOrIds:[],model:lr,api:"gemini",type:sr,"@currentContextTjpAddr":Q},Mi=void 0;var gc,bc;function yc(){return{geminiUrl:gc,vertexUrl:bc}}p(yc,"getDefaultBaseUrls");function Ec(n,e,t,i){var o,s;if(!n?.baseUrl){let a=yc();return e?(o=a.vertexUrl)!==null&&o!==void 0?o:t:(s=a.geminiUrl)!==null&&s!==void 0?s:i}return n.baseUrl}p(Ec,"getBaseUrl");var xe=class{static{p(this,"BaseModule")}};function _(n,e){let t=/\{([^}]+)\}/g;return n.replace(t,(i,o)=>{if(Object.prototype.hasOwnProperty.call(e,o)){let s=e[o];return s!=null?String(s):""}else throw new Error(`Key '${o}' not found in valueMap.`)})}p(_,"formatMap");function l(n,e,t){for(let s=0;s<e.length-1;s++){let a=e[s];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 f=d[u];l(f,e.slice(s+1),t[u])}else for(let u of d)l(u,e.slice(s+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(s+1),t);return}(!n[a]||typeof n[a]!="object")&&(n[a]={}),n=n[a]}let i=e[e.length-1],o=n[i];if(o!==void 0){if(!t||typeof t=="object"&&Object.keys(t).length===0||t===o)return;if(typeof o=="object"&&typeof t=="object"&&o!==null&&t!==null)Object.assign(o,t);else throw new Error(`Cannot set value for an existing key. Key: ${i}`)}else i==="_self"&&typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.assign(n,t):n[i]=t}p(l,"setValueByPath");function r(n,e,t=void 0){try{if(e.length===1&&e[0]==="_self")return n;for(let i=0;i<e.length;i++){if(typeof n!="object"||n===null)return t;let o=e[i];if(o.endsWith("[]")){let s=o.slice(0,-2);if(s in n){let a=n[s];return Array.isArray(a)?a.map(c=>r(c,e.slice(i+1),t)):t}else return t}else n=n[o]}return n}catch(i){if(i instanceof TypeError)return t;throw i}}p(r,"getValueByPath");function wc(n,e){for(let[t,i]of Object.entries(e)){let o=t.split("."),s=i.split("."),a=new Set,c=-1;for(let d=0;d<o.length;d++)if(o[d]==="*"){c=d;break}if(c!==-1&&s.length>c)for(let d=c;d<s.length;d++){let u=s[d];u!=="*"&&!u.endsWith("[]")&&!u.endsWith("[0]")&&a.add(u)}Ui(n,o,s,0,a)}}p(wc,"moveValueByPath");function Ui(n,e,t,i,o){if(i>=e.length||typeof n!="object"||n===null)return;let s=e[i];if(s.endsWith("[]")){let a=s.slice(0,-2),c=n;if(a in c&&Array.isArray(c[a]))for(let d of c[a])Ui(d,e,t,i+1,o)}else if(s==="*"){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let a=n,c=Object.keys(a).filter(u=>!u.startsWith("_")&&!o.has(u)),d={};for(let u of c)d[u]=a[u];for(let[u,f]of Object.entries(d)){let h=[];for(let m of t.slice(i))m==="*"?h.push(u):h.push(m);l(a,h,f)}for(let u of c)delete a[u]}}else{let a=n;s in a&&Ui(a[s],e,t,i+1,o)}}p(Ui,"_moveValueRecursive");function Lo(n){if(typeof n!="string")throw new Error("fromImageBytes must be a string");return n}p(Lo,"tBytes$1");function vc(n){let e={},t=r(n,["operationName"]);t!=null&&l(e,["operationName"],t);let i=r(n,["resourceName"]);return i!=null&&l(e,["_url","resourceName"],i),e}p(vc,"fetchPredictOperationParametersToVertex");function Ic(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response","generateVideoResponse"]);return a!=null&&l(e,["response"],Cc(a)),e}p(Ic,"generateVideosOperationFromMldev$1");function Tc(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response"]);return a!=null&&l(e,["response"],_c(a)),e}p(Tc,"generateVideosOperationFromVertex$1");function Cc(n){let e={},t=r(n,["generatedSamples"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>Sc(a))),l(e,["generatedVideos"],s)}let i=r(n,["raiMediaFilteredCount"]);i!=null&&l(e,["raiMediaFilteredCount"],i);let o=r(n,["raiMediaFilteredReasons"]);return o!=null&&l(e,["raiMediaFilteredReasons"],o),e}p(Cc,"generateVideosResponseFromMldev$1");function _c(n){let e={},t=r(n,["videos"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>Ac(a))),l(e,["generatedVideos"],s)}let i=r(n,["raiMediaFilteredCount"]);i!=null&&l(e,["raiMediaFilteredCount"],i);let o=r(n,["raiMediaFilteredReasons"]);return o!=null&&l(e,["raiMediaFilteredReasons"],o),e}p(_c,"generateVideosResponseFromVertex$1");function Sc(n){let e={},t=r(n,["video"]);return t!=null&&l(e,["video"],Gc(t)),e}p(Sc,"generatedVideoFromMldev$1");function Ac(n){let e={},t=r(n,["_self"]);return t!=null&&l(e,["video"],Mc(t)),e}p(Ac,"generatedVideoFromVertex$1");function xc(n){let e={},t=r(n,["operationName"]);return t!=null&&l(e,["_url","operationName"],t),e}p(xc,"getOperationParametersToMldev");function Nc(n){let e={},t=r(n,["operationName"]);return t!=null&&l(e,["_url","operationName"],t),e}p(Nc,"getOperationParametersToVertex");function $c(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response"]);return a!=null&&l(e,["response"],Pc(a)),e}p($c,"importFileOperationFromMldev$1");function Pc(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["parent"]);i!=null&&l(e,["parent"],i);let o=r(n,["documentName"]);return o!=null&&l(e,["documentName"],o),e}p(Pc,"importFileResponseFromMldev$1");function Ra(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response"]);return a!=null&&l(e,["response"],Rc(a)),e}p(Ra,"uploadToFileSearchStoreOperationFromMldev");function Rc(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["parent"]);i!=null&&l(e,["parent"],i);let o=r(n,["documentName"]);return o!=null&&l(e,["documentName"],o),e}p(Rc,"uploadToFileSearchStoreResponseFromMldev");function Gc(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["encodedVideo"]);i!=null&&l(e,["videoBytes"],Lo(i));let o=r(n,["encoding"]);return o!=null&&l(e,["mimeType"],o),e}p(Gc,"videoFromMldev$1");function Mc(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["uri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["videoBytes"],Lo(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(Mc,"videoFromVertex$1");var dr;(function(n){n.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",n.OUTCOME_OK="OUTCOME_OK",n.OUTCOME_FAILED="OUTCOME_FAILED",n.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(dr||(dr={}));var ur;(function(n){n.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",n.PYTHON="PYTHON"})(ur||(ur={}));var fr;(function(n){n.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",n.SILENT="SILENT",n.WHEN_IDLE="WHEN_IDLE",n.INTERRUPT="INTERRUPT"})(fr||(fr={}));var Ve;(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"})(Ve||(Ve={}));var pr;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(pr||(pr={}));var hr;(function(n){n.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",n.SIMPLE_SEARCH="SIMPLE_SEARCH",n.ELASTIC_SEARCH="ELASTIC_SEARCH"})(hr||(hr={}));var mr;(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"})(mr||(mr={}));var gr;(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"})(gr||(gr={}));var br;(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"})(br||(br={}));var yr;(function(n){n.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",n.LOW="LOW",n.HIGH="HIGH"})(yr||(yr={}));var Er;(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"})(Er||(Er={}));var wr;(function(n){n.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",n.SEVERITY="SEVERITY",n.PROBABILITY="PROBABILITY"})(wr||(wr={}));var vr;(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"})(vr||(vr={}));var Ir;(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"})(Ir||(Ir={}));var Tr;(function(n){n.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",n.NEGLIGIBLE="NEGLIGIBLE",n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH"})(Tr||(Tr={}));var Cr;(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"})(Cr||(Cr={}));var _r;(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"})(_r||(_r={}));var Sr;(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"})(Sr||(Sr={}));var Ar;(function(n){n.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",n.ON_DEMAND="ON_DEMAND",n.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(Ar||(Ar={}));var gn;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.AUDIO="AUDIO"})(gn||(gn={}));var xr;(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"})(xr||(xr={}));var Nr;(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"})(Nr||(Nr={}));var $r;(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"})($r||($r={}));var Fi;(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"})(Fi||(Fi={}));var Pr;(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"})(Pr||(Pr={}));var Rr;(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"})(Rr||(Rr={}));var Gr;(function(n){n.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",n.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",n.BALANCED="BALANCED",n.PRIORITIZE_COST="PRIORITIZE_COST"})(Gr||(Gr={}));var Mr;(function(n){n.UNSPECIFIED="UNSPECIFIED",n.BLOCKING="BLOCKING",n.NON_BLOCKING="NON_BLOCKING"})(Mr||(Mr={}));var kr;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(kr||(kr={}));var Dr;(function(n){n.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",n.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(Dr||(Dr={}));var bn;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.AUTO="AUTO",n.ANY="ANY",n.NONE="NONE",n.VALIDATED="VALIDATED"})(bn||(bn={}));var Lr;(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"})(Lr||(Lr={}));var Ur;(function(n){n.DONT_ALLOW="DONT_ALLOW",n.ALLOW_ADULT="ALLOW_ADULT",n.ALLOW_ALL="ALLOW_ALL"})(Ur||(Ur={}));var Fr;(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"})(Fr||(Fr={}));var Br;(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"})(Br||(Br={}));var Vr;(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"})(Vr||(Vr={}));var qr;(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"})(qr||(qr={}));var Hr;(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"})(Hr||(Hr={}));var Or;(function(n){n.FOREGROUND="FOREGROUND",n.BACKGROUND="BACKGROUND",n.PROMPT="PROMPT",n.SEMANTIC="SEMANTIC",n.INTERACTIVE="INTERACTIVE"})(Or||(Or={}));var zr;(function(n){n.ASSET="ASSET",n.STYLE="STYLE"})(zr||(zr={}));var Kr;(function(n){n.INSERT="INSERT",n.REMOVE="REMOVE",n.REMOVE_STATIC="REMOVE_STATIC",n.OUTPAINT="OUTPAINT"})(Kr||(Kr={}));var Jr;(function(n){n.OPTIMIZED="OPTIMIZED",n.LOSSLESS="LOSSLESS"})(Jr||(Jr={}));var Wr;(function(n){n.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",n.PREFERENCE_TUNING="PREFERENCE_TUNING"})(Wr||(Wr={}));var Xr;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.STATE_PENDING="STATE_PENDING",n.STATE_ACTIVE="STATE_ACTIVE",n.STATE_FAILED="STATE_FAILED"})(Xr||(Xr={}));var Yr;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.PROCESSING="PROCESSING",n.ACTIVE="ACTIVE",n.FAILED="FAILED"})(Yr||(Yr={}));var Qr;(function(n){n.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",n.UPLOADED="UPLOADED",n.GENERATED="GENERATED"})(Qr||(Qr={}));var Zr;(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"})(Zr||(Zr={}));var jr;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.VIDEO="VIDEO",n.AUDIO="AUDIO",n.DOCUMENT="DOCUMENT"})(jr||(jr={}));var ea;(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"})(ea||(ea={}));var ta;(function(n){n.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",n.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",n.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(ta||(ta={}));var na;(function(n){n.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",n.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",n.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(na||(na={}));var ia;(function(n){n.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",n.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",n.NO_INTERRUPTION="NO_INTERRUPTION"})(ia||(ia={}));var oa;(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"})(oa||(oa={}));var sa;(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"})(sa||(sa={}));var ra;(function(n){n.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",n.QUALITY="QUALITY",n.DIVERSITY="DIVERSITY",n.VOCALIZATION="VOCALIZATION"})(ra||(ra={}));var bt;(function(n){n.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",n.PLAY="PLAY",n.PAUSE="PAUSE",n.STOP="STOP",n.RESET_CONTEXT="RESET_CONTEXT"})(bt||(bt={}));var kt=class{static{p(this,"HttpResponse")}constructor(e){let t={};for(let i of e.headers.entries())t[i[0]]=i[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}};var ot=class{static{p(this,"GenerateContentResponse")}get text(){var e,t,i,o,s,a,c,d;if(((o=(i=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.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="",f=!1,h=[];for(let m of(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[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(m))g!=="text"&&g!=="thought"&&g!=="thoughtSignature"&&(b!==null||b!==void 0)&&h.push(g);if(typeof m.text=="string"){if(typeof m.thought=="boolean"&&m.thought)continue;f=!0,u+=m.text}}return h.length>0&&console.warn(`there are non-text parts ${h} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),f?u:void 0}get data(){var e,t,i,o,s,a,c,d;if(((o=(i=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.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="",f=[];for(let h of(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||c===void 0?void 0:c.parts)!==null&&d!==void 0?d:[]){for(let[m,g]of Object.entries(h))m!=="inlineData"&&(g!==null||g!==void 0)&&f.push(m);h.inlineData&&typeof h.inlineData.data=="string"&&(u+=atob(h.inlineData.data))}return f.length>0&&console.warn(`there are non-data parts ${f} 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,i,o,s,a,c,d;if(((o=(i=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.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=(s=this.candidates)===null||s===void 0?void 0:s[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(f=>f.functionCall).map(f=>f.functionCall).filter(f=>f!==void 0);if(u?.length!==0)return u}get executableCode(){var e,t,i,o,s,a,c,d,u;if(((o=(i=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.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 f=(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[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(h=>h.executableCode).map(h=>h.executableCode).filter(h=>h!==void 0);if(f?.length!==0)return(u=f?.[0])===null||u===void 0?void 0:u.code}get codeExecutionResult(){var e,t,i,o,s,a,c,d,u;if(((o=(i=(t=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||t===void 0?void 0:t.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.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 f=(d=(c=(a=(s=this.candidates)===null||s===void 0?void 0:s[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(h=>h.codeExecutionResult).map(h=>h.codeExecutionResult).filter(h=>h!==void 0);if(f?.length!==0)return(u=f?.[0])===null||u===void 0?void 0:u.output}},yn=class{static{p(this,"EmbedContentResponse")}},En=class{static{p(this,"GenerateImagesResponse")}},Bi=class{static{p(this,"EditImageResponse")}},Vi=class{static{p(this,"UpscaleImageResponse")}},qi=class{static{p(this,"RecontextImageResponse")}},Hi=class{static{p(this,"SegmentImageResponse")}},wn=class{static{p(this,"ListModelsResponse")}},vn=class{static{p(this,"DeleteModelResponse")}},In=class{static{p(this,"CountTokensResponse")}},Oi=class{static{p(this,"ComputeTokensResponse")}};var Tn=class n{static{p(this,"GenerateVideosOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,o,s=e;return t?o=Tc(s):o=Ic(s),Object.assign(i,o),i}},Cn=class{static{p(this,"ListTuningJobsResponse")}},_n=class{static{p(this,"CancelTuningJobResponse")}},Sn=class{static{p(this,"DeleteCachedContentResponse")}},An=class{static{p(this,"ListCachedContentsResponse")}},zi=class{static{p(this,"ListDocumentsResponse")}},Ki=class{static{p(this,"ListFileSearchStoresResponse")}},Ji=class{static{p(this,"UploadToFileSearchStoreResumableResponse")}};var Wi=class n{static{p(this,"ImportFileOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,s=$c(e);return Object.assign(i,s),i}},Xi=class{static{p(this,"ListFilesResponse")}},Yi=class{static{p(this,"CreateFileResponse")}},Qi=class{static{p(this,"DeleteFileResponse")}};var xn=class{static{p(this,"ListBatchJobsResponse")}};var Zi=class{static{p(this,"LiveServerMessage")}get text(){var e,t,i;let o="",s=!1,a=[];for(let c of(i=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&i!==void 0?i:[]){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;s=!0,o+=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.`),s?o:void 0}get data(){var e,t,i;let o="",s=[];for(let a of(i=(t=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||t===void 0?void 0:t.parts)!==null&&i!==void 0?i:[]){for(let[c,d]of Object.entries(a))c!=="inlineData"&&d!==null&&s.push(c);a.inlineData&&typeof a.inlineData.data=="string"&&(o+=atob(a.inlineData.data))}return s.length>0&&console.warn(`there are non-data parts ${s} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),o.length>0?btoa(o):void 0}};var ji=class{static{p(this,"LiveMusicServerMessage")}get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var eo=class n{static{p(this,"UploadToFileSearchStoreOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,s=Ra(e);return Object.assign(i,s),i}};function F(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}`}p(F,"tModel");function Ga(n,e){let t=F(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:""}p(Ga,"tCachesModel");function Ma(n){return Array.isArray(n)?n.map(e=>Nn(e)):[Nn(n)]}p(Ma,"tBlobs");function Nn(n){if(typeof n=="object"&&n!==null)return n;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof n}`)}p(Nn,"tBlob");function ka(n){let e=Nn(n);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}p(ka,"tImageBlob");function Da(n){let e=Nn(n);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}p(Da,"tAudioBlob");function aa(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}`)}p(aa,"tPart");function La(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("PartListUnion is required");return Array.isArray(n)?n.map(e=>aa(e)):[aa(n)]}p(La,"tParts");function to(n){return n!=null&&typeof n=="object"&&"parts"in n&&Array.isArray(n.parts)}p(to,"_isContent");function la(n){return n!=null&&typeof n=="object"&&"functionCall"in n}p(la,"_isFunctionCallPart");function ca(n){return n!=null&&typeof n=="object"&&"functionResponse"in n}p(ca,"_isFunctionResponsePart");function ce(n){if(n==null)throw new Error("ContentUnion is required");return to(n)?n:{role:"user",parts:La(n)}}p(ce,"tContent");function Uo(n,e){if(!e)return[];if(n.isVertexAI()&&Array.isArray(e))return e.flatMap(t=>{let i=ce(t);return i.parts&&i.parts.length>0&&i.parts[0].text!==void 0?[i.parts[0].text]:[]});if(n.isVertexAI()){let t=ce(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=>ce(t)):[ce(e)]}p(Uo,"tContentsForEmbed");function Ie(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("contents are required");if(!Array.isArray(n)){if(la(n)||ca(n))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[ce(n)]}let e=[],t=[],i=to(n[0]);for(let o of n){let s=to(o);if(s!=i)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(s)e.push(o);else{if(la(o)||ca(o))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(o)}}return i||e.push({role:"user",parts:La(t)}),e}p(Ie,"tContents");function kc(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(i=>i!=="null");if(t.length===1)e.type=Object.values(Ve).includes(t[0].toUpperCase())?t[0].toUpperCase():Ve.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let i of t)e.anyOf.push({type:Object.values(Ve).includes(i.toUpperCase())?i.toUpperCase():Ve.TYPE_UNSPECIFIED})}}p(kc,"flattenTypeArrayToAnyOf");function yt(n){let e={},t=["items"],i=["anyOf"],o=["properties"];if(n.type&&n.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=n.anyOf;s!=null&&s.length==2&&(s[0].type==="null"?(e.nullable=!0,n=s[1]):s[1].type==="null"&&(e.nullable=!0,n=s[0])),n.type instanceof Array&&kc(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(Ve).includes(c.toUpperCase())?c.toUpperCase():Ve.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=yt(c);else if(i.includes(a)){let d=[];for(let u of c){if(u.type=="null"){e.nullable=!0;continue}d.push(yt(u))}e[a]=d}else if(o.includes(a)){let d={};for(let[u,f]of Object.entries(c))d[u]=yt(f);e[a]=d}else{if(a==="additionalProperties")continue;e[a]=c}return e}p(yt,"processJsonSchema");function Fo(n){return yt(n)}p(Fo,"tSchema");function Bo(n){if(typeof n=="object")return n;if(typeof n=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:n}}};throw new Error(`Unsupported speechConfig type: ${typeof n}`)}p(Bo,"tSpeechConfig");function Vo(n){if("multiSpeakerVoiceConfig"in n)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return n}p(Vo,"tLiveSpeechConfig");function It(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=yt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=yt(e.response));return n}p(It,"tTool");function Tt(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}p(Tt,"tTools");function Dc(n,e,t,i=1){let o=!e.startsWith(`${t}/`)&&e.split("/").length===i;return n.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${n.getProject()}/${e}`:e.startsWith(`${t}/`)?`projects/${n.getProject()}/locations/${n.getLocation()}/${e}`:o?`projects/${n.getProject()}/locations/${n.getLocation()}/${t}/${e}`:e:o?`${t}/${e}`:e}p(Dc,"resourceName");function Le(n,e){if(typeof e!="string")throw new Error("name must be a string");return Dc(n,e,"cachedContents")}p(Le,"tCachedContentName");function Ua(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}}p(Ua,"tTuningJobStatus");function qe(n){return Lo(n)}p(qe,"tBytes");function Lc(n){return n!=null&&typeof n=="object"&&"name"in n}p(Lc,"_isFile");function Uc(n){return n!=null&&typeof n=="object"&&"video"in n}p(Uc,"isGeneratedVideo");function Fc(n){return n!=null&&typeof n=="object"&&"uri"in n}p(Fc,"isVideo");function Fa(n){var e;let t;if(Lc(n)&&(t=n.name),!(Fc(n)&&(t=n.uri,t===void 0))&&!(Uc(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 o=t.split("files/")[1].match(/[a-z0-9]+/);if(o===null)throw new Error(`Could not extract file name from URI ${t}`);t=o[0]}else t.startsWith("files/")&&(t=t.split("files/")[1]);return t}}p(Fa,"tFileName");function Ba(n,e){let t;return n.isVertexAI()?t=e?"publishers/google/models":"models":t=e?"models":"tunedModels",t}p(Ba,"tModelsUrl");function Va(n){for(let e of["models","tunedModels","publisherModels"])if(Bc(n,e))return n[e];return[]}p(Va,"tExtractModels");function Bc(n,e){return n!==null&&typeof n=="object"&&e in n}p(Bc,"hasField");function Vc(n,e={}){let t=n,i={name:t.name,description:t.description,parametersJsonSchema:t.inputSchema};return t.outputSchema&&(i.responseJsonSchema=t.outputSchema),e.behavior&&(i.behavior=e.behavior),{functionDeclarations:[i]}}p(Vc,"mcpToGeminiTool");function qc(n,e={}){let t=[],i=new Set;for(let o of n){let s=o.name;if(i.has(s))throw new Error(`Duplicate function name ${s} found in MCP tools. Please ensure function names are unique.`);i.add(s);let a=Vc(o,e);a.functionDeclarations&&t.push(...a.functionDeclarations)}return{functionDeclarations:t}}p(qc,"mcpToolsToGeminiTool");function qa(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 i=[t.gcsUri,t.bigqueryUri].filter(Boolean).length,o=[t.inlinedRequests,t.fileName].filter(Boolean).length;if(n.isVertexAI()){if(o>0||i!==1)throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(i>0||o!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return t}p(qa,"tBatchJobSource");function Hc(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}`)}p(Hc,"tBatchJobDestination");function Ha(n){if(typeof n!="object"||n===null)return{};let e=n,t=e.inlinedResponses;if(typeof t!="object"||t===null)return n;let o=t.inlinedResponses;if(!Array.isArray(o)||o.length===0)return n;let s=!1;for(let a of o){if(typeof a!="object"||a===null)continue;let d=a.response;if(typeof d!="object"||d===null)continue;if(d.embedding!==void 0){s=!0;break}}return s&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),n}p(Ha,"tRecvBatchJobDestination");function Ct(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}.`)}p(Ct,"tBatchJobName");function Oa(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}p(Oa,"tJobState");function Oc(n){let e={},t=r(n,["responsesFile"]);t!=null&&l(e,["fileName"],t);let i=r(n,["inlinedResponses","inlinedResponses"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>Cd(a))),l(e,["inlinedResponses"],s)}let o=r(n,["inlinedEmbedContentResponses","inlinedResponses"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["inlinedEmbedContentResponses"],s)}return e}p(Oc,"batchJobDestinationFromMldev");function zc(n){let e={},t=r(n,["predictionsFormat"]);t!=null&&l(e,["format"],t);let i=r(n,["gcsDestination","outputUriPrefix"]);i!=null&&l(e,["gcsUri"],i);let o=r(n,["bigqueryDestination","outputUri"]);return o!=null&&l(e,["bigqueryUri"],o),e}p(zc,"batchJobDestinationFromVertex");function Kc(n){let e={},t=r(n,["format"]);t!=null&&l(e,["predictionsFormat"],t);let i=r(n,["gcsUri"]);i!=null&&l(e,["gcsDestination","outputUriPrefix"],i);let o=r(n,["bigqueryUri"]);if(o!=null&&l(e,["bigqueryDestination","outputUri"],o),r(n,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(r(n,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is not supported in Vertex AI.");if(r(n,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");return e}p(Kc,"batchJobDestinationToVertex");function hn(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata","displayName"]);i!=null&&l(e,["displayName"],i);let o=r(n,["metadata","state"]);o!=null&&l(e,["state"],Oa(o));let s=r(n,["metadata","createTime"]);s!=null&&l(e,["createTime"],s);let a=r(n,["metadata","endTime"]);a!=null&&l(e,["endTime"],a);let c=r(n,["metadata","updateTime"]);c!=null&&l(e,["updateTime"],c);let d=r(n,["metadata","model"]);d!=null&&l(e,["model"],d);let u=r(n,["metadata","output"]);return u!=null&&l(e,["dest"],Oc(Ha(u))),e}p(hn,"batchJobFromMldev");function no(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["displayName"]);i!=null&&l(e,["displayName"],i);let o=r(n,["state"]);o!=null&&l(e,["state"],Oa(o));let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["createTime"]);a!=null&&l(e,["createTime"],a);let c=r(n,["startTime"]);c!=null&&l(e,["startTime"],c);let d=r(n,["endTime"]);d!=null&&l(e,["endTime"],d);let u=r(n,["updateTime"]);u!=null&&l(e,["updateTime"],u);let f=r(n,["model"]);f!=null&&l(e,["model"],f);let h=r(n,["inputConfig"]);h!=null&&l(e,["src"],Jc(h));let m=r(n,["outputConfig"]);m!=null&&l(e,["dest"],zc(Ha(m)));let g=r(n,["completionStats"]);return g!=null&&l(e,["completionStats"],g),e}p(no,"batchJobFromVertex");function Jc(n){let e={},t=r(n,["instancesFormat"]);t!=null&&l(e,["format"],t);let i=r(n,["gcsSource","uris"]);i!=null&&l(e,["gcsUri"],i);let o=r(n,["bigquerySource","inputUri"]);return o!=null&&l(e,["bigqueryUri"],o),e}p(Jc,"batchJobSourceFromVertex");function Wc(n,e){let t={};if(r(e,["format"])!==void 0)throw new Error("format parameter is not supported in Gemini API.");if(r(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(r(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is not supported in Gemini API.");let i=r(e,["fileName"]);i!=null&&l(t,["fileName"],i);let o=r(e,["inlinedRequests"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>Td(n,a))),l(t,["requests","requests"],s)}return t}p(Wc,"batchJobSourceToMldev");function Xc(n){let e={},t=r(n,["format"]);t!=null&&l(e,["instancesFormat"],t);let i=r(n,["gcsUri"]);i!=null&&l(e,["gcsSource","uris"],i);let o=r(n,["bigqueryUri"]);if(o!=null&&l(e,["bigquerySource","inputUri"],o),r(n,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(r(n,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is not supported in Vertex AI.");return e}p(Xc,"batchJobSourceToVertex");function Yc(n){let e={},t=r(n,["data"]);if(t!=null&&l(e,["data"],t),r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(Yc,"blobToMldev$4");function Qc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Ct(n,i)),t}p(Qc,"cancelBatchJobParametersToMldev");function Zc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Ct(n,i)),t}p(Zc,"cancelBatchJobParametersToVertex");function jc(n){let e={},t=r(n,["content"]);t!=null&&l(e,["content"],t);let i=r(n,["citationMetadata"]);i!=null&&l(e,["citationMetadata"],ed(i));let o=r(n,["tokenCount"]);o!=null&&l(e,["tokenCount"],o);let s=r(n,["finishReason"]);s!=null&&l(e,["finishReason"],s);let a=r(n,["avgLogprobs"]);a!=null&&l(e,["avgLogprobs"],a);let c=r(n,["groundingMetadata"]);c!=null&&l(e,["groundingMetadata"],c);let d=r(n,["index"]);d!=null&&l(e,["index"],d);let u=r(n,["logprobsResult"]);u!=null&&l(e,["logprobsResult"],u);let f=r(n,["safetyRatings"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(g=>g)),l(e,["safetyRatings"],m)}let h=r(n,["urlContextMetadata"]);return h!=null&&l(e,["urlContextMetadata"],h),e}p(jc,"candidateFromMldev$1");function ed(n){let e={},t=r(n,["citationSources"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>o)),l(e,["citations"],i)}return e}p(ed,"citationMetadataFromMldev$1");function za(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>Pd(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(za,"contentToMldev$4");function td(n,e){let t={},i=r(n,["displayName"]);if(e!==void 0&&i!=null&&l(e,["batch","displayName"],i),r(n,["dest"])!==void 0)throw new Error("dest parameter is not supported in Gemini API.");return t}p(td,"createBatchJobConfigToMldev");function nd(n,e){let t={},i=r(n,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=r(n,["dest"]);return e!==void 0&&o!=null&&l(e,["outputConfig"],Kc(Hc(o))),t}p(nd,"createBatchJobConfigToVertex");function da(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["src"]);o!=null&&l(t,["batch","inputConfig"],Wc(n,qa(n,o)));let s=r(e,["config"]);return s!=null&&td(s,t),t}p(da,"createBatchJobParametersToMldev");function id(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],F(n,i));let o=r(e,["src"]);o!=null&&l(t,["inputConfig"],Xc(qa(n,o)));let s=r(e,["config"]);return s!=null&&nd(s,t),t}p(id,"createBatchJobParametersToVertex");function od(n,e){let t={},i=r(n,["displayName"]);return e!==void 0&&i!=null&&l(e,["batch","displayName"],i),t}p(od,"createEmbeddingsBatchJobConfigToMldev");function sd(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["src"]);o!=null&&l(t,["batch","inputConfig"],fd(n,o));let s=r(e,["config"]);return s!=null&&od(s,t),t}p(sd,"createEmbeddingsBatchJobParametersToMldev");function rd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Ct(n,i)),t}p(rd,"deleteBatchJobParametersToMldev");function ad(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Ct(n,i)),t}p(ad,"deleteBatchJobParametersToVertex");function ld(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["name"]);i!=null&&l(e,["name"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);return s!=null&&l(e,["error"],s),e}p(ld,"deleteResourceJobFromMldev");function cd(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["name"]);i!=null&&l(e,["name"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);return s!=null&&l(e,["error"],s),e}p(cd,"deleteResourceJobFromVertex");function dd(n,e){let t={},i=r(e,["contents"]);if(i!=null){let s=Uo(n,i);Array.isArray(s)&&(s=s.map(a=>a)),l(t,["requests[]","request","content"],s)}let o=r(e,["config"]);return o!=null&&(l(t,["_self"],ud(o,t)),wc(t,{"requests[].*":"requests[].request.*"})),t}p(dd,"embedContentBatchToMldev");function ud(n,e){let t={},i=r(n,["taskType"]);e!==void 0&&i!=null&&l(e,["requests[]","taskType"],i);let o=r(n,["title"]);e!==void 0&&o!=null&&l(e,["requests[]","title"],o);let s=r(n,["outputDimensionality"]);if(e!==void 0&&s!=null&&l(e,["requests[]","outputDimensionality"],s),r(n,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(r(n,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return t}p(ud,"embedContentConfigToMldev$1");function fd(n,e){let t={},i=r(e,["fileName"]);i!=null&&l(t,["file_name"],i);let o=r(e,["inlinedRequests"]);return o!=null&&l(t,["requests"],dd(n,o)),t}p(fd,"embeddingsBatchJobSourceToMldev");function pd(n){let e={};if(r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=r(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(pd,"fileDataToMldev$4");function hd(n){let e={},t=r(n,["id"]);t!=null&&l(e,["id"],t);let i=r(n,["args"]);i!=null&&l(e,["args"],i);let o=r(n,["name"]);if(o!=null&&l(e,["name"],o),r(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(r(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}p(hd,"functionCallToMldev$4");function md(n){let e={},t=r(n,["mode"]);t!=null&&l(e,["mode"],t);let i=r(n,["allowedFunctionNames"]);if(i!=null&&l(e,["allowedFunctionNames"],i),r(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}p(md,"functionCallingConfigToMldev$2");function gd(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],za(ce(o)));let s=r(e,["temperature"]);s!=null&&l(i,["temperature"],s);let a=r(e,["topP"]);a!=null&&l(i,["topP"],a);let c=r(e,["topK"]);c!=null&&l(i,["topK"],c);let d=r(e,["candidateCount"]);d!=null&&l(i,["candidateCount"],d);let u=r(e,["maxOutputTokens"]);u!=null&&l(i,["maxOutputTokens"],u);let f=r(e,["stopSequences"]);f!=null&&l(i,["stopSequences"],f);let h=r(e,["responseLogprobs"]);h!=null&&l(i,["responseLogprobs"],h);let m=r(e,["logprobs"]);m!=null&&l(i,["logprobs"],m);let g=r(e,["presencePenalty"]);g!=null&&l(i,["presencePenalty"],g);let b=r(e,["frequencyPenalty"]);b!=null&&l(i,["frequencyPenalty"],b);let E=r(e,["seed"]);E!=null&&l(i,["seed"],E);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],Fo(v));let I=r(e,["responseJsonSchema"]);if(I!=null&&l(i,["responseJsonSchema"],I),r(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(r(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");let T=r(e,["safetySettings"]);if(t!==void 0&&T!=null){let V=T;Array.isArray(V)&&(V=V.map(he=>Rd(he))),l(t,["safetySettings"],V)}let C=r(e,["tools"]);if(t!==void 0&&C!=null){let V=Tt(C);Array.isArray(V)&&(V=V.map(he=>Md(It(he)))),l(t,["tools"],V)}let N=r(e,["toolConfig"]);if(t!==void 0&&N!=null&&l(t,["toolConfig"],Gd(N)),r(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let S=r(e,["cachedContent"]);t!==void 0&&S!=null&&l(t,["cachedContent"],Le(n,S));let x=r(e,["responseModalities"]);x!=null&&l(i,["responseModalities"],x);let P=r(e,["mediaResolution"]);P!=null&&l(i,["mediaResolution"],P);let $=r(e,["speechConfig"]);if($!=null&&l(i,["speechConfig"],Bo($)),r(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let R=r(e,["thinkingConfig"]);R!=null&&l(i,["thinkingConfig"],R);let L=r(e,["imageConfig"]);L!=null&&l(i,["imageConfig"],Id(L));let Y=r(e,["enableEnhancedCivicAnswers"]);return Y!=null&&l(i,["enableEnhancedCivicAnswers"],Y),i}p(gd,"generateContentConfigToMldev$1");function bd(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["candidates"]);if(i!=null){let d=i;Array.isArray(d)&&(d=d.map(u=>jc(u))),l(e,["candidates"],d)}let o=r(n,["modelVersion"]);o!=null&&l(e,["modelVersion"],o);let s=r(n,["promptFeedback"]);s!=null&&l(e,["promptFeedback"],s);let a=r(n,["responseId"]);a!=null&&l(e,["responseId"],a);let c=r(n,["usageMetadata"]);return c!=null&&l(e,["usageMetadata"],c),e}p(bd,"generateContentResponseFromMldev$1");function yd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Ct(n,i)),t}p(yd,"getBatchJobParametersToMldev");function Ed(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Ct(n,i)),t}p(Ed,"getBatchJobParametersToVertex");function wd(n){let e={};if(r(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=r(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}p(wd,"googleMapsToMldev$4");function vd(n){let e={};if(r(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(r(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=r(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}p(vd,"googleSearchToMldev$4");function Id(n){let e={},t=r(n,["aspectRatio"]);t!=null&&l(e,["aspectRatio"],t);let i=r(n,["imageSize"]);if(i!=null&&l(e,["imageSize"],i),r(n,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(r(n,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}p(Id,"imageConfigToMldev$1");function Td(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["request","model"],F(n,i));let o=r(e,["contents"]);if(o!=null){let c=Ie(o);Array.isArray(c)&&(c=c.map(d=>za(d))),l(t,["request","contents"],c)}let s=r(e,["metadata"]);s!=null&&l(t,["metadata"],s);let a=r(e,["config"]);return a!=null&&l(t,["request","generationConfig"],gd(n,a,r(t,["request"],{}))),t}p(Td,"inlinedRequestToMldev");function Cd(n){let e={},t=r(n,["response"]);t!=null&&l(e,["response"],bd(t));let i=r(n,["error"]);return i!=null&&l(e,["error"],i),e}p(Cd,"inlinedResponseFromMldev");function _d(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);if(e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),r(n,["filter"])!==void 0)throw new Error("filter parameter is not supported in Gemini API.");return t}p(_d,"listBatchJobsConfigToMldev");function Sd(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);e!==void 0&&o!=null&&l(e,["_query","pageToken"],o);let s=r(n,["filter"]);return e!==void 0&&s!=null&&l(e,["_query","filter"],s),t}p(Sd,"listBatchJobsConfigToVertex");function Ad(n){let e={},t=r(n,["config"]);return t!=null&&_d(t,e),e}p(Ad,"listBatchJobsParametersToMldev");function xd(n){let e={},t=r(n,["config"]);return t!=null&&Sd(t,e),e}p(xd,"listBatchJobsParametersToVertex");function Nd(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["operations"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>hn(a))),l(e,["batchJobs"],s)}return e}p(Nd,"listBatchJobsResponseFromMldev");function $d(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["batchPredictionJobs"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>no(a))),l(e,["batchJobs"],s)}return e}p($d,"listBatchJobsResponseFromVertex");function Pd(n){let e={},t=r(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let i=r(n,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=r(n,["executableCode"]);o!=null&&l(e,["executableCode"],o);let s=r(n,["fileData"]);s!=null&&l(e,["fileData"],pd(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],hd(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],Yc(d));let u=r(n,["text"]);u!=null&&l(e,["text"],u);let f=r(n,["thought"]);f!=null&&l(e,["thought"],f);let h=r(n,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=r(n,["videoMetadata"]);return m!=null&&l(e,["videoMetadata"],m),e}p(Pd,"partToMldev$4");function Rd(n){let e={},t=r(n,["category"]);if(t!=null&&l(e,["category"],t),r(n,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let i=r(n,["threshold"]);return i!=null&&l(e,["threshold"],i),e}p(Rd,"safetySettingToMldev$1");function Gd(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],md(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(Gd,"toolConfigToMldev$2");function Md(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let f=t;Array.isArray(f)&&(f=f.map(h=>h)),l(e,["functionDeclarations"],f)}if(r(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let i=r(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let o=r(n,["computerUse"]);o!=null&&l(e,["computerUse"],o);let s=r(n,["fileSearch"]);s!=null&&l(e,["fileSearch"],s);let a=r(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),r(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],wd(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],vd(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Md,"toolToMldev$4");var ke;(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"})(ke||(ke={}));var De=class{static{p(this,"Pager")}constructor(e,t,i,o){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,i,o)}init(e,t,i){var o,s;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=t?.sdkHttpResponse,this.idxInternal=0;let a={config:{}};!i||Object.keys(i).length===0?a={config:{}}:typeof i=="object"?a=Object.assign({},i):a=i,a.config&&(a.config.pageToken=t.nextPageToken),this.paramsInternal=a,this.pageInternalSize=(s=(o=a.config)===null||o===void 0?void 0:o.pageSize)!==null&&s!==void 0?s: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:p(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:p(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 io=class extends xe{static{p(this,"Batches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new De(ke.PAGED_ITEM_BATCH_JOBS,i=>this.listInternal(i),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=da(this.apiClient,e),i=t._url,o=_("{model}:batchGenerateContent",i),c=t.batch.inputConfig.requests,d=c.requests,u=[];for(let f of d){let h=Object.assign({},f);if(h.systemInstruction){let m=h.systemInstruction;delete h.systemInstruction;let g=h.request;g.systemInstruction=m,h.request=g}u.push(h)}return c.requests=u,delete t.config,delete t._url,delete t._query,{path:o,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 i=t?Object.assign({},t):{},o=Date.now().toString();if(i.displayName||(i.displayName=`genaiBatchJob_${o}`),i.dest===void 0){let s=this.getGcsUri(e),a=this.getBigqueryUri(e);if(s)s.endsWith(".jsonl")?i.dest=`${s.slice(0,-6)}/dest`:i.dest=`${s}_dest_${o}`;else if(a)i.dest=`${a}_dest_${o}`;else throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.")}return i}async createInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=id(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>no(f))}else{let u=da(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>hn(f))}}async createEmbeddingsInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=sd(this.apiClient,e);return s=_("{model}:asyncBatchEmbedContent",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>hn(d))}}async get(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Ed(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>no(f))}else{let u=yd(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>hn(f))}}async cancel(e){var t,i,o,s;let a="",c={};if(this.apiClient.isVertexAI()){let d=Zc(this.apiClient,e);a=_("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:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}else{let d=Qc(this.apiClient,e);a=_("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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal})}}async listInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=xd(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=$d(f),m=new xn;return Object.assign(m,h),m})}else{let u=Ad(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Nd(f),m=new xn;return Object.assign(m,h),m})}}async delete(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=ad(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>cd(f))}else{let u=rd(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>ld(f))}}};function kd(n){let e={},t=r(n,["data"]);if(t!=null&&l(e,["data"],t),r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(kd,"blobToMldev$3");function ua(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>ou(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(ua,"contentToMldev$3");function Dd(n,e){let t={},i=r(n,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=r(n,["expireTime"]);e!==void 0&&o!=null&&l(e,["expireTime"],o);let s=r(n,["displayName"]);e!==void 0&&s!=null&&l(e,["displayName"],s);let a=r(n,["contents"]);if(e!==void 0&&a!=null){let f=Ie(a);Array.isArray(f)&&(f=f.map(h=>ua(h))),l(e,["contents"],f)}let c=r(n,["systemInstruction"]);e!==void 0&&c!=null&&l(e,["systemInstruction"],ua(ce(c)));let d=r(n,["tools"]);if(e!==void 0&&d!=null){let f=d;Array.isArray(f)&&(f=f.map(h=>ru(h))),l(e,["tools"],f)}let u=r(n,["toolConfig"]);if(e!==void 0&&u!=null&&l(e,["toolConfig"],su(u)),r(n,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return t}p(Dd,"createCachedContentConfigToMldev");function Ld(n,e){let t={},i=r(n,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=r(n,["expireTime"]);e!==void 0&&o!=null&&l(e,["expireTime"],o);let s=r(n,["displayName"]);e!==void 0&&s!=null&&l(e,["displayName"],s);let a=r(n,["contents"]);if(e!==void 0&&a!=null){let h=Ie(a);Array.isArray(h)&&(h=h.map(m=>m)),l(e,["contents"],h)}let c=r(n,["systemInstruction"]);e!==void 0&&c!=null&&l(e,["systemInstruction"],ce(c));let d=r(n,["tools"]);if(e!==void 0&&d!=null){let h=d;Array.isArray(h)&&(h=h.map(m=>au(m))),l(e,["tools"],h)}let u=r(n,["toolConfig"]);e!==void 0&&u!=null&&l(e,["toolConfig"],u);let f=r(n,["kmsKeyName"]);return e!==void 0&&f!=null&&l(e,["encryption_spec","kmsKeyName"],f),t}p(Ld,"createCachedContentConfigToVertex");function Ud(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],Ga(n,i));let o=r(e,["config"]);return o!=null&&Dd(o,t),t}p(Ud,"createCachedContentParametersToMldev");function Fd(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],Ga(n,i));let o=r(e,["config"]);return o!=null&&Ld(o,t),t}p(Fd,"createCachedContentParametersToVertex");function Bd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Le(n,i)),t}p(Bd,"deleteCachedContentParametersToMldev");function Vd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Le(n,i)),t}p(Vd,"deleteCachedContentParametersToVertex");function qd(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(qd,"deleteCachedContentResponseFromMldev");function Hd(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Hd,"deleteCachedContentResponseFromVertex");function Od(n){let e={};if(r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=r(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(Od,"fileDataToMldev$3");function zd(n){let e={},t=r(n,["id"]);t!=null&&l(e,["id"],t);let i=r(n,["args"]);i!=null&&l(e,["args"],i);let o=r(n,["name"]);if(o!=null&&l(e,["name"],o),r(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(r(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}p(zd,"functionCallToMldev$3");function Kd(n){let e={},t=r(n,["mode"]);t!=null&&l(e,["mode"],t);let i=r(n,["allowedFunctionNames"]);if(i!=null&&l(e,["allowedFunctionNames"],i),r(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}p(Kd,"functionCallingConfigToMldev$1");function Jd(n){let e={};if(r(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=r(n,["description"]);t!=null&&l(e,["description"],t);let i=r(n,["name"]);i!=null&&l(e,["name"],i);let o=r(n,["parameters"]);o!=null&&l(e,["parameters"],o);let s=r(n,["parametersJsonSchema"]);s!=null&&l(e,["parametersJsonSchema"],s);let a=r(n,["response"]);a!=null&&l(e,["response"],a);let c=r(n,["responseJsonSchema"]);return c!=null&&l(e,["responseJsonSchema"],c),e}p(Jd,"functionDeclarationToVertex$2");function Wd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Le(n,i)),t}p(Wd,"getCachedContentParametersToMldev");function Xd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Le(n,i)),t}p(Xd,"getCachedContentParametersToVertex");function Yd(n){let e={};if(r(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=r(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}p(Yd,"googleMapsToMldev$3");function Qd(n){let e={};if(r(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(r(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=r(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}p(Qd,"googleSearchToMldev$3");function Zd(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),t}p(Zd,"listCachedContentsConfigToMldev");function jd(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),t}p(jd,"listCachedContentsConfigToVertex");function eu(n){let e={},t=r(n,["config"]);return t!=null&&Zd(t,e),e}p(eu,"listCachedContentsParametersToMldev");function tu(n){let e={},t=r(n,["config"]);return t!=null&&jd(t,e),e}p(tu,"listCachedContentsParametersToVertex");function nu(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["cachedContents"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["cachedContents"],s)}return e}p(nu,"listCachedContentsResponseFromMldev");function iu(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["cachedContents"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["cachedContents"],s)}return e}p(iu,"listCachedContentsResponseFromVertex");function ou(n){let e={},t=r(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let i=r(n,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=r(n,["executableCode"]);o!=null&&l(e,["executableCode"],o);let s=r(n,["fileData"]);s!=null&&l(e,["fileData"],Od(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],zd(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],kd(d));let u=r(n,["text"]);u!=null&&l(e,["text"],u);let f=r(n,["thought"]);f!=null&&l(e,["thought"],f);let h=r(n,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=r(n,["videoMetadata"]);return m!=null&&l(e,["videoMetadata"],m),e}p(ou,"partToMldev$3");function su(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],Kd(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(su,"toolConfigToMldev$1");function ru(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let f=t;Array.isArray(f)&&(f=f.map(h=>h)),l(e,["functionDeclarations"],f)}if(r(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let i=r(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let o=r(n,["computerUse"]);o!=null&&l(e,["computerUse"],o);let s=r(n,["fileSearch"]);s!=null&&l(e,["fileSearch"],s);let a=r(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),r(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],Yd(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],Qd(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(ru,"toolToMldev$3");function au(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>Jd(m))),l(e,["functionDeclarations"],h)}let i=r(n,["retrieval"]);i!=null&&l(e,["retrieval"],i);let o=r(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let s=r(n,["computerUse"]);if(s!=null&&l(e,["computerUse"],s),r(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let a=r(n,["codeExecution"]);a!=null&&l(e,["codeExecution"],a);let c=r(n,["enterpriseWebSearch"]);c!=null&&l(e,["enterpriseWebSearch"],c);let d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],d);let u=r(n,["googleSearch"]);u!=null&&l(e,["googleSearch"],u);let f=r(n,["urlContext"]);return f!=null&&l(e,["urlContext"],f),e}p(au,"toolToVertex$2");function lu(n,e){let t={},i=r(n,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=r(n,["expireTime"]);return e!==void 0&&o!=null&&l(e,["expireTime"],o),t}p(lu,"updateCachedContentConfigToMldev");function cu(n,e){let t={},i=r(n,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=r(n,["expireTime"]);return e!==void 0&&o!=null&&l(e,["expireTime"],o),t}p(cu,"updateCachedContentConfigToVertex");function du(n,e){let t={},i=r(e,["name"]);i!=null&&l(t,["_url","name"],Le(n,i));let o=r(e,["config"]);return o!=null&&lu(o,t),t}p(du,"updateCachedContentParametersToMldev");function uu(n,e){let t={},i=r(e,["name"]);i!=null&&l(t,["_url","name"],Le(n,i));let o=r(e,["config"]);return o!=null&&cu(o,t),t}p(uu,"updateCachedContentParametersToVertex");var oo=class extends xe{static{p(this,"Caches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new De(ke.PAGED_ITEM_CACHED_CONTENTS,i=>this.listInternal(i),await this.listInternal(t),t)}async create(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Fd(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let u=Ud(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async get(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Xd(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let u=Wd(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async delete(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Vd(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Hd(f),m=new Sn;return Object.assign(m,h),m})}else{let u=Bd(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=qd(f),m=new Sn;return Object.assign(m,h),m})}}async update(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=uu(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let u=du(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async listInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=tu(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=iu(f),m=new An;return Object.assign(m,h),m})}else{let u=eu(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=nu(f),m=new An;return Object.assign(m,h),m})}}};function $n(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,i=Object.getOwnPropertySymbols(n);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(n,i[o])&&(t[i[o]]=n[i[o]]);return t}p($n,"__rest");function fa(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:p(function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}},"next")};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}p(fa,"__values");function k(n){return this instanceof k?(this.v=n,this):new k(n)}p(k,"__await");function Se(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",a),o[Symbol.asyncIterator]=function(){return this},o;function a(g){return function(b){return Promise.resolve(b).then(g,h)}}function c(g,b){i[g]&&(o[g]=function(E){return new Promise(function(w,v){s.push([g,E,w,v])>1||d(g,E)})},b&&(o[g]=b(o[g])))}function d(g,b){try{u(i[g](b))}catch(E){m(s[0][3],E)}}function u(g){g.value instanceof k?Promise.resolve(g.value.v).then(f,h):m(s[0][2],g)}function f(g){d("next",g)}function h(g){d("throw",g)}function m(g,b){g(b),s.shift(),s.length&&d(s[0][0],s[0][1])}}p(Se,"__asyncGenerator");function Ae(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 fa=="function"?fa(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(a){return new Promise(function(c,d){a=n[s](a),o(c,d,a.done,a.value)})}}function o(s,a,c,d){Promise.resolve(d).then(function(u){s({value:u,done:c})},a)}}p(Ae,"__asyncValues");function fu(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:Ka(t)}p(fu,"isValidResponse");function Ka(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}p(Ka,"isValidContent");function pu(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}.`)}}p(pu,"validateHistory");function pa(n){if(n===void 0||n.length===0)return[];let e=[],t=n.length,i=0;for(;i<t;)if(n[i].role==="user")e.push(n[i]),i++;else{let o=[],s=!0;for(;i<t&&n[i].role==="model";)o.push(n[i]),s&&!Ka(n[i])&&(s=!1),i++;s?e.push(...o):e.pop()}return e}p(pa,"extractCuratedHistory");var so=class{static{p(this,"Chats")}constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new ro(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},ro=class{static{p(this,"Chat")}constructor(e,t,i,o={},s=[]){this.apiClient=e,this.modelsModule=t,this.model=i,this.config=o,this.history=s,this.sendPromise=Promise.resolve(),pu(s)}async sendMessage(e){var t;await this.sendPromise;let i=ce(e.message),o=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(i),config:(t=e.config)!==null&&t!==void 0?t:this.config});return this.sendPromise=(async()=>{var s,a,c;let d=await o,u=(a=(s=d.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content,f=d.automaticFunctionCallingHistory,h=this.getHistory(!0).length,m=[];f!=null&&(m=(c=f.slice(h))!==null&&c!==void 0?c:[]);let g=u?[u]:[];this.recordHistory(i,g,m)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),o}async sendMessageStream(e){var t;await this.sendPromise;let i=ce(e.message),o=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(i),config:(t=e.config)!==null&&t!==void 0?t:this.config});this.sendPromise=o.then(()=>{}).catch(()=>{});let s=await o;return this.processStreamResponse(s,i)}getHistory(e=!1){let t=e?pa(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return Se(this,arguments,p(function*(){var o,s,a,c,d,u;let f=[];try{for(var h=!0,m=Ae(e),g;g=yield k(m.next()),o=g.done,!o;h=!0){c=g.value,h=!1;let b=c;if(fu(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&&f.push(E)}yield yield k(b)}}catch(b){s={error:b}}finally{try{!h&&!o&&(a=m.return)&&(yield k(a.call(m)))}finally{if(s)throw s.error}}this.recordHistory(t,f)},"processStreamResponse_1"))}recordHistory(e,t,i){let o=[];t.length>0&&t.every(s=>s.role!==void 0)?o=t:o.push({role:"model",parts:[]}),i&&i.length>0?this.history.push(...pa(i)):this.history.push(e),this.history.push(...o)}};var Pn=class n extends Error{static{p(this,"ApiError")}constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,n.prototype)}};function hu(n){let e={},t=r(n,["file"]);return t!=null&&l(e,["file"],t),e}p(hu,"createFileParametersToMldev");function mu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(mu,"createFileResponseFromMldev");function gu(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","file"],Fa(t)),e}p(gu,"deleteFileParametersToMldev");function bu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(bu,"deleteFileResponseFromMldev");function yu(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","file"],Fa(t)),e}p(yu,"getFileParametersToMldev");function Eu(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),t}p(Eu,"listFilesConfigToMldev");function wu(n){let e={},t=r(n,["config"]);return t!=null&&Eu(t,e),e}p(wu,"listFilesParametersToMldev");function vu(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["files"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["files"],s)}return e}p(vu,"listFilesResponseFromMldev");var ao=class extends xe{static{p(this,"Files")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new De(ke.PAGED_ITEM_FILES,i=>this.listInternal(i),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,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=wu(e);return s=_("files",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>{let u=vu(d),f=new Xi;return Object.assign(f,u),f})}}async createInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=hu(e);return s=_("upload/v1beta/files",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=mu(d),f=new Yi;return Object.assign(f,u),f})}}async get(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=yu(e);return s=_("files/{file}",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>d)}}async delete(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=gu(e);return s=_("files/{file}",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>{let u=bu(d),f=new Qi;return Object.assign(f,u),f})}}};function mn(n){let e={},t=r(n,["data"]);if(t!=null&&l(e,["data"],t),r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(mn,"blobToMldev$2");function Iu(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>Uu(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(Iu,"contentToMldev$2");function Tu(n){let e={};if(r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=r(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(Tu,"fileDataToMldev$2");function Cu(n){let e={},t=r(n,["id"]);t!=null&&l(e,["id"],t);let i=r(n,["args"]);i!=null&&l(e,["args"],i);let o=r(n,["name"]);if(o!=null&&l(e,["name"],o),r(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(r(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}p(Cu,"functionCallToMldev$2");function _u(n){let e={};if(r(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=r(n,["description"]);t!=null&&l(e,["description"],t);let i=r(n,["name"]);i!=null&&l(e,["name"],i);let o=r(n,["parameters"]);o!=null&&l(e,["parameters"],o);let s=r(n,["parametersJsonSchema"]);s!=null&&l(e,["parametersJsonSchema"],s);let a=r(n,["response"]);a!=null&&l(e,["response"],a);let c=r(n,["responseJsonSchema"]);return c!=null&&l(e,["responseJsonSchema"],c),e}p(_u,"functionDeclarationToVertex$1");function Su(n){let e={},t=r(n,["modelSelectionConfig"]);t!=null&&l(e,["modelConfig"],t);let i=r(n,["responseJsonSchema"]);i!=null&&l(e,["responseJsonSchema"],i);let o=r(n,["audioTimestamp"]);o!=null&&l(e,["audioTimestamp"],o);let s=r(n,["candidateCount"]);s!=null&&l(e,["candidateCount"],s);let a=r(n,["enableAffectiveDialog"]);a!=null&&l(e,["enableAffectiveDialog"],a);let c=r(n,["frequencyPenalty"]);c!=null&&l(e,["frequencyPenalty"],c);let d=r(n,["logprobs"]);d!=null&&l(e,["logprobs"],d);let u=r(n,["maxOutputTokens"]);u!=null&&l(e,["maxOutputTokens"],u);let f=r(n,["mediaResolution"]);f!=null&&l(e,["mediaResolution"],f);let h=r(n,["presencePenalty"]);h!=null&&l(e,["presencePenalty"],h);let m=r(n,["responseLogprobs"]);m!=null&&l(e,["responseLogprobs"],m);let g=r(n,["responseMimeType"]);g!=null&&l(e,["responseMimeType"],g);let b=r(n,["responseModalities"]);b!=null&&l(e,["responseModalities"],b);let E=r(n,["responseSchema"]);E!=null&&l(e,["responseSchema"],E);let w=r(n,["routingConfig"]);w!=null&&l(e,["routingConfig"],w);let v=r(n,["seed"]);v!=null&&l(e,["seed"],v);let I=r(n,["speechConfig"]);I!=null&&l(e,["speechConfig"],Ja(I));let T=r(n,["stopSequences"]);T!=null&&l(e,["stopSequences"],T);let C=r(n,["temperature"]);C!=null&&l(e,["temperature"],C);let N=r(n,["thinkingConfig"]);N!=null&&l(e,["thinkingConfig"],N);let S=r(n,["topK"]);S!=null&&l(e,["topK"],S);let x=r(n,["topP"]);if(x!=null&&l(e,["topP"],x),r(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}p(Su,"generationConfigToVertex$1");function Au(n){let e={};if(r(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=r(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}p(Au,"googleMapsToMldev$2");function xu(n){let e={};if(r(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(r(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=r(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}p(xu,"googleSearchToMldev$2");function Nu(n,e){let t={},i=r(n,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],i);let o=r(n,["responseModalities"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","responseModalities"],o);let s=r(n,["temperature"]);e!==void 0&&s!=null&&l(e,["setup","generationConfig","temperature"],s);let a=r(n,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let c=r(n,["topK"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","topK"],c);let d=r(n,["maxOutputTokens"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","maxOutputTokens"],d);let u=r(n,["mediaResolution"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","mediaResolution"],u);let f=r(n,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let h=r(n,["speechConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","speechConfig"],Vo(h));let m=r(n,["thinkingConfig"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","thinkingConfig"],m);let g=r(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=r(n,["systemInstruction"]);e!==void 0&&b!=null&&l(e,["setup","systemInstruction"],Iu(ce(b)));let E=r(n,["tools"]);if(e!==void 0&&E!=null){let S=Tt(E);Array.isArray(S)&&(S=S.map(x=>Bu(It(x)))),l(e,["setup","tools"],S)}let w=r(n,["sessionResumption"]);e!==void 0&&w!=null&&l(e,["setup","sessionResumption"],Fu(w));let v=r(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&l(e,["setup","inputAudioTranscription"],v);let I=r(n,["outputAudioTranscription"]);e!==void 0&&I!=null&&l(e,["setup","outputAudioTranscription"],I);let T=r(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&l(e,["setup","realtimeInputConfig"],T);let C=r(n,["contextWindowCompression"]);e!==void 0&&C!=null&&l(e,["setup","contextWindowCompression"],C);let N=r(n,["proactivity"]);if(e!==void 0&&N!=null&&l(e,["setup","proactivity"],N),r(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}p(Nu,"liveConnectConfigToMldev$1");function $u(n,e){let t={},i=r(n,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],Su(i));let o=r(n,["responseModalities"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","responseModalities"],o);let s=r(n,["temperature"]);e!==void 0&&s!=null&&l(e,["setup","generationConfig","temperature"],s);let a=r(n,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let c=r(n,["topK"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","topK"],c);let d=r(n,["maxOutputTokens"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","maxOutputTokens"],d);let u=r(n,["mediaResolution"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","mediaResolution"],u);let f=r(n,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let h=r(n,["speechConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","speechConfig"],Ja(Vo(h)));let m=r(n,["thinkingConfig"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","thinkingConfig"],m);let g=r(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=r(n,["systemInstruction"]);e!==void 0&&b!=null&&l(e,["setup","systemInstruction"],ce(b));let E=r(n,["tools"]);if(e!==void 0&&E!=null){let x=Tt(E);Array.isArray(x)&&(x=x.map(P=>Vu(It(P)))),l(e,["setup","tools"],x)}let w=r(n,["sessionResumption"]);e!==void 0&&w!=null&&l(e,["setup","sessionResumption"],w);let v=r(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&l(e,["setup","inputAudioTranscription"],v);let I=r(n,["outputAudioTranscription"]);e!==void 0&&I!=null&&l(e,["setup","outputAudioTranscription"],I);let T=r(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&l(e,["setup","realtimeInputConfig"],T);let C=r(n,["contextWindowCompression"]);e!==void 0&&C!=null&&l(e,["setup","contextWindowCompression"],C);let N=r(n,["proactivity"]);e!==void 0&&N!=null&&l(e,["setup","proactivity"],N);let S=r(n,["explicitVadSignal"]);return e!==void 0&&S!=null&&l(e,["setup","explicitVadSignal"],S),t}p($u,"liveConnectConfigToVertex");function Pu(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],F(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],Nu(o,t)),t}p(Pu,"liveConnectParametersToMldev");function Ru(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],F(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],$u(o,t)),t}p(Ru,"liveConnectParametersToVertex");function Gu(n){let e={},t=r(n,["musicGenerationConfig"]);return t!=null&&l(e,["musicGenerationConfig"],t),e}p(Gu,"liveMusicSetConfigParametersToMldev");function Mu(n){let e={},t=r(n,["weightedPrompts"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>o)),l(e,["weightedPrompts"],i)}return e}p(Mu,"liveMusicSetWeightedPromptsParametersToMldev");function ku(n){let e={},t=r(n,["media"]);if(t!=null){let u=Ma(t);Array.isArray(u)&&(u=u.map(f=>mn(f))),l(e,["mediaChunks"],u)}let i=r(n,["audio"]);i!=null&&l(e,["audio"],mn(Da(i)));let o=r(n,["audioStreamEnd"]);o!=null&&l(e,["audioStreamEnd"],o);let s=r(n,["video"]);s!=null&&l(e,["video"],mn(ka(s)));let a=r(n,["text"]);a!=null&&l(e,["text"],a);let c=r(n,["activityStart"]);c!=null&&l(e,["activityStart"],c);let d=r(n,["activityEnd"]);return d!=null&&l(e,["activityEnd"],d),e}p(ku,"liveSendRealtimeInputParametersToMldev");function Du(n){let e={},t=r(n,["media"]);if(t!=null){let u=Ma(t);Array.isArray(u)&&(u=u.map(f=>f)),l(e,["mediaChunks"],u)}let i=r(n,["audio"]);i!=null&&l(e,["audio"],Da(i));let o=r(n,["audioStreamEnd"]);o!=null&&l(e,["audioStreamEnd"],o);let s=r(n,["video"]);s!=null&&l(e,["video"],ka(s));let a=r(n,["text"]);a!=null&&l(e,["text"],a);let c=r(n,["activityStart"]);c!=null&&l(e,["activityStart"],c);let d=r(n,["activityEnd"]);return d!=null&&l(e,["activityEnd"],d),e}p(Du,"liveSendRealtimeInputParametersToVertex");function Lu(n){let e={},t=r(n,["setupComplete"]);t!=null&&l(e,["setupComplete"],t);let i=r(n,["serverContent"]);i!=null&&l(e,["serverContent"],i);let o=r(n,["toolCall"]);o!=null&&l(e,["toolCall"],o);let s=r(n,["toolCallCancellation"]);s!=null&&l(e,["toolCallCancellation"],s);let a=r(n,["usageMetadata"]);a!=null&&l(e,["usageMetadata"],qu(a));let c=r(n,["goAway"]);c!=null&&l(e,["goAway"],c);let d=r(n,["sessionResumptionUpdate"]);d!=null&&l(e,["sessionResumptionUpdate"],d);let u=r(n,["voiceActivityDetectionSignal"]);return u!=null&&l(e,["voiceActivityDetectionSignal"],u),e}p(Lu,"liveServerMessageFromVertex");function Uu(n){let e={},t=r(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let i=r(n,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=r(n,["executableCode"]);o!=null&&l(e,["executableCode"],o);let s=r(n,["fileData"]);s!=null&&l(e,["fileData"],Tu(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],Cu(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],mn(d));let u=r(n,["text"]);u!=null&&l(e,["text"],u);let f=r(n,["thought"]);f!=null&&l(e,["thought"],f);let h=r(n,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=r(n,["videoMetadata"]);return m!=null&&l(e,["videoMetadata"],m),e}p(Uu,"partToMldev$2");function Fu(n){let e={},t=r(n,["handle"]);if(t!=null&&l(e,["handle"],t),r(n,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}p(Fu,"sessionResumptionConfigToMldev$1");function Ja(n){let e={},t=r(n,["voiceConfig"]);t!=null&&l(e,["voiceConfig"],t);let i=r(n,["languageCode"]);if(i!=null&&l(e,["languageCode"],i),r(n,["multiSpeakerVoiceConfig"])!==void 0)throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");return e}p(Ja,"speechConfigToVertex$1");function Bu(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let f=t;Array.isArray(f)&&(f=f.map(h=>h)),l(e,["functionDeclarations"],f)}if(r(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let i=r(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let o=r(n,["computerUse"]);o!=null&&l(e,["computerUse"],o);let s=r(n,["fileSearch"]);s!=null&&l(e,["fileSearch"],s);let a=r(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),r(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],Au(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],xu(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Bu,"toolToMldev$2");function Vu(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>_u(m))),l(e,["functionDeclarations"],h)}let i=r(n,["retrieval"]);i!=null&&l(e,["retrieval"],i);let o=r(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let s=r(n,["computerUse"]);if(s!=null&&l(e,["computerUse"],s),r(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let a=r(n,["codeExecution"]);a!=null&&l(e,["codeExecution"],a);let c=r(n,["enterpriseWebSearch"]);c!=null&&l(e,["enterpriseWebSearch"],c);let d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],d);let u=r(n,["googleSearch"]);u!=null&&l(e,["googleSearch"],u);let f=r(n,["urlContext"]);return f!=null&&l(e,["urlContext"],f),e}p(Vu,"toolToVertex$1");function qu(n){let e={},t=r(n,["promptTokenCount"]);t!=null&&l(e,["promptTokenCount"],t);let i=r(n,["cachedContentTokenCount"]);i!=null&&l(e,["cachedContentTokenCount"],i);let o=r(n,["candidatesTokenCount"]);o!=null&&l(e,["responseTokenCount"],o);let s=r(n,["toolUsePromptTokenCount"]);s!=null&&l(e,["toolUsePromptTokenCount"],s);let a=r(n,["thoughtsTokenCount"]);a!=null&&l(e,["thoughtsTokenCount"],a);let c=r(n,["totalTokenCount"]);c!=null&&l(e,["totalTokenCount"],c);let d=r(n,["promptTokensDetails"]);if(d!=null){let g=d;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["promptTokensDetails"],g)}let u=r(n,["cacheTokensDetails"]);if(u!=null){let g=u;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["cacheTokensDetails"],g)}let f=r(n,["candidatesTokensDetails"]);if(f!=null){let g=f;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["responseTokensDetails"],g)}let h=r(n,["toolUsePromptTokensDetails"]);if(h!=null){let g=h;Array.isArray(g)&&(g=g.map(b=>b)),l(e,["toolUsePromptTokensDetails"],g)}let m=r(n,["trafficType"]);return m!=null&&l(e,["trafficType"],m),e}p(qu,"usageMetadataFromVertex");function Hu(n){let e={},t=r(n,["data"]);if(t!=null&&l(e,["data"],t),r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(Hu,"blobToMldev$1");function Ou(n){let e={},t=r(n,["content"]);t!=null&&l(e,["content"],t);let i=r(n,["citationMetadata"]);i!=null&&l(e,["citationMetadata"],zu(i));let o=r(n,["tokenCount"]);o!=null&&l(e,["tokenCount"],o);let s=r(n,["finishReason"]);s!=null&&l(e,["finishReason"],s);let a=r(n,["avgLogprobs"]);a!=null&&l(e,["avgLogprobs"],a);let c=r(n,["groundingMetadata"]);c!=null&&l(e,["groundingMetadata"],c);let d=r(n,["index"]);d!=null&&l(e,["index"],d);let u=r(n,["logprobsResult"]);u!=null&&l(e,["logprobsResult"],u);let f=r(n,["safetyRatings"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(g=>g)),l(e,["safetyRatings"],m)}let h=r(n,["urlContextMetadata"]);return h!=null&&l(e,["urlContextMetadata"],h),e}p(Ou,"candidateFromMldev");function zu(n){let e={},t=r(n,["citationSources"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>o)),l(e,["citations"],i)}return e}p(zu,"citationMetadataFromMldev");function Ku(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["contents"]);if(o!=null){let s=Ie(o);Array.isArray(s)&&(s=s.map(a=>a)),l(t,["contents"],s)}return t}p(Ku,"computeTokensParametersToVertex");function Ju(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["tokensInfo"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>s)),l(e,["tokensInfo"],o)}return e}p(Ju,"computeTokensResponseFromVertex");function Wu(n){let e={},t=r(n,["values"]);t!=null&&l(e,["values"],t);let i=r(n,["statistics"]);return i!=null&&l(e,["statistics"],Xu(i)),e}p(Wu,"contentEmbeddingFromVertex");function Xu(n){let e={},t=r(n,["truncated"]);t!=null&&l(e,["truncated"],t);let i=r(n,["token_count"]);return i!=null&&l(e,["tokenCount"],i),e}p(Xu,"contentEmbeddingStatisticsFromVertex");function Jn(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>sp(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(Jn,"contentToMldev$1");function Yu(n){let e={},t=r(n,["controlType"]);t!=null&&l(e,["controlType"],t);let i=r(n,["enableControlImageComputation"]);return i!=null&&l(e,["computeControl"],i),e}p(Yu,"controlReferenceConfigToVertex");function Qu(n){let e={};if(r(n,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is not supported in Gemini API.");if(r(n,["tools"])!==void 0)throw new Error("tools parameter is not supported in Gemini API.");if(r(n,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is not supported in Gemini API.");return e}p(Qu,"countTokensConfigToMldev");function Zu(n,e){let t={},i=r(n,["systemInstruction"]);e!==void 0&&i!=null&&l(e,["systemInstruction"],ce(i));let o=r(n,["tools"]);if(e!==void 0&&o!=null){let a=o;Array.isArray(a)&&(a=a.map(c=>Za(c))),l(e,["tools"],a)}let s=r(n,["generationConfig"]);return e!==void 0&&s!=null&&l(e,["generationConfig"],Of(s)),t}p(Zu,"countTokensConfigToVertex");function ju(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["contents"]);if(o!=null){let a=Ie(o);Array.isArray(a)&&(a=a.map(c=>Jn(c))),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&Qu(s),t}p(ju,"countTokensParametersToMldev");function ef(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["contents"]);if(o!=null){let a=Ie(o);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&Zu(s,t),t}p(ef,"countTokensParametersToVertex");function tf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["totalTokens"]);i!=null&&l(e,["totalTokens"],i);let o=r(n,["cachedContentTokenCount"]);return o!=null&&l(e,["cachedContentTokenCount"],o),e}p(tf,"countTokensResponseFromMldev");function nf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["totalTokens"]);return i!=null&&l(e,["totalTokens"],i),e}p(nf,"countTokensResponseFromVertex");function of(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],F(n,i)),t}p(of,"deleteModelParametersToMldev");function sf(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],F(n,i)),t}p(sf,"deleteModelParametersToVertex");function rf(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(rf,"deleteModelResponseFromMldev");function af(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(af,"deleteModelResponseFromVertex");function lf(n,e){let t={},i=r(n,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=r(n,["negativePrompt"]);e!==void 0&&o!=null&&l(e,["parameters","negativePrompt"],o);let s=r(n,["numberOfImages"]);e!==void 0&&s!=null&&l(e,["parameters","sampleCount"],s);let a=r(n,["aspectRatio"]);e!==void 0&&a!=null&&l(e,["parameters","aspectRatio"],a);let c=r(n,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=r(n,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let u=r(n,["safetyFilterLevel"]);e!==void 0&&u!=null&&l(e,["parameters","safetySetting"],u);let f=r(n,["personGeneration"]);e!==void 0&&f!=null&&l(e,["parameters","personGeneration"],f);let h=r(n,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let m=r(n,["includeRaiReason"]);e!==void 0&&m!=null&&l(e,["parameters","includeRaiReason"],m);let g=r(n,["language"]);e!==void 0&&g!=null&&l(e,["parameters","language"],g);let b=r(n,["outputMimeType"]);e!==void 0&&b!=null&&l(e,["parameters","outputOptions","mimeType"],b);let E=r(n,["outputCompressionQuality"]);e!==void 0&&E!=null&&l(e,["parameters","outputOptions","compressionQuality"],E);let w=r(n,["addWatermark"]);e!==void 0&&w!=null&&l(e,["parameters","addWatermark"],w);let v=r(n,["labels"]);e!==void 0&&v!=null&&l(e,["labels"],v);let I=r(n,["editMode"]);e!==void 0&&I!=null&&l(e,["parameters","editMode"],I);let T=r(n,["baseSteps"]);return e!==void 0&&T!=null&&l(e,["parameters","editConfig","baseSteps"],T),t}p(lf,"editImageConfigToVertex");function cf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["referenceImages"]);if(s!=null){let c=s;Array.isArray(c)&&(c=c.map(d=>up(d))),l(t,["instances[0]","referenceImages"],c)}let a=r(e,["config"]);return a!=null&&lf(a,t),t}p(cf,"editImageParametersInternalToVertex");function df(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>Wn(s))),l(e,["generatedImages"],o)}return e}p(df,"editImageResponseFromVertex");function uf(n,e){let t={},i=r(n,["taskType"]);e!==void 0&&i!=null&&l(e,["requests[]","taskType"],i);let o=r(n,["title"]);e!==void 0&&o!=null&&l(e,["requests[]","title"],o);let s=r(n,["outputDimensionality"]);if(e!==void 0&&s!=null&&l(e,["requests[]","outputDimensionality"],s),r(n,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(r(n,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return t}p(uf,"embedContentConfigToMldev");function ff(n,e){let t={},i=r(n,["taskType"]);e!==void 0&&i!=null&&l(e,["instances[]","task_type"],i);let o=r(n,["title"]);e!==void 0&&o!=null&&l(e,["instances[]","title"],o);let s=r(n,["outputDimensionality"]);e!==void 0&&s!=null&&l(e,["parameters","outputDimensionality"],s);let a=r(n,["mimeType"]);e!==void 0&&a!=null&&l(e,["instances[]","mimeType"],a);let c=r(n,["autoTruncate"]);return e!==void 0&&c!=null&&l(e,["parameters","autoTruncate"],c),t}p(ff,"embedContentConfigToVertex");function pf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["contents"]);if(o!=null){let c=Uo(n,o);Array.isArray(c)&&(c=c.map(d=>d)),l(t,["requests[]","content"],c)}let s=r(e,["config"]);s!=null&&uf(s,t);let a=r(e,["model"]);return a!==void 0&&l(t,["requests[]","model"],F(n,a)),t}p(pf,"embedContentParametersToMldev");function hf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["contents"]);if(o!=null){let a=Uo(n,o);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["instances[]","content"],a)}let s=r(e,["config"]);return s!=null&&ff(s,t),t}p(hf,"embedContentParametersToVertex");function mf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["embeddings"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["embeddings"],s)}let o=r(n,["metadata"]);return o!=null&&l(e,["metadata"],o),e}p(mf,"embedContentResponseFromMldev");function gf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["predictions[]","embeddings"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>Wu(a))),l(e,["embeddings"],s)}let o=r(n,["metadata"]);return o!=null&&l(e,["metadata"],o),e}p(gf,"embedContentResponseFromVertex");function bf(n){let e={},t=r(n,["endpoint"]);t!=null&&l(e,["name"],t);let i=r(n,["deployedModelId"]);return i!=null&&l(e,["deployedModelId"],i),e}p(bf,"endpointFromVertex");function yf(n){let e={};if(r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=r(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(yf,"fileDataToMldev$1");function Ef(n){let e={},t=r(n,["id"]);t!=null&&l(e,["id"],t);let i=r(n,["args"]);i!=null&&l(e,["args"],i);let o=r(n,["name"]);if(o!=null&&l(e,["name"],o),r(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(r(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}p(Ef,"functionCallToMldev$1");function wf(n){let e={},t=r(n,["mode"]);t!=null&&l(e,["mode"],t);let i=r(n,["allowedFunctionNames"]);if(i!=null&&l(e,["allowedFunctionNames"],i),r(n,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}p(wf,"functionCallingConfigToMldev");function vf(n){let e={};if(r(n,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");let t=r(n,["description"]);t!=null&&l(e,["description"],t);let i=r(n,["name"]);i!=null&&l(e,["name"],i);let o=r(n,["parameters"]);o!=null&&l(e,["parameters"],o);let s=r(n,["parametersJsonSchema"]);s!=null&&l(e,["parametersJsonSchema"],s);let a=r(n,["response"]);a!=null&&l(e,["response"],a);let c=r(n,["responseJsonSchema"]);return c!=null&&l(e,["responseJsonSchema"],c),e}p(vf,"functionDeclarationToVertex");function If(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],Jn(ce(o)));let s=r(e,["temperature"]);s!=null&&l(i,["temperature"],s);let a=r(e,["topP"]);a!=null&&l(i,["topP"],a);let c=r(e,["topK"]);c!=null&&l(i,["topK"],c);let d=r(e,["candidateCount"]);d!=null&&l(i,["candidateCount"],d);let u=r(e,["maxOutputTokens"]);u!=null&&l(i,["maxOutputTokens"],u);let f=r(e,["stopSequences"]);f!=null&&l(i,["stopSequences"],f);let h=r(e,["responseLogprobs"]);h!=null&&l(i,["responseLogprobs"],h);let m=r(e,["logprobs"]);m!=null&&l(i,["logprobs"],m);let g=r(e,["presencePenalty"]);g!=null&&l(i,["presencePenalty"],g);let b=r(e,["frequencyPenalty"]);b!=null&&l(i,["frequencyPenalty"],b);let E=r(e,["seed"]);E!=null&&l(i,["seed"],E);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],Fo(v));let I=r(e,["responseJsonSchema"]);if(I!=null&&l(i,["responseJsonSchema"],I),r(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(r(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");let T=r(e,["safetySettings"]);if(t!==void 0&&T!=null){let V=T;Array.isArray(V)&&(V=V.map(he=>fp(he))),l(t,["safetySettings"],V)}let C=r(e,["tools"]);if(t!==void 0&&C!=null){let V=Tt(C);Array.isArray(V)&&(V=V.map(he=>Ep(It(he)))),l(t,["tools"],V)}let N=r(e,["toolConfig"]);if(t!==void 0&&N!=null&&l(t,["toolConfig"],yp(N)),r(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let S=r(e,["cachedContent"]);t!==void 0&&S!=null&&l(t,["cachedContent"],Le(n,S));let x=r(e,["responseModalities"]);x!=null&&l(i,["responseModalities"],x);let P=r(e,["mediaResolution"]);P!=null&&l(i,["mediaResolution"],P);let $=r(e,["speechConfig"]);if($!=null&&l(i,["speechConfig"],Bo($)),r(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let R=r(e,["thinkingConfig"]);R!=null&&l(i,["thinkingConfig"],R);let L=r(e,["imageConfig"]);L!=null&&l(i,["imageConfig"],Xf(L));let Y=r(e,["enableEnhancedCivicAnswers"]);return Y!=null&&l(i,["enableEnhancedCivicAnswers"],Y),i}p(If,"generateContentConfigToMldev");function Tf(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],ce(o));let s=r(e,["temperature"]);s!=null&&l(i,["temperature"],s);let a=r(e,["topP"]);a!=null&&l(i,["topP"],a);let c=r(e,["topK"]);c!=null&&l(i,["topK"],c);let d=r(e,["candidateCount"]);d!=null&&l(i,["candidateCount"],d);let u=r(e,["maxOutputTokens"]);u!=null&&l(i,["maxOutputTokens"],u);let f=r(e,["stopSequences"]);f!=null&&l(i,["stopSequences"],f);let h=r(e,["responseLogprobs"]);h!=null&&l(i,["responseLogprobs"],h);let m=r(e,["logprobs"]);m!=null&&l(i,["logprobs"],m);let g=r(e,["presencePenalty"]);g!=null&&l(i,["presencePenalty"],g);let b=r(e,["frequencyPenalty"]);b!=null&&l(i,["frequencyPenalty"],b);let E=r(e,["seed"]);E!=null&&l(i,["seed"],E);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],Fo(v));let I=r(e,["responseJsonSchema"]);I!=null&&l(i,["responseJsonSchema"],I);let T=r(e,["routingConfig"]);T!=null&&l(i,["routingConfig"],T);let C=r(e,["modelSelectionConfig"]);C!=null&&l(i,["modelConfig"],C);let N=r(e,["safetySettings"]);if(t!==void 0&&N!=null){let $e=N;Array.isArray($e)&&($e=$e.map(at=>at)),l(t,["safetySettings"],$e)}let S=r(e,["tools"]);if(t!==void 0&&S!=null){let $e=Tt(S);Array.isArray($e)&&($e=$e.map(at=>Za(It(at)))),l(t,["tools"],$e)}let x=r(e,["toolConfig"]);t!==void 0&&x!=null&&l(t,["toolConfig"],x);let P=r(e,["labels"]);t!==void 0&&P!=null&&l(t,["labels"],P);let $=r(e,["cachedContent"]);t!==void 0&&$!=null&&l(t,["cachedContent"],Le(n,$));let R=r(e,["responseModalities"]);R!=null&&l(i,["responseModalities"],R);let L=r(e,["mediaResolution"]);L!=null&&l(i,["mediaResolution"],L);let Y=r(e,["speechConfig"]);Y!=null&&l(i,["speechConfig"],Qa(Bo(Y)));let V=r(e,["audioTimestamp"]);V!=null&&l(i,["audioTimestamp"],V);let he=r(e,["thinkingConfig"]);he!=null&&l(i,["thinkingConfig"],he);let Ge=r(e,["imageConfig"]);if(Ge!=null&&l(i,["imageConfig"],Yf(Ge)),r(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return i}p(Tf,"generateContentConfigToVertex");function ha(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["contents"]);if(o!=null){let a=Ie(o);Array.isArray(a)&&(a=a.map(c=>Jn(c))),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&l(t,["generationConfig"],If(n,s,t)),t}p(ha,"generateContentParametersToMldev");function ma(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["contents"]);if(o!=null){let a=Ie(o);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&l(t,["generationConfig"],Tf(n,s,t)),t}p(ma,"generateContentParametersToVertex");function ga(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["candidates"]);if(i!=null){let d=i;Array.isArray(d)&&(d=d.map(u=>Ou(u))),l(e,["candidates"],d)}let o=r(n,["modelVersion"]);o!=null&&l(e,["modelVersion"],o);let s=r(n,["promptFeedback"]);s!=null&&l(e,["promptFeedback"],s);let a=r(n,["responseId"]);a!=null&&l(e,["responseId"],a);let c=r(n,["usageMetadata"]);return c!=null&&l(e,["usageMetadata"],c),e}p(ga,"generateContentResponseFromMldev");function ba(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["candidates"]);if(i!=null){let u=i;Array.isArray(u)&&(u=u.map(f=>f)),l(e,["candidates"],u)}let o=r(n,["createTime"]);o!=null&&l(e,["createTime"],o);let s=r(n,["modelVersion"]);s!=null&&l(e,["modelVersion"],s);let a=r(n,["promptFeedback"]);a!=null&&l(e,["promptFeedback"],a);let c=r(n,["responseId"]);c!=null&&l(e,["responseId"],c);let d=r(n,["usageMetadata"]);return d!=null&&l(e,["usageMetadata"],d),e}p(ba,"generateContentResponseFromVertex");function Cf(n,e){let t={};if(r(n,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(r(n,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is not supported in Gemini API.");let i=r(n,["numberOfImages"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=r(n,["aspectRatio"]);e!==void 0&&o!=null&&l(e,["parameters","aspectRatio"],o);let s=r(n,["guidanceScale"]);if(e!==void 0&&s!=null&&l(e,["parameters","guidanceScale"],s),r(n,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");let a=r(n,["safetyFilterLevel"]);e!==void 0&&a!=null&&l(e,["parameters","safetySetting"],a);let c=r(n,["personGeneration"]);e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c);let d=r(n,["includeSafetyAttributes"]);e!==void 0&&d!=null&&l(e,["parameters","includeSafetyAttributes"],d);let u=r(n,["includeRaiReason"]);e!==void 0&&u!=null&&l(e,["parameters","includeRaiReason"],u);let f=r(n,["language"]);e!==void 0&&f!=null&&l(e,["parameters","language"],f);let h=r(n,["outputMimeType"]);e!==void 0&&h!=null&&l(e,["parameters","outputOptions","mimeType"],h);let m=r(n,["outputCompressionQuality"]);if(e!==void 0&&m!=null&&l(e,["parameters","outputOptions","compressionQuality"],m),r(n,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is not supported in Gemini API.");if(r(n,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let g=r(n,["imageSize"]);if(e!==void 0&&g!=null&&l(e,["parameters","sampleImageSize"],g),r(n,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is not supported in Gemini API.");return t}p(Cf,"generateImagesConfigToMldev");function _f(n,e){let t={},i=r(n,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=r(n,["negativePrompt"]);e!==void 0&&o!=null&&l(e,["parameters","negativePrompt"],o);let s=r(n,["numberOfImages"]);e!==void 0&&s!=null&&l(e,["parameters","sampleCount"],s);let a=r(n,["aspectRatio"]);e!==void 0&&a!=null&&l(e,["parameters","aspectRatio"],a);let c=r(n,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=r(n,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let u=r(n,["safetyFilterLevel"]);e!==void 0&&u!=null&&l(e,["parameters","safetySetting"],u);let f=r(n,["personGeneration"]);e!==void 0&&f!=null&&l(e,["parameters","personGeneration"],f);let h=r(n,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let m=r(n,["includeRaiReason"]);e!==void 0&&m!=null&&l(e,["parameters","includeRaiReason"],m);let g=r(n,["language"]);e!==void 0&&g!=null&&l(e,["parameters","language"],g);let b=r(n,["outputMimeType"]);e!==void 0&&b!=null&&l(e,["parameters","outputOptions","mimeType"],b);let E=r(n,["outputCompressionQuality"]);e!==void 0&&E!=null&&l(e,["parameters","outputOptions","compressionQuality"],E);let w=r(n,["addWatermark"]);e!==void 0&&w!=null&&l(e,["parameters","addWatermark"],w);let v=r(n,["labels"]);e!==void 0&&v!=null&&l(e,["labels"],v);let I=r(n,["imageSize"]);e!==void 0&&I!=null&&l(e,["parameters","sampleImageSize"],I);let T=r(n,["enhancePrompt"]);return e!==void 0&&T!=null&&l(e,["parameters","enhancePrompt"],T),t}p(_f,"generateImagesConfigToVertex");function Sf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["config"]);return s!=null&&Cf(s,t),t}p(Sf,"generateImagesParametersToMldev");function Af(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["config"]);return s!=null&&_f(s,t),t}p(Af,"generateImagesParametersToVertex");function xf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>Bf(a))),l(e,["generatedImages"],s)}let o=r(n,["positivePromptSafetyAttributes"]);return o!=null&&l(e,["positivePromptSafetyAttributes"],Xa(o)),e}p(xf,"generateImagesResponseFromMldev");function Nf(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>Wn(a))),l(e,["generatedImages"],s)}let o=r(n,["positivePromptSafetyAttributes"]);return o!=null&&l(e,["positivePromptSafetyAttributes"],Ya(o)),e}p(Nf,"generateImagesResponseFromVertex");function $f(n,e){let t={},i=r(n,["numberOfVideos"]);if(e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i),r(n,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(r(n,["fps"])!==void 0)throw new Error("fps parameter is not supported in Gemini API.");let o=r(n,["durationSeconds"]);if(e!==void 0&&o!=null&&l(e,["parameters","durationSeconds"],o),r(n,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");let s=r(n,["aspectRatio"]);e!==void 0&&s!=null&&l(e,["parameters","aspectRatio"],s);let a=r(n,["resolution"]);e!==void 0&&a!=null&&l(e,["parameters","resolution"],a);let c=r(n,["personGeneration"]);if(e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c),r(n,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is not supported in Gemini API.");let d=r(n,["negativePrompt"]);e!==void 0&&d!=null&&l(e,["parameters","negativePrompt"],d);let u=r(n,["enhancePrompt"]);if(e!==void 0&&u!=null&&l(e,["parameters","enhancePrompt"],u),r(n,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is not supported in Gemini API.");let f=r(n,["lastFrame"]);e!==void 0&&f!=null&&l(e,["instances[0]","lastFrame"],Xn(f));let h=r(n,["referenceImages"]);if(e!==void 0&&h!=null){let m=h;Array.isArray(m)&&(m=m.map(g=>Rp(g))),l(e,["instances[0]","referenceImages"],m)}if(r(n,["mask"])!==void 0)throw new Error("mask parameter is not supported in Gemini API.");if(r(n,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is not supported in Gemini API.");return t}p($f,"generateVideosConfigToMldev");function Pf(n,e){let t={},i=r(n,["numberOfVideos"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=r(n,["outputGcsUri"]);e!==void 0&&o!=null&&l(e,["parameters","storageUri"],o);let s=r(n,["fps"]);e!==void 0&&s!=null&&l(e,["parameters","fps"],s);let a=r(n,["durationSeconds"]);e!==void 0&&a!=null&&l(e,["parameters","durationSeconds"],a);let c=r(n,["seed"]);e!==void 0&&c!=null&&l(e,["parameters","seed"],c);let d=r(n,["aspectRatio"]);e!==void 0&&d!=null&&l(e,["parameters","aspectRatio"],d);let u=r(n,["resolution"]);e!==void 0&&u!=null&&l(e,["parameters","resolution"],u);let f=r(n,["personGeneration"]);e!==void 0&&f!=null&&l(e,["parameters","personGeneration"],f);let h=r(n,["pubsubTopic"]);e!==void 0&&h!=null&&l(e,["parameters","pubsubTopic"],h);let m=r(n,["negativePrompt"]);e!==void 0&&m!=null&&l(e,["parameters","negativePrompt"],m);let g=r(n,["enhancePrompt"]);e!==void 0&&g!=null&&l(e,["parameters","enhancePrompt"],g);let b=r(n,["generateAudio"]);e!==void 0&&b!=null&&l(e,["parameters","generateAudio"],b);let E=r(n,["lastFrame"]);e!==void 0&&E!=null&&l(e,["instances[0]","lastFrame"],Ne(E));let w=r(n,["referenceImages"]);if(e!==void 0&&w!=null){let T=w;Array.isArray(T)&&(T=T.map(C=>Gp(C))),l(e,["instances[0]","referenceImages"],T)}let v=r(n,["mask"]);e!==void 0&&v!=null&&l(e,["instances[0]","mask"],Pp(v));let I=r(n,["compressionQuality"]);return e!==void 0&&I!=null&&l(e,["parameters","compressionQuality"],I),t}p(Pf,"generateVideosConfigToVertex");function Rf(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response","generateVideoResponse"]);return a!=null&&l(e,["response"],Df(a)),e}p(Rf,"generateVideosOperationFromMldev");function Gf(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response"]);return a!=null&&l(e,["response"],Lf(a)),e}p(Gf,"generateVideosOperationFromVertex");function Mf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["image"]);s!=null&&l(t,["instances[0]","image"],Xn(s));let a=r(e,["video"]);a!=null&&l(t,["instances[0]","video"],ja(a));let c=r(e,["source"]);c!=null&&Uf(c,t);let d=r(e,["config"]);return d!=null&&$f(d,t),t}p(Mf,"generateVideosParametersToMldev");function kf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["image"]);s!=null&&l(t,["instances[0]","image"],Ne(s));let a=r(e,["video"]);a!=null&&l(t,["instances[0]","video"],el(a));let c=r(e,["source"]);c!=null&&Ff(c,t);let d=r(e,["config"]);return d!=null&&Pf(d,t),t}p(kf,"generateVideosParametersToVertex");function Df(n){let e={},t=r(n,["generatedSamples"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>qf(a))),l(e,["generatedVideos"],s)}let i=r(n,["raiMediaFilteredCount"]);i!=null&&l(e,["raiMediaFilteredCount"],i);let o=r(n,["raiMediaFilteredReasons"]);return o!=null&&l(e,["raiMediaFilteredReasons"],o),e}p(Df,"generateVideosResponseFromMldev");function Lf(n){let e={},t=r(n,["videos"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>Hf(a))),l(e,["generatedVideos"],s)}let i=r(n,["raiMediaFilteredCount"]);i!=null&&l(e,["raiMediaFilteredCount"],i);let o=r(n,["raiMediaFilteredReasons"]);return o!=null&&l(e,["raiMediaFilteredReasons"],o),e}p(Lf,"generateVideosResponseFromVertex");function Uf(n,e){let t={},i=r(n,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=r(n,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],Xn(o));let s=r(n,["video"]);return e!==void 0&&s!=null&&l(e,["instances[0]","video"],ja(s)),t}p(Uf,"generateVideosSourceToMldev");function Ff(n,e){let t={},i=r(n,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=r(n,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],Ne(o));let s=r(n,["video"]);return e!==void 0&&s!=null&&l(e,["instances[0]","video"],el(s)),t}p(Ff,"generateVideosSourceToVertex");function Bf(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["image"],Qf(t));let i=r(n,["raiFilteredReason"]);i!=null&&l(e,["raiFilteredReason"],i);let o=r(n,["_self"]);return o!=null&&l(e,["safetyAttributes"],Xa(o)),e}p(Bf,"generatedImageFromMldev");function Wn(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["image"],Wa(t));let i=r(n,["raiFilteredReason"]);i!=null&&l(e,["raiFilteredReason"],i);let o=r(n,["_self"]);o!=null&&l(e,["safetyAttributes"],Ya(o));let s=r(n,["prompt"]);return s!=null&&l(e,["enhancedPrompt"],s),e}p(Wn,"generatedImageFromVertex");function Vf(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["mask"],Wa(t));let i=r(n,["labels"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>s)),l(e,["labels"],o)}return e}p(Vf,"generatedImageMaskFromVertex");function qf(n){let e={},t=r(n,["video"]);return t!=null&&l(e,["video"],Np(t)),e}p(qf,"generatedVideoFromMldev");function Hf(n){let e={},t=r(n,["_self"]);return t!=null&&l(e,["video"],$p(t)),e}p(Hf,"generatedVideoFromVertex");function Of(n){let e={},t=r(n,["modelSelectionConfig"]);t!=null&&l(e,["modelConfig"],t);let i=r(n,["responseJsonSchema"]);i!=null&&l(e,["responseJsonSchema"],i);let o=r(n,["audioTimestamp"]);o!=null&&l(e,["audioTimestamp"],o);let s=r(n,["candidateCount"]);s!=null&&l(e,["candidateCount"],s);let a=r(n,["enableAffectiveDialog"]);a!=null&&l(e,["enableAffectiveDialog"],a);let c=r(n,["frequencyPenalty"]);c!=null&&l(e,["frequencyPenalty"],c);let d=r(n,["logprobs"]);d!=null&&l(e,["logprobs"],d);let u=r(n,["maxOutputTokens"]);u!=null&&l(e,["maxOutputTokens"],u);let f=r(n,["mediaResolution"]);f!=null&&l(e,["mediaResolution"],f);let h=r(n,["presencePenalty"]);h!=null&&l(e,["presencePenalty"],h);let m=r(n,["responseLogprobs"]);m!=null&&l(e,["responseLogprobs"],m);let g=r(n,["responseMimeType"]);g!=null&&l(e,["responseMimeType"],g);let b=r(n,["responseModalities"]);b!=null&&l(e,["responseModalities"],b);let E=r(n,["responseSchema"]);E!=null&&l(e,["responseSchema"],E);let w=r(n,["routingConfig"]);w!=null&&l(e,["routingConfig"],w);let v=r(n,["seed"]);v!=null&&l(e,["seed"],v);let I=r(n,["speechConfig"]);I!=null&&l(e,["speechConfig"],Qa(I));let T=r(n,["stopSequences"]);T!=null&&l(e,["stopSequences"],T);let C=r(n,["temperature"]);C!=null&&l(e,["temperature"],C);let N=r(n,["thinkingConfig"]);N!=null&&l(e,["thinkingConfig"],N);let S=r(n,["topK"]);S!=null&&l(e,["topK"],S);let x=r(n,["topP"]);if(x!=null&&l(e,["topP"],x),r(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}p(Of,"generationConfigToVertex");function zf(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],F(n,i)),t}p(zf,"getModelParametersToMldev");function Kf(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],F(n,i)),t}p(Kf,"getModelParametersToVertex");function Jf(n){let e={};if(r(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=r(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}p(Jf,"googleMapsToMldev$1");function Wf(n){let e={};if(r(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(r(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=r(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}p(Wf,"googleSearchToMldev$1");function Xf(n){let e={},t=r(n,["aspectRatio"]);t!=null&&l(e,["aspectRatio"],t);let i=r(n,["imageSize"]);if(i!=null&&l(e,["imageSize"],i),r(n,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(r(n,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}p(Xf,"imageConfigToMldev");function Yf(n){let e={},t=r(n,["aspectRatio"]);t!=null&&l(e,["aspectRatio"],t);let i=r(n,["imageSize"]);i!=null&&l(e,["imageSize"],i);let o=r(n,["outputMimeType"]);o!=null&&l(e,["imageOutputOptions","mimeType"],o);let s=r(n,["outputCompressionQuality"]);return s!=null&&l(e,["imageOutputOptions","compressionQuality"],s),e}p(Yf,"imageConfigToVertex");function Qf(n){let e={},t=r(n,["bytesBase64Encoded"]);t!=null&&l(e,["imageBytes"],qe(t));let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(Qf,"imageFromMldev");function Wa(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["imageBytes"],qe(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(Wa,"imageFromVertex");function Xn(n){let e={};if(r(n,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");let t=r(n,["imageBytes"]);t!=null&&l(e,["bytesBase64Encoded"],qe(t));let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(Xn,"imageToMldev");function Ne(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["imageBytes"]);i!=null&&l(e,["bytesBase64Encoded"],qe(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(Ne,"imageToVertex");function Zf(n,e,t){let i={},o=r(e,["pageSize"]);t!==void 0&&o!=null&&l(t,["_query","pageSize"],o);let s=r(e,["pageToken"]);t!==void 0&&s!=null&&l(t,["_query","pageToken"],s);let a=r(e,["filter"]);t!==void 0&&a!=null&&l(t,["_query","filter"],a);let c=r(e,["queryBase"]);return t!==void 0&&c!=null&&l(t,["_url","models_url"],Ba(n,c)),i}p(Zf,"listModelsConfigToMldev");function jf(n,e,t){let i={},o=r(e,["pageSize"]);t!==void 0&&o!=null&&l(t,["_query","pageSize"],o);let s=r(e,["pageToken"]);t!==void 0&&s!=null&&l(t,["_query","pageToken"],s);let a=r(e,["filter"]);t!==void 0&&a!=null&&l(t,["_query","filter"],a);let c=r(e,["queryBase"]);return t!==void 0&&c!=null&&l(t,["_url","models_url"],Ba(n,c)),i}p(jf,"listModelsConfigToVertex");function ep(n,e){let t={},i=r(e,["config"]);return i!=null&&Zf(n,i,t),t}p(ep,"listModelsParametersToMldev");function tp(n,e){let t={},i=r(e,["config"]);return i!=null&&jf(n,i,t),t}p(tp,"listModelsParametersToVertex");function np(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["_self"]);if(o!=null){let s=Va(o);Array.isArray(s)&&(s=s.map(a=>lo(a))),l(e,["models"],s)}return e}p(np,"listModelsResponseFromMldev");function ip(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["_self"]);if(o!=null){let s=Va(o);Array.isArray(s)&&(s=s.map(a=>co(a))),l(e,["models"],s)}return e}p(ip,"listModelsResponseFromVertex");function op(n){let e={},t=r(n,["maskMode"]);t!=null&&l(e,["maskMode"],t);let i=r(n,["segmentationClasses"]);i!=null&&l(e,["maskClasses"],i);let o=r(n,["maskDilation"]);return o!=null&&l(e,["dilation"],o),e}p(op,"maskReferenceConfigToVertex");function lo(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["displayName"]);i!=null&&l(e,["displayName"],i);let o=r(n,["description"]);o!=null&&l(e,["description"],o);let s=r(n,["version"]);s!=null&&l(e,["version"],s);let a=r(n,["_self"]);a!=null&&l(e,["tunedModelInfo"],wp(a));let c=r(n,["inputTokenLimit"]);c!=null&&l(e,["inputTokenLimit"],c);let d=r(n,["outputTokenLimit"]);d!=null&&l(e,["outputTokenLimit"],d);let u=r(n,["supportedGenerationMethods"]);u!=null&&l(e,["supportedActions"],u);let f=r(n,["temperature"]);f!=null&&l(e,["temperature"],f);let h=r(n,["maxTemperature"]);h!=null&&l(e,["maxTemperature"],h);let m=r(n,["topP"]);m!=null&&l(e,["topP"],m);let g=r(n,["topK"]);g!=null&&l(e,["topK"],g);let b=r(n,["thinking"]);return b!=null&&l(e,["thinking"],b),e}p(lo,"modelFromMldev");function co(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["displayName"]);i!=null&&l(e,["displayName"],i);let o=r(n,["description"]);o!=null&&l(e,["description"],o);let s=r(n,["versionId"]);s!=null&&l(e,["version"],s);let a=r(n,["deployedModels"]);if(a!=null){let h=a;Array.isArray(h)&&(h=h.map(m=>bf(m))),l(e,["endpoints"],h)}let c=r(n,["labels"]);c!=null&&l(e,["labels"],c);let d=r(n,["_self"]);d!=null&&l(e,["tunedModelInfo"],vp(d));let u=r(n,["defaultCheckpointId"]);u!=null&&l(e,["defaultCheckpointId"],u);let f=r(n,["checkpoints"]);if(f!=null){let h=f;Array.isArray(h)&&(h=h.map(m=>m)),l(e,["checkpoints"],h)}return e}p(co,"modelFromVertex");function sp(n){let e={},t=r(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let i=r(n,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=r(n,["executableCode"]);o!=null&&l(e,["executableCode"],o);let s=r(n,["fileData"]);s!=null&&l(e,["fileData"],yf(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],Ef(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],Hu(d));let u=r(n,["text"]);u!=null&&l(e,["text"],u);let f=r(n,["thought"]);f!=null&&l(e,["thought"],f);let h=r(n,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=r(n,["videoMetadata"]);return m!=null&&l(e,["videoMetadata"],m),e}p(sp,"partToMldev$1");function rp(n){let e={},t=r(n,["productImage"]);return t!=null&&l(e,["image"],Ne(t)),e}p(rp,"productImageToVertex");function ap(n,e){let t={},i=r(n,["numberOfImages"]);e!==void 0&&i!=null&&l(e,["parameters","sampleCount"],i);let o=r(n,["baseSteps"]);e!==void 0&&o!=null&&l(e,["parameters","baseSteps"],o);let s=r(n,["outputGcsUri"]);e!==void 0&&s!=null&&l(e,["parameters","storageUri"],s);let a=r(n,["seed"]);e!==void 0&&a!=null&&l(e,["parameters","seed"],a);let c=r(n,["safetyFilterLevel"]);e!==void 0&&c!=null&&l(e,["parameters","safetySetting"],c);let d=r(n,["personGeneration"]);e!==void 0&&d!=null&&l(e,["parameters","personGeneration"],d);let u=r(n,["addWatermark"]);e!==void 0&&u!=null&&l(e,["parameters","addWatermark"],u);let f=r(n,["outputMimeType"]);e!==void 0&&f!=null&&l(e,["parameters","outputOptions","mimeType"],f);let h=r(n,["outputCompressionQuality"]);e!==void 0&&h!=null&&l(e,["parameters","outputOptions","compressionQuality"],h);let m=r(n,["enhancePrompt"]);e!==void 0&&m!=null&&l(e,["parameters","enhancePrompt"],m);let g=r(n,["labels"]);return e!==void 0&&g!=null&&l(e,["labels"],g),t}p(ap,"recontextImageConfigToVertex");function lp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["source"]);o!=null&&dp(o,t);let s=r(e,["config"]);return s!=null&&ap(s,t),t}p(lp,"recontextImageParametersToVertex");function cp(n){let e={},t=r(n,["predictions"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>Wn(o))),l(e,["generatedImages"],i)}return e}p(cp,"recontextImageResponseFromVertex");function dp(n,e){let t={},i=r(n,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=r(n,["personImage"]);e!==void 0&&o!=null&&l(e,["instances[0]","personImage","image"],Ne(o));let s=r(n,["productImages"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>rp(c))),l(e,["instances[0]","productImages"],a)}return t}p(dp,"recontextImageSourceToVertex");function up(n){let e={},t=r(n,["referenceImage"]);t!=null&&l(e,["referenceImage"],Ne(t));let i=r(n,["referenceId"]);i!=null&&l(e,["referenceId"],i);let o=r(n,["referenceType"]);o!=null&&l(e,["referenceType"],o);let s=r(n,["maskImageConfig"]);s!=null&&l(e,["maskImageConfig"],op(s));let a=r(n,["controlImageConfig"]);a!=null&&l(e,["controlImageConfig"],Yu(a));let c=r(n,["styleImageConfig"]);c!=null&&l(e,["styleImageConfig"],c);let d=r(n,["subjectImageConfig"]);return d!=null&&l(e,["subjectImageConfig"],d),e}p(up,"referenceImageAPIInternalToVertex");function Xa(n){let e={},t=r(n,["safetyAttributes","categories"]);t!=null&&l(e,["categories"],t);let i=r(n,["safetyAttributes","scores"]);i!=null&&l(e,["scores"],i);let o=r(n,["contentType"]);return o!=null&&l(e,["contentType"],o),e}p(Xa,"safetyAttributesFromMldev");function Ya(n){let e={},t=r(n,["safetyAttributes","categories"]);t!=null&&l(e,["categories"],t);let i=r(n,["safetyAttributes","scores"]);i!=null&&l(e,["scores"],i);let o=r(n,["contentType"]);return o!=null&&l(e,["contentType"],o),e}p(Ya,"safetyAttributesFromVertex");function fp(n){let e={},t=r(n,["category"]);if(t!=null&&l(e,["category"],t),r(n,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");let i=r(n,["threshold"]);return i!=null&&l(e,["threshold"],i),e}p(fp,"safetySettingToMldev");function pp(n){let e={},t=r(n,["image"]);return t!=null&&l(e,["image"],Ne(t)),e}p(pp,"scribbleImageToVertex");function hp(n,e){let t={},i=r(n,["mode"]);e!==void 0&&i!=null&&l(e,["parameters","mode"],i);let o=r(n,["maxPredictions"]);e!==void 0&&o!=null&&l(e,["parameters","maxPredictions"],o);let s=r(n,["confidenceThreshold"]);e!==void 0&&s!=null&&l(e,["parameters","confidenceThreshold"],s);let a=r(n,["maskDilation"]);e!==void 0&&a!=null&&l(e,["parameters","maskDilation"],a);let c=r(n,["binaryColorThreshold"]);e!==void 0&&c!=null&&l(e,["parameters","binaryColorThreshold"],c);let d=r(n,["labels"]);return e!==void 0&&d!=null&&l(e,["labels"],d),t}p(hp,"segmentImageConfigToVertex");function mp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["source"]);o!=null&&bp(o,t);let s=r(e,["config"]);return s!=null&&hp(s,t),t}p(mp,"segmentImageParametersToVertex");function gp(n){let e={},t=r(n,["predictions"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>Vf(o))),l(e,["generatedMasks"],i)}return e}p(gp,"segmentImageResponseFromVertex");function bp(n,e){let t={},i=r(n,["prompt"]);e!==void 0&&i!=null&&l(e,["instances[0]","prompt"],i);let o=r(n,["image"]);e!==void 0&&o!=null&&l(e,["instances[0]","image"],Ne(o));let s=r(n,["scribbleImage"]);return e!==void 0&&s!=null&&l(e,["instances[0]","scribble"],pp(s)),t}p(bp,"segmentImageSourceToVertex");function Qa(n){let e={},t=r(n,["voiceConfig"]);t!=null&&l(e,["voiceConfig"],t);let i=r(n,["languageCode"]);if(i!=null&&l(e,["languageCode"],i),r(n,["multiSpeakerVoiceConfig"])!==void 0)throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");return e}p(Qa,"speechConfigToVertex");function yp(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],wf(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(yp,"toolConfigToMldev");function Ep(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let f=t;Array.isArray(f)&&(f=f.map(h=>h)),l(e,["functionDeclarations"],f)}if(r(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let i=r(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let o=r(n,["computerUse"]);o!=null&&l(e,["computerUse"],o);let s=r(n,["fileSearch"]);s!=null&&l(e,["fileSearch"],s);let a=r(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),r(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],Jf(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],Wf(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Ep,"toolToMldev$1");function Za(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>vf(m))),l(e,["functionDeclarations"],h)}let i=r(n,["retrieval"]);i!=null&&l(e,["retrieval"],i);let o=r(n,["googleSearchRetrieval"]);o!=null&&l(e,["googleSearchRetrieval"],o);let s=r(n,["computerUse"]);if(s!=null&&l(e,["computerUse"],s),r(n,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");let a=r(n,["codeExecution"]);a!=null&&l(e,["codeExecution"],a);let c=r(n,["enterpriseWebSearch"]);c!=null&&l(e,["enterpriseWebSearch"],c);let d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],d);let u=r(n,["googleSearch"]);u!=null&&l(e,["googleSearch"],u);let f=r(n,["urlContext"]);return f!=null&&l(e,["urlContext"],f),e}p(Za,"toolToVertex");function wp(n){let e={},t=r(n,["baseModel"]);t!=null&&l(e,["baseModel"],t);let i=r(n,["createTime"]);i!=null&&l(e,["createTime"],i);let o=r(n,["updateTime"]);return o!=null&&l(e,["updateTime"],o),e}p(wp,"tunedModelInfoFromMldev");function vp(n){let e={},t=r(n,["labels","google-vertex-llm-tuning-base-model-id"]);t!=null&&l(e,["baseModel"],t);let i=r(n,["createTime"]);i!=null&&l(e,["createTime"],i);let o=r(n,["updateTime"]);return o!=null&&l(e,["updateTime"],o),e}p(vp,"tunedModelInfoFromVertex");function Ip(n,e){let t={},i=r(n,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=r(n,["description"]);e!==void 0&&o!=null&&l(e,["description"],o);let s=r(n,["defaultCheckpointId"]);return e!==void 0&&s!=null&&l(e,["defaultCheckpointId"],s),t}p(Ip,"updateModelConfigToMldev");function Tp(n,e){let t={},i=r(n,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=r(n,["description"]);e!==void 0&&o!=null&&l(e,["description"],o);let s=r(n,["defaultCheckpointId"]);return e!==void 0&&s!=null&&l(e,["defaultCheckpointId"],s),t}p(Tp,"updateModelConfigToVertex");function Cp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","name"],F(n,i));let o=r(e,["config"]);return o!=null&&Ip(o,t),t}p(Cp,"updateModelParametersToMldev");function _p(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["config"]);return o!=null&&Tp(o,t),t}p(_p,"updateModelParametersToVertex");function Sp(n,e){let t={},i=r(n,["outputGcsUri"]);e!==void 0&&i!=null&&l(e,["parameters","storageUri"],i);let o=r(n,["safetyFilterLevel"]);e!==void 0&&o!=null&&l(e,["parameters","safetySetting"],o);let s=r(n,["personGeneration"]);e!==void 0&&s!=null&&l(e,["parameters","personGeneration"],s);let a=r(n,["includeRaiReason"]);e!==void 0&&a!=null&&l(e,["parameters","includeRaiReason"],a);let c=r(n,["outputMimeType"]);e!==void 0&&c!=null&&l(e,["parameters","outputOptions","mimeType"],c);let d=r(n,["outputCompressionQuality"]);e!==void 0&&d!=null&&l(e,["parameters","outputOptions","compressionQuality"],d);let u=r(n,["enhanceInputImage"]);e!==void 0&&u!=null&&l(e,["parameters","upscaleConfig","enhanceInputImage"],u);let f=r(n,["imagePreservationFactor"]);e!==void 0&&f!=null&&l(e,["parameters","upscaleConfig","imagePreservationFactor"],f);let h=r(n,["labels"]);e!==void 0&&h!=null&&l(e,["labels"],h);let m=r(n,["numberOfImages"]);e!==void 0&&m!=null&&l(e,["parameters","sampleCount"],m);let g=r(n,["mode"]);return e!==void 0&&g!=null&&l(e,["parameters","mode"],g),t}p(Sp,"upscaleImageAPIConfigInternalToVertex");function Ap(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],F(n,i));let o=r(e,["image"]);o!=null&&l(t,["instances[0]","image"],Ne(o));let s=r(e,["upscaleFactor"]);s!=null&&l(t,["parameters","upscaleConfig","upscaleFactor"],s);let a=r(e,["config"]);return a!=null&&Sp(a,t),t}p(Ap,"upscaleImageAPIParametersInternalToVertex");function xp(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>Wn(s))),l(e,["generatedImages"],o)}return e}p(xp,"upscaleImageResponseFromVertex");function Np(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["encodedVideo"]);i!=null&&l(e,["videoBytes"],qe(i));let o=r(n,["encoding"]);return o!=null&&l(e,["mimeType"],o),e}p(Np,"videoFromMldev");function $p(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["uri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["videoBytes"],qe(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p($p,"videoFromVertex");function Pp(n){let e={},t=r(n,["image"]);t!=null&&l(e,["_self"],Ne(t));let i=r(n,["maskMode"]);return i!=null&&l(e,["maskMode"],i),e}p(Pp,"videoGenerationMaskToVertex");function Rp(n){let e={},t=r(n,["image"]);t!=null&&l(e,["image"],Xn(t));let i=r(n,["referenceType"]);return i!=null&&l(e,["referenceType"],i),e}p(Rp,"videoGenerationReferenceImageToMldev");function Gp(n){let e={},t=r(n,["image"]);t!=null&&l(e,["image"],Ne(t));let i=r(n,["referenceType"]);return i!=null&&l(e,["referenceType"],i),e}p(Gp,"videoGenerationReferenceImageToVertex");function ja(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["videoBytes"]);i!=null&&l(e,["encodedVideo"],qe(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["encoding"],o),e}p(ja,"videoToMldev");function el(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["videoBytes"]);i!=null&&l(e,["bytesBase64Encoded"],qe(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(el,"videoToVertex");function Mp(n,e){let t={},i=r(n,["displayName"]);return e!==void 0&&i!=null&&l(e,["displayName"],i),t}p(Mp,"createFileSearchStoreConfigToMldev");function kp(n){let e={},t=r(n,["config"]);return t!=null&&Mp(t,e),e}p(kp,"createFileSearchStoreParametersToMldev");function Dp(n,e){let t={},i=r(n,["force"]);return e!==void 0&&i!=null&&l(e,["_query","force"],i),t}p(Dp,"deleteFileSearchStoreConfigToMldev");function Lp(n){let e={},t=r(n,["name"]);t!=null&&l(e,["_url","name"],t);let i=r(n,["config"]);return i!=null&&Dp(i,e),e}p(Lp,"deleteFileSearchStoreParametersToMldev");function Up(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","name"],t),e}p(Up,"getFileSearchStoreParametersToMldev");function Fp(n,e){let t={},i=r(n,["customMetadata"]);if(e!==void 0&&i!=null){let s=i;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["customMetadata"],s)}let o=r(n,["chunkingConfig"]);return e!==void 0&&o!=null&&l(e,["chunkingConfig"],o),t}p(Fp,"importFileConfigToMldev");function Bp(n){let e={},t=r(n,["name"]);t!=null&&l(e,["name"],t);let i=r(n,["metadata"]);i!=null&&l(e,["metadata"],i);let o=r(n,["done"]);o!=null&&l(e,["done"],o);let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["response"]);return a!=null&&l(e,["response"],qp(a)),e}p(Bp,"importFileOperationFromMldev");function Vp(n){let e={},t=r(n,["fileSearchStoreName"]);t!=null&&l(e,["_url","file_search_store_name"],t);let i=r(n,["fileName"]);i!=null&&l(e,["fileName"],i);let o=r(n,["config"]);return o!=null&&Fp(o,e),e}p(Vp,"importFileParametersToMldev");function qp(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["parent"]);i!=null&&l(e,["parent"],i);let o=r(n,["documentName"]);return o!=null&&l(e,["documentName"],o),e}p(qp,"importFileResponseFromMldev");function Hp(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),t}p(Hp,"listFileSearchStoresConfigToMldev");function Op(n){let e={},t=r(n,["config"]);return t!=null&&Hp(t,e),e}p(Op,"listFileSearchStoresParametersToMldev");function zp(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["fileSearchStores"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["fileSearchStores"],s)}return e}p(zp,"listFileSearchStoresResponseFromMldev");function tl(n,e){let t={},i=r(n,["mimeType"]);e!==void 0&&i!=null&&l(e,["mimeType"],i);let o=r(n,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let s=r(n,["customMetadata"]);if(e!==void 0&&s!=null){let c=s;Array.isArray(c)&&(c=c.map(d=>d)),l(e,["customMetadata"],c)}let a=r(n,["chunkingConfig"]);return e!==void 0&&a!=null&&l(e,["chunkingConfig"],a),t}p(tl,"uploadToFileSearchStoreConfigToMldev");function Kp(n){let e={},t=r(n,["fileSearchStoreName"]);t!=null&&l(e,["_url","file_search_store_name"],t);let i=r(n,["config"]);return i!=null&&tl(i,e),e}p(Kp,"uploadToFileSearchStoreParametersToMldev");function Jp(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Jp,"uploadToFileSearchStoreResumableResponseFromMldev");var Wp="Content-Type",Xp="X-Server-Timeout",Yp="User-Agent",uo="x-goog-api-client",Qp="1.33.0",Zp=`google-genai-sdk/${Qp}`,jp="v1beta1",eh="v1beta",fo=class{static{p(this,"ApiClient")}constructor(e){var t,i;this.clientOptions=Object.assign(Object.assign({},e),{project:e.project,location:e.location,apiKey:e.apiKey,vertexai:e.vertexai});let o={};this.clientOptions.vertexai?(o.apiVersion=(t=this.clientOptions.apiVersion)!==null&&t!==void 0?t:jp,o.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(o.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:eh,o.baseUrl="https://generativelanguage.googleapis.com/"),o.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=o,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(o,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 i=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&i.push(e.apiVersion),i.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,i){let o=[this.getRequestUrlInternal(t)];return i&&o.push(this.getBaseResourcePath()),e!==""&&o.push(e),new URL(`${o.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 i=this.shouldPrependVertexProjectPath(e),o=this.constructUrl(e.path,t,i);if(e.queryParams)for(let[a,c]of Object.entries(e.queryParams))o.searchParams.append(a,String(c));let s={};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 s.body=e.body;return s=await this.includeExtraHttpOptionsToRequestInit(s,t,o.toString(),e.abortSignal),this.unaryApiCall(o,s,e.httpMethod)}patchHttpOptions(e,t){let i=JSON.parse(JSON.stringify(e));for(let[o,s]of Object.entries(t))typeof s=="object"?i[o]=Object.assign(Object.assign({},i[o]),s):s!==void 0&&(i[o]=s);return i}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let i=this.shouldPrependVertexProjectPath(e),o=this.constructUrl(e.path,t,i);(!o.searchParams.has("alt")||o.searchParams.get("alt")!=="sse")&&o.searchParams.set("alt","sse");let s={};return s.body=e.body,s=await this.includeExtraHttpOptionsToRequestInit(s,t,o.toString(),e.abortSignal),this.streamApiCall(o,s,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,t,i,o){if(t&&t.timeout||o){let s=new AbortController,a=s.signal;if(t.timeout&&t?.timeout>0){let c=setTimeout(()=>s.abort(),t.timeout);c&&typeof c.unref=="function"&&c.unref()}o&&o.addEventListener("abort",()=>{s.abort()}),e.signal=a}return t&&t.extraBody!==null&&th(e,t.extraBody),e.headers=await this.getHeadersInternal(t,i),e}async unaryApiCall(e,t,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:i})).then(async o=>(await ya(o),new kt(o))).catch(o=>{throw o instanceof Error?o:new Error(JSON.stringify(o))})}async streamApiCall(e,t,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:i})).then(async o=>(await ya(o),this.processStreamResponse(o))).catch(o=>{throw o instanceof Error?o:new Error(JSON.stringify(o))})}processStreamResponse(e){return Se(this,arguments,p(function*(){var i;let o=(i=e?.body)===null||i===void 0?void 0:i.getReader(),s=new TextDecoder("utf-8");if(!o)throw new Error("Response body is empty");try{let a="",c="data:",d=[`
|
|
667
667
|
|
|
668
668
|
`,"\r\r",`\r
|
|
669
669
|
\r
|
|
670
|
-
`];for(;;){let{done:u,value:f}=yield G(o.read());if(u){if(a.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let h=s.decode(f,{stream:!0});try{let b=JSON.parse(h);if("error"in b){let E=JSON.parse(JSON.stringify(b.error)),w=E.status,v=E.code,I=`got status: ${w}. ${JSON.stringify(b)}`;if(v>=400&&v<600)throw new Sn({message:I,status:v})}}catch(b){if(b.name==="ApiError")throw b}a+=h;let m=-1,g=0;for(;;){m=-1,g=0;for(let w of d){let v=a.indexOf(w);v!==-1&&(m===-1||v<m)&&(m=v,g=w.length)}if(m===-1)break;let b=a.substring(0,m);a=a.substring(m+g);let E=b.trim();if(E.startsWith(c)){let w=E.substring(c.length).trim();try{let v=new Response(w,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield G(new $t(v))}catch(v){throw new Error(`exception parsing stream chunk ${w}. ${v}`)}}}}}finally{o.releaseLock()}},"processStreamResponse_1"))}async apiCall(e,t){return fetch(e,t).catch(i=>{throw new Error(`exception ${i} sending request`)})}getDefaultHeaders(){let e={},t=Op+" "+this.clientOptions.userAgentExtra;return e[Hp]=t,e[oo]=t,e[Bp]="application/json",e}async getHeadersInternal(e,t){let i=new Headers;if(e&&e.headers){for(let[o,s]of Object.entries(e.headers))i.append(o,s);e.timeout&&e.timeout>0&&i.append(Vp,String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(i,t),i}getFileName(e){var t;let i="";return typeof e=="string"&&(i=e.replace(/[/\\]+$/,""),i=(t=i.split(/[/\\]/).pop())!==null&&t!==void 0?t:""),i}async uploadFile(e,t){var i;let o={};t!=null&&(o.mimeType=t.mimeType,o.name=t.name,o.displayName=t.displayName),o.name&&!o.name.startsWith("files/")&&(o.name=`files/${o.name}`);let s=this.clientOptions.uploader,a=await s.stat(e);o.sizeBytes=String(a.size);let c=(i=t?.mimeType)!==null&&i!==void 0?i:a.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");o.mimeType=c;let d={file:o},u=this.getFileName(e),f=_("upload/v1beta/files",d._url),h=await this.fetchUploadUrl(f,o.sizeBytes,o.mimeType,u,d,t?.httpOptions);return s.upload(e,h,this)}async uploadFileToFileSearchStore(e,t,i){var o;let s=this.clientOptions.uploader,a=await s.stat(t),c=String(a.size),d=(o=i?.mimeType)!==null&&o!==void 0?o: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`,f=this.getFileName(t),h={};i!=null&&Ja(i,h);let m=await this.fetchUploadUrl(u,c,d,f,h,i?.httpOptions);return s.uploadToFileSearchStore(t,m,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,t,i,o,s,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":`${i}`},o?{"X-Goog-Upload-File-Name":o}:{})};let u=await this.request({path:e,body:JSON.stringify(s),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 f=(c=u?.headers)===null||c===void 0?void 0:c["x-goog-upload-url"];if(f===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return f}};async function da(n){var e;if(n===void 0)throw new Error("response is undefined");if(!n.ok){let t=n.status,i;!((e=n.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?i=await n.json():i={error:{message:await n.text(),code:n.status,status:n.statusText}};let o=JSON.stringify(i);throw t>=400&&t<600?new Sn({message:o,status:t}):new Error(o)}}p(da,"throwErrorIfNotOK");function Jp(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 s=JSON.parse(n.body);if(typeof s=="object"&&s!==null&&!Array.isArray(s))t=s;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 i(s,a){let c=Object.assign({},s);for(let d in a)if(Object.prototype.hasOwnProperty.call(a,d)){let u=a[d],f=c[d];u&&typeof u=="object"&&!Array.isArray(u)&&f&&typeof f=="object"&&!Array.isArray(f)?c[d]=i(f,u):(f&&u&&typeof f!=typeof u&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${d}". Original type: ${typeof f}, New type: ${typeof u}. Overwriting.`),c[d]=u)}return c}p(i,"deepMerge");let o=i(t,e);n.body=JSON.stringify(o)}p(Jp,"includeExtraBodyToRequestInit");var Wp="mcp_used/unknown",Xp=!1;function Wa(n){for(let e of n)if(Yp(e)||typeof e=="object"&&"inputSchema"in e)return!0;return Xp}p(Wa,"hasMcpToolUsage");function Xa(n){var e;let t=(e=n[oo])!==null&&e!==void 0?e:"";n[oo]=(t+` ${Wp}`).trimStart()}p(Xa,"setMcpUsageHeader");function Yp(n){return n!==null&&typeof n=="object"&&n instanceof ro}p(Yp,"isMcpCallableTool");function Qp(n){return Ae(this,arguments,p(function*(t,i=100){let o,s=0;for(;s<i;){let a=yield G(t.listTools({cursor:o}));for(let c of a.tools)yield yield G(c),s++;if(!a.nextCursor)break;o=a.nextCursor}},"listAllTools_1"))}p(Qp,"listAllTools");var ro=class n{static{p(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,i,o;if(this.mcpTools.length>0)return;let s={},a=[];for(let f of this.mcpClients)try{for(var c=!0,d=(t=void 0,xe(Qp(f))),u;u=await d.next(),e=u.done,!e;c=!0){o=u.value,c=!1;let h=o;a.push(h);let m=h.name;if(s[m])throw new Error(`Duplicate function name ${m} found in MCP tools. Please ensure function names are unique.`);s[m]=f}}catch(h){t={error:h}}finally{try{!c&&!e&&(i=d.return)&&await i.call(d)}finally{if(t)throw t.error}}this.mcpTools=a,this.functionNameToMcpClient=s}async tool(){return await this.initialize(),Mc(this.mcpTools,this.config)}async callTool(e){await this.initialize();let t=[];for(let i of e)if(i.name in this.functionNameToMcpClient){let o=this.functionNameToMcpClient[i.name],s;this.config.timeout&&(s={timeout:this.config.timeout});let a=await o.callTool({name:i.name,arguments:i.args},void 0,s);t.push({functionResponse:{name:i.name,response:a.isError?{error:a}:a}})}return t}};async function Zp(n,e,t){let i=new Ji,o;t.data instanceof Blob?o=JSON.parse(await t.data.text()):o=JSON.parse(t.data),Object.assign(i,o),e(i)}p(Zp,"handleWebSocketMessage$1");var ao=class{static{p(this,"LiveMusic")}constructor(e,t,i){this.apiClient=e,this.auth=t,this.webSocketFactory=i}async connect(e){var t,i;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 o=this.apiClient.getWebsocketBaseUrl(),s=this.apiClient.getApiVersion(),a=eh(this.apiClient.getDefaultHeaders()),c=this.apiClient.getApiKey(),d=`${o}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${c}`,u=p(()=>{},"onopenResolve"),f=new Promise(T=>{u=T}),h=e.callbacks,m=p(function(){u({})},"onopenAwaitedCallback"),g=this.apiClient,b={onopen:m,onmessage:p(T=>{Zp(g,h.onmessage,T)},"onmessage"),onerror:(t=h?.onerror)!==null&&t!==void 0?t:function(T){},onclose:(i=h?.onclose)!==null&&i!==void 0?i:function(T){}},E=this.webSocketFactory.create(d,jp(a),b);E.connect(),await f;let I={setup:{model:U(this.apiClient,e.model)}};return E.send(JSON.stringify(I)),new lo(E,this.apiClient)}},lo=class{static{p(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=Su(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let t=_u(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){let t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(pt.PLAY)}pause(){this.sendPlaybackControl(pt.PAUSE)}stop(){this.sendPlaybackControl(pt.STOP)}resetContext(){this.sendPlaybackControl(pt.RESET_CONTEXT)}close(){this.conn.close()}};function jp(n){let e={};return n.forEach((t,i)=>{e[i]=t}),e}p(jp,"headersToMap$1");function eh(n){let e=new Headers;for(let[t,i]of Object.entries(n))e.append(t,i);return e}p(eh,"mapToHeaders$1");var th="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function nh(n,e,t){let i=new Ki,o;t.data instanceof Blob?o=await t.data.text():t.data instanceof ArrayBuffer?o=new TextDecoder().decode(t.data):o=t.data;let s=JSON.parse(o);if(n.isVertexAI()){let a=Nu(s);Object.assign(i,a)}else Object.assign(i,s);e(i)}p(nh,"handleWebSocketMessage");var co=class{static{p(this,"Live")}constructor(e,t,i){this.apiClient=e,this.auth=t,this.webSocketFactory=i,this.music=new ao(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,i,o,s,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(),f,h=this.apiClient.getHeaders();e.config&&e.config.tools&&Wa(e.config.tools)&&Xa(h);let m=sh(h);if(this.apiClient.isVertexAI())f=`${d}/ws/google.cloud.aiplatform.${u}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(m,f);else{let x=this.apiClient.getApiKey(),k="BidiGenerateContent",O="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."),k="BidiGenerateContentConstrained",O="access_token"),f=`${d}/ws/google.ai.generativelanguage.${u}.GenerativeService.${k}?${O}=${x}`}let g=p(()=>{},"onopenResolve"),b=new Promise(x=>{g=x}),E=e.callbacks,w=p(function(){var x;(x=E?.onopen)===null||x===void 0||x.call(E),g({})},"onopenAwaitedCallback"),v=this.apiClient,I={onopen:w,onmessage:p(x=>{nh(v,E.onmessage,x)},"onmessage"),onerror:(t=E?.onerror)!==null&&t!==void 0?t:function(x){},onclose:(i=E?.onclose)!==null&&i!==void 0?i:function(x){}},T=this.webSocketFactory.create(f,oh(m),I);T.connect(),await b;let S=U(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&S.startsWith("publishers/")){let x=this.apiClient.getProject(),k=this.apiClient.getLocation();S=`projects/${x}/locations/${k}/`+S}let N={};this.apiClient.isVertexAI()&&((o=e.config)===null||o===void 0?void 0:o.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[un.AUDIO]}:e.config.responseModalities=[un.AUDIO]),!((s=e.config)===null||s===void 0)&&s.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 $=(c=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&c!==void 0?c:[],A=[];for(let x of $)if(this.isCallableTool(x)){let k=x;A.push(await k.tool())}else A.push(x);A.length>0&&(e.config.tools=A);let P={model:S,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?N=Cu(this.apiClient,P):N=Tu(this.apiClient,P),delete N.config,T.send(JSON.stringify(N)),new uo(T,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},ih={turnComplete:!0},uo=class{static{p(this,"Session")}constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(t.turns!==null&&t.turns!==void 0){let i=[];try{i=Ie(t.turns),e.isVertexAI()||(i=i.map(o=>Hn(o)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:i,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let i=[];if(t.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(t.functionResponses)?i=t.functionResponses:i=[t.functionResponses],i.length===0)throw new Error("functionResponses is required.");for(let s of i){if(typeof s!="object"||s===null||!("name"in s)||!("response"in s))throw new Error(`Could not parse function response, type '${typeof s}'.`);if(!e.isVertexAI()&&!("id"in s))throw new Error(th)}return{toolResponse:{functionResponses:i}}}sendClientContent(e){e=Object.assign(Object.assign({},ih),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};this.apiClient.isVertexAI()?t={realtimeInput:xu(e)}:t={realtimeInput:Au(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 oh(n){let e={};return n.forEach((t,i)=>{e[i]=t}),e}p(oh,"headersToMap");function sh(n){let e=new Headers;for(let[t,i]of Object.entries(n))e.append(t,i);return e}p(sh,"mapToHeaders");var ua=10;function fa(n){var e,t,i;if(!((e=n?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let o=!1;for(let a of(t=n?.tools)!==null&&t!==void 0?t:[])if(mt(a)){o=!0;break}if(!o)return!0;let s=(i=n?.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls;return s&&(s<0||!Number.isInteger(s))||s==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:",s),!0):!1}p(fa,"shouldDisableAfc");function mt(n){return"callTool"in n&&typeof n.callTool=="function"}p(mt,"isCallableTool");function rh(n){var e,t,i;return(i=(t=(e=n.config)===null||e===void 0?void 0:e.tools)===null||t===void 0?void 0:t.some(o=>mt(o)))!==null&&i!==void 0?i:!1}p(rh,"hasCallableTools");function pa(n){var e;let t=[];return!((e=n?.config)===null||e===void 0)&&e.tools&&n.config.tools.forEach((i,o)=>{if(mt(i))return;let s=i;s.functionDeclarations&&s.functionDeclarations.length>0&&t.push(o)}),t}p(pa,"findAfcIncompatibleToolIndexes");function ha(n){var e;return!(!((e=n?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}p(ha,"shouldAppendAfcHistory");var fo=class extends Ne{static{p(this,"Models")}constructor(e){super(),this.apiClient=e,this.generateContent=async t=>{var i,o,s,a,c;let d=await this.processParamsMaybeAddMcpUsage(t);if(this.maybeMoveToResponseJsonSchem(t),!rh(t)||fa(t.config))return await this.generateContentInternal(d);let u=pa(t);if(u.length>0){let E=u.map(w=>`tools[${w}]`).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 f,h,m=Ie(d.contents),g=(s=(o=(i=d.config)===null||i===void 0?void 0:i.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&s!==void 0?s:ua,b=0;for(;b<g&&(f=await this.generateContentInternal(d),!(!f.functionCalls||f.functionCalls.length===0));){let E=f.candidates[0].content,w=[];for(let v of(c=(a=t.config)===null||a===void 0?void 0:a.tools)!==null&&c!==void 0?c:[])if(mt(v)){let T=await v.callTool(f.functionCalls);w.push(...T)}b++,h={role:"user",parts:w},d.contents=Ie(d.contents),d.contents.push(E),d.contents.push(h),ha(d.config)&&(m.push(E),m.push(h))}return ha(d.config)&&(f.automaticFunctionCallingHistory=m),f},this.generateContentStream=async t=>{var i,o,s,a,c;if(this.maybeMoveToResponseJsonSchem(t),fa(t.config)){let h=await this.processParamsMaybeAddMcpUsage(t);return await this.generateContentStreamInternal(h)}let d=pa(t);if(d.length>0){let h=d.map(m=>`tools[${m}]`).join(", ");throw new Error(`Incompatible tools found at ${h}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let u=(s=(o=(i=t?.config)===null||i===void 0?void 0:i.toolConfig)===null||o===void 0?void 0:o.functionCallingConfig)===null||s===void 0?void 0:s.streamFunctionCallArguments,f=(c=(a=t?.config)===null||a===void 0?void 0:a.automaticFunctionCalling)===null||c===void 0?void 0:c.disable;if(u&&!f)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(i=>{var o;let s,a=[];if(i?.generatedImages)for(let d of i.generatedImages)d&&d?.safetyAttributes&&((o=d?.safetyAttributes)===null||o===void 0?void 0:o.contentType)==="Positive Prompt"?s=d?.safetyAttributes:a.push(d);let c;return s?c={generatedImages:a,positivePromptSafetyAttributes:s,sdkHttpResponse:i.sdkHttpResponse}:c={generatedImages:a,sdkHttpResponse:i.sdkHttpResponse},c}),this.list=async t=>{var i;let a={config:Object.assign(Object.assign({},{queryBase:!0}),t?.config)};if(this.apiClient.isVertexAI()&&!a.config.queryBase){if(!((i=a.config)===null||i===void 0)&&i.filter)throw new Error("Filtering tuned models list for Vertex AI is not currently supported");a.config.filter="labels.tune-type:*"}return new De(Me.PAGED_ITEM_MODELS,c=>this.listInternal(c),await this.listInternal(a),a)},this.editImage=async t=>{let i={model:t.model,prompt:t.prompt,referenceImages:[],config:t.config};return t.referenceImages&&t.referenceImages&&(i.referenceImages=t.referenceImages.map(o=>o.toReferenceImageAPI())),await this.editImageInternal(i)},this.upscaleImage=async t=>{let i={numberOfImages:1,mode:"upscale"};t.config&&(i=Object.assign(Object.assign({},i),t.config));let o={model:t.model,image:t.image,upscaleFactor:t.upscaleFactor,config:i};return await this.upscaleImageInternal(o)},this.generateVideos=async t=>{var i,o,s,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()||(!((i=t.video)===null||i===void 0)&&i.uri&&(!((o=t.video)===null||o===void 0)&&o.videoBytes)?t.video={uri:t.video.uri,mimeType:t.video.mimeType}:!((a=(s=t.source)===null||s===void 0?void 0:s.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,i,o;let s=(t=e.config)===null||t===void 0?void 0:t.tools;if(!s)return e;let a=await Promise.all(s.map(async d=>mt(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=(o=(i=e.config.httpOptions)===null||i===void 0?void 0:i.headers)!==null&&o!==void 0?o:{},u=Object.assign({},d);Object.keys(u).length===0&&(u=this.apiClient.getDefaultHeaders()),Xa(u),c.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:u})}return c}async initAfcToolsMap(e){var t,i,o;let s=new Map;for(let a of(i=(t=e.config)===null||t===void 0?void 0:t.tools)!==null&&i!==void 0?i:[])if(mt(a)){let c=a,d=await c.tool();for(let u of(o=d.functionDeclarations)!==null&&o!==void 0?o:[]){if(!u.name)throw new Error("Function declaration name is required.");if(s.has(u.name))throw new Error(`Duplicate tool declaration name: ${u.name}`);s.set(u.name,c)}}return s}async processAfcStream(e){var t,i,o;let s=(o=(i=(t=e.config)===null||t===void 0?void 0:t.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&o!==void 0?o:ua,a=!1,c=0,d=await this.initAfcToolsMap(e);return function(u,f,h){return Ae(this,arguments,function*(){for(var m,g,b,E,w,v;c<s;){a&&(c++,a=!1);let N=yield G(u.processParamsMaybeAddMcpUsage(h)),$=yield G(u.generateContentStreamInternal(N)),A=[],P=[];try{for(var I=!0,T=(g=void 0,xe($)),S;S=yield G(T.next()),m=S.done,!m;I=!0){E=S.value,I=!1;let x=E;if(yield yield G(x),x.candidates&&(!((w=x.candidates[0])===null||w===void 0)&&w.content)){P.push(x.candidates[0].content);for(let k of(v=x.candidates[0].content.parts)!==null&&v!==void 0?v:[])if(c<s&&k.functionCall){if(!k.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has(k.functionCall.name)){let O=yield G(f.get(k.functionCall.name).callTool([k.functionCall]));A.push(...O)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${f.keys()}, mising tool: ${k.functionCall.name}`)}}}}catch(x){g={error:x}}finally{try{!I&&!m&&(b=T.return)&&(yield G(b.call(T)))}finally{if(g)throw g.error}}if(A.length>0){a=!0;let x=new tt;x.candidates=[{content:{role:"user",parts:A}}],yield yield G(x);let k=[];k.push(...P),k.push({role:"user",parts:A});let O=Ie(h.contents).concat(k);h.contents=O}else break}})}(this,d,e)}async generateContentInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=aa(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=ca(f),m=new tt;return Object.assign(m,h),m})}else{let u=ra(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=la(f),m=new tt;return Object.assign(m,h),m})}}async generateContentStreamInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=aa(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}),a.then(function(h){return Ae(this,arguments,function*(){var m,g,b,E;try{for(var w=!0,v=xe(h),I;I=yield G(v.next()),m=I.done,!m;w=!0){E=I.value,w=!1;let T=E,S=ca(yield G(T.json()));S.sdkHttpResponse={headers:T.headers};let N=new tt;Object.assign(N,S),yield yield G(N)}}catch(T){g={error:T}}finally{try{!w&&!m&&(b=v.return)&&(yield G(b.call(v)))}finally{if(g)throw g.error}}})})}else{let u=ra(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}),a.then(function(h){return Ae(this,arguments,function*(){var m,g,b,E;try{for(var w=!0,v=xe(h),I;I=yield G(v.next()),m=I.done,!m;w=!0){E=I.value,w=!1;let T=E,S=la(yield G(T.json()));S.sdkHttpResponse={headers:T.headers};let N=new tt;Object.assign(N,S),yield yield G(N)}}catch(T){g={error:T}}finally{try{!w&&!m&&(b=v.return)&&(yield G(b.call(v)))}finally{if(g)throw g.error}}})})}}async embedContent(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=rf(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=lf(f),m=new pn;return Object.assign(m,h),m})}else{let u=sf(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=af(f),m=new pn;return Object.assign(m,h),m})}}async generateImagesInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Ef(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=vf(f),m=new hn;return Object.assign(m,h),m})}else{let u=yf(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=wf(f),m=new hn;return Object.assign(m,h),m})}}async editImageInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=ef(this.apiClient,e);return s=_("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>{let u=tf(d),f=new Mi;return Object.assign(f,u),f})}else throw new Error("This method is only supported by the Vertex AI.")}async upscaleImageInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=Ep(this.apiClient,e);return s=_("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>{let u=wp(d),f=new Di;return Object.assign(f,u),f})}else throw new Error("This method is only supported by the Vertex AI.")}async recontextImage(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=ep(this.apiClient,e);return s=_("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=tp(d),f=new ki;return Object.assign(f,u),f})}else throw new Error("This method is only supported by the Vertex AI.")}async segmentImage(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=ap(this.apiClient,e);return s=_("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=lp(d),f=new Li;return Object.assign(f,u),f})}else throw new Error("This method is only supported by the Vertex AI.")}async get(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Uf(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>io(f))}else{let u=Lf(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>no(f))}}async listInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Jf(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Xf(f),m=new mn;return Object.assign(m,h),m})}else{let u=Kf(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Wf(f),m=new mn;return Object.assign(m,h),m})}}async update(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=bp(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>io(f))}else{let u=gp(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>no(f))}}async delete(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Yu(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Zu(f),m=new gn;return Object.assign(m,h),m})}else{let u=Xu(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Qu(f),m=new gn;return Object.assign(m,h),m})}}async countTokens(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Ku(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Wu(f),m=new bn;return Object.assign(m,h),m})}else{let u=zu(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Ju(f),m=new bn;return Object.assign(m,h),m})}}async computeTokens(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=Uu(this.apiClient,e);return s=_("{model}:computeTokens",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>{let u=Fu(d),f=new Ui;return Object.assign(f,u),f})}else throw new Error("This method is only supported by the Vertex AI.")}async generateVideosInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Af(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>{let h=_f(f),m=new yn;return Object.assign(m,h),m})}else{let u=Sf(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>{let h=Cf(f),m=new yn;return Object.assign(m,h),m})}}};var po=class extends Ne{static{p(this,"Operations")}constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let t=e.operation,i=e.config;if(t.name===void 0||t.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let o=t.name.split("/operations/")[0],s;i&&"httpOptions"in i&&(s=i.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:o,config:{httpOptions:s}});return t._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let o=await this.getVideosOperationInternal({operationName:t.name,config:i});return t._fromAPIResponse({apiResponse:o,_isVertexAI:!1})}}async get(e){let t=e.operation,i=e.config;if(t.name===void 0||t.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let o=t.name.split("/operations/")[0],s;i&&"httpOptions"in i&&(s=i.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:o,config:{httpOptions:s}});return t._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let o=await this.getVideosOperationInternal({operationName:t.name,config:i});return t._fromAPIResponse({apiResponse:o,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=vc(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a}else{let u=wc(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a}}async fetchPredictVideosOperationInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=pc(e);return s=_("{resourceName}:fetchPredictOperation",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o}else throw new Error("This method is only supported by the Vertex AI.")}};function ah(n){let e={},t=r(n,["data"]);if(t!=null&&l(e,["data"],t),r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(ah,"blobToMldev");function lh(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>bh(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(lh,"contentToMldev");function ch(n,e,t){let i={},o=r(e,["expireTime"]);t!==void 0&&o!=null&&l(t,["expireTime"],o);let s=r(e,["newSessionExpireTime"]);t!==void 0&&s!=null&&l(t,["newSessionExpireTime"],s);let a=r(e,["uses"]);t!==void 0&&a!=null&&l(t,["uses"],a);let c=r(e,["liveConnectConstraints"]);t!==void 0&&c!=null&&l(t,["bidiGenerateContentSetup"],gh(n,c));let d=r(e,["lockAdditionalFields"]);return t!==void 0&&d!=null&&l(t,["fieldMask"],d),i}p(ch,"createAuthTokenConfigToMldev");function dh(n,e){let t={},i=r(e,["config"]);return i!=null&&l(t,["config"],ch(n,i,t)),t}p(dh,"createAuthTokenParametersToMldev");function uh(n){let e={};if(r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=r(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(uh,"fileDataToMldev");function fh(n){let e={},t=r(n,["id"]);t!=null&&l(e,["id"],t);let i=r(n,["args"]);i!=null&&l(e,["args"],i);let o=r(n,["name"]);if(o!=null&&l(e,["name"],o),r(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(r(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}p(fh,"functionCallToMldev");function ph(n){let e={};if(r(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=r(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}p(ph,"googleMapsToMldev");function hh(n){let e={};if(r(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(r(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=r(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}p(hh,"googleSearchToMldev");function mh(n,e){let t={},i=r(n,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],i);let o=r(n,["responseModalities"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","responseModalities"],o);let s=r(n,["temperature"]);e!==void 0&&s!=null&&l(e,["setup","generationConfig","temperature"],s);let a=r(n,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let c=r(n,["topK"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","topK"],c);let d=r(n,["maxOutputTokens"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","maxOutputTokens"],d);let u=r(n,["mediaResolution"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","mediaResolution"],u);let f=r(n,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let h=r(n,["speechConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","speechConfig"],Do(h));let m=r(n,["thinkingConfig"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","thinkingConfig"],m);let g=r(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=r(n,["systemInstruction"]);e!==void 0&&b!=null&&l(e,["setup","systemInstruction"],lh(le(b)));let E=r(n,["tools"]);if(e!==void 0&&E!=null){let $=Et(E);Array.isArray($)&&($=$.map(A=>Eh(yt(A)))),l(e,["setup","tools"],$)}let w=r(n,["sessionResumption"]);e!==void 0&&w!=null&&l(e,["setup","sessionResumption"],yh(w));let v=r(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&l(e,["setup","inputAudioTranscription"],v);let I=r(n,["outputAudioTranscription"]);e!==void 0&&I!=null&&l(e,["setup","outputAudioTranscription"],I);let T=r(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&l(e,["setup","realtimeInputConfig"],T);let S=r(n,["contextWindowCompression"]);e!==void 0&&S!=null&&l(e,["setup","contextWindowCompression"],S);let N=r(n,["proactivity"]);if(e!==void 0&&N!=null&&l(e,["setup","proactivity"],N),r(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}p(mh,"liveConnectConfigToMldev");function gh(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],U(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],mh(o,t)),t}p(gh,"liveConnectConstraintsToMldev");function bh(n){let e={},t=r(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let i=r(n,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=r(n,["executableCode"]);o!=null&&l(e,["executableCode"],o);let s=r(n,["fileData"]);s!=null&&l(e,["fileData"],uh(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],fh(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],ah(d));let u=r(n,["text"]);u!=null&&l(e,["text"],u);let f=r(n,["thought"]);f!=null&&l(e,["thought"],f);let h=r(n,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=r(n,["videoMetadata"]);return m!=null&&l(e,["videoMetadata"],m),e}p(bh,"partToMldev");function yh(n){let e={},t=r(n,["handle"]);if(t!=null&&l(e,["handle"],t),r(n,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}p(yh,"sessionResumptionConfigToMldev");function Eh(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let f=t;Array.isArray(f)&&(f=f.map(h=>h)),l(e,["functionDeclarations"],f)}if(r(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let i=r(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let o=r(n,["computerUse"]);o!=null&&l(e,["computerUse"],o);let s=r(n,["fileSearch"]);s!=null&&l(e,["fileSearch"],s);let a=r(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),r(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],ph(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],hh(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Eh,"toolToMldev");function wh(n){let e=[];for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){let i=n[t];if(typeof i=="object"&&i!=null&&Object.keys(i).length>0){let o=Object.keys(i).map(s=>`${t}.${s}`);e.push(...o)}else e.push(t)}return e.join(",")}p(wh,"getFieldMasks");function vh(n,e){let t=null,i=n.bidiGenerateContentSetup;if(typeof i=="object"&&i!==null&&"setup"in i){let s=i.setup;typeof s=="object"&&s!==null?(n.bidiGenerateContentSetup=s,t=s):delete n.bidiGenerateContentSetup}else i!==void 0&&delete n.bidiGenerateContentSetup;let o=n.fieldMask;if(t){let s=wh(t);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)s?n.fieldMask=s:delete n.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&o!==null&&Array.isArray(o)&&o.length>0){let a=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],c=[];o.length>0&&(c=o.map(u=>a.includes(u)?`generationConfig.${u}`:u));let d=[];s&&d.push(s),c.length>0&&d.push(...c),d.length>0?n.fieldMask=d.join(","):delete n.fieldMask}else delete n.fieldMask}else o!==null&&Array.isArray(o)&&o.length>0?n.fieldMask=o.join(","):delete n.fieldMask;return n}p(vh,"convertBidiSetupToTokenSetup");var ho=class extends Ne{static{p(this,"Tokens")}constructor(e){super(),this.apiClient=e}async create(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let c=dh(this.apiClient,e);s=_("auth_tokens",c._url),a=c._query,delete c.config,delete c._url,delete c._query;let d=vh(c,e.config);return o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(u=>u.json()),o.then(u=>u)}}};function Ih(n,e){let t={},i=r(n,["force"]);return e!==void 0&&i!=null&&l(e,["_query","force"],i),t}p(Ih,"deleteDocumentConfigToMldev");function Th(n){let e={},t=r(n,["name"]);t!=null&&l(e,["_url","name"],t);let i=r(n,["config"]);return i!=null&&Ih(i,e),e}p(Th,"deleteDocumentParametersToMldev");function Ch(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","name"],t),e}p(Ch,"getDocumentParametersToMldev");function _h(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),t}p(_h,"listDocumentsConfigToMldev");function Sh(n){let e={},t=r(n,["parent"]);t!=null&&l(e,["_url","parent"],t);let i=r(n,["config"]);return i!=null&&_h(i,e),e}p(Sh,"listDocumentsParametersToMldev");function Ah(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["documents"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["documents"],s)}return e}p(Ah,"listDocumentsResponseFromMldev");var mo=class extends Ne{static{p(this,"Documents")}constructor(e){super(),this.apiClient=e,this.list=async t=>new De(Me.PAGED_ITEM_DOCUMENTS,i=>this.listInternal({parent:t.parent,config:i.config}),await this.listInternal(t),t)}async get(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Ch(e);return s=_("{name}",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>d)}}async delete(e){var t,i;let o="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Th(e);o=_("{name}",a._url),s=a._query,delete a._url,delete a._query,await this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}}async listInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Sh(e);return s=_("{parent}/documents",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=Ah(d),f=new Fi;return Object.assign(f,u),f})}}};var go=class extends Ne{static{p(this,"FileSearchStores")}constructor(e,t=new mo(e)){super(),this.apiClient=e,this.documents=t,this.list=async(i={})=>new De(Me.PAGED_ITEM_FILE_SEARCH_STORES,o=>this.listInternal(o),await this.listInternal(i),i)}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,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Ap(e);return s=_("fileSearchStores",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>d)}}async get(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=$p(e);return s=_("{name}",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>d)}}async delete(e){var t,i;let o="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Np(e);o=_("{name}",a._url),s=a._query,delete a._url,delete a._query,await this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}}async listInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=kp(e);return s=_("fileSearchStores",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=Lp(d),f=new Bi;return Object.assign(f,u),f})}}async uploadToFileSearchStoreInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Up(e);return s=_("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=Fp(d),f=new Vi;return Object.assign(f,u),f})}}async importFile(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Gp(e);return s=_("{file_search_store_name}:importFile",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=Rp(d),f=new Hi;return Object.assign(f,u),f})}}};var Ya=p(function(){let{crypto:n}=globalThis;if(n?.randomUUID)return Ya=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,i=>(+i^t()&15>>+i/4).toString(16))},"uuid4Internal"),xh=p(()=>Ya(),"uuid4");function bo(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}p(bo,"isAbortError");var yo=p(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 me=class extends Error{static{p(this,"GeminiNextGenAPIClientError")}},ge=class n extends me{static{p(this,"APIError")}constructor(e,t,i,o){super(`${n.makeMessage(e,t,i)}`),this.status=e,this.headers=o,this.error=t}static makeMessage(e,t,i){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):i;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,i,o){if(!e||!o)return new gt({message:i,cause:yo(t)});let s=t;return e===400?new xn(e,s,i,o):e===401?new Nn(e,s,i,o):e===403?new $n(e,s,i,o):e===404?new Pn(e,s,i,o):e===409?new Rn(e,s,i,o):e===422?new Gn(e,s,i,o):e===429?new Mn(e,s,i,o):e>=500?new Dn(e,s,i,o):new n(e,s,i,o)}},Pt=class extends ge{static{p(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},gt=class extends ge{static{p(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},An=class extends gt{static{p(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},xn=class extends ge{static{p(this,"BadRequestError")}},Nn=class extends ge{static{p(this,"AuthenticationError")}},$n=class extends ge{static{p(this,"PermissionDeniedError")}},Pn=class extends ge{static{p(this,"NotFoundError")}},Rn=class extends ge{static{p(this,"ConflictError")}},Gn=class extends ge{static{p(this,"UnprocessableEntityError")}},Mn=class extends ge{static{p(this,"RateLimitError")}},Dn=class extends ge{static{p(this,"InternalServerError")}};var Nh=/^[a-z][a-z0-9+.-]*:/i,$h=p(n=>Nh.test(n),"isAbsoluteURL"),Eo=p(n=>(Eo=Array.isArray,Eo(n)),"isArrayInternal"),Ph=Eo,Rh=Ph,ma=Rh;function Gh(n){if(!n)return!0;for(let e in n)return!1;return!0}p(Gh,"isEmptyObj");function Mh(n,e){return Object.prototype.hasOwnProperty.call(n,e)}p(Mh,"hasOwn");var Dh=p((n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new me(`${n} must be an integer`);if(e<0)throw new me(`${n} must be a positive integer`);return e},"validatePositiveInteger"),kh=p(n=>{try{return JSON.parse(n)}catch{return}},"safeJSON");var Lh=p(n=>new Promise(e=>setTimeout(e,n)),"sleep$1");var ft="0.0.1";function Uh(){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"}p(Uh,"getDetectedPlatform");var Fh=p(()=>{var n,e,t,i,o;let s=Uh();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ft,"X-Stainless-OS":ba(Deno.build.os),"X-Stainless-Arch":ga(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":ft,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ft,"X-Stainless-OS":ba((t=globalThis.process.platform)!==null&&t!==void 0?t:"unknown"),"X-Stainless-Arch":ga((i=globalThis.process.arch)!==null&&i!==void 0?i:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(o=globalThis.process.version)!==null&&o!==void 0?o:"unknown"};let a=Bh();return a?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ft,"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":ft,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Bh(){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 i=t.exec(navigator.userAgent);if(i){let o=i[1]||0,s=i[2]||0,a=i[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}p(Bh,"getBrowserInfo");var ga=p(n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown","normalizeArch"),ba=p(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"),on,Vh=p(()=>on??(on=Fh()),"getPlatformHeaders");function Hh(){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`")}p(Hh,"getDefaultFetch");function Qa(...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)}p(Qa,"makeReadableStream");function qh(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Qa({start(){},async pull(t){let{done:i,value:o}=await e.next();i?t.close():t.enqueue(o)},async cancel(){var t;await((t=e.return)===null||t===void 0?void 0:t.call(e))}})}p(qh,"ReadableStreamFrom");function Za(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}}}p(Za,"ReadableStreamToAsyncIterable");async function Oh(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 i=n.getReader(),o=i.cancel();i.releaseLock(),await o}p(Oh,"CancelReadableStream");var zh=p(({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var ja=p(()=>{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 Ni(n,e,t){return ja(),new File(n,e??"unknown_file",t)}p(Ni,"makeFile");function Kh(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}p(Kh,"getName");var Jh=p(n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function","isAsyncIterable");var el=p(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"),Wh=p(n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&el(n),"isFileLike"),Xh=p(n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function","isResponseLike");async function Yh(n,e,t){if(ja(),n=await n,Wh(n))return n instanceof File?n:Ni([await n.arrayBuffer()],n.name);if(Xh(n)){let o=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),Ni(await wo(o),e,t)}let i=await wo(n);if(e||(e=Kh(n)),!t?.type){let o=i.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(t=Object.assign(Object.assign({},t),{type:o}))}return Ni(i,e,t)}p(Yh,"toFile");async function wo(n){var e,t,i,o,s;let a=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)a.push(n);else if(el(n))a.push(n instanceof Blob?n:await n.arrayBuffer());else if(Jh(n))try{for(var c=!0,d=xe(n),u;u=await d.next(),e=u.done,!e;c=!0){o=u.value,c=!1;let f=o;a.push(...await wo(f))}}catch(f){t={error:f}}finally{try{!c&&!e&&(i=d.return)&&await i.call(d)}finally{if(t)throw t.error}}else{let f=(s=n?.constructor)===null||s===void 0?void 0:s.name;throw new Error(`Unexpected data type: ${typeof n}${f?`; constructor: ${f}`:""}${Qh(n)}`)}return a}p(wo,"getBytes");function Qh(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}p(Qh,"propsForError");var kn=class{static{p(this,"APIResource")}constructor(e){this._client=e}};kn._key=[];function tl(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}p(tl,"encodeURIPath");var ya=Object.freeze(Object.create(null)),Zh=p((n=tl)=>p(function(t,...i){if(t.length===1)return t[0];let o=!1,s=[],a=t.reduce((f,h,m)=>{var g,b,E;/[?#]/.test(h)&&(o=!0);let w=i[m],v=(o?encodeURIComponent:n)(""+w);return m!==i.length&&(w==null||typeof w=="object"&&w.toString===((E=Object.getPrototypeOf((b=Object.getPrototypeOf((g=w.hasOwnProperty)!==null&&g!==void 0?g:ya))!==null&&b!==void 0?b:ya))===null||E===void 0?void 0:E.toString))&&(v=w+"",s.push({start:f.length+h.length,length:v.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`})),f+h+(m===i.length?"":v)},""),c=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=d.exec(c))!==null;)s.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(s.sort((f,h)=>f.start-h.start),s.length>0){let f=0,h=s.reduce((m,g)=>{let b=" ".repeat(g.start-f),E="^".repeat(g.length);return f=g.start+g.length,m+b+E},"");throw new me(`Path parameters result in path with invalid segments:
|
|
670
|
+
`];for(;;){let{done:u,value:f}=yield k(o.read());if(u){if(a.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let h=s.decode(f,{stream:!0});try{let b=JSON.parse(h);if("error"in b){let E=JSON.parse(JSON.stringify(b.error)),w=E.status,v=E.code,I=`got status: ${w}. ${JSON.stringify(b)}`;if(v>=400&&v<600)throw new Pn({message:I,status:v})}}catch(b){if(b.name==="ApiError")throw b}a+=h;let m=-1,g=0;for(;;){m=-1,g=0;for(let w of d){let v=a.indexOf(w);v!==-1&&(m===-1||v<m)&&(m=v,g=w.length)}if(m===-1)break;let b=a.substring(0,m);a=a.substring(m+g);let E=b.trim();if(E.startsWith(c)){let w=E.substring(c.length).trim();try{let v=new Response(w,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield k(new kt(v))}catch(v){throw new Error(`exception parsing stream chunk ${w}. ${v}`)}}}}}finally{o.releaseLock()}},"processStreamResponse_1"))}async apiCall(e,t){return fetch(e,t).catch(i=>{throw new Error(`exception ${i} sending request`)})}getDefaultHeaders(){let e={},t=Zp+" "+this.clientOptions.userAgentExtra;return e[Yp]=t,e[uo]=t,e[Wp]="application/json",e}async getHeadersInternal(e,t){let i=new Headers;if(e&&e.headers){for(let[o,s]of Object.entries(e.headers))i.append(o,s);e.timeout&&e.timeout>0&&i.append(Xp,String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(i,t),i}getFileName(e){var t;let i="";return typeof e=="string"&&(i=e.replace(/[/\\]+$/,""),i=(t=i.split(/[/\\]/).pop())!==null&&t!==void 0?t:""),i}async uploadFile(e,t){var i;let o={};t!=null&&(o.mimeType=t.mimeType,o.name=t.name,o.displayName=t.displayName),o.name&&!o.name.startsWith("files/")&&(o.name=`files/${o.name}`);let s=this.clientOptions.uploader,a=await s.stat(e);o.sizeBytes=String(a.size);let c=(i=t?.mimeType)!==null&&i!==void 0?i:a.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");o.mimeType=c;let d={file:o},u=this.getFileName(e),f=_("upload/v1beta/files",d._url),h=await this.fetchUploadUrl(f,o.sizeBytes,o.mimeType,u,d,t?.httpOptions);return s.upload(e,h,this)}async uploadFileToFileSearchStore(e,t,i){var o;let s=this.clientOptions.uploader,a=await s.stat(t),c=String(a.size),d=(o=i?.mimeType)!==null&&o!==void 0?o: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`,f=this.getFileName(t),h={};i!=null&&tl(i,h);let m=await this.fetchUploadUrl(u,c,d,f,h,i?.httpOptions);return s.uploadToFileSearchStore(t,m,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,t,i,o,s,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":`${i}`},o?{"X-Goog-Upload-File-Name":o}:{})};let u=await this.request({path:e,body:JSON.stringify(s),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 f=(c=u?.headers)===null||c===void 0?void 0:c["x-goog-upload-url"];if(f===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return f}};async function ya(n){var e;if(n===void 0)throw new Error("response is undefined");if(!n.ok){let t=n.status,i;!((e=n.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?i=await n.json():i={error:{message:await n.text(),code:n.status,status:n.statusText}};let o=JSON.stringify(i);throw t>=400&&t<600?new Pn({message:o,status:t}):new Error(o)}}p(ya,"throwErrorIfNotOK");function th(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 s=JSON.parse(n.body);if(typeof s=="object"&&s!==null&&!Array.isArray(s))t=s;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 i(s,a){let c=Object.assign({},s);for(let d in a)if(Object.prototype.hasOwnProperty.call(a,d)){let u=a[d],f=c[d];u&&typeof u=="object"&&!Array.isArray(u)&&f&&typeof f=="object"&&!Array.isArray(f)?c[d]=i(f,u):(f&&u&&typeof f!=typeof u&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${d}". Original type: ${typeof f}, New type: ${typeof u}. Overwriting.`),c[d]=u)}return c}p(i,"deepMerge");let o=i(t,e);n.body=JSON.stringify(o)}p(th,"includeExtraBodyToRequestInit");var nh="mcp_used/unknown",ih=!1;function nl(n){for(let e of n)if(oh(e)||typeof e=="object"&&"inputSchema"in e)return!0;return ih}p(nl,"hasMcpToolUsage");function il(n){var e;let t=(e=n[uo])!==null&&e!==void 0?e:"";n[uo]=(t+` ${nh}`).trimStart()}p(il,"setMcpUsageHeader");function oh(n){return n!==null&&typeof n=="object"&&n instanceof po}p(oh,"isMcpCallableTool");function sh(n){return Se(this,arguments,p(function*(t,i=100){let o,s=0;for(;s<i;){let a=yield k(t.listTools({cursor:o}));for(let c of a.tools)yield yield k(c),s++;if(!a.nextCursor)break;o=a.nextCursor}},"listAllTools_1"))}p(sh,"listAllTools");var po=class n{static{p(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,i,o;if(this.mcpTools.length>0)return;let s={},a=[];for(let f of this.mcpClients)try{for(var c=!0,d=(t=void 0,Ae(sh(f))),u;u=await d.next(),e=u.done,!e;c=!0){o=u.value,c=!1;let h=o;a.push(h);let m=h.name;if(s[m])throw new Error(`Duplicate function name ${m} found in MCP tools. Please ensure function names are unique.`);s[m]=f}}catch(h){t={error:h}}finally{try{!c&&!e&&(i=d.return)&&await i.call(d)}finally{if(t)throw t.error}}this.mcpTools=a,this.functionNameToMcpClient=s}async tool(){return await this.initialize(),qc(this.mcpTools,this.config)}async callTool(e){await this.initialize();let t=[];for(let i of e)if(i.name in this.functionNameToMcpClient){let o=this.functionNameToMcpClient[i.name],s;this.config.timeout&&(s={timeout:this.config.timeout});let a=await o.callTool({name:i.name,arguments:i.args},void 0,s);t.push({functionResponse:{name:i.name,response:a.isError?{error:a}:a}})}return t}};async function rh(n,e,t){let i=new ji,o;t.data instanceof Blob?o=JSON.parse(await t.data.text()):o=JSON.parse(t.data),Object.assign(i,o),e(i)}p(rh,"handleWebSocketMessage$1");var ho=class{static{p(this,"LiveMusic")}constructor(e,t,i){this.apiClient=e,this.auth=t,this.webSocketFactory=i}async connect(e){var t,i;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 o=this.apiClient.getWebsocketBaseUrl(),s=this.apiClient.getApiVersion(),a=lh(this.apiClient.getDefaultHeaders()),c=this.apiClient.getApiKey(),d=`${o}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${c}`,u=p(()=>{},"onopenResolve"),f=new Promise(T=>{u=T}),h=e.callbacks,m=p(function(){u({})},"onopenAwaitedCallback"),g=this.apiClient,b={onopen:m,onmessage:p(T=>{rh(g,h.onmessage,T)},"onmessage"),onerror:(t=h?.onerror)!==null&&t!==void 0?t:function(T){},onclose:(i=h?.onclose)!==null&&i!==void 0?i:function(T){}},E=this.webSocketFactory.create(d,ah(a),b);E.connect(),await f;let I={setup:{model:F(this.apiClient,e.model)}};return E.send(JSON.stringify(I)),new mo(E,this.apiClient)}},mo=class{static{p(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=Mu(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let t=Gu(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){let t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(bt.PLAY)}pause(){this.sendPlaybackControl(bt.PAUSE)}stop(){this.sendPlaybackControl(bt.STOP)}resetContext(){this.sendPlaybackControl(bt.RESET_CONTEXT)}close(){this.conn.close()}};function ah(n){let e={};return n.forEach((t,i)=>{e[i]=t}),e}p(ah,"headersToMap$1");function lh(n){let e=new Headers;for(let[t,i]of Object.entries(n))e.append(t,i);return e}p(lh,"mapToHeaders$1");var ch="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function dh(n,e,t){let i=new Zi,o;t.data instanceof Blob?o=await t.data.text():t.data instanceof ArrayBuffer?o=new TextDecoder().decode(t.data):o=t.data;let s=JSON.parse(o);if(n.isVertexAI()){let a=Lu(s);Object.assign(i,a)}else Object.assign(i,s);e(i)}p(dh,"handleWebSocketMessage");var go=class{static{p(this,"Live")}constructor(e,t,i){this.apiClient=e,this.auth=t,this.webSocketFactory=i,this.music=new ho(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,i,o,s,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(),f,h=this.apiClient.getHeaders();e.config&&e.config.tools&&nl(e.config.tools)&&il(h);let m=ph(h);if(this.apiClient.isVertexAI())f=`${d}/ws/google.cloud.aiplatform.${u}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(m,f);else{let $=this.apiClient.getApiKey(),R="BidiGenerateContent",L="key";$?.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."),R="BidiGenerateContentConstrained",L="access_token"),f=`${d}/ws/google.ai.generativelanguage.${u}.GenerativeService.${R}?${L}=${$}`}let g=p(()=>{},"onopenResolve"),b=new Promise($=>{g=$}),E=e.callbacks,w=p(function(){var $;($=E?.onopen)===null||$===void 0||$.call(E),g({})},"onopenAwaitedCallback"),v=this.apiClient,I={onopen:w,onmessage:p($=>{dh(v,E.onmessage,$)},"onmessage"),onerror:(t=E?.onerror)!==null&&t!==void 0?t:function($){},onclose:(i=E?.onclose)!==null&&i!==void 0?i:function($){}},T=this.webSocketFactory.create(f,fh(m),I);T.connect(),await b;let C=F(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&C.startsWith("publishers/")){let $=this.apiClient.getProject(),R=this.apiClient.getLocation();C=`projects/${$}/locations/${R}/`+C}let N={};this.apiClient.isVertexAI()&&((o=e.config)===null||o===void 0?void 0:o.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[gn.AUDIO]}:e.config.responseModalities=[gn.AUDIO]),!((s=e.config)===null||s===void 0)&&s.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 S=(c=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&c!==void 0?c:[],x=[];for(let $ of S)if(this.isCallableTool($)){let R=$;x.push(await R.tool())}else x.push($);x.length>0&&(e.config.tools=x);let P={model:C,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?N=Ru(this.apiClient,P):N=Pu(this.apiClient,P),delete N.config,T.send(JSON.stringify(N)),new bo(T,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},uh={turnComplete:!0},bo=class{static{p(this,"Session")}constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(t.turns!==null&&t.turns!==void 0){let i=[];try{i=Ie(t.turns),e.isVertexAI()||(i=i.map(o=>Jn(o)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:i,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let i=[];if(t.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(t.functionResponses)?i=t.functionResponses:i=[t.functionResponses],i.length===0)throw new Error("functionResponses is required.");for(let s of i){if(typeof s!="object"||s===null||!("name"in s)||!("response"in s))throw new Error(`Could not parse function response, type '${typeof s}'.`);if(!e.isVertexAI()&&!("id"in s))throw new Error(ch)}return{toolResponse:{functionResponses:i}}}sendClientContent(e){e=Object.assign(Object.assign({},uh),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};this.apiClient.isVertexAI()?t={realtimeInput:Du(e)}:t={realtimeInput:ku(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 fh(n){let e={};return n.forEach((t,i)=>{e[i]=t}),e}p(fh,"headersToMap");function ph(n){let e=new Headers;for(let[t,i]of Object.entries(n))e.append(t,i);return e}p(ph,"mapToHeaders");var Ea=10;function wa(n){var e,t,i;if(!((e=n?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let o=!1;for(let a of(t=n?.tools)!==null&&t!==void 0?t:[])if(Et(a)){o=!0;break}if(!o)return!0;let s=(i=n?.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls;return s&&(s<0||!Number.isInteger(s))||s==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:",s),!0):!1}p(wa,"shouldDisableAfc");function Et(n){return"callTool"in n&&typeof n.callTool=="function"}p(Et,"isCallableTool");function hh(n){var e,t,i;return(i=(t=(e=n.config)===null||e===void 0?void 0:e.tools)===null||t===void 0?void 0:t.some(o=>Et(o)))!==null&&i!==void 0?i:!1}p(hh,"hasCallableTools");function va(n){var e;let t=[];return!((e=n?.config)===null||e===void 0)&&e.tools&&n.config.tools.forEach((i,o)=>{if(Et(i))return;let s=i;s.functionDeclarations&&s.functionDeclarations.length>0&&t.push(o)}),t}p(va,"findAfcIncompatibleToolIndexes");function Ia(n){var e;return!(!((e=n?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}p(Ia,"shouldAppendAfcHistory");var yo=class extends xe{static{p(this,"Models")}constructor(e){super(),this.apiClient=e,this.generateContent=async t=>{var i,o,s,a,c;let d=await this.processParamsMaybeAddMcpUsage(t);if(this.maybeMoveToResponseJsonSchem(t),!hh(t)||wa(t.config))return await this.generateContentInternal(d);let u=va(t);if(u.length>0){let E=u.map(w=>`tools[${w}]`).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 f,h,m=Ie(d.contents),g=(s=(o=(i=d.config)===null||i===void 0?void 0:i.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&s!==void 0?s:Ea,b=0;for(;b<g&&(f=await this.generateContentInternal(d),!(!f.functionCalls||f.functionCalls.length===0));){let E=f.candidates[0].content,w=[];for(let v of(c=(a=t.config)===null||a===void 0?void 0:a.tools)!==null&&c!==void 0?c:[])if(Et(v)){let T=await v.callTool(f.functionCalls);w.push(...T)}b++,h={role:"user",parts:w},d.contents=Ie(d.contents),d.contents.push(E),d.contents.push(h),Ia(d.config)&&(m.push(E),m.push(h))}return Ia(d.config)&&(f.automaticFunctionCallingHistory=m),f},this.generateContentStream=async t=>{var i,o,s,a,c;if(this.maybeMoveToResponseJsonSchem(t),wa(t.config)){let h=await this.processParamsMaybeAddMcpUsage(t);return await this.generateContentStreamInternal(h)}let d=va(t);if(d.length>0){let h=d.map(m=>`tools[${m}]`).join(", ");throw new Error(`Incompatible tools found at ${h}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let u=(s=(o=(i=t?.config)===null||i===void 0?void 0:i.toolConfig)===null||o===void 0?void 0:o.functionCallingConfig)===null||s===void 0?void 0:s.streamFunctionCallArguments,f=(c=(a=t?.config)===null||a===void 0?void 0:a.automaticFunctionCalling)===null||c===void 0?void 0:c.disable;if(u&&!f)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(i=>{var o;let s,a=[];if(i?.generatedImages)for(let d of i.generatedImages)d&&d?.safetyAttributes&&((o=d?.safetyAttributes)===null||o===void 0?void 0:o.contentType)==="Positive Prompt"?s=d?.safetyAttributes:a.push(d);let c;return s?c={generatedImages:a,positivePromptSafetyAttributes:s,sdkHttpResponse:i.sdkHttpResponse}:c={generatedImages:a,sdkHttpResponse:i.sdkHttpResponse},c}),this.list=async t=>{var i;let a={config:Object.assign(Object.assign({},{queryBase:!0}),t?.config)};if(this.apiClient.isVertexAI()&&!a.config.queryBase){if(!((i=a.config)===null||i===void 0)&&i.filter)throw new Error("Filtering tuned models list for Vertex AI is not currently supported");a.config.filter="labels.tune-type:*"}return new De(ke.PAGED_ITEM_MODELS,c=>this.listInternal(c),await this.listInternal(a),a)},this.editImage=async t=>{let i={model:t.model,prompt:t.prompt,referenceImages:[],config:t.config};return t.referenceImages&&t.referenceImages&&(i.referenceImages=t.referenceImages.map(o=>o.toReferenceImageAPI())),await this.editImageInternal(i)},this.upscaleImage=async t=>{let i={numberOfImages:1,mode:"upscale"};t.config&&(i=Object.assign(Object.assign({},i),t.config));let o={model:t.model,image:t.image,upscaleFactor:t.upscaleFactor,config:i};return await this.upscaleImageInternal(o)},this.generateVideos=async t=>{var i,o,s,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()||(!((i=t.video)===null||i===void 0)&&i.uri&&(!((o=t.video)===null||o===void 0)&&o.videoBytes)?t.video={uri:t.video.uri,mimeType:t.video.mimeType}:!((a=(s=t.source)===null||s===void 0?void 0:s.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,i,o;let s=(t=e.config)===null||t===void 0?void 0:t.tools;if(!s)return e;let a=await Promise.all(s.map(async d=>Et(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&&nl(e.config.tools)){let d=(o=(i=e.config.httpOptions)===null||i===void 0?void 0:i.headers)!==null&&o!==void 0?o:{},u=Object.assign({},d);Object.keys(u).length===0&&(u=this.apiClient.getDefaultHeaders()),il(u),c.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:u})}return c}async initAfcToolsMap(e){var t,i,o;let s=new Map;for(let a of(i=(t=e.config)===null||t===void 0?void 0:t.tools)!==null&&i!==void 0?i:[])if(Et(a)){let c=a,d=await c.tool();for(let u of(o=d.functionDeclarations)!==null&&o!==void 0?o:[]){if(!u.name)throw new Error("Function declaration name is required.");if(s.has(u.name))throw new Error(`Duplicate tool declaration name: ${u.name}`);s.set(u.name,c)}}return s}async processAfcStream(e){var t,i,o;let s=(o=(i=(t=e.config)===null||t===void 0?void 0:t.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&o!==void 0?o:Ea,a=!1,c=0,d=await this.initAfcToolsMap(e);return function(u,f,h){return Se(this,arguments,function*(){for(var m,g,b,E,w,v;c<s;){a&&(c++,a=!1);let N=yield k(u.processParamsMaybeAddMcpUsage(h)),S=yield k(u.generateContentStreamInternal(N)),x=[],P=[];try{for(var I=!0,T=(g=void 0,Ae(S)),C;C=yield k(T.next()),m=C.done,!m;I=!0){E=C.value,I=!1;let $=E;if(yield yield k($),$.candidates&&(!((w=$.candidates[0])===null||w===void 0)&&w.content)){P.push($.candidates[0].content);for(let R of(v=$.candidates[0].content.parts)!==null&&v!==void 0?v:[])if(c<s&&R.functionCall){if(!R.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has(R.functionCall.name)){let L=yield k(f.get(R.functionCall.name).callTool([R.functionCall]));x.push(...L)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${f.keys()}, mising tool: ${R.functionCall.name}`)}}}}catch($){g={error:$}}finally{try{!I&&!m&&(b=T.return)&&(yield k(b.call(T)))}finally{if(g)throw g.error}}if(x.length>0){a=!0;let $=new ot;$.candidates=[{content:{role:"user",parts:x}}],yield yield k($);let R=[];R.push(...P),R.push({role:"user",parts:x});let L=Ie(h.contents).concat(R);h.contents=L}else break}})}(this,d,e)}async generateContentInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=ma(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=ba(f),m=new ot;return Object.assign(m,h),m})}else{let u=ha(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=ga(f),m=new ot;return Object.assign(m,h),m})}}async generateContentStreamInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=ma(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}),a.then(function(h){return Se(this,arguments,function*(){var m,g,b,E;try{for(var w=!0,v=Ae(h),I;I=yield k(v.next()),m=I.done,!m;w=!0){E=I.value,w=!1;let T=E,C=ba(yield k(T.json()));C.sdkHttpResponse={headers:T.headers};let N=new ot;Object.assign(N,C),yield yield k(N)}}catch(T){g={error:T}}finally{try{!w&&!m&&(b=v.return)&&(yield k(b.call(v)))}finally{if(g)throw g.error}}})})}else{let u=ha(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}),a.then(function(h){return Se(this,arguments,function*(){var m,g,b,E;try{for(var w=!0,v=Ae(h),I;I=yield k(v.next()),m=I.done,!m;w=!0){E=I.value,w=!1;let T=E,C=ga(yield k(T.json()));C.sdkHttpResponse={headers:T.headers};let N=new ot;Object.assign(N,C),yield yield k(N)}}catch(T){g={error:T}}finally{try{!w&&!m&&(b=v.return)&&(yield k(b.call(v)))}finally{if(g)throw g.error}}})})}}async embedContent(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=hf(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=gf(f),m=new yn;return Object.assign(m,h),m})}else{let u=pf(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=mf(f),m=new yn;return Object.assign(m,h),m})}}async generateImagesInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Af(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Nf(f),m=new En;return Object.assign(m,h),m})}else{let u=Sf(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=xf(f),m=new En;return Object.assign(m,h),m})}}async editImageInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=cf(this.apiClient,e);return s=_("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>{let u=df(d),f=new Bi;return Object.assign(f,u),f})}else throw new Error("This method is only supported by the Vertex AI.")}async upscaleImageInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=Ap(this.apiClient,e);return s=_("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>{let u=xp(d),f=new Vi;return Object.assign(f,u),f})}else throw new Error("This method is only supported by the Vertex AI.")}async recontextImage(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=lp(this.apiClient,e);return s=_("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=cp(d),f=new qi;return Object.assign(f,u),f})}else throw new Error("This method is only supported by the Vertex AI.")}async segmentImage(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=mp(this.apiClient,e);return s=_("{model}:predict",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=gp(d),f=new Hi;return Object.assign(f,u),f})}else throw new Error("This method is only supported by the Vertex AI.")}async get(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Kf(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>co(f))}else{let u=zf(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>lo(f))}}async listInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=tp(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=ip(f),m=new wn;return Object.assign(m,h),m})}else{let u=ep(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=np(f),m=new wn;return Object.assign(m,h),m})}}async update(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=_p(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>co(f))}else{let u=Cp(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>lo(f))}}async delete(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=sf(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=af(f),m=new vn;return Object.assign(m,h),m})}else{let u=of(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=rf(f),m=new vn;return Object.assign(m,h),m})}}async countTokens(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=ef(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=nf(f),m=new In;return Object.assign(m,h),m})}else{let u=ju(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=tf(f),m=new In;return Object.assign(m,h),m})}}async computeTokens(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=Ku(this.apiClient,e);return s=_("{model}:computeTokens",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>{let u=Ju(d),f=new Oi;return Object.assign(f,u),f})}else throw new Error("This method is only supported by the Vertex AI.")}async generateVideosInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=kf(this.apiClient,e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>{let h=Gf(f),m=new Tn;return Object.assign(m,h),m})}else{let u=Mf(this.apiClient,e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a.then(f=>{let h=Rf(f),m=new Tn;return Object.assign(m,h),m})}}};var Eo=class extends xe{static{p(this,"Operations")}constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let t=e.operation,i=e.config;if(t.name===void 0||t.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let o=t.name.split("/operations/")[0],s;i&&"httpOptions"in i&&(s=i.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:o,config:{httpOptions:s}});return t._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let o=await this.getVideosOperationInternal({operationName:t.name,config:i});return t._fromAPIResponse({apiResponse:o,_isVertexAI:!1})}}async get(e){let t=e.operation,i=e.config;if(t.name===void 0||t.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let o=t.name.split("/operations/")[0],s;i&&"httpOptions"in i&&(s=i.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:o,config:{httpOptions:s}});return t._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let o=await this.getVideosOperationInternal({operationName:t.name,config:i});return t._fromAPIResponse({apiResponse:o,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Nc(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a}else{let u=xc(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),a}}async fetchPredictVideosOperationInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=vc(e);return s=_("{resourceName}:fetchPredictOperation",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o}else throw new Error("This method is only supported by the Vertex AI.")}};function mh(n){let e={},t=r(n,["data"]);if(t!=null&&l(e,["data"],t),r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(mh,"blobToMldev");function gh(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>_h(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(gh,"contentToMldev");function bh(n,e,t){let i={},o=r(e,["expireTime"]);t!==void 0&&o!=null&&l(t,["expireTime"],o);let s=r(e,["newSessionExpireTime"]);t!==void 0&&s!=null&&l(t,["newSessionExpireTime"],s);let a=r(e,["uses"]);t!==void 0&&a!=null&&l(t,["uses"],a);let c=r(e,["liveConnectConstraints"]);t!==void 0&&c!=null&&l(t,["bidiGenerateContentSetup"],Ch(n,c));let d=r(e,["lockAdditionalFields"]);return t!==void 0&&d!=null&&l(t,["fieldMask"],d),i}p(bh,"createAuthTokenConfigToMldev");function yh(n,e){let t={},i=r(e,["config"]);return i!=null&&l(t,["config"],bh(n,i,t)),t}p(yh,"createAuthTokenParametersToMldev");function Eh(n){let e={};if(r(n,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");let t=r(n,["fileUri"]);t!=null&&l(e,["fileUri"],t);let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(Eh,"fileDataToMldev");function wh(n){let e={},t=r(n,["id"]);t!=null&&l(e,["id"],t);let i=r(n,["args"]);i!=null&&l(e,["args"],i);let o=r(n,["name"]);if(o!=null&&l(e,["name"],o),r(n,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(r(n,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}p(wh,"functionCallToMldev");function vh(n){let e={};if(r(n,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");let t=r(n,["enableWidget"]);return t!=null&&l(e,["enableWidget"],t),e}p(vh,"googleMapsToMldev");function Ih(n){let e={};if(r(n,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(r(n,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");let t=r(n,["timeRangeFilter"]);return t!=null&&l(e,["timeRangeFilter"],t),e}p(Ih,"googleSearchToMldev");function Th(n,e){let t={},i=r(n,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],i);let o=r(n,["responseModalities"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","responseModalities"],o);let s=r(n,["temperature"]);e!==void 0&&s!=null&&l(e,["setup","generationConfig","temperature"],s);let a=r(n,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let c=r(n,["topK"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","topK"],c);let d=r(n,["maxOutputTokens"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","maxOutputTokens"],d);let u=r(n,["mediaResolution"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","mediaResolution"],u);let f=r(n,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let h=r(n,["speechConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","speechConfig"],Vo(h));let m=r(n,["thinkingConfig"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","thinkingConfig"],m);let g=r(n,["enableAffectiveDialog"]);e!==void 0&&g!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],g);let b=r(n,["systemInstruction"]);e!==void 0&&b!=null&&l(e,["setup","systemInstruction"],gh(ce(b)));let E=r(n,["tools"]);if(e!==void 0&&E!=null){let S=Tt(E);Array.isArray(S)&&(S=S.map(x=>Ah(It(x)))),l(e,["setup","tools"],S)}let w=r(n,["sessionResumption"]);e!==void 0&&w!=null&&l(e,["setup","sessionResumption"],Sh(w));let v=r(n,["inputAudioTranscription"]);e!==void 0&&v!=null&&l(e,["setup","inputAudioTranscription"],v);let I=r(n,["outputAudioTranscription"]);e!==void 0&&I!=null&&l(e,["setup","outputAudioTranscription"],I);let T=r(n,["realtimeInputConfig"]);e!==void 0&&T!=null&&l(e,["setup","realtimeInputConfig"],T);let C=r(n,["contextWindowCompression"]);e!==void 0&&C!=null&&l(e,["setup","contextWindowCompression"],C);let N=r(n,["proactivity"]);if(e!==void 0&&N!=null&&l(e,["setup","proactivity"],N),r(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}p(Th,"liveConnectConfigToMldev");function Ch(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],F(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],Th(o,t)),t}p(Ch,"liveConnectConstraintsToMldev");function _h(n){let e={},t=r(n,["mediaResolution"]);t!=null&&l(e,["mediaResolution"],t);let i=r(n,["codeExecutionResult"]);i!=null&&l(e,["codeExecutionResult"],i);let o=r(n,["executableCode"]);o!=null&&l(e,["executableCode"],o);let s=r(n,["fileData"]);s!=null&&l(e,["fileData"],Eh(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],wh(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],mh(d));let u=r(n,["text"]);u!=null&&l(e,["text"],u);let f=r(n,["thought"]);f!=null&&l(e,["thought"],f);let h=r(n,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=r(n,["videoMetadata"]);return m!=null&&l(e,["videoMetadata"],m),e}p(_h,"partToMldev");function Sh(n){let e={},t=r(n,["handle"]);if(t!=null&&l(e,["handle"],t),r(n,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}p(Sh,"sessionResumptionConfigToMldev");function Ah(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let f=t;Array.isArray(f)&&(f=f.map(h=>h)),l(e,["functionDeclarations"],f)}if(r(n,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");let i=r(n,["googleSearchRetrieval"]);i!=null&&l(e,["googleSearchRetrieval"],i);let o=r(n,["computerUse"]);o!=null&&l(e,["computerUse"],o);let s=r(n,["fileSearch"]);s!=null&&l(e,["fileSearch"],s);let a=r(n,["codeExecution"]);if(a!=null&&l(e,["codeExecution"],a),r(n,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],vh(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],Ih(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Ah,"toolToMldev");function xh(n){let e=[];for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){let i=n[t];if(typeof i=="object"&&i!=null&&Object.keys(i).length>0){let o=Object.keys(i).map(s=>`${t}.${s}`);e.push(...o)}else e.push(t)}return e.join(",")}p(xh,"getFieldMasks");function Nh(n,e){let t=null,i=n.bidiGenerateContentSetup;if(typeof i=="object"&&i!==null&&"setup"in i){let s=i.setup;typeof s=="object"&&s!==null?(n.bidiGenerateContentSetup=s,t=s):delete n.bidiGenerateContentSetup}else i!==void 0&&delete n.bidiGenerateContentSetup;let o=n.fieldMask;if(t){let s=xh(t);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)s?n.fieldMask=s:delete n.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&o!==null&&Array.isArray(o)&&o.length>0){let a=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],c=[];o.length>0&&(c=o.map(u=>a.includes(u)?`generationConfig.${u}`:u));let d=[];s&&d.push(s),c.length>0&&d.push(...c),d.length>0?n.fieldMask=d.join(","):delete n.fieldMask}else delete n.fieldMask}else o!==null&&Array.isArray(o)&&o.length>0?n.fieldMask=o.join(","):delete n.fieldMask;return n}p(Nh,"convertBidiSetupToTokenSetup");var wo=class extends xe{static{p(this,"Tokens")}constructor(e){super(),this.apiClient=e}async create(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let c=yh(this.apiClient,e);s=_("auth_tokens",c._url),a=c._query,delete c.config,delete c._url,delete c._query;let d=Nh(c,e.config);return o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(u=>u.json()),o.then(u=>u)}}};function $h(n,e){let t={},i=r(n,["force"]);return e!==void 0&&i!=null&&l(e,["_query","force"],i),t}p($h,"deleteDocumentConfigToMldev");function Ph(n){let e={},t=r(n,["name"]);t!=null&&l(e,["_url","name"],t);let i=r(n,["config"]);return i!=null&&$h(i,e),e}p(Ph,"deleteDocumentParametersToMldev");function Rh(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","name"],t),e}p(Rh,"getDocumentParametersToMldev");function Gh(n,e){let t={},i=r(n,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=r(n,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),t}p(Gh,"listDocumentsConfigToMldev");function Mh(n){let e={},t=r(n,["parent"]);t!=null&&l(e,["_url","parent"],t);let i=r(n,["config"]);return i!=null&&Gh(i,e),e}p(Mh,"listDocumentsParametersToMldev");function kh(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=r(n,["documents"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(a=>a)),l(e,["documents"],s)}return e}p(kh,"listDocumentsResponseFromMldev");var vo=class extends xe{static{p(this,"Documents")}constructor(e){super(),this.apiClient=e,this.list=async t=>new De(ke.PAGED_ITEM_DOCUMENTS,i=>this.listInternal({parent:t.parent,config:i.config}),await this.listInternal(t),t)}async get(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Rh(e);return s=_("{name}",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>d)}}async delete(e){var t,i;let o="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Ph(e);o=_("{name}",a._url),s=a._query,delete a._url,delete a._query,await this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}}async listInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Mh(e);return s=_("{parent}/documents",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=kh(d),f=new zi;return Object.assign(f,u),f})}}};var Io=class extends xe{static{p(this,"FileSearchStores")}constructor(e,t=new vo(e)){super(),this.apiClient=e,this.documents=t,this.list=async(i={})=>new De(ke.PAGED_ITEM_FILE_SEARCH_STORES,o=>this.listInternal(o),await this.listInternal(i),i)}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,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=kp(e);return s=_("fileSearchStores",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>d)}}async get(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Up(e);return s=_("{name}",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>d)}}async delete(e){var t,i;let o="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=Lp(e);o=_("{name}",a._url),s=a._query,delete a._url,delete a._query,await this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}}async listInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Op(e);return s=_("fileSearchStores",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=zp(d),f=new Ki;return Object.assign(f,u),f})}}async uploadToFileSearchStoreInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Kp(e);return s=_("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=Jp(d),f=new Ji;return Object.assign(f,u),f})}}async importFile(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Vp(e);return s=_("{file_search_store_name}:importFile",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>{let u=Bp(d),f=new Wi;return Object.assign(f,u),f})}}};var ol=p(function(){let{crypto:n}=globalThis;if(n?.randomUUID)return ol=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,i=>(+i^t()&15>>+i/4).toString(16))},"uuid4Internal"),Dh=p(()=>ol(),"uuid4");function To(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}p(To,"isAbortError");var Co=p(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 ge=class extends Error{static{p(this,"GeminiNextGenAPIClientError")}},be=class n extends ge{static{p(this,"APIError")}constructor(e,t,i,o){super(`${n.makeMessage(e,t,i)}`),this.status=e,this.headers=o,this.error=t}static makeMessage(e,t,i){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):i;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,i,o){if(!e||!o)return new wt({message:i,cause:Co(t)});let s=t;return e===400?new Gn(e,s,i,o):e===401?new Mn(e,s,i,o):e===403?new kn(e,s,i,o):e===404?new Dn(e,s,i,o):e===409?new Ln(e,s,i,o):e===422?new Un(e,s,i,o):e===429?new Fn(e,s,i,o):e>=500?new Bn(e,s,i,o):new n(e,s,i,o)}},Dt=class extends be{static{p(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},wt=class extends be{static{p(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Rn=class extends wt{static{p(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},Gn=class extends be{static{p(this,"BadRequestError")}},Mn=class extends be{static{p(this,"AuthenticationError")}},kn=class extends be{static{p(this,"PermissionDeniedError")}},Dn=class extends be{static{p(this,"NotFoundError")}},Ln=class extends be{static{p(this,"ConflictError")}},Un=class extends be{static{p(this,"UnprocessableEntityError")}},Fn=class extends be{static{p(this,"RateLimitError")}},Bn=class extends be{static{p(this,"InternalServerError")}};var Lh=/^[a-z][a-z0-9+.-]*:/i,Uh=p(n=>Lh.test(n),"isAbsoluteURL"),_o=p(n=>(_o=Array.isArray,_o(n)),"isArrayInternal"),Fh=_o,Bh=Fh,Ta=Bh;function Vh(n){if(!n)return!0;for(let e in n)return!1;return!0}p(Vh,"isEmptyObj");function qh(n,e){return Object.prototype.hasOwnProperty.call(n,e)}p(qh,"hasOwn");var Hh=p((n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ge(`${n} must be an integer`);if(e<0)throw new ge(`${n} must be a positive integer`);return e},"validatePositiveInteger"),Oh=p(n=>{try{return JSON.parse(n)}catch{return}},"safeJSON");var zh=p(n=>new Promise(e=>setTimeout(e,n)),"sleep$1");var gt="0.0.1";function Kh(){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"}p(Kh,"getDetectedPlatform");var Jh=p(()=>{var n,e,t,i,o;let s=Kh();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gt,"X-Stainless-OS":_a(Deno.build.os),"X-Stainless-Arch":Ca(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":gt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gt,"X-Stainless-OS":_a((t=globalThis.process.platform)!==null&&t!==void 0?t:"unknown"),"X-Stainless-Arch":Ca((i=globalThis.process.arch)!==null&&i!==void 0?i:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(o=globalThis.process.version)!==null&&o!==void 0?o:"unknown"};let a=Wh();return a?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gt,"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":gt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Wh(){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 i=t.exec(navigator.userAgent);if(i){let o=i[1]||0,s=i[2]||0,a=i[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}p(Wh,"getBrowserInfo");var Ca=p(n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown","normalizeArch"),_a=p(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"),cn,Xh=p(()=>cn??(cn=Jh()),"getPlatformHeaders");function Yh(){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`")}p(Yh,"getDefaultFetch");function sl(...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)}p(sl,"makeReadableStream");function Qh(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return sl({start(){},async pull(t){let{done:i,value:o}=await e.next();i?t.close():t.enqueue(o)},async cancel(){var t;await((t=e.return)===null||t===void 0?void 0:t.call(e))}})}p(Qh,"ReadableStreamFrom");function rl(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}}}p(rl,"ReadableStreamToAsyncIterable");async function Zh(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 i=n.getReader(),o=i.cancel();i.releaseLock(),await o}p(Zh,"CancelReadableStream");var jh=p(({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var al=p(()=>{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 ki(n,e,t){return al(),new File(n,e??"unknown_file",t)}p(ki,"makeFile");function em(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}p(em,"getName");var tm=p(n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function","isAsyncIterable");var ll=p(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"),nm=p(n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&ll(n),"isFileLike"),im=p(n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function","isResponseLike");async function om(n,e,t){if(al(),n=await n,nm(n))return n instanceof File?n:ki([await n.arrayBuffer()],n.name);if(im(n)){let o=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),ki(await So(o),e,t)}let i=await So(n);if(e||(e=em(n)),!t?.type){let o=i.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(t=Object.assign(Object.assign({},t),{type:o}))}return ki(i,e,t)}p(om,"toFile");async function So(n){var e,t,i,o,s;let a=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)a.push(n);else if(ll(n))a.push(n instanceof Blob?n:await n.arrayBuffer());else if(tm(n))try{for(var c=!0,d=Ae(n),u;u=await d.next(),e=u.done,!e;c=!0){o=u.value,c=!1;let f=o;a.push(...await So(f))}}catch(f){t={error:f}}finally{try{!c&&!e&&(i=d.return)&&await i.call(d)}finally{if(t)throw t.error}}else{let f=(s=n?.constructor)===null||s===void 0?void 0:s.name;throw new Error(`Unexpected data type: ${typeof n}${f?`; constructor: ${f}`:""}${sm(n)}`)}return a}p(So,"getBytes");function sm(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}p(sm,"propsForError");var Vn=class{static{p(this,"APIResource")}constructor(e){this._client=e}};Vn._key=[];function cl(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}p(cl,"encodeURIPath");var Sa=Object.freeze(Object.create(null)),rm=p((n=cl)=>p(function(t,...i){if(t.length===1)return t[0];let o=!1,s=[],a=t.reduce((f,h,m)=>{var g,b,E;/[?#]/.test(h)&&(o=!0);let w=i[m],v=(o?encodeURIComponent:n)(""+w);return m!==i.length&&(w==null||typeof w=="object"&&w.toString===((E=Object.getPrototypeOf((b=Object.getPrototypeOf((g=w.hasOwnProperty)!==null&&g!==void 0?g:Sa))!==null&&b!==void 0?b:Sa))===null||E===void 0?void 0:E.toString))&&(v=w+"",s.push({start:f.length+h.length,length:v.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`})),f+h+(m===i.length?"":v)},""),c=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=d.exec(c))!==null;)s.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(s.sort((f,h)=>f.start-h.start),s.length>0){let f=0,h=s.reduce((m,g)=>{let b=" ".repeat(g.start-f),E="^".repeat(g.length);return f=g.start+g.length,m+b+E},"");throw new ge(`Path parameters result in path with invalid segments:
|
|
671
671
|
${s.map(m=>m.error).join(`
|
|
672
672
|
`)}
|
|
673
673
|
${a}
|
|
674
|
-
${h}`)}return a},"path"),"createPathTagFunction"),
|
|
675
|
-
`):[]}};
|
|
676
|
-
`,"\r"]);
|
|
677
|
-
`);i.enqueue(a)}catch(o){i.error(o)}},async cancel(){var i;await((i=t.return)===null||i===void 0?void 0:i.call(t))}})}};function
|
|
678
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,i,o]=sm(e,":");return o.startsWith(" ")&&(o=o.substring(1)),t==="event"?this.event=o:t==="data"&&this.data.push(o),null}};function sm(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}p(sm,"partition");async function rm(n,e){let{response:t,requestLogID:i,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{var c;if(e.options.stream)return fe(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):vo.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 fe(n).debug(`[${i}] response parsed`,et({retryOfRequestLogID:o,url:t.url,status:t.status,body:a,durationMs:Date.now()-s})),a}p(rm,"defaultParseResponse");var To=class n extends Promise{static{p(this,"APIPromise")}constructor(e,t,i=rm){super(o=>{o(null)}),this.responsePromise=t,this.parseResponse=i,this.client=e}_thenUnwrap(e){return new n(this.client,this.responsePromise,async(t,i)=>e(await this.parseResponse(t,i),i))}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 nl=Symbol("brand.privateNullableHeaders");function*am(n){if(!n)return;if(nl in n){let{values:i,nulls:o}=n;yield*i.entries();for(let s of o)yield[s,null];return}let e=!1,t;n instanceof Headers?t=n.entries():ma(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let i of t){let o=i[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=ma(i[1])?i[1]:[i[1]],a=!1;for(let c of s)c!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,c])}}p(am,"iterateHeaders");var $i=p(n=>{let e=new Headers,t=new Set;for(let i of n){let o=new Set;for(let[s,a]of am(i)){let c=s.toLowerCase();o.has(c)||(e.delete(s),o.add(c)),a===null?(e.delete(s),t.add(c)):(e.append(s,a),t.delete(c))}}return{[nl]:!0,values:e,nulls:t}},"buildHeaders");var Pi=p(n=>{var e,t,i,o,s,a;if(typeof globalThis.process<"u")return(i=(t=(e=globalThis.process.env)===null||e===void 0?void 0:e[n])===null||t===void 0?void 0:t.trim())!==null&&i!==void 0?i:void 0;if(typeof globalThis.Deno<"u")return(a=(s=(o=globalThis.Deno.env)===null||o===void 0?void 0:o.get)===null||s===void 0?void 0:s.call(o,n))===null||a===void 0?void 0:a.trim()},"readEnv");var il,Bn=class n{static{p(this,"BaseGeminiNextGenAPIClient")}constructor(e){var t,i,o,s,a,c,d,u=e===void 0?{}:e,{baseURL:f=Pi("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:h=(t=Pi("GEMINI_API_KEY"))!==null&&t!==void 0?t:null,apiVersion:m="v1beta"}=u,g=_n(u,["baseURL","apiKey","apiVersion"]);let b=Object.assign(Object.assign({apiKey:h,apiVersion:m},g),{baseURL:f||"https://generativelanguage.googleapis.com"});this.baseURL=b.baseURL,this.timeout=(i=b.timeout)!==null&&i!==void 0?i:n.DEFAULT_TIMEOUT,this.logger=(o=b.logger)!==null&&o!==void 0?o:console;let E="warn";this.logLevel=E,this.logLevel=(a=(s=wa(b.logLevel,"ClientOptions.logLevel",this))!==null&&s!==void 0?s:wa(Pi("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:Hh(),this.encoder=zh,this._options=b,this.apiKey=h,this.apiVersion=m}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 $i([{"x-goog-api-key":this.apiKey}])}stringifyQuery(e){return Object.entries(e).filter(([t,i])=>typeof i<"u").map(([t,i])=>{if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(i)}`;if(i===null)return`${encodeURIComponent(t)}=`;throw new me(`Cannot stringify type ${typeof i}; 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 ${ft}`}defaultIdempotencyKey(){return`stainless-node-retry-${xh()}`}makeStatusError(e,t,i,o){return ge.generate(e,t,i,o)}buildURL(e,t,i){let o=!this.baseURLOverridden()&&i||this.baseURL,s=$h(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Gh(a)||(t=Object.assign(Object.assign({},a),t)),typeof t=="object"&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:i}){}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,i){return this.request(Promise.resolve(i).then(o=>Object.assign({method:e,path:t},o)))}request(e,t=null){return new To(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,i){var o,s,a;let c=await e,d=(o=c.maxRetries)!==null&&o!==void 0?o:this.maxRetries;t==null&&(t=d),await this.prepareOptions(c);let{req:u,url:f,timeout:h}=await this.buildRequest(c,{retryCount:d-t});await this.prepareRequest(u,{url:f,options:c});let m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=i===void 0?"":`, retryOf: ${i}`,b=Date.now();if(fe(this).debug(`[${m}] sending request`,et({retryOfRequestLogID:i,method:c.method,url:f,options:c,headers:u.headers})),!((s=c.signal)===null||s===void 0)&&s.aborted)throw new Pt;let E=new AbortController,w=await this.fetchWithTimeout(f,u,h,E).catch(yo),v=Date.now();if(w instanceof globalThis.Error){let T=`retrying, ${t} attempts remaining`;if(!((a=c.signal)===null||a===void 0)&&a.aborted)throw new Pt;let S=bo(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(t)return fe(this).info(`[${m}] connection ${S?"timed out":"failed"} - ${T}`),fe(this).debug(`[${m}] connection ${S?"timed out":"failed"} (${T})`,et({retryOfRequestLogID:i,url:f,durationMs:v-b,message:w.message})),this.retryRequest(c,t,i??m);throw fe(this).info(`[${m}] connection ${S?"timed out":"failed"} - error; no more retries left`),fe(this).debug(`[${m}] connection ${S?"timed out":"failed"} (error; no more retries left)`,et({retryOfRequestLogID:i,url:f,durationMs:v-b,message:w.message})),S?new An:new gt({cause:w})}let I=`[${m}${g}] ${u.method} ${f} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${v-b}ms`;if(!w.ok){let T=await this.shouldRetry(w);if(t&&T){let x=`retrying, ${t} attempts remaining`;return await Oh(w.body),fe(this).info(`${I} - ${x}`),fe(this).debug(`[${m}] response error (${x})`,et({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,durationMs:v-b})),this.retryRequest(c,t,i??m,w.headers)}let S=T?"error; no more retries left":"error; not retryable";fe(this).info(`${I} - ${S}`);let N=await w.text().catch(x=>yo(x).message),$=kh(N),A=$?void 0:N;throw fe(this).debug(`[${m}] response error (${S})`,et({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,message:A,durationMs:Date.now()-b})),this.makeStatusError(w.status,$,A,w.headers)}return fe(this).info(I),fe(this).debug(`[${m}] response start`,et({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,durationMs:v-b})),{response:w,options:c,controller:E,requestLogID:m,retryOfRequestLogID:i,startTime:b}}async fetchWithTimeout(e,t,i,o){let s=t||{},{signal:a,method:c}=s,d=_n(s,["signal","method"]);a&&a.addEventListener("abort",()=>o.abort());let u=setTimeout(()=>o.abort(),i),f=globalThis.ReadableStream&&d.body instanceof globalThis.ReadableStream||typeof d.body=="object"&&d.body!==null&&Symbol.asyncIterator in d.body,h=Object.assign(Object.assign(Object.assign({signal:o.signal},f?{duplex:"half"}:{}),{method:"GET"}),d);c&&(h.method=c.toUpperCase());try{return await this.fetch.call(void 0,e,h)}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,i,o){var s;let a,c=o?.get("retry-after-ms");if(c){let u=parseFloat(c);Number.isNaN(u)||(a=u)}let d=o?.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=(s=e.maxRetries)!==null&&s!==void 0?s:this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,u)}return await Lh(a),this.makeRequest(e,t-1,i)}calculateDefaultRetryTimeoutMillis(e,t){let s=t-e,a=Math.min(.5*Math.pow(2,s),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){var i,o,s;let a=Object.assign({},e),{method:c,path:d,query:u,defaultBaseURL:f}=a,h=this.buildURL(d,u,f);"timeout"in a&&Dh("timeout",a.timeout),a.timeout=(i=a.timeout)!==null&&i!==void 0?i:this.timeout;let{bodyHeaders:m,body:g}=this.buildBody({options:a}),b=await this.buildHeaders({options:e,method:c,bodyHeaders:m,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}),(o=this.fetchOptions)!==null&&o!==void 0?o:{}),(s=a.fetchOptions)!==null&&s!==void 0?s:{}),url:h,timeout:a.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:i,retryCount:o}){let s={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=$i([s,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),Vh()),await this.authHeaders(e),this._options.defaultHeaders,i,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let i=$i([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&i.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:qh(e)}:this.encoder({body:e,headers:i})}};Bn.DEFAULT_TIMEOUT=6e4;var Y=class extends Bn{static{p(this,"GeminiNextGenAPIClient")}constructor(){super(...arguments),this.interactions=new Un(this)}};il=Y;Y.GeminiNextGenAPIClient=il;Y.GeminiNextGenAPIClientError=me;Y.APIError=ge;Y.APIConnectionError=gt;Y.APIConnectionTimeoutError=An;Y.APIUserAbortError=Pt;Y.NotFoundError=Pn;Y.ConflictError=Rn;Y.RateLimitError=Mn;Y.BadRequestError=xn;Y.AuthenticationError=Nn;Y.InternalServerError=Dn;Y.PermissionDeniedError=$n;Y.UnprocessableEntityError=Gn;Y.toFile=Yh;Y.Interactions=Un;function lm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(lm,"cancelTuningJobParametersToMldev");function cm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(cm,"cancelTuningJobParametersToVertex");function dm(n,e){let t={},i=r(n,["sdkHttpResponse"]);return i!=null&&l(t,["sdkHttpResponse"],i),t}p(dm,"cancelTuningJobResponseFromMldev");function um(n,e){let t={},i=r(n,["sdkHttpResponse"]);return i!=null&&l(t,["sdkHttpResponse"],i),t}p(um,"cancelTuningJobResponseFromVertex");function fm(n,e,t){let i={};if(r(n,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is not supported in Gemini API.");let o=r(n,["tunedModelDisplayName"]);if(e!==void 0&&o!=null&&l(e,["displayName"],o),r(n,["description"])!==void 0)throw new Error("description parameter is not supported in Gemini API.");let s=r(n,["epochCount"]);e!==void 0&&s!=null&&l(e,["tuningTask","hyperparameters","epochCount"],s);let a=r(n,["learningRateMultiplier"]);if(a!=null&&l(i,["tuningTask","hyperparameters","learningRateMultiplier"],a),r(n,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(r(n,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(r(n,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is not supported in Gemini API.");let c=r(n,["batchSize"]);e!==void 0&&c!=null&&l(e,["tuningTask","hyperparameters","batchSize"],c);let d=r(n,["learningRate"]);if(e!==void 0&&d!=null&&l(e,["tuningTask","hyperparameters","learningRate"],d),r(n,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");if(r(n,["beta"])!==void 0)throw new Error("beta parameter is not supported in Gemini API.");return i}p(fm,"createTuningJobConfigToMldev");function pm(n,e,t){let i={},o=r(t,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){let g=r(n,["validationDataset"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec"],Ia(g))}else if(o==="PREFERENCE_TUNING"){let g=r(n,["validationDataset"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec"],Ia(g))}let s=r(n,["tunedModelDisplayName"]);e!==void 0&&s!=null&&l(e,["tunedModelDisplayName"],s);let a=r(n,["description"]);e!==void 0&&a!=null&&l(e,["description"],a);let c=r(t,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let g=r(n,["epochCount"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","epochCount"],g)}else if(c==="PREFERENCE_TUNING"){let g=r(n,["epochCount"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],g)}let d=r(t,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let g=r(n,["learningRateMultiplier"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],g)}else if(d==="PREFERENCE_TUNING"){let g=r(n,["learningRateMultiplier"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],g)}let u=r(t,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let g=r(n,["exportLastCheckpointOnly"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","exportLastCheckpointOnly"],g)}else if(u==="PREFERENCE_TUNING"){let g=r(n,["exportLastCheckpointOnly"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],g)}let f=r(t,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){let g=r(n,["adapterSize"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","adapterSize"],g)}else if(f==="PREFERENCE_TUNING"){let g=r(n,["adapterSize"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],g)}if(r(n,["batchSize"])!==void 0)throw new Error("batchSize parameter is not supported in Vertex AI.");if(r(n,["learningRate"])!==void 0)throw new Error("learningRate parameter is not supported in Vertex AI.");let h=r(n,["labels"]);e!==void 0&&h!=null&&l(e,["labels"],h);let m=r(n,["beta"]);return e!==void 0&&m!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","beta"],m),i}p(pm,"createTuningJobConfigToVertex");function hm(n,e){let t={},i=r(n,["baseModel"]);i!=null&&l(t,["baseModel"],i);let o=r(n,["preTunedModel"]);o!=null&&l(t,["preTunedModel"],o);let s=r(n,["trainingDataset"]);s!=null&&_m(s);let a=r(n,["config"]);return a!=null&&fm(a,t),t}p(hm,"createTuningJobParametersPrivateToMldev");function mm(n,e){let t={},i=r(n,["baseModel"]);i!=null&&l(t,["baseModel"],i);let o=r(n,["preTunedModel"]);o!=null&&l(t,["preTunedModel"],o);let s=r(n,["trainingDataset"]);s!=null&&Sm(s,t,e);let a=r(n,["config"]);return a!=null&&pm(a,t,e),t}p(mm,"createTuningJobParametersPrivateToVertex");function gm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(gm,"getTuningJobParametersToMldev");function bm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(bm,"getTuningJobParametersToVertex");function ym(n,e,t){let i={},o=r(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let s=r(n,["pageToken"]);e!==void 0&&s!=null&&l(e,["_query","pageToken"],s);let a=r(n,["filter"]);return e!==void 0&&a!=null&&l(e,["_query","filter"],a),i}p(ym,"listTuningJobsConfigToMldev");function Em(n,e,t){let i={},o=r(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let s=r(n,["pageToken"]);e!==void 0&&s!=null&&l(e,["_query","pageToken"],s);let a=r(n,["filter"]);return e!==void 0&&a!=null&&l(e,["_query","filter"],a),i}p(Em,"listTuningJobsConfigToVertex");function wm(n,e){let t={},i=r(n,["config"]);return i!=null&&ym(i,t),t}p(wm,"listTuningJobsParametersToMldev");function vm(n,e){let t={},i=r(n,["config"]);return i!=null&&Em(i,t),t}p(vm,"listTuningJobsParametersToVertex");function Im(n,e){let t={},i=r(n,["sdkHttpResponse"]);i!=null&&l(t,["sdkHttpResponse"],i);let o=r(n,["nextPageToken"]);o!=null&&l(t,["nextPageToken"],o);let s=r(n,["tunedModels"]);if(s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>ol(c))),l(t,["tuningJobs"],a)}return t}p(Im,"listTuningJobsResponseFromMldev");function Tm(n,e){let t={},i=r(n,["sdkHttpResponse"]);i!=null&&l(t,["sdkHttpResponse"],i);let o=r(n,["nextPageToken"]);o!=null&&l(t,["nextPageToken"],o);let s=r(n,["tuningJobs"]);if(s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>Co(c))),l(t,["tuningJobs"],a)}return t}p(Tm,"listTuningJobsResponseFromVertex");function Cm(n,e){let t={},i=r(n,["name"]);i!=null&&l(t,["model"],i);let o=r(n,["name"]);return o!=null&&l(t,["endpoint"],o),t}p(Cm,"tunedModelFromMldev");function _m(n,e){let t={};if(r(n,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(r(n,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");let i=r(n,["examples"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>s)),l(t,["examples","examples"],o)}return t}p(_m,"tuningDatasetToMldev");function Sm(n,e,t){let i={},o=r(t,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){let a=r(n,["gcsUri"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(o==="PREFERENCE_TUNING"){let a=r(n,["gcsUri"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}let s=r(t,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){let a=r(n,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(s==="PREFERENCE_TUNING"){let a=r(n,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}if(r(n,["examples"])!==void 0)throw new Error("examples parameter is not supported in Vertex AI.");return i}p(Sm,"tuningDatasetToVertex");function ol(n,e){let t={},i=r(n,["sdkHttpResponse"]);i!=null&&l(t,["sdkHttpResponse"],i);let o=r(n,["name"]);o!=null&&l(t,["name"],o);let s=r(n,["state"]);s!=null&&l(t,["state"],$a(s));let a=r(n,["createTime"]);a!=null&&l(t,["createTime"],a);let c=r(n,["tuningTask","startTime"]);c!=null&&l(t,["startTime"],c);let d=r(n,["tuningTask","completeTime"]);d!=null&&l(t,["endTime"],d);let u=r(n,["updateTime"]);u!=null&&l(t,["updateTime"],u);let f=r(n,["description"]);f!=null&&l(t,["description"],f);let h=r(n,["baseModel"]);h!=null&&l(t,["baseModel"],h);let m=r(n,["_self"]);return m!=null&&l(t,["tunedModel"],Cm(m)),t}p(ol,"tuningJobFromMldev");function Co(n,e){let t={},i=r(n,["sdkHttpResponse"]);i!=null&&l(t,["sdkHttpResponse"],i);let o=r(n,["name"]);o!=null&&l(t,["name"],o);let s=r(n,["state"]);s!=null&&l(t,["state"],$a(s));let a=r(n,["createTime"]);a!=null&&l(t,["createTime"],a);let c=r(n,["startTime"]);c!=null&&l(t,["startTime"],c);let d=r(n,["endTime"]);d!=null&&l(t,["endTime"],d);let u=r(n,["updateTime"]);u!=null&&l(t,["updateTime"],u);let f=r(n,["error"]);f!=null&&l(t,["error"],f);let h=r(n,["description"]);h!=null&&l(t,["description"],h);let m=r(n,["baseModel"]);m!=null&&l(t,["baseModel"],m);let g=r(n,["tunedModel"]);g!=null&&l(t,["tunedModel"],g);let b=r(n,["preTunedModel"]);b!=null&&l(t,["preTunedModel"],b);let E=r(n,["supervisedTuningSpec"]);E!=null&&l(t,["supervisedTuningSpec"],E);let w=r(n,["preferenceOptimizationSpec"]);w!=null&&l(t,["preferenceOptimizationSpec"],w);let v=r(n,["tuningDataStats"]);v!=null&&l(t,["tuningDataStats"],v);let I=r(n,["encryptionSpec"]);I!=null&&l(t,["encryptionSpec"],I);let T=r(n,["partnerModelTuningSpec"]);T!=null&&l(t,["partnerModelTuningSpec"],T);let S=r(n,["customBaseModel"]);S!=null&&l(t,["customBaseModel"],S);let N=r(n,["experiment"]);N!=null&&l(t,["experiment"],N);let $=r(n,["labels"]);$!=null&&l(t,["labels"],$);let A=r(n,["outputUri"]);A!=null&&l(t,["outputUri"],A);let P=r(n,["pipelineJob"]);P!=null&&l(t,["pipelineJob"],P);let x=r(n,["serviceAccount"]);x!=null&&l(t,["serviceAccount"],x);let k=r(n,["tunedModelDisplayName"]);k!=null&&l(t,["tunedModelDisplayName"],k);let O=r(n,["veoTuningSpec"]);return O!=null&&l(t,["veoTuningSpec"],O),t}p(Co,"tuningJobFromVertex");function Am(n,e){let t={},i=r(n,["sdkHttpResponse"]);i!=null&&l(t,["sdkHttpResponse"],i);let o=r(n,["name"]);o!=null&&l(t,["name"],o);let s=r(n,["metadata"]);s!=null&&l(t,["metadata"],s);let a=r(n,["done"]);a!=null&&l(t,["done"],a);let c=r(n,["error"]);return c!=null&&l(t,["error"],c),t}p(Am,"tuningOperationFromMldev");function Ia(n,e){let t={},i=r(n,["gcsUri"]);i!=null&&l(t,["validationDatasetUri"],i);let o=r(n,["vertexDatasetResource"]);return o!=null&&l(t,["validationDatasetUri"],o),t}p(Ia,"tuningValidationDatasetToVertex");var _o=class extends Ne{static{p(this,"Tunings")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new De(Me.PAGED_ITEM_TUNING_JOBS,i=>this.listInternal(i),await this.listInternal(t),t),this.get=async t=>await this.getInternal(t),this.tune=async t=>{var i;if(this.apiClient.isVertexAI())if(t.baseModel.startsWith("projects/")){let o={tunedModelName:t.baseModel};!((i=t.config)===null||i===void 0)&&i.preTunedModelCheckpointId&&(o.checkpointId=t.config.preTunedModelCheckpointId);let s=Object.assign(Object.assign({},t),{preTunedModel:o});return s.baseModel=void 0,await this.tuneInternal(s)}else{let o=Object.assign({},t);return await this.tuneInternal(o)}else{let o=Object.assign({},t),s=await this.tuneMldevInternal(o),a="";return s.metadata!==void 0&&s.metadata.tunedModel!==void 0?a=s.metadata.tunedModel:s.name!==void 0&&s.name.includes("/operations/")&&(a=s.name.split("/operations/")[0]),{name:a,state:Gi.JOB_STATE_QUEUED}}}}async getInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=bm(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>Co(f))}else{let u=gm(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>ol(f))}}async listInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=vm(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Tm(f),m=new En;return Object.assign(m,h),m})}else{let u=wm(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Im(f),m=new En;return Object.assign(m,h),m})}}async cancel(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=cm(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=um(f),m=new wn;return Object.assign(m,h),m})}else{let u=lm(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=dm(f),m=new wn;return Object.assign(m,h),m})}}async tuneInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=mm(e,e);return s=_("tuningJobs",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>Co(d))}else throw new Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=hm(e);return s=_("tunedModels",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>Am(d))}}};var So=class{static{p(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.")}},xm=1024*1024*8,Nm=3,$m=1e3,Pm=2,Vn="x-goog-upload-status";async function Rm(n,e,t){var i;let o=await sl(n,e,t),s=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[Vn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return s.file}p(Rm,"uploadBlob");async function Gm(n,e,t){var i;let o=await sl(n,e,t),s=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[Vn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let a=Ca(s),c=new Wi;return Object.assign(c,a),c}p(Gm,"uploadBlobToFileSearchStore");async function sl(n,e,t){var i,o;let s=0,a=0,c=new $t(new Response),d="upload";for(s=n.size;a<s;){let u=Math.min(xm,s-a),f=n.slice(a,a+u);a+u>=s&&(d+=", finalize");let h=0,m=$m;for(;h<Nm&&(c=await t.request({path:"",body:f,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:e,headers:{"X-Goog-Upload-Command":d,"X-Goog-Upload-Offset":String(a),"Content-Length":String(u)}}}),!(!((i=c?.headers)===null||i===void 0)&&i[Vn]));)h++,await Dm(m),m=m*Pm;if(a+=u,((o=c?.headers)===null||o===void 0?void 0:o[Vn])!=="active")break;if(s<=a)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return c}p(sl,"uploadBlobInternal");async function Mm(n){return{size:n.size,type:n.type}}p(Mm,"getBlobStat");function Dm(n){return new Promise(e=>setTimeout(e,n))}p(Dm,"sleep");var Ao=class{static{p(this,"BrowserUploader")}async upload(e,t,i){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await Rm(e,t,i)}async uploadToFileSearchStore(e,t,i){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await Gm(e,t,i)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await Mm(e)}};var xo=class{static{p(this,"BrowserWebSocketFactory")}create(e,t,i){return new No(e,t,i)}},No=class{static{p(this,"BrowserWebSocket")}constructor(e,t,i){this.url=e,this.headers=t,this.callbacks=i}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 Ta="x-goog-api-key",$o=class{static{p(this,"WebAuth")}constructor(e){this.apiKey=e}async addAuthHeaders(e,t){if(e.get(Ta)===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(Ta,this.apiKey)}}};var km="gl-node/",Rt=class{static{p(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 i=uc(e.httpOptions,e.vertexai,void 0,void 0);i&&(e.httpOptions?e.httpOptions.baseUrl=i:e.httpOptions={baseUrl:i}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let o=new $o(this.apiKey);this.apiClient=new so({auth:o,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:km+"web",uploader:new Ao,downloader:new So}),this.models=new fo(this.apiClient),this.live=new co(this.apiClient,o,new xo),this.batches=new Qi(this.apiClient),this.chats=new ji(this.models,this.apiClient),this.caches=new Zi(this.apiClient),this.files=new to(this.apiClient),this.operations=new po(this.apiClient),this.authTokens=new ho(this.apiClient),this.tunings=new _o(this.apiClient),this.fileSearchStores=new go(this.apiClient)}};var nt=J||!0,rl=new Map,al=[];function it(){let n=`[${it.name}]`;try{return nt&&console.log(`${n} starting... (I: a5cf5821b42e1c71182dd61431977e25)`),rl}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{nt&&console.log(`${n} complete.`)}}p(it,"getAllFunctionInfos");function Lo(){let n=`[${Lo.name}]`;try{return nt&&console.log(`${n} starting... (I: 82c9a8fc91d8121fb843af32e76c2e25)`),al}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{nt&&console.log(`${n} complete.`)}}p(Lo,"getDeprecatedFunctionInfoNames");function Lm({functionInfos:n}){let e=`[${Lm.name}]`;try{nt&&console.log(`${e} starting... (I: 14fee8e27384a040494542182031ae25)`),n.size===0&&console.warn(`${e} empty functionInfos? (W: 97fcb8fc47689bc418893c09a16a2525)`);for(let[t,i]of n)al.includes(t)?nt&&console.log(`${e} functionInfo.nameOrId (${t}) is deprecated. Skipping add. (I: 3256eadf54f8087088a704798e2fd825)`):rl.set(t,i)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{nt&&console.log(`${e} complete.`)}}p(Lm,"registerFunctionInfos");var be=J;function Gt(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)`)}}p(Gt,"textSourceToGeminiRole");function ll(n){return n.api==="gemini"}p(ll,"isPromptInfoGemini");function Uo({systemPromptEntries:n}){let e=`[${Uo.name}]`;try{if(be&&console.log(`${e} starting... (I: 18693a97427939699285ef8c1a9cc425)`),n.length===0)return;n.every(i=>i.src===X.HUMAN)||be&&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(i=>!!i.content.parts).flatMap(i=>i.content.parts)};return be&&console.log(`${e} sysInstructionContent: ${L(t)} (I: 011e5b865c23eb0b640df3f464ac2525)`),t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{be&&console.log(`${e} complete.`)}}p(Uo,"systemPromptEntriesToSystemInstructionContent");function Fo({ibGib:n}){let e=`[${Fo.name}]`;try{if(be&&console.log(`${e} starting... (I: 986d3edcd4f3aaf1d7eb0f8b59206b25)`),!n)return be&&console.warn(`${e} ibGib falsy. (W: a70390e8bc3f420a92d3a84f4c78f12a)`),!1;if(!Ze({ibGib:n}))return be&&console.log(`${e} not a comment ibgib (I: 6a62c4f6e13776616855c4f237a5206b)`),!1;if(!n.data)return be&&console.log(`${e} ibGib.data falsy (I: 69eb86975640475395bb74944141a46d)`),!1;let{text:t}=n.data;return t?t.includes(tn)?(be&&console.log(`${e} has tag. returning true. (I: 6d76b27d558d44f696582f41af561f29)`),!0):(be&&console.log(`${e} no indicator found. returning false. (I: 815f181a0a08058362f76b08a8964674)`),!1):(be&&console.log(`${e} text falsy (I: e348e38c841b4443b3f09e75c0215b24)`),!1)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{be&&console.log(`${e} complete.`)}}p(Fo,"isFunctionCallRequestComment");function Bo({functionInfoIbGib:n}){let e=`[${Bo.name}]`;try{if(be&&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:i,fnResult:o}=n.data;if(!t)throw new Error(`${e} functionInfoIbGib.data.fnName is required. (E: 6f7a8b1c2d3e4f5a6b7c8d9e)`);return{call:{functionCall:{name:t,args:i??{}}},response:{functionResponse:{name:t,response:{value:o}}}}}catch(t){throw console.error(`${e} Error: ${y(t)}`),t}finally{be&&console.log(`${e} complete.`)}}p(Bo,"getFunctionCallAndResponseParts");var Mt=J,zn="function_info",cl="function_info";function dl({data:n}){let e=`[${dl.name}]`,{model:t,api:i,agentId:o,timestamp:s}=n;if(!t)throw new Error(`${e} data.model falsy (E: 6f47a28c0a8a45d794149c83e8f27e25)`);if(!i)throw new Error(`${e} data.api falsy (E: a0a812508a952a87c619d38084b7e325)`);if(!o)throw new Error(`${e} data.agentId falsy (E: ac35c1592c458e2c0e5908f6a9a3e525)`);let a=Ke(s);if([t,i,o,a].some(d=>d.includes(" ")))throw new Error("invalid data. ib must not contain spaces (E: 36a56e4685163848458be06f51d4ad25)");return[cl,a,t,i,o].join(" ")}p(dl,"getFunctionInfoIb");async function Kn(n){let e=`[${Kn.name}]`;try{Mt&&console.log(`${e} starting... (I: f4c9f0810a4d877f676297f6e6a96825)`);let{fnRawRequest:t,api:i,model:o,agentId:s,fnName:a,fnArgs:c,fnResult:d,fnComplete:u,parseErrorMsg:f,execErrorMsg:h,repromptWithResult:m,saveInSpace:g,metaspace:b,space:E}=n,w=new Date,v={name:o,timestamp:Ft(w),timestampMs:w.getMilliseconds(),agentId:s,api:i,model:o,fnRawRequest:t,fnName:a,fnArgs:c,fnResult:d,fnComplete:u,repromptWithResult:m};f&&(v.parseErrorMsg=f),h&&(v.execErrorMsg=h);let I=dl({data:v}),T=await oe.firstGen({ib:I,parentIbGib:oe.primitive({ib:cl}),data:v,nCounter:!0,dna:!0,tjp:{uuid:!0}});if(Mt&&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}),Mt&&console.log(`${e} persisted resFunctionInfo (${C({ibGib:T.newIbGib})}) to space ${E.data?.uuid} (I: aa98e877d3b34e0d2a3b7711f8f27e25)`),await b.registerNewIbGib({ibGib:T.newIbGib,space:E}),Mt&&console.log(`${e} registered new function info ibgib (${C({ibGib:T.newIbGib})}) with metaspace (I: aa98e877d3b34e0d2a3b7711f8f27e25)`)}return T}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Mt&&console.log(`${e} complete.`)}}p(Kn,"createFunctionInfoIbGib");var M=J,Jn=class n extends Ps{static{p(this,"AgentWitness_V1")}lc=`[${n.name}]`;availableFunctions=new Map;commentIbGibs_system=[];commentIbGibs_chat=[];_metaspace;fnGetAPIKey=p(()=>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=p(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=st({count:32})}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{M&&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(Ut)||t.push(`agent.data.subSpaceId must match regexp: ${Ut}. (E: f381eff533aa3f4713316f93f7f1dc25)`),this.data.name?this.data.name.match(ct)||t.push(`agent name must match regexp: ${ct}`):t.push("agent name falsy (E: 1351325107e5ac5ea6b7b789b73de125)"),this.data.description&&(this.data.description.match(yi)||t.push(`agent description must match regexp: ${yi}`))):t.push("this.data falsy (E: f5f151e11b12cad814b37ecad7c74a25)"),t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{M&&console.log(`${e} complete.`)}}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{M&&console.log(`${e} starting... (I: ce38519ac4bef52844a558fe31cda825)`),await super.initialize(),this._metaspace=await D();let t=new Ue;if(await t.initialized,!t.contextUpdated$)throw new Error("(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: e8840870af18091e6e4d52490ddca825)");if(t.contextUpdated$.subscribe(Ge({next:p(async i=>{let o=`${e}[ibGibProxy.contextUpdated$][next]`;M&&console.log(`${o} nextIbGib: ${L(i)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleContextUpdated()},"next"),error:p(async i=>{debugger;console.error(`${e}[ibGibProxy.contextUpdated$][error] what up? ${y(i)}`)},"error")})),this.ib&&this.gib&&this.data){let i=this.toIbGibDto();await this.loadIbGibDto(i);let o=await this._metaspace.getLocalUserSpace({localSpaceId:i.data?.superSpaceId});if(!o)throw new Error(`couldn't get local space with agent.data.superSpaceId (${i.data?.superSpaceId})? (E: 0fc1b8a8ffa26f39d8a15218ec818725)`);await this.ibGibProxy?.setWrappedIbGib({ibGib:i,space:o})}else M&&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{M&&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(C({ibGib:this})!==C({ibGib:this.ibGibProxy.ibGib})){let t=this.ibGibProxy.ibGib.data.n??0,i=this.data?.n??0;if(t<=i){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 H(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{M&&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 i=await t.getLocalUserSpace({localSpaceId:this.data.subSpaceId});if(!i){let o=await this.validateThis();if(o.length>0)throw new Error(`this agent has validation errors: ${o} (E: 9a0c6125cf89789ddb1610cf5a752225)`);if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 06e30e1d53fd4935333c7cf7e10db425)");i=await t.createLocalSpaceAndUpdateBootstrap({allowCancel:!1,zeroSpace:t.zeroSpace,spaceName:this.name+this.uuid.substring(0,5),createBootstrap:!1})}if(!i)throw new Error("(UNEXPECTED) space still falsy after creating locally? (E: 037ef1e6f54a675d0367227fdae16525)");return i}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{M&&console.log(`${e} complete.`)}}async getSuperSpace(){let e=`[${this.getSuperSpace.name}]`;try{M&&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 i=await t.getLocalUserSpace({localSpaceId:this.data.superSpaceId});if(!i)throw new Error(`(UNEXPECTED) superSpace falsy? this.data.superSpaceId: ${this.data.superSpaceId} (E: fd9435212e8b87e4b60034bf9e797f25)`);return i}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{M&&console.log(`${e} complete.`)}}_activeContext=void 0;async setActiveContext(e){let t=`${this.lc}[${this.setActiveContext.name}]`;try{M&&console.log(`${t} starting... (I: genuuid)`);let{contextIbGib:i,loggingInfo:o}=e;if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: ab5377fda6bc324638722d9832bab925)");if(!i)throw new Error("(UNEXPECTED) contextIbGib falsy? (E: 694525e512cfdd12c14e1213dbaab925)");if(!i.data)throw new Error("(UNEXPECTED) contextIbGib.data falsy? (E: f337252a23c822bcbd76144540050825)");let s=C({ibGib:i}),a=Q({ibGib:i});if(!a)throw new Error(`(UNEXPECTED) contextTjpAddr falsy? contextIbGib (${s}) 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?M&&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(Ge({next:p(async f=>{console.log(`${d}[next] nextIbGib: ${L(f)}`)},"next"),complete:p(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:p(async f=>{debugger;console.error(`${d}[error] ${y(f)}`)},"error")}));let u=`${t}[newContextChild]`;if(!c.newContextChild$)throw new Error("(UNEXPECTED) proxy.newContextChild$ falsy? (E: 123cf5624c3d2a6308aafc0c41f8a925)");c.newContextChild$.subscribe(Ge({next:p(async f=>{if(console.log(`${u}[next] newChild: ${L(f)}`),!f.data)throw new Error("newChild.data falsy? (E: a654134a2695c176971b0cd1426ced25)");if(Ze({ibGib:f})){let h=this.commentIbGibs_chat.map(w=>Q({ibGib:w})??C({ibGib:w})),m=Q({ibGib:f})??C({ibGib:f});if(h.includes(m)){console.log(`${t} already did this comment (${m}) (I: bce18642bb9babeb553e6188d7ae2825)`);return}let{safeIbCommentMetadataText:g}=Ye({ib:f.ib}),{textSrc:b}=Dt({addlMetadataText:g??"",ifError:"warn"}),E=f.data.text.startsWith("system: ");await this.addTexts({infos:[{textSrc:b??X.UNKNOWN,commentIbGib:f,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:p(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:p(async f=>{debugger;console.error(`${u}[error] ${y(f)}`)},"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:i})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{M&&console.log(`${t} complete.`)}}async updateName({name:e}){let t=`${this.lc}[${this.updateName.name}]`;try{if(M&&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(ct.test(e))await this.mut8Self({dataToAddOrPatch:{name:e}});else throw new Error(`invalid name ${e}. must match regexp: ${ct.source} (E: 507a2bfc0aaa60bd7bb608d253239e25)`)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{M&&console.log(`${t} complete.`)}}async updateAvailableFunctions({availableFunctions:e}){let t=`${this.lc}[${this.updateAvailableFunctions.name}]`;try{M&&console.log(`${t} starting... (I: 68f1bfa343925a657f8c0545b191c725)`);let i=[];for(let o of e)if(!this.availableFunctions.has(o.nameOrId)){let s=it().get(o.nameOrId);if(s)i.push(s);else{console.error(`(UNEXPECTED) ${o} function not registered with getAllFunctionInfos()? skipping adding this function to the agent... (E: e860fe13c02677b274ac0e7df2587a25)`);continue}}i.length>0&&(console.log(`${t} adding newly found functions to agent: ${i.map(o=>o.nameOrId)}. (I: ab2b0ae6a62b3ced6a5f1e2e8cec4f25)`),await this.addAvailableFunctions(i))}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{M&&console.log(`${t} complete.`)}}async mut8Self({dataToAddOrPatch:e}){let t=`${this.lc}[${this.mut8Self.name}]`;try{M&&console.log(`${t} starting... (I: f4618832a0fe07ff8c89cea889d20725)`);let i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: genuuid)");let o=await i.getLocalUserSpace({lock:!1,localSpaceId:this.data.superSpaceId});if(!o)throw new Error(`couldn't get local superSpace given by this.data.superSpaceId (${this.data.superSpaceId}) (E: genuuid)`);let{tjpGib:s}=z({gib:this.gib});if(!s)throw new Error(`(UNEXPECTED) this.gib (${this.gib}) has no tjpGib? (E: 75b8dcb82b58d3b0db40b39149023e25)`);await qt({fn:p(async()=>{let a=Re();await a.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1});let c=await ss({type:"mut8",src:this.toIbGibDto(),dataToAddOrPatch:e,dna:!0,nCounter:!0});await i.persistTransformResult({resTransform:c,space:o});let d=c.newIbGib;await this.loadIbGibDto(d),await a.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!0}),await i.registerNewIbGib({ibGib:d,space:o}),await Vo({newAgentIbGib:d,metaspace:i,space:o,type:this.data.type})},"fn"),scope:s,secondsValid:60,maxDelayMs:100,maxLockAttempts:Number.MAX_SAFE_INTEGER,space:o,callerInstanceId:this.instanceId})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{M&&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(M&&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 Re().updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1}),e.forEach(o=>{this.availableFunctions.has(o.nameOrId)&&console.warn(`${t} this.availableFunctions already has an entry for ${o.nameOrId}. replacing anyway. (W: ef2372a27be67174cb3605eac2c85c25)`),this.availableFunctions.set(o.nameOrId,o)}),await this.mut8Self({dataToAddOrPatch:{availableFunctionNameOrIds:Array.from(this.availableFunctions.keys())}})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{M&&console.log(`${t} complete.`)}}async doPrompt(){let e=`[${this.doPrompt.name}]`;try{if(M&&console.log(`${e} starting... (I: e7f1a7845cdf1bdce1f12d74c71a6425)`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 3c528e2376a2f2600b347b2c183a5225)");let t=await this.composePromptInfo();M&&console.log(`${e} promptTextInfo: ${L(t)} (I: b769b5f2a47623a99f78210994d90525)`);let i=await this.callTextAPI(t);if(M&&console.log(`${e} api result:`,i,"(I: e4d2c767eb3d6e38d83123d684a07425)"),"text"in i)await this.doPrompt_text(i.text);else{let{functionCalls:o}=i;await this.doPrompt_functionCalls({functionCalls:o})}}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{M&&console.log(`${e} complete.`)}}async doPrompt_text(e){let t=`${this.lc}[${this.doPrompt_text.name}]`;try{M&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{M&&console.log(`${t} complete.`)}}async doPrompt_functionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls.name}]`;try{if(M&&console.log(`${t} starting... (I: a4f1b581517a9c2a9187e9f8f3519925)`),e.length===0)throw new Error("(UNEXPECTED) functionCalls.length is zero? (E: 6434b8515a435a59b331452b563f4425)");let i=await this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({functionCalls:e});if(await this.doPrompt_functionCalls_addFunctionCallRequestComment({functionInfoIbGibs:i}),i.some(s=>!!s.data?.repromptWithResult&&s.data.fnName!=="tellUser")){let s=await this.doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt({functionInfoIbGibs:i});s.length>0?(console.log(`${t} transientDecompressionPromptText: ${s} (I: 11c11d544b7c8f8f8e7e5f7c1a9e3625)`),this.transientDecompressionPromptText=s,await this.rePrompt()):console.warn(`${t} (UNEXPECTED) there is no decompression text? (W: 6ce5da95c1c89a7ec48a00fbc1d11825)`)}else M&&console.log(`${t} no repromptWithResult. returning early. (I: 9c0113c958c7404534291f6700325925)`)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{M&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls.name}]`;try{if(M&&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 i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: acf8a69e853eb8663f1dd0f79a823e25)");let o=[];for(let s of e)try{M&&console.log(`${t} processing functionCall: ${s} (I: a0c0b22b3c6b6c4b674a5a9c8c8b9e25)`);let a,c,d,u,f,h="";try{if(c=JSON.parse(s),h=c?.name??"",!h)throw new Error("functionName (functionCallParsedObj.name) falsy (E: e2397d675863a12b7609495b0007a025)");if(M&&console.log(`${t} functionCallParsedObj:`,L(c),"(I: 750f097243b85644d111971e0f929c25)"),u=it().get(c.name),!u)throw new Error(`no APIFunctionInfo found that matches functionName (${h}) (E: 9d36b6472ec5cdf95e4f498292449925)`);f=c.args,M&&console.log(`${t} valid params (I: a4d5c13c79a2405c8d20464b42083325)`)}catch(m){d=`${t} invalid functionCallParsedObj. error: ${y(m)}. functionCallStr: ${s}. (E: 1687a24c5a3667d34689a09f8f753125)`,console.error(d),c=void 0}if(u){M&&console.log(`${t} found functionInfo: ${u.nameOrId} (I: 837c7a8200689a0b2314b73057812b25)`);let m,g=!1,b;try{M&&console.log(`${t} calling function impl for ${u.nameOrId} (I: b145d08186782089c18564305f0f1125)`),m=await u.fnViaCmd(f),g=!0,M&&console.log(`${t} functionImpl complete for ${u.nameOrId}. result:`,L(m),"(I: e19d476f489261263165914750472d25)")}catch(w){b=`${t} could not call functionImpl for ${u.nameOrId}: ${y(w)} (E: 9c0e97f29a9290f9d57637b7053f0c25)`,console.error(b)}a=(await Kn({api:this.data.api,model:this.data.model,agentId:this.data.uuid,fnRawRequest:s,fnName:h,fnArgs:c.args,repromptWithResult:c.args?.repromptWithResult??!1,fnResult:m,fnComplete:g,execErrorMsg:b,parseErrorMsg:void 0,saveInSpace:!0,metaspace:i,space:await this.getSuperSpace()})).newIbGib}else a=(await Kn({api:this.data.api,model:this.data.model,agentId:this.data.uuid,fnRawRequest:s,fnName:h,fnArgs:c.args,repromptWithResult:c.args?.repromptWithResult??!1,fnResult:void 0,fnComplete:void 0,execErrorMsg:void 0,parseErrorMsg:d,saveInSpace:!0,metaspace:i,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)");o.push(a)}catch(a){throw console.error(`${t} ${y(a)}`),a}finally{M&&console.log(`${t} complete.`)}if(o.length===0)throw new Error("(UNEXPECTED) functionInfoIbGibs.length === 0? We expect at least one to be created (E: a8f81c56377cdbdeb468af6b21879825)");return o}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{M&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_addFunctionCallRequestComment({functionInfoIbGibs:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_addFunctionCallRequestComment.name}]`;try{M&&console.log(`${t} starting... (I: 5000adac5e8c4a7158a720c38f56b325)`);let i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: d7275731461d8d0526af3088553ae525)");let o=await this.getSuperSpace(),s=dt({tagText:tn,contentText:e.map(f=>C({ibGib:f})).join(`
|
|
679
|
-
`),randomIdLength:4}),a=
|
|
680
|
-
`)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{M&&console.log(`${t} complete.`)}}repromptCount=0;repromptMax=12;async rePrompt(){let e=`${this.lc}[${this.rePrompt.name}]`;try{M&&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{M&&console.log(`${e} complete.`)}}async witness(e){if(e.ib===Vt&&e.gib===Ht)return this.getComments_Chat().length>0&&await this.doPrompt(),Tt;throw new Error(`arg (${L(e)}) not implemented. only expect ${Tt} right now to trigger doPrompt. (E: 24da0ad7333b6bbb359d1be425db3c25)`)}};var F=J,Ve=class n extends Jn{static{p(this,"AgentWitnessGemini_V1")}lc=`[${n.name}]`;async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{F&&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{F&&console.log(`${e} complete.`)}}parseAddlMetadataString({ib:e}){let t=`${this.lc}[${this.parseAddlMetadataString.name}]`;try{throw F&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{F&&console.log(`${t} complete.`)}}async addTexts(e){let t=`${this.lc}[${this.addTexts.name}]`;try{let i=Re();await i.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1});let o=this._metaspace;if(!o)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 s=[],a=[],c=[],d=await this.getSuperSpace();for(let h of e.infos){let{textSrc:m,isSystem:g}=h,{text:b,commentIbGib:E}=h;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 w=vt({textSrc:m});if(E)F&&console.log(`${t} adding existing commentIbGib (I: 72a3f7aafde92f65b168d27605f94625)`);else{if(F&&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 Qe({text:b,addlMetadataText:w,saveInSpace:!0,space:d})).newIbGib,await o.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 Yn({ibGib:E});if(v.length>0)throw new Error(`validation errors with trying to add a commentIbGib. errors: ${v} (E: beee1893050f9bcf9842c66831595225)`);s.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 f=await Ns({timeline:this.toIbGibDto(),rel8nInfos:u,timelineIndexInfo:{rel8nName:je,type:this.data.type},metaspace:o,space:d});return await this.loadIbGibDto(f),await i.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!0}),s}catch(i){throw console.error(`${t} ${y(i)}`),i}}async composePromptInfo(){let e=`${this.lc}[${this.composePromptInfo.name}]`;try{if(F&&console.log(`${e} starting... (I: 155774d4811b038034342d5750174325)`),!this._metaspace)throw new Error("this.metaspace falsy (E: 7232a3a1b4348d460ed1375b32677125)");let t=[];for(let f of this.commentIbGibs_system){let h=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:f});t.push(...h)}let i=this.data?.["@currentContextTjpAddr"]??W;if(i!==W&&t.push({src:X.HARDCODED,content:{role:Gt(X.HARDCODED),parts:[{text:ul({currentContextTjpAddr:i})}]}}),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 o=[],s=this.commentIbGibs_chat.length>1?this.commentIbGibs_chat.slice(0,-1):[];for(let f of s){let h=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:f});o.push(...h)}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)o.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:o,chatPromptCurrent:a};return F&&console.log(`${e} resPromptInfo:`,L(u),"(I: 8f17a8c45b9a91e20a5c5064d9114a25)"),u}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{F&&console.log(`${e} complete.`)}}async callTextAPI(e){let t=`${this.lc}[${this.callTextAPI.name}]`;try{if(F&&console.log(`${t} starting... (I: 27885f5b14682646542e9658417b2f25)`),!ll(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:i,model:o}=this.data;if(i!=="gemini")throw new Error(`api not supported: ${i} (E: 7e5c7c17988a666a86e72299630c7f25)`);F&&console.log(`${t} calling gemini api with model: ${o} (I: 6208942a419e9041bb037384135a0c25)`);let s=await this.fnGetAPIKey();if(!s)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 Rt({apiKey:s});let a=Array.from(this.availableFunctions.values()).map(I=>({name:I.nameOrId,description:I.schema?.description,parameters:I.schema?.parameters}));a.some(I=>I.parameters==="undefined")&&console.error(`${t} (UNEXPECTED) function schema parameters not defined for all APIFunctionInfo values. (E: ae7227cdd65c0ab4513c7b282a1e4825)`),F&&(console.log(`${t} Gemini functionDeclarations:`),console.dir(a));let{systemPromptEntries:c,chatPromptHistoryParts:d,chatPromptCurrent:u}=e,f=ie(u);F&&console.log(`chatPromptCurrent_final (before decompression): ${L(f)} (I: bbd4c7b9f3225afe9da1761918d0ac25)`),F&&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 h,m=p(async I=>{if(!this._genAI)throw new Error("(UNEXPECTED) this._genAI falsy? (E: 503a0d9e3f729de7653ee3565b017b25)");let T=d.map(P=>P.content),S={model:I,history:T,config:{systemInstruction:Uo({systemPromptEntries:c}),tools:[{functionDeclarations:a}],toolConfig:{functionCallingConfig:{mode:e.overrideFunctionCallingMode??fn.ANY}}}},N=this._genAI.chats.create(S),$={message:u.content.parts};return await N.sendMessage($)},"fnGoModel"),g=0,b=o;do{g++;try{h=await m(b);break}catch(I){let T=I.message,S=I.status??"[STATUS?]";T.includes(`${503}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${ut}) for this next call. error (${I.status}): ${y(I)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=ut):T.includes(`${429}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${ut}) for this next call. error (${I.status}): ${y(I)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=ut):console.error(`${t}[fnGoModel][${b}] error trying to get result from model. error (${I.status}): ${y(I)} (E: a67d595c8ed313d458369d4d0b3e7f25)`)}await H(2e3)}while(!h&&g<Ai);if(!h)throw new Error("couldn't get result from model (E: ede013a53f875d99a96a2e257c7e7125)");let E=h,w=[],v=E.candidates?.[0]?.content?.parts||[];for(let I of v)I.functionCall&&w.push(I.functionCall);if(!w||w.length===0){if(F&&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 F&&(console.log(`${t} Gemini function calls:`),console.dir(w)),{functionCalls:w.map(I=>JSON.stringify(I,null,2))}}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{F&&console.log(`${t} complete.`)}}async createPromptInfoEntriesFromGeminiComment({commentIbGib:e}){let t=`[${this.createPromptInfoEntriesFromGeminiComment.name}]`;try{F&&console.log(`${t} starting... (I: 826a9d6b120d96532afbe1f7a22e8d25)`);let i=await Yn({ibGib:e});if(i.length>0)throw new Error(`validation errors with commentIbGib. Cannot create a prompt info entry. errors: ${i} (E: beee1893050f9bcf9842c66831595225)`);let{safeIbCommentMetadataText:o}=Ye({ib:e.ib});if(!o)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:s,timestampInTicks:a,errorMsg:c,other:d}=Dt({addlMetadataText:o,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(Fo({ibGib:e})){let f=await this.getFunctionInfoIbGibs({fcrCommentIbGib:e}),h=[],m=[];for(let E of f){let{call:w,response:v}=Bo({functionInfoIbGib:E});if(!w)throw new Error("(UNEXPECTED) call falsy? (E: 5c8f3bd6de3b300e1c105b9603bb7b25)");if(!v)throw new Error("(UNEXPECTED) response falsy? (E: d0388c838975c93126c1a6d64f781d25)");if(w.functionCall.name!==v.functionResponse.name)throw new Error("(UNEXPECTED) functionCall.name !== functionResponse.name? (E: e49f0d60093354db2b6ad17fdf86d425)");h.push(w),m.push(v)}let g={src:X.AI,content:{role:Gt("ai"),parts:h}},b={src:X.FUNCTION,content:{role:Gt(X.FUNCTION),parts:m}};return[g,b]}else return[{src:s,content:{role:Gt(s),parts:[{text:e.data.text}]}}]}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{F&&console.log(`${t} complete.`)}}async promptOneOff(e){let t=`${this.lc}[${this.promptOneOff.name}]`;try{F&&console.log(`${t} starting... (I: genuuid)`);let{text:i,systemInstructions:o}=e;if(!i)throw new Error("(UNEXPECTED) opts.text falsy? (E: genuuid)");if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: genuuid)");let{api:s,model:a}=this.data;if(s!=="gemini")throw new Error(`api not supported: ${s} (E: genuuid)`);F&&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 Rt({apiKey:c});let d=p(async b=>{if(!this._genAI)throw new Error("(UNEXPECTED) this._genAI falsy? (E: fbe235713d48f0d8e87cd0b88ec54825)");let E={model:b,config:{systemInstruction:o}},v=await this._genAI.chats.create(E).sendMessage({message:i});if(v.text)return v.text;throw new Error("response.text empty/falsy, potentially blocked by safety settings (E: a21a78c9471f27a42c07d1c859187825)")},"fnGoModel"),u,f=0,h=[];e.modelOverrides&&e.modelOverrides.length>0?h.push(...e.modelOverrides):h.push(a),e.modelBackupOverrides&&e.modelBackupOverrides.length>0?h.push(...e.modelBackupOverrides):h.push(ut);let m=0,g=1;do{f++,g++;let b=h[m];try{u=await d(b);break}catch(E){if(E instanceof Error){let w=E.message,v=E.status??"[STATUS?]";if(w.includes(`${503}`))if(m===h.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{m++;let I=h[m];console.error(`${t}[fnGoModel][${b}] error trying to get result from model: GEMINI_ERROR_STATUS_MODEL_OVERLOADED ${503}. will try using the next model (${I}) for this next call. error (${v}): ${y(E)} (E: b07a041bb97ea95b03cd6f9856f01525)`)}else if(w.includes(`${429}`))if(m===h.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{m++;let I=h[m];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 (${I}) 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)`)}f>1&&await H(g*1e3)}while(!u&&f<Ai);return u}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{F&&console.log(`${t} complete.`)}}async getFunctionInfoIbGibs({fcrCommentIbGib:e}){let t=`[${this.getFunctionInfoIbGibs.name}]`;try{F&&console.log(`${t} starting... (I: 976a684b7ae58cda523b17fc0c62e325)`);let i=[];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 o=this._metaspace;if(!o)throw new Error("(UNEXPECTED) this.metaspace falsy. (E: 997d071847c5d7e80692f48191244e25)");let s=await this.getSuperSpace();if(!s)throw new Error("(UNEXPECTED) superSpace falsy? (E: dd1600f15e1e659c01f73991656a3325)");let a=e.rel8ns?.[zn]??[];if(a.length===0)return F&&console.warn(`${t} no functionInfoAddrs (I: 5f8965e92c305689c11677a1148b7425)`),[];F&&console.log(`${t} functionInfoAddrs: ${a} (I: e7b1f5a4576c493326b913e48a505e25)`);let c=await o.get({addrs:a,space:s});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 i=c.ibGibs,F&&console.log(`${t} resFunctionInfoIbGibs: ${L(i.map(d=>C({ibGib:d})))} (I: a5661b5c449608f0e8d773135a599a25)`),i}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{F&&console.log(`${t} complete.`)}}async loadIbGibDto(e){let t=`[${this.loadIbGibDto.name}]`;try{if(F&&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 i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: e5762b1e3f77f84ca338641edc011225)");let o=await this.getSuperSpace(),s=p(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=it().get(d);u?this.availableFunctions.set(d,u):Lo().includes(d)?F&&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 i.get({addrs:a,space:o});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 i.get({addrs:c,space:o});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 qt({scope:"prune",secondsValid:60,maxDelayMs:100,maxLockAttempts:1800,space:o,callerInstanceId:Ke(),fn:s})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{F&&console.log(`${t} complete.`)}}};setTimeout(()=>{Re().registerFactory({classname:Ve.name,fnDtoToAgentWitness:p(async e=>e.data?e.data.classname?e.data.classname===Ve.name?{applies:!0,agent:await Ho({agentIbGib:e})}:{applies:!1}:{applies:!1}:{applies:!1},"fnDtoToAgentWitness")})});function ul({currentContextTjpAddr:n}){let e=`[${ul.name}]`;try{F&&console.log(`${e} starting... (I: 7edafbba277d57eae51af325cf7eb225)`);let t=z({ibGibAddr:n});return`Your current context ibGibAddr is ${n}
|
|
681
|
-
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{
|
|
682
|
-
`)}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{Z&&console.log(`${i} complete.`)}}p(dt,"taggifyForPrompt");function vt({textSrc:n,other:e}){let t=`[${vt.name}]`;return e?[n,Ke(),e].join("_"):[n,Ke()].join("_")}p(vt,"getAddlMetadataTextForAgentText");function Dt({addlMetadataText:n,ifError:e="warn"}){let t=`[${vt.name}]`;try{Z&&console.log(`${t} starting... (I: 89b8b19a8d785b945fe0f816df762d25)`);let[i,o,...s]=n.split("_");if(!i)throw new Error("addlMetadataText.textSrc falsy (E: 40bbec4269c1688ab1390fa5d5440325)");if(!Ys(i))throw new Error(`addlMetadataText.textSrc (${i}) is unexpected value. Expected one of ${Ei} (E: 02bae41275a39210e5737548747bd825)`);if(!o)throw new Error("addlMetadataText.timestampInTicks falsy (E: 03cbbc7515a1cff1fc7c12e3947c6825)");let a=Number.parseInt(o);if(Number.isNaN(a))throw new Error(`invalid timestampInTicks (${o}): value should be an integer but parse is NaN (E: 9d31e3563d972c02553ce18a19a19b25)`);return{textSrc:i,timestampInTicks:a,other:s.length>0?s:void 0}}catch(i){let o=`${t} ${y(i)}`;switch(e){case"ignore":return{textSrc:X.UNKNOWN,timestampInTicks:0,errorMsg:y(i)};case"warn":return console.warn(`${t} ${o} (W: 3e1f4a98ad6461c9bd96462841c31b25)`),{textSrc:X.UNKNOWN,timestampInTicks:0,errorMsg:y(i)};default:throw console.error(`${t} ${o} (E: 6396ed44947c52adf85788e1adc22825)`),new Error(o)}}finally{Z&&console.log(`${t} complete.`)}}p(Dt,"parseAddlMetadataTextForAgentText");function _i({data:n}){let e=`[${_i.name}]`,{name:t,uuid:i,type:o}=n;if(!t)throw new Error(`${e} data.name falsy (E: 4c172c5b8a110ae26479b8c4006f3225)`);if(!i)throw new Error(`${e} data.uuid falsy (E: 67d2c79ac39e70e5ecfd1745e1fd3525)`);if(!o)throw new Error(`${e} data.type falsy (E: 53bf1f9a145a16be81296437682a7a25)`);if([t,i,o].some(a=>a.includes(" ")))throw new Error("invalid data. ib must not contain spaces in name, uuid, type. (E: 36a56e4685163848458be06f51d4ad25)");return[lt,t,i,o].join(" ")}p(_i,"getAgentIb");function js({ib:n}){let[e,t,i,o]=n.split(" ");if(e!==lt)throw new Error(`invalid ib. first term expected to e an atom: ${lt} (E: 3c01d42035d2e32c4bfd5c1bf363f725)`);if(!t)throw new Error("invalid ib. name falsy in agent ib (E: 8b494c544f05b8ef9c866078b761a725)");if(!i)throw new Error("invalid ib. uuid falsy in agent ib (E: aba195db3ddcb000324ebed15351b725)");if(!o)throw new Error("invalid ib. type falsy in agent ib (E: 8c814772394ae76342f95e885570c325)");return{atom:e,name:t,uuid:i,type:o}}p(js,"parseAgentIb");async function Yn({ibGib:n}){let e=`[${Yn.name}]`;try{Z&&console.log(`${e} starting... (I: f9a733a5a05b7f7494836d86a79e2d25)`);let t=await rt({ibGib:n})??[];if(!Ze({ibGib:n}))return t.push(`${e} not a comment ibgib (E: 08676d94c698c6e42e6c35e94a58f125)`),t;let{safeIbCommentMetadataText:i}=Ye({ib:n.ib});if(i){let o=Dt({addlMetadataText:i,ifError:"warn"});o.errorMsg&&t.push(`${e} could not parse addlMetadataText: ${o.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.`)}}p(Yn,"validateAgentWitnessCommentIbGib");var Zn="settings",Um="general",Fm="text-editor",Bm="projects",Vm="projects-explorer",Hm="projects-dropdown",qm="project",Om="minigame",zm="chronologys",Km="identity-manager",ne={general:Um,textEditor:Fm,projects:Bm,projectsExplorer:Vm,projectsDropdown:Hm,project:qm,minigame:Om,chronologys:zm,identityManager:Km},Jm=Object.values(ne);var Oo={type:ne.general,editor:void 0,readonly:!0,viewer:"ibgib-raw-viewer"},zo={type:ne.textEditor,wrap:"wrap"},Wm={type:ne.project,openChildTjpAddrs:[],activeChildTjpAddr:void 0,lensMode:"raw"},Xm={type:ne.minigame},Ym={type:ne.chronologys,openChildTjpAddrs:[],activeChildTjpAddr:void 0},Qm={type:ne.identityManager,openChildTjpAddrs:[],activeChildTjpAddr:void 0},fl={sections:{},children:{}};var qe=J;async function Ko({ibGib:n}){let e=`[${Ko.name}]`;try{qe&&console.log(`${e} starting... (I: 57ac4c0a3448bc5e98ecf5bfb02ce825)`);let{ib:t}=q({ibGib:n}),i=t.split(" ").at(0);if(!i)throw new Error("(UNEXPECTED) atom falsy? we split the ib by spaces (space-delimiter). this makes no sense. (E: 6a9ea640ae38823aeefc6ec82a05d625)");return`${Zn}_${i}`}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{qe&&console.log(`${e} complete.`)}}p(Ko,"getSettingsScope");async function Ee({settingsType:n,useCase:e}){let t=`[${Ee.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(i){throw console.error(`${t} ${y(i)}`),i}finally{qe&&console.log(`${t} complete.`)}}p(Ee,"getSectionName");async function jn({sectionName:n,settingsIbGib:e}){let t=`[${jn.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(i){throw console.error(`${t} ${y(i)}`),i}finally{qe&&console.log(`${t} complete.`)}}p(jn,"getSettingsSection");function pl({scope:n}){let e=`[${pl.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,"__")),`${Zn} ${n}`}catch(t){throw console.error(`${e} ${y(t)}`),t}}p(pl,"getSettingsIb");async function Jo({scope:n,metaspace:e,space:t,saveInSpace:i}){let o=`[${Jo.name}]`;try{let s=pl({scope:n}),a=await hl(),d=await oe.firstGen({parentIbGib:oe.primitive({ib:Zn}),ib:s,data:a,rel8ns:void 0,dna:!0,nCounter:!0,tjp:{timestamp:!0,uuid:!0}});if(i){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(s){throw console.error(`${o} ${y(s)}`),s}}p(Jo,"createSettings");async function hl(){let n=`[${hl.name}]`;try{qe&&console.log(`${n} starting... (I: 3d7cc3f242cc88ad28dafaf85d646a25)`);let e=ie(fl),t=await Ee({settingsType:"general",useCase:"default"}),i=await Ee({settingsType:"general",useCase:"current"});e.sections[t]=ie(Oo),e.sections[i]=ie(Oo);let o=await Ee({settingsType:"text-editor",useCase:"default"}),s=await Ee({settingsType:"text-editor",useCase:"current"});return e.sections[o]=ie(zo),e.sections[s]=ie(zo),e}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{qe&&console.log(`${n} complete.`)}}p(hl,"getDefaultSettingsData");var R=J,ce=class n{static{p(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{p(this,"IbGibDynamicComponentInstanceBase")}lc=`[${n.name}]`;elements;createdPromise;settings;get agent(){return this.agents.at(0)}agents=[];get ib(){let{ib:e}=q({ibGibAddr:this.ibGibAddr??W});return e}get gib(){let{gib:e}=q({ibGibAddr:this.ibGibAddr??W});return e}ibGibAddr=W;ibGibProxy;get ibGib(){let e=this.ibGibAddr??W,{ib:t,gib:i}=q({ibGibAddr:e});return this.ibGibAddr&&!Ct({gib:i})?this.ibGibProxy?.ibGib:oe.primitive({ib:t})}get tjpAddr(){return this.ibGib?Q({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:i,localOnly:o,animationEmoji:s}){let a=`${this.lc}[${this.showBusy.name}]`;try{this._isBusy=e,o?this.dispatchEvent(new CustomEvent(_t,{detail:{isBusy:e,title:t,msg:i,animationEmoji:s},bubbles:!0,composed:!0})):window.dispatchEvent(new CustomEvent(_t,{detail:{isBusy:e,title:t,msg:i,animationEmoji:s}}))}catch(c){throw console.error(`${a} ${y(c)}`),c}}async getMetaspace(){let e=`${this.lc}[${this.getMetaspace.name}]`;try{if(R&&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{R&&console.log(`${e} complete.`)}}constructor(){super(),this._instanceId=st({count:8})}async initialize(e){let{ibGibAddr:t,meta:i,html:o,css:s}=e,a=`${this.lc}[${this.initialize.name}]`;try{R&&console.log(`${a} starting... (I: c9b94131bc2f0d20e1397c214dad6725)`),this.ibGibAddr=t,this.meta=i,this.html=o,this.css=s,this.attachShadow({mode:"open"}),await this.meta.bootstrapPromise}catch(c){throw console.error(`${a} ${y(c)}`),c}finally{R&&console.log(`${a} complete.`)}}async initAgents(){let e=`${this.lc}[${this.initAgents.name}]`;R&&console.log(`${e} does nothing in base class (I: 0b31a650b942619a0e36a1a7f763e825)`)}async connectedCallback(){let e=`${this.lc}[${this.connectedCallback.name}]`;try{R&&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{R&&console.log(`${e} complete.`)}}async connectedCallback_initComponent(){let e=`${this.lc}[${this.connectedCallback_initComponent.name}]`;try{if(R&&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?`
|
|
674
|
+
${h}`)}return a},"path"),"createPathTagFunction"),dn=rm(cl);var qn=class extends Vn{static{p(this,"BaseInteractions")}create(e,t){var i;let{api_version:o=this._client.apiVersion}=e,s=$n(e,["api_version"]);if("model"in s&&"agent_config"in s)throw new ge("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in s&&"generation_config"in s)throw new ge("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(dn`/${o}/interactions`,Object.assign(Object.assign({body:s},t),{stream:(i=e.stream)!==null&&i!==void 0?i:!1}))}delete(e,t={},i){let{api_version:o=this._client.apiVersion}=t??{};return this._client.delete(dn`/${o}/interactions/${e}`,i)}cancel(e,t={},i){let{api_version:o=this._client.apiVersion}=t??{};return this._client.post(dn`/${o}/interactions/${e}/cancel`,i)}get(e,t={},i){var o;let s=t??{},{api_version:a=this._client.apiVersion}=s,c=$n(s,["api_version"]);return this._client.get(dn`/${a}/interactions/${e}`,Object.assign(Object.assign({query:c},i),{stream:(o=t?.stream)!==null&&o!==void 0?o:!1}))}};qn._key=Object.freeze(["interactions"]);var Hn=class extends qn{static{p(this,"Interactions")}};function am(n){let e=0;for(let o of n)e+=o.length;let t=new Uint8Array(e),i=0;for(let o of n)t.set(o,i),i+=o.length;return t}p(am,"concatBytes");var un;function qo(n){let e;return(un??(e=new globalThis.TextEncoder,un=e.encode.bind(e)))(n)}p(qo,"encodeUTF8");var fn;function Aa(n){let e;return(fn??(e=new globalThis.TextDecoder,fn=e.decode.bind(e)))(n)}p(Aa,"decodeUTF8");var vt=class{static{p(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"?qo(e):e;this.buffer=am([this.buffer,t]);let i=[],o;for(;(o=lm(this.buffer,this.carriageReturnIndex))!=null;){if(o.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=o.index;continue}if(this.carriageReturnIndex!=null&&(o.index!==this.carriageReturnIndex+1||o.carriage)){i.push(Aa(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null;continue}let s=this.carriageReturnIndex!==null?o.preceding-1:o.preceding,a=Aa(this.buffer.subarray(0,s));i.push(a),this.buffer=this.buffer.subarray(o.index),this.carriageReturnIndex=null}return i}flush(){return this.buffer.length?this.decode(`
|
|
675
|
+
`):[]}};vt.NEWLINE_CHARS=new Set([`
|
|
676
|
+
`,"\r"]);vt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function lm(n,e){for(let o=e??0;o<n.length;o++){if(n[o]===10)return{preceding:o,index:o+1,carriage:!1};if(n[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}p(lm,"findNewlineIndex");function cm(n){for(let i=0;i<n.length-1;i++){if(n[i]===10&&n[i+1]===10||n[i]===13&&n[i+1]===13)return i+2;if(n[i]===13&&n[i+1]===10&&i+3<n.length&&n[i+2]===13&&n[i+3]===10)return i+4}return-1}p(cm,"findDoubleNewlineIndex");var On={off:0,error:200,warn:300,info:400,debug:500},xa=p((n,e,t)=>{if(n){if(qh(On,n))return n;fe(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(On))}`)}},"parseLogLevel");function Mt(){}p(Mt,"noop");function pn(n,e,t){return!e||On[n]>On[t]?Mt:e[n].bind(e)}p(pn,"makeLogFn");var dm={error:Mt,warn:Mt,info:Mt,debug:Mt},Na=new WeakMap;function fe(n){var e;let t=n.logger,i=(e=n.logLevel)!==null&&e!==void 0?e:"off";if(!t)return dm;let o=Na.get(t);if(o&&o[0]===i)return o[1];let s={error:pn("error",t,i),warn:pn("warn",t,i),info:pn("info",t,i),debug:pn("debug",t,i)};return Na.set(t,[i,s]),s}p(fe,"loggerFor");var it=p(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 Ao=class n{static{p(this,"Stream")}constructor(e,t,i){this.iterator=e,this.controller=t,this.client=i}static fromSSEResponse(e,t,i){let o=!1,s=i?fe(i):console;function a(){return Se(this,arguments,p(function*(){var d,u,f,h;if(o)throw new ge("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let m=!1;try{try{for(var g=!0,b=Ae(um(e,t)),E;E=yield k(b.next()),d=E.done,!d;g=!0){h=E.value,g=!1;let w=h;if(!m)if(w.data.startsWith("[DONE]")){m=!0;continue}else try{yield yield k(JSON.parse(w.data))}catch(v){throw s.error("Could not parse message into JSON:",w.data),s.error("From chunk:",w.raw),v}}}catch(w){u={error:w}}finally{try{!g&&!d&&(f=b.return)&&(yield k(f.call(b)))}finally{if(u)throw u.error}}m=!0}catch(w){if(To(w))return yield k(void 0);throw w}finally{m||t.abort()}},"iterator_1"))}return p(a,"iterator"),new n(a,t,i)}static fromReadableStream(e,t,i){let o=!1;function s(){return Se(this,arguments,p(function*(){var d,u,f,h;let m=new vt,g=rl(e);try{for(var b=!0,E=Ae(g),w;w=yield k(E.next()),d=w.done,!d;b=!0){h=w.value,b=!1;let v=h;for(let I of m.decode(v))yield yield k(I)}}catch(v){u={error:v}}finally{try{!b&&!d&&(f=E.return)&&(yield k(f.call(E)))}finally{if(u)throw u.error}}for(let v of m.flush())yield yield k(v)},"iterLines_1"))}p(s,"iterLines");function a(){return Se(this,arguments,p(function*(){var d,u,f,h;if(o)throw new ge("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let m=!1;try{try{for(var g=!0,b=Ae(s()),E;E=yield k(b.next()),d=E.done,!d;g=!0){h=E.value,g=!1;let w=h;m||w&&(yield yield k(JSON.parse(w)))}}catch(w){u={error:w}}finally{try{!g&&!d&&(f=b.return)&&(yield k(f.call(b)))}finally{if(u)throw u.error}}m=!0}catch(w){if(To(w))return yield k(void 0);throw w}finally{m||t.abort()}},"iterator_2"))}return p(a,"iterator"),new n(a,t,i)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],i=this.iterator(),o=p(s=>({next:p(()=>{if(s.length===0){let a=i.next();e.push(a),t.push(a)}return s.shift()},"next")}),"teeIterator");return[new n(()=>o(e),this.controller,this.client),new n(()=>o(t),this.controller,this.client)]}toReadableStream(){let e=this,t;return sl({async start(){t=e[Symbol.asyncIterator]()},async pull(i){try{let{value:o,done:s}=await t.next();if(s)return i.close();let a=qo(JSON.stringify(o)+`
|
|
677
|
+
`);i.enqueue(a)}catch(o){i.error(o)}},async cancel(){var i;await((i=t.return)===null||i===void 0?void 0:i.call(t))}})}};function um(n,e){return Se(this,arguments,p(function*(){var i,o,s,a;if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ge("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 ge("Attempted to iterate over a response with no body");let c=new xo,d=new vt,u=rl(n.body);try{for(var f=!0,h=Ae(fm(u)),m;m=yield k(h.next()),i=m.done,!i;f=!0){a=m.value,f=!1;let g=a;for(let b of d.decode(g)){let E=c.decode(b);E&&(yield yield k(E))}}}catch(g){o={error:g}}finally{try{!f&&!i&&(s=h.return)&&(yield k(s.call(h)))}finally{if(o)throw o.error}}for(let g of d.flush()){let b=c.decode(g);b&&(yield yield k(b))}},"_iterSSEMessages_1"))}p(um,"_iterSSEMessages");function fm(n){return Se(this,arguments,p(function*(){var t,i,o,s;let a=new Uint8Array;try{for(var c=!0,d=Ae(n),u;u=yield k(d.next()),t=u.done,!t;c=!0){s=u.value,c=!1;let f=s;if(f==null)continue;let h=f instanceof ArrayBuffer?new Uint8Array(f):typeof f=="string"?qo(f):f,m=new Uint8Array(a.length+h.length);m.set(a),m.set(h,a.length),a=m;let g;for(;(g=cm(a))!==-1;)yield yield k(a.slice(0,g)),a=a.slice(g)}}catch(f){i={error:f}}finally{try{!c&&!t&&(o=d.return)&&(yield k(o.call(d)))}finally{if(i)throw i.error}}a.length>0&&(yield yield k(a))},"iterSSEChunks_1"))}p(fm,"iterSSEChunks");var xo=class{static{p(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 s={event:this.event,data:this.data.join(`
|
|
678
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,i,o]=pm(e,":");return o.startsWith(" ")&&(o=o.substring(1)),t==="event"?this.event=o:t==="data"&&this.data.push(o),null}};function pm(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}p(pm,"partition");async function hm(n,e){let{response:t,requestLogID:i,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{var c;if(e.options.stream)return fe(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):Ao.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 fe(n).debug(`[${i}] response parsed`,it({retryOfRequestLogID:o,url:t.url,status:t.status,body:a,durationMs:Date.now()-s})),a}p(hm,"defaultParseResponse");var No=class n extends Promise{static{p(this,"APIPromise")}constructor(e,t,i=hm){super(o=>{o(null)}),this.responsePromise=t,this.parseResponse=i,this.client=e}_thenUnwrap(e){return new n(this.client,this.responsePromise,async(t,i)=>e(await this.parseResponse(t,i),i))}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 dl=Symbol("brand.privateNullableHeaders");function*mm(n){if(!n)return;if(dl in n){let{values:i,nulls:o}=n;yield*i.entries();for(let s of o)yield[s,null];return}let e=!1,t;n instanceof Headers?t=n.entries():Ta(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let i of t){let o=i[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=Ta(i[1])?i[1]:[i[1]],a=!1;for(let c of s)c!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,c])}}p(mm,"iterateHeaders");var Di=p(n=>{let e=new Headers,t=new Set;for(let i of n){let o=new Set;for(let[s,a]of mm(i)){let c=s.toLowerCase();o.has(c)||(e.delete(s),o.add(c)),a===null?(e.delete(s),t.add(c)):(e.append(s,a),t.delete(c))}}return{[dl]:!0,values:e,nulls:t}},"buildHeaders");var Li=p(n=>{var e,t,i,o,s,a;if(typeof globalThis.process<"u")return(i=(t=(e=globalThis.process.env)===null||e===void 0?void 0:e[n])===null||t===void 0?void 0:t.trim())!==null&&i!==void 0?i:void 0;if(typeof globalThis.Deno<"u")return(a=(s=(o=globalThis.Deno.env)===null||o===void 0?void 0:o.get)===null||s===void 0?void 0:s.call(o,n))===null||a===void 0?void 0:a.trim()},"readEnv");var ul,zn=class n{static{p(this,"BaseGeminiNextGenAPIClient")}constructor(e){var t,i,o,s,a,c,d,u=e===void 0?{}:e,{baseURL:f=Li("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:h=(t=Li("GEMINI_API_KEY"))!==null&&t!==void 0?t:null,apiVersion:m="v1beta"}=u,g=$n(u,["baseURL","apiKey","apiVersion"]);let b=Object.assign(Object.assign({apiKey:h,apiVersion:m},g),{baseURL:f||"https://generativelanguage.googleapis.com"});this.baseURL=b.baseURL,this.timeout=(i=b.timeout)!==null&&i!==void 0?i:n.DEFAULT_TIMEOUT,this.logger=(o=b.logger)!==null&&o!==void 0?o:console;let E="warn";this.logLevel=E,this.logLevel=(a=(s=xa(b.logLevel,"ClientOptions.logLevel",this))!==null&&s!==void 0?s:xa(Li("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:Yh(),this.encoder=jh,this._options=b,this.apiKey=h,this.apiVersion=m}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 Di([{"x-goog-api-key":this.apiKey}])}stringifyQuery(e){return Object.entries(e).filter(([t,i])=>typeof i<"u").map(([t,i])=>{if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(i)}`;if(i===null)return`${encodeURIComponent(t)}=`;throw new ge(`Cannot stringify type ${typeof i}; 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 ${gt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Dh()}`}makeStatusError(e,t,i,o){return be.generate(e,t,i,o)}buildURL(e,t,i){let o=!this.baseURLOverridden()&&i||this.baseURL,s=Uh(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Vh(a)||(t=Object.assign(Object.assign({},a),t)),typeof t=="object"&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:i}){}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,i){return this.request(Promise.resolve(i).then(o=>Object.assign({method:e,path:t},o)))}request(e,t=null){return new No(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,i){var o,s,a;let c=await e,d=(o=c.maxRetries)!==null&&o!==void 0?o:this.maxRetries;t==null&&(t=d),await this.prepareOptions(c);let{req:u,url:f,timeout:h}=await this.buildRequest(c,{retryCount:d-t});await this.prepareRequest(u,{url:f,options:c});let m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=i===void 0?"":`, retryOf: ${i}`,b=Date.now();if(fe(this).debug(`[${m}] sending request`,it({retryOfRequestLogID:i,method:c.method,url:f,options:c,headers:u.headers})),!((s=c.signal)===null||s===void 0)&&s.aborted)throw new Dt;let E=new AbortController,w=await this.fetchWithTimeout(f,u,h,E).catch(Co),v=Date.now();if(w instanceof globalThis.Error){let T=`retrying, ${t} attempts remaining`;if(!((a=c.signal)===null||a===void 0)&&a.aborted)throw new Dt;let C=To(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(t)return fe(this).info(`[${m}] connection ${C?"timed out":"failed"} - ${T}`),fe(this).debug(`[${m}] connection ${C?"timed out":"failed"} (${T})`,it({retryOfRequestLogID:i,url:f,durationMs:v-b,message:w.message})),this.retryRequest(c,t,i??m);throw fe(this).info(`[${m}] connection ${C?"timed out":"failed"} - error; no more retries left`),fe(this).debug(`[${m}] connection ${C?"timed out":"failed"} (error; no more retries left)`,it({retryOfRequestLogID:i,url:f,durationMs:v-b,message:w.message})),C?new Rn:new wt({cause:w})}let I=`[${m}${g}] ${u.method} ${f} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${v-b}ms`;if(!w.ok){let T=await this.shouldRetry(w);if(t&&T){let $=`retrying, ${t} attempts remaining`;return await Zh(w.body),fe(this).info(`${I} - ${$}`),fe(this).debug(`[${m}] response error (${$})`,it({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,durationMs:v-b})),this.retryRequest(c,t,i??m,w.headers)}let C=T?"error; no more retries left":"error; not retryable";fe(this).info(`${I} - ${C}`);let N=await w.text().catch($=>Co($).message),S=Oh(N),x=S?void 0:N;throw fe(this).debug(`[${m}] response error (${C})`,it({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,message:x,durationMs:Date.now()-b})),this.makeStatusError(w.status,S,x,w.headers)}return fe(this).info(I),fe(this).debug(`[${m}] response start`,it({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,durationMs:v-b})),{response:w,options:c,controller:E,requestLogID:m,retryOfRequestLogID:i,startTime:b}}async fetchWithTimeout(e,t,i,o){let s=t||{},{signal:a,method:c}=s,d=$n(s,["signal","method"]);a&&a.addEventListener("abort",()=>o.abort());let u=setTimeout(()=>o.abort(),i),f=globalThis.ReadableStream&&d.body instanceof globalThis.ReadableStream||typeof d.body=="object"&&d.body!==null&&Symbol.asyncIterator in d.body,h=Object.assign(Object.assign(Object.assign({signal:o.signal},f?{duplex:"half"}:{}),{method:"GET"}),d);c&&(h.method=c.toUpperCase());try{return await this.fetch.call(void 0,e,h)}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,i,o){var s;let a,c=o?.get("retry-after-ms");if(c){let u=parseFloat(c);Number.isNaN(u)||(a=u)}let d=o?.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=(s=e.maxRetries)!==null&&s!==void 0?s:this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,u)}return await zh(a),this.makeRequest(e,t-1,i)}calculateDefaultRetryTimeoutMillis(e,t){let s=t-e,a=Math.min(.5*Math.pow(2,s),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){var i,o,s;let a=Object.assign({},e),{method:c,path:d,query:u,defaultBaseURL:f}=a,h=this.buildURL(d,u,f);"timeout"in a&&Hh("timeout",a.timeout),a.timeout=(i=a.timeout)!==null&&i!==void 0?i:this.timeout;let{bodyHeaders:m,body:g}=this.buildBody({options:a}),b=await this.buildHeaders({options:e,method:c,bodyHeaders:m,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}),(o=this.fetchOptions)!==null&&o!==void 0?o:{}),(s=a.fetchOptions)!==null&&s!==void 0?s:{}),url:h,timeout:a.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:i,retryCount:o}){let s={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=Di([s,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),Xh()),await this.authHeaders(e),this._options.defaultHeaders,i,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let i=Di([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&i.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:Qh(e)}:this.encoder({body:e,headers:i})}};zn.DEFAULT_TIMEOUT=6e4;var ee=class extends zn{static{p(this,"GeminiNextGenAPIClient")}constructor(){super(...arguments),this.interactions=new Hn(this)}};ul=ee;ee.GeminiNextGenAPIClient=ul;ee.GeminiNextGenAPIClientError=ge;ee.APIError=be;ee.APIConnectionError=wt;ee.APIConnectionTimeoutError=Rn;ee.APIUserAbortError=Dt;ee.NotFoundError=Dn;ee.ConflictError=Ln;ee.RateLimitError=Fn;ee.BadRequestError=Gn;ee.AuthenticationError=Mn;ee.InternalServerError=Bn;ee.PermissionDeniedError=kn;ee.UnprocessableEntityError=Un;ee.toFile=om;ee.Interactions=Hn;function gm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(gm,"cancelTuningJobParametersToMldev");function bm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(bm,"cancelTuningJobParametersToVertex");function ym(n,e){let t={},i=r(n,["sdkHttpResponse"]);return i!=null&&l(t,["sdkHttpResponse"],i),t}p(ym,"cancelTuningJobResponseFromMldev");function Em(n,e){let t={},i=r(n,["sdkHttpResponse"]);return i!=null&&l(t,["sdkHttpResponse"],i),t}p(Em,"cancelTuningJobResponseFromVertex");function wm(n,e,t){let i={};if(r(n,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is not supported in Gemini API.");let o=r(n,["tunedModelDisplayName"]);if(e!==void 0&&o!=null&&l(e,["displayName"],o),r(n,["description"])!==void 0)throw new Error("description parameter is not supported in Gemini API.");let s=r(n,["epochCount"]);e!==void 0&&s!=null&&l(e,["tuningTask","hyperparameters","epochCount"],s);let a=r(n,["learningRateMultiplier"]);if(a!=null&&l(i,["tuningTask","hyperparameters","learningRateMultiplier"],a),r(n,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(r(n,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(r(n,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is not supported in Gemini API.");let c=r(n,["batchSize"]);e!==void 0&&c!=null&&l(e,["tuningTask","hyperparameters","batchSize"],c);let d=r(n,["learningRate"]);if(e!==void 0&&d!=null&&l(e,["tuningTask","hyperparameters","learningRate"],d),r(n,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");if(r(n,["beta"])!==void 0)throw new Error("beta parameter is not supported in Gemini API.");return i}p(wm,"createTuningJobConfigToMldev");function vm(n,e,t){let i={},o=r(t,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){let g=r(n,["validationDataset"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec"],$a(g))}else if(o==="PREFERENCE_TUNING"){let g=r(n,["validationDataset"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec"],$a(g))}let s=r(n,["tunedModelDisplayName"]);e!==void 0&&s!=null&&l(e,["tunedModelDisplayName"],s);let a=r(n,["description"]);e!==void 0&&a!=null&&l(e,["description"],a);let c=r(t,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let g=r(n,["epochCount"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","epochCount"],g)}else if(c==="PREFERENCE_TUNING"){let g=r(n,["epochCount"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],g)}let d=r(t,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let g=r(n,["learningRateMultiplier"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],g)}else if(d==="PREFERENCE_TUNING"){let g=r(n,["learningRateMultiplier"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],g)}let u=r(t,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let g=r(n,["exportLastCheckpointOnly"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","exportLastCheckpointOnly"],g)}else if(u==="PREFERENCE_TUNING"){let g=r(n,["exportLastCheckpointOnly"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],g)}let f=r(t,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){let g=r(n,["adapterSize"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","adapterSize"],g)}else if(f==="PREFERENCE_TUNING"){let g=r(n,["adapterSize"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],g)}if(r(n,["batchSize"])!==void 0)throw new Error("batchSize parameter is not supported in Vertex AI.");if(r(n,["learningRate"])!==void 0)throw new Error("learningRate parameter is not supported in Vertex AI.");let h=r(n,["labels"]);e!==void 0&&h!=null&&l(e,["labels"],h);let m=r(n,["beta"]);return e!==void 0&&m!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","beta"],m),i}p(vm,"createTuningJobConfigToVertex");function Im(n,e){let t={},i=r(n,["baseModel"]);i!=null&&l(t,["baseModel"],i);let o=r(n,["preTunedModel"]);o!=null&&l(t,["preTunedModel"],o);let s=r(n,["trainingDataset"]);s!=null&&Gm(s);let a=r(n,["config"]);return a!=null&&wm(a,t),t}p(Im,"createTuningJobParametersPrivateToMldev");function Tm(n,e){let t={},i=r(n,["baseModel"]);i!=null&&l(t,["baseModel"],i);let o=r(n,["preTunedModel"]);o!=null&&l(t,["preTunedModel"],o);let s=r(n,["trainingDataset"]);s!=null&&Mm(s,t,e);let a=r(n,["config"]);return a!=null&&vm(a,t,e),t}p(Tm,"createTuningJobParametersPrivateToVertex");function Cm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(Cm,"getTuningJobParametersToMldev");function _m(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(_m,"getTuningJobParametersToVertex");function Sm(n,e,t){let i={},o=r(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let s=r(n,["pageToken"]);e!==void 0&&s!=null&&l(e,["_query","pageToken"],s);let a=r(n,["filter"]);return e!==void 0&&a!=null&&l(e,["_query","filter"],a),i}p(Sm,"listTuningJobsConfigToMldev");function Am(n,e,t){let i={},o=r(n,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let s=r(n,["pageToken"]);e!==void 0&&s!=null&&l(e,["_query","pageToken"],s);let a=r(n,["filter"]);return e!==void 0&&a!=null&&l(e,["_query","filter"],a),i}p(Am,"listTuningJobsConfigToVertex");function xm(n,e){let t={},i=r(n,["config"]);return i!=null&&Sm(i,t),t}p(xm,"listTuningJobsParametersToMldev");function Nm(n,e){let t={},i=r(n,["config"]);return i!=null&&Am(i,t),t}p(Nm,"listTuningJobsParametersToVertex");function $m(n,e){let t={},i=r(n,["sdkHttpResponse"]);i!=null&&l(t,["sdkHttpResponse"],i);let o=r(n,["nextPageToken"]);o!=null&&l(t,["nextPageToken"],o);let s=r(n,["tunedModels"]);if(s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>fl(c))),l(t,["tuningJobs"],a)}return t}p($m,"listTuningJobsResponseFromMldev");function Pm(n,e){let t={},i=r(n,["sdkHttpResponse"]);i!=null&&l(t,["sdkHttpResponse"],i);let o=r(n,["nextPageToken"]);o!=null&&l(t,["nextPageToken"],o);let s=r(n,["tuningJobs"]);if(s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>$o(c))),l(t,["tuningJobs"],a)}return t}p(Pm,"listTuningJobsResponseFromVertex");function Rm(n,e){let t={},i=r(n,["name"]);i!=null&&l(t,["model"],i);let o=r(n,["name"]);return o!=null&&l(t,["endpoint"],o),t}p(Rm,"tunedModelFromMldev");function Gm(n,e){let t={};if(r(n,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(r(n,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");let i=r(n,["examples"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>s)),l(t,["examples","examples"],o)}return t}p(Gm,"tuningDatasetToMldev");function Mm(n,e,t){let i={},o=r(t,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){let a=r(n,["gcsUri"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(o==="PREFERENCE_TUNING"){let a=r(n,["gcsUri"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}let s=r(t,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){let a=r(n,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(s==="PREFERENCE_TUNING"){let a=r(n,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}if(r(n,["examples"])!==void 0)throw new Error("examples parameter is not supported in Vertex AI.");return i}p(Mm,"tuningDatasetToVertex");function fl(n,e){let t={},i=r(n,["sdkHttpResponse"]);i!=null&&l(t,["sdkHttpResponse"],i);let o=r(n,["name"]);o!=null&&l(t,["name"],o);let s=r(n,["state"]);s!=null&&l(t,["state"],Ua(s));let a=r(n,["createTime"]);a!=null&&l(t,["createTime"],a);let c=r(n,["tuningTask","startTime"]);c!=null&&l(t,["startTime"],c);let d=r(n,["tuningTask","completeTime"]);d!=null&&l(t,["endTime"],d);let u=r(n,["updateTime"]);u!=null&&l(t,["updateTime"],u);let f=r(n,["description"]);f!=null&&l(t,["description"],f);let h=r(n,["baseModel"]);h!=null&&l(t,["baseModel"],h);let m=r(n,["_self"]);return m!=null&&l(t,["tunedModel"],Rm(m)),t}p(fl,"tuningJobFromMldev");function $o(n,e){let t={},i=r(n,["sdkHttpResponse"]);i!=null&&l(t,["sdkHttpResponse"],i);let o=r(n,["name"]);o!=null&&l(t,["name"],o);let s=r(n,["state"]);s!=null&&l(t,["state"],Ua(s));let a=r(n,["createTime"]);a!=null&&l(t,["createTime"],a);let c=r(n,["startTime"]);c!=null&&l(t,["startTime"],c);let d=r(n,["endTime"]);d!=null&&l(t,["endTime"],d);let u=r(n,["updateTime"]);u!=null&&l(t,["updateTime"],u);let f=r(n,["error"]);f!=null&&l(t,["error"],f);let h=r(n,["description"]);h!=null&&l(t,["description"],h);let m=r(n,["baseModel"]);m!=null&&l(t,["baseModel"],m);let g=r(n,["tunedModel"]);g!=null&&l(t,["tunedModel"],g);let b=r(n,["preTunedModel"]);b!=null&&l(t,["preTunedModel"],b);let E=r(n,["supervisedTuningSpec"]);E!=null&&l(t,["supervisedTuningSpec"],E);let w=r(n,["preferenceOptimizationSpec"]);w!=null&&l(t,["preferenceOptimizationSpec"],w);let v=r(n,["tuningDataStats"]);v!=null&&l(t,["tuningDataStats"],v);let I=r(n,["encryptionSpec"]);I!=null&&l(t,["encryptionSpec"],I);let T=r(n,["partnerModelTuningSpec"]);T!=null&&l(t,["partnerModelTuningSpec"],T);let C=r(n,["customBaseModel"]);C!=null&&l(t,["customBaseModel"],C);let N=r(n,["experiment"]);N!=null&&l(t,["experiment"],N);let S=r(n,["labels"]);S!=null&&l(t,["labels"],S);let x=r(n,["outputUri"]);x!=null&&l(t,["outputUri"],x);let P=r(n,["pipelineJob"]);P!=null&&l(t,["pipelineJob"],P);let $=r(n,["serviceAccount"]);$!=null&&l(t,["serviceAccount"],$);let R=r(n,["tunedModelDisplayName"]);R!=null&&l(t,["tunedModelDisplayName"],R);let L=r(n,["veoTuningSpec"]);return L!=null&&l(t,["veoTuningSpec"],L),t}p($o,"tuningJobFromVertex");function km(n,e){let t={},i=r(n,["sdkHttpResponse"]);i!=null&&l(t,["sdkHttpResponse"],i);let o=r(n,["name"]);o!=null&&l(t,["name"],o);let s=r(n,["metadata"]);s!=null&&l(t,["metadata"],s);let a=r(n,["done"]);a!=null&&l(t,["done"],a);let c=r(n,["error"]);return c!=null&&l(t,["error"],c),t}p(km,"tuningOperationFromMldev");function $a(n,e){let t={},i=r(n,["gcsUri"]);i!=null&&l(t,["validationDatasetUri"],i);let o=r(n,["vertexDatasetResource"]);return o!=null&&l(t,["validationDatasetUri"],o),t}p($a,"tuningValidationDatasetToVertex");var Po=class extends xe{static{p(this,"Tunings")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new De(ke.PAGED_ITEM_TUNING_JOBS,i=>this.listInternal(i),await this.listInternal(t),t),this.get=async t=>await this.getInternal(t),this.tune=async t=>{var i;if(this.apiClient.isVertexAI())if(t.baseModel.startsWith("projects/")){let o={tunedModelName:t.baseModel};!((i=t.config)===null||i===void 0)&&i.preTunedModelCheckpointId&&(o.checkpointId=t.config.preTunedModelCheckpointId);let s=Object.assign(Object.assign({},t),{preTunedModel:o});return s.baseModel=void 0,await this.tuneInternal(s)}else{let o=Object.assign({},t);return await this.tuneInternal(o)}else{let o=Object.assign({},t),s=await this.tuneMldevInternal(o),a="";return s.metadata!==void 0&&s.metadata.tunedModel!==void 0?a=s.metadata.tunedModel:s.name!==void 0&&s.name.includes("/operations/")&&(a=s.name.split("/operations/")[0]),{name:a,state:Fi.JOB_STATE_QUEUED}}}}async getInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=_m(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>$o(f))}else{let u=Cm(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>fl(f))}}async listInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Nm(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Pm(f),m=new Cn;return Object.assign(m,h),m})}else{let u=xm(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=$m(f),m=new Cn;return Object.assign(m,h),m})}}async cancel(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=bm(e);return 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:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=Em(f),m=new _n;return Object.assign(m,h),m})}else{let u=gm(e);return 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:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:f.headers},m})),a.then(f=>{let h=ym(f),m=new _n;return Object.assign(m,h),m})}}async tuneInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=Tm(e,e);return s=_("tuningJobs",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>$o(d))}else throw new Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let c=Im(e);return s=_("tunedModels",c._url),a=c._query,delete c._url,delete c._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(t=e.config)===null||t===void 0?void 0:t.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:d.headers},f})),o.then(d=>km(d))}}};var Ro=class{static{p(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.")}},Dm=1024*1024*8,Lm=3,Um=1e3,Fm=2,Kn="x-goog-upload-status";async function Bm(n,e,t){var i;let o=await pl(n,e,t),s=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[Kn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return s.file}p(Bm,"uploadBlob");async function Vm(n,e,t){var i;let o=await pl(n,e,t),s=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[Kn])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let a=Ra(s),c=new eo;return Object.assign(c,a),c}p(Vm,"uploadBlobToFileSearchStore");async function pl(n,e,t){var i,o;let s=0,a=0,c=new kt(new Response),d="upload";for(s=n.size;a<s;){let u=Math.min(Dm,s-a),f=n.slice(a,a+u);a+u>=s&&(d+=", finalize");let h=0,m=Um;for(;h<Lm&&(c=await t.request({path:"",body:f,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:e,headers:{"X-Goog-Upload-Command":d,"X-Goog-Upload-Offset":String(a),"Content-Length":String(u)}}}),!(!((i=c?.headers)===null||i===void 0)&&i[Kn]));)h++,await Hm(m),m=m*Fm;if(a+=u,((o=c?.headers)===null||o===void 0?void 0:o[Kn])!=="active")break;if(s<=a)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return c}p(pl,"uploadBlobInternal");async function qm(n){return{size:n.size,type:n.type}}p(qm,"getBlobStat");function Hm(n){return new Promise(e=>setTimeout(e,n))}p(Hm,"sleep");var Go=class{static{p(this,"BrowserUploader")}async upload(e,t,i){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await Bm(e,t,i)}async uploadToFileSearchStore(e,t,i){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await Vm(e,t,i)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await qm(e)}};var Mo=class{static{p(this,"BrowserWebSocketFactory")}create(e,t,i){return new ko(e,t,i)}},ko=class{static{p(this,"BrowserWebSocket")}constructor(e,t,i){this.url=e,this.headers=t,this.callbacks=i}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 Pa="x-goog-api-key",Do=class{static{p(this,"WebAuth")}constructor(e){this.apiKey=e}async addAuthHeaders(e,t){if(e.get(Pa)===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(Pa,this.apiKey)}}};var Om="gl-node/",Lt=class{static{p(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 ee({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 i=Ec(e.httpOptions,e.vertexai,void 0,void 0);i&&(e.httpOptions?e.httpOptions.baseUrl=i:e.httpOptions={baseUrl:i}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let o=new Do(this.apiKey);this.apiClient=new fo({auth:o,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:Om+"web",uploader:new Go,downloader:new Ro}),this.models=new yo(this.apiClient),this.live=new go(this.apiClient,o,new Mo),this.batches=new io(this.apiClient),this.chats=new so(this.models,this.apiClient),this.caches=new oo(this.apiClient),this.files=new ao(this.apiClient),this.operations=new Eo(this.apiClient),this.authTokens=new wo(this.apiClient),this.tunings=new Po(this.apiClient),this.fileSearchStores=new Io(this.apiClient)}};var st=K,hl=new Map,ml=[];function rt(){let n=`[${rt.name}]`;try{return st&&console.log(`${n} starting... (I: a5cf5821b42e1c71182dd61431977e25)`),hl}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{st&&console.log(`${n} complete.`)}}p(rt,"getAllFunctionInfos");function Ho(){let n=`[${Ho.name}]`;try{return st&&console.log(`${n} starting... (I: 82c9a8fc91d8121fb843af32e76c2e25)`),ml}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{st&&console.log(`${n} complete.`)}}p(Ho,"getDeprecatedFunctionInfoNames");function zm({functionInfos:n}){let e=`[${zm.name}]`;try{st&&console.log(`${e} starting... (I: 14fee8e27384a040494542182031ae25)`),n.size===0&&console.warn(`${e} empty functionInfos? (W: 97fcb8fc47689bc418893c09a16a2525)`);for(let[t,i]of n)ml.includes(t)?st&&console.log(`${e} functionInfo.nameOrId (${t}) is deprecated. Skipping add. (I: 3256eadf54f8087088a704798e2fd825)`):hl.set(t,i)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{st&&console.log(`${e} complete.`)}}p(zm,"registerFunctionInfos");var ye=K;function Ut(n){switch(n){case j.HUMAN:return"user";case j.AI:return"model";case j.FUNCTION:return"user";case j.HARDCODED:return"user";case j.UNKNOWN:return"user";default:throw new Error(`(UNEXPECTED) src is not a valid TextSource? src: ${n} (E: 9d954fe0bc49cf4572a65b19b6173925)`)}}p(Ut,"textSourceToGeminiRole");function gl(n){return n.api==="gemini"}p(gl,"isPromptInfoGemini");function Oo({systemPromptEntries:n}){let e=`[${Oo.name}]`;try{if(ye&&console.log(`${e} starting... (I: 18693a97427939699285ef8c1a9cc425)`),n.length===0)return;n.every(i=>i.src===j.HUMAN)||ye&&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(i=>!!i.content.parts).flatMap(i=>i.content.parts)};return ye&&console.log(`${e} sysInstructionContent: ${U(t)} (I: 011e5b865c23eb0b640df3f464ac2525)`),t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{ye&&console.log(`${e} complete.`)}}p(Oo,"systemPromptEntriesToSystemInstructionContent");function zo({ibGib:n}){let e=`[${zo.name}]`;try{if(ye&&console.log(`${e} starting... (I: 986d3edcd4f3aaf1d7eb0f8b59206b25)`),!n)return ye&&console.warn(`${e} ibGib falsy. (W: a70390e8bc3f420a92d3a84f4c78f12a)`),!1;if(!tt({ibGib:n}))return ye&&console.log(`${e} not a comment ibgib (I: 6a62c4f6e13776616855c4f237a5206b)`),!1;if(!n.data)return ye&&console.log(`${e} ibGib.data falsy (I: 69eb86975640475395bb74944141a46d)`),!1;let{text:t}=n.data;return t?t.includes(an)?(ye&&console.log(`${e} has tag. returning true. (I: 6d76b27d558d44f696582f41af561f29)`),!0):(ye&&console.log(`${e} no indicator found. returning false. (I: 815f181a0a08058362f76b08a8964674)`),!1):(ye&&console.log(`${e} text falsy (I: e348e38c841b4443b3f09e75c0215b24)`),!1)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{ye&&console.log(`${e} complete.`)}}p(zo,"isFunctionCallRequestComment");function Ko({functionInfoIbGib:n}){let e=`[${Ko.name}]`;try{if(ye&&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:i,fnResult:o}=n.data;if(!t)throw new Error(`${e} functionInfoIbGib.data.fnName is required. (E: 6f7a8b1c2d3e4f5a6b7c8d9e)`);return{call:{functionCall:{name:t,args:i??{}}},response:{functionResponse:{name:t,response:{value:o}}}}}catch(t){throw console.error(`${e} Error: ${y(t)}`),t}finally{ye&&console.log(`${e} complete.`)}}p(Ko,"getFunctionCallAndResponseParts");var Ft=K,Yn="function_info",bl="function_info";function yl({data:n}){let e=`[${yl.name}]`,{model:t,api:i,agentId:o,timestamp:s}=n;if(!t)throw new Error(`${e} data.model falsy (E: 6f47a28c0a8a45d794149c83e8f27e25)`);if(!i)throw new Error(`${e} data.api falsy (E: a0a812508a952a87c619d38084b7e325)`);if(!o)throw new Error(`${e} data.agentId falsy (E: ac35c1592c458e2c0e5908f6a9a3e525)`);let a=We(s);if([t,i,o,a].some(d=>d.includes(" ")))throw new Error("invalid data. ib must not contain spaces (E: 36a56e4685163848458be06f51d4ad25)");return[bl,a,t,i,o].join(" ")}p(yl,"getFunctionInfoIb");async function Qn(n){let e=`[${Qn.name}]`;try{Ft&&console.log(`${e} starting... (I: f4c9f0810a4d877f676297f6e6a96825)`);let{fnRawRequest:t,api:i,model:o,agentId:s,fnName:a,fnArgs:c,fnResult:d,fnComplete:u,parseErrorMsg:f,execErrorMsg:h,repromptWithResult:m,saveInSpace:g,metaspace:b,space:E}=n,w=new Date,v={name:o,timestamp:zt(w),timestampMs:w.getMilliseconds(),agentId:s,api:i,model:o,fnRawRequest:t,fnName:a,fnArgs:c,fnResult:d,fnComplete:u,repromptWithResult:m};f&&(v.parseErrorMsg=f),h&&(v.execErrorMsg=h);let I=yl({data:v}),T=await re.firstGen({ib:I,parentIbGib:re.primitive({ib:bl}),data:v,nCounter:!0,dna:!0,tjp:{uuid:!0}});if(Ft&&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}),Ft&&console.log(`${e} persisted resFunctionInfo (${A({ibGib:T.newIbGib})}) to space ${E.data?.uuid} (I: aa98e877d3b34e0d2a3b7711f8f27e25)`),await b.registerNewIbGib({ibGib:T.newIbGib,space:E}),Ft&&console.log(`${e} registered new function info ibgib (${A({ibGib:T.newIbGib})}) with metaspace (I: aa98e877d3b34e0d2a3b7711f8f27e25)`)}return T}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Ft&&console.log(`${e} complete.`)}}p(Qn,"createFunctionInfoIbGib");var D=K,Zn=class n extends Bs{static{p(this,"AgentWitness_V1")}lc=`[${n.name}]`;availableFunctions=new Map;commentIbGibs_system=[];commentIbGibs_chat=[];_metaspace;fnGetAPIKey=p(()=>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=p(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=ct({count:32})}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{D&&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(Ot)||t.push(`agent.data.subSpaceId must match regexp: ${Ot}. (E: f381eff533aa3f4713316f93f7f1dc25)`),this.data.name?this.data.name.match(pt)||t.push(`agent name must match regexp: ${pt}`):t.push("agent name falsy (E: 1351325107e5ac5ea6b7b789b73de125)"),this.data.description&&(this.data.description.match(Ci)||t.push(`agent description must match regexp: ${Ci}`))):t.push("this.data falsy (E: f5f151e11b12cad814b37ecad7c74a25)"),t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{D&&console.log(`${e} complete.`)}}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{D&&console.log(`${e} starting... (I: ce38519ac4bef52844a558fe31cda825)`),await super.initialize(),this._metaspace=await M();let t=new Be;if(await t.initialized,!t.contextUpdated$)throw new Error("(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: e8840870af18091e6e4d52490ddca825)");if(t.contextUpdated$.subscribe(Me({next:p(async i=>{let o=`${e}[ibGibProxy.contextUpdated$][next]`;D&&console.log(`${o} nextIbGib: ${U(i)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleContextUpdated()},"next"),error:p(async i=>{debugger;console.error(`${e}[ibGibProxy.contextUpdated$][error] what up? ${y(i)}`)},"error")})),this.ib&&this.gib&&this.data){let i=this.toIbGibDto();await this.loadIbGibDto(i);let o=await this._metaspace.getLocalUserSpace({localSpaceId:i.data?.superSpaceId});if(!o)throw new Error(`couldn't get local space with agent.data.superSpaceId (${i.data?.superSpaceId})? (E: 0fc1b8a8ffa26f39d8a15218ec818725)`);await this.ibGibProxy?.setWrappedIbGib({ibGib:i,space:o})}else D&&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{D&&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(A({ibGib:this})!==A({ibGib:this.ibGibProxy.ibGib})){let t=this.ibGibProxy.ibGib.data.n??0,i=this.data?.n??0;if(t<=i){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 O(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{D&&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 i=await t.getLocalUserSpace({localSpaceId:this.data.subSpaceId});if(!i){let o=await this.validateThis();if(o.length>0)throw new Error(`this agent has validation errors: ${o} (E: 9a0c6125cf89789ddb1610cf5a752225)`);if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 06e30e1d53fd4935333c7cf7e10db425)");i=await t.createLocalSpaceAndUpdateBootstrap({allowCancel:!1,zeroSpace:t.zeroSpace,spaceName:this.name+this.uuid.substring(0,5),createBootstrap:!1})}if(!i)throw new Error("(UNEXPECTED) space still falsy after creating locally? (E: 037ef1e6f54a675d0367227fdae16525)");return i}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{D&&console.log(`${e} complete.`)}}async getSuperSpace(){let e=`[${this.getSuperSpace.name}]`;try{D&&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 i=await t.getLocalUserSpace({localSpaceId:this.data.superSpaceId});if(!i)throw new Error(`(UNEXPECTED) superSpace falsy? this.data.superSpaceId: ${this.data.superSpaceId} (E: fd9435212e8b87e4b60034bf9e797f25)`);return i}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{D&&console.log(`${e} complete.`)}}_activeContext=void 0;async setActiveContext(e){let t=`${this.lc}[${this.setActiveContext.name}]`;try{D&&console.log(`${t} starting... (I: genuuid)`);let{contextIbGib:i,loggingInfo:o}=e;if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: ab5377fda6bc324638722d9832bab925)");if(!i)throw new Error("(UNEXPECTED) contextIbGib falsy? (E: 694525e512cfdd12c14e1213dbaab925)");if(!i.data)throw new Error("(UNEXPECTED) contextIbGib.data falsy? (E: f337252a23c822bcbd76144540050825)");let s=A({ibGib:i}),a=X({ibGib:i});if(!a)throw new Error(`(UNEXPECTED) contextTjpAddr falsy? contextIbGib (${s}) 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?D&&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 Be;await c.initialized;let d=`${t}[contextUpdated]`;if(!c.contextUpdated$)throw new Error("(UNEXPECTED) proxy.contextUpdated$ falsy? (E: 868c5e3bf025baa6d1ae727ab1160c25)");c.contextUpdated$.subscribe(Me({next:p(async f=>{console.log(`${d}[next] nextIbGib: ${U(f)}`)},"next"),complete:p(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:p(async f=>{debugger;console.error(`${d}[error] ${y(f)}`)},"error")}));let u=`${t}[newContextChild]`;if(!c.newContextChild$)throw new Error("(UNEXPECTED) proxy.newContextChild$ falsy? (E: 123cf5624c3d2a6308aafc0c41f8a925)");c.newContextChild$.subscribe(Me({next:p(async f=>{if(console.log(`${u}[next] newChild: ${U(f)}`),!f.data)throw new Error("newChild.data falsy? (E: a654134a2695c176971b0cd1426ced25)");if(tt({ibGib:f})){let h=this.commentIbGibs_chat.map(w=>X({ibGib:w})??A({ibGib:w})),m=X({ibGib:f})??A({ibGib:f});if(h.includes(m)){console.log(`${t} already did this comment (${m}) (I: bce18642bb9babeb553e6188d7ae2825)`);return}let{safeIbCommentMetadataText:g}=je({ib:f.ib}),{textSrc:b}=Bt({addlMetadataText:g??"",ifError:"warn"}),E=f.data.text.startsWith("system: ");await this.addTexts({infos:[{textSrc:b??j.UNKNOWN,commentIbGib:f,isSystem:E}]}),b===j.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:p(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:p(async f=>{debugger;console.error(`${u}[error] ${y(f)}`)},"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:i})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{D&&console.log(`${t} complete.`)}}async updateName({name:e}){let t=`${this.lc}[${this.updateName.name}]`;try{if(D&&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(pt.test(e))await this.mut8Self({dataToAddOrPatch:{name:e}});else throw new Error(`invalid name ${e}. must match regexp: ${pt.source} (E: 507a2bfc0aaa60bd7bb608d253239e25)`)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{D&&console.log(`${t} complete.`)}}async updateAvailableFunctions({availableFunctions:e}){let t=`${this.lc}[${this.updateAvailableFunctions.name}]`;try{D&&console.log(`${t} starting... (I: 68f1bfa343925a657f8c0545b191c725)`);let i=[];for(let o of e)if(!this.availableFunctions.has(o.nameOrId)){let s=rt().get(o.nameOrId);if(s)i.push(s);else{console.error(`(UNEXPECTED) ${o} function not registered with getAllFunctionInfos()? skipping adding this function to the agent... (E: e860fe13c02677b274ac0e7df2587a25)`);continue}}i.length>0&&(console.log(`${t} adding newly found functions to agent: ${i.map(o=>o.nameOrId)}. (I: ab2b0ae6a62b3ced6a5f1e2e8cec4f25)`),await this.addAvailableFunctions(i))}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{D&&console.log(`${t} complete.`)}}async mut8Self({dataToAddOrPatch:e}){let t=`${this.lc}[${this.mut8Self.name}]`;try{D&&console.log(`${t} starting... (I: f4618832a0fe07ff8c89cea889d20725)`);let i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: genuuid)");let o=await i.getLocalUserSpace({lock:!1,localSpaceId:this.data.superSpaceId});if(!o)throw new Error(`couldn't get local superSpace given by this.data.superSpaceId (${this.data.superSpaceId}) (E: genuuid)`);let{tjpGib:s}=W({gib:this.gib});if(!s)throw new Error(`(UNEXPECTED) this.gib (${this.gib}) has no tjpGib? (E: 75b8dcb82b58d3b0db40b39149023e25)`);await Wt({fn:p(async()=>{let a=Re();await a.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1});let c=await ps({type:"mut8",src:this.toIbGibDto(),dataToAddOrPatch:e,dna:!0,nCounter:!0});await i.persistTransformResult({resTransform:c,space:o});let d=c.newIbGib;await this.loadIbGibDto(d),await a.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!0}),await i.registerNewIbGib({ibGib:d,space:o}),await Jo({newAgentIbGib:d,metaspace:i,space:o,type:this.data.type})},"fn"),scope:s,secondsValid:60,maxDelayMs:100,maxLockAttempts:Number.MAX_SAFE_INTEGER,space:o,callerInstanceId:this.instanceId})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{D&&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(D&&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 Re().updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1}),e.forEach(o=>{this.availableFunctions.has(o.nameOrId)&&console.warn(`${t} this.availableFunctions already has an entry for ${o.nameOrId}. replacing anyway. (W: ef2372a27be67174cb3605eac2c85c25)`),this.availableFunctions.set(o.nameOrId,o)}),await this.mut8Self({dataToAddOrPatch:{availableFunctionNameOrIds:Array.from(this.availableFunctions.keys())}})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{D&&console.log(`${t} complete.`)}}async doPrompt(){let e=`[${this.doPrompt.name}]`;try{if(D&&console.log(`${e} starting... (I: e7f1a7845cdf1bdce1f12d74c71a6425)`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 3c528e2376a2f2600b347b2c183a5225)");let t=await this.composePromptInfo();D&&console.log(`${e} promptTextInfo: ${U(t)} (I: b769b5f2a47623a99f78210994d90525)`);let i=await this.callTextAPI(t);if(D&&console.log(`${e} api result:`,i,"(I: e4d2c767eb3d6e38d83123d684a07425)"),"text"in i)await this.doPrompt_text(i.text);else{let{functionCalls:o}=i;await this.doPrompt_functionCalls({functionCalls:o})}}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{D&&console.log(`${e} complete.`)}}async doPrompt_text(e){let t=`${this.lc}[${this.doPrompt_text.name}]`;try{D&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{D&&console.log(`${t} complete.`)}}async doPrompt_functionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls.name}]`;try{if(D&&console.log(`${t} starting... (I: a4f1b581517a9c2a9187e9f8f3519925)`),e.length===0)throw new Error("(UNEXPECTED) functionCalls.length is zero? (E: 6434b8515a435a59b331452b563f4425)");let i=await this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({functionCalls:e});if(await this.doPrompt_functionCalls_addFunctionCallRequestComment({functionInfoIbGibs:i}),i.some(s=>!!s.data?.repromptWithResult&&s.data.fnName!=="tellUser")){let s=await this.doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt({functionInfoIbGibs:i});s.length>0?(console.log(`${t} transientDecompressionPromptText: ${s} (I: 11c11d544b7c8f8f8e7e5f7c1a9e3625)`),this.transientDecompressionPromptText=s,await this.rePrompt()):console.warn(`${t} (UNEXPECTED) there is no decompression text? (W: 6ce5da95c1c89a7ec48a00fbc1d11825)`)}else D&&console.log(`${t} no repromptWithResult. returning early. (I: 9c0113c958c7404534291f6700325925)`)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{D&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls.name}]`;try{if(D&&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 i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: acf8a69e853eb8663f1dd0f79a823e25)");let o=[];for(let s of e)try{D&&console.log(`${t} processing functionCall: ${s} (I: a0c0b22b3c6b6c4b674a5a9c8c8b9e25)`);let a,c,d,u,f,h="";try{if(c=JSON.parse(s),h=c?.name??"",!h)throw new Error("functionName (functionCallParsedObj.name) falsy (E: e2397d675863a12b7609495b0007a025)");if(D&&console.log(`${t} functionCallParsedObj:`,U(c),"(I: 750f097243b85644d111971e0f929c25)"),u=rt().get(c.name),!u)throw new Error(`no APIFunctionInfo found that matches functionName (${h}) (E: 9d36b6472ec5cdf95e4f498292449925)`);f=c.args,D&&console.log(`${t} valid params (I: a4d5c13c79a2405c8d20464b42083325)`)}catch(m){d=`${t} invalid functionCallParsedObj. error: ${y(m)}. functionCallStr: ${s}. (E: 1687a24c5a3667d34689a09f8f753125)`,console.error(d),c=void 0}if(u){D&&console.log(`${t} found functionInfo: ${u.nameOrId} (I: 837c7a8200689a0b2314b73057812b25)`);let m,g=!1,b;try{D&&console.log(`${t} calling function impl for ${u.nameOrId} (I: b145d08186782089c18564305f0f1125)`),m=await u.fnViaCmd(f),g=!0,D&&console.log(`${t} functionImpl complete for ${u.nameOrId}. result:`,U(m),"(I: e19d476f489261263165914750472d25)")}catch(w){b=`${t} could not call functionImpl for ${u.nameOrId}: ${y(w)} (E: 9c0e97f29a9290f9d57637b7053f0c25)`,console.error(b)}a=(await Qn({api:this.data.api,model:this.data.model,agentId:this.data.uuid,fnRawRequest:s,fnName:h,fnArgs:c.args,repromptWithResult:c.args?.repromptWithResult??!1,fnResult:m,fnComplete:g,execErrorMsg:b,parseErrorMsg:void 0,saveInSpace:!0,metaspace:i,space:await this.getSuperSpace()})).newIbGib}else a=(await Qn({api:this.data.api,model:this.data.model,agentId:this.data.uuid,fnRawRequest:s,fnName:h,fnArgs:c.args,repromptWithResult:c.args?.repromptWithResult??!1,fnResult:void 0,fnComplete:void 0,execErrorMsg:void 0,parseErrorMsg:d,saveInSpace:!0,metaspace:i,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)");o.push(a)}catch(a){throw console.error(`${t} ${y(a)}`),a}finally{D&&console.log(`${t} complete.`)}if(o.length===0)throw new Error("(UNEXPECTED) functionInfoIbGibs.length === 0? We expect at least one to be created (E: a8f81c56377cdbdeb468af6b21879825)");return o}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{D&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_addFunctionCallRequestComment({functionInfoIbGibs:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_addFunctionCallRequestComment.name}]`;try{D&&console.log(`${t} starting... (I: 5000adac5e8c4a7158a720c38f56b325)`);let i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: d7275731461d8d0526af3088553ae525)");let o=await this.getSuperSpace(),s=ht({tagText:an,contentText:e.map(f=>A({ibGib:f})).join(`
|
|
679
|
+
`),randomIdLength:4}),a=_t({textSrc:"ai",other:"functionCallRequest"}),c=await et({text:s,addlMetadataText:a,saveInSpace:!0,space:o}),d=await Xe({type:"rel8",src:c.newIbGib,rel8nsToAddByAddr:{[Yn]:e.map(f=>A({ibGib:f}))},dna:!0,nCounter:!0}),u=d.newIbGib;await i.persistTransformResult({resTransform:d,space:o}),await i.registerNewIbGib({ibGib:u,space:o}),await this.addTexts({infos:[{textSrc:"ai",commentIbGib:u}]})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{D&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt({functionInfoIbGibs:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt.name}]`;try{D&&console.log(`${t} starting... (I: c245f78f6c78a98d62375a9f14b3d625)`);let i=[];for(let o of e)try{let s=A({ibGib:o});if(!o.data)throw new Error(`(UNEXPECTED) !functionInfoIbGib.data? functionInfoAddr: ${s} (E: 7815e4854513c26b889517a9bd7e0d25)`);let{fnRawRequest:a,fnComplete:c,fnResult:d}=o.data,f=ht({tagText:s,contentText:U({fnRawRequest:a,fnComplete:c,fnResult:d}),randomIdLength:void 0});i.push(f)}catch(s){console.error(`${t} could not call functionImpl: ${y(s)} (E: 2a3b8b37e146c524b67119e3a74e3d25)`)}return i.join(`
|
|
680
|
+
`)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{D&&console.log(`${t} complete.`)}}repromptCount=0;repromptMax=12;async rePrompt(){let e=`${this.lc}[${this.rePrompt.name}]`;try{D&&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{D&&console.log(`${e} complete.`)}}async witness(e){if(e.ib===Kt&&e.gib===Jt)return this.getComments_Chat().length>0&&await this.doPrompt(),At;throw new Error(`arg (${U(e)}) not implemented. only expect ${At} right now to trigger doPrompt. (E: 24da0ad7333b6bbb359d1be425db3c25)`)}};var B=K,He=class n extends Zn{static{p(this,"AgentWitnessGemini_V1")}lc=`[${n.name}]`;async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{B&&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{B&&console.log(`${e} complete.`)}}parseAddlMetadataString({ib:e}){let t=`${this.lc}[${this.parseAddlMetadataString.name}]`;try{throw B&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{B&&console.log(`${t} complete.`)}}async addTexts(e){let t=`${this.lc}[${this.addTexts.name}]`;try{let i=Re();await i.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1});let o=this._metaspace;if(!o)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 s=[],a=[],c=[],d=await this.getSuperSpace();for(let h of e.infos){let{textSrc:m,isSystem:g}=h,{text:b,commentIbGib:E}=h;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 w=_t({textSrc:m});if(E)B&&console.log(`${t} adding existing commentIbGib (I: 72a3f7aafde92f65b168d27605f94625)`);else{if(B&&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 et({text:b,addlMetadataText:w,saveInSpace:!0,space:d})).newIbGib,await o.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 ti({ibGib:E});if(v.length>0)throw new Error(`validation errors with trying to add a commentIbGib. errors: ${v} (E: beee1893050f9bcf9842c66831595225)`);s.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 f=await Us({timeline:this.toIbGibDto(),rel8nInfos:u,timelineIndexInfo:{rel8nName:nt,type:this.data.type},metaspace:o,space:d});return await this.loadIbGibDto(f),await i.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!0}),s}catch(i){throw console.error(`${t} ${y(i)}`),i}}async composePromptInfo(){let e=`${this.lc}[${this.composePromptInfo.name}]`;try{if(B&&console.log(`${e} starting... (I: 155774d4811b038034342d5750174325)`),!this._metaspace)throw new Error("this.metaspace falsy (E: 7232a3a1b4348d460ed1375b32677125)");let t=[];for(let f of this.commentIbGibs_system){let h=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:f});t.push(...h)}let i=this.data?.["@currentContextTjpAddr"]??Q;if(i!==Q&&t.push({src:j.HARDCODED,content:{role:Ut(j.HARDCODED),parts:[{text:El({currentContextTjpAddr:i})}]}}),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 o=[],s=this.commentIbGibs_chat.length>1?this.commentIbGibs_chat.slice(0,-1):[];for(let f of s){let h=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:f});o.push(...h)}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)o.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:o,chatPromptCurrent:a};return B&&console.log(`${e} resPromptInfo:`,U(u),"(I: 8f17a8c45b9a91e20a5c5064d9114a25)"),u}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{B&&console.log(`${e} complete.`)}}async callTextAPI(e){let t=`${this.lc}[${this.callTextAPI.name}]`;try{if(B&&console.log(`${t} starting... (I: 27885f5b14682646542e9658417b2f25)`),!gl(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:i,model:o}=this.data;if(i!=="gemini")throw new Error(`api not supported: ${i} (E: 7e5c7c17988a666a86e72299630c7f25)`);B&&console.log(`${t} calling gemini api with model: ${o} (I: 6208942a419e9041bb037384135a0c25)`);let s=await this.fnGetAPIKey();if(!s)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 Lt({apiKey:s});let a=Array.from(this.availableFunctions.values()).map(I=>({name:I.nameOrId,description:I.schema?.description,parameters:I.schema?.parameters}));a.some(I=>I.parameters==="undefined")&&console.error(`${t} (UNEXPECTED) function schema parameters not defined for all APIFunctionInfo values. (E: ae7227cdd65c0ab4513c7b282a1e4825)`),B&&(console.log(`${t} Gemini functionDeclarations:`),console.dir(a));let{systemPromptEntries:c,chatPromptHistoryParts:d,chatPromptCurrent:u}=e,f=se(u);B&&console.log(`chatPromptCurrent_final (before decompression): ${U(f)} (I: bbd4c7b9f3225afe9da1761918d0ac25)`),B&&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 h,m=p(async I=>{if(!this._genAI)throw new Error("(UNEXPECTED) this._genAI falsy? (E: 503a0d9e3f729de7653ee3565b017b25)");let T=d.map(P=>P.content),C={model:I,history:T,config:{systemInstruction:Oo({systemPromptEntries:c}),tools:[{functionDeclarations:a}],toolConfig:{functionCallingConfig:{mode:e.overrideFunctionCallingMode??bn.ANY}}}},N=this._genAI.chats.create(C),S={message:u.content.parts};return await N.sendMessage(S)},"fnGoModel"),g=0,b=o;do{g++;try{h=await m(b);break}catch(I){let T=I.message,C=I.status??"[STATUS?]";T.includes(`${503}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${mt}) for this next call. error (${I.status}): ${y(I)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=mt):T.includes(`${429}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${mt}) for this next call. error (${I.status}): ${y(I)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=mt):console.error(`${t}[fnGoModel][${b}] error trying to get result from model. error (${I.status}): ${y(I)} (E: a67d595c8ed313d458369d4d0b3e7f25)`)}await O(2e3)}while(!h&&g<Gi);if(!h)throw new Error("couldn't get result from model (E: ede013a53f875d99a96a2e257c7e7125)");let E=h,w=[],v=E.candidates?.[0]?.content?.parts||[];for(let I of v)I.functionCall&&w.push(I.functionCall);if(!w||w.length===0){if(B&&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 B&&(console.log(`${t} Gemini function calls:`),console.dir(w)),{functionCalls:w.map(I=>JSON.stringify(I,null,2))}}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{B&&console.log(`${t} complete.`)}}async createPromptInfoEntriesFromGeminiComment({commentIbGib:e}){let t=`[${this.createPromptInfoEntriesFromGeminiComment.name}]`;try{B&&console.log(`${t} starting... (I: 826a9d6b120d96532afbe1f7a22e8d25)`);let i=await ti({ibGib:e});if(i.length>0)throw new Error(`validation errors with commentIbGib. Cannot create a prompt info entry. errors: ${i} (E: beee1893050f9bcf9842c66831595225)`);let{safeIbCommentMetadataText:o}=je({ib:e.ib});if(!o)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:s,timestampInTicks:a,errorMsg:c,other:d}=Bt({addlMetadataText:o,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(zo({ibGib:e})){let f=await this.getFunctionInfoIbGibs({fcrCommentIbGib:e}),h=[],m=[];for(let E of f){let{call:w,response:v}=Ko({functionInfoIbGib:E});if(!w)throw new Error("(UNEXPECTED) call falsy? (E: 5c8f3bd6de3b300e1c105b9603bb7b25)");if(!v)throw new Error("(UNEXPECTED) response falsy? (E: d0388c838975c93126c1a6d64f781d25)");if(w.functionCall.name!==v.functionResponse.name)throw new Error("(UNEXPECTED) functionCall.name !== functionResponse.name? (E: e49f0d60093354db2b6ad17fdf86d425)");h.push(w),m.push(v)}let g={src:j.AI,content:{role:Ut("ai"),parts:h}},b={src:j.FUNCTION,content:{role:Ut(j.FUNCTION),parts:m}};return[g,b]}else return[{src:s,content:{role:Ut(s),parts:[{text:e.data.text}]}}]}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{B&&console.log(`${t} complete.`)}}async promptOneOff(e){let t=`${this.lc}[${this.promptOneOff.name}]`;try{B&&console.log(`${t} starting... (I: genuuid)`);let{text:i,systemInstructions:o}=e;if(!i)throw new Error("(UNEXPECTED) opts.text falsy? (E: genuuid)");if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: genuuid)");let{api:s,model:a}=this.data;if(s!=="gemini")throw new Error(`api not supported: ${s} (E: genuuid)`);B&&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 Lt({apiKey:c});let d=p(async b=>{if(!this._genAI)throw new Error("(UNEXPECTED) this._genAI falsy? (E: fbe235713d48f0d8e87cd0b88ec54825)");let E={model:b,config:{systemInstruction:o}},v=await this._genAI.chats.create(E).sendMessage({message:i});if(v.text)return v.text;throw new Error("response.text empty/falsy, potentially blocked by safety settings (E: a21a78c9471f27a42c07d1c859187825)")},"fnGoModel"),u,f=0,h=[];e.modelOverrides&&e.modelOverrides.length>0?h.push(...e.modelOverrides):h.push(a),e.modelBackupOverrides&&e.modelBackupOverrides.length>0?h.push(...e.modelBackupOverrides):h.push(mt);let m=0,g=1;do{f++,g++;let b=h[m];try{u=await d(b);break}catch(E){if(E instanceof Error){let w=E.message,v=E.status??"[STATUS?]";if(w.includes(`${503}`))if(m===h.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{m++;let I=h[m];console.error(`${t}[fnGoModel][${b}] error trying to get result from model: GEMINI_ERROR_STATUS_MODEL_OVERLOADED ${503}. will try using the next model (${I}) for this next call. error (${v}): ${y(E)} (E: b07a041bb97ea95b03cd6f9856f01525)`)}else if(w.includes(`${429}`))if(m===h.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{m++;let I=h[m];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 (${I}) 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)`)}f>1&&await O(g*1e3)}while(!u&&f<Gi);return u}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{B&&console.log(`${t} complete.`)}}async getFunctionInfoIbGibs({fcrCommentIbGib:e}){let t=`[${this.getFunctionInfoIbGibs.name}]`;try{B&&console.log(`${t} starting... (I: 976a684b7ae58cda523b17fc0c62e325)`);let i=[];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 o=this._metaspace;if(!o)throw new Error("(UNEXPECTED) this.metaspace falsy. (E: 997d071847c5d7e80692f48191244e25)");let s=await this.getSuperSpace();if(!s)throw new Error("(UNEXPECTED) superSpace falsy? (E: dd1600f15e1e659c01f73991656a3325)");let a=e.rel8ns?.[Yn]??[];if(a.length===0)return B&&console.warn(`${t} no functionInfoAddrs (I: 5f8965e92c305689c11677a1148b7425)`),[];B&&console.log(`${t} functionInfoAddrs: ${a} (I: e7b1f5a4576c493326b913e48a505e25)`);let c=await o.get({addrs:a,space:s});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 i=c.ibGibs,B&&console.log(`${t} resFunctionInfoIbGibs: ${U(i.map(d=>A({ibGib:d})))} (I: a5661b5c449608f0e8d773135a599a25)`),i}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{B&&console.log(`${t} complete.`)}}async loadIbGibDto(e){let t=`[${this.loadIbGibDto.name}]`;try{if(B&&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 i=this._metaspace;if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: e5762b1e3f77f84ca338641edc011225)");let o=await this.getSuperSpace(),s=p(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=rt().get(d);u?this.availableFunctions.set(d,u):Ho().includes(d)?B&&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 i.get({addrs:a,space:o});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 i.get({addrs:c,space:o});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 Wt({scope:"prune",secondsValid:60,maxDelayMs:100,maxLockAttempts:1800,space:o,callerInstanceId:We(),fn:s})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{B&&console.log(`${t} complete.`)}}};setTimeout(()=>{Re().registerFactory({classname:He.name,fnDtoToAgentWitness:p(async e=>e.data?e.data.classname?e.data.classname===He.name?{applies:!0,agent:await Wo({agentIbGib:e})}:{applies:!1}:{applies:!1}:{applies:!1},"fnDtoToAgentWitness")})});function El({currentContextTjpAddr:n}){let e=`[${El.name}]`;try{B&&console.log(`${e} starting... (I: 7edafbba277d57eae51af325cf7eb225)`);let t=W({ibGibAddr:n});return`Your current context ibGibAddr is ${n}
|
|
681
|
+
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{B&&console.log(`${e} complete.`)}}p(El,"getTextPartForCurrentContextTjpAddr");var Oe=K,ni=class n{static{p(this,"CreateConcreteAgentWitnessFactory_Gemini")}lc=`[${n.name}]`;arg;constructor(e){this.arg=e}async createInitialData(e){let t=`${this.lc}[${this.createInitialData.name}]`;try{Oe&&console.log(`${t} starting... (I: f4c8ac488804666077cfc2237972d625)`);let{name:i,api:o,model:s,type:a,availableFunctions:c}=this.arg;if(!s)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=se(cr);return i&&(d.name=i),d.uuid=await Fe(),d.superSpaceId=e.data.uuid,d.api=o,d.model=s,d.type=a,d.availableFunctionNameOrIds=c.map(u=>u.nameOrId),d.classname=He.name,d}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{Oe&&console.log(`${t} complete.`)}}async createInitialRel8ns(){let e=`${this.lc}[${this.createInitialRel8ns.name}]`;try{return Oe&&console.log(`${e} starting... (I: 2d4933ea3761bd7df701d8d306fb2825)`),Mi?se(Mi):void 0}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Oe&&console.log(`${e} complete.`)}}async createWitness(){let e=`[${this.createWitness.name}]`;try{Oe&&console.log(`${e} starting... (I: 36709dfa0c398d63d64c4f6ba9055625)`);let{api:t,model:i}=this.arg;if(t==="gemini"){let o=new He;return await o.initialized,o}else throw new Error(`(UNEXPECTED) unknown api: ${t}? only 'gemini' currently implemented (E: 2d1cb22ce787c6c42d4532c260320125)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Oe&&console.log(`${e} complete.`)}}};async function Wo({agentIbGib:n}){let e=`[${Wo.name}]`;try{Oe&&console.log(`${e} starting... (I: 5a4efefba9e4bdfb942afbe7919fff25)`);let t=new He;return await t.initialized,await t.loadIbGibDto(n),t.fnGetAPIKey=async()=>await Zt({dbName:ks(),storeName:await Ms(),key:await Ds()})??"",t}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Oe&&console.log(`${e} complete.`)}}p(Wo,"agentIbGibDtoToWitness");var te=K;async function Ni({metaspace:n,space:e,createIfNone:t}){let i=`[${Ni.name}]`;try{if(te&&console.log(`${i} starting... (I: ad1594767abce66ca80fea8c8d89f325)`),e??=await n.getLocalUserSpace({lock:!1}),!e)throw new Error("(UNEXPECTED) space falsy after getting local user space? (E: bc68d97d46dcf1d15dd74edba200b725)");let o=await $s({metaspace:n,space:e});if(!o.rel8ns)throw new Error("(UNEXPECTED) tagsIbGib.rel8ns falsy? (E: dc50e8d218fe5e30bbaec7f37d484525)");let a=(o.rel8ns[gs]??[]).filter(u=>{let{ib:f}=H({ibGibAddr:u});return f===_s}),c,d;if(a.length===0){if(t){te&&console.log(`${i} creating new agents tag... (I: 47f4f4fa89f1a1bba960e0a6ff5f5225)`);let{newTagIbGib:u}=await n.createTagIbGib({text:Is,icon:Ts,description:Cs,space:e});return d=u,te&&console.log(`${i} creating new agents tag complete. (I: 5f41d644f2b692348377f918057cf225)`),u}}else a.length===1?(c=a.at(0),te&&console.log(`${i} exactly one agent tag addr found (${c}) in space (${e.ib}) (I: 7ef995963313c966216097760d0cdb25)`)):(c=a.at(0),console.error(`${i} 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(o){throw console.error(`${i} ${y(o)}`),o}finally{te&&console.log(`${i} complete.`)}}p(Ni,"getTag_Agents");async function ln({metaspace:n,type:e,spaceId:t,space:i}){let o=`[${ln.name}]`;try{if(te&&console.log(`${o} starting... (I: 41037d1926051c4b051769069f518f25)`),i??=await n.getLocalUserSpace({localSpaceId:t,lock:!1}),!i)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:i}))throw new Error("(UNEXPECTED) couldn't initialize/get agents special ibgib? (E: 1abe0e2543711744adbdb7026b242e25)");let a=await n.getSpecialRel8dIbGibs({rel8nName:nt,type:e,space:i})??[],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=Re(),f=await u.getLatestAgent({id:d.data.uuid});if(!f){if(f=await u.getAgentWitnessFromDto({dto:d}),!f){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:f,throwIfNewerFound:!1})}c.push(f)}return c}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{te&&console.log(`${o} complete.`)}}p(ln,"getAgents");async function Jo({metaspace:n,type:e,space:t,newAgentIbGib:i}){await p(async()=>{let s=`[${Jo.name}]`;try{if(te&&console.log(`${s} starting... (I: bf6ff6bf4132eaa943eaa3af1ee17225)`),!i.data)throw new Error("(UNEXPECTED) newAgentIbGib.data falsy? (E: 26e03d0a8e286ac3a13b678a50c87a25)");if(!i.data.uuid)throw new Error("(UNEXPECTED) newAgentIbGib.data.uuid falsy? (E: 31b753e01275272484ea93e3dfe53225)");let c=await Re().getLatestAgent({id:i.data.uuid});if(c&&c.data.n>i.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 (${i.data.uuid}) already in existence, but the caller is trying to update the special ibgib index with the older agent. (E: 5c0c028075736f22072c55e20a0c7e25)`)}let d=A({ibGib:i});await ue({type:i.data.type,rel8nInfos:[{rel8nName:nt,ibGibs:[z({ibGib:i})]}],metaspace:n,space:t})}catch(a){throw console.error(`${s} ${y(a)}`),a}finally{te&&console.log(`${s} complete.`)}},"fn")()}p(Jo,"updateAgentIndex");async function Xo({ibGib:n,metaspace:e,space:t}){let i=`[${Xo.name}]`;try{if(te&&console.log(`${i} starting...`),!n)throw new Error("ibGib required (E: 753a0aa13e4e5ea20d7f6bb92d963625)");let o=await Xt({ibGib:n,metaspace:e,space:t,scope:"agent",skipGetLatest:!1});if(!o){console.warn(`${i} couldn't find agent for domain ibGib (${n.ib}) (W: 9536a8e67fe83ddc819c476f5a50c825)`);return}let s=X({ibGib:n,defaultIfNone:"incomingAddr"}),a=A({ibGib:o}),d=await Re().getAgentByAddr({agentAddr:a,metaspace:e,spaceId:t.data.uuid});return te&&console.log(d?`${i} complete. Found agent ${A({ibGib:d})} for domain ${s}`:`${i} complete. No agent found for ibgib tjp ${s}`),d}catch(o){throw console.error(`${i} ${y(o)}`),o}}p(Xo,"getAgentForDomainIbGib");function $i(n){let e=`[${$i.name}]`;try{te&&console.log(`${e} starting... (I: 2a9899514ac6e478eb55819a57fd9725)`);let{api:t}=n;switch(t){case"gemini":return new ni(n);default:throw new Error(`(UNEXPECTED) api: ${t}? only 'gemini' currently implemented? (E: 071fedab181fda80666858c14ea73625)`)}}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{te&&console.log(`${e} complete.`)}}p($i,"getConcreteAgentFactory");function ht({tagText:n,contentText:e,randomIdLength:t}){let i=`[${ht.name}]`;try{te&&console.log(`${i} starting... (I: 94104ec059c89d4ba458d96580791d25)`);let o=t?`${n}|${ct({count:t})}`:n;return[`[${o} begin]`,e,`[${o} end]`].join(`
|
|
682
|
+
`)}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{te&&console.log(`${i} complete.`)}}p(ht,"taggifyForPrompt");function _t({textSrc:n,other:e}){let t=`[${_t.name}]`;return e?[n,We(),e].join("_"):[n,We()].join("_")}p(_t,"getAddlMetadataTextForAgentText");function Bt({addlMetadataText:n,ifError:e="warn"}){let t=`[${_t.name}]`;try{te&&console.log(`${t} starting... (I: 89b8b19a8d785b945fe0f816df762d25)`);let[i,o,...s]=n.split("_");if(!i)throw new Error("addlMetadataText.textSrc falsy (E: 40bbec4269c1688ab1390fa5d5440325)");if(!or(i))throw new Error(`addlMetadataText.textSrc (${i}) is unexpected value. Expected one of ${_i} (E: 02bae41275a39210e5737548747bd825)`);if(!o)throw new Error("addlMetadataText.timestampInTicks falsy (E: 03cbbc7515a1cff1fc7c12e3947c6825)");let a=Number.parseInt(o);if(Number.isNaN(a))throw new Error(`invalid timestampInTicks (${o}): value should be an integer but parse is NaN (E: 9d31e3563d972c02553ce18a19a19b25)`);return{textSrc:i,timestampInTicks:a,other:s.length>0?s:void 0}}catch(i){let o=`${t} ${y(i)}`;switch(e){case"ignore":return{textSrc:j.UNKNOWN,timestampInTicks:0,errorMsg:y(i)};case"warn":return console.warn(`${t} ${o} (W: 3e1f4a98ad6461c9bd96462841c31b25)`),{textSrc:j.UNKNOWN,timestampInTicks:0,errorMsg:y(i)};default:throw console.error(`${t} ${o} (E: 6396ed44947c52adf85788e1adc22825)`),new Error(o)}}finally{te&&console.log(`${t} complete.`)}}p(Bt,"parseAddlMetadataTextForAgentText");function Pi({data:n}){let e=`[${Pi.name}]`,{name:t,uuid:i,type:o}=n;if(!t)throw new Error(`${e} data.name falsy (E: 4c172c5b8a110ae26479b8c4006f3225)`);if(!i)throw new Error(`${e} data.uuid falsy (E: 67d2c79ac39e70e5ecfd1745e1fd3525)`);if(!o)throw new Error(`${e} data.type falsy (E: 53bf1f9a145a16be81296437682a7a25)`);if([t,i,o].some(a=>a.includes(" ")))throw new Error("invalid data. ib must not contain spaces in name, uuid, type. (E: 36a56e4685163848458be06f51d4ad25)");return[ft,t,i,o].join(" ")}p(Pi,"getAgentIb");function ar({ib:n}){let[e,t,i,o]=n.split(" ");if(e!==ft)throw new Error(`invalid ib. first term expected to e an atom: ${ft} (E: 3c01d42035d2e32c4bfd5c1bf363f725)`);if(!t)throw new Error("invalid ib. name falsy in agent ib (E: 8b494c544f05b8ef9c866078b761a725)");if(!i)throw new Error("invalid ib. uuid falsy in agent ib (E: aba195db3ddcb000324ebed15351b725)");if(!o)throw new Error("invalid ib. type falsy in agent ib (E: 8c814772394ae76342f95e885570c325)");return{atom:e,name:t,uuid:i,type:o}}p(ar,"parseAgentIb");async function ti({ibGib:n}){let e=`[${ti.name}]`;try{te&&console.log(`${e} starting... (I: f9a733a5a05b7f7494836d86a79e2d25)`);let t=await dt({ibGib:n})??[];if(!tt({ibGib:n}))return t.push(`${e} not a comment ibgib (E: 08676d94c698c6e42e6c35e94a58f125)`),t;let{safeIbCommentMetadataText:i}=je({ib:n.ib});if(i){let o=Bt({addlMetadataText:i,ifError:"warn"});o.errorMsg&&t.push(`${e} could not parse addlMetadataText: ${o.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{te&&console.log(`${e} complete.`)}}p(ti,"validateAgentWitnessCommentIbGib");var ii="settings",Km="general",Jm="text-editor",Wm="projects",Xm="projects-explorer",Ym="projects-dropdown",Qm="project",Zm="minigame",jm="chronologys",eg="identity-manager",oe={general:Km,textEditor:Jm,projects:Wm,projectsExplorer:Xm,projectsDropdown:Ym,project:Qm,minigame:Zm,chronologys:jm,identityManager:eg},tg=Object.values(oe);var Yo={type:oe.general,editor:void 0,readonly:!0,viewer:"ibgib-raw-viewer"},Qo={type:oe.textEditor,wrap:"wrap"},ng={type:oe.project,openChildTjpAddrs:[],activeChildTjpAddr:void 0,lensMode:"raw"},ig={type:oe.minigame},og={type:oe.chronologys,openChildTjpAddrs:[],activeChildTjpAddr:void 0},sg={type:oe.identityManager,openChildTjpAddrs:[],activeChildTjpAddr:void 0},wl={sections:{},children:{}};var ze=K;async function Zo({ibGib:n}){let e=`[${Zo.name}]`;try{ze&&console.log(`${e} starting... (I: 57ac4c0a3448bc5e98ecf5bfb02ce825)`);let{ib:t}=H({ibGib:n}),i=t.split(" ").at(0);if(!i)throw new Error("(UNEXPECTED) atom falsy? we split the ib by spaces (space-delimiter). this makes no sense. (E: 6a9ea640ae38823aeefc6ec82a05d625)");return`${ii}_${i}`}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{ze&&console.log(`${e} complete.`)}}p(Zo,"getSettingsScope");async function we({settingsType:n,useCase:e}){let t=`[${we.name}]`;try{if(ze&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{ze&&console.log(`${t} complete.`)}}p(we,"getSectionName");async function oi({sectionName:n,settingsIbGib:e}){let t=`[${oi.name}]`;try{if(ze&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{ze&&console.log(`${t} complete.`)}}p(oi,"getSettingsSection");function vl({scope:n}){let e=`[${vl.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,"__")),`${ii} ${n}`}catch(t){throw console.error(`${e} ${y(t)}`),t}}p(vl,"getSettingsIb");async function jo({scope:n,metaspace:e,space:t,saveInSpace:i}){let o=`[${jo.name}]`;try{let s=vl({scope:n}),a=await Il(),d=await re.firstGen({parentIbGib:re.primitive({ib:ii}),ib:s,data:a,rel8ns:void 0,dna:!0,nCounter:!0,tjp:{timestamp:!0,uuid:!0}});if(i){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(s){throw console.error(`${o} ${y(s)}`),s}}p(jo,"createSettings");async function Il(){let n=`[${Il.name}]`;try{ze&&console.log(`${n} starting... (I: 3d7cc3f242cc88ad28dafaf85d646a25)`);let e=se(wl),t=await we({settingsType:"general",useCase:"default"}),i=await we({settingsType:"general",useCase:"current"});e.sections[t]=se(Yo),e.sections[i]=se(Yo);let o=await we({settingsType:"text-editor",useCase:"default"}),s=await we({settingsType:"text-editor",useCase:"current"});return e.sections[o]=se(Qo),e.sections[s]=se(Qo),e}catch(e){throw console.error(`${n} ${y(e)}`),e}finally{ze&&console.log(`${n} complete.`)}}p(Il,"getDefaultSettingsData");var G=K,de=class n{static{p(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}},Ke=class n extends HTMLElement{static{p(this,"IbGibDynamicComponentInstanceBase")}lc=`[${n.name}]`;elements;createdPromise;settings;get agent(){return this.agents.at(0)}agents=[];get ib(){let{ib:e}=H({ibGibAddr:this.ibGibAddr??Q});return e}get gib(){let{gib:e}=H({ibGibAddr:this.ibGibAddr??Q});return e}ibGibAddr=Q;ibGibProxy;get ibGib(){let e=this.ibGibAddr??Q,{ib:t,gib:i}=H({ibGibAddr:e});return this.ibGibAddr&&!xt({gib:i})?this.ibGibProxy?.ibGib:re.primitive({ib:t})}get tjpAddr(){return this.ibGib?X({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:i,localOnly:o,animationEmoji:s}){let a=`${this.lc}[${this.showBusy.name}]`;try{this._isBusy=e,o?this.dispatchEvent(new CustomEvent(Nt,{detail:{isBusy:e,title:t,msg:i,animationEmoji:s},bubbles:!0,composed:!0})):window.dispatchEvent(new CustomEvent(Nt,{detail:{isBusy:e,title:t,msg:i,animationEmoji:s}}))}catch(c){throw console.error(`${a} ${y(c)}`),c}}async getMetaspace(){let e=`${this.lc}[${this.getMetaspace.name}]`;try{if(G&&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{G&&console.log(`${e} complete.`)}}constructor(){super(),this._instanceId=ct({count:8})}async initialize(e){let{ibGibAddr:t,meta:i,html:o,css:s}=e,a=`${this.lc}[${this.initialize.name}]`;try{G&&console.log(`${a} starting... (I: c9b94131bc2f0d20e1397c214dad6725)`),this.ibGibAddr=t,this.meta=i,this.html=o,this.css=s,this.attachShadow({mode:"open"}),await this.meta.bootstrapPromise}catch(c){throw console.error(`${a} ${y(c)}`),c}finally{G&&console.log(`${a} complete.`)}}async initAgents(){let e=`${this.lc}[${this.initAgents.name}]`;G&&console.log(`${e} does nothing in base class (I: 0b31a650b942619a0e36a1a7f763e825)`)}async connectedCallback(){let e=`${this.lc}[${this.connectedCallback.name}]`;try{G&&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{G&&console.log(`${e} complete.`)}}async connectedCallback_initComponent(){let e=`${this.lc}[${this.connectedCallback_initComponent.name}]`;try{if(G&&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?`
|
|
683
683
|
<style>
|
|
684
684
|
${this.css.join(`
|
|
685
685
|
`)}
|
|
686
686
|
</style>
|
|
687
687
|
${this.html}
|
|
688
|
-
`: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{
|
|
689
|
-
agent.data: ${
|
|
690
|
-
ibGib.data: ${K({ibGib:this.ibGib})} (W: cb22e8b064d8c2d7b3b2c488ed169225)`),this.agents=[s]}else if(e)console.warn(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${C({ibGib:this.ibGib})}) (W: e4219903462baab438a23c786d714825)`);else throw new Error(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${C({ibGib:this.ibGib})}) (E: 7182d1aa070b9578c78a5b8b401d8425)`)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{R&&console.log(`${t} complete.`)}}async getSettings({settingsType:e,useCase:t}){let i=`${this.lc}[${this.getSettings.name}]`;try{if(R&&console.log(`${i} 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 o=await jn({sectionName:await Ee({settingsType:e,useCase:t}),settingsIbGib:this.settings.ibGib});return o||R&&console.log(`${i} settingsSection does not exist. returning undefined. (I: 0462d83f5ae8049708274b88e9b0d825)`),o}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{R&&console.log(`${i} complete.`)}}async updateSettings({settingsType:e,useCase:t,newSectionInfo:i}){let o=`${this.lc}[${this.updateSettings.name}]`;try{R&&console.log(`${o} starting... (I: 80ce98cf386e0c04d30e8b15ac0f2925)`);let s=await Ee({settingsType:e,useCase:t}),a=await at({timeline:this.settings.ibGib,metaspace:await this.getMetaspace(),mut8Opts:{dataToAddOrPatch:{sections:{[s]:i}}}});await H(100)}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{R&&console.log(`${o} complete.`)}}async getCurrentSettings({settingsType:e}){let t=`${this.lc}[${this.getCurrentSettings.name}]`;try{if(R&&console.log(`${t} starting... (I: da0baee73e386089a8c059f83cc43825)`),!this.settings)return;let i=await Ee({settingsType:e,useCase:"current"});return jn({sectionName:i,settingsIbGib:this.settings.ibGib})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{R&&console.log(`${t} complete.`)}}async initSettings(){let e=`${this.lc}[${this.initSettings.name}]`;try{if(R&&console.log(`${e} starting... (I: acfee8787d32a6075442e2887a386a25)`),!this.ibGib)throw new Error("(UNEXPECTED) this.ibGib falsy? (E: 8ce2e73bea87b9330b131778a3981825)");let t=await this.getMetaspace(),i=await t.getLocalUserSpace({lock:!1});if(!i)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: f77ce7269a6f0d7ad8978349b4c6cd25)");if(Ct({ibGib:this.ibGib})){console.error(`${e} this.ibGib is primitive, so what are we initializing settings for? (W: 9915089019b81c6935b32ae877095825)`);return}let o=await Ko({ibGib:this.ibGib}),s=await Ot({scope:o,ibGib:this.ibGib,metaspace:t,space:i});if(s||(s=(await Jo({scope:o,metaspace:t,space:i,saveInSpace:!0})).newIbGib,await ui({scope:o,domainIbGib:this.ibGib,localIbGib:s,metaspace:t,space:i})),!s)throw new Error("(UNEXPECTED) settings falsy still? should be initialized. (E: a179adcbbab800cff849b8aa95fbe425)");let a=new Ue;if(await a.setWrappedIbGib({ibGib:s,space:i}),this.settings=a,!await this.getCurrentSettings({settingsType:ne.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{R&&console.log(`${e} complete.`)}}async exportIbGib({ibGib:e,compress:t}){let i=`${this.lc}[${this.exportIbGib.name}]`;try{R&&console.log(`${i} starting... (I: 623d9463d919683be81f749821a95825)`);let o=await this.getMetaspace();if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: 3d15dbd074ac0c15b834a788d0b57d25)");if(Ct({ibGib:e}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let s=await o.getLocalUserSpace({lock:!1});if(!s)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: 7bb735be58282f1bd7abe5d9ffabb525)");await Cs({ibGib:e,compress:t,metaspace:o,space:s})}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{R&&console.log(`${i} complete.`)}}async importIbGib({exportIbGibJsonString:e,rel8nName:t,force:i,skipRegisterTimelines:o,divergentTimelineStrategy:s}){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,f]=await Ts({exportIbGibJsonString:e,metaspace:c});if(!u.data)throw new Error("(UNEXPECTED) rawExportIbGib.data falsy? this is assumed validated at this point. (E: 6bc4e84db08e3c6228b2c40c2ea50825)");let h=u.data.contextIbGibAddr,m=!1;if(!i){let g=await c.get({addr:h,space:d});g.success&&(g.ibGibs??[]).length===1&&(console.log(`${a} export's ibGib addr (${h}) already exists in the space, so we're skipping doing any physical importing of the export's graph. (I: 429b5bdcd0585c697869f568c4673825)`),m=!0)}if(!m){di;let g=[],b=[];Object.values(f).forEach(A=>{os({ibGib:A})?g.push(A):b.push(A)});let E=await c.put({ibGibs:g,isDna:!0,space:d,force:i});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:w,mapWithTjp_NoDna:v,mapWithoutTjps:I}=di({ibGibs:b}),T=await c.put({ibGibs:Object.values(I),space:d,force:i});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 S={...w,...v},N=Object.values(S),$=await c.put({ibGibs:N,space:d,force:i});if(!$.success||$.errorMsg)throw new Error(`there was an error putting the export's timeline ibgibs into the space (${d.ib}). error: ${$.errorMsg||"[unknown error (E: be4a28961574765798c8d3686ae89c25)]"} (E: 066796a23da3c9f748558fd25bfdf525)`);if(!o){let A=We({ibGibs:N}),P=Object.values(A);for(let x of P){let k=x.at(-1);if(!k)throw new Error("(UNEXPECTED) latestInTimeline falsy? this would mean that we had an empty timeline, and this doesn't make sense... (E: 3bec09e79768cc39d8029f4fe3af9825)");let O=await c.getLatestAddr({ibGib:k,space:d});!1||await c.registerNewIbGib({ibGib:k,space:d})}}}throw new Error("not implemented (E: 66c308e420e848c8d7cd01c8fddf8425)")}catch(c){throw console.error(`${a} ${y(c)}`),c}finally{R&&console.log(`${a} complete.`)}}},kt=class extends Oe{static{p(this,"IbGibDynamicComponentInstanceBase_Parent")}childInfos=[];get activeChildInfo(){return this.childInfos.find(e=>e.active)}async activateIbGib({addr:e,ibGib:t}){let i=`${this.lc}[${this.activateIbGib.name}]`;try{let m=function(g){let b=q({ibGibAddr:g.addr}).gib;return(z({gib:b}).tjpGib??b)===h};var o=m;for(p(m,"tabInfoSharesTjpGib"),R&&console.log(`${i} starting... (I: 05015d78983488496dcca4fa36718725)`);!this.createdPromise;)await H(50);if(await this.createdPromise,!this.elements)throw new Error("(UNEXPECTED) this.elements falsy? (E: fa221c138f211ee93c717c9dd0cf3225)");let{contentEl:s}=this.elements;if(!t&&!e)throw new Error("(UNEXPECTED) both ibGib and addr falsy? (E: 529fb88738cdacb10aea87b8450f2525)");if(t&&e&&C({ibGib:t})!==e)throw new Error("(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: c99a94d8744e3a720cdbc094d53c4e25)");e??=C({ibGib:t});let a=await re(),c=await this.getLoadedChildInfo({addr:e,ibGib:t});if(c.active){console.log(`${i} 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,s.innerHTML=""),c.childBtnEl.classList.add("active"),c.childBtnEl.scrollIntoView({behavior:"smooth"}),c.active=!0;let u=q({ibGibAddr:e}).gib,h=z({gib:u}).tjpGib??u;if(this.childInfos.some(g=>m(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:s,componentToInject:c.component})}catch(s){throw console.error(`${i} ${y(s)}`),s}finally{R&&console.log(`${i} complete.`)}}},ei=class n extends kt{static{p(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{R&&console.log(`${t} starting... (I: e0d5f8ed67b8a7f43822fa3843fd4525)`);let i=C({ibGib:e}),o=Q({ibGib:e,defaultIfNone:"incomingAddr"});if(!o)throw new Error(`(UNEXPECTED) tjpAddr false after incomingAddr default? ibGib: ${L(e)} (E: 707988b4d22a27c1287aa5a815d88825)`);let s=await this.getLoadedChildInfo({addr:i,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: ${L(this.ibGib)} (E: ecea08dcacd198bb38cc44a860cc6825)`);if(!a.openChildTjpAddrs.includes(o))throw new Error(`${t} (UNEXPECTED) projectSettings didn't have the tjpAddr (${o})? projectSettings: ${L(a)} (E: genuuid)`);let c=a.openChildTjpAddrs.filter(g=>g!==o),d;if(a.activeChildTjpAddr===o)if(c.length>0){let g=a.openChildTjpAddrs.indexOf(o)-1;g<0&&(g=0),d=a.openChildTjpAddrs.at(g)}else d=this.tjpAddr,c.push(this.tjpAddr);let u=await Ee({settingsType:this.settingsType,useCase:"current"}),f={...a,openChildTjpAddrs:c},h=await this.getMetaspace(),m=await at({timeline:this.settings.ibGib,metaspace:h,mut8Opts:{dataToAddOrPatch:{sections:{[u]:f}}}});s.active&&await this.activateIbGib({addr:d}),this.childInfos=this.childInfos.filter(g=>g.addr!==s.addr),await this.removeTabBtn({tabInfo:s})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{R&&console.log(`${t} complete.`)}}async reopenOldTabs(){let e=`${this.lc}[${this.reopenOldTabs.name}]`;try{R&&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 i;try{for(let o of t.openChildTjpAddrs)i=o,await this.activateIbGib({addr:o})}catch(o){throw console.error(`${e} error during activating child ibGib tabs. childTjpAddr: ${i??"[unset?]"} (E: 0396b2e24d08f42ac94510bb718a1725)`),o}finally{this.reloadingTabs=!1}await this.activateIbGib({addr:t.activeChildTjpAddr})}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{R&&console.log(`${e} complete.`)}}},ze=class extends Oe{static{p(this,"IbGibFormInstanceBase")}setLoading(e,t="#btn-submit, #btn-generate",i){if(!this.shadowRoot)return;let o=this.shadowRoot.querySelector(t);if(o)if(o.disabled=e,e)o.setAttribute("data-loading","true"),i&&(o.setAttribute("data-original-text",o.textContent||""),o.textContent=i);else{o.removeAttribute("data-loading");let s=o.getAttribute("data-original-text");s!==null&&(o.textContent=s,o.removeAttribute("data-original-text"))}}setStatus(e,t,i="status-area",o="status-text"){if(!this.shadowRoot)return;let s=this.shadowRoot.getElementById(i),a=this.shadowRoot.getElementById(o);a&&(a.textContent=e,a.className=`status-msg ${t}`),s&&(e?s.classList.remove("hidden"):s.classList.add("hidden"))}dispatchShellMessage(e,t){this.dispatchEvent(new CustomEvent(se,{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 i=this.shadowRoot.querySelectorAll("input, select, textarea"),o=!0;for(let s of Array.from(i)){let a=s;if(!a.checkValidity()){o=!1,a.reportValidity();break}}return o}validateInputPattern({input:e,pattern:t,errorMessage:i,required:o=!0}){if(!e)return!0;let s=e.value.trim();if(!s&&!o)return e.classList.remove("invalid"),e.setCustomValidity(""),!0;let a=t.test(s);return a?(e.classList.remove("invalid"),e.setCustomValidity("")):(e.classList.add("invalid"),e.setCustomValidity(i),e.reportValidity()),a}showBusy({isBusy:e,title:t,msg:i,localOnly:o,submitBtnSelector:s,loadingText:a,animationEmoji:c}){let d=`${this.lc}[${this.showBusy.name}]`;try{this.setLoading(e,s,a),this.toggleAllInputsDisabled(e),super.showBusy({isBusy:e,title:t,msg:i,localOnly:o,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(i=>{i.id==="btn-submit"||i.id==="btn-generate"||(i.disabled=e)})}};function ml(n,e,t){let i=`[${ml.name}]`;try{globalThis.ibgib||(globalThis.ibgib={dbName_hack:n.dbName,apiKeyName_hack:n.apiKeyName,storeName_hack:n.storeName}),globalThis.ibgib[e]||(globalThis.ibgib[e]={version:t,spaceShim:{},fnDefaultGetAPIKey:p(async()=>await Jt({dbName:n.dbName,storeName:n.storeName,key:n.apiKeyName})??"","fnDefaultGetAPIKey"),dbName_hack:n.dbName,apiKeyName_hack:n.apiKeyName,storeName_hack:n.storeName})}catch(o){throw console.error(`${i} ${y(o)}`),o}}p(ml,"initIbGibGlobalThis");function Zm(n,e,t){if(!globalThis.ibgib?.[n]){if(!e)throw new Error(`Global context not initialized and config not provided for key '${n}'.`);ml(e,n,t)}return globalThis.ibgib[n]}p(Zm,"getIbGibGlobalThis_IbGibApp");function ye(n){let e=p(async()=>D(),"fnGetMetaspace"),t=new Promise(async(i,o)=>{try{let s=1e5,a=0,c;do{if(n)c=Zm(n)?.bootstrapPromise;else if(c=globalThis.ibgib?.bootstrapPromise,!c&&globalThis.ibgib){let d=Object.keys(globalThis.ibgib);for(let u of d)if(globalThis.ibgib[u]?.bootstrapPromise){c=globalThis.ibgib[u].bootstrapPromise;break}}if(a++,a>s)break;await H(10)}while(c===void 0);if(!c){i();return}await c,i()}catch(s){o(s)}});return{fnGetMetaspace:e,bootstrapPromise:t}}p(ye,"getComponentCtorArg");var gl="ibgib-identity-header",ti=class extends ce{static{p(this,"IdentityHeaderComponentMeta")}lc="[IdentityHeaderComponentMeta]";routeRegExp=new RegExp(`^${gl}$`);componentName=gl;constructor(){super(ye()),customElements.get(this.componentName)||customElements.define(this.componentName,Wo)}async createInstance({path:e,ibGibAddr:t}){let i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:Os,css:[he,qs]}),i}},Wo=class extends Oe{static{p(this,"IdentityHeaderComponentInstance")}lc="[IdentityHeaderComponentInstance]";activeAddr=null;_onRequestIdentityChange=null;_onIdentityUpdateAvailable=null;_onIdentityChanged=null;_onDocumentClick=null;pendingUpdateDetail=null;keystoneCache=new Map;isDropdownLocked=!1;dropdownHideTimer=null;constructor(){super()}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let i=await D();if(!i)return{username:"",description:"",isPrimary:!1};let o=await i.getLocalUserSpace({lock:!1});if(!o)return{username:"",description:"",isPrimary:!1};try{let a=await new ee().getKeystoneCommonInfo({addr:e,metaspace:i,space:o}),c={username:a?.name??"",description:a?.description??"",isPrimary:a?.isPrimary??!1};return this.keystoneCache.set(e,c),c}catch{return{username:"",description:"",isPrimary:!1}}}async initialize(e){await super.initialize(e)}async created(){this.elements={},this.elements.containerEl=this.shadowRoot.getElementById("container"),this.elements.btnIdentityPillEl=this.shadowRoot.getElementById("btn-identity-pill"),this.elements.pillAuthContentEl=this.shadowRoot.getElementById("pill-auth-content"),this.elements.pillUnauthContentEl=this.shadowRoot.getElementById("pill-unauth-content"),this.elements.identityAvatarEl=this.shadowRoot.getElementById("identity-avatar"),this.elements.identityUsernameEl=this.shadowRoot.getElementById("identity-username"),this.elements.updateBadgeEl=this.shadowRoot.getElementById("update-badge"),this.elements.dropdownMenuEl=this.shadowRoot.getElementById("dropdown-menu"),this.elements.sectionUpdateEl=this.shadowRoot.getElementById("section-update"),this.elements.btnMenuUpdateIdentityEl=this.shadowRoot.getElementById("btn-menu-update-identity"),this.elements.updateNTextEl=this.shadowRoot.getElementById("update-n-text"),this.elements.sectionIdentitiesEl=this.shadowRoot.getElementById("section-identities"),this.elements.identitiesListEl=this.shadowRoot.getElementById("identities-list"),this.elements.sectionActionsEl=this.shadowRoot.getElementById("section-actions"),this.elements.btnMenuCreateAccountEl=this.shadowRoot.getElementById("btn-menu-create-account"),this.elements.btnMenuSignInEl=this.shadowRoot.getElementById("btn-menu-sign-in"),this.elements.btnMenuGoogleSsoEl=this.shadowRoot.getElementById("btn-menu-google-sso"),this.elements.btnMenuGithubSsoEl=this.shadowRoot.getElementById("btn-menu-github-sso"),this.elements.sectionSettingsEl=this.shadowRoot.getElementById("section-settings"),this.elements.btnMenuManageEl=this.shadowRoot.getElementById("btn-menu-manage"),this.elements.syncProgressModalEl=this.shadowRoot.getElementById("sync-progress-modal"),this.elements.syncModalSpinnerEl=this.shadowRoot.getElementById("sync-modal-spinner"),this.elements.syncModalTitleEl=this.shadowRoot.getElementById("sync-modal-title"),this.elements.syncModalMsgEl=this.shadowRoot.getElementById("sync-modal-msg"),this.elements.syncModalStatusEl=this.shadowRoot.getElementById("sync-modal-status"),this.elements.syncModalNTextEl=this.shadowRoot.getElementById("sync-modal-n-text"),this.elements.btnSyncModalCloseEl=this.shadowRoot.getElementById("btn-sync-modal-close"),this.elements.contentEl=this.elements.containerEl,this.initHandlers(),await this.loadKeystonesIndex(),this._onRequestIdentityChange=e=>this.handleRequestIdentityChange(e),this._onIdentityUpdateAvailable=e=>this.handleIdentityUpdateAvailable(e),this._onIdentityChanged=e=>this.handleIdentityChanged(e),this._onDocumentClick=e=>{let t=e.composedPath?e.composedPath():[];this.elements?.containerEl&&!t.includes(this.elements.containerEl)&&this.closeDropdown()},window.addEventListener(Pe,this._onRequestIdentityChange),window.addEventListener(St,this._onIdentityUpdateAvailable),window.addEventListener(ve,this._onIdentityChanged),document.addEventListener("click",this._onDocumentClick),await this.resolveActiveIdentity(),await this.renderUI()}async loadKeystonesIndex(){let e=`${this.lc}[loadKeystonesIndex]`;try{let t=await D();if(!t)return;let i=await t.getLocalUserSpace({lock:!1});if(!i)return;let o=await t.getSpecialIbGib({type:"keystones",space:i,initialize:!0});o&&(this.ibGibAddr=C({ibGib:o}),await this.loadIbGib(),await this.initSettings())}catch(t){console.error(`${e} ${y(t)}`)}}async disconnected(){this._onRequestIdentityChange&&window.removeEventListener(Pe,this._onRequestIdentityChange),this._onIdentityUpdateAvailable&&window.removeEventListener(St,this._onIdentityUpdateAvailable),this._onIdentityChanged&&window.removeEventListener(ve,this._onIdentityChanged),this._onDocumentClick&&document.removeEventListener("click",this._onDocumentClick)}closeDropdown(){this.dropdownHideTimer&&(clearTimeout(this.dropdownHideTimer),this.dropdownHideTimer=null),this.isDropdownLocked=!1,this.elements?.btnIdentityPillEl.classList.remove("locked"),this.elements?.dropdownMenuEl.classList.add("hidden")}initHandlers(){this.elements.containerEl.addEventListener("mouseenter",()=>{this.dropdownHideTimer&&(clearTimeout(this.dropdownHideTimer),this.dropdownHideTimer=null),this.elements.dropdownMenuEl.classList.remove("hidden")}),this.elements.containerEl.addEventListener("mouseleave",()=>{this.isDropdownLocked||(this.dropdownHideTimer=setTimeout(()=>{this.elements?.dropdownMenuEl.classList.add("hidden"),this.dropdownHideTimer=null},300))}),this.elements.btnIdentityPillEl.addEventListener("click",e=>{e.stopPropagation(),this.dropdownHideTimer&&(clearTimeout(this.dropdownHideTimer),this.dropdownHideTimer=null),this.isDropdownLocked=!this.isDropdownLocked,this.isDropdownLocked?(this.elements.btnIdentityPillEl.classList.add("locked"),this.elements.dropdownMenuEl.classList.remove("hidden")):(this.elements.btnIdentityPillEl.classList.remove("locked"),this.elements.dropdownMenuEl.classList.add("hidden"))}),this.elements.btnSyncModalCloseEl.addEventListener("click",e=>{e.stopPropagation(),this.elements?.syncProgressModalEl.classList.add("hidden")}),this.elements.btnMenuUpdateIdentityEl.addEventListener("click",async e=>{if(e.stopPropagation(),!this.activeAddr)return;let t=`${this.lc}[btnMenuUpdateIdentityEl.click]`;this.closeDropdown();let i=this.pendingUpdateDetail?.localN??0,o=this.pendingUpdateDetail?.serverN??0;this.elements&&(this.elements.syncModalSpinnerEl.textContent="\u{1F504}",this.elements.syncModalSpinnerEl.style.animation="spin-pulse 2s infinite ease-in-out",this.elements.syncModalTitleEl.textContent="Updating Identity Keystone...",this.elements.syncModalMsgEl.textContent="Fetching delta graph from server and fast-forwarding local space...",this.elements.syncModalNTextEl.textContent=`n: ${i} \u2794 ${o}`,this.elements.btnSyncModalCloseEl.classList.add("hidden"),this.elements.syncProgressModalEl.classList.remove("hidden"));try{await Le().updateActiveKeystone({activePrimaryAddr:this.activeAddr}),this.elements&&(this.elements.syncModalSpinnerEl.textContent="\u2705",this.elements.syncModalSpinnerEl.style.animation="none",this.elements.syncModalTitleEl.textContent="Identity Updated!",this.elements.syncModalMsgEl.textContent="Successfully fast-forwarded identity keystone.",this.elements.btnSyncModalCloseEl.textContent="Done",this.elements.btnSyncModalCloseEl.classList.remove("hidden")),this.pendingUpdateDetail=null,this.elements&&(this.elements.updateBadgeEl.classList.add("hidden"),this.elements.sectionUpdateEl.classList.add("hidden")),setTimeout(()=>{this.elements?.syncProgressModalEl.classList.add("hidden")},1500),window.dispatchEvent(new CustomEvent(ve,{detail:{activeIdentityAddr:this.activeAddr},bubbles:!0,composed:!0}))}catch(s){console.error(`${t} ${y(s)}`),this.elements&&(this.elements.syncModalSpinnerEl.textContent="\u274C",this.elements.syncModalSpinnerEl.style.animation="none",this.elements.syncModalTitleEl.textContent="Update Failed",this.elements.syncModalMsgEl.textContent=y(s),this.elements.btnSyncModalCloseEl.textContent="Close",this.elements.btnSyncModalCloseEl.classList.remove("hidden"))}}),this.elements.btnMenuCreateAccountEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown(),window.dispatchEvent(new CustomEvent(se,{detail:{action:"show-keystone-creator"},bubbles:!0,composed:!0}))}),this.elements.btnMenuSignInEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown(),window.dispatchEvent(new CustomEvent(se,{detail:{action:"show-add-device"},bubbles:!0,composed:!0}))}),this.elements.btnMenuGoogleSsoEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown()}),this.elements.btnMenuGithubSsoEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown()}),this.elements.btnMenuManageEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown(),this.navigateToManager()})}navigateToManager(){window.dispatchEvent(new CustomEvent(se,{detail:{action:"show-identity-manager"},bubbles:!0,composed:!0}))}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{let t=globalThis.ibgib??{};if(!this.settings){this.activeAddr=null,t.identity=void 0;return}let o=(await this.getSettings({settingsType:ne.general,useCase:"current"}))?.activeIdentityAddr,a=(this.ibGib?.rel8ns?.keystone??[]).map(async u=>{let f=await this.getKeystoneDetails(u);return{addr:u,isPrimary:f?.isPrimary??!1}}),d=(await Promise.all(a)).filter(u=>u.isPrimary).map(u=>u.addr);if(o&&d.includes(o)?this.activeAddr=o:d.length>0?this.activeAddr=d[0]:this.activeAddr=null,this.activeAddr){let u=await D();if(u){let f=await u.getLocalUserSpace({lock:!1});if(f){let h=await u.get({addr:this.activeAddr,space:f});if(h.success&&h.ibGibs&&h.ibGibs.length>0){let m=h.ibGibs[0],g,b=m.data?.delegates;if(b)for(let E of Object.keys(b)){let w=b[E];if(w.allowedVerbs?.includes("sync")){let v=await u.get({addr:w.delegateAddr,space:f});if(v.success&&v.ibGibs&&v.ibGibs.length>0){g=v.ibGibs[0];break}}}t.identity={domainIdentity:m,syncDelegateIdentity:g,tjpAddr:this.activeAddr}}}}}else t.identity=void 0}catch(t){console.error(`${e} ${y(t)}`),this.activeAddr=null}}async renderUI(){if(!this.elements)return;let e=this.ibGib?.rel8ns?.keystone??[];if(this.activeAddr){let i=this.activeAddr;this.elements.btnIdentityPillEl.classList.remove("unauth"),this.elements.pillAuthContentEl.classList.remove("hidden"),this.elements.pillUnauthContentEl.classList.add("hidden");let o=await this.getKeystoneDetails(i),s=o.username||i.substring(0,10)+"...";this.elements.identityUsernameEl.textContent=s;let a=o.username?o.username.charAt(0).toUpperCase():"I";this.elements.identityAvatarEl.textContent=a;let c=zt({ibGibAddr:i});this.elements.identityAvatarEl.style.backgroundColor=c.tjpColor||c.punctiliarColor,this.elements.identityAvatarEl.style.color=c.tjpColorContrast||c.punctiliarColorContrast}else this.elements.btnIdentityPillEl.classList.add("unauth"),this.elements.pillAuthContentEl.classList.add("hidden"),this.elements.pillUnauthContentEl.classList.remove("hidden");this.pendingUpdateDetail&&this.pendingUpdateDetail.hasUpdate&&(!this.pendingUpdateDetail.activePrimaryAddr||this.pendingUpdateDetail.activePrimaryAddr===this.activeAddr)?(this.elements.updateBadgeEl.classList.remove("hidden"),this.elements.sectionUpdateEl.classList.remove("hidden"),this.elements.updateNTextEl&&(this.elements.updateNTextEl.textContent=`n: ${this.pendingUpdateDetail.localN} \u2794 ${this.pendingUpdateDetail.serverN}`)):(this.elements.updateBadgeEl.classList.add("hidden"),this.elements.sectionUpdateEl.classList.add("hidden")),this.elements.identitiesListEl.innerHTML="";let t=[];for(let i of e){let o=await this.getKeystoneDetails(i);o.isPrimary&&t.push({addr:i,username:o.username||i.substring(0,10)+"..."})}if(t.length>0){this.elements.sectionIdentitiesEl.classList.remove("hidden");for(let i of t){let o=i.addr===this.activeAddr,s=document.createElement("button");s.className=`dropdown-item identity-item ${o?"active-identity":""}`,s.innerHTML=`
|
|
688
|
+
`: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{G&&console.log(`${e} complete.`)}}async connectedCallback_reconnectComponent(){let e=`${this.lc}[${this.connectedCallback_reconnectComponent.name}]`;try{G&&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{G&&console.log(`${e} complete.`)}}async disconnectedCallback(){let e=`${this.lc}[${this.disconnectedCallback.name}]`;try{G&&console.log(`${e} starting... (I: 6f3b25c23fb874b1ac513e8f0d1f4e25)`),await this.disconnected()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}}async attributeChangedCallback(e,t,i){let o=`${this.lc}[attributeChangedCallback]`;G&&console.log(`${o} starting... (I: 33cd68579171582166d25d8898640f25): ${e} ${t} => ${i}`),console.warn(`${o} nothing done in base class atow (W: 9eb93eb8fde7c0058c79cea841936a25)`)}async destroy(){let e=`${this.lc}[${this.destroy.name}]`;try{G&&console.log(`${e} starting... (I: 536989c9491b544105b6d01a688fbb25)`),await this.destroyed()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}}async destroyed(){let e=`${this.lc}[${this.destroyed.name}]`;try{G&&console.log(`${e} starting... (I: f34f3ca04b06b1e00ebe04df22331125)`)}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}return G&&console.log(`${e} does nothing in the base class. (I: d9437f962e0aec40d69ad6159e7b5725)`),Promise.resolve()}async loadIbGib(e){let t=`${this.lc}[${this.loadIbGib.name}]`;try{G&&console.log(`${t} starting... (I: 4dcb1b7a3d86f3415ca7224c07126925)`);let i=e?.getLatest??!1;if(this.ibGib){console.warn(`${t} this.ibGib already loaded. idempotently returning early without doing anything. (W: 15498d346a32e884acec108cb3c8ee25)`);return}if(xt({gib:H({ibGibAddr:this.ibGibAddr??Q}).gib})){G&&console.log(`${t} component loading primitive ibgib (I: 3349796ef6139c1e718c8626c7935625)`);return}let o=await this.getMetaspace(),s=await o.getLocalUserSpace({lock:!1});if(!s)throw new Error("(UNEXPECTED) local user space falsy? (E: bb093b7e9781064e8db9a4390b63bb25)");if(i){let h=await o.getLatestAddr({addr:this.ibGibAddr,space:s});h&&h!==this.ibGibAddr&&(this.ibGibAddr=h)}let a=await o.get({addrs:[this.ibGibAddr],space:s});if(!a.success||a.ibGibs?.length!==1)throw new Error(`couldn't get ibGib (${this.ibGibAddr}) in space (${s?.ib??"undefined"}) (E: 59c3461bebf3e0065df72bd1bd8dc125)`);let c=a.ibGibs.at(0),d=new Be;if(await d.initialized,!d.contextUpdated$)throw new Error("(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: 351dfc898d2c3da2d7928079cec14925)");if(d.contextUpdated$.subscribe(Me({next:p(async h=>{let m=`${t}[ibGibProxy.contextUpdated$][next]`;G&&console.log(`${m} nextIbGib: ${U(h)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleContextUpdated()},"next"),error:p(async h=>{debugger;console.error(`${t}[ibGibProxy.contextUpdated$][error] what up? ${y(h)}`)},"error")})),!d.newContextChild$)throw new Error("(UNEXPECTED) ibGibProxy.newContextChild$ falsy? (E: 2cbde5ab402cc6d81259c74d68bca725)");d.newContextChild$.subscribe(Me({next:p(async h=>{let m=`${t}[ibGibProxy.contextUpdated$][next]`;G&&console.log(`${m} childIbGib: ${U(h)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleNewContextChild({childIbGib:h})},"next"),error:p(async h=>{debugger;console.error(`${t}[ibGibProxy.contextUpdated$][error] what up? ${y(h)}`)},"error")}));let u=await d.witness(s),f=await d.witness(c);this.ibGibProxy=d,this.ibGibAddr=A({ibGib:d.ibGib})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{G&&console.log(`${t} complete.`)}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{let{ibGib:t}=this;this.ibGibAddr=t?A({ibGib:t}):Q,G&&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{G&&console.log(`${t} child added to contextcontext updated. childIbGib: ${U(e)} (I: 07d02c9182c6629cbbacd39fd0ff7f25)`),console.log(A({ibGib:e}))}catch(i){throw console.error(`${t} ${y(i)}`),i}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;try{if(G&&console.log(`${e} starting... (I: 7e5704afe17fb937c8473e7801f56e25)`),this.ibGib){let{punctiliarColor:t,punctiliarColorTranslucent:i,punctiliarColorContrast:o,tjpColor:s,tjpColorTranslucent:a,tjpColorContrast:c,errorMsg:d}=Yt({ibGib:this.ibGib,translucentAlpha:10});d?console.error(`${e} ${d} (E: 65e0d330d029c1fe39f3d6280dda3725)`):(this.style.setProperty("--ibgib-color",t),this.style.setProperty("--ibgib-color-translucent",i),this.style.setProperty("--ibgib-color-contrast",o),this.style.setProperty("--tjp-color",s??t),this.style.setProperty("--tjp-color-translucent",a??i),this.style.setProperty("--tjp-color-contrast",c??"lime"))}await this.renderUI_busy()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}}async renderUI_busy(){}async loadAgentsCoupledToIbGib({dontThrowIfNone:e}={}){let t=`${this.lc}[${this.loadAgentsCoupledToIbGib.name}]`;try{let i=await this.getMetaspace(),o=await i.getLocalUserSpace({lock:!1});if(!o)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 s=await Xo({ibGib:this.ibGib,metaspace:i,space:o});if(s){let a=s.data.n;await s.setActiveContext({contextIbGib:this.ibGib,loggingInfo:this.lc}),await O(32);let c=s.data.n;a!==c&&console.warn(`${t} setting active context for agent changed agent.data.n.
|
|
689
|
+
agent.data: ${U(z({ibGib:s}))}
|
|
690
|
+
ibGib.data: ${z({ibGib:this.ibGib})} (W: cb22e8b064d8c2d7b3b2c488ed169225)`),this.agents=[s]}else if(e)console.warn(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${A({ibGib:this.ibGib})}) (W: e4219903462baab438a23c786d714825)`);else throw new Error(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${A({ibGib:this.ibGib})}) (E: 7182d1aa070b9578c78a5b8b401d8425)`)}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{G&&console.log(`${t} complete.`)}}async getSettings({settingsType:e,useCase:t}){let i=`${this.lc}[${this.getSettings.name}]`;try{if(G&&console.log(`${i} 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 o=await oi({sectionName:await we({settingsType:e,useCase:t}),settingsIbGib:this.settings.ibGib});return o||G&&console.log(`${i} settingsSection does not exist. returning undefined. (I: 0462d83f5ae8049708274b88e9b0d825)`),o}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{G&&console.log(`${i} complete.`)}}async updateSettings({settingsType:e,useCase:t,newSectionInfo:i}){let o=`${this.lc}[${this.updateSettings.name}]`;try{G&&console.log(`${o} starting... (I: 80ce98cf386e0c04d30e8b15ac0f2925)`);let s=await we({settingsType:e,useCase:t}),a=await ut({timeline:this.settings.ibGib,metaspace:await this.getMetaspace(),mut8Opts:{dataToAddOrPatch:{sections:{[s]:i}}}});await O(100)}catch(s){throw console.error(`${o} ${y(s)}`),s}finally{G&&console.log(`${o} complete.`)}}async getCurrentSettings({settingsType:e}){let t=`${this.lc}[${this.getCurrentSettings.name}]`;try{if(G&&console.log(`${t} starting... (I: da0baee73e386089a8c059f83cc43825)`),!this.settings)return;let i=await we({settingsType:e,useCase:"current"});return oi({sectionName:i,settingsIbGib:this.settings.ibGib})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{G&&console.log(`${t} complete.`)}}async initSettings(){let e=`${this.lc}[${this.initSettings.name}]`;try{if(G&&console.log(`${e} starting... (I: acfee8787d32a6075442e2887a386a25)`),!this.ibGib)throw new Error("(UNEXPECTED) this.ibGib falsy? (E: 8ce2e73bea87b9330b131778a3981825)");let t=await this.getMetaspace(),i=await t.getLocalUserSpace({lock:!1});if(!i)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: f77ce7269a6f0d7ad8978349b4c6cd25)");if(xt({ibGib:this.ibGib})){console.error(`${e} this.ibGib is primitive, so what are we initializing settings for? (W: 9915089019b81c6935b32ae877095825)`);return}let o=await Zo({ibGib:this.ibGib}),s=await Xt({scope:o,ibGib:this.ibGib,metaspace:t,space:i});if(s||(s=(await jo({scope:o,metaspace:t,space:i,saveInSpace:!0})).newIbGib,await gi({scope:o,domainIbGib:this.ibGib,localIbGib:s,metaspace:t,space:i})),!s)throw new Error("(UNEXPECTED) settings falsy still? should be initialized. (E: a179adcbbab800cff849b8aa95fbe425)");let a=new Be;if(await a.setWrappedIbGib({ibGib:s,space:i}),this.settings=a,!await this.getCurrentSettings({settingsType:oe.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{G&&console.log(`${e} complete.`)}}async exportIbGib({ibGib:e,compress:t}){let i=`${this.lc}[${this.exportIbGib.name}]`;try{G&&console.log(`${i} starting... (I: 623d9463d919683be81f749821a95825)`);let o=await this.getMetaspace();if(!o)throw new Error("(UNEXPECTED) metaspace falsy? (E: 3d15dbd074ac0c15b834a788d0b57d25)");if(xt({ibGib:e}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let s=await o.getLocalUserSpace({lock:!1});if(!s)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: 7bb735be58282f1bd7abe5d9ffabb525)");await Gs({ibGib:e,compress:t,metaspace:o,space:s})}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{G&&console.log(`${i} complete.`)}}async importIbGib({exportIbGibJsonString:e,rel8nName:t,force:i,skipRegisterTimelines:o,divergentTimelineStrategy:s}){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,f]=await Rs({exportIbGibJsonString:e,metaspace:c});if(!u.data)throw new Error("(UNEXPECTED) rawExportIbGib.data falsy? this is assumed validated at this point. (E: 6bc4e84db08e3c6228b2c40c2ea50825)");let h=u.data.contextIbGibAddr,m=!1;if(!i){let g=await c.get({addr:h,space:d});g.success&&(g.ibGibs??[]).length===1&&(console.log(`${a} export's ibGib addr (${h}) already exists in the space, so we're skipping doing any physical importing of the export's graph. (I: 429b5bdcd0585c697869f568c4673825)`),m=!0)}if(!m){mi;let g=[],b=[];Object.values(f).forEach(x=>{fs({ibGib:x})?g.push(x):b.push(x)});let E=await c.put({ibGibs:g,isDna:!0,space:d,force:i});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:w,mapWithTjp_NoDna:v,mapWithoutTjps:I}=mi({ibGibs:b}),T=await c.put({ibGibs:Object.values(I),space:d,force:i});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={...w,...v},N=Object.values(C),S=await c.put({ibGibs:N,space:d,force:i});if(!S.success||S.errorMsg)throw new Error(`there was an error putting the export's timeline ibgibs into the space (${d.ib}). error: ${S.errorMsg||"[unknown error (E: be4a28961574765798c8d3686ae89c25)]"} (E: 066796a23da3c9f748558fd25bfdf525)`);if(!o){let x=Ye({ibGibs:N}),P=Object.values(x);for(let $ of P){let R=$.at(-1);if(!R)throw new Error("(UNEXPECTED) latestInTimeline falsy? this would mean that we had an empty timeline, and this doesn't make sense... (E: 3bec09e79768cc39d8029f4fe3af9825)");let L=await c.getLatestAddr({ibGib:R,space:d});!1||await c.registerNewIbGib({ibGib:R,space:d})}}}throw new Error("not implemented (E: 66c308e420e848c8d7cd01c8fddf8425)")}catch(c){throw console.error(`${a} ${y(c)}`),c}finally{G&&console.log(`${a} complete.`)}}},Vt=class extends Ke{static{p(this,"IbGibDynamicComponentInstanceBase_Parent")}childInfos=[];get activeChildInfo(){return this.childInfos.find(e=>e.active)}async activateIbGib({addr:e,ibGib:t}){let i=`${this.lc}[${this.activateIbGib.name}]`;try{let m=function(g){let b=H({ibGibAddr:g.addr}).gib;return(W({gib:b}).tjpGib??b)===h};var o=m;for(p(m,"tabInfoSharesTjpGib"),G&&console.log(`${i} starting... (I: 05015d78983488496dcca4fa36718725)`);!this.createdPromise;)await O(50);if(await this.createdPromise,!this.elements)throw new Error("(UNEXPECTED) this.elements falsy? (E: fa221c138f211ee93c717c9dd0cf3225)");let{contentEl:s}=this.elements;if(!t&&!e)throw new Error("(UNEXPECTED) both ibGib and addr falsy? (E: 529fb88738cdacb10aea87b8450f2525)");if(t&&e&&A({ibGib:t})!==e)throw new Error("(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: c99a94d8744e3a720cdbc094d53c4e25)");e??=A({ibGib:t});let a=await ae(),c=await this.getLoadedChildInfo({addr:e,ibGib:t});if(c.active){console.log(`${i} 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,s.innerHTML=""),c.childBtnEl.classList.add("active"),c.childBtnEl.scrollIntoView({behavior:"smooth"}),c.active=!0;let u=H({ibGibAddr:e}).gib,h=W({gib:u}).tjpGib??u;if(this.childInfos.some(g=>m(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:s,componentToInject:c.component})}catch(s){throw console.error(`${i} ${y(s)}`),s}finally{G&&console.log(`${i} complete.`)}}},si=class n extends Vt{static{p(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{G&&console.log(`${t} starting... (I: e0d5f8ed67b8a7f43822fa3843fd4525)`);let i=A({ibGib:e}),o=X({ibGib:e,defaultIfNone:"incomingAddr"});if(!o)throw new Error(`(UNEXPECTED) tjpAddr false after incomingAddr default? ibGib: ${U(e)} (E: 707988b4d22a27c1287aa5a815d88825)`);let s=await this.getLoadedChildInfo({addr:i,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: ${U(this.ibGib)} (E: ecea08dcacd198bb38cc44a860cc6825)`);if(!a.openChildTjpAddrs.includes(o))throw new Error(`${t} (UNEXPECTED) projectSettings didn't have the tjpAddr (${o})? projectSettings: ${U(a)} (E: genuuid)`);let c=a.openChildTjpAddrs.filter(g=>g!==o),d;if(a.activeChildTjpAddr===o)if(c.length>0){let g=a.openChildTjpAddrs.indexOf(o)-1;g<0&&(g=0),d=a.openChildTjpAddrs.at(g)}else d=this.tjpAddr,c.push(this.tjpAddr);let u=await we({settingsType:this.settingsType,useCase:"current"}),f={...a,openChildTjpAddrs:c},h=await this.getMetaspace(),m=await ut({timeline:this.settings.ibGib,metaspace:h,mut8Opts:{dataToAddOrPatch:{sections:{[u]:f}}}});s.active&&await this.activateIbGib({addr:d}),this.childInfos=this.childInfos.filter(g=>g.addr!==s.addr),await this.removeTabBtn({tabInfo:s})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{G&&console.log(`${t} complete.`)}}async reopenOldTabs(){let e=`${this.lc}[${this.reopenOldTabs.name}]`;try{G&&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 i;try{for(let o of t.openChildTjpAddrs)i=o,await this.activateIbGib({addr:o})}catch(o){throw console.error(`${e} error during activating child ibGib tabs. childTjpAddr: ${i??"[unset?]"} (E: 0396b2e24d08f42ac94510bb718a1725)`),o}finally{this.reloadingTabs=!1}await this.activateIbGib({addr:t.activeChildTjpAddr})}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{G&&console.log(`${e} complete.`)}}},Je=class extends Ke{static{p(this,"IbGibFormInstanceBase")}setLoading(e,t="#btn-submit, #btn-generate",i){if(!this.shadowRoot)return;let o=this.shadowRoot.querySelector(t);if(o)if(o.disabled=e,e)o.setAttribute("data-loading","true"),i&&(o.setAttribute("data-original-text",o.textContent||""),o.textContent=i);else{o.removeAttribute("data-loading");let s=o.getAttribute("data-original-text");s!==null&&(o.textContent=s,o.removeAttribute("data-original-text"))}}setStatus(e,t,i="status-area",o="status-text"){if(!this.shadowRoot)return;let s=this.shadowRoot.getElementById(i),a=this.shadowRoot.getElementById(o);a&&(a.textContent=e,a.className=`status-msg ${t}`),s&&(e?s.classList.remove("hidden"):s.classList.add("hidden"))}dispatchShellMessage(e,t){this.dispatchEvent(new CustomEvent(ne,{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 i=this.shadowRoot.querySelectorAll("input, select, textarea"),o=!0;for(let s of Array.from(i)){let a=s;if(!a.checkValidity()){o=!1,a.reportValidity();break}}return o}validateInputPattern({input:e,pattern:t,errorMessage:i,required:o=!0}){if(!e)return!0;let s=e.value.trim();if(!s&&!o)return e.classList.remove("invalid"),e.setCustomValidity(""),!0;let a=t.test(s);return a?(e.classList.remove("invalid"),e.setCustomValidity("")):(e.classList.add("invalid"),e.setCustomValidity(i),e.reportValidity()),a}showBusy({isBusy:e,title:t,msg:i,localOnly:o,submitBtnSelector:s,loadingText:a,animationEmoji:c}){let d=`${this.lc}[${this.showBusy.name}]`;try{this.setLoading(e,s,a),this.toggleAllInputsDisabled(e),super.showBusy({isBusy:e,title:t,msg:i,localOnly:o,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(i=>{i.id==="btn-submit"||i.id==="btn-generate"||(i.disabled=e)})}};function Tl(n,e,t){let i=`[${Tl.name}]`;try{globalThis.ibgib||(globalThis.ibgib={dbName_hack:n.dbName,apiKeyName_hack:n.apiKeyName,storeName_hack:n.storeName}),globalThis.ibgib[e]||(globalThis.ibgib[e]={version:t,spaceShim:{},fnDefaultGetAPIKey:p(async()=>await Zt({dbName:n.dbName,storeName:n.storeName,key:n.apiKeyName})??"","fnDefaultGetAPIKey"),dbName_hack:n.dbName,apiKeyName_hack:n.apiKeyName,storeName_hack:n.storeName})}catch(o){throw console.error(`${i} ${y(o)}`),o}}p(Tl,"initIbGibGlobalThis");function rg(n,e,t){if(!globalThis.ibgib?.[n]){if(!e)throw new Error(`Global context not initialized and config not provided for key '${n}'.`);Tl(e,n,t)}return globalThis.ibgib[n]}p(rg,"getIbGibGlobalThis_IbGibApp");function Ee(n){let e=p(async()=>M(),"fnGetMetaspace"),t=new Promise(async(i,o)=>{try{let s=1e5,a=0,c;do{if(n)c=rg(n)?.bootstrapPromise;else if(c=globalThis.ibgib?.bootstrapPromise,!c&&globalThis.ibgib){let d=Object.keys(globalThis.ibgib);for(let u of d)if(globalThis.ibgib[u]?.bootstrapPromise){c=globalThis.ibgib[u].bootstrapPromise;break}}if(a++,a>s)break;await O(10)}while(c===void 0);if(!c){i();return}await c,i()}catch(s){o(s)}});return{fnGetMetaspace:e,bootstrapPromise:t}}p(Ee,"getComponentCtorArg");var Cl="ibgib-identity-header",ri=class extends de{static{p(this,"IdentityHeaderComponentMeta")}lc="[IdentityHeaderComponentMeta]";routeRegExp=new RegExp(`^${Cl}$`);componentName=Cl;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,es)}async createInstance({path:e,ibGibAddr:t}){let i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:Zs,css:[me,Qs]}),i}},es=class extends Ke{static{p(this,"IdentityHeaderComponentInstance")}lc="[IdentityHeaderComponentInstance]";activeAddr=null;_onRequestIdentityChange=null;_onIdentityUpdateAvailable=null;_onIdentityChanged=null;_onDocumentClick=null;pendingUpdateDetail=null;keystoneCache=new Map;isDropdownLocked=!1;dropdownHideTimer=null;constructor(){super()}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let i=await M();if(!i)return{username:"",description:"",isPrimary:!1};let o=await i.getLocalUserSpace({lock:!1});if(!o)return{username:"",description:"",isPrimary:!1};try{let a=await new Z().getKeystoneCommonInfo({addr:e,metaspace:i,space:o}),c={username:a?.name??"",description:a?.description??"",isPrimary:a?.isPrimary??!1};return this.keystoneCache.set(e,c),c}catch(s){return console.error(`${this.lc}[getKeystoneDetails] Registered keystone address ${e} not found in local browser space: ${y(s)} (E: a123456789abcdef0123456789c0002)`),{username:"",description:"",isPrimary:!1}}}async initialize(e){await super.initialize(e)}async created(){this.elements={},this.elements.containerEl=this.shadowRoot.getElementById("container"),this.elements.btnIdentityPillEl=this.shadowRoot.getElementById("btn-identity-pill"),this.elements.pillAuthContentEl=this.shadowRoot.getElementById("pill-auth-content"),this.elements.pillUnauthContentEl=this.shadowRoot.getElementById("pill-unauth-content"),this.elements.identityAvatarEl=this.shadowRoot.getElementById("identity-avatar"),this.elements.identityUsernameEl=this.shadowRoot.getElementById("identity-username"),this.elements.updateBadgeEl=this.shadowRoot.getElementById("update-badge"),this.elements.dropdownMenuEl=this.shadowRoot.getElementById("dropdown-menu"),this.elements.sectionUpdateEl=this.shadowRoot.getElementById("section-update"),this.elements.btnMenuUpdateIdentityEl=this.shadowRoot.getElementById("btn-menu-update-identity"),this.elements.updateNTextEl=this.shadowRoot.getElementById("update-n-text"),this.elements.sectionIdentitiesEl=this.shadowRoot.getElementById("section-identities"),this.elements.identitiesListEl=this.shadowRoot.getElementById("identities-list"),this.elements.sectionActionsEl=this.shadowRoot.getElementById("section-actions"),this.elements.btnMenuCreateAccountEl=this.shadowRoot.getElementById("btn-menu-create-account"),this.elements.btnMenuSignInEl=this.shadowRoot.getElementById("btn-menu-sign-in"),this.elements.btnMenuGoogleSsoEl=this.shadowRoot.getElementById("btn-menu-google-sso"),this.elements.btnMenuGithubSsoEl=this.shadowRoot.getElementById("btn-menu-github-sso"),this.elements.sectionSettingsEl=this.shadowRoot.getElementById("section-settings"),this.elements.btnMenuManageEl=this.shadowRoot.getElementById("btn-menu-manage"),this.elements.syncProgressModalEl=this.shadowRoot.getElementById("sync-progress-modal"),this.elements.syncModalSpinnerEl=this.shadowRoot.getElementById("sync-modal-spinner"),this.elements.syncModalTitleEl=this.shadowRoot.getElementById("sync-modal-title"),this.elements.syncModalMsgEl=this.shadowRoot.getElementById("sync-modal-msg"),this.elements.syncModalStatusEl=this.shadowRoot.getElementById("sync-modal-status"),this.elements.syncModalNTextEl=this.shadowRoot.getElementById("sync-modal-n-text"),this.elements.btnSyncModalCloseEl=this.shadowRoot.getElementById("btn-sync-modal-close"),this.elements.contentEl=this.elements.containerEl,this.initHandlers(),await this.loadKeystonesIndex(),this._onRequestIdentityChange=e=>this.handleRequestIdentityChange(e),this._onIdentityUpdateAvailable=e=>this.handleIdentityUpdateAvailable(e),this._onIdentityChanged=e=>this.handleIdentityChanged(e),this._onDocumentClick=e=>{let t=e.composedPath?e.composedPath():[];this.elements?.containerEl&&!t.includes(this.elements.containerEl)&&this.closeDropdown()},window.addEventListener(Pe,this._onRequestIdentityChange),window.addEventListener($t,this._onIdentityUpdateAvailable),window.addEventListener(ve,this._onIdentityChanged),document.addEventListener("click",this._onDocumentClick),await this.resolveActiveIdentity(),await this.renderUI()}async loadKeystonesIndex(){let e=`${this.lc}[loadKeystonesIndex]`;try{let t=await M();if(!t)return;let i=await t.getLocalUserSpace({lock:!1});if(!i)return;let o=await t.getSpecialIbGib({type:"keystones",space:i,initialize:!0});o&&(this.ibGibAddr=A({ibGib:o}),await this.loadIbGib(),await this.initSettings())}catch(t){console.error(`${e} ${y(t)}`)}}async disconnected(){this._onRequestIdentityChange&&window.removeEventListener(Pe,this._onRequestIdentityChange),this._onIdentityUpdateAvailable&&window.removeEventListener($t,this._onIdentityUpdateAvailable),this._onIdentityChanged&&window.removeEventListener(ve,this._onIdentityChanged),this._onDocumentClick&&document.removeEventListener("click",this._onDocumentClick)}closeDropdown(){this.dropdownHideTimer&&(clearTimeout(this.dropdownHideTimer),this.dropdownHideTimer=null),this.isDropdownLocked=!1,this.elements?.btnIdentityPillEl.classList.remove("locked"),this.elements?.dropdownMenuEl.classList.add("hidden")}initHandlers(){this.elements.containerEl.addEventListener("mouseenter",()=>{this.dropdownHideTimer&&(clearTimeout(this.dropdownHideTimer),this.dropdownHideTimer=null),this.elements.dropdownMenuEl.classList.remove("hidden")}),this.elements.containerEl.addEventListener("mouseleave",()=>{this.isDropdownLocked||(this.dropdownHideTimer=setTimeout(()=>{this.elements?.dropdownMenuEl.classList.add("hidden"),this.dropdownHideTimer=null},300))}),this.elements.btnIdentityPillEl.addEventListener("click",e=>{e.stopPropagation(),this.dropdownHideTimer&&(clearTimeout(this.dropdownHideTimer),this.dropdownHideTimer=null),this.isDropdownLocked=!this.isDropdownLocked,this.isDropdownLocked?(this.elements.btnIdentityPillEl.classList.add("locked"),this.elements.dropdownMenuEl.classList.remove("hidden")):(this.elements.btnIdentityPillEl.classList.remove("locked"),this.elements.dropdownMenuEl.classList.add("hidden"))}),this.elements.btnSyncModalCloseEl.addEventListener("click",e=>{e.stopPropagation(),this.elements?.syncProgressModalEl.classList.add("hidden")}),this.elements.btnMenuUpdateIdentityEl.addEventListener("click",async e=>{if(e.stopPropagation(),!this.activeAddr)return;let t=`${this.lc}[btnMenuUpdateIdentityEl.click]`;this.closeDropdown();let i=this.pendingUpdateDetail?.localN??0,o=this.pendingUpdateDetail?.serverN??0;this.elements&&(this.elements.syncModalSpinnerEl.textContent="\u{1F504}",this.elements.syncModalSpinnerEl.style.animation="spin-pulse 2s infinite ease-in-out",this.elements.syncModalTitleEl.textContent="Updating Identity Keystone...",this.elements.syncModalMsgEl.textContent="Fetching delta graph from server and fast-forwarding local space...",this.elements.syncModalNTextEl.textContent=`n: ${i} \u2794 ${o}`,this.elements.btnSyncModalCloseEl.classList.add("hidden"),this.elements.syncProgressModalEl.classList.remove("hidden"));try{await Qe().updateActiveKeystone({activePrimaryAddr:this.activeAddr}),this.elements&&(this.elements.syncModalSpinnerEl.textContent="\u2705",this.elements.syncModalSpinnerEl.style.animation="none",this.elements.syncModalTitleEl.textContent="Identity Updated!",this.elements.syncModalMsgEl.textContent="Successfully fast-forwarded identity keystone.",this.elements.btnSyncModalCloseEl.textContent="Done",this.elements.btnSyncModalCloseEl.classList.remove("hidden")),this.pendingUpdateDetail=null,this.elements&&(this.elements.updateBadgeEl.classList.add("hidden"),this.elements.sectionUpdateEl.classList.add("hidden")),setTimeout(()=>{this.elements?.syncProgressModalEl.classList.add("hidden")},1500),window.dispatchEvent(new CustomEvent(ve,{detail:{activeIdentityAddr:this.activeAddr},bubbles:!0,composed:!0}))}catch(s){console.error(`${t} ${y(s)}`),this.elements&&(this.elements.syncModalSpinnerEl.textContent="\u274C",this.elements.syncModalSpinnerEl.style.animation="none",this.elements.syncModalTitleEl.textContent="Update Failed",this.elements.syncModalMsgEl.textContent=y(s),this.elements.btnSyncModalCloseEl.textContent="Close",this.elements.btnSyncModalCloseEl.classList.remove("hidden"))}}),this.elements.btnMenuCreateAccountEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown(),window.dispatchEvent(new CustomEvent(ne,{detail:{action:"show-keystone-creator"},bubbles:!0,composed:!0}))}),this.elements.btnMenuSignInEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown(),window.dispatchEvent(new CustomEvent(ne,{detail:{action:"show-add-device"},bubbles:!0,composed:!0}))}),this.elements.btnMenuGoogleSsoEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown()}),this.elements.btnMenuGithubSsoEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown()}),this.elements.btnMenuManageEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown(),this.navigateToManager()})}navigateToManager(){window.dispatchEvent(new CustomEvent(ne,{detail:{action:"show-identity-manager"},bubbles:!0,composed:!0}))}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{let t=globalThis.ibgib??{};if(!this.settings){this.activeAddr=null,t.identity=void 0;return}let o=(await this.getSettings({settingsType:oe.general,useCase:"current"}))?.activeIdentityAddr,a=(this.ibGib?.rel8ns?.keystone??[]).map(async u=>{let f=await this.getKeystoneDetails(u);return{addr:u,isPrimary:f?.isPrimary??!1}}),d=(await Promise.all(a)).filter(u=>u.isPrimary).map(u=>u.addr);if(o&&d.includes(o)?this.activeAddr=o:d.length>0?this.activeAddr=d[0]:this.activeAddr=null,this.activeAddr){let u=await M();if(u){let f=await u.getLocalUserSpace({lock:!1});if(f){let h=await u.get({addr:this.activeAddr,space:f});if(h.success&&h.ibGibs&&h.ibGibs.length>0){let m=h.ibGibs[0],g,b=m.data?.delegates;if(b)for(let E of Object.keys(b)){let w=b[E];if(w.allowedVerbs?.includes("sync")){let v=await u.get({addr:w.delegateAddr,space:f});if(v.success&&v.ibGibs&&v.ibGibs.length>0){g=v.ibGibs[0];break}}}t.identity={domainIdentity:m,syncDelegateIdentity:g,tjpAddr:this.activeAddr}}}}}else t.identity=void 0}catch(t){console.error(`${e} ${y(t)}`),this.activeAddr=null}}async renderUI(){if(!this.elements)return;let e=this.ibGib?.rel8ns?.keystone??[];if(this.activeAddr){let i=this.activeAddr;this.elements.btnIdentityPillEl.classList.remove("unauth"),this.elements.pillAuthContentEl.classList.remove("hidden"),this.elements.pillUnauthContentEl.classList.add("hidden");let o=await this.getKeystoneDetails(i),s=o.username||i.substring(0,10)+"...";this.elements.identityUsernameEl.textContent=s;let a=o.username?o.username.charAt(0).toUpperCase():"I";this.elements.identityAvatarEl.textContent=a;let c=Yt({ibGibAddr:i});this.elements.identityAvatarEl.style.backgroundColor=c.tjpColor||c.punctiliarColor,this.elements.identityAvatarEl.style.color=c.tjpColorContrast||c.punctiliarColorContrast}else this.elements.btnIdentityPillEl.classList.add("unauth"),this.elements.pillAuthContentEl.classList.add("hidden"),this.elements.pillUnauthContentEl.classList.remove("hidden");this.pendingUpdateDetail&&this.pendingUpdateDetail.hasUpdate&&(!this.pendingUpdateDetail.activePrimaryAddr||this.pendingUpdateDetail.activePrimaryAddr===this.activeAddr)?(this.elements.updateBadgeEl.classList.remove("hidden"),this.elements.sectionUpdateEl.classList.remove("hidden"),this.elements.updateNTextEl&&(this.elements.updateNTextEl.textContent=`n: ${this.pendingUpdateDetail.localN} \u2794 ${this.pendingUpdateDetail.serverN}`)):(this.elements.updateBadgeEl.classList.add("hidden"),this.elements.sectionUpdateEl.classList.add("hidden")),this.elements.identitiesListEl.innerHTML="";let t=[];for(let i of e){let o=await this.getKeystoneDetails(i);o.isPrimary&&t.push({addr:i,username:o.username||i.substring(0,10)+"..."})}if(t.length>0){this.elements.sectionIdentitiesEl.classList.remove("hidden");for(let i of t){let o=i.addr===this.activeAddr,s=document.createElement("button");s.className=`dropdown-item identity-item ${o?"active-identity":""}`,s.innerHTML=`
|
|
691
691
|
<span class="icon">${o?"\u{1F7E2}":"\u26AA"}</span>
|
|
692
692
|
<span class="identity-name">${i.username}</span>
|
|
693
693
|
${o?'<span class="identity-badge-active">Active</span>':""}
|
|
694
|
-
`,s.addEventListener("click",a=>{a.stopPropagation(),this.closeDropdown(),o||window.dispatchEvent(new CustomEvent(Pe,{detail:{activeIdentityAddr:i.addr},bubbles:!0,composed:!0}))}),this.elements.identitiesListEl.appendChild(s)}}else this.elements.sectionIdentitiesEl.classList.add("hidden")}handleIdentityUpdateAvailable(e){let t=e.detail;t&&(t.hasUpdate&&(!t.activePrimaryAddr||t.activePrimaryAddr===this.activeAddr)?(this.pendingUpdateDetail=t,this.elements&&(this.elements.updateBadgeEl?.classList.remove("hidden"),this.elements.sectionUpdateEl?.classList.remove("hidden"),this.elements.updateNTextEl&&(this.elements.updateNTextEl.textContent=`n: ${t.localN} \u2794 ${t.serverN}`))):(this.pendingUpdateDetail=null,this.elements&&(this.elements.updateBadgeEl?.classList.add("hidden"),this.elements.sectionUpdateEl?.classList.add("hidden"))))}async handleIdentityChanged(e){this.pendingUpdateDetail=null,this.elements&&(this.elements.updateBadgeEl?.classList.add("hidden"),this.elements.sectionUpdateEl?.classList.add("hidden")),await this.resolveActiveIdentity(),await this.renderUI()}async handleRequestIdentityChange(e){let t=`${this.lc}[handleRequestIdentityChange]`,i=e.detail?.activeIdentityAddr;if(i)try{if(!this.settings)return;let o=await this.getSettings({settingsType:
|
|
694
|
+
`,s.addEventListener("click",a=>{a.stopPropagation(),this.closeDropdown(),o||window.dispatchEvent(new CustomEvent(Pe,{detail:{activeIdentityAddr:i.addr},bubbles:!0,composed:!0}))}),this.elements.identitiesListEl.appendChild(s)}}else this.elements.sectionIdentitiesEl.classList.add("hidden")}handleIdentityUpdateAvailable(e){let t=e.detail;t&&(t.hasUpdate&&(!t.activePrimaryAddr||t.activePrimaryAddr===this.activeAddr)?(this.pendingUpdateDetail=t,this.elements&&(this.elements.updateBadgeEl?.classList.remove("hidden"),this.elements.sectionUpdateEl?.classList.remove("hidden"),this.elements.updateNTextEl&&(this.elements.updateNTextEl.textContent=`n: ${t.localN} \u2794 ${t.serverN}`))):(this.pendingUpdateDetail=null,this.elements&&(this.elements.updateBadgeEl?.classList.add("hidden"),this.elements.sectionUpdateEl?.classList.add("hidden"))))}async handleIdentityChanged(e){this.pendingUpdateDetail=null,this.elements&&(this.elements.updateBadgeEl?.classList.add("hidden"),this.elements.sectionUpdateEl?.classList.add("hidden")),await this.resolveActiveIdentity(),await this.renderUI()}async handleRequestIdentityChange(e){let t=`${this.lc}[handleRequestIdentityChange]`,i=e.detail?.activeIdentityAddr;if(i)try{if(!this.settings)return;let o=await this.getSettings({settingsType:oe.general,useCase:"current"})??{type:"general"};o.activeIdentityAddr=i,await this.updateSettings({settingsType:oe.general,useCase:"current",newSectionInfo:o}),await this.resolveActiveIdentity(),await this.renderUI(),window.dispatchEvent(new CustomEvent(ve,{detail:{activeIdentityAddr:i},bubbles:!0,composed:!0}))}catch(o){console.error(`${t} ${y(o)}`)}}async handleContextUpdated(){await this.renderUI()}};var _l=`:host {
|
|
695
695
|
display: block;
|
|
696
696
|
width: 100%;
|
|
697
697
|
max-width: 100%;
|
|
@@ -868,7 +868,7 @@ h2 {
|
|
|
868
868
|
|
|
869
869
|
.close-tab-button:hover {
|
|
870
870
|
color: var(--clr-danger, #ff5555) !important;
|
|
871
|
-
}`;var
|
|
871
|
+
}`;var Sl=`<div id="container" class="component-container">
|
|
872
872
|
<header id="identity-manager-header">
|
|
873
873
|
<h2 id="title">Identity Manager</h2>
|
|
874
874
|
<div class="tabs-row">
|
|
@@ -886,8 +886,8 @@ h2 {
|
|
|
886
886
|
<button id="btn-create-placeholder" class="action-btn">Create/Load Identity</button>
|
|
887
887
|
</div>
|
|
888
888
|
</div>
|
|
889
|
-
</div>`;var El="ibgib-identity-manager",ni=class extends ce{static{p(this,"IdentityManagerComponentMeta")}lc="[IdentityManagerComponentMeta]";routeRegExp=new RegExp(`^${El}$`);componentName=El;constructor(){super(ye()),customElements.get(this.componentName)||customElements.define(this.componentName,Xo)}async createInstance({path:e,ibGibAddr:t}){let i=`${this.lc}[${this.createInstance.name}]`,o=document.createElement(this.componentName);return await o.initialize({ibGibAddr:t,meta:this,html:yl,css:[he,bl]}),o}},Xo=class extends ei{static{p(this,"IdentityManagerComponentInstance")}lc="[IdentityManagerComponentInstance]";globalActiveAddr=null;_onIdentityChanged=null;_onUiMessage=null;keystoneCache=new Map;metaspace;get settingsType(){return ne.identityManager}constructor(){super()}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let i=await D();if(!i)return{username:"",description:"",isPrimary:!1,n:0};let o=await i.getLocalUserSpace({lock:!1});if(!o)return{username:"",description:"",isPrimary:!1,n:0};try{let a=await new ee().getKeystoneCommonInfo({addr:e,metaspace:i,space:o});if(a){let c={username:a.name,description:a.description,isPrimary:a.isPrimary,n:a.n};return this.keystoneCache.set(e,c),c}}catch(s){console.warn(`Error getting details for keystone ${e}: ${y(s)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async initialize(e){this.metaspace||(this.metaspace=await D({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=async t=>{if(this.globalActiveAddr=t.detail?.activeIdentityAddr||null,this.keystoneCache.clear(),await this.loadKeystonesIndex(),this.childInfos){for(let i of this.childInfos)if(i.component)try{let o=i.component;typeof o.loadIbGib=="function"&&await o.loadIbGib({getLatest:!0})}catch(o){console.warn(`[IdentityManager] Error reloading child component: ${y(o)}`)}}await this.renderUI()},window.addEventListener(ve,this._onIdentityChanged),this.addEventListener("ibgib-view-keystone-details",async t=>{let i=t.detail?.addr;i&&await this.activateIbGib({addr:i})}),this._onUiMessage&&window.removeEventListener(se,this._onUiMessage),this._onUiMessage=t=>{let i=t.detail?.action,o=t.detail?.subAction;i==="show-keystone-creator"||o==="show-keystone-creator"?this.handleAddNewIdentityFlow("ibgib-keystone-creator"):(i==="show-add-device"||o==="show-add-device")&&this.handleAddNewIdentityFlow("ibgib-add-device")},window.addEventListener(se,this._onUiMessage),this.ibGibAddr===W||!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(i=>{if(!i||i==="^"||i==="gib")return!1;let{gib:o}=q({ibGibAddr:i});return!!o&&o!=="gib"&&o!=="^"});if(t.length!==(e.openChildTjpAddrs??[]).length){e.openChildTjpAddrs=t;let i=await D();if(i){let o=await Ee({settingsType:this.settingsType,useCase:"current"});await at({timeline:this.settings.ibGib,metaspace:i,mut8Opts:{dataToAddOrPatch:{sections:{[o]:e}}}})}}}!e||(e.openChildTjpAddrs??[]).length===0?await this.loadDefaultPrimaryIdentityTabs():await this.reopenOldTabs()}async disconnected(){this._onIdentityChanged&&(window.removeEventListener(ve,this._onIdentityChanged),this._onIdentityChanged=null),this._onUiMessage&&(window.removeEventListener(se,this._onUiMessage),this._onUiMessage=null)}async loadKeystonesIndex(){let e=`${this.lc}[loadKeystonesIndex]`;try{let t=await D();if(!t)return;let i=await t.getLocalUserSpace({lock:!1});if(!i)return;let o=await t.getSpecialIbGib({type:"keystones",space:i,initialize:!0});o&&(this.ibGibAddr=C({ibGib:o}),await this.loadIbGib({getLatest:!0}),await this.initSettings())}catch(t){console.error(`${e} ${y(t)}`)}}initHandlers(){this.elements.btnAddIdentityEl.addEventListener("click",()=>this.handleAddNewIdentityFlow("ibgib-keystone-creator")),this.elements.btnCreatePlaceholderEl.addEventListener("click",()=>this.handleAddNewIdentityFlow("ibgib-keystone-creator")),this.elements.tabsListEl.addEventListener("wheel",e=>{e.deltaY!==0&&(e.preventDefault(),this.elements.tabsListEl.scrollBy({left:e.deltaY,behavior:"smooth"}))},{passive:!1})}async handleAddNewIdentityFlow(e="ibgib-keystone-creator"){let t=`${this.lc}[${this.handleAddNewIdentityFlow.name}]`;console.log(`${t} Triggering identity creation/import flow (${e})...`);try{let o=await(await re()).getComponentInstance({path:e,ibGibAddr:W,useRegExpPrefilter:!0});if(o){this.elements.noIdentityPlaceholderEl.classList.add("hidden");let s=this.elements.contentEl.querySelector("ibgib-keystone-creator");s&&s.remove();let a=this.elements.contentEl.querySelector("ibgib-add-device");a&&a.remove();let c=this.activeChildInfo;c&&(c.childBtnEl.classList.remove("active"),c.active=!1),this.elements.contentEl.innerHTML="",this.elements.contentEl.appendChild(o),console.log(`${t} Mounted ${e} successfully.`)}else throw new Error(`Could not find meta for ${e}`)}catch(i){console.error(`${t} ${y(i)}`)}}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{if(!this.settings){this.globalActiveAddr=null;return}let i=(await this.getSettings({settingsType:ne.general,useCase:"current"}))?.activeIdentityAddr,s=(this.ibGib?.rel8ns?.keystone??[]).map(async d=>{let u=await this.getKeystoneDetails(d);return{addr:d,isPrimary:u?.isPrimary??!1}}),c=(await Promise.all(s)).filter(d=>d.isPrimary).map(d=>d.addr);i&&c.includes(i)?this.globalActiveAddr=i: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 i of this.childInfos){let o=i.childBtnEl;o.className=`tab-btn ${i.active?"active":""} ${i.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}=q({ibGibAddr:a});return!!c&&c!=="gib"&&c!=="^"}).map(async a=>{let c=await this.getKeystoneDetails(a);return{addr:a,isPrimary:c?.isPrimary??!1}}),o=(await Promise.all(t)).filter(a=>a.isPrimary).map(a=>a.addr);if(o.length===0){this.elements.noIdentityPlaceholderEl.classList.remove("hidden");return}this.elements.noIdentityPlaceholderEl.classList.add("hidden"),this.reloadingTabs=!0;try{for(let a of o)await this.activateIbGib({addr:a})}finally{this.reloadingTabs=!1}let s=o.includes(this.globalActiveAddr||"")?this.globalActiveAddr:o[0];await this.activateIbGib({addr:s})}async activateIbGib({addr:e,ibGib:t}){let i=`${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(pi))throw new Error(`ibGib.ib (${t.ib}) does not start with keystone atom (${pi}) (E: e0df410381c8e569eb6da996e79b6826)`);if(this.elements.noIdentityPlaceholderEl.classList.add("hidden"),!this.reloadingTabs){let o=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(o){let s=!1,a=Q({ibGib:this.activeChildInfo.component?.ibGib||t,defaultIfNone:"incomingAddr"});if(a&&(o.openChildTjpAddrs.includes(a)||(o.openChildTjpAddrs.push(a),s=!0),o.activeChildTjpAddr!==a&&(o.activeChildTjpAddr=a,s=!0)),s){let c=await D();if(c){let d=await Ee({settingsType:this.settingsType,useCase:"current"});await at({timeline:this.settings.ibGib,metaspace:c,mut8Opts:{dataToAddOrPatch:{sections:{[d]:o}}}})}}}}await this.renderUI()}catch(o){console.error(`${i} ${y(o)}`)}}async getLoadedChildInfo({addr:e,ibGib:t}){let i=`${this.lc}[getLoadedChildInfo]`;try{if(!e)throw new Error("(UNEXPECTED) addr falsy?");if(e==="^"||e==="gib"||q({ibGibAddr:e}).gib==="^")throw new Error(`Cannot load child info for primitive address ${e}`);let o=z({ibGibAddr:e}).tjpGib??q({ibGibAddr:e}).gib,s=p(async()=>{let u=await(await re()).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=>(z({ibGibAddr:d.addr}).tjpGib??q({ibGibAddr:d.addr}).gib)===o);if(c.length>0){if(c.length!==1)throw new Error("(UNEXPECTED) filtered.length !== 1?");a=c[0],a.component||(a.component=await s())}else{let d=await s(),u=0;for(;!d.ibGib;)if(await H(100),u++,u>50){debugger;throw new Error("(UNEXPECTED) detailsComponent.ibGib falsy? didn't load? (E: de50689834124914f770520f1eccb826)")}t=d.ibGib,e=C({ibGib:t});let f=await this.addChild({addr:e,ibGib:t});a={addr:e,childBtnEl:f,component:d,active:!1},this.childInfos.push(a)}return a}catch(o){throw console.error(`${i} ${y(o)}`),o}}async addChild({addr:e,ibGib:t}){let i=`${this.lc}[addChild]`;try{if(e??=C({ibGib:t}),e==="^"||e==="gib"||q({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:o}=this.elements;e??=C({ibGib:t});let s=document.createElement("button");if(s.className="tab-btn",s.id=`identity-tab-button-${e}`,await this.updateTabTitleAndText({span:s,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",s.appendChild(c),c.addEventListener("click",async d=>{d.stopPropagation(),await this.closeTab({ibGib:t})})}return o.appendChild(s),s.addEventListener("click",async c=>{await this.activateIbGib({addr:e})}),s}catch(o){throw console.error(`${i} ${y(o)}`),o}}async updateTabTitleAndText({span:e,ibGib:t,addr:i}){let o=await this.getKeystoneDetails(i),s=o.username,a=16;if(s)s.length>a&&(s=s.substring(0,a-3)+"..."),e.textContent=s;else{let d=i;d.length>12&&(d=d.substring(0,5)+"..."+d.substring(d.length-4)),e.textContent=d}let c=[];if(o.username&&c.push(`User: ${o.username}`),o.description){let d=o.description.length>100?o.description.substring(0,97)+"...":o.description;c.push(`Desc: ${d}`)}c.push(`Addr: ${i}`),e.title=c.join(`
|
|
890
|
-
`)}async removeTabBtn({tabInfo:e}){this.elements.tabsListEl.removeChild(e.childBtnEl)}};var
|
|
889
|
+
</div>`;var Al="ibgib-identity-manager",ai=class extends de{static{p(this,"IdentityManagerComponentMeta")}lc="[IdentityManagerComponentMeta]";routeRegExp=new RegExp(`^${Al}$`);componentName=Al;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,ts)}async createInstance({path:e,ibGibAddr:t}){let i=`${this.lc}[${this.createInstance.name}]`,o=document.createElement(this.componentName);return await o.initialize({ibGibAddr:t,meta:this,html:Sl,css:[me,_l]}),o}},ts=class extends si{static{p(this,"IdentityManagerComponentInstance")}lc="[IdentityManagerComponentInstance]";globalActiveAddr=null;_onIdentityChanged=null;_onUiMessage=null;keystoneCache=new Map;metaspace;get settingsType(){return oe.identityManager}constructor(){super()}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let i=await M();if(!i)return{username:"",description:"",isPrimary:!1,n:0};let o=await i.getLocalUserSpace({lock:!1});if(!o)return{username:"",description:"",isPrimary:!1,n:0};try{let a=await new Z().getKeystoneCommonInfo({addr:e,metaspace:i,space:o});if(a){let c={username:a.name,description:a.description,isPrimary:a.isPrimary,n:a.n};return this.keystoneCache.set(e,c),c}}catch(s){console.warn(`Error getting details for keystone ${e}: ${y(s)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async initialize(e){this.metaspace||(this.metaspace=await M({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=async t=>{if(this.globalActiveAddr=t.detail?.activeIdentityAddr||null,this.keystoneCache.clear(),await this.loadKeystonesIndex(),this.childInfos){for(let i of this.childInfos)if(i.component)try{let o=i.component;typeof o.loadIbGib=="function"&&await o.loadIbGib({getLatest:!0})}catch(o){console.warn(`[IdentityManager] Error reloading child component: ${y(o)}`)}}await this.renderUI()},window.addEventListener(ve,this._onIdentityChanged),this.addEventListener("ibgib-view-keystone-details",async t=>{let i=t.detail?.addr;i&&await this.activateIbGib({addr:i})}),this._onUiMessage&&window.removeEventListener(ne,this._onUiMessage),this._onUiMessage=t=>{let i=t.detail?.action,o=t.detail?.subAction;i==="show-keystone-creator"||o==="show-keystone-creator"?this.handleAddNewIdentityFlow("ibgib-keystone-creator"):(i==="show-add-device"||o==="show-add-device")&&this.handleAddNewIdentityFlow("ibgib-add-device")},window.addEventListener(ne,this._onUiMessage),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(i=>{if(!i||i==="^"||i==="gib")return!1;let{gib:o}=H({ibGibAddr:i});return!!o&&o!=="gib"&&o!=="^"});if(t.length!==(e.openChildTjpAddrs??[]).length){e.openChildTjpAddrs=t;let i=await M();if(i){let o=await we({settingsType:this.settingsType,useCase:"current"});await ut({timeline:this.settings.ibGib,metaspace:i,mut8Opts:{dataToAddOrPatch:{sections:{[o]:e}}}})}}}!e||(e.openChildTjpAddrs??[]).length===0?await this.loadDefaultPrimaryIdentityTabs():await this.reopenOldTabs()}async disconnected(){this._onIdentityChanged&&(window.removeEventListener(ve,this._onIdentityChanged),this._onIdentityChanged=null),this._onUiMessage&&(window.removeEventListener(ne,this._onUiMessage),this._onUiMessage=null)}async loadKeystonesIndex(){let e=`${this.lc}[loadKeystonesIndex]`;try{let t=await M();if(!t)return;let i=await t.getLocalUserSpace({lock:!1});if(!i)return;let o=await t.getSpecialIbGib({type:"keystones",space:i,initialize:!0});o&&(this.ibGibAddr=A({ibGib:o}),await this.loadIbGib({getLatest:!0}),await this.initSettings())}catch(t){console.error(`${e} ${y(t)}`)}}initHandlers(){this.elements.btnAddIdentityEl.addEventListener("click",()=>this.handleAddNewIdentityFlow("ibgib-keystone-creator")),this.elements.btnCreatePlaceholderEl.addEventListener("click",()=>this.handleAddNewIdentityFlow("ibgib-keystone-creator")),this.elements.tabsListEl.addEventListener("wheel",e=>{e.deltaY!==0&&(e.preventDefault(),this.elements.tabsListEl.scrollBy({left:e.deltaY,behavior:"smooth"}))},{passive:!1})}async handleAddNewIdentityFlow(e="ibgib-keystone-creator"){let t=`${this.lc}[${this.handleAddNewIdentityFlow.name}]`;console.log(`${t} Triggering identity creation/import flow (${e})...`);try{let o=await(await ae()).getComponentInstance({path:e,ibGibAddr:Q,useRegExpPrefilter:!0});if(o){this.elements.noIdentityPlaceholderEl.classList.add("hidden");let s=this.elements.contentEl.querySelector("ibgib-keystone-creator");s&&s.remove();let a=this.elements.contentEl.querySelector("ibgib-add-device");a&&a.remove();let c=this.activeChildInfo;c&&(c.childBtnEl.classList.remove("active"),c.active=!1),this.elements.contentEl.innerHTML="",this.elements.contentEl.appendChild(o),console.log(`${t} Mounted ${e} successfully.`)}else throw new Error(`Could not find meta for ${e}`)}catch(i){console.error(`${t} ${y(i)}`)}}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{if(!this.settings){this.globalActiveAddr=null;return}let i=(await this.getSettings({settingsType:oe.general,useCase:"current"}))?.activeIdentityAddr,s=(this.ibGib?.rel8ns?.keystone??[]).map(async d=>{let u=await this.getKeystoneDetails(d);return{addr:d,isPrimary:u?.isPrimary??!1}}),c=(await Promise.all(s)).filter(d=>d.isPrimary).map(d=>d.addr);i&&c.includes(i)?this.globalActiveAddr=i: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 i of this.childInfos){let o=i.childBtnEl;o.className=`tab-btn ${i.active?"active":""} ${i.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}=H({ibGibAddr:a});return!!c&&c!=="gib"&&c!=="^"}).map(async a=>{let c=await this.getKeystoneDetails(a);return{addr:a,isPrimary:c?.isPrimary??!1}}),o=(await Promise.all(t)).filter(a=>a.isPrimary).map(a=>a.addr);if(o.length===0){this.elements.noIdentityPlaceholderEl.classList.remove("hidden");return}this.elements.noIdentityPlaceholderEl.classList.add("hidden"),this.reloadingTabs=!0;try{for(let a of o)await this.activateIbGib({addr:a})}finally{this.reloadingTabs=!1}let s=o.includes(this.globalActiveAddr||"")?this.globalActiveAddr:o[0];await this.activateIbGib({addr:s})}async activateIbGib({addr:e,ibGib:t}){let i=`${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(yi))throw new Error(`ibGib.ib (${t.ib}) does not start with keystone atom (${yi}) (E: e0df410381c8e569eb6da996e79b6826)`);if(this.elements.noIdentityPlaceholderEl.classList.add("hidden"),!this.reloadingTabs){let o=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(o){let s=!1,a=X({ibGib:this.activeChildInfo.component?.ibGib||t,defaultIfNone:"incomingAddr"});if(a&&(o.openChildTjpAddrs.includes(a)||(o.openChildTjpAddrs.push(a),s=!0),o.activeChildTjpAddr!==a&&(o.activeChildTjpAddr=a,s=!0)),s){let c=await M();if(c){let d=await we({settingsType:this.settingsType,useCase:"current"});await ut({timeline:this.settings.ibGib,metaspace:c,mut8Opts:{dataToAddOrPatch:{sections:{[d]:o}}}})}}}}await this.renderUI()}catch(o){console.error(`${i} ${y(o)}`)}}async getLoadedChildInfo({addr:e,ibGib:t}){let i=`${this.lc}[getLoadedChildInfo]`;try{if(!e)throw new Error("(UNEXPECTED) addr falsy?");if(e==="^"||e==="gib"||H({ibGibAddr:e}).gib==="^")throw new Error(`Cannot load child info for primitive address ${e}`);let o=W({ibGibAddr:e}).tjpGib??H({ibGibAddr:e}).gib,s=p(async()=>{let u=await(await ae()).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=>(W({ibGibAddr:d.addr}).tjpGib??H({ibGibAddr:d.addr}).gib)===o);if(c.length>0){if(c.length!==1)throw new Error("(UNEXPECTED) filtered.length !== 1?");a=c[0],a.component||(a.component=await s())}else{let d=await s(),u=0;for(;!d.ibGib;)if(await O(100),u++,u>50){debugger;throw new Error("(UNEXPECTED) detailsComponent.ibGib falsy? didn't load? (E: de50689834124914f770520f1eccb826)")}t=d.ibGib,e=A({ibGib:t});let f=await this.addChild({addr:e,ibGib:t});a={addr:e,childBtnEl:f,component:d,active:!1},this.childInfos.push(a)}return a}catch(o){throw console.error(`${i} ${y(o)}`),o}}async addChild({addr:e,ibGib:t}){let i=`${this.lc}[addChild]`;try{if(e??=A({ibGib:t}),e==="^"||e==="gib"||H({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:o}=this.elements;e??=A({ibGib:t});let s=document.createElement("button");if(s.className="tab-btn",s.id=`identity-tab-button-${e}`,await this.updateTabTitleAndText({span:s,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",s.appendChild(c),c.addEventListener("click",async d=>{d.stopPropagation(),await this.closeTab({ibGib:t})})}return o.appendChild(s),s.addEventListener("click",async c=>{await this.activateIbGib({addr:e})}),s}catch(o){throw console.error(`${i} ${y(o)}`),o}}async updateTabTitleAndText({span:e,ibGib:t,addr:i}){let o=await this.getKeystoneDetails(i),s=o.username,a=16;if(s)s.length>a&&(s=s.substring(0,a-3)+"..."),e.textContent=s;else{let d=i;d.length>12&&(d=d.substring(0,5)+"..."+d.substring(d.length-4)),e.textContent=d}let c=[];if(o.username&&c.push(`User: ${o.username}`),o.description){let d=o.description.length>100?o.description.substring(0,97)+"...":o.description;c.push(`Desc: ${d}`)}c.push(`Addr: ${i}`),e.title=c.join(`
|
|
890
|
+
`)}async removeTabBtn({tabInfo:e}){this.elements.tabsListEl.removeChild(e.childBtnEl)}};var xl=`:host {
|
|
891
891
|
display: block;
|
|
892
892
|
width: 100%;
|
|
893
893
|
margin: 1rem auto;
|
|
@@ -899,17 +899,105 @@ h2 {
|
|
|
899
899
|
color: var(--clr-accent, #50fa7b);
|
|
900
900
|
}
|
|
901
901
|
|
|
902
|
+
.mode-tabs {
|
|
903
|
+
display: flex;
|
|
904
|
+
gap: 0.5rem;
|
|
905
|
+
background: rgba(0, 0, 0, 0.25);
|
|
906
|
+
padding: 0.25rem;
|
|
907
|
+
border-radius: 10px;
|
|
908
|
+
border: 1px solid var(--clr-border, rgba(255, 255, 255, 0.1));
|
|
909
|
+
margin-bottom: 1rem;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
.mode-tab {
|
|
913
|
+
flex: 1;
|
|
914
|
+
padding: 0.6rem 0.75rem;
|
|
915
|
+
border: none;
|
|
916
|
+
border-radius: 8px;
|
|
917
|
+
background: transparent;
|
|
918
|
+
color: var(--clr-text-secondary, #a6adc8);
|
|
919
|
+
font-weight: 600;
|
|
920
|
+
font-size: 0.9rem;
|
|
921
|
+
cursor: pointer;
|
|
922
|
+
transition: all 0.2s ease;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
.mode-tab:hover {
|
|
926
|
+
color: var(--clr-text, #cdd6f4);
|
|
927
|
+
background: rgba(255, 255, 255, 0.05);
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
.mode-tab.active {
|
|
931
|
+
background: #45475a;
|
|
932
|
+
color: #89b4fa;
|
|
933
|
+
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
|
|
934
|
+
}
|
|
935
|
+
|
|
902
936
|
.subtitle {
|
|
903
937
|
color: var(--clr-text-secondary, #a6adc8);
|
|
904
|
-
font-size: 0.
|
|
938
|
+
font-size: 0.92rem;
|
|
905
939
|
margin: 0;
|
|
940
|
+
line-height: 1.45;
|
|
906
941
|
}
|
|
907
942
|
|
|
908
943
|
.content {
|
|
909
|
-
margin-top: 1.
|
|
944
|
+
margin-top: 1.25rem;
|
|
910
945
|
display: flex;
|
|
911
946
|
flex-direction: column;
|
|
912
|
-
gap: 1.
|
|
947
|
+
gap: 1.25rem;
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
.tab-panel.hidden, .hidden {
|
|
951
|
+
display: none !important;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
.sso-buttons {
|
|
955
|
+
display: flex;
|
|
956
|
+
flex-direction: column;
|
|
957
|
+
gap: 0.75rem;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
.sso-btn {
|
|
961
|
+
display: flex;
|
|
962
|
+
align-items: center;
|
|
963
|
+
justify-content: center;
|
|
964
|
+
gap: 0.75rem;
|
|
965
|
+
padding: 0.8rem 1.25rem;
|
|
966
|
+
border: 1px solid rgba(255, 255, 255, 0.15);
|
|
967
|
+
border-radius: 8px;
|
|
968
|
+
background: #1e1e2e;
|
|
969
|
+
color: #cdd6f4;
|
|
970
|
+
font-size: 0.95rem;
|
|
971
|
+
font-weight: 600;
|
|
972
|
+
cursor: pointer;
|
|
973
|
+
transition: transform 0.15s ease, background 0.15s ease;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
.sso-btn:hover {
|
|
977
|
+
transform: translateY(-1px);
|
|
978
|
+
background: #313244;
|
|
979
|
+
border-color: #89b4fa;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
.divider {
|
|
983
|
+
display: flex;
|
|
984
|
+
align-items: center;
|
|
985
|
+
text-align: center;
|
|
986
|
+
margin: 0.5rem 0;
|
|
987
|
+
color: #a6adc8;
|
|
988
|
+
font-size: 0.75rem;
|
|
989
|
+
font-weight: 700;
|
|
990
|
+
letter-spacing: 1px;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
.divider::before, .divider::after {
|
|
994
|
+
content: '';
|
|
995
|
+
flex: 1;
|
|
996
|
+
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
.divider span {
|
|
1000
|
+
padding: 0 0.75rem;
|
|
913
1001
|
}
|
|
914
1002
|
|
|
915
1003
|
.input-group {
|
|
@@ -923,8 +1011,25 @@ h2 {
|
|
|
923
1011
|
color: var(--clr-text-secondary, #a6adc8);
|
|
924
1012
|
}
|
|
925
1013
|
|
|
1014
|
+
.text-input {
|
|
1015
|
+
width: 100%;
|
|
1016
|
+
padding: 0.75rem 1rem;
|
|
1017
|
+
border-radius: 8px;
|
|
1018
|
+
border: 1px solid rgba(255, 255, 255, 0.15);
|
|
1019
|
+
background: #11111b;
|
|
1020
|
+
color: #cdd6f4;
|
|
1021
|
+
font-size: 0.95rem;
|
|
1022
|
+
box-sizing: border-box;
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
.text-input:focus {
|
|
1026
|
+
outline: none;
|
|
1027
|
+
border-color: #89b4fa;
|
|
1028
|
+
box-shadow: 0 0 0 2px rgba(137, 180, 250, 0.2);
|
|
1029
|
+
}
|
|
1030
|
+
|
|
926
1031
|
.action-row {
|
|
927
|
-
margin-top:
|
|
1032
|
+
margin-top: 0.5rem;
|
|
928
1033
|
width: 100%;
|
|
929
1034
|
}
|
|
930
1035
|
|
|
@@ -954,10 +1059,6 @@ h2 {
|
|
|
954
1059
|
margin-top: 0.5rem;
|
|
955
1060
|
}
|
|
956
1061
|
|
|
957
|
-
.status-area.hidden {
|
|
958
|
-
display: none;
|
|
959
|
-
}
|
|
960
|
-
|
|
961
1062
|
.result-area {
|
|
962
1063
|
padding: 1.5rem;
|
|
963
1064
|
background: rgba(255, 255, 255, 0.03);
|
|
@@ -966,7 +1067,6 @@ h2 {
|
|
|
966
1067
|
display: flex;
|
|
967
1068
|
flex-direction: column;
|
|
968
1069
|
gap: 0.75rem;
|
|
969
|
-
transition: opacity var(--t-med, 0.2s ease);
|
|
970
1070
|
}
|
|
971
1071
|
|
|
972
1072
|
.result-area.collapsed {
|
|
@@ -983,59 +1083,138 @@ h2 {
|
|
|
983
1083
|
font-size: 0.8rem;
|
|
984
1084
|
color: var(--clr-warn, #f38ba8);
|
|
985
1085
|
margin: 0.5rem 0 0;
|
|
986
|
-
}
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
<
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
<
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
<
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
</div>`;var Il={$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 Tl={$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 Cl={$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 _l={$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 Sl={$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 Al={$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 xl={$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 ot=class n{static{p(this,"KeystoneProfileBuilder")}_template;_username;_emails;_description;_details;_customizations={};constructor(e){this._template=JSON.parse(JSON.stringify(e))}static buildKeystone(e){let t;switch(e){case"high":t=Il;break;case"medium":t=Tl;break;case"low":t=Cl;break;case"session":t=_l;break;case"test":t=Sl;break;case"domain":t=Al;break;case"sync":t=xl;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._emails?this._emails.includes(e)||this._emails.push(e):this._emails=[e],this}withEmails(e){return this._emails=[...e],this}withDescription(e){return this._description=e,this}withDetails(e){return this._details=e,this}customizePool(e,t){let{behavior:i,...o}=t;return this._customizations[e]={template:o,behavior:i},this}getFrameDetails(){let e={...this._details};return this._username&&(e.username=this._username),this._emails&&this._emails.length>0&&(e.emails=[...this._emails]),this._description&&(e.description=this._description),e}async compileConfigs(){let e=[],t="";if(this._username||this._emails&&this._emails.length>0){let i=this._emails?.[0]??"",o=`${this._username||""}:${i}`;t=await Bt({s:o})}else t=await Bt({s:"default-keystone-salt"});for(let[i,o]of Object.entries(this._template.pools)){let s=this._customizations[o.id];s&&(s.template&&Object.assign(o,s.template),s.behavior&&o.behavior&&Object.assign(o.behavior,s.behavior));let a=`${t}-${o.id}`,c=await Bt({s:a}),d=Ms({template:o,salt:c});e.push(d)}return e}};var Nl="ibgib-keystone-creator",ii=class extends ce{static{p(this,"KeystoneCreatorComponentMeta")}lc="[KeystoneCreatorComponentMeta]";routeRegExp=new RegExp(`^${Nl}$`);componentName=Nl;constructor(){super(ye()),customElements.get(this.componentName)||customElements.define(this.componentName,Yo)}async createInstance({path:e,ibGibAddr:t}){let i=`${this.lc}[${this.createInstance.name}]`,o=document.createElement(this.componentName);return await o.initialize({ibGibAddr:t,meta:this,html:vl,css:[he,wl]}),o}},Yo=class extends ze{static{p(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.inputEmail=this.shadowRoot.getElementById("input-email"),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 i=await D(),o=await i.getLocalUserSpace({});if(o){let a=(await i.getSpecialIbGib({type:"keystones",space:o,initialize:!0}))?.rel8ns?.keystone??[];this.hasExistingIdentities=a.length>0}}catch(i){console.warn(`${e} Error checking existing identities: ${y(i)}`),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.shadowRoot.getElementById("btn-switch-sign-in")?.addEventListener("click",e=>{e.preventDefault(),window.dispatchEvent(new CustomEvent(se,{detail:{action:"show-add-device"},bubbles:!0,composed:!0}))}),this.elements.inputUsername.addEventListener("input",()=>{this.elements.inputUsername.classList.remove("invalid")}),this.elements.inputDescription.addEventListener("input",()=>{this.elements.inputDescription.classList.remove("invalid")}),this.elements.inputEmail.addEventListener("input",()=>{this.elements.inputEmail.classList.remove("invalid")}),this.elements.inputSecret.addEventListener("input",()=>{this.elements.inputSecret.classList.remove("invalid")})}setButtonLoading(e){let t=this.shadowRoot?.getElementById("btn-generate");t&&(t.disabled=e,t.textContent=e?"Generating...":"Generate Identity Keystone")}async handleGenerate(){let e=`${this.lc}[${this.handleGenerate.name}]`;try{console.log(`${e} starting genesis orchestration...`);let t=500;this.setStatus("Initializing genesis...","info");let i=this.elements.inputUsername.value.trim();if(this.elements.inputUsername.value=i,!this.validateInputPattern({input:this.elements.inputUsername,pattern:Wt,errorMessage:"Username must be 1-63 characters (alphanumeric, underscores, hyphens, dots).",required:!0})){this.setStatus("Invalid username. Must be 1-63 characters (alphanumeric, _, -, .).","error");return}let o=this.elements.inputDescription.value.trim();if(this.elements.inputDescription.value=o,!this.validateInputPattern({input:this.elements.inputDescription,pattern:Rs,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");return}let s=this.elements.inputEmail.value.trim();if(this.elements.inputEmail.value=s,s&&!Gs(s)){this.elements.inputEmail.classList.add("invalid"),this.setStatus("Invalid email address format.","error");return}let a=this.elements.inputSecret.value.trim();if(a)this.elements.inputSecret.classList.remove("invalid");else{this.elements.inputSecret.classList.add("invalid"),this.setStatus("Please enter a master secret.","error");return}if(this.setButtonLoading(!0),this.showBusy({isBusy:!0,title:"Checking Email Availability...",msg:"Checking server identity index...",animationEmoji:"\u{1F50D}"}),s){let P=await ue().checkEmailAvailability({email:s});if(!P.available){let x=P.message||"Email/Identity is already registered.";console.error(`${e} ${x}`),this.setStatus(x,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1);return}}this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Preparing configuration and policy options...",animationEmoji:"\u2699\uFE0F"});let c=ot.buildKeystone("domain").withUsername(i).withDescription(o);s&&c.withEmails([s]),c.withDetails({client:"space-gib-web",role:"domain-identity"});let d=await c.compileConfigs(),u=await D(),f=await u.getLocalUserSpace({});if(!f)throw new Error("No default space found in metaspace.");this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Generating cryptographic domain identity keys...",animationEmoji:"\u{1F511}"});let h=new ee,m=await h.genesis({masterSecret:a,emails:s?[s]:void 0,configs:d,metaspace:u,space:f,frameDetails:c.getFrameDetails(),isPrimary:!0}),g=C({ibGib:m});console.log(`${e} local genesis complete: ${g}`),await H(t),this.setStatus("Local genesis complete. Creating sync delegate...","info"),console.log(`\u2713 Local genesis complete: ${g}`),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Generating cryptographic sync delegate keys...",animationEmoji:"\u{1F511}"});let b=await Qt({masterSecret:a}),E=ot.buildKeystone("sync").withUsername(`${i}-sync`).withDescription(`Sync Delegate for ${i}`).withDetails({client:"space-gib-web",role:"sync-delegate"}),w=await E.compileConfigs(),v=await h.genesis({masterSecret:b,configs:w,metaspace:u,space:f,frameDetails:E.getFrameDetails()}),I=C({ibGib:v});console.log(`${e} sync delegate genesis complete: ${I}`),await H(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 T=await h.registerDelegate({parentKeystone:m,delegateKeystone:v,masterSecret:a,metaspace:u,space:f,allowedVerbs:[Xt,Yt]}),S=C({ibGib:T});console.log(`${e} delegate registered. evolved parent address: ${S}`),await H(t),console.log("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(`
|
|
1037
|
-
|
|
1038
|
-
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
input::placeholder {
|
|
1089
|
+
color: rgba(255, 255, 255, 0.35);
|
|
1090
|
+
opacity: 1;
|
|
1091
|
+
}`;var Nl=`<div id="container" class="component-container">
|
|
1092
|
+
<h2 id="title">Create Account</h2>
|
|
1093
|
+
|
|
1094
|
+
<!-- Mode Selector Tabs -->
|
|
1095
|
+
<div class="mode-tabs">
|
|
1096
|
+
<button id="tab-quick" class="mode-tab active">\u26A1 Quick (Passwordless)</button>
|
|
1097
|
+
<button id="tab-password" class="mode-tab">\u{1F511} Password-based</button>
|
|
1098
|
+
</div>
|
|
1099
|
+
|
|
1100
|
+
<!-- Mode Subtitles -->
|
|
1101
|
+
<p id="subtitle-quick" class="subtitle">\u26A1 Skip passwords \u2014 sign in with Google, GitHub, or an Email code. You can always set up a password later.</p>
|
|
1102
|
+
<p id="subtitle-password" class="subtitle hidden">\u{1F511} Full local ownership \u2014 your password never leaves your device. You can link Google or GitHub later.</p>
|
|
1103
|
+
|
|
1104
|
+
<div class="content">
|
|
1105
|
+
<!-- ----------------------------------------------------------------- -->
|
|
1106
|
+
<!-- Tab 1: Quick (Passwordless) Content -->
|
|
1107
|
+
<!-- ----------------------------------------------------------------- -->
|
|
1108
|
+
<div id="panel-quick" class="tab-panel">
|
|
1109
|
+
<div class="sso-buttons">
|
|
1110
|
+
<button id="btn-google-sso" class="sso-btn google-btn">
|
|
1111
|
+
<svg width="18" height="18" viewBox="0 0 24 24"><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"/><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"/><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"/><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"/></svg>
|
|
1112
|
+
Continue with Google
|
|
1113
|
+
</button>
|
|
1114
|
+
<button id="btn-github-sso" class="sso-btn github-btn">
|
|
1115
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/></svg>
|
|
1116
|
+
Continue with GitHub
|
|
1117
|
+
</button>
|
|
1118
|
+
</div>
|
|
1119
|
+
|
|
1120
|
+
<div class="divider">
|
|
1121
|
+
<span>OR USE EMAIL CODE</span>
|
|
1122
|
+
</div>
|
|
1123
|
+
|
|
1124
|
+
<div class="input-group">
|
|
1125
|
+
<div style="display: flex; align-items: center; gap: 0.4rem;">
|
|
1126
|
+
<label for="input-quick-email">Use custom email sign-in</label>
|
|
1127
|
+
<button id="btn-email-info" class="info-icon-btn" title="Learn about custom email sign-in" style="background: none; border: none; cursor: pointer; padding: 0; font-size: 0.9rem; line-height: 1;">\u2139\uFE0F</button>
|
|
1128
|
+
</div>
|
|
1129
|
+
<input type="email" id="input-quick-email" placeholder="Enter your email address..." class="text-input">
|
|
1130
|
+
</div>
|
|
1131
|
+
|
|
1132
|
+
<div class="action-row" style="margin-top: 0.75rem;">
|
|
1133
|
+
<button id="btn-quick-send-code" class="action-btn">Send 6-Digit Verification Code</button>
|
|
1134
|
+
</div>
|
|
1135
|
+
|
|
1136
|
+
<div id="section-quick-otp" class="input-group hidden" style="margin-top: 1.25rem; padding: 1rem; border: 1px dashed #89b4fa; border-radius: 8px; background: rgba(137, 180, 250, 0.05);">
|
|
1137
|
+
<label for="input-quick-otp" style="font-weight: bold; color: #89b4fa;">\u2709\uFE0F Enter 6-Digit Email Verification Code</label>
|
|
1138
|
+
<p style="font-size: 0.82rem; color: #a6adc8; margin-top: 0.25rem; margin-bottom: 0.75rem;">Check your email for your 6-digit verification code:</p>
|
|
1139
|
+
<div style="display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: center;">
|
|
1140
|
+
<input type="text" id="input-quick-otp" maxlength="6" placeholder="123456" class="text-input" style="font-family: monospace; font-size: 1.2rem; letter-spacing: 4px; text-align: center; max-width: 160px;">
|
|
1141
|
+
<button id="btn-quick-verify-code" class="action-btn" style="white-space: nowrap; width: auto;">Verify Code</button>
|
|
1142
|
+
</div>
|
|
1143
|
+
</div>
|
|
1144
|
+
</div>
|
|
1145
|
+
|
|
1146
|
+
<!-- ----------------------------------------------------------------- -->
|
|
1147
|
+
<!-- Tab 2: Password-based Content -->
|
|
1148
|
+
<!-- ----------------------------------------------------------------- -->
|
|
1149
|
+
<div id="panel-password" class="tab-panel hidden">
|
|
1150
|
+
<div class="input-group">
|
|
1151
|
+
<label for="input-username">Username</label>
|
|
1152
|
+
<input type="text" id="input-username" placeholder="Enter your username..." class="text-input">
|
|
1153
|
+
</div>
|
|
1154
|
+
|
|
1155
|
+
<div class="input-group">
|
|
1156
|
+
<label for="input-description">Description (Optional)</label>
|
|
1157
|
+
<input type="text" id="input-description" placeholder="Enter an optional description..." class="text-input">
|
|
1158
|
+
</div>
|
|
1159
|
+
|
|
1160
|
+
<div class="input-group">
|
|
1161
|
+
<label for="input-email">Primary Email (Optional)</label>
|
|
1162
|
+
<input type="email" id="input-email" placeholder="Enter your primary email address..." class="text-input">
|
|
1163
|
+
</div>
|
|
1164
|
+
|
|
1165
|
+
<div class="input-group">
|
|
1166
|
+
<label for="input-secret">Password (Keep this private!)</label>
|
|
1167
|
+
<input type="password" id="input-secret" placeholder="Enter your password..." class="secret-input text-input">
|
|
1168
|
+
</div>
|
|
1169
|
+
|
|
1170
|
+
<div class="checkbox-group" style="margin-top: 0.5rem; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem;">
|
|
1171
|
+
<input type="checkbox" id="checkbox-make-active" checked style="cursor: pointer; width: 1rem; height: 1rem;">
|
|
1172
|
+
<label for="checkbox-make-active" style="cursor: pointer; font-size: 0.9rem; user-select: none;">Make this the active identity</label>
|
|
1173
|
+
</div>
|
|
1174
|
+
|
|
1175
|
+
<div class="action-row">
|
|
1176
|
+
<button id="btn-generate" class="action-btn">Generate Identity Keystone</button>
|
|
1177
|
+
</div>
|
|
1178
|
+
</div>
|
|
1179
|
+
|
|
1180
|
+
<!-- ----------------------------------------------------------------- -->
|
|
1181
|
+
<!-- Status & Verification Areas -->
|
|
1182
|
+
<!-- ----------------------------------------------------------------- -->
|
|
1183
|
+
<div id="status-area" class="status-area hidden">
|
|
1184
|
+
<p id="status-text" class="status-msg"></p>
|
|
1185
|
+
</div>
|
|
1186
|
+
|
|
1187
|
+
<div id="section-code-verification" class="input-group hidden" style="margin-top: 1.5rem; padding: 1rem; border: 1px dashed #89b4fa; border-radius: 8px; background: rgba(137, 180, 250, 0.05);">
|
|
1188
|
+
<label for="input-verify-code" style="font-weight: bold; color: #89b4fa;">\u2709\uFE0F Enter 6-Digit Email Verification Code</label>
|
|
1189
|
+
<p style="font-size: 0.82rem; color: #a6adc8; margin-top: 0.25rem; margin-bottom: 0.75rem;">A 6-digit verification code was sent to your email. Enter it below to activate your identity:</p>
|
|
1190
|
+
<div style="display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: center;">
|
|
1191
|
+
<input type="text" id="input-verify-code" maxlength="6" placeholder="123456" class="text-input" style="font-family: monospace; font-size: 1.2rem; letter-spacing: 4px; text-align: center; max-width: 160px;">
|
|
1192
|
+
<button id="btn-submit-code" class="action-btn" style="white-space: nowrap;">Verify Code</button>
|
|
1193
|
+
<button id="btn-resend-code" class="action-btn" style="white-space: nowrap; background: #45475a; color: #cdd6f4;">Resend Code</button>
|
|
1194
|
+
</div>
|
|
1195
|
+
</div>
|
|
1196
|
+
|
|
1197
|
+
<div id="result-area" class="result-area collapsed">
|
|
1198
|
+
<h3>New Keystone Generated!</h3>
|
|
1199
|
+
<p class="address-label">Address:</p>
|
|
1200
|
+
<code id="keystone-addr" class="keystone-addr"></code>
|
|
1201
|
+
<p class="warning">\u26A0\uFE0F Store this address safely. It is your root identity for this space.</p>
|
|
1202
|
+
</div>
|
|
1203
|
+
|
|
1204
|
+
<div class="switch-workflow" style="margin-top: 1.2rem; text-align: center; font-size: 0.9rem; color: #a6adc8;">
|
|
1205
|
+
Already have a device paired? <button id="btn-switch-sign-in" class="link-btn" style="background: none; border: none; color: #89b4fa; font-weight: 600; cursor: pointer; text-decoration: underline; padding: 0; font-size: 0.9rem;">Pair New Device</button>
|
|
1206
|
+
</div>
|
|
1207
|
+
|
|
1208
|
+
<!-- Privacy Footer Note -->
|
|
1209
|
+
<div class="privacy-footer" style="margin-top: 1rem; text-align: center; font-size: 0.78rem; color: #a6adc8; line-height: 1.4;">
|
|
1210
|
+
\u2139\uFE0F Primary email addresses and identity keystones form part of the public graph for account discovery. Business data requires authorized sync delegates. Learn more in our <a id="link-privacy-policy" href="#privacy" style="color: #89b4fa; text-decoration: underline;">Privacy Policy</a>.
|
|
1211
|
+
</div>
|
|
1212
|
+
</div>
|
|
1213
|
+
</div>`;var $l={$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 Pl={$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 Rl={$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 Gl={$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 Ml={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Domain Identity Profile",securityLevel:"low"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"replace-all",selectSequentially:1,selectRandomly:1,targetBindingCount:2}}}};var kl={$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 Dl={$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:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-256",rounds:2,behavior:{size:10,replenish:"replace-all",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}}}};var Ue=class n{static{p(this,"KeystoneProfileBuilder")}_template;_username;_emails;_description;_details;_customizations={};constructor(e){this._template=JSON.parse(JSON.stringify(e))}static buildKeystone(e){if(e==="test")throw new Error("Security Violation: Keystone profile 'test' is prohibited when NODE_ENV=production. (E: 8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d)");let t;switch(e){case"high":t=$l;break;case"medium":t=Pl;break;case"low":t=Rl;break;case"session":t=Gl;break;case"test":t=Ml;break;case"domain":t=kl;break;case"sync":t=Dl;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._emails?this._emails.includes(e)||this._emails.push(e):this._emails=[e],this}withEmails(e){return this._emails=[...e],this}withDescription(e){return this._description=e,this}withDetails(e){return this._details=e,this}customizePool(e,t){let{behavior:i,...o}=t;return this._customizations[e]={template:o,behavior:i},this}getFrameDetails(){let e={...this._details};return this._username&&(e.username=this._username),this._emails&&this._emails.length>0&&(e.emails=[...this._emails]),this._description&&(e.description=this._description),e}async compileConfigs(){let e=[],t="";if(this._username||this._emails&&this._emails.length>0){let i=this._emails?.[0]??"",o=`${this._username||""}:${i}`;t=await lt({s:o})}else t=await lt({s:"default-keystone-salt"});for(let[i,o]of Object.entries(this._template.pools)){let s=this._customizations[o.id];s&&(s.template&&Object.assign(o,s.template),s.behavior&&o.behavior&&Object.assign(o.behavior,s.behavior));let a=`${t}-${o.id}`,c=await lt({s:a}),d=qs({template:o,salt:c});e.push(d)}return e}};var yg="ibgib_custodian_delegate_secret_";async function li({primaryTjpAddr:n}){let e=`[${li.name}]`;try{if(!n)throw new Error("primaryTjpAddr is required to derive local custodian delegate secret (E: a1b2c3d4e5f67890123456789a000101)");let t=`${yg}${n}`,i=localStorage.getItem(t);if(i)return i;let o=`${await Fe()}-${await Fe()}-${await Fe()}-${Date.now()}`,s=await lt({s:o,algorithm:ds.sha_512});return localStorage.setItem(t,s),s}catch(t){throw console.error(`${e} ${y(t)}`),t}}p(li,"deriveLocalCustodianDelegateSecret");async function qt({providerId:n,parentTjpAddr:e}){let t=`[${qt.name}]`;try{let o=await J().getSsoConfig();if(!o.success||!o.providers)return{success:!1,message:o.message||"SSO configuration retrieval failed."};let s=o.providers,a=Array.isArray(s)?s.find(m=>m.providerId===n):s[n];if(!a)return{success:!1,message:`SSO provider '${n}' is not configured on this server environment.`};let c=await Fe(),d={providerId:n,parentTjpAddr:e,userNonce:c},u=btoa(JSON.stringify(d)),f=a.authUrl;f.includes("client_id=")?f.includes("state=")||(f=`${f}&state=${encodeURIComponent(u)}`):f=`${f}?client_id=${a.clientId}&redirect_uri=${encodeURIComponent(a.redirectUri)}&response_type=code&scope=${encodeURIComponent(a.scope)}&state=${encodeURIComponent(u)}`;let h=window.open(f,"sso-oauth-popup","width=600,height=700,status=yes,toolbar=no,menubar=no,location=yes");return h?await new Promise(m=>{let g,b=p(E=>{if(E.origin!==window.location.origin)return;let w=E.data;w&&w.type==="sso-oauth-callback"&&(window.removeEventListener("message",b),clearInterval(g),m({success:!0,code:w.code,stateObj:w.stateObj||d,redirectUri:a.redirectUri}))},"messageListener");window.addEventListener("message",b),g=setInterval(()=>{h.closed&&(clearInterval(g),window.removeEventListener("message",b),m({success:!1,message:"Authentication cancelled (window closed)."}))},500)}):{success:!1,message:"Popup blocked by browser. Please enable popups for this site."}}catch(i){let o=y(i);return console.error(`${t} ${o}`),{success:!1,message:o}}}p(qt,"executeSsoOAuthPopup");var Ll="ibgib-keystone-creator",ci=class extends de{static{p(this,"KeystoneCreatorComponentMeta")}lc="[KeystoneCreatorComponentMeta]";routeRegExp=new RegExp(`^${Ll}$`);componentName=Ll;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,ns)}async createInstance({path:e,ibGibAddr:t}){let i=`${this.lc}[${this.createInstance.name}]`,o=document.createElement(this.componentName);return await o.initialize({ibGibAddr:t,meta:this,html:Nl,css:[me,xl]}),o}},ns=class extends Je{static{p(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.inputEmail=this.shadowRoot.getElementById("input-email"),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 i=await M(),o=await i.getLocalUserSpace({});if(o){let a=(await i.getSpecialIbGib({type:"keystones",space:o,initialize:!0}))?.rel8ns?.keystone??[];this.hasExistingIdentities=a.length>0}}catch(i){console.warn(`${e} Error checking existing identities: ${y(i)}`),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(){let e=this.shadowRoot?.getElementById("tab-quick"),t=this.shadowRoot?.getElementById("tab-password"),i=this.shadowRoot?.getElementById("panel-quick"),o=this.shadowRoot?.getElementById("panel-password"),s=this.shadowRoot?.getElementById("subtitle-quick"),a=this.shadowRoot?.getElementById("subtitle-password");e?.addEventListener("click",()=>{e.classList.add("active"),t?.classList.remove("active"),i?.classList.remove("hidden"),o?.classList.add("hidden"),s?.classList.remove("hidden"),a?.classList.add("hidden")}),t?.addEventListener("click",()=>{t.classList.add("active"),e?.classList.remove("active"),o?.classList.remove("hidden"),i?.classList.add("hidden"),a?.classList.remove("hidden"),s?.classList.add("hidden")}),this.shadowRoot?.getElementById("btn-google-sso")?.addEventListener("click",()=>this.handleSsoClick("google")),this.shadowRoot?.getElementById("btn-github-sso")?.addEventListener("click",()=>this.handleSsoClick("github")),this.shadowRoot?.getElementById("btn-email-info")?.addEventListener("click",E=>{E.preventDefault(),Ps({title:"Custom Email Sign-In",msg:`When you enter your email address, we dispatch a 6-digit one-time verification code to your inbox.
|
|
1214
|
+
|
|
1215
|
+
Entering the code creates your cryptographic identity delegate on your device and signs you in seamlessly without needing a password!`})});let f=this.shadowRoot?.getElementById("btn-quick-send-code"),h=this.shadowRoot?.getElementById("input-quick-email"),m=this.shadowRoot?.getElementById("section-quick-otp"),g=this.shadowRoot?.getElementById("input-quick-otp"),b=this.shadowRoot?.getElementById("btn-quick-verify-code");f?.addEventListener("click",()=>this.handleQuickSendCode()),b?.addEventListener("click",()=>this.handleQuickVerifyCode()),this.elements.btnGenerateEl.addEventListener("click",()=>this.handleGenerate()),this.shadowRoot.getElementById("btn-switch-sign-in")?.addEventListener("click",E=>{E.preventDefault(),window.dispatchEvent(new CustomEvent(ne,{detail:{action:"show-add-device"},bubbles:!0,composed:!0}))}),this.elements.inputUsername?.addEventListener("input",()=>{this.elements.inputUsername.classList.remove("invalid")}),this.elements.inputDescription?.addEventListener("input",()=>{this.elements.inputDescription.classList.remove("invalid")}),this.elements.inputEmail?.addEventListener("input",()=>{this.elements.inputEmail.classList.remove("invalid")}),this.elements.inputSecret?.addEventListener("input",()=>{this.elements.inputSecret.classList.remove("invalid")})}setButtonLoading(e){let t=this.shadowRoot?.getElementById("btn-generate");t&&(t.disabled=e,t.textContent=e?"Generating...":"Generate Identity Keystone")}async handleSsoClick(e){let t=`${this.lc}[${this.handleSsoClick.name}]`;this.setStatus(`Opening ${e.toUpperCase()} SSO authorization window...`,"info");let i=await qt({providerId:e});if(!i.success||!i.code){this.setStatus(i.message||`${e.toUpperCase()} sign-in cancelled.`,"error");return}this.setStatus(`Exchanging ${e.toUpperCase()} authorization code...`,"info");let o=J(),s=await o.postSsoLogin({code:i.code,providerId:e,redirectUri:i.redirectUri});if(!s.success||!s.primaryTjpAddr||!s.custodianReqs){this.setStatus(s.message||`${e.toUpperCase()} login failed.`,"error");return}let{primaryTjpAddr:a,custodianReqs:c}=s;this.setStatus("Deriving local device delegate keys...","info");let d=await li({primaryTjpAddr:a}),u=s.userInfo?.email||"",f=u?u.split("@")[0]:"user",h=Ue.buildKeystone("sync").withUsername(`${f}-sync`).withDescription(`Sync Delegate for ${f}`).withDetails({client:"space-gib-web",role:"sync-delegate",primaryTjpAddr:a,custodianReqs:c}),m=await h.compileConfigs(),g=await M(),b=await g.getLocalUserSpace({lock:!1});if(!b){this.setStatus("Could not access local user space.","error");return}let w=await new Z().genesis({masterSecret:d,configs:m,metaspace:g,space:b,frameDetails:h.getFrameDetails(),isPrimary:!1});this.setStatus("Registering device delegate with custodian server...","info");let v=await o.postCustodianRegisterDelegate({delegateKeystone:w});if(!v.success){this.setStatus(v.message||"Custodian delegate registration failed.","error");return}await this.finalizeIdentityOnboarding({primaryKeystone:v.evolvedPrimaryKeystone||s.primaryKeystone,primaryGraph:v.primaryGraph||s.primaryGraph,delegateKeystone:w,primaryTjpAddr:a,delegateSecret:d,makeActive:!0})}async handleQuickSendCode(){let e=`${this.lc}[${this.handleQuickSendCode.name}]`,t=this.shadowRoot?.getElementById("btn-quick-send-code"),i=this.shadowRoot?.getElementById("input-quick-email"),o=this.shadowRoot?.getElementById("section-quick-otp"),s=(i?.value||"").trim();if(!s||!Ei(s)){this.setStatus("Please enter a valid email address.","error");return}t&&(t.disabled=!0,t.textContent="Sending Verification Code..."),this.setStatus("Requesting verification code...","info");try{let a=await J().postVerificationCode({email:s});a.success?(o?.classList.remove("hidden"),this.setStatus("\u2709\uFE0F 6-digit verification code sent to your email!","success")):this.setStatus(a.message||"Failed to dispatch verification code.","error")}catch(a){let c=y(a);console.error(`${e} ${c}`),this.setStatus(`Failed to dispatch verification code: ${c}`,"error")}finally{t&&(t.disabled=!1,t.textContent="Send 6-Digit Verification Code")}}async handleQuickVerifyCode(){let e=`${this.lc}[${this.handleQuickVerifyCode.name}]`,t=this.shadowRoot?.getElementById("input-quick-email"),i=this.shadowRoot?.getElementById("input-quick-otp"),o=this.shadowRoot?.getElementById("btn-quick-verify-code"),s=(t?.value||"").trim(),a=(i?.value||"").trim();if(!a||a.length!==6||!/^\d{6}$/.test(a)){this.setStatus("Please enter a valid 6-digit verification code.","error");return}o&&(o.disabled=!0,o.textContent="Verifying..."),this.setStatus("Verifying code & completing onboarding...","info"),this.showBusy({isBusy:!0,title:"Verifying Code...",msg:`Great! Juust a moment...
|
|
1216
|
+
(Validating code, promoting server domain space, other security stuff...)`,animationEmoji:"\u{1F510}"});try{let c=await J().postCustodianGenesis({email:s,code:a});if(!c.success||!c.primaryTjpAddr||!c.custodianReqs){this.setStatus(c.message||"Custodian verification failed.","error");return}let d=c.primaryTjpAddr,u=c.custodianReqs;this.setStatus("Constructing local sync delegate...","info"),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Generating cryptographic sync delegate keys...",animationEmoji:"\u{1F511}"});let f=await li({primaryTjpAddr:d}),h=s.split("@")[0],m=Ue.buildKeystone("sync").withUsername(`${h}-sync`).withDescription(`Sync Delegate for ${h}`).withDetails({client:"space-gib-web",role:"sync-delegate",primaryTjpAddr:d,custodianReqs:u}),g=await m.compileConfigs(),b=await M(),E=await b.getLocalUserSpace({lock:!1});if(!E){this.setStatus("Failed to access local user space.","error");return}let v=await new Z().genesis({masterSecret:f,configs:g,metaspace:b,space:E,frameDetails:m.getFrameDetails(),isPrimary:!1});this.setStatus("Registering device delegate with custodian server...","info"),this.showBusy({isBusy:!0,title:"Registering Delegate...",msg:"Registering local delegate with custodian server...",animationEmoji:"\u{1F4DD}"});let I=await J().postCustodianRegisterDelegate({delegateKeystone:v});if(!I.success){this.setStatus(I.message||"Failed to register delegate with custodian server.","error");return}await this.finalizeIdentityOnboarding({primaryKeystone:I.evolvedPrimaryKeystone||c.primaryKeystone,primaryGraph:I.primaryGraph||c.primaryGraph,delegateKeystone:v,primaryTjpAddr:d,delegateSecret:f,makeActive:!0})}catch(c){let d=y(c);console.error(`${e} ${d}`,c),this.setStatus(`Error: ${d}`,"error")}finally{this.showBusy({isBusy:!1}),o&&(o.disabled=!1,o.textContent="Verify Code")}}async handleGenerate(){let e=`${this.lc}[${this.handleGenerate.name}]`;try{console.log(`${e} starting genesis orchestration...`);let t=500;this.setStatus("Initializing genesis...","info");let i=this.elements.inputUsername.value.trim();if(this.elements.inputUsername.value=i,!this.validateInputPattern({input:this.elements.inputUsername,pattern:jt,errorMessage:"Username must be 1-63 characters (alphanumeric, underscores, hyphens, dots).",required:!0})){this.setStatus("Invalid username. Must be 1-63 characters (alphanumeric, _, -, .).","error");return}let o=this.elements.inputDescription.value.trim();if(this.elements.inputDescription.value=o,!this.validateInputPattern({input:this.elements.inputDescription,pattern:Vs,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");return}let s=this.elements.inputEmail.value.trim();if(this.elements.inputEmail.value=s,s&&!Ei(s)){this.elements.inputEmail.classList.add("invalid"),this.setStatus("Invalid email address format.","error");return}let a=this.elements.inputSecret.value.trim();if(a)this.elements.inputSecret.classList.remove("invalid");else{this.elements.inputSecret.classList.add("invalid"),this.setStatus("Please enter a master secret.","error");return}if(this.setButtonLoading(!0),this.showBusy({isBusy:!0,title:"Checking Email Availability...",msg:"Checking server identity index...",animationEmoji:"\u{1F50D}"}),s){let R=await J().checkEmailAvailability({email:s});if(!R.available){let L=R.message||"Email/Identity is already registered.";console.error(`${e} ${L}`),this.setStatus(L,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1);return}}this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Preparing configuration and policy options...",animationEmoji:"\u2699\uFE0F"});let c=!0,d="domain".toLowerCase(),u=c&&d==="test"?"domain":d;console.log(`${e} Using keystone policy profile '${u}' (I: 90123456789abcdef0123456789abcde)`);let f=Ue.buildKeystone(u).withUsername(i).withDescription(o);s&&f.withEmails([s]),f.withDetails({client:"space-gib-web",role:"domain-identity"});let h=await f.compileConfigs(),m=await M(),g=await m.getLocalUserSpace({});if(!g)throw new Error("No default space found in metaspace.");this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Generating cryptographic domain identity keys...",animationEmoji:"\u{1F511}"});let b=new Z,E=await b.genesis({masterSecret:a,emails:s?[s]:void 0,configs:h,metaspace:m,space:g,frameDetails:f.getFrameDetails(),isPrimary:!0}),w=X({ibGib:E,defaultIfNone:"incomingAddr"});console.log(`${e} local genesis complete: ${w}`),await O(t),this.setStatus("Local genesis complete. Creating sync delegate...","info"),console.log(`\u2713 Local genesis complete: ${w}`),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Generating cryptographic sync delegate keys...",animationEmoji:"\u{1F511}"});let v=await nn({masterSecret:a}),I=Ue.buildKeystone(u).withUsername(`${i}-sync`).withDescription(`Sync Delegate for ${i}`).withDetails({client:"space-gib-web",role:"sync-delegate",primaryTjpAddr:w}),T=await I.compileConfigs(),C=await b.genesis({masterSecret:v,configs:T,metaspace:m,space:g,frameDetails:I.getFrameDetails()}),N=A({ibGib:C});console.log(`${e} sync delegate genesis complete: ${N}`),await O(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 S=await b.registerDelegate({parentKeystone:E,delegateKeystone:C,masterSecret:a,metaspace:m,space:g,allowedVerbs:[en,tn]}),x=A({ibGib:S});console.log(`${e} delegate registered. evolved parent address: ${x}`),await O(t),this.setStatus("Syncing genesis keystone to server...","info"),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Staging pending genesis keystone on server...",animationEmoji:"\u{1F504}"});let P=await J().postGenesisKeystone(E);if(!P.success){let R=`Sync failed: ${P.message}`;console.error(`${e} ${R}`),this.setStatus(R,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1);return}if(P.pending||P.statusCode===202){if(console.log(`${e} Genesis keystone quarantined in pending staging area. Prompting for 6-digit verification code.`),this.showBusy({isBusy:!1}),this.setFormDisabled(!0),!this.shadowRoot)throw new Error("(UNEXPECTED) this.shadowRoot falsy? (E: 6d316f5a2bf8e6a0286306468d35c826)");let R=Pt(this.shadowRoot,"section-code-verification"),L=Pt(this.shadowRoot,"input-verify-code"),Y=Pt(this.shadowRoot,"btn-submit-code"),V=Pt(this.shadowRoot,"btn-resend-code");R.classList.remove("hidden"),R.scrollIntoView({behavior:"smooth",block:"nearest"}),this.setStatus("\u2709\uFE0F Verification code sent to your email. Enter 6-digit code below:","info");let he=p(async()=>{V.disabled=!0,V.textContent="Sending...",this.setStatus("Resending verification code to your email...","info");let Ge=await J().postVerificationCode({email:s,primaryTjpAddr:w});Ge.success?this.setStatus("\u2709\uFE0F New verification code sent to your email!","success"):this.setStatus(Ge.message||"Failed to resend verification code.","error"),V.disabled=!1,V.textContent="Resend Code"},"onResendCode");V.addEventListener("click",he),await new Promise((Ge,$e)=>{let at=p(async()=>{let Ht=L.value.trim();if(!Ht||Ht.length!==6||!/^\d{6}$/.test(Ht)){this.setStatus("Please enter a valid 6-digit numeric verification code (e.g. 482901).","error");return}Y.disabled=!0,Y.textContent="Verifying...",this.showBusy({isBusy:!0,title:"Verifying & Activating...",msg:`Great! Juust a moment...
|
|
1217
|
+
(Validating code, promoting server domain space, other security stuff...)`,animationEmoji:"\u{1F510}"});let ls=await J().postVerifyCode({email:s,primaryTjpAddr:w,code:Ht});if(!ls.success){this.showBusy({isBusy:!1}),this.setStatus(ls.message||"Incorrect verification code.","error"),Y.disabled=!1,Y.textContent="Verify Code";return}console.log(`${e} Code verified & server domain promoted! Syncing delegate...`),this.showBusy({isBusy:!0,title:"Syncing Delegate...",msg:"Posting evolved domain identity and sync delegate to server...",animationEmoji:"\u26A1"}),Y.removeEventListener("click",at),R.classList.add("hidden"),this.setFormDisabled(!1);let cs=await J().putEvolveKeystone({domainAddr:w,keystoneIbGib:S,relatedKeystoneIbGibs:[C]});cs.success||console.warn(`${e} Delegate sync warning after code verification: ${cs.message}`),Ge()},"onSubmitCode");Y.addEventListener("click",at)})}else{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 R=await J().putEvolveKeystone({domainAddr:w,keystoneIbGib:S,relatedKeystoneIbGibs:[C]});if(!R.success){let L=`Delegate registration sync failed: ${R.message}`;console.error(`${e} ${L}`),this.setStatus(L,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1);return}}await this.finalizeIdentityOnboarding({primaryKeystone:S,delegateKeystone:C,primaryTjpAddr:x,masterSecret:a,delegateSecret:v,makeActive:this.elements.checkboxMakeActive?.checked??!0})}catch(t){let i=y(t);console.error(`${e} ${i}`,t),this.setStatus(`Error: ${i}`,"error")}finally{this.showBusy({isBusy:!1,submitBtnSelector:"#btn-generate"}),this.setButtonLoading(!1)}}async finalizeIdentityOnboarding({primaryKeystone:e,primaryGraph:t,delegateKeystone:i,primaryTjpAddr:o,masterSecret:s,delegateSecret:a,makeActive:c=!0}){let d=`${this.lc}[${this.finalizeIdentityOnboarding.name}]`,u=500,f=await M();if(!f)throw new Error("(UNEXPECTED) metaspace falsy? Expected active global metaspace instance. (E: 2e37a8b6fe987449c5d8693a7d4a2827)");let h=await f.getLocalUserSpace({});if(!h)throw new Error("(UNEXPECTED) space falsy? Expected valid default local user space from metaspace. (E: 1e37a8b6fe987449c5d8693a7d4a2826)");if(t){let E=Object.values(t);for(let w of E)await f.put({ibGibs:[w],space:h}),await f.registerNewIbGib({ibGib:w,space:h})}else e&&(await f.put({ibGibs:[e],space:h}),await f.registerNewIbGib({ibGib:e,space:h}));let m=new Z;try{await m.getLatestKeystone({addr:o,metaspace:f,space:h})}catch(E){let w=`Primary identity keystone ${o} not found in local browser space! Error: ${y(E)}`;throw console.error(`${d} ${w} (E: a123456789abcdef0123456789c0001)`),new Error(w)}this.showBusy({isBusy:!0,title:"Registering Identity...",msg:"Updating local identity indexes and scope settings...",animationEmoji:"\u{1F4BE}"});let g=[z({ibGib:i})];if(!e&&!t)throw new Error("(UNEXPECTED) primaryKeystone and primaryGraph both falsy? We should have gotten this back from the server. (E: e34cd882ac66633c75c53318a3b28826)");if(!i)throw new Error("(UNEXPECTED) delegateKeystone falsy? We should have made this locally and even registered it with the server. (E: 56b1c396269e15f008b7e298c71bc826)");e&&g.unshift(z({ibGib:e})),await ue({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:g}],metaspace:f,space:h}),s&&(window.dev_domainI=e,window.dev_domainIMasterSecret=s,window.dev_syncDelegate=i,window.dev_syncDelegateSecret=a),c&&window.dispatchEvent(new CustomEvent(Pe,{detail:{activeIdentityAddr:o},bubbles:!0,composed:!0}));let b="Identity successfully created and activated!";this.showBusy({isBusy:!0,title:"Success!",msg:b,animationEmoji:"\u2705"}),await O(u),this.elements?.keystoneAddrEl&&(this.elements.keystoneAddrEl.textContent=o),this.elements?.statusArea&&this.elements.statusArea.classList.remove("hidden"),this.setStatus(b,"success"),console.log(`${d} \u2713 ${b}`),window.dispatchEvent(new CustomEvent(ne,{detail:{action:"show-identity-manager",addr:o},bubbles:!0,composed:!0})),this.showBusy({isBusy:!1})}setFormDisabled(e){let t=this.shadowRoot,i=["input-username","input-description","input-email","input-secret","checkbox-make-active","btn-generate","btn-switch-sign-in"];for(let o of i){let s=t.getElementById(o);s&&(s.disabled=e,e?(s.style.opacity="0.5",s.style.pointerEvents="none"):(s.style.opacity="1",s.style.pointerEvents="auto"))}}async renderUI(){}async handleContextUpdated(){await this.renderUI()}};var Ul=`:host {
|
|
1039
1218
|
display: block;
|
|
1040
1219
|
width: 100%;
|
|
1041
1220
|
max-width: 100%;
|
|
@@ -1656,7 +1835,7 @@ Updating local identity indexes and scope settings...`,animationEmoji:"\u{1F4BE}
|
|
|
1656
1835
|
background: rgba(0, 0, 0, 0.5);
|
|
1657
1836
|
box-shadow: 0 0 8px rgba(80, 250, 123, 0.15);
|
|
1658
1837
|
}
|
|
1659
|
-
`;var
|
|
1838
|
+
`;var Fl=`<div id="container" class="component-container">
|
|
1660
1839
|
<div id="historical-warning-banner" class="warning-banner hidden">
|
|
1661
1840
|
<span>\u26A0\uFE0F Viewing Historical Frame (Past State)</span>
|
|
1662
1841
|
</div>
|
|
@@ -1810,7 +1989,7 @@ Updating local identity indexes and scope settings...`,animationEmoji:"\u{1F4BE}
|
|
|
1810
1989
|
</div>
|
|
1811
1990
|
</div>
|
|
1812
1991
|
</div>
|
|
1813
|
-
`;function oi({keystone:n,providerId:e}){if(!n?.data?.challengePools)return!1;let t=`custodian-manage-${e}`;return n.data.challengePools.some(i=>i.id===t)}p(oi,"isSsoProviderLinked");var pe=!1,Rl="ibgib-keystone-details",si=class extends ce{static{p(this,"KeystoneDetailsComponentMeta")}lc="[KeystoneDetailsComponentMeta]";routeRegExp=new RegExp(`^${Rl}$`);componentName=Rl;constructor(){super(ye()),customElements.get(this.componentName)||customElements.define(this.componentName,Qo)}async createInstance({path:e,ibGibAddr:t}){let i=`${this.lc}[${this.createInstance.name}]`,o=document.createElement(this.componentName);return await o.initialize({ibGibAddr:t,meta:this,html:Pl,css:[he,$l]}),o}},Qo=class extends Oe{static{p(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{pe&&console.log(`${t} starting... (I: 4c9328643a18e56b56e57292c87bd226)`),await super.initialize(e),await this.loadIbGib({getLatest:!1})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{pe&&console.log(`${t} complete.`)}}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let i=await D();if(!i)return{username:"",description:"",isPrimary:!1,n:0};let o=await i.getLocalUserSpace({lock:!1});if(!o)return{username:"",description:"",isPrimary:!1,n:0};try{let a=await new ee().getKeystoneCommonInfo({addr:e,metaspace:i,space:o});if(a){let c={username:a.name,description:a.description,isPrimary:a.isPrimary,n:a.n};return this.keystoneCache.set(e,c),c}else console.warn(`[getKeystoneDetails] Keystone common info not found in local space for addr: ${e}`)}catch(s){console.warn(`Error getting details for keystone ${e}: ${y(s)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async created(){let e=`${this.lc}[${this.created.name}]`;try{pe&&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.btnCheckUpdatesEl=t.getElementById("btn-check-updates"),this.elements.btnUpdateIdentityEl=t.getElementById("btn-update-identity"),this.elements.syncStatusMsgEl=t.getElementById("sync-status-msg"),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.inputCurrentPassphraseEl=t.getElementById("input-current-passphrase"),this.elements.inputNewPassphraseEl=t.getElementById("input-new-passphrase"),this.elements.inputConfirmPassphraseEl=t.getElementById("input-confirm-passphrase"),this.elements.btnChangePassphraseEl=t.getElementById("btn-change-passphrase"),this.elements.changePassphraseStatusEl=t.getElementById("change-passphrase-status"),this.elements.changePassphraseCardEl=t.getElementById("change-passphrase-card"),this.elements.contentEl=t.getElementById("identity-details-view"),this.initHandlers(),this._onIdentityChanged=async i=>{this.globalActiveAddr=i.detail?.activeIdentityAddr||null,this.keystoneCache.clear(),await this.updateFrameDetailsView(),this.updateActiveButtonState()},window.addEventListener(ve,this._onIdentityChanged),await this.resolveActiveIdentity(),await this.loadIbGib({getLatest:!1})}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{pe&&console.log(`${e} complete.`)}}async disconnected(){this._onIdentityChanged&&window.removeEventListener(ve,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.btnCheckUpdatesEl.addEventListener("click",()=>this.handleCheckForUpdates()),this.elements.btnUpdateIdentityEl.addEventListener("click",()=>this.handleUpdateIdentity()),this.elements.btnLinkGoogleEl.addEventListener("click",()=>this.handleSSOClick("google")),this.elements.btnLinkGithubEl.addEventListener("click",()=>this.handleSSOClick("github")),this.elements.btnChangePassphraseEl.addEventListener("click",()=>this.handleChangePassphrase())}toggleAccordion(){let e=this.elements.rawAccordionHeaderEl,t=this.elements.rawAccordionContentEl;e.classList.toggle("expanded"),t.classList.toggle("expanded")}setSyncStatus(e,t){let i=this.elements.syncStatusMsgEl;i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden")}async handleCheckForUpdates(){let e=`${this.lc}[${this.handleCheckForUpdates.name}]`;if(this.ibGibAddr){this.setSyncStatus("Checking server for keystone updates...","info");try{let t=await D(),i=t?await t.getLocalUserSpace({lock:!1}):void 0,s=await Le().checkForKeystoneUpdate({activePrimaryAddr:this.ibGibAddr,metaspace:t,space:i});s.hasUpdate?this.setSyncStatus(`Update Available (Server n=${s.serverN}, Local n=${s.localN})`,"info"):this.setSyncStatus(`Up to Date (n=${s.localN})`,"success")}catch(t){console.error(`${e} ${y(t)}`),this.setSyncStatus(`Check failed: ${y(t)}`,"error")}}}async handleUpdateIdentity(){let e=`${this.lc}[${this.handleUpdateIdentity.name}]`;if(this.ibGibAddr){this.setSyncStatus("Updating identity keystone from server...","info");try{let t=await D(),i=t?await t.getLocalUserSpace({lock:!1}):void 0,s=await Le().updateActiveKeystone({activePrimaryAddr:this.ibGibAddr,metaspace:t,space:i});if(s){let a=C({ibGib:s});this.ibGibAddr=a,this.staticIbGib=s,this.setSyncStatus(`Identity updated successfully to n=${s.data?.n??0}`,"success"),await this.loadIbGib({getLatest:!0})}else this.setSyncStatus("Identity is already up to date.","info")}catch(t){console.error(`${e} ${y(t)}`),this.setSyncStatus(`Update failed: ${y(t)}`,"error")}}}async handleVerifyIdentityChain(){let e=`${this.lc}[${this.handleVerifyIdentityChain.name}]`;console.log(`${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(Pe,{detail:{activeIdentityAddr:this.ibGibAddr},bubbles:!0,composed:!0}))}setVerificationStatus(e,t){let i=this.elements.verificationStatusEl;i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden")}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{let t=globalThis.ibgib?.identity?.domainIdentity;this.globalActiveAddr=t?C({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(pe&&console.log(`${t} starting... (I: f0f7e8d52cbdc37bec844b2875996e26)`),!this.ibGibAddr)return;let i=await D();if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: a9864dbbaefc1082ce7bd228ebd67c26)");let o=await i.getLocalUserSpace({lock:!1});if(!o)throw new Error("(UNEXPECTED) space falsy and we couldn't get default local user space from metaspace? (E: fa298edcecbda889cfd7b228fbd57c26)");let s=this.ibGibAddr;if(e?.getLatest){let c=await i.getLatestAddr({addr:this.ibGibAddr,space:o});c&&(s=c,this.ibGibAddr=c)}let a=await i.get({addrs:[s],space:o});if(a.success&&a.ibGibs&&a.ibGibs.length===1)this.staticIbGib=a.ibGibs[0];else{let d=a.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find address ${s}. addrsNotFound: ${d}? resGet.errorMsg: ${a.errorMsg} (E: e0e5c9b7de2837bc902fa88390cd9f26)`)}await this.updateFrameDetailsView()}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{pe&&console.log(`${t} complete.`)}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;try{pe&&console.log(`${e} starting... (I: c8aa086352d8079708e00f78b6ac0826)`),await super.renderUI()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{pe&&console.log(`${e} complete.`)}}updateActiveButtonState(){if(!this.elements)return;let e=z({ibGibAddr:this.ibGibAddr}).tjpGib??q({ibGibAddr:this.ibGibAddr}).gib,t=this.globalActiveAddr?z({ibGibAddr:this.globalActiveAddr}).tjpGib??q({ibGibAddr:this.globalActiveAddr}).gib:null,i=!!(this.globalActiveAddr&&e===t);if(i?(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=i,this.elements.btnLinkGoogleEl.classList.remove("disabled"),this.elements.btnLinkGithubEl.classList.remove("disabled");let o=oi({keystone:this.ibGib,providerId:"google"}),s=oi({keystone:this.ibGib,providerId:"github"}),a=this.elements.btnLinkGoogleEl,c=a.querySelector(".toggle-state-text");o?(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");s?(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(pe&&console.log(`${e} starting... (I: 1fa9e66d2e78fb100874573e2db71d26)`),!this.elements)return;let t=this.ibGib;if(!t){this.clearActiveDetails();return}let i=this.ibGibAddr;this.elements.identityAddrEl.textContent=i,this.elements.identityGenEl.textContent=t.data?.n!==void 0?String(t.data.n):"0 (Genesis)";let o=t.data?.timestamp,s="N/A";if(o){let m=parseInt(o);isNaN(m)?s=new Date(o).toLocaleString():s=new Date(m).toLocaleString()}this.elements.identityTimestampEl.textContent=s,this.elements.identityUuidEl.textContent=t.data?.uuid||"N/A";let a=t.data?.frameDetails;this.elements.identityFrameDetailsEl.textContent=a?L(a):"{}";let c=!1,d=await D();if(d){let m=await d.getLocalUserSpace({lock:!1});if(m){try{let g=await d.getLatestAddr({addr:this.ibGibAddr,space:m});g&&g!==this.ibGibAddr&&(c=!0)}catch(g){console.warn(`${e} Error checking latest address: ${y(g)}`)}try{let b=await new ee().getAggregateDetails({latestKeystone:t,metaspace:d,space:m});this.elements.identityAggrDetailsEl.textContent=b?L(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,f=this.elements.containerEl;u&&f&&(c?(u.classList.remove("hidden"),f.classList.add("is-historical")):(u.classList.add("hidden"),f.classList.remove("is-historical"))),this.elements.rawKeystoneJsonEl.textContent=L(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.changePassphraseCardEl.classList.remove("hidden")):(this.elements.delegatesCardEl.classList.add("hidden"),this.elements.ssoLinkCardEl.classList.add("hidden"),this.elements.changePassphraseCardEl.classList.add("hidden")),this.updateActiveButtonState()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{pe&&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 i of e){let o=document.createElement("div");o.className="pool-card";let s=i.config||{},a=s.behavior||{},c=s.allowedVerbs||[],d=i.challenges?Object.keys(i.challenges).length:0,u=!!i.isForeign,f=i.challenges||{},h=Object.entries(f).map(([m,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`
|
|
1992
|
+
`;function di({keystone:n,providerId:e}){if(!n?.data?.challengePools)return!1;let t=`custodian-manage-${e}`;return n.data.challengePools.some(i=>i.id===t)}p(di,"isSsoProviderLinked");var pe=!1,Bl="ibgib-keystone-details",ui=class extends de{static{p(this,"KeystoneDetailsComponentMeta")}lc="[KeystoneDetailsComponentMeta]";routeRegExp=new RegExp(`^${Bl}$`);componentName=Bl;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,is)}async createInstance({path:e,ibGibAddr:t}){let i=`${this.lc}[${this.createInstance.name}]`,o=document.createElement(this.componentName);return await o.initialize({ibGibAddr:t,meta:this,html:Fl,css:[me,Ul]}),o}},is=class extends Ke{static{p(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{pe&&console.log(`${t} starting... (I: 4c9328643a18e56b56e57292c87bd226)`),await super.initialize(e),await this.loadIbGib({getLatest:!1})}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{pe&&console.log(`${t} complete.`)}}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let i=await M();if(!i)return{username:"",description:"",isPrimary:!1,n:0};let o=await i.getLocalUserSpace({lock:!1});if(!o)return{username:"",description:"",isPrimary:!1,n:0};try{let a=await new Z().getKeystoneCommonInfo({addr:e,metaspace:i,space:o});if(a){let c={username:a.name,description:a.description,isPrimary:a.isPrimary,n:a.n};return this.keystoneCache.set(e,c),c}else console.warn(`[getKeystoneDetails] Keystone common info not found in local space for addr: ${e}`)}catch(s){console.warn(`Error getting details for keystone ${e}: ${y(s)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async created(){let e=`${this.lc}[${this.created.name}]`;try{pe&&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.btnCheckUpdatesEl=t.getElementById("btn-check-updates"),this.elements.btnUpdateIdentityEl=t.getElementById("btn-update-identity"),this.elements.syncStatusMsgEl=t.getElementById("sync-status-msg"),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.inputCurrentPassphraseEl=t.getElementById("input-current-passphrase"),this.elements.inputNewPassphraseEl=t.getElementById("input-new-passphrase"),this.elements.inputConfirmPassphraseEl=t.getElementById("input-confirm-passphrase"),this.elements.btnChangePassphraseEl=t.getElementById("btn-change-passphrase"),this.elements.changePassphraseStatusEl=t.getElementById("change-passphrase-status"),this.elements.changePassphraseCardEl=t.getElementById("change-passphrase-card"),this.elements.contentEl=t.getElementById("identity-details-view"),this.initHandlers(),this._onIdentityChanged=async i=>{this.globalActiveAddr=i.detail?.activeIdentityAddr||null,this.keystoneCache.clear(),await this.updateFrameDetailsView(),this.updateActiveButtonState()},window.addEventListener(ve,this._onIdentityChanged),await this.resolveActiveIdentity(),await this.loadIbGib({getLatest:!1})}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{pe&&console.log(`${e} complete.`)}}async disconnected(){this._onIdentityChanged&&window.removeEventListener(ve,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.btnCheckUpdatesEl.addEventListener("click",()=>this.handleCheckForUpdates()),this.elements.btnUpdateIdentityEl.addEventListener("click",()=>this.handleUpdateIdentity()),this.elements.btnLinkGoogleEl.addEventListener("click",()=>this.handleSSOClick("google")),this.elements.btnLinkGithubEl.addEventListener("click",()=>this.handleSSOClick("github")),this.elements.btnChangePassphraseEl.addEventListener("click",()=>this.handleChangePassphrase())}toggleAccordion(){let e=this.elements.rawAccordionHeaderEl,t=this.elements.rawAccordionContentEl;e.classList.toggle("expanded"),t.classList.toggle("expanded")}setSyncStatus(e,t){let i=this.elements.syncStatusMsgEl;i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden")}async handleCheckForUpdates(){let e=`${this.lc}[${this.handleCheckForUpdates.name}]`;if(this.ibGibAddr){this.setSyncStatus("Checking server for keystone updates...","info");try{let t=await M(),i=t?await t.getLocalUserSpace({lock:!1}):void 0,s=await Qe().checkForKeystoneUpdate({activePrimaryAddr:this.ibGibAddr,metaspace:t,space:i});s.hasUpdate?this.setSyncStatus(`Update Available (Server n=${s.serverN}, Local n=${s.localN})`,"info"):this.setSyncStatus(`Up to Date (n=${s.localN})`,"success")}catch(t){console.error(`${e} ${y(t)}`),this.setSyncStatus(`Check failed: ${y(t)}`,"error")}}}async handleUpdateIdentity(){let e=`${this.lc}[${this.handleUpdateIdentity.name}]`;if(this.ibGibAddr){this.setSyncStatus("Updating identity keystone from server...","info");try{let t=await M(),i=t?await t.getLocalUserSpace({lock:!1}):void 0,s=await Qe().updateActiveKeystone({activePrimaryAddr:this.ibGibAddr,metaspace:t,space:i});if(s){let a=A({ibGib:s});this.ibGibAddr=a,this.staticIbGib=s,this.setSyncStatus(`Identity updated successfully to n=${s.data?.n??0}`,"success"),await this.loadIbGib({getLatest:!0})}else this.setSyncStatus("Identity is already up to date.","info")}catch(t){console.error(`${e} ${y(t)}`),this.setSyncStatus(`Update failed: ${y(t)}`,"error")}}}async handleVerifyIdentityChain(){let e=`${this.lc}[${this.handleVerifyIdentityChain.name}]`;console.log(`${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(Pe,{detail:{activeIdentityAddr:this.ibGibAddr},bubbles:!0,composed:!0}))}setVerificationStatus(e,t){let i=this.elements.verificationStatusEl;i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden")}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{let t=globalThis.ibgib?.identity?.domainIdentity;this.globalActiveAddr=t?A({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(pe&&console.log(`${t} starting... (I: f0f7e8d52cbdc37bec844b2875996e26)`),!this.ibGibAddr)return;let i=await M();if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: a9864dbbaefc1082ce7bd228ebd67c26)");let o=await i.getLocalUserSpace({lock:!1});if(!o)throw new Error("(UNEXPECTED) space falsy and we couldn't get default local user space from metaspace? (E: fa298edcecbda889cfd7b228fbd57c26)");let s=this.ibGibAddr;if(e?.getLatest){let c=await i.getLatestAddr({addr:this.ibGibAddr,space:o});c&&(s=c,this.ibGibAddr=c)}let a=await i.get({addrs:[s],space:o});if(a.success&&a.ibGibs&&a.ibGibs.length===1)this.staticIbGib=a.ibGibs[0];else{let d=a.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find address ${s}. addrsNotFound: ${d}? resGet.errorMsg: ${a.errorMsg} (E: e0e5c9b7de2837bc902fa88390cd9f26)`)}await this.updateFrameDetailsView()}catch(i){throw console.error(`${t} Registered identity keystone address ${this.ibGibAddr} not found in local browser space: ${y(i)} (E: a123456789abcdef0123456789c0003)`),i}finally{pe&&console.log(`${t} complete.`)}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;try{pe&&console.log(`${e} starting... (I: c8aa086352d8079708e00f78b6ac0826)`),await super.renderUI()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{pe&&console.log(`${e} complete.`)}}updateActiveButtonState(){if(!this.elements)return;let e=W({ibGibAddr:this.ibGibAddr}).tjpGib??H({ibGibAddr:this.ibGibAddr}).gib,t=this.globalActiveAddr?W({ibGibAddr:this.globalActiveAddr}).tjpGib??H({ibGibAddr:this.globalActiveAddr}).gib:null,i=!!(this.globalActiveAddr&&e===t);if(i?(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=i,this.elements.btnLinkGoogleEl.classList.remove("disabled"),this.elements.btnLinkGithubEl.classList.remove("disabled");let o=di({keystone:this.ibGib,providerId:"google"}),s=di({keystone:this.ibGib,providerId:"github"}),a=this.elements.btnLinkGoogleEl,c=a.querySelector(".toggle-state-text");o?(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");s?(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(pe&&console.log(`${e} starting... (I: 1fa9e66d2e78fb100874573e2db71d26)`),!this.elements)return;let t=this.ibGib;if(!t){this.clearActiveDetails();return}let i=this.ibGibAddr;this.elements.identityAddrEl.textContent=i,this.elements.identityGenEl.textContent=t.data?.n!==void 0?String(t.data.n):"0 (Genesis)";let o=t.data?.timestamp,s="N/A";if(o){let m=parseInt(o);isNaN(m)?s=new Date(o).toLocaleString():s=new Date(m).toLocaleString()}this.elements.identityTimestampEl.textContent=s,this.elements.identityUuidEl.textContent=t.data?.uuid||"N/A";let a=t.data?.frameDetails;this.elements.identityFrameDetailsEl.textContent=a?U(a):"{}";let c=!1,d=await M();if(d){let m=await d.getLocalUserSpace({lock:!1});if(m){try{let g=await d.getLatestAddr({addr:this.ibGibAddr,space:m});g&&g!==this.ibGibAddr&&(c=!0)}catch(g){console.warn(`${e} Error checking latest address: ${y(g)}`)}try{let b=await new Z().getAggregateDetails({latestKeystone:t,metaspace:d,space:m});this.elements.identityAggrDetailsEl.textContent=b?U(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,f=this.elements.containerEl;u&&f&&(c?(u.classList.remove("hidden"),f.classList.add("is-historical")):(u.classList.add("hidden"),f.classList.remove("is-historical"))),this.elements.rawKeystoneJsonEl.textContent=U(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.changePassphraseCardEl.classList.remove("hidden")):(this.elements.delegatesCardEl.classList.add("hidden"),this.elements.ssoLinkCardEl.classList.add("hidden"),this.elements.changePassphraseCardEl.classList.add("hidden")),this.updateActiveButtonState()}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{pe&&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 i of e){let o=document.createElement("div");o.className="pool-card";let s=i.config||{},a=s.behavior||{},c=s.allowedVerbs||[],d=i.challenges?Object.keys(i.challenges).length:0,u=!!i.isForeign,f=i.challenges||{},h=Object.entries(f).map(([m,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`
|
|
1814
1993
|
<div class="pool-challenge-item">
|
|
1815
1994
|
<span class="challenge-id">${m}</span>
|
|
1816
1995
|
<span class="challenge-hash" title="${g.hash||""}">${b}</span>
|
|
@@ -1894,8 +2073,8 @@ Updating local identity indexes and scope settings...`,animationEmoji:"\u{1F4BE}
|
|
|
1894
2073
|
No registered delegates.
|
|
1895
2074
|
</td>
|
|
1896
2075
|
</tr>
|
|
1897
|
-
`;return}let i=await
|
|
1898
|
-
Device: ${d}`);let b=document.createElement("td");b.textContent=s,b.title=s;let E=document.createElement("td");E.textContent=a.allowedVerbs?a.allowedVerbs.join(", "):"-",E.title=E.textContent;let w=!!(f&&o&&f!==o),v=document.createElement("td"),I=document.createElement("button");I.className="action-btn secondary small",I.textContent="View Details",I.addEventListener("click",async()=>{let S=`${this.lc}[renderDelegates.click]`;if(w)this.showRemoteDelegateModal(a);else if(a.delegateAddr){let N=a.delegateAddr;if(i){let $=await i.getLocalUserSpace({lock:!1});if($)try{let A=await i.getLatestAddr({addr:s,space:$});A&&(N=A)}catch(A){console.warn(`${S} Error resolving latest delegate address: ${y(A)}`)}}this.dispatchEvent(new CustomEvent("ibgib-view-keystone-details",{detail:{addr:N},bubbles:!0,composed:!0}))}else this.showRemoteDelegateModal(a)}),v.appendChild(I);let T=document.createElement("button");T.className="action-btn danger small",T.style.marginLeft="0.4rem",T.textContent="Revoke",T.addEventListener("click",async()=>{await this.handleRevokeDelegate(s,d)}),v.appendChild(T),c.appendChild(u),c.appendChild(b),c.appendChild(E),c.appendChild(v),t.appendChild(c)}}async handleRevokeDelegate(e,t){let i=`${this.lc}[${this.handleRevokeDelegate.name}]`;try{let o;try{o=await Kt({msg:`Enter Master Passphrase to revoke delegate '${t}':`,confirm:!1})}catch{return}if(!o)return;this.setSyncStatus("Revoking delegate device...","info");let s=await D();if(!s)throw new Error("Metaspace not found");let a=await s.getLocalUserSpace({lock:!1});if(!a)throw new Error("Local space not found");let d=await new ee().unregisterDelegate({parentKeystone:this.ibGib,delegateTjpAddr:e,masterSecret:o,metaspace:s,space:a}),u=Q({ibGib:this.ibGib})||C({ibGib:this.ibGib}),f=await ue().putEvolveKeystone({domainAddr:u,keystoneIbGib:d,relatedKeystoneIbGibs:[]});if(!f.success)throw new Error(`Server rejected delegate revocation: ${f.message}`);await s.put({ibGibs:[d],space:a}),await s.registerNewIbGib({ibGib:d,space:a}),await de({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[K({ibGib:d})]}],metaspace:s,space:a});let h=C({ibGib:d});window.dispatchEvent(new CustomEvent(ve,{detail:{activeIdentityAddr:h},bubbles:!0,composed:!0})),this.setSyncStatus(`Successfully revoked device '${t}'!`,"success"),this.ibGibAddr=h,this.staticIbGib=d,await this.loadIbGib({getLatest:!0})}catch(o){console.error(`${i} Delegate revocation failed: ${y(o)}`),this.setSyncStatus(`Revocation failed: ${y(o)}`,"error")}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{pe&&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{pe&&console.log(`${e} complete.`)}}async handleNewContextChild({childIbGib:e}){let t=`${this.lc}[${this.handleNewContextChild.name}]`;try{pe&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{pe&&console.log(`${t} complete.`)}}async handleSSOLink(e){let t=`${this.lc}[${this.handleSSOLink.name}]`;this.setSSOStatus(`Linking ${e}...`,"info");try{let i=await fetch("/api/identity/sso/config");if(!i.ok)throw new Error(`Failed to fetch SSO config from server: ${i.statusText}`);let o=await i.json();if(!o.success||!o.providers)throw new Error(`SSO configuration fetch failed: ${o.message||"unknown error"}`);let s=o.providers.find(g=>g.providerId===e);if(!s)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=`${s.authUrl}?client_id=${s.clientId}&redirect_uri=${encodeURIComponent(s.redirectUri)}&response_type=code&scope=${encodeURIComponent(s.scope)}&state=${encodeURIComponent(d)}`,f=window.open(u,"sso-oauth-popup","width=600,height=700,status=yes,toolbar=no,menubar=no,location=yes");if(!f)throw new Error("Popup blocked by browser. Please enable popups for this site.");let h,m=p(async g=>{if(g.origin!==window.location.origin)return;let b=g.data;b&&b.type==="sso-oauth-callback"&&(window.removeEventListener("message",m),clearInterval(h),await this.handleSSOLinkCallback(b.code,c,s.redirectUri))},"messageListener");window.addEventListener("message",m),h=setInterval(()=>{if(f.closed){clearInterval(h),window.removeEventListener("message",m);let g=this.elements.ssoStatusMsgEl;g.textContent&&g.textContent.startsWith("Linking")&&this.setSSOStatus("Linking cancelled (window closed).","error")}},500)}catch(i){console.error(`${t} SSO link initiation failed: ${y(i)}`),this.setSSOStatus(`Link failed: ${y(i)}`,"error")}}setSSOStatus(e,t){let i=this.elements.ssoStatusMsgEl;i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden")}async handleSSOLinkCallback(e,t,i){let o=`${this.lc}[${this.handleSSOLinkCallback.name}]`;this.setSSOStatus("Retrieving challenge pool configuration from server...","info");try{let s=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:i})});if(!s.ok){let v=await s.json().catch(()=>({}));throw new Error(`Server link exchange failed: ${v.message||s.statusText}`)}let a=await s.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 ee,u,f=!1,h=0,m=8;for(;h<m&&!f;){try{let v=h===0?"Link successful! Enter your local Master Secret (Passphrase) to sign and register the custodian pool":`Incorrect passphrase. Please try again (${m-h} tries remaining):`;u=await Kt({msg:v,confirm:!1})}catch{pe&&console.log(`${o}[promptForSecret] user cancelled (I: 911ff1fb0234949228481968e9087626)`),u=void 0;break}if(!u)break;f=await d.verifySigningSecret({keystoneIbGib:this.ibGib,signingSecret:u,poolId:"manage"}),f||h++}if(!f){this.setSSOStatus("Link cancelled or failed (incorrect passphrase).","error");return}this.setSSOStatus("Evolving identity locally and generating cryptographic signatures...","info");let g=await D();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 w=await ue().putEvolveKeystone({domainAddr:t.parentTjpAddr,keystoneIbGib:E,relatedKeystoneIbGibs:[]});if(!w.success)throw new Error(`Server synchronization rejected: ${w.message}`);await de({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[K({ibGib:E})]}],metaspace:g,space:b}),this.setSSOStatus(`Successfully linked with ${t.providerId}!`,"success"),await this.loadIbGib({getLatest:!1})}catch(s){console.error(`${o} SSO callback processing failed: ${y(s)}`),this.setSSOStatus(`Link failed: ${y(s)}`,"error")}}async handleSSOClick(e){oi({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 i=new ee,o,s=!1,a=0,c=8;for(;a<c&&!s;){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):`;o=await Kt({msg:g,confirm:!1})}catch{o=void 0;break}if(!o)break;s=await i.verifySigningSecret({keystoneIbGib:this.ibGib,signingSecret:o,poolId:"manage"}),s||a++}if(!s){this.setSSOStatus("Unlink cancelled or failed (incorrect passphrase).","error");return}this.setSSOStatus("Evolving identity locally and removing custodian pool...","info");let d=await D();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 f=`custodian-manage-${e}`,h=await i.removePools({latestKeystone:this.ibGib,masterSecret:o,poolIds:[f],metaspace:d,space:u});this.setSSOStatus("Publishing evolved identity keystone to server...","info");let m=await ue().putEvolveKeystone({domainAddr:C({ibGib:this.ibGib}),keystoneIbGib:h,relatedKeystoneIbGibs:[]});if(!m.success)throw new Error(`Server synchronization rejected: ${m.message}`);await de({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[K({ibGib:h})]}],metaspace:d,space:u}),this.setSSOStatus(`Successfully unlinked ${e}!`,"success"),await this.loadIbGib({getLatest:!0})}catch(i){console.error(`${t} SSO unlink failed: ${y(i)}`),this.setSSOStatus(`Unlink failed: ${y(i)}`,"error")}}setChangePassphraseStatus(e,t){let i=this.elements.changePassphraseStatusEl;i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden")}async handleChangePassphrase(){let e=`${this.lc}[${this.handleChangePassphrase.name}]`;this.setChangePassphraseStatus("Validating entries...","info");try{let t=this.elements.inputCurrentPassphraseEl.value,i=this.elements.inputNewPassphraseEl.value,o=this.elements.inputConfirmPassphraseEl.value;if(!t){this.setChangePassphraseStatus("Current passphrase is required.","error");return}if(!i){this.setChangePassphraseStatus("New passphrase is required.","error");return}if(i!==o){this.setChangePassphraseStatus("New passphrase and confirmation do not match.","error");return}let s=new ee;if(!await s.verifySigningSecret({keystoneIbGib:this.ibGib,signingSecret:t,poolId:"manage"})){this.setChangePassphraseStatus("Incorrect current passphrase.","error");return}this.setChangePassphraseStatus("Evolving primary identity keystone...","info");let c=await D();if(!c)throw new Error("Metaspace not found");let d=await c.getLocalUserSpace({lock:!1});if(!d)throw new Error("Local space not found");debugger;let{newKeystone:u,newDelegates:f}=await s.changePassword({keystoneIbGib:this.ibGib,newMasterSecret:i,signingSecret:t,signingPoolId:"manage",metaspace:c,space:d});debugger;this.setChangePassphraseStatus("Resolving and rotating delegate keystones...","info"),this.setChangePassphraseStatus("Syncing evolved keystones to server...","info");let h=C({ibGib:this.ibGib}),m=await ue().putEvolveKeystone({domainAddr:h,keystoneIbGib:u,relatedKeystoneIbGibs:f});if(!m.success)throw new Error(`Server synchronization rejected: ${m.message}`);this.setChangePassphraseStatus("Updating local indexes...","info");let g=[K({ibGib:u})];f&&f.forEach(E=>{g.push(K({ibGib:E}))}),await de({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:g}],metaspace:c,space:d}),this.elements.inputCurrentPassphraseEl.value="",this.elements.inputNewPassphraseEl.value="",this.elements.inputConfirmPassphraseEl.value="",this.setChangePassphraseStatus("Passphrase updated successfully!","success"),await this.loadIbGib({getLatest:!0})}catch(t){console.error(`${e} Passphrase rotation failed: ${y(t)}`),this.setChangePassphraseStatus(`Update failed: ${y(t)}`,"error")}}};var Gl=`:host {
|
|
2076
|
+
`;return}let i=await M(),o;if(i){let s=await i.getLocalUserSpace({lock:!1});s?.ib&&(o=ws({spaceIb:s.ib}).spaceId)}for(let[s,a]of Object.entries(e)){let c=document.createElement("tr"),d=a.deviceName||a.details?.deviceTag||a.details?.name||"Device Delegate",u=document.createElement("td"),f=a.spaceId||a.details?.spaceId,h=null;f&&(h=document.createElement("span"),h.style.marginLeft="0.5rem",h.style.padding="0.15rem 0.4rem",h.style.borderRadius="4px",h.style.fontSize="0.75rem",h.style.fontWeight="bold",o&&f===o?(h.textContent="This Device",h.className="badge badge-this-device",h.style.backgroundColor="#1b5e20",h.style.color="#a5d6a7"):(h.textContent="Remote Device",h.className="badge badge-remote-device",h.style.backgroundColor="#0d47a1",h.style.color="#90caf9"));let m=p((C,N)=>{u.innerHTML="";let S=document.createElement("span");S.textContent=C,u.appendChild(S),h&&u.appendChild(h),u.title=N||C},"applyNameAndBadge"),g=`\u{1F4BB} ${d}`;m(g,`TJP: ${s}
|
|
2077
|
+
Device: ${d}`);let b=document.createElement("td");b.textContent=s,b.title=s;let E=document.createElement("td");E.textContent=a.allowedVerbs?a.allowedVerbs.join(", "):"-",E.title=E.textContent;let w=!!(f&&o&&f!==o),v=document.createElement("td"),I=document.createElement("button");I.className="action-btn secondary small",I.textContent="View Details",I.addEventListener("click",async()=>{let C=`${this.lc}[renderDelegates.click]`;if(w)this.showRemoteDelegateModal(a);else if(a.delegateAddr){let N=a.delegateAddr;if(i){let S=await i.getLocalUserSpace({lock:!1});if(S)try{let x=await i.getLatestAddr({addr:s,space:S});x&&(N=x)}catch(x){console.warn(`${C} Error resolving latest delegate address: ${y(x)}`)}}this.dispatchEvent(new CustomEvent("ibgib-view-keystone-details",{detail:{addr:N},bubbles:!0,composed:!0}))}else this.showRemoteDelegateModal(a)}),v.appendChild(I);let T=document.createElement("button");T.className="action-btn danger small",T.style.marginLeft="0.4rem",T.textContent="Revoke",T.addEventListener("click",async()=>{await this.handleRevokeDelegate(s,d)}),v.appendChild(T),c.appendChild(u),c.appendChild(b),c.appendChild(E),c.appendChild(v),t.appendChild(c)}}async handleRevokeDelegate(e,t){let i=`${this.lc}[${this.handleRevokeDelegate.name}]`;try{let o;try{o=await Qt({msg:`Enter Master Passphrase to revoke delegate '${t}':`,confirm:!1})}catch{return}if(!o)return;this.setSyncStatus("Revoking delegate device...","info");let s=await M();if(!s)throw new Error("Metaspace not found");let a=await s.getLocalUserSpace({lock:!1});if(!a)throw new Error("Local space not found");let d=await new Z().unregisterDelegate({parentKeystone:this.ibGib,delegateTjpAddr:e,masterSecret:o,metaspace:s,space:a}),u=X({ibGib:this.ibGib})||A({ibGib:this.ibGib}),f=await J().putEvolveKeystone({domainAddr:u,keystoneIbGib:d,relatedKeystoneIbGibs:[]});if(!f.success)throw new Error(`Server rejected delegate revocation: ${f.message}`);await s.put({ibGibs:[d],space:a}),await s.registerNewIbGib({ibGib:d,space:a}),await ue({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[z({ibGib:d})]}],metaspace:s,space:a});let h=A({ibGib:d});window.dispatchEvent(new CustomEvent(ve,{detail:{activeIdentityAddr:h},bubbles:!0,composed:!0})),this.setSyncStatus(`Successfully revoked device '${t}'!`,"success"),this.ibGibAddr=h,this.staticIbGib=d,await this.loadIbGib({getLatest:!0})}catch(o){console.error(`${i} Delegate revocation failed: ${y(o)}`),this.setSyncStatus(`Revocation failed: ${y(o)}`,"error")}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{pe&&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{pe&&console.log(`${e} complete.`)}}async handleNewContextChild({childIbGib:e}){let t=`${this.lc}[${this.handleNewContextChild.name}]`;try{pe&&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(i){throw console.error(`${t} ${y(i)}`),i}finally{pe&&console.log(`${t} complete.`)}}async handleSSOLink(e){let t=`${this.lc}[${this.handleSSOLink.name}]`;this.setSSOStatus(`Linking ${e}...`,"info");try{let i=await qt({providerId:e,parentTjpAddr:this.ibGibAddr});if(!i.success||!i.code){this.setSSOStatus(i.message||"Linking cancelled.","error");return}await this.handleSSOLinkCallback(i.code,i.stateObj,i.redirectUri)}catch(i){console.error(`${t} SSO link initiation failed: ${y(i)}`),this.setSSOStatus(`Link failed: ${y(i)}`,"error")}}setSSOStatus(e,t){let i=this.elements.ssoStatusMsgEl;i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden")}async handleSSOLinkCallback(e,t,i){let o=`${this.lc}[${this.handleSSOLinkCallback.name}]`;this.setSSOStatus("Retrieving challenge pool configuration from server...","info");try{let s=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:i})});if(!s.ok){let v=await s.json().catch(()=>({}));throw new Error(`Server link exchange failed: ${v.message||s.statusText}`)}let a=await s.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 Z,u,f=!1,h=0,m=8;for(;h<m&&!f;){try{let v=h===0?"Link successful! Enter your local Master Secret (Passphrase) to sign and register the custodian pool":`Incorrect passphrase. Please try again (${m-h} tries remaining):`;u=await Qt({msg:v,confirm:!1})}catch{pe&&console.log(`${o}[promptForSecret] user cancelled (I: 911ff1fb0234949228481968e9087626)`),u=void 0;break}if(!u)break;f=await d.verifySigningSecret({keystoneIbGib:this.ibGib,signingSecret:u,poolId:"manage"}),f||h++}if(!f){this.setSSOStatus("Link cancelled or failed (incorrect passphrase).","error");return}this.setSSOStatus("Evolving identity locally and generating cryptographic signatures...","info");let g=await M();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 w=await J().putEvolveKeystone({domainAddr:t.parentTjpAddr,keystoneIbGib:E,relatedKeystoneIbGibs:[]});if(!w.success)throw new Error(`Server synchronization rejected: ${w.message}`);await ue({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[z({ibGib:E})]}],metaspace:g,space:b}),this.setSSOStatus(`Successfully linked with ${t.providerId}!`,"success"),await this.loadIbGib({getLatest:!1})}catch(s){console.error(`${o} SSO callback processing failed: ${y(s)}`),this.setSSOStatus(`Link failed: ${y(s)}`,"error")}}async handleSSOClick(e){di({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 i=new Z,o,s=!1,a=0,c=8;for(;a<c&&!s;){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):`;o=await Qt({msg:g,confirm:!1})}catch{o=void 0;break}if(!o)break;s=await i.verifySigningSecret({keystoneIbGib:this.ibGib,signingSecret:o,poolId:"manage"}),s||a++}if(!s){this.setSSOStatus("Unlink cancelled or failed (incorrect passphrase).","error");return}this.setSSOStatus("Evolving identity locally and removing custodian pool...","info");let d=await M();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 f=`custodian-manage-${e}`,h=await i.removePools({latestKeystone:this.ibGib,masterSecret:o,poolIds:[f],metaspace:d,space:u});this.setSSOStatus("Publishing evolved identity keystone to server...","info");let m=await J().putEvolveKeystone({domainAddr:A({ibGib:this.ibGib}),keystoneIbGib:h,relatedKeystoneIbGibs:[]});if(!m.success)throw new Error(`Server synchronization rejected: ${m.message}`);await ue({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[z({ibGib:h})]}],metaspace:d,space:u}),this.setSSOStatus(`Successfully unlinked ${e}!`,"success"),await this.loadIbGib({getLatest:!0})}catch(i){console.error(`${t} SSO unlink failed: ${y(i)}`),this.setSSOStatus(`Unlink failed: ${y(i)}`,"error")}}setChangePassphraseStatus(e,t){let i=this.elements.changePassphraseStatusEl;i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden")}async handleChangePassphrase(){let e=`${this.lc}[${this.handleChangePassphrase.name}]`;this.setChangePassphraseStatus("Validating entries...","info");try{let t=this.elements.inputCurrentPassphraseEl.value,i=this.elements.inputNewPassphraseEl.value,o=this.elements.inputConfirmPassphraseEl.value;if(!t){this.setChangePassphraseStatus("Current passphrase is required.","error");return}if(!i){this.setChangePassphraseStatus("New passphrase is required.","error");return}if(i!==o){this.setChangePassphraseStatus("New passphrase and confirmation do not match.","error");return}let s=new Z;if(!await s.verifySigningSecret({keystoneIbGib:this.ibGib,signingSecret:t,poolId:"manage"})){this.setChangePassphraseStatus("Incorrect current passphrase.","error");return}this.setChangePassphraseStatus("Evolving primary identity keystone...","info");let c=await M();if(!c)throw new Error("(UNEXPECTED) metaspace falsy? (E: 95e3c8374b0f088f339f5c5a8700f826)");let d=await c.getLocalUserSpace({lock:!1});if(!d)throw new Error("(UNEXPECTED) couldn't get default local space? (E: 2fc1281c28351fd378a1d7f88eaa0526)");debugger;let{newKeystone:u,newDelegates:f}=await s.changePassword({keystoneIbGib:this.ibGib,newMasterSecret:i,signingSecret:t,signingPoolId:"manage",metaspace:c,space:d});debugger;this.setChangePassphraseStatus("Resolving and rotating delegate keystones...","info"),this.setChangePassphraseStatus("Syncing evolved keystones to server...","info");let h=A({ibGib:this.ibGib}),m=await J().putEvolveKeystone({domainAddr:h,keystoneIbGib:u,relatedKeystoneIbGibs:f});if(!m.success)throw new Error(`Server synchronization rejected: ${m.message}`);this.setChangePassphraseStatus("Updating local indexes...","info");let g=[z({ibGib:u})];f&&f.forEach(E=>{g.push(z({ibGib:E}))}),await ue({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:g}],metaspace:c,space:d}),this.elements.inputCurrentPassphraseEl.value="",this.elements.inputNewPassphraseEl.value="",this.elements.inputConfirmPassphraseEl.value="",this.setChangePassphraseStatus("Passphrase updated successfully!","success"),await this.loadIbGib({getLatest:!0})}catch(t){console.error(`${e} Passphrase rotation failed: ${y(t)}`),this.setChangePassphraseStatus(`Update failed: ${y(t)}`,"error")}}};var Vl=`:host {
|
|
1899
2078
|
display: block;
|
|
1900
2079
|
width: 100%;
|
|
1901
2080
|
max-width: 100%;
|
|
@@ -1941,7 +2120,7 @@ Device: ${d}`);let b=document.createElement("td");b.textContent=s,b.title=s;let
|
|
|
1941
2120
|
flex-direction: column;
|
|
1942
2121
|
gap: 1.5rem;
|
|
1943
2122
|
}
|
|
1944
|
-
`;var
|
|
2123
|
+
`;var ql=`<div id="container" class="scrubber-container">
|
|
1945
2124
|
<div class="scrubber-nav">
|
|
1946
2125
|
<button id="btn-scrub-first" class="action-btn scrubber-btn" title="First Frame"><<</button>
|
|
1947
2126
|
<button id="btn-scrub-prev10" class="action-btn scrubber-btn" title="Back 10 Frames">-10</button>
|
|
@@ -1956,7 +2135,7 @@ Device: ${d}`);let b=document.createElement("td");b.textContent=s,b.title=s;let
|
|
|
1956
2135
|
<!-- Details component for the active frame will be injected here -->
|
|
1957
2136
|
</div>
|
|
1958
2137
|
</div>
|
|
1959
|
-
`;var Te=!1,
|
|
2138
|
+
`;var Te=!1,Hl="ibgib-keystone-scrubber",fi=class extends de{static{p(this,"KeystoneScrubberComponentMeta")}lc="[KeystoneScrubberComponentMeta]";routeRegExp=new RegExp(`^${Hl}$`);componentName=Hl;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,os)}async createInstance({path:e,ibGibAddr:t}){let i=`${this.lc}[${this.createInstance.name}]`,o=document.createElement(this.componentName);return await o.initialize({ibGibAddr:t,meta:this,html:ql,css:[me,Vl]}),o}},os=class n extends Vt{static{p(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]`;Te&&console.log(`${e} (I: 3adca837d5c898d8e839d23c59538126)`),super()}async initialize(e){let t=`${this.lc}[${this.initialize.name}]`;try{Te&&console.log(`${t} starting... (I: 75eecfc01af7f3fa9897932ec5457526)`),await super.initialize(e),await this.loadIbGib()}catch(i){throw console.error(`${t} ${y(i)}`),i}finally{Te&&console.log(`${t} complete.`)}}async created(){let e=`${this.lc}[${this.created.name}]`;try{Te&&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(i=>console.error(`${this.lc} loadHistoryData error: ${y(i)}`))}catch(t){throw console.error(`${e} ${y(t)}`),t}finally{Te&&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(Te&&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{Te&&console.log(`${e} complete.`)}}async activateIbGib({addr:e,ibGib:t}){let i=`${this.lc}[activateIbGib]`;try{if(Te&&console.log(`${i} starting... (I: 890a8cb88f72c918a8bcf82c8af63e26)`),!e)return;let o=await this.getLoadedChildInfo({addr:e,ibGib:t}),s=this.activeChildInfo;s&&(s.active=!1),o.active=!0,await(await ae()).inject({parentEl:this.elements.contentEl,componentToInject:o.component})}catch(o){console.error(`${i} ${y(o)}`)}}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 i=await M();if(!i)return;let o=await i.getLocalUserSpace({lock:!1});if(!o)return;let s=e,a=[];for(;s;){let c=await i.get({addr:s,space:o});if(!c.success||!c.ibGibs||c.ibGibs.length===0){console.warn(`${t} Could not find frame at ${s}`);break}let d=c.ibGibs[0];if(a.push(s),d.data?.n===0)break;let u=d.rel8ns?.past;s=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 i=`${this.lc}[${this.getLoadedChildInfo.name}]`;try{if(Te&&console.log(`${i} starting... (I: 9eea188f6b55f04b483fbda8a110f826)`),!e)throw new Error("(UNEXPECTED) addr falsy?");let o=W({ibGibAddr:e}).tjpGib??H({ibGibAddr:e}).gib,s=p(async()=>{let u=await(await ae()).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 s())}else{let d=await s();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(o){throw console.error(`${i} ${y(o)}`),o}finally{Te&&console.log(`${i} complete.`)}}async addChild({addr:e,ibGib:t}){let i=`${this.lc}[${this.addChild.name}]`;try{Te&&console.log(`${i} starting... (I: 824f98b6f9a2c922f8b3a9f67ad63e26)`);let o=document.createElement("div");return o.style.display="none",o}catch(o){throw console.error(`${i} ${y(o)}`),o}finally{Te&&console.log(`${i} complete.`)}}};var Ol=`:host {
|
|
1960
2139
|
display: block;
|
|
1961
2140
|
width: 100%;
|
|
1962
2141
|
margin: 1rem auto;
|
|
@@ -2088,19 +2267,18 @@ Device: ${d}`);let b=document.createElement("td");b.textContent=s,b.title=s;let
|
|
|
2088
2267
|
font-family: monospace;
|
|
2089
2268
|
font-size: 0.85rem;
|
|
2090
2269
|
color: #89b4fa;
|
|
2091
|
-
}`;var
|
|
2092
|
-
<h2 id="title">
|
|
2270
|
+
}`;var zl=`<div id="container" class="component-container">
|
|
2271
|
+
<h2 id="title">Sign In New Device</h2>
|
|
2093
2272
|
<div class="content">
|
|
2094
|
-
<p>
|
|
2273
|
+
<p>Sign in on this device to add it to an existing account.</p>
|
|
2095
2274
|
|
|
2096
2275
|
<div class="input-group">
|
|
2097
|
-
<label for="input-identifier">
|
|
2098
|
-
<input type="text" id="input-identifier" placeholder="Enter registered
|
|
2099
|
-
class="text-input">
|
|
2276
|
+
<label for="input-identifier">Email</label>
|
|
2277
|
+
<input type="text" id="input-identifier" placeholder="Enter registered email..." class="text-input">
|
|
2100
2278
|
</div>
|
|
2101
2279
|
|
|
2102
2280
|
<div class="input-group">
|
|
2103
|
-
<label for="input-device-tag">Device
|
|
2281
|
+
<label for="input-device-tag">Device Name</label>
|
|
2104
2282
|
<input type="text" id="input-device-tag" placeholder="e.g. laptop, phone, living-room..."
|
|
2105
2283
|
class="text-input">
|
|
2106
2284
|
</div>
|
|
@@ -2119,7 +2297,7 @@ Device: ${d}`);let b=document.createElement("td");b.textContent=s,b.title=s;let
|
|
|
2119
2297
|
</div>
|
|
2120
2298
|
|
|
2121
2299
|
<div class="action-row">
|
|
2122
|
-
<button id="btn-add-device" class="action-btn">
|
|
2300
|
+
<button id="btn-add-device" class="action-btn">Sign In</button>
|
|
2123
2301
|
</div>
|
|
2124
2302
|
|
|
2125
2303
|
<div class="switch-workflow" style="margin-top: 1.2rem; text-align: center; font-size: 0.9rem; color: #a6adc8;">
|
|
@@ -2139,7 +2317,7 @@ Device: ${d}`);let b=document.createElement("td");b.textContent=s,b.title=s;let
|
|
|
2139
2317
|
<p class="warning">\u2705 This device is now authorized to sync with your primary identity.</p>
|
|
2140
2318
|
</div>
|
|
2141
2319
|
</div>
|
|
2142
|
-
</div>`;var
|
|
2320
|
+
</div>`;var Kl="ibgib-add-device",pi=class extends de{static{p(this,"AddDeviceComponentMeta")}lc="[AddDeviceComponentMeta]";routeRegExp=new RegExp(`^${Kl}$`);componentName=Kl;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,ss)}async createInstance({path:e,ibGibAddr:t}){let i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:zl,css:[me,Ol]}),i}},ss=class extends Je{static{p(this,"AddDeviceComponentInstance")}lc="[AddDeviceComponentInstance]";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.inputIdentifier=this.shadowRoot.getElementById("input-identifier"),this.elements.inputDeviceTag=this.shadowRoot.getElementById("input-device-tag")||this.shadowRoot.getElementById("input-device-name"),this.elements.inputPassphrase=this.shadowRoot.getElementById("input-passphrase"),this.elements.checkboxMakeActive=this.shadowRoot.getElementById("checkbox-make-active"),this.elements.btnAddDeviceEl=this.shadowRoot.getElementById("btn-add-device"),this.elements.statusArea=this.shadowRoot.getElementById("status-area"),this.elements.statusText=this.shadowRoot.getElementById("status-text"),this.elements.resultAreaEl=this.shadowRoot.getElementById("result-area"),this.elements.delegateAddrEl=this.shadowRoot.getElementById("delegate-addr"),this.elements.contentEl=this.elements.containerEl,this.initHandlers(),await this.renderUI()}async disconnected(){}initHandlers(){this.elements.btnAddDeviceEl.addEventListener("click",()=>this.handleAddDevice()),this.shadowRoot.getElementById("btn-switch-create-account")?.addEventListener("click",e=>{e.preventDefault(),window.dispatchEvent(new CustomEvent(ne,{detail:{action:"show-keystone-creator"},bubbles:!0,composed:!0}))}),this.elements.inputIdentifier.addEventListener("input",()=>{this.elements.inputIdentifier.classList.remove("invalid")}),this.elements.inputDeviceTag.addEventListener("input",()=>{this.elements.inputDeviceTag.classList.remove("invalid")}),this.elements.inputPassphrase.addEventListener("input",()=>{this.elements.inputPassphrase.classList.remove("invalid")})}setButtonLoading(e){this.elements?.btnAddDeviceEl&&(this.elements.btnAddDeviceEl.disabled=e,this.elements.btnAddDeviceEl.textContent=e?"Pairing...":"Pair & Add Device")}async handleAddDevice(){let e=`${this.lc}[${this.handleAddDevice.name}]`;try{this.setStatus("Initializing device pairing...","info");let i=this.elements.inputIdentifier.value.trim();if(this.elements.inputIdentifier.value=i,!i){this.elements.inputIdentifier.classList.add("invalid"),this.setStatus("Please enter a registered email.","error");return}let o=this.elements.inputDeviceTag.value.trim();if(this.elements.inputDeviceTag.value=o,!o||!jt.test(o)){this.elements.inputDeviceTag.classList.add("invalid"),this.setStatus("Please enter a valid Device Name (e.g. 'work-laptop').","error");return}let s=this.elements.inputPassphrase.value.trim();if(this.elements.inputPassphrase.value=s,!s){this.elements.inputPassphrase.classList.add("invalid"),this.setStatus("Please enter your master passphrase.","error");return}this.setButtonLoading(!0),this.showBusy({isBusy:!0,title:"Locating Identity...",msg:"Searching for primary identity...",animationEmoji:"\u{1F50D}"});let a=await M(),c=await a.getLocalUserSpace({});if(!c)throw new Error("No default space found in metaspace.");let u=(await a.getSpecialIbGib({type:"keystones",space:c,initialize:!0}))?.rel8ns?.keystone??[],f;for(let S of u){let P=(await a.get({addrs:[S],space:c}))?.ibGibs?.[0];if(P&&P.data){let $=P.data.frameDetails?.username??"",R=P.data.emails??P.data.frameDetails?.emails??[];if($.toLowerCase()===i.toLowerCase()||R.some(L=>L.toLowerCase()===i.toLowerCase())){f=P;break}}}if(!f){this.setStatus("Locating identity on server...","info");let S=await J().lookupPrimaryKeystone({identifier:i});if(S.success&&S.primaryKeystoneIbGib){let x=S.primaryKeystoneIbGib,P=S.tjpAddr||A({ibGib:x}),$=await J().getKeystoneGraph(P);if($.success&&$.graph){let R=Object.values($.graph);await a.put({ibGibs:R,space:c});let L=Ye({ibGibs:R});for(let V of Object.keys(L)){let he=L[V];for(let Ge of he)await a.registerNewIbGib({ibGib:Ge,space:c})}let Y=L[P]||L[Object.keys(L)[0]];Y&&Y.length>0?f=Y[Y.length-1]:f=x}else await a.put({ibGibs:[x],space:c}),await a.registerNewIbGib({ibGib:x,space:c}),f=x}}if(!f){let S=`No registered identity found for '${i}'. Please check your username/email or create a new account.`;console.error(`${e} ${S}`),this.setStatus(S,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1);return}let h=f.data?.frameDetails?.username??"user";this.setStatus("Generating local device delegate...","info"),this.showBusy({isBusy:!0,title:"Generating Keys...",msg:"Generating cryptographic delegate keys for this device...",animationEmoji:"\u{1F511}"});let m=X({ibGib:f,defaultIfNone:"incomingAddr"});if(!m)throw new Error("(UNEXPECTED) primaryTjpAddr falsy? couldn't get tjpAddr from primaryKeystone? (E: bc8cc8678e1ce4194ab02646160fde26)");let g=await nn({masterSecret:s}),b=Ue.buildKeystone("sync").withUsername(`${h}-sync-${o}`).withDescription(`Sync Delegate for ${h} on ${o}`).withDetails({client:"space-gib-web",role:"sync-delegate",deviceTag:o,primaryTjpAddr:m}),E=await b.compileConfigs(),w=new Z,v=await w.genesis({masterSecret:g,configs:E,metaspace:a,space:c,frameDetails:b.getFrameDetails()}),I=A({ibGib:v});console.log(`${e} Local device delegate generated: ${I}`),await O(500),this.setStatus("Registering device on primary identity...","info"),this.showBusy({isBusy:!0,title:"Registering Device...",msg:"Updating primary identity with new device delegate...",animationEmoji:"\u{1F4DD}"});let T=await w.registerDelegate({parentKeystone:f,delegateKeystone:v,masterSecret:s,metaspace:a,space:c,allowedVerbs:[en,tn],deviceName:o}),C=A({ibGib:T});console.log(`${e} Primary identity evolved with delegate: ${C}`),await O(500),this.setStatus("Syncing device pairing to server...","info"),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Posting device pairing to server sync node...",animationEmoji:"\u{1F504}"});let N=await J().putEvolveKeystone({domainAddr:m,keystoneIbGib:T,relatedKeystoneIbGibs:[v]});if(!N.success){let S=`Server rejected device pairing: ${N.message}`;console.error(`${e} ${S}`),this.setStatus(S,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1);return}this.showBusy({isBusy:!0,title:"Updating Local Indexes...",msg:"Registering new device in local index...",animationEmoji:"\u{1F4BE}"}),await ue({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[z({ibGib:T}),z({ibGib:v})]}],metaspace:a,space:c}),this.elements.checkboxMakeActive.checked&&window.dispatchEvent(new CustomEvent(Pe,{detail:{activeIdentityAddr:C},bubbles:!0,composed:!0})),this.showBusy({isBusy:!1}),this.setButtonLoading(!1),this.elements.delegateAddrEl.innerText=I,this.elements.resultAreaEl.classList.remove("collapsed"),this.setStatus("Device successfully paired!","success")}catch(t){console.error(`${e} ${y(t)}`,t),this.setStatus(`Pairing failed: ${y(t)}`,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1)}}};var Jl=`:host {
|
|
2143
2321
|
display: block;
|
|
2144
2322
|
width: 100%;
|
|
2145
2323
|
}
|
|
@@ -2257,7 +2435,7 @@ Device: ${d}`);let b=document.createElement("td");b.textContent=s,b.title=s;let
|
|
|
2257
2435
|
margin-top: 0;
|
|
2258
2436
|
color: #f38ba8;
|
|
2259
2437
|
}
|
|
2260
|
-
`;var
|
|
2438
|
+
`;var Wl=`<div id="container" class="component-container">
|
|
2261
2439
|
<h2 id="title">Remove / Unlink Device</h2>
|
|
2262
2440
|
<div class="content">
|
|
2263
2441
|
<p>Unlink an authorized delegate device from your primary identity timeline.</p>
|
|
@@ -2288,7 +2466,7 @@ Device: ${d}`);let b=document.createElement("td");b.textContent=s,b.title=s;let
|
|
|
2288
2466
|
</div>
|
|
2289
2467
|
</div>
|
|
2290
2468
|
</div>
|
|
2291
|
-
`;var Vl="ibgib-remove-device",li=class extends ce{static{p(this,"RemoveDeviceComponentMeta")}lc="[RemoveDeviceComponentMeta]";routeRegExp=new RegExp(`^${Vl}$`);componentName=Vl;constructor(){super(ye()),customElements.get(this.componentName)||customElements.define(this.componentName,es)}async createInstance({path:e,ibGibAddr:t}){let i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:Bl,css:[he,Fl]}),i}},es=class extends ze{static{p(this,"RemoveDeviceComponentInstance")}lc="[RemoveDeviceComponentInstance]";activePrimaryKeystone;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.selectDelegateEl=this.shadowRoot.getElementById("select-delegate"),this.elements.inputPassphrase=this.shadowRoot.getElementById("input-passphrase"),this.elements.btnRemoveDeviceEl=this.shadowRoot.getElementById("btn-remove-device"),this.elements.statusArea=this.shadowRoot.getElementById("status-area"),this.elements.statusText=this.shadowRoot.getElementById("status-text"),this.elements.resultAreaEl=this.shadowRoot.getElementById("result-area"),this.elements.contentEl=this.elements.containerEl,this.initHandlers(),await this.loadRegisteredDelegates(),await this.renderUI()}async disconnected(){}initHandlers(){this.elements.btnRemoveDeviceEl.addEventListener("click",()=>this.handleRemoveDevice()),this.elements.inputPassphrase.addEventListener("input",()=>{this.elements.inputPassphrase.classList.remove("invalid")})}async loadRegisteredDelegates(){let e=`${this.lc}[${this.loadRegisteredDelegates.name}]`;try{let t=await D(),i=await t.getLocalUserSpace({});if(!i)return;let s=(await t.getSpecialIbGib({type:"keystones",space:i,initialize:!0}))?.rel8ns?.keystone??[];for(let f of s){let m=(await t.get({addrs:[f],space:i}))?.ibGibs?.[0];if(m&&m.data&&!m.data.isDelegate){this.activePrimaryKeystone=m;break}}let a=this.elements.selectDelegateEl;a.innerHTML="";let c=this.activePrimaryKeystone?.data?.delegates??{},d=Object.keys(c);if(d.length===0){let f=document.createElement("option");f.value="",f.text="No registered delegate devices found",a.appendChild(f),this.elements.btnRemoveDeviceEl.disabled=!0;return}let u=document.createElement("option");u.value="",u.text="-- Select a device to unlink --",a.appendChild(u);for(let f of d){let h=c[f],m=document.createElement("option");m.value=f,m.text=`${h.delegateAddr.split("^")[0]} (TJP: ${f.substring(0,20)}...)`,a.appendChild(m)}this.elements.btnRemoveDeviceEl.disabled=!1}catch(t){console.error(`${e} ${y(t)}`)}}async handleRemoveDevice(){let e=`${this.lc}[${this.handleRemoveDevice.name}]`;try{let i=this.elements.selectDelegateEl.value;if(!i){this.setStatus("Please select a device delegate to unlink.","error");return}let o=this.elements.inputPassphrase.value.trim();if(this.elements.inputPassphrase.value=o,!o){this.elements.inputPassphrase.classList.add("invalid"),this.setStatus("Please enter your master passphrase.","error");return}if(!this.activePrimaryKeystone){this.setStatus("No active primary identity keystone found.","error");return}this.showBusy({isBusy:!0,title:"Revoking Device...",msg:"Evolving primary identity to revoke delegate device...",animationEmoji:"\u{1F512}",submitBtnSelector:"#btn-remove-device",loadingText:"Unlinking..."});let s=await D(),a=await s.getLocalUserSpace({});if(!a)throw new Error("No default space found in metaspace.");let d=await new ee().unregisterDelegate({parentKeystone:this.activePrimaryKeystone,delegateTjpAddr:i,masterSecret:o,metaspace:s,space:a});await s.put({ibGibs:[d],space:a}),await s.registerNewIbGib({ibGib:d,space:a}),this.activePrimaryKeystone=d,await H(500),this.showBusy({isBusy:!1}),this.elements.resultAreaEl.classList.remove("collapsed"),this.setStatus("Device successfully unlinked and revoked!","success"),await this.loadRegisteredDelegates()}catch(t){console.error(`${e} ${y(t)}`),this.setStatus(`Revocation failed: ${y(t)}`,"error"),this.showBusy({isBusy:!1})}}};async function Hl(){let n=await re();n.registerComponentMeta(new ti),n.registerComponentMeta(new ni),n.registerComponentMeta(new ii),n.registerComponentMeta(new si),n.registerComponentMeta(new ri),n.registerComponentMeta(new ai),n.registerComponentMeta(new li)}p(Hl,"registerStandardIdentityComponents");var ts=class{static{p(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(Bs);t&&t.addEventListener("click",()=>this.toggleLeftPanel());let i=document.getElementById(Vs);i&&i.addEventListener("click",()=>this.toggleRightPanel());let o=document.getElementById(Ls);o&&(o.addEventListener("mousedown",()=>{this.leftPanelState==="expanded"&&(this.isResizingLeft=!0)}),o.addEventListener("dblclick",()=>this.toggleLeftPanel()));let s=document.getElementById(Us);s&&(s.addEventListener("mousedown",()=>{this.rightPanelState==="expanded"&&(this.isResizingRight=!0)}),s.addEventListener("dblclick",()=>this.toggleRightPanel()));let a=document.getElementById(Fs);a&&a.addEventListener("mousedown",()=>this.isResizingFooter=!0),window.addEventListener("mousemove",f=>this.handleMouseMove(f)),window.addEventListener("mouseup",()=>this.handleMouseUp());let c=document.getElementById(Hs);c&&c.addEventListener("click",()=>this.showIdentityManager()),window.addEventListener(se,f=>{let h=f.detail?.action;h==="show-identity-manager"?this.showIdentityManager():h==="show-keystone-creator"?this.showKeystoneCreator():h==="show-add-device"&&this.showAddDevice()});let d,u=!1;window.addEventListener(_t,f=>{let{isBusy:h,title:m,msg:g,animationEmoji:b}=f.detail;h?(u=!0,d?d.update({title:m,msg:g,animationEmoji:b}):vs({title:m||"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 i=await(await re()).getComponentInstance({path:"ibgib-identity-manager",ibGibAddr:W,useRegExpPrefilter:!0}),o=document.getElementById(Zt);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${y(t)}`)}}async showKeystoneCreator(){let e=`${this.lc}[${this.showKeystoneCreator.name}]`;try{let i=await(await re()).getComponentInstance({path:"ibgib-keystone-creator",ibGibAddr:W,useRegExpPrefilter:!0}),o=document.getElementById(Zt);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${y(t)}`)}}async showAddDevice(){let e=`${this.lc}[${this.showAddDevice.name}]`;try{let i=await(await re()).getComponentInstance({path:"ibgib-add-device",ibGibAddr:W,useRegExpPrefilter:!0}),o=document.getElementById(Zt);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${y(t)}`)}}toggleLeftPanel(){this.leftPanelState=this.leftPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(Ds);e&&(this.leftPanelState==="collapsed"?e.classList.add("collapsed"):e.classList.remove("collapsed"))}toggleRightPanel(){this.rightPanelState=this.rightPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(ks);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{Hl()}catch(t){console.error(`${e} ${y(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 o=await(await re()).getComponentInstance({path:"ibgib-identity-header",ibGibAddr:W,useRegExpPrefilter:!0}),s=document.getElementById("identity-header-container");s&&o&&(s.innerHTML="",s.appendChild(o)),window.dispatchEvent(new CustomEvent(ws,{detail:{timestamp:Date.now()}}));let a=globalThis.ibgib?.identity?.domainIdentity;if(a){let c=C({ibGib:a}),d=Le(),u=await d.checkForKeystoneUpdate({activePrimaryAddr:c});u.hasUpdate?(console.log(`${e} \u{1F514} Keystone update available on app boot! Server n=${u.serverN}, Local n=${u.localN}`),await d.updateActiveKeystone({activePrimaryAddr:c})):console.log(`${e} Keystone identity up to date on app boot (n=${u.localN}).`)}setInterval(async()=>{console.log("[KeystoneSyncService] \u26A0\uFE0F HEARTBEAT TEST MODE: Interval set to 30s for testing (MUST be changed to 5m for production)");try{let c=globalThis.ibgib?.identity?.domainIdentity;if(c){let d=C({ibGib:c}),f=await Le().checkForKeystoneUpdate({activePrimaryAddr:d});f.hasUpdate&&console.log(`[KeystoneSyncService] \u{1F514} Heartbeat detected keystone update on server! Server n=${f.serverN}, Local n=${f.localN}`)}}catch(c){console.warn(`[KeystoneSyncService] Heartbeat update check error: ${y(c)}`)}},3e4)}catch(t){console.error(`${e} ${y(t)}`)}}};function P0(){let n="[getSpaceGibShellSvc]",e=xs(Es);return e.spaceGibShellSvc||(typeof console<"u"&&console.log(`${n} initializing SpaceGibShellService singleton on globalThis... (I: genuuid)`),e.spaceGibShellSvc=new ts),e.spaceGibShellSvc}p(P0,"getSpaceGibShellSvc");export{jt as a,Ks as b,Qe as c,Ze as d,en as e,Ue as f,Ib as g,Tb as h,X as i,Cb as j,Re as k,it as l,Lm as m,vt as n,Zn as o,P0 as p};
|
|
2469
|
+
`;var Xl="ibgib-remove-device",hi=class extends de{static{p(this,"RemoveDeviceComponentMeta")}lc="[RemoveDeviceComponentMeta]";routeRegExp=new RegExp(`^${Xl}$`);componentName=Xl;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,rs)}async createInstance({path:e,ibGibAddr:t}){let i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:Wl,css:[me,Jl]}),i}},rs=class extends Je{static{p(this,"RemoveDeviceComponentInstance")}lc="[RemoveDeviceComponentInstance]";activePrimaryKeystone;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.selectDelegateEl=this.shadowRoot.getElementById("select-delegate"),this.elements.inputPassphrase=this.shadowRoot.getElementById("input-passphrase"),this.elements.btnRemoveDeviceEl=this.shadowRoot.getElementById("btn-remove-device"),this.elements.statusArea=this.shadowRoot.getElementById("status-area"),this.elements.statusText=this.shadowRoot.getElementById("status-text"),this.elements.resultAreaEl=this.shadowRoot.getElementById("result-area"),this.elements.contentEl=this.elements.containerEl,this.initHandlers(),await this.loadRegisteredDelegates(),await this.renderUI()}async disconnected(){}initHandlers(){this.elements.btnRemoveDeviceEl.addEventListener("click",()=>this.handleRemoveDevice()),this.elements.inputPassphrase.addEventListener("input",()=>{this.elements.inputPassphrase.classList.remove("invalid")})}async loadRegisteredDelegates(){let e=`${this.lc}[${this.loadRegisteredDelegates.name}]`;try{let t=await M(),i=await t.getLocalUserSpace({});if(!i)return;let s=(await t.getSpecialIbGib({type:"keystones",space:i,initialize:!0}))?.rel8ns?.keystone??[];for(let f of s){let m=(await t.get({addrs:[f],space:i}))?.ibGibs?.[0];if(m&&m.data&&!m.data.isDelegate){this.activePrimaryKeystone=m;break}}let a=this.elements.selectDelegateEl;a.innerHTML="";let c=this.activePrimaryKeystone?.data?.delegates??{},d=Object.keys(c);if(d.length===0){let f=document.createElement("option");f.value="",f.text="No registered delegate devices found",a.appendChild(f),this.elements.btnRemoveDeviceEl.disabled=!0;return}let u=document.createElement("option");u.value="",u.text="-- Select a device to unlink --",a.appendChild(u);for(let f of d){let h=c[f],m=document.createElement("option");m.value=f,m.text=`${h.delegateAddr.split("^")[0]} (TJP: ${f.substring(0,20)}...)`,a.appendChild(m)}this.elements.btnRemoveDeviceEl.disabled=!1}catch(t){console.error(`${e} ${y(t)}`)}}async handleRemoveDevice(){let e=`${this.lc}[${this.handleRemoveDevice.name}]`;try{let i=this.elements.selectDelegateEl.value;if(!i){this.setStatus("Please select a device delegate to unlink.","error");return}let o=this.elements.inputPassphrase.value.trim();if(this.elements.inputPassphrase.value=o,!o){this.elements.inputPassphrase.classList.add("invalid"),this.setStatus("Please enter your master passphrase.","error");return}if(!this.activePrimaryKeystone){this.setStatus("No active primary identity keystone found.","error");return}this.showBusy({isBusy:!0,title:"Revoking Device...",msg:"Evolving primary identity to revoke delegate device...",animationEmoji:"\u{1F512}",submitBtnSelector:"#btn-remove-device",loadingText:"Unlinking..."});let s=await M(),a=await s.getLocalUserSpace({});if(!a)throw new Error("No default space found in metaspace.");let d=await new Z().unregisterDelegate({parentKeystone:this.activePrimaryKeystone,delegateTjpAddr:i,masterSecret:o,metaspace:s,space:a});await s.put({ibGibs:[d],space:a}),await s.registerNewIbGib({ibGib:d,space:a}),this.activePrimaryKeystone=d,await O(500),this.showBusy({isBusy:!1}),this.elements.resultAreaEl.classList.remove("collapsed"),this.setStatus("Device successfully unlinked and revoked!","success"),await this.loadRegisteredDelegates()}catch(t){console.error(`${e} ${y(t)}`),this.setStatus(`Revocation failed: ${y(t)}`,"error"),this.showBusy({isBusy:!1})}}};async function Yl(){let n=await ae();n.registerComponentMeta(new ri),n.registerComponentMeta(new ai),n.registerComponentMeta(new ci),n.registerComponentMeta(new ui),n.registerComponentMeta(new fi),n.registerComponentMeta(new pi),n.registerComponentMeta(new hi)}p(Yl,"registerStandardIdentityComponents");var as=class{static{p(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(Ws);t&&t.addEventListener("click",()=>this.toggleLeftPanel());let i=document.getElementById(Xs);i&&i.addEventListener("click",()=>this.toggleRightPanel());let o=document.getElementById(zs);o&&(o.addEventListener("mousedown",()=>{this.leftPanelState==="expanded"&&(this.isResizingLeft=!0)}),o.addEventListener("dblclick",()=>this.toggleLeftPanel()));let s=document.getElementById(Ks);s&&(s.addEventListener("mousedown",()=>{this.rightPanelState==="expanded"&&(this.isResizingRight=!0)}),s.addEventListener("dblclick",()=>this.toggleRightPanel()));let a=document.getElementById(Js);a&&a.addEventListener("mousedown",()=>this.isResizingFooter=!0),window.addEventListener("mousemove",f=>this.handleMouseMove(f)),window.addEventListener("mouseup",()=>this.handleMouseUp());let c=document.getElementById(Ys);c&&c.addEventListener("click",()=>this.showIdentityManager()),window.addEventListener(ne,f=>{let h=f.detail?.action;h==="show-identity-manager"?this.showIdentityManager():h==="show-keystone-creator"?this.showKeystoneCreator():h==="show-add-device"&&this.showAddDevice()});let d,u=!1;window.addEventListener(Nt,f=>{let{isBusy:h,title:m,msg:g,animationEmoji:b}=f.detail;h?(u=!0,d?d.update({title:m,msg:g,animationEmoji:b}):Ns({title:m||"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 i=await(await ae()).getComponentInstance({path:"ibgib-identity-manager",ibGibAddr:Q,useRegExpPrefilter:!0}),o=document.getElementById(on);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${y(t)}`)}}async showKeystoneCreator(){let e=`${this.lc}[${this.showKeystoneCreator.name}]`;try{let i=await(await ae()).getComponentInstance({path:"ibgib-keystone-creator",ibGibAddr:Q,useRegExpPrefilter:!0}),o=document.getElementById(on);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${y(t)}`)}}async showAddDevice(){let e=`${this.lc}[${this.showAddDevice.name}]`;try{let i=await(await ae()).getComponentInstance({path:"ibgib-add-device",ibGibAddr:Q,useRegExpPrefilter:!0}),o=document.getElementById(on);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${y(t)}`)}}toggleLeftPanel(){this.leftPanelState=this.leftPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(Hs);e&&(this.leftPanelState==="collapsed"?e.classList.add("collapsed"):e.classList.remove("collapsed"))}toggleRightPanel(){this.rightPanelState=this.rightPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(Os);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{Yl()}catch(t){console.error(`${e} ${y(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 o=await(await ae()).getComponentInstance({path:"ibgib-identity-header",ibGibAddr:Q,useRegExpPrefilter:!0}),s=document.getElementById("identity-header-container");s&&o&&(s.innerHTML="",s.appendChild(o)),window.dispatchEvent(new CustomEvent(xs,{detail:{timestamp:Date.now()}}));let a=globalThis.ibgib?.identity?.domainIdentity;if(a){let c=A({ibGib:a}),d=Qe(),u=await d.checkForKeystoneUpdate({activePrimaryAddr:c});u.hasUpdate?(console.log(`${e} \u{1F514} Keystone update available on app boot! Server n=${u.serverN}, Local n=${u.localN}`),await d.updateActiveKeystone({activePrimaryAddr:c})):console.log(`${e} Keystone identity up to date on app boot (n=${u.localN}).`)}}catch(t){console.error(`${e} ${y(t)}`)}}};function Y0(){let n="[getSpaceGibShellSvc]",e=Ls(As);return e.spaceGibShellSvc||(typeof console<"u"&&console.log(`${n} initializing SpaceGibShellService singleton on globalThis... (I: genuuid)`),e.spaceGibShellSvc=new as),e.spaceGibShellSvc}p(Y0,"getSpaceGibShellSvc");export{sn as a,er as b,et as c,tt as d,rn as e,Be as f,Pb as g,Rb as h,j as i,Gb as j,Re as k,rt as l,zm as m,_t as n,ii as o,Y0 as p};
|
|
2292
2470
|
/*! Bundled license information:
|
|
2293
2471
|
|
|
2294
2472
|
@google/genai/dist/web/index.mjs:
|
|
@@ -2326,4 +2504,4 @@ Device: ${d}`);let b=document.createElement("td");b.textContent=s,b.title=s;let
|
|
|
2326
2504
|
* SPDX-License-Identifier: Apache-2.0
|
|
2327
2505
|
*)
|
|
2328
2506
|
*/
|
|
2329
|
-
//# sourceMappingURL=chunk-
|
|
2507
|
+
//# sourceMappingURL=chunk-QPR6ILY2.mjs.map
|